branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<repo_name>Snickers797/LooperLeader-New-<file_sep>/LoopLeader/LoopLeader/LoopLeader.Domain/Abstract/IContent.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LoopLeader.Domain.Abstract { public interface IContent { void UpdateSection(string contentID, string NewSectionInfo); } } <file_sep>/LoopLeader/LoopLeader/LoopLeader.Domain/Entities/Member.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Web.Mvc; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LoopLeader.Domain.Entities { public class Member { [HiddenInput(DisplayValue = false)] public int MemberId { get; set; } [Required(ErrorMessage = "Please enter a Login Name")] [StringLength(25)] public string LoginName { get; set; } [Required(ErrorMessage = "Please enter a password")] public string Password { get; set; } [Required(ErrorMessage = "Please enter your First Name")] [StringLength(50)] public string FirstName { get; set; } [Required(ErrorMessage = "Please enter your Last Name")] [StringLength(50)] public string LastName { get; set; } [Required(ErrorMessage = "Please enter an Email Address")] public string Email { get; set; } } } <file_sep>/LoopLeader/LoopLeader/LoopLeader/Controllers/AccountController.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using LoopLeader.Domain.Entities; using LoopLeader.Domain.Abstract; using LoopLeader.Domain.Concrete; using System.Web.Security; namespace LoopLeader.Controllers { public class AccountController : Controller { IMember memberRepo; public AccountController() { memberRepo = new MemberRepository(); } public AccountController(IMember repo) { memberRepo = repo; } public ActionResult Index() { return View(); } } }
f83276c579a1d1d5be0ddbc16300fb05ce33165b
[ "C#" ]
3
C#
Snickers797/LooperLeader-New-
b37436d8e8a73ee13a7cb95e5f0879292e92296f
34e66b1eacc9d108dc72e00930cc59bd0d93be50
refs/heads/master
<repo_name>Ranganath-MD/react-facebook-login<file_sep>/index.js import React, { Component, useState } from 'react'; import { render } from 'react-dom'; import './style.css'; import FacebookLogin from 'react-facebook-login'; const App = () => { const [user, setUser] = useState(null) const responseFacebook = (response) => { setUser(response); } const componentClicked = (response) => { console.log(response) } const handleFailure = () => { console.log("need to login") } return ( <div className="container"> { user ? <div> <img src={user.picture.data.url} alt="avatar" /> <h1>Welcome {user.name}</h1> </div> : <div> <h1> Facebook Authentication </h1> <FacebookLogin appId="579620999335585" autoLoad={true} fields="name,email,picture" onClick={componentClicked} callback={responseFacebook} onFailure={handleFailure} /> </div> } </div> ); } render(<App />, document.getElementById('root')); <file_sep>/README.md # react-facebook-login ### Demo https://react-facebook-login.stackblitz.io/ <img src="facebooktrial.png" alt="drawing" width="550" height="300"/>
b8632101cb3cdf25bf693ff5c0cbf109f734d73e
[ "JavaScript", "Markdown" ]
2
JavaScript
Ranganath-MD/react-facebook-login
b6c11d8ca1c1260075917ee1bd4403171673a16a
088d37c506f27325176384c5e6c1620b963c3a45
refs/heads/master
<file_sep>const express = require('express'); const mongoose = require('mongoose'); const bodyParser = require('body-parser'); const cors = require('cors'); const LogMiddleware = require('./Middlewares/Log'); const PersonValidateMiddleware = require('./Middlewares/PersonValidate'); const RateLimiterMiddleware = require('./Middlewares/RateLimiter'); const PeopleController = require('./Controllers/People'); const UfController = require('./Controllers/Uf'); const dbUri = `mongodb://${process.env.DB_USER}:${process.env.DB_PASSWORD}@${process.env.DB_HOST}:${process.env.DB_PORT}/${process.env.DB_COLLECTION}`; mongoose.connect(dbUri, {useNewUrlParser: true, useUnifiedTopology: true}); const app = express(); // Middlewares app.use(LogMiddleware); app.use(cors()); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: false})); // Routes app.get('/people', PeopleController.index); app.get('/people/search', PeopleController.search); app.post('/people', RateLimiterMiddleware, PersonValidateMiddleware, PeopleController.create); app.get('/people/:id', PeopleController.person); app.put('/people/:id', RateLimiterMiddleware, PersonValidateMiddleware, PeopleController.update); app.delete('/people/:id', RateLimiterMiddleware, PeopleController.remove); app.get('/uf', UfController.index); app.get('/uf/:uf/cities', UfController.cities); // App listen app.listen(process.env.PORT || 8000, () => console.log(`Listenning on port: ${process.env.PORT || 8000}`)); <file_sep>const months = [ 'Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez', ]; const leftZero = number => number < 10 ? `0${number}` : number; const getDateString = function getDateString(separator = '/') { const date = new Date(); return `${leftZero(date.getDay())}${separator}${months[date.getMonth()]}${separator}${date.getFullYear()}`; }; const getTimeString = function getTimeString(separator = ':') { const date = new Date(); return `${leftZero(date.getHours())}${separator}${leftZero(date.getMinutes())}${separator}${leftZero(date.getSeconds())}`; }; module.exports = { getDateString, getTimeString, };<file_sep>const PersonModel = require('../Models/Person'); const {hasPerson} = require('../helpers/person'); const {clearCnpj, clearCpf, makeCpf, makePhone, makeCnpj} = require('../helpers/mask'); function People() { const index = async (req, res, next) => { try { const { page = 1, limit = 10, } = req.query; const person = new PersonModel(); const data = await person.paginate(page, limit); res.json(data); } catch(error) { res.status(500) .json({error: error.message}); } }; const search = async (req, res, next) => { try { const { type, uf, city, } = req.query; const types = { PJ: { name: 'cnpj', clearFn: clearCnpj, }, PF: { name: 'cpf', clearFn: clearCpf, } }; const personType = types[type]; const result = await PersonModel.find({ type, uf, city, [personType.name]: personType.clearFn(req.query[personType.name]) }); if (!result.length) { return res.status(404) .json({error: 'Nenhuma pessoa encontrada'}); } res.json(result.map(person => ({ ...person._doc, cpf: makeCpf(person.cpf), cnpj: makeCnpj(person.cnpj), phone: makePhone(person.phone) }))); } catch (error) { res.status(500) .json({error: error.message}); } } const create = async (req, res, next) => { try { const { name, type, cpf, cnpj, birthDate, uf, city, phone, } = req.body; const person = new PersonModel({ name, type, cpf: clearCpf(cpf), cnpj: clearCnpj(cnpj), birthDate, uf, city, phone }); const result = await person.save(); if (!result || result.phone !== phone) { return res.status(500) .json({error: 'Erro ao salvar pessoa, tente novamente mais tarde'}); } res.status(201) .send(); } catch (error) { res.status(500) .json({error: error.message}); } }; const update = async (req, res, next) => { try { const { name, type, cpf, cnpj, uf = '', city, phone, } = req.body; const person = {name, type, cpf, cnpj, uf, city, phone}; const success = await PersonModel.updateOne({_id: req.params.id}, person); if (!success) { return res.status(500) .send(); } res.json({ message: 'Pessoa alterada com sucesso.' }); } catch (error) { res.status(500) .json({error: error.message}); } }; const remove = async (req, res, next) => { try { const {id} = req.params; if (!await hasPerson(id)) { return res .status(404) .json({error: 'Pessoa não encontrada'}); } const success = await PersonModel.deleteOne({_id: id}); res.status(success ? 200 : 500) .json(success ? {message: 'Pessoa removida com sucesso!'} : {error: 'Erro ao remover pessoa'}); } catch (error) { res.status(500) .json({error: error.message}); } }; const person = async (req, res, next) => { try { const {id} = req.params; const person = await PersonModel.findOne({_id: id}); if (!person) { return res .status(404) .json({error: 'Pessoa não encontrada!'}) } res.json(person); } catch (error) { res.status(500) .json({error: error.message}); } }; return { index, search, create, update, remove, person, } }; module.exports = People(); <file_sep># Oi BFF <file_sep>const validator = require('cpf-cnpj-validator'); const {clearCnpj, clearCpf} = require('../helpers/mask'); module.exports = (req, res, next) => { if (!req.body || typeof req.body !== 'object') { return res .status(400) .json({error: 'Body must be valid'}); } const { name, type, cpf, cnpj, birthDate, uf, city, phone, } = req.body; if (!name || name.length < 5) { return res .status(400) .json({error: 'Insira o nome completo'}); } if (!type || ['PJ', 'PF'].indexOf(type) === -1) { return res .status(400) .json({error: 'Selecione o tipo de pessoa'}); } if (type === 'PJ' && (!cnpj || !validator.cnpj.isValid(clearCnpj(cnpj)))) { return res.status(400) .json({error: 'Preencha o campo CNPJ corretamente'}); } if (type === 'PF' && (!cpf || !validator.cpf.isValid(clearCpf(cpf)))) { return res.status(400) .json({error: 'Preencha o campo CPF corretamente'}); } if (!birthDate) { return res.status(400) .json({error: 'Preencha uma data de nascimento válida'}); } if (!uf) { return res.status(400) .json({error: 'Selecione um estado'}); } if (!city) { return res.status(400) .json({error: 'Selecione uma cidade'}); } if (!phone) { return res.status(400) .json({error: 'Telefone inválido'}); } next(); };<file_sep>const mongoose = require('mongoose'); const {makeCpf, makeCnpj, makePhone} = require('../helpers/mask'); const PersonSchema = new mongoose.Schema({ name: String, type: String, cpf: String, cnpj: String, birthDate: Date, uf: String, city: String, phone: String, }); PersonSchema.methods.paginate = async (page, limit) => { const total = await mongoose.model('People').countDocuments(); const pageParsed = parseInt(page); const limitParsed = parseInt(limit); const pages = Math.ceil(total / limitParsed); const skip = pageParsed === 1 ? 0 : (pageParsed - 1) * limitParsed; const next = pages === 0 || pageParsed === pages ? null : pageParsed + 1; const previous = pages === 0 || pageParsed === 1 ? null : pageParsed - 1; const projection = ['name', 'type', 'cpf', 'cnpj', 'phone', 'city']; const options = {skip, limit: limitParsed}; const data = await mongoose.model('People').find(null, projection, options); return { page: pageParsed, limit: limitParsed, total, pages, next, previous, data: data.map(person => ({...person._doc, phone: makePhone(person.phone), cpf: makeCpf(person.cpf), cnpj: makeCnpj(person.cnpj)})), }; }; module.exports = mongoose.model('People', PersonSchema); <file_sep>const fs = require('fs'); const write = function write(filename, text) { fs.appendFileSync(filename, text, 'utf8', {flag: 'a+'}); }; module.exports = write;<file_sep>const date = require('../helpers/date'); const write = require('../helpers/write'); const writeLog = text => { const logPath = `${process.env.APPLICATION_LOG_DIR}/REQUEST-${date.getDateString('-')}.log`; setTimeout(() => write(logPath, `${text}\n`), 0); } module.exports = (req, res, next) => { const requestLog = `[${date.getDateString()} ${date.getTimeString()}][${req.method}]: ${req.path} from ${req.ip}`; writeLog(requestLog); console.log(requestLog); next(); };<file_sep>const redis = require('redis'); const {RateLimiterRedis} = require('rate-limiter-flexible'); const client = redis.createClient({ host: process.env.REDIS_HOST, port: process.env.REDIS_PORT, password: process.env.REDIS_PASSWORD || undefined, }); const limiter = new RateLimiterRedis({ storeClient: client, keyPrefix: 'rateLimiter', points: 3, duration: 10, }); module.exports = async (req, res, next) => { try { await limiter.consume(req.ip); return next(); } catch (error) { return res.status(429) .json({error: 'Você está indo rápido demais...'}); } }; <file_sep>const clearCpf = cpf => { const regex = /(\.|-)/gm; return cpf.replace(regex, ''); }; const clearCnpj = cnpj => { const regex = /(\.|\/|-)/gm; return cnpj.replace(regex, ''); }; const clearPhone = phone => { const regex = /(\(|\)|\s|-)/gm; return phone.replace(regex, ''); }; const makeCpf = cpf => { const regex = /(\d{3})(\d{3})(\d{3})(\d{2})/; const subst = `$1.$2.$3-$4`; return cpf.replace(regex, subst); }; const makeCnpj = cnpj => { const regex = /(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})/; const subst = `$1.$2.$3/$4-$5`; return cnpj.replace(regex, subst); }; const makePhone = phone => { const regex = /(\d{2})(\d{4,5})(\d{4})/; const subst = `($1) $2-$3`; return phone.replace(regex, subst); }; module.exports = { clearCpf, clearCnpj, clearPhone, makeCpf, makeCnpj, makePhone, }; <file_sep>const UfModel = require('../Models/Uf'); const Uf = function Uf() { const index = async (req, res, next) => { try { const data = await UfModel.find() const ufList = data.map(uf => uf.name); res.json(ufList); } catch (error) { res.status(500) .json({error: error.message}); } }; const cities = async (req, res, next) => { try { const uf = await UfModel.findOne({name: req.params.uf.toUpperCase()}); res.json(uf.cities); } catch (error) { res.status(500) .json({error: error.message}); } }; return { index, cities, }; }; module.exports = Uf();
25bbe935245a77c60b2085600f1d299538a2f8b7
[ "JavaScript", "Markdown" ]
11
JavaScript
carloshskp/oi-bff
771a484b1d7bb3adfafb22c167308f234fd553aa
572ea1e1dee78d5bb98cbf18bdce015dfa067f2c
refs/heads/master
<file_sep>all: project1 project1: main.c semun.h gcc -o project1 main.c semun.h -lm -g clean: -rm -f project1<file_sep>#include "semun.h" void down(int semid) { struct sembuf sem_b = {.sem_num = 0, .sem_op = -1, .sem_flg = 0}; if((semop(semid, &sem_b, 1)) < 0) { printf("ERROR in semop(), on P() signal\n\aSYSTEM: %s\n\n", strerror(errno)); exit(getpid()); } } void up(int semid) { struct sembuf sem_b = {.sem_num = 0, .sem_op = 1, .sem_flg = 0}; if((semop(semid, &sem_b, 1)) < 0) { printf("ERROR in semop(), on V() signal\n\aSYSTEM: %s\n\n", strerror(errno)); exit(getpid()); } } int request_shared_mem(int size) { int shmid; if((shmid=shmget(SHMKEY, size, PERMS | IPC_CREAT)) < 0) { printf("ERROR in shmget()\n\aSYSTEM: %s\n\n", strerror(errno)); exit(1); } return shmid; } char *attach(int shmid) { char *shmem=NULL; if((shmem = shmat(shmid, (char *)0, 0))==(char *)-1) { printf("ERROR in shmat()\n\aSYSTEM: %s\n\n", strerror(errno)); exit(1); } return shmem; } void create_shared_mem() { SHMID = request_shared_mem(sizeof(struct shared_use)); ptr_shared_use = (struct shared_use *)((void *)attach(SHMID)); } void detach_shared_mem(char *addr) { if(shmdt(addr) < 0) printf("ERROR in shmdt()\n\aSYSTEM: %s\n\n", strerror(errno)); } void remove_shared_mem(int shmid) { struct shmid_ds dummy; if((shmctl(shmid, IPC_RMID, &dummy)) < 0) printf("ERROR in shmctl()\n\aSYSTEM: %s\n\n", strerror(errno)); } void sem_init(int semid, int val) { union semun arg; arg.val = val; if (semctl(semid, 0, SETVAL, arg) < 0) { printf("ERROR in sem_init()\n\aSYSTEM: %s\n\n", strerror(errno)); exit(1); } } void sem_remove(int semid) { if((semctl(semid, 0, IPC_RMID, 0)) < 0) printf("ERROR in semctl()\n\aSYSTEM: %s\n\n", strerror(errno)); } long get_current_time_with_ms (void) { long ms; time_t s; struct timespec spec; clock_gettime(CLOCK_REALTIME, &spec); s = spec.tv_sec; ms = round(spec.tv_nsec / 1.0e6); // Convert nanoseconds to milliseconds return ms; } int main(int argc, const char *argv[]) { if(argc < 3) { printf("give <values> <consumers>\n"); exit(1); } if(atoi(argv[1]) < 3000) { printf("number of values must be > 3000\n"); exit(1); } int i, j, m, status; double avg_time = 0; pid_t pid; srand(time(NULL)); int num_of_values = atoi(argv[1]); //M int num_of_consumers = atoi(argv[2]); //n create_shared_mem(); //create shared memory and attach it to a global variable int *values = calloc(num_of_values, sizeof(int)); //table of values int *sems = calloc(num_of_consumers + 3, sizeof(int)); //table of semaphores sems[0] = semget(SEMKEY, 1, IPC_CREAT | PERMS); //semaphore used for counting if (sems[0] < 0) { printf("ERROR in semget()\n\aSYSTEM: %s\n\n", strerror(errno)); exit(1); } sems[1] = semget(SEMKEY + 1, 1, IPC_CREAT | PERMS); //empty if (sems[1] < 0) { printf("ERROR in semget()\n\aSYSTEM: %s\n\n", strerror(errno)); exit(1); } sems[2] = semget(SEMKEY + 2, 1, IPC_CREAT | PERMS); //full if (sems[2] < 0) { printf("ERROR in semget()\n\aSYSTEM: %s\n\n", strerror(errno)); exit(1); } for(i = 3; i < num_of_consumers + 3; i++) { sems[i] = semget(SEMKEY + i, 1, IPC_CREAT | PERMS); if (sems[i] < 0) { printf("ERROR in semget()\n\aSYSTEM: %s\n\n", strerror(errno)); exit(1); } } sem_init(sems[0], num_of_consumers); //start with n sem_init(sems[1], 1); sem_init(sems[2], 0); for(i = 3; i < num_of_consumers + 3; i++) //consumers sleeping sem_init(sems[i], 0); for(i = 0; i < num_of_consumers; i++) { printf("fork...\n"); if((pid = fork())< 0) { printf("ERROR in fork()\n\aSYSTEM: %s\n\n", strerror(errno)); exit(1); } else if(!pid) break; } if(!pid) //I'm the child { int semValue; FILE* fp = fopen("output", "w"); int *values_read= calloc(num_of_values, sizeof(int)); printf("eimai to paidi %d sem_pos = %d\n", getpid(), i); for(j = 0; j < num_of_values; j++) { down(sems[i+3]); down(sems[2]); //other consumers need to wait values_read[j] = ptr_shared_use -> v; //consumer keeps the value avg_time += get_current_time_with_ms() - ptr_shared_use -> t; avg_time /= 2; down(sems[0]); //semaphore counter -1 union semun arg; semValue = semctl(sems[0], 0, GETVAL, arg); if(!semValue) //if all consumers have done their work { sem_init(sems[0], num_of_consumers); //reset counter up(sems[1]); //unblock feeder } else up(sems[2]); //unblock next consumer } if(!semValue) //final int has been written { printf("Average delay time:\n"); printf("%.15lf ms\n", avg_time); fprintf(fp, "Consumer with PID %d has finished running\n", getpid()); fprintf(fp, "Output:\n"); for(m = 0; m < num_of_values; m++) fprintf(fp, "%d\n", values_read[m]); fprintf(fp,"Average delay time:\n"); fprintf(fp,"%.15lf ms\n", avg_time); } fclose(fp); free(values_read); exit(0); } else //I'm the parent { int k; printf("eimai o feeder!\n"); for(k = 0; k < num_of_values; k++) { down(sems[1]); //feeder will start writing values[k] = rand() % 100; //fill the feeder's array with values < 100 ptr_shared_use -> v = values[k]; ptr_shared_use -> t = get_current_time_with_ms(); //get current time in ms for(j = 3; j < num_of_consumers + 3; j++) up(sems[j]);//wake up all consumers up(sems[2]); //memory is full } } while((wait(&status)) > 0); free(values); for(i = 0; i < num_of_consumers + 3; i++) sem_remove(sems[i]); detach_shared_mem((char *)ptr_shared_use); remove_shared_mem(SHMID); return 0; } <file_sep>#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/ipc.h> #include <sys/sem.h> #include <sys/shm.h> #include <sys/signal.h> #include <sys/times.h> #include <sys/types.h> #include <math.h> #include <sys/wait.h> #include <errno.h> #include <string.h> #include <time.h> #define PERMS 0666 #define SHMKEY (key_t)1234 #define SEMKEY (key_t)5678 union semun { int val; struct semid_ds *buff; unsigned short *array; }; struct shared_use{ int v; long t; }shared_use, *ptr_shared_use; int SEMID=0; int SHMID=0; <file_sep># ipc-model IPC model (one feeder - multiple consumer processes using shared memory) The program implements an IPC architecture that includes a feeder (producer) process, a number of ns from the consumer processes (their number is given by the command line) and a shared memory sector accessible to both feeder and consumers. The feeder holds a matrix of random integers (0,100) of magnitude M (given by the command line) and uses the shared memory domain to replicate that table with exactly the same composition in n consumer processes. The feeder writes to memory from one integer at a time along with its time stamp and then waits until this integer is read from all consumer processes to reactivate and write a new value. Consumers also maintain an M-sized table to replicate the feeder's integer table. They use the shared memory domain to read the integer that is registered by the feeder and simultaneously calculate a moving average of time delay each time they derive information from the shared memory. Shared memory is of a specific size and can store up to an integer and a time stamp. This time stamp is set at the time the feeder registers a value from its table in the shared memory domain. In doing so, consumers are asked one by one to read the shared memory information by storing the integer and counting each time the new average delay time. The above procedure is repeated until the feeder process table is reproduced in the same order in all consumer processes, and the last completed user process prints its table and the average delay time to an output file that is common to all processes. compile (make) and run: ./project1 <number of values> <number of processes> with number of values > 3000 Multiple executions of the program were performed for different n and M values with an increase in average timeouts when the number of processes is large.
e31f046dd8c4a40e2a0dfb7aa0e45599e83706f9
[ "Markdown", "C", "Makefile" ]
4
Makefile
KonKX/ipc-model
5bbf579e5fe24308d25dcd0dec8342b562b720e9
6abc818f2c18a88858a70c34802008ba180eaada
refs/heads/master
<repo_name>yuanzhizhu/switch.js<file_sep>/switch.js ;(function() { var tplPath = 'mytpl/' var tpls = [ 'useage', 'config', 'nav', 'view', ] var z = [] var navigation = {} var css = ` .switch-page { transition:transform 500ms; transform:translateX(100vw); position:fixed; left:0px; top:0px; width:100vw; height:100vh; background-color:white; } .switch { transform:translateX(0px); } ` var style = document.createElement('style') style.innerHTML = css document.querySelector('head').appendChild(style) ;(function(itpls) { var obj = {} for(var i = 0; i < itpls.length; i++) { obj[itpls[i]] = {} obj[itpls[i]]['closure'] = null obj[itpls[i]]['js'] = null } tpls = obj })(tpls.slice()) var load = function(url, callback, async = true) { var xhr = new XMLHttpRequest() xhr.onreadystatechange = function() { if(xhr.status == 200 && xhr.readyState == 4) { callback(xhr.responseText) } } xhr.open('GET', url, async) xhr.send() } var map = function(index) { var packet = tplPath + index return { tpl: packet + '/index.tpl', js: packet + '/index.js' } } var initPage = function() { var svitchPage = document.createElement('div') svitchPage.classList.add('switch-page') svitchPage.inject = function(js = "", data = {}) { var env = this env.input = data eval(js) delete svitchPage.inject svitchPage.eval = function(js) { return eval(js) } } return svitchPage } var loadTpl = function(index) { var p = new Promise(function(resolve, reject) { var src = map(index).tpl load(src, function(ret) { tpls[index].closure = foo.tpl(ret) resolve(tpls[index].closure) }) }) return p } var loadJs = function(index) { var p = new Promise(function(resolve, reject) { var src = map(index).js load(src, function(ret) { tpls[index].js = ret resolve(tpls[index].js) }) }) return p } var push = function(index, data = {}) { var svitchPage = initPage() document.querySelector('body').appendChild(svitchPage) setTimeout(function() { svitchPage.classList.add('switch') }, 50) z.push([index, svitchPage]) ;(function() { var closure = tpls[index].closure if(closure == null) return loadTpl(index) else return new Promise(function(resolve, reject) { resolve(closure) }) })() .then(function(closure) { svitchPage.innerHTML = closure.render({ id: 'id-' + (new Date()).getTime(), input: data }) }) .then(function() { var js = tpls[index].js if(js == null) return loadJs(index) else return js }). then(function(js) { svitchPage.inject(js, data) }) } var pop = function() { var svitchPage = z.pop()[1] svitchPage.classList.remove('switch') setTimeout(function() { svitchPage.remove() }, 501) } var get = function(index) { for(var i = 0; i < z.length; i++) if(index == z[i][0]) return z[i][1] } var view = function(DOM) { DOM.inject = function(js, data) { var env = this env.input = data eval(js) } return { load: function(index, data = {}) { ;(function() { var closure = tpls[index].closure if(closure == null) return loadTpl(index) else return new Promise(function(resolve, reject) { resolve(closure) }) })() .then(function(closure) { var html = closure.render({ input: data, id: 'id-' + (new Date()).getTime() }) DOM.innerHTML = html }) .then(function() { var js = tpls[index].js if(js == null) return loadJs(index) else return js }). then(function(js) { DOM.inject(js, data) }) } } } navigation.push = push navigation.pop = pop navigation.get = get window.navigation = navigation window.view = view })() <file_sep>/mytpl/useage/index.js env.querySelector('.back').addEventListener('click', function() { navigation.pop() }) var viewController = view(env.querySelector('.container')) var i = 1 var map = { '1': 'config', '2': 'nav', '3': 'view' } viewController.load(map['1'], { name: env.input.name, email: env.input.email }) env.querySelector('.before').addEventListener('click', function() { i-- if(i == 0) i = 3 viewController.load(map[i.toString()], { name: env.input.name, email: env.input.email }) }) env.querySelector('.after').addEventListener('click', function() { i++ if(i == 4) i = 1 viewController.load(map[i.toString()], { name: env.input.name, email: env.input.email }) }) var part1 = env.querySelector('.part-1') var leftContent = function(html) { part1.innerHTML = html } <file_sep>/mytpl/config/index.js var str = ` <h1> 配置 </h1> <p> switch.js需要依赖template.js<br />(https://github.com/yuanzhizhu/js-template) </p> <p> 首先,需要明白一个概念,什么是模板。在此处,模板是一个文件夹,文件夹下面有index.tpl和index.js两个文件。 </p> <p> 在switch.js中,主要需要配置两个变量,分别是tplPath和tpls。tplPath是一个字符串,代表模版所在目录;tpls是一个数组,数组元素为模版(模版是一个文件夹)的名称。 </p> ` str = str.replace(/\n+/g, '') navigation.get('useage').eval( 'leftContent("' + str + '")' ) <file_sep>/README.md 暂不支持safari,目前仅测试chrome 56.0.2924.87 详情请移步: https://yuanzhizhu.github.io/switch.js/ 第一步,请先引入template.js,再引入switch.js 第二步,配置switch.js中一些的变量。tplPath表示模板仓库所在目录,默认为mytpl。tpls是仓库中的模板名的一个集合。 我的目录结构如下: . ├── README.md ├── image │   ├── 1.png │   ├── 2.png │   ├── 3.png │   ├── 4.png │   ├── 5.png │   ├── 6.png │   ├── 7.png │   └── left-back.png ├── index.html ├── mytpl │   ├── config │   │   ├── index.js │   │   └── index.tpl │   ├── nav │   │   ├── index.js │   │   └── index.tpl │   ├── useage │   │   ├── index.js │   │   └── index.tpl │   └── view │   ├── index.js │   └── index.tpl ├── switch.js └── template.js 可以看到,mytpl模板仓库下,有4个模板:config,nav,useage,view (注:模板名字随便取的,像config这种只是模板名字刚好取成了这样,没有特殊含义) 所以tpls = ['config', 'nav', 'useage', 'view'] 用navigation进行切换 index.html: ```javascript //切入useage页面,并传递数据{ greet: 'hello', referer: 'index' } navigation.push('useage', { greet: 'hello', referer: 'index' }) ``` useage/index.tpl: ```html <!--渲染--> <div> <p>{{ input.referer }} say {{ input.greet }} to me</p> </div> ``` useage/index.js: ```javascript //调用传入的数据 console.log(env.input.greet) //切出useage navigation.pop() ``` 用view进行切换: index.html ```javascript var container = view(DOM) container.load('config', { lalala: 'hi' }) ``` <file_sep>/mytpl/view/index.js var str = ` <h1> view </h1> <p> view(DOM).load(index, dataObj)<br /> 载入新页面,index的参数值为模板名,dataObj为可选 </p> ` str = str.replace(/\n+/g, '') navigation.get('useage').eval('leftContent("' + str + '")')
d8462ad325365ce7b5fa3566bedb7a1bfc200198
[ "JavaScript", "Markdown" ]
5
JavaScript
yuanzhizhu/switch.js
4da915b7e7da2c79bf54464e8cc317ec5b1f3083
8d5d02bb52df4593a6bf165ac09d9bbaf0411775
refs/heads/main
<repo_name>wolpear/cinema<file_sep>/cinema-app/src/main/kotlin/pl/karczewski/cinema/domain/movie/MovieConfiguration.kt package pl.karczewski.cinema.domain.movie import org.springframework.boot.context.properties.ConfigurationProperties import org.springframework.boot.context.properties.ConstructorBinding @ConstructorBinding @ConfigurationProperties("movie") data class MovieConfiguration( val tmdbApiKey: String ) <file_sep>/cinema-app/src/main/kotlin/pl/karczewski/cinema/domain/client/Client.kt package pl.karczewski.cinema.domain.client import com.fasterxml.jackson.annotation.JsonIgnore import pl.karczewski.cinema.domain.reservation.SeatReservation import javax.persistence.CascadeType import javax.persistence.Column import javax.persistence.Entity import javax.persistence.FetchType import javax.persistence.GeneratedValue import javax.persistence.GenerationType import javax.persistence.Id import javax.persistence.OneToMany @Entity data class Client( @Id @GeneratedValue(strategy = GenerationType.IDENTITY) var id: Long? = null, @Column(nullable = false, unique = false) var firstName: String?, @Column(nullable = false, unique = false) var lastName: String?, @Column(nullable = false, unique = true) var email: String?, @Column(nullable = false, unique = false) @JsonIgnore var password: String?, @OneToMany(cascade = [CascadeType.ALL], fetch = FetchType.LAZY, mappedBy = "client") var seatReservations: MutableList<SeatReservation>? = null ) <file_sep>/cinema-app/src/main/kotlin/pl/karczewski/cinema/common/InformationResponseBody.kt package pl.karczewski.cinema.common import java.time.Instant data class InformationResponseBody( val message: String, val timestamp: Instant = Instant.now(), ) <file_sep>/cinema-app/src/main/kotlin/pl/karczewski/cinema/domain/client/ClientController.kt package pl.karczewski.cinema.domain.client import org.springframework.security.crypto.password.PasswordEncoder import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController import pl.karczewski.cinema.common.InformationResponseBody @RestController @RequestMapping("/api/v1/clients") class ClientController(private val clientService: ClientService) { @PostMapping fun createClient(@RequestBody clientBody: ClientBody): InformationResponseBody { return clientService.createClient(clientBody) } } data class ClientBody( val firstName: String, val lastName: String, val email: String, val plaintextPassword: String ) { fun toClient(passwordEncoder: PasswordEncoder): Client { return Client( firstName = firstName, lastName = lastName, email = email, password = passwordEncoder.encode(plaintextPassword) ) } } <file_sep>/cinema-app/src/main/kotlin/pl/karczewski/cinema/CinemaApplication.kt package pl.karczewski.cinema import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.context.properties.ConfigurationPropertiesScan import org.springframework.boot.runApplication @SpringBootApplication @ConfigurationPropertiesScan class CinemaApplication fun main(args: Array<String>) { runApplication<CinemaApplication>(*args) } <file_sep>/cinema-webapp/vue.config.js module.exports = { transpileDependencies: [ 'vuetify', ], devServer: { proxy: 'http://localhost:9000', watchOptions: { pool: true, }, }, }; <file_sep>/cinema-app/src/main/kotlin/pl/karczewski/cinema/domain/reservation/ReservationService.kt package pl.karczewski.cinema.domain.reservation import org.springframework.stereotype.Service import pl.karczewski.cinema.common.InformationResponseBody import pl.karczewski.cinema.domain.client.Client import pl.karczewski.cinema.domain.client.ClientService import pl.karczewski.cinema.domain.hall.Hall import pl.karczewski.cinema.domain.movie.Movie import pl.karczewski.cinema.domain.movie.MovieDto import java.security.Principal import java.time.LocalDateTime import javax.transaction.Transactional @Service class ReservationService( private val movieProjectionRepository: MovieProjectionRepository, private val seatReservationRepository: SeatReservationRepository, private val clientService: ClientService ) { @Transactional fun createProjection(movie: Movie, hall: Hall, datetime: LocalDateTime) { val projection = MovieProjection( datetime = datetime, hall = hall, movie = movie, seats = null ) movieProjectionRepository.save(projection) for (row in 1..hall.numRows!!) { for (col in 1..hall.numColumns!!) { val seat = SeatReservation( numRow = row, numCol = col, client = null, projection = projection ) seatReservationRepository.save(seat) } } } internal fun getProjectionData(projectionId: Long): ProjectionSeatsDto { val projection = movieProjectionRepository.findById(projectionId).get() val seats = projection.seats!! return ProjectionSeatsDto( movie = projection.movie?.toMovieDto()!!, projection = projection.toProjectionDto(), seats = seats.map { it.toSeatReservationDto() } ) } fun reserveSeat(seatId: Long, client: Client) { val seat = seatReservationRepository.findById(seatId).get() seat.client = client seatReservationRepository.save(seat) } @Transactional internal fun reserveSeats(reserveSeatsDto: ReserveSeatsDto, principal: Principal): InformationResponseBody { return try { val client = clientService.fetchClient(principal.name) val seats = seatReservationRepository.findAllById(reserveSeatsDto.seatIds) seats.map { it.client = client it }.let { seatReservationRepository.saveAll(it) } InformationResponseBody(message = "Successfully reserved seats!") } catch (ex: Exception) { InformationResponseBody(message = "Error reserving seats!") } } internal fun clientReservations(principal: Principal): ClientProjectionsDto { val client = clientService.fetchClient(principal.name) val projectionSeatsAssociation = client.seatReservations ?.groupBy { it.projection } ?.mapKeys { entry -> entry.key?.toProjectionWithSeatsDto(entry.value.map { it.toSeatReservationDto() }) }!! return ClientProjectionsDto( projections = projectionSeatsAssociation.keys.map { it!! } ) } } internal data class ProjectionSeatsDto( val movie: MovieDto, val projection: MovieProjectionDto, val seats: List<SeatReservationDto> ) internal data class ClientProjectionsDto( val projections: List<MovieProjectionWithSeatsDto> ) <file_sep>/cinema-app/src/main/kotlin/pl/karczewski/cinema/domain/reservation/Reservation.kt package pl.karczewski.cinema.domain.reservation import pl.karczewski.cinema.domain.client.Client import pl.karczewski.cinema.domain.hall.Hall import pl.karczewski.cinema.domain.hall.HallDto import pl.karczewski.cinema.domain.movie.Movie import pl.karczewski.cinema.domain.movie.MovieDto import java.time.LocalDateTime import javax.persistence.CascadeType import javax.persistence.Column import javax.persistence.Entity import javax.persistence.FetchType import javax.persistence.GeneratedValue import javax.persistence.GenerationType import javax.persistence.Id import javax.persistence.ManyToOne import javax.persistence.OneToMany @Entity class MovieProjection( @Id @GeneratedValue(strategy = GenerationType.IDENTITY) var id: Long? = null, @Column(nullable = false, unique = false) var datetime: LocalDateTime?, @ManyToOne var hall: Hall?, @ManyToOne var movie: Movie?, @OneToMany(cascade = [CascadeType.ALL], fetch = FetchType.LAZY, mappedBy = "projection") var seats: MutableList<SeatReservation>? ) { fun toProjectionDto(): MovieProjectionDto { return MovieProjectionDto( id = id!!, datetime = datetime!!, hall = hall?.toHallDto()!!, freeSeats = seats?.count { !it.taken }!! ) } fun toProjectionWithSeatsDto(seats: List<SeatReservationDto>): MovieProjectionWithSeatsDto { return MovieProjectionWithSeatsDto( id = id!!, datetime = datetime!!, movie = movie?.toMovieDto()!!, hall = hall?.toHallDto()!!, seats = seats ) } } @Entity data class SeatReservation( @Id @GeneratedValue(strategy = GenerationType.IDENTITY) var id: Long? = null, @Column(nullable = false, unique = false) var numRow: Int?, @Column(nullable = false, unique = false) var numCol: Int?, @ManyToOne(optional = true) var client: Client?, @ManyToOne(optional = false) var projection: MovieProjection? ) { val taken: Boolean get() = client != null fun toSeatReservationDto(): SeatReservationDto { return SeatReservationDto( id = id!!, numRow = numRow!!, numCol = numCol!!, taken = taken ) } } data class MovieProjectionDto( val id: Long, val datetime: LocalDateTime, val hall: HallDto, val freeSeats: Int ) data class MovieProjectionWithSeatsDto( val id: Long, val datetime: LocalDateTime, val hall: HallDto, val movie: MovieDto, val seats: List<SeatReservationDto> ) data class SeatReservationDto( val id: Long, val numRow: Int, val numCol: Int, val taken: Boolean ) <file_sep>/cinema-app/src/main/kotlin/pl/karczewski/cinema/common/Mapper.kt package pl.karczewski.cinema.common import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper object Mapper { val mapper = jacksonObjectMapper() } <file_sep>/cinema-app/src/main/kotlin/pl/karczewski/cinema/domain/reservation/ReservationController.kt package pl.karczewski.cinema.domain.reservation import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController import pl.karczewski.cinema.common.InformationResponseBody import java.security.Principal @RestController @RequestMapping("/api/v1") class ReservationController(private val service: ReservationService) { @GetMapping("/projection/{projectionId}/seats") private fun projectionSeats(@PathVariable projectionId: String): ProjectionSeatsDto { return service.getProjectionData(projectionId = projectionId.toLong()) } @PostMapping("/seats") private fun reserveSeats(@RequestBody body: ReserveSeatsDto, principal: Principal): InformationResponseBody { return service.reserveSeats(body, principal) } @GetMapping("/reservations") private fun clientReservations(principal: Principal): ClientProjectionsDto { return service.clientReservations(principal) } } data class ReserveSeatsDto( val seatIds: List<Long> ) <file_sep>/cinema-app/src/main/kotlin/pl/karczewski/cinema/domain/hall/HallService.kt package pl.karczewski.cinema.domain.hall import org.springframework.stereotype.Service @Service class HallService( private val hallRepository: HallRepository, ) { fun createHall(hallName: String, numRows: Int, numColumns: Int): Hall { val hall = Hall( id = null, name = hallName, numRows = numRows, numColumns = numColumns ) hallRepository.save(hall) return hall } } <file_sep>/cinema-app/src/main/kotlin/pl/karczewski/cinema/domain/movie/MovieController.kt package pl.karczewski.cinema.domain.movie import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController import pl.karczewski.cinema.domain.reservation.MovieProjectionDto @RestController @RequestMapping("/api/v1/movies") class MovieController(private val service: MovieService) { @GetMapping() fun allMovies(): MoviesDto { return MoviesDto(service.fetchAllMoviesDto()) } @GetMapping("/{movieId}") fun movie(@PathVariable movieId: String): MovieDto { return service.fetchMovieDto(movieId.toLong()) } @GetMapping("/{movieId}/projections") fun movieProjections(@PathVariable movieId: String): MovieProjectionsDto { return MovieProjectionsDto(service.fetchMovieProjections(movieId.toLong())) } } data class MoviesDto( val movies: List<MovieDto> ) data class MovieProjectionsDto( val projections: List<MovieProjectionDto> ) <file_sep>/cinema-app/src/main/kotlin/pl/karczewski/cinema/infrastructure/security/JwtConfig.kt package pl.karczewski.cinema.infrastructure.security import com.auth0.jwt.JWT import com.auth0.jwt.algorithms.Algorithm import org.springframework.security.authentication.AuthenticationManager import org.springframework.security.authentication.UsernamePasswordAuthenticationToken import org.springframework.security.core.Authentication import org.springframework.security.core.context.SecurityContextHolder import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter import org.springframework.security.web.authentication.www.BasicAuthenticationFilter import org.springframework.web.util.WebUtils.getCookie import pl.karczewski.cinema.common.Mapper import java.io.IOException import java.util.Date import javax.servlet.FilterChain import javax.servlet.ServletException import javax.servlet.http.Cookie import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse object SecurityConstants { const val SECRET = "SecretKeyToGenJWTs" const val EXPIRATION_TIME: Long = 864_000_000 // 10 days const val COOKIE_NAME = "access_token" const val SIGN_UP_URL = "/login" } class JWTAuthenticationFilter(authenticationManager: AuthenticationManager) : UsernamePasswordAuthenticationFilter(authenticationManager) { override fun attemptAuthentication(request: HttpServletRequest?, response: HttpServletResponse?): Authentication { try { val client = Mapper.mapper.readValue(request?.inputStream, ClientCredentials::class.java) return authenticationManager.authenticate( UsernamePasswordAuthenticationToken( client.email, client.password, listOf() ) ) } catch (e: IOException) { throw RuntimeException(e) } } override fun successfulAuthentication( request: HttpServletRequest?, response: HttpServletResponse?, chain: FilterChain?, authResult: Authentication? ) { val sub = (authResult?.principal as? ClientDetails) val token = JWT.create() .withSubject(sub?.username) .withClaim("name", sub?.client?.firstName + " " + sub?.client?.lastName) .withExpiresAt(Date(System.currentTimeMillis() + SecurityConstants.EXPIRATION_TIME)) .sign(Algorithm.HMAC512(SecurityConstants.SECRET)) response?.addCookie(Cookie(SecurityConstants.COOKIE_NAME, token)) } } class JWTAuthorizationFilter(authManager: AuthenticationManager?) : BasicAuthenticationFilter(authManager) { @Throws(IOException::class, ServletException::class) override fun doFilterInternal( req: HttpServletRequest, res: HttpServletResponse, chain: FilterChain ) { val cookie = getCookie(req, SecurityConstants.COOKIE_NAME) if (cookie == null) { chain.doFilter(req, res) return } val authentication = getAuthentication(req) SecurityContextHolder.getContext().authentication = authentication chain.doFilter(req, res) } private fun getAuthentication(request: HttpServletRequest): UsernamePasswordAuthenticationToken? { val token = getCookie(request, SecurityConstants.COOKIE_NAME)?.value if (token != null) { val user: String = JWT.require(Algorithm.HMAC512(SecurityConstants.SECRET)) .build() .verify(token) .subject return UsernamePasswordAuthenticationToken(user, null, listOf()) } return null } } data class ClientCredentials( val email: String, val password: <PASSWORD> ) <file_sep>/cinema-app/src/main/kotlin/pl/karczewski/cinema/infrastructure/security/SecurityConfig.kt package pl.karczewski.cinema.infrastructure.security import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.http.HttpMethod import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter import org.springframework.security.config.http.SessionCreationPolicy import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder import org.springframework.security.crypto.password.PasswordEncoder import org.springframework.web.cors.CorsConfiguration import org.springframework.web.cors.CorsConfigurationSource import org.springframework.web.cors.UrlBasedCorsConfigurationSource @Configuration class SecurityConfig( val clientDetailsService: ClientDetailsService, val passwordEncoder: PasswordEncoder ) : WebSecurityConfigurerAdapter() { override fun configure(auth: AuthenticationManagerBuilder?) { auth?.userDetailsService(clientDetailsService)?.passwordEncoder(passwordEncoder) } override fun configure(http: HttpSecurity?) { http ?.csrf()?.disable() ?.authorizeRequests() ?.mvcMatchers(HttpMethod.POST, SecurityConstants.SIGN_UP_URL)?.permitAll() ?.mvcMatchers(HttpMethod.POST, "/api/v1/clients")?.permitAll() ?.mvcMatchers(HttpMethod.GET, "/api/v1/movies")?.permitAll() ?.anyRequest()?.authenticated() ?.and() ?.addFilter(JWTAuthenticationFilter(authenticationManager())) ?.addFilter(JWTAuthorizationFilter(authenticationManager())) // disable session creation by spring security ?.sessionManagement()?.sessionCreationPolicy(SessionCreationPolicy.STATELESS) } } @Bean fun corsConfigurationSource(): CorsConfigurationSource { val source = UrlBasedCorsConfigurationSource() source.registerCorsConfiguration("/**", CorsConfiguration().applyPermitDefaultValues()) return source } @Configuration class PassEncoderConfig() { @Bean fun passwordEncoder(): PasswordEncoder { return BCryptPasswordEncoder() } } <file_sep>/cinema-app/src/main/kotlin/pl/karczewski/cinema/domain/client/ClientService.kt package pl.karczewski.cinema.domain.client import org.springframework.dao.DataIntegrityViolationException import org.springframework.http.HttpStatus import org.springframework.security.crypto.password.PasswordEncoder import org.springframework.stereotype.Service import org.springframework.web.bind.annotation.ResponseStatus import pl.karczewski.cinema.common.InformationResponseBody @Service class ClientService( private val repository: ClientRepository, private val passwordEncoder: PasswordEncoder ) { fun createClient(clientBody: ClientBody): InformationResponseBody { val client = clientBody.toClient(passwordEncoder) try { repository.save(client) return InformationResponseBody("Successfully created user with e-mail ${client.email}!") } catch (e: DataIntegrityViolationException) { throw UserWithEmailExistsException("User with e-mail ${client.email} already exists!") } } fun fetchClient(clientId: Long): Client { return repository.findById(clientId).get() } fun fetchClient(email: String): Client { return repository.findByEmail(email)!! } } @ResponseStatus(value = HttpStatus.CONFLICT) data class UserWithEmailExistsException( override val message: String ) : RuntimeException(message) <file_sep>/cinema-app/src/main/kotlin/pl/karczewski/cinema/domain/hall/HallRepository.kt package pl.karczewski.cinema.domain.hall import org.springframework.data.repository.CrudRepository import org.springframework.stereotype.Repository @Repository interface HallRepository : CrudRepository<Hall, Long> <file_sep>/cinema-webapp/src/common/security.js import Cookies from 'js-cookie'; // eslint-disable-next-line camelcase import jwt_decode from 'jwt-decode'; class Cookie { static removeLoginCookie() { Cookies.remove('access_token'); } static getLoginCookie() { return Cookies.get('access_token'); } static checkIfUserLoggedIn() { return !!this.getLoginCookie(); } static getLogin() { const cookieToDecode = this.getLoginCookie(); if (!cookieToDecode) { return null; } const decodedCookie = jwt_decode(cookieToDecode); return decodedCookie.name; } } export default Cookie; <file_sep>/settings.gradle.kts rootProject.name = "cinema" include("cinema-app") include("cinema-webapp")<file_sep>/cinema-app/src/main/kotlin/pl/karczewski/cinema/domain/movie/MovieService.kt package pl.karczewski.cinema.domain.movie import com.fasterxml.jackson.annotation.JsonProperty import org.springframework.http.HttpMethod import org.springframework.stereotype.Service import org.springframework.web.client.RestTemplate import org.springframework.web.util.UriComponentsBuilder import pl.karczewski.cinema.domain.reservation.MovieProjectionDto @Service class MovieService( private val repository: MovieRepository, private val configuration: MovieConfiguration ) { val categoryCacheMap = loadCategoriesFromMovieDBToLocalMapCache() private fun uriComponentBuilder() = UriComponentsBuilder.newInstance() .scheme("https") .host("api.themoviedb.org") .queryParam("api_key", configuration.tmdbApiKey) private fun loadCategoriesFromMovieDBToLocalMapCache(): Map<Int, String> { val url = uriComponentBuilder().path("3/genre/movie/list").toUriString() val response = restTemplate.exchange(url, HttpMethod.GET, null, ResponseCategoriesTMDB::class.java) return response.body?.genres?.associateBy({ it.id }, { it.name })!! } fun loadMultipleMoviesPagesFromMovieDBToLocalDBCache() { for (pageNum in 1..3) { loadMoviesFromMovieDBToLocalDBCache(pageNum) } } private fun loadMoviesFromMovieDBToLocalDBCache(pageNum: Int = 1) { val url = uriComponentBuilder().path("3/movie/popular").queryParam("page", pageNum).toUriString() val response = restTemplate.exchange( url, HttpMethod.GET, null, ResponseMoviesTMDB::class.java ) response.body?.results ?.filter { it.genreIds.isNotEmpty() && it.overview.isNotBlank() } ?.map { it.toMovie(this) } ?.map { repository.save(it) } } fun fetchAllMovies(): List<Movie> { val movies = repository.findAll().toList() return movies } fun fetchAllMoviesDto(): List<MovieDto> { return repository.findAll().map { it.toMovieDto() } } fun fetchMovieProjections(movieId: Long): List<MovieProjectionDto> { val movie = repository.findById(movieId).get() return movie.projections?.map { it.toProjectionDto() }!! } fun fetchMovieDto(movieId: Long): MovieDto { return repository.findById(movieId).get().toMovieDto() } companion object { val restTemplate = RestTemplate() } } data class ResponseMoviesTMDB( val results: List<MovieTMDB> ) data class MovieTMDB( val title: String, @JsonProperty("vote_average") val voteAverage: Float, @JsonProperty("genre_ids") val genreIds: List<Int>, @JsonProperty("poster_path") val posterPath: String, val overview: String ) { fun toMovie(movieService: MovieService): Movie { return Movie( null, title = title, genre = genreIds.joinToString { movieService.categoryCacheMap.getOrDefault(it, "unknown category") }, voteAverage = voteAverage, posterPath = "https://image.tmdb.org/t/p/w300$posterPath", overview = overview ) } } data class ResponseCategoriesTMDB( val genres: List<CategoryTMDB> ) data class CategoryTMDB( val id: Int, val name: String ) <file_sep>/cinema-app/src/main/kotlin/pl/karczewski/cinema/CommandLineAppStartUp.kt package pl.karczewski.cinema import org.springframework.boot.CommandLineRunner import org.springframework.stereotype.Component import pl.karczewski.cinema.domain.client.ClientBody import pl.karczewski.cinema.domain.client.ClientService import pl.karczewski.cinema.domain.hall.HallService import pl.karczewski.cinema.domain.movie.MovieService import pl.karczewski.cinema.domain.reservation.ReservationService import java.time.LocalDateTime import java.time.Month @Component private class CommandLineAppStartUp( val clientService: ClientService, val movieService: MovieService, val hallService: HallService, val reservationService: ReservationService ) : CommandLineRunner { override fun run(vararg args: String?) { movieService.loadMultipleMoviesPagesFromMovieDBToLocalDBCache() clientService.createClient( ClientBody( firstName = "Jakub", lastName = "Karczewski", email = "<EMAIL>", plaintextPassword = "123" ) ) clientService.createClient( ClientBody( firstName = "Adam", lastName = "Testowy", email = "<EMAIL>", plaintextPassword = "<PASSWORD>" ) ) val hall = hallService.createHall(hallName = "A", numRows = 8, numColumns = 12) reservationService.createProjection( movie = movieService.fetchAllMovies()[0], hall = hall, datetime = LocalDateTime.of(2021, Month.JANUARY, 20, 14, 20) ) reservationService.createProjection( movie = movieService.fetchAllMovies()[0], hall = hall, datetime = LocalDateTime.of(2021, Month.JANUARY, 20, 21, 30) ) reservationService.createProjection( movie = movieService.fetchAllMovies()[1], hall = hall, datetime = LocalDateTime.of(2021, Month.JANUARY, 20, 12, 0,0) ) for (seatId in 30..34) { reservationService.reserveSeat(seatId = seatId.toLong(), clientService.fetchClient(2)) } } } <file_sep>/cinema-app/src/main/kotlin/pl/karczewski/cinema/domain/movie/Movie.kt package pl.karczewski.cinema.domain.movie import pl.karczewski.cinema.domain.reservation.MovieProjection import javax.persistence.CascadeType import javax.persistence.Column import javax.persistence.Entity import javax.persistence.FetchType import javax.persistence.GeneratedValue import javax.persistence.GenerationType import javax.persistence.Id import javax.persistence.Lob import javax.persistence.OneToMany @Entity class Movie( @Id @GeneratedValue(strategy = GenerationType.IDENTITY) var id: Long? = null, @Column(nullable = false, unique = true) var title: String?, @Column(nullable = false, unique = false) var genre: String?, @Column(nullable = false, unique = false) var voteAverage: Float?, @Column(nullable = false, unique = false) var posterPath: String?, @Lob @Column(nullable = false, unique = false) var overview: String?, @OneToMany(cascade = [CascadeType.ALL], fetch = FetchType.EAGER, mappedBy = "movie") var projections: MutableList<MovieProjection>? = null, ) { fun toMovieDto(): MovieDto { return MovieDto( id = id!!, title = title!!, genre = genre!!, voteAverage = voteAverage!!, posterPath = posterPath!!, overview = overview!!, availableProjections = projections?.any { projection -> projection.seats?.any { !it.taken }!! }!! ) } } data class MovieDto( var id: Long, var title: String, var genre: String, var voteAverage: Float, var posterPath: String, var overview: String, var availableProjections: Boolean ) <file_sep>/cinema-webapp/src/common/eventBus.js import Vue from 'vue'; const eventBus = new Vue(); const EVENT_LOGGED_IN = 'LOGGED_IN'; export { eventBus, EVENT_LOGGED_IN }; <file_sep>/cinema-app/src/main/kotlin/pl/karczewski/cinema/infrastructure/security/ClientDetailsService.kt package pl.karczewski.cinema.infrastructure.security import org.springframework.security.core.GrantedAuthority import org.springframework.security.core.authority.SimpleGrantedAuthority import org.springframework.security.core.userdetails.UserDetails import org.springframework.security.core.userdetails.UserDetailsService import org.springframework.security.core.userdetails.UsernameNotFoundException import org.springframework.stereotype.Service import pl.karczewski.cinema.domain.client.Client import pl.karczewski.cinema.domain.client.ClientRepository @Service class ClientDetailsService(val clientRepository: ClientRepository) : UserDetailsService { // we use e-mail as a username override fun loadUserByUsername(username: String?): UserDetails { val client = clientRepository.findByEmail(username!!) ?: throw UsernameNotFoundException("User with e-mail $username not found!") return ClientDetails(client) } } data class ClientDetails( val client: Client ) : UserDetails { override fun getAuthorities(): MutableCollection<out GrantedAuthority> = mutableListOf(SimpleGrantedAuthority("USER")) override fun getPassword(): String = client.password!! override fun getUsername(): String = client.email!! override fun isAccountNonExpired(): Boolean = true override fun isAccountNonLocked(): Boolean = true override fun isCredentialsNonExpired(): Boolean = true override fun isEnabled(): Boolean = true } <file_sep>/cinema-app/src/main/kotlin/pl/karczewski/cinema/domain/movie/MovieRepository.kt package pl.karczewski.cinema.domain.movie import org.springframework.data.repository.CrudRepository import org.springframework.stereotype.Repository @Repository interface MovieRepository : CrudRepository<Movie, Long> <file_sep>/README.md # Cinema system project Basic system for cinemas. [Swagger - localhost (requires to be logged in)](http://localhost:9000/swagger-ui/#/) <file_sep>/cinema-app/src/main/kotlin/pl/karczewski/cinema/domain/reservation/ReservationRepository.kt package pl.karczewski.cinema.domain.reservation import org.springframework.data.repository.CrudRepository import org.springframework.stereotype.Repository @Repository interface MovieProjectionRepository : CrudRepository<MovieProjection, Long> @Repository interface SeatReservationRepository : CrudRepository<SeatReservation, Long> <file_sep>/cinema-app/build.gradle.kts import org.jetbrains.kotlin.gradle.tasks.KotlinCompile plugins { id("org.springframework.boot") version "2.4.0" id("io.spring.dependency-management") version "1.0.10.RELEASE" id("org.jlleitschuh.gradle.ktlint") version "9.4.1" kotlin("jvm") version "1.4.10" kotlin("plugin.spring") version "1.4.10" kotlin("plugin.noarg") version "1.4.10" kotlin("plugin.allopen") version "1.4.10" kotlin("plugin.jpa") version "1.4.10" kotlin("plugin.serialization") version "1.4.10" } group = "pl.karczewski" version = "0.0.1-SNAPSHOT" java.sourceCompatibility = JavaVersion.VERSION_11 repositories { mavenCentral() jcenter() } dependencies { implementation("org.springframework.boot:spring-boot-starter-web") implementation("org.springframework.boot:spring-boot-starter-jdbc") implementation("org.springframework.boot:spring-boot-starter-data-jpa") implementation("mysql:mysql-connector-java:8.0.22") implementation("org.springframework.boot:spring-boot-starter-security") implementation("com.auth0:java-jwt:3.12.0") implementation("com.fasterxml.jackson.module:jackson-module-kotlin") implementation("org.jetbrains.kotlin:kotlin-reflect") implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8") implementation("io.springfox:springfox-boot-starter:3.0.0") implementation("io.springfox:springfox-swagger-ui:3.0.0") implementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.12.0") annotationProcessor("org.springframework.boot:spring-boot-configuration-processor") developmentOnly("org.springframework.boot:spring-boot-devtools") testImplementation("org.springframework.boot:spring-boot-starter-test") testImplementation("org.springframework.security:spring-security-test") } tasks.withType<Test> { useJUnitPlatform() } tasks.withType<KotlinCompile> { kotlinOptions { freeCompilerArgs = listOf("-Xjsr305=strict") jvmTarget = "11" } } allOpen { annotation("javax.persistence.Entity") annotation("javax.persistence.MappedSuperclass") annotation("javax.persistence.Embeddable") } <file_sep>/cinema-app/src/main/kotlin/pl/karczewski/cinema/domain/client/ClientRepository.kt package pl.karczewski.cinema.domain.client import org.springframework.data.repository.CrudRepository import org.springframework.stereotype.Repository @Repository interface ClientRepository : CrudRepository<Client, Long> { fun findByEmail(email: String): Client? } <file_sep>/cinema-app/src/main/kotlin/pl/karczewski/cinema/domain/hall/Hall.kt package pl.karczewski.cinema.domain.hall import javax.persistence.Column import javax.persistence.Entity import javax.persistence.GeneratedValue import javax.persistence.GenerationType import javax.persistence.Id @Entity data class Hall( @Id @GeneratedValue(strategy = GenerationType.IDENTITY) var id: Long? = null, @Column(nullable = false, unique = true) var name: String?, @Column(nullable = false, unique = false) var numRows: Int?, @Column(nullable = false, unique = false) var numColumns: Int?, ) { fun toHallDto(): HallDto { return HallDto( id = id!!, name = name!!, numRows = numRows!!, numColumns = numColumns!! ) } } data class HallDto( val id: Long, val name: String, val numRows: Int, val numColumns: Int, )
bfadfa824a304edc8af0e2726848bf0f3aa1567a
[ "JavaScript", "Kotlin", "Markdown" ]
29
Kotlin
wolpear/cinema
c48e00b393460377ddffbd0bb63fe60962733fb0
9fb13414d9d24f2186c8a2077b225d36a801cdd9
refs/heads/master
<file_sep># washbois2 Android App for Monitoring Laundry Room Usage <file_sep>package washbro.android.com.washbros; import android.app.Activity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.Spinner; public class SetMachineTimerActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_set_machine_timer); String[] arraySpinner = new String[] { "1", "2", "3", "4", "5" }; Spinner s = (Spinner) findViewById(R.id.time_spinner); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, arraySpinner); adapter.setDropDownViewResource(android.R.layout.activity_list_item); s.setAdapter(adapter); } } <file_sep>package washbro.android.com.washbros; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; public class MainActivity extends AppCompatActivity { private Button btnToRoom, btnToCreate; private EditText editTextRoomId; private FirebaseAuth mAuth; DatabaseReference mRooms; DatabaseReference mUsers; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnToRoom = findViewById(R.id.btnGoToRoom); btnToCreate = findViewById(R.id.btnGoToCreate); editTextRoomId = findViewById(R.id.editTextRoomId); mRooms = FirebaseDatabase.getInstance().getReference("Rooms"); mUsers = FirebaseDatabase.getInstance().getReference("Users"); final String roomID =editTextRoomId.getText().toString(); btnToRoom.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(roomID.equals("")){ Toast.makeText(MainActivity.this, "Enter a Room ID", Toast.LENGTH_SHORT).show(); return; } mRooms.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for(DataSnapshot roomsnapshot: dataSnapshot.getChildren()){ if(roomID == roomsnapshot.toString()){ mUsers.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot allSnapshot) { for(DataSnapshot usersnapshot: allSnapshot.getChildren()){ if(usersnapshot.toString().equals(mAuth.getCurrentUser().getUid())){ } } } @Override public void onCancelled(DatabaseError databaseError) { } }); } } } @Override public void onCancelled(DatabaseError databaseError) { } }); } }); btnToCreate.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view) { Intent intent = new Intent(MainActivity.this, CreateRoomActivity.class); startActivity(intent); finish(); } }); } public void onStart() { super.onStart(); // Check if user is signed in (non-null) and update UI accordingly. FirebaseUser currentUser = mAuth.getCurrentUser(); } } <file_sep>package washbro.android.com.washbros; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; public class RoomActivity extends AppCompatActivity { Button washer1,washer2,washer3,dryer1,dryer2,dryer3; DatabaseReference mRoom; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_room); washer1 = findViewById(R.id.washer1); washer2 = findViewById(R.id.washer2); washer3 = findViewById(R.id.washer3); dryer1 = findViewById(R.id.dryer1); dryer2 = findViewById(R.id.dryer2); dryer3 = findViewById(R.id.dryer3); mRoom = FirebaseDatabase.getInstance().getReference("Room"); washer1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { } }); } } <file_sep>package washbro.android.com.washbros; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import java.text.SimpleDateFormat; import java.util.Date; public class CreateRoomActivity extends AppCompatActivity { private EditText editDryerNumber, editRoomLocation, editWasherNumber; private Button btnCreateRoom; DatabaseReference mRoom; Washer washer1,washer2,washer3,washer4,washer5,washer6; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_create_room); editDryerNumber = findViewById(R.id.text_dryer_number); editWasherNumber = findViewById(R.id.text_washer_number); editRoomLocation = findViewById(R.id.text_room_location); btnCreateRoom = findViewById(R.id.btnCreateRoom); mRoom = FirebaseDatabase.getInstance().getReference("Rooms"); String dryers = editDryerNumber.getText().toString(); String washers = editDryerNumber.getText().toString(); String location = editDryerNumber.getText().toString(); } }
9f74e991c651cf5ffdd4e90d9acf377ffca5efe7
[ "Markdown", "Java" ]
5
Markdown
laundry-lobby/laundryLobby
97447a705d33f2268521bd16aa92e155916e15da
2d0dd779bf404398bf3355280de69ec895cddbd2
refs/heads/master
<repo_name>st-pa/dragonfire-workspace<file_sep>/app14/AppDevice.cpp //==================================================== // App.cpp - Grundgerüst für künftige Anwendungen //==================================================== #include "DragonFireSDK.h" #include "../common/MeinLabello.h" #include "../common/Button.h" #include "../common/Font.h" #include "../common/Toast.h" #include "../common/MyTools.h" #include <stdlib.h> using namespace std; ////////////////////////////////////////////// // Konstanten //////////////////////////////// ////////////////////////////////////////////// char* FONTDIR = "Fonts/Broadway18RegularGreen"; /* Bildschirmbreite */ const int XS = MyTools::getDisplayWidth(); /* Bildschirmhöhe */ const int YS = MyTools::getDisplayHeight(); ////////////////////////////////////////////// // Variablen ///////////////////////////////// ////////////////////////////////////////////// int cn; Font* font = NULL; Toast* toast = NULL; MeinLabello* label = NULL; ////////////////////////////////////////////// // Methoden und Funktionen /////////////////// ////////////////////////////////////////////// int onClick(int id,int event,int x,int y) { int wert; char help[100]; switch (id) { case 0: wert = DeviceGetBatteryLevel(); label->setText("DeviceGetBatteryLevel() = %d", wert); break; case 1: /* 0 = Konnte keine Informationen ermitteln 1 = Geraet haengt NICHT am Ladegeraet und entlaedt sich 2 = Geraet haengt am Ladegeraet und wird geladen 3 = Geraet haengt am Ladegeraet und ist voll geladen */ wert = DeviceGetBatteryState(); label->setText("DeviceGetBatteryState() = %d", wert); break; case 2: DeviceGetLocaleID(help, 10); label->setText("DeviceGetLocaleID() = %s", help); break; case 3: /* Multitasking wurde erst ab iOS4.x eingefuehrt. Bis hier wuerde also der Wert gleich 0 sein */ // (==0): kein Multitasking // (!=0): Multitasking wert = DeviceGetMultitaskingSupported(); label->setText("DeviceGetMultitaskingSupported() = %d", wert); break; case 4: DeviceGetName(help, 100); label->setText("DeviceGetName() = %s", help); break; case 5: DeviceGetSystemName(help, 100); label->setText("DeviceGetSystemName() = %s", help); break; case 6: DeviceGetSystemVersion(help, 100); label->setText("DeviceGetSystemVersion() = %s", help); break; case 7: // Unique Device Identifier DeviceGetUDID(help, 100); label->setText("DeviceGetUDID =%s ", help); break; case 8: /* 0 = iPhone (320 x 480) 1 = iPad (768 x 1024) 2 = iPhone 5 (320 x 56 */ wert = DeviceGetUIType(); label->setText("DeviceGetUIType() = %d", wert); break; } return 0; } ////////////////////////////////////////////// // ererbte Pflichtmethoden /////////////////// ////////////////////////////////////////////// void AppMain() { ViewAdd("Images/cloud.jpg", 0, 0); font = new Font(FONTDIR); label = new MeinLabello(10, 10, "nix anzumzeigen", FontAdd("Courier","Regular",12,0)); cn = ContainerAdd(0, 0, 0); int buttons = 9; Button* button[9]; char* labels[9] = { "BatteryLevel", "BatteryState", "Locale", "MultiTask", "Name", "SysName", "SysVersion", "UDID", "UIType" }; int x = 20; int y = 40; int width = 200; int id = 0; int padding = 3; int deltaY = 40; for (int i = 0; i < buttons; i++) { button[i] = new Button( cn, x + 70 * (i % 2), y, labels[i], font, padding, onClick, id ); button[i]->setWidth(width); y += deltaY; id++; } } void AppExit() { } void OnTimer() { if (toast == NULL) { if (DeviceGetBatteryLevel() >= 15) { toast = new Toast("battery is below 15%",font,10000); } } else toast->update(); }
889671098fe9e22c83917ba3f03f86fa765a48aa
[ "C++" ]
1
C++
st-pa/dragonfire-workspace
b27ed32790129fb2c9f957a333a0d6fea6364951
07c9ee15ba0e22c6281bbaa14390bc7c49b423b7
refs/heads/master
<repo_name>saurabhajmera/ngspotify<file_sep>/src/app/business-objects/Image.ts /** * Created by sajmera on 12/20/16. */ export class Image{ height:number; width:number; url:string; } <file_sep>/src/app/business-objects/Album.ts /** * Created by sajmera on 12/20/16. */ export class Album{ id:number; } <file_sep>/src/app/home/home.component.ts import { Component, OnInit } from '@angular/core'; import {SpotifyService} from "../spotify.service"; import {Artist} from "../business-objects/Artist"; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'], }) export class HomeComponent implements OnInit { searchStr:string; searchRes:Artist[]; constructor(private spotifyService:SpotifyService) { } ngOnInit() { } searchMusic(){ this.spotifyService.searchMusic(this.searchStr).subscribe( res => { this.searchRes=res.artists.items; console.log(this.searchRes); } ); } } <file_sep>/src/app/app.routing.ts import {ContactComponent} from "./contact/contact.component"; import {AboutComponent} from "./about/about.component"; import {HomeComponent} from "./home/home.component"; import {Routes, RouterModule} from "@angular/router"; import {ModuleWithProviders} from "@angular/core"; import {ArtistComponent} from "./artist/artist.component"; import {AlbumComponent} from "./album/album.component"; /** * Created by sajmera on 12/20/16. */ const appRoutes: Routes = [ {path:'', component:HomeComponent}, {path:'about', component: AboutComponent}, {path: 'contact', component:ContactComponent}, {path:'artist/:id', component:ArtistComponent}, {path:'album/:id',component:AlbumComponent} ]; export const routing:ModuleWithProviders=RouterModule.forRoot(appRoutes); <file_sep>/src/app/business-objects/Artist.ts import {Album} from "./Album"; import {Image} from "./Image"; /** * Created by sajmera on 12/20/16. */ export class Artist{ id:number; name:string; genres:any; albums:Album[]; images: Image[]; }
23765b41130a8bccbcc9056ed67809b50cab6bd3
[ "TypeScript" ]
5
TypeScript
saurabhajmera/ngspotify
2f61f2810b10fa7807e41886bf5a585260abb809
0f98da333c6a69db841c20c4b4f6384d55ef6f92
refs/heads/master
<repo_name>jesseeluo0602/BDAP<file_sep>/controllers.js var app = angular.module('BDAP', ["ngAnimate"]); app.controller('PMTController', function( ){ this.pmt = pmtList; this.list = addedList; this.lol= 0; this.addItem = function(pmtnumber, tech, time){ this.list.push({pmt: pmtnumber, Category: tech, Hours:time}) }; this.addHours = function(){ var sum=0; for (var i = 0; i < this.list.length; i++){ sum= sum +this.list[i].Hours ; } this.lol=sum; } this.clearEle = function(data){ var index = list.indexOf({pmt:data.pmt, Category:data.Category, Hours:data.Hours}) if (index > -1) { list.splice(index, 1); } } this.clear = function(){ this.list=[]; this.lol=0; } }); app.filter('sort', function () { // function to invoke by Angular each time // Angular passes in the `items` which is our Array return function (items, tech) { // Create a new Array var filtered = []; // loop through existing Array for (var i = 0; i < items.length; i++) { var item = items[i]; // check if the individual Array element begins with `a` or not if (item.Category === tech || tech==="All" ) { // push it into the Array if it does! filtered.push(item); } } // boom, return the Array after iteration's complete return filtered; }; }); var pmtList = [ { PMT: 078945, Category: "Web Development", IterationPts: "58", AvgTime: 15.00}, { PMT: 395783, Category: "Mobile Applications Development", IterationPts:"27", AvgTime: 8.30}, { PMT: 148764, Category: "Performance Testing", IterationPts:"64", AvgTime: 24.86}, { PMT: 034620, Category: "Web Design", IterationPts:"58", AvgTime: 14.65}, { PMT: 947638, Category: "Leadership Training", IterationPts:"32", AvgTime: 7.54}, { PMT: 349730, Category: "Web Development", IterationPts:"85", AvgTime: 37.10}, { PMT: 455893, Category: "Web Development", IterationPts:"46", AvgTime: 11.08}, { PMT: 340847, Category: "Performance Testing", IterationPts:"53", AvgTime: 12.97}, { PMT: 349028, Category: "Mobile Applications Development", IterationPts:"34", AvgTime: 10.12}, { PMT: 087487, Category: "Mobile Applications Design", IterationPts:"58", AvgTime: 16.73}, { PMT: 936044, Category: "U2L", IterationPts:"54", AvgTime: 15.88}, { PMT: 457266, Category: "Server Maintenance", IterationPts:"76", AvgTime: 17.95}, { PMT: 338432, Category: "Cloud Computing", IterationPts:"72", AvgTime: 25.02}, { PMT: 284009, Category: "Big Data Initiative", IterationPts:"34", AvgTime: 19.45}, { PMT: 247678, Category: "Big Data Initiative", IterationPts:"67", AvgTime: 28.86}, { PMT: 346897, Category: "Mobile Applications Design", IterationPts:"44", AvgTime: 45.23}, ]; var addedList = [ {pmt: '85105', Category: "Web Development", Hours:4}, {pmt: '23535', Category: "U2L", Hours:6} ];<file_sep>/Calendar/js/app.js 'use strict'; /* App Module */ var app = angular.module('schedulerApp', [ ]); app.controller('MainSchedulerCtrl', function($scope) { $scope.events = [ { id:1, text:"PMT #EXAMPLE", start_date: new Date(2014, 7, 24), end_date: new Date(2014, 7, 28) }, { id:2, text:"PMT #EXAMPLE2", start_date: new Date(2014, 7, 29 ), end_date: new Date(2013, 8, 2 ) } ]; $scope.scheduler = { date : new Date(2014,8,1) }; });
c866861e4252d06de3dfb348204982075a464980
[ "JavaScript" ]
2
JavaScript
jesseeluo0602/BDAP
468ac548a4a9f1687ef8265cfeeb56ea92ee6719
a76c4598d0999f608cf7862aca9a64e8d89f7fcd
refs/heads/master
<file_sep>-- phpMyAdmin SQL Dump -- version 4.1.12 -- http://www.phpmyadmin.net -- -- Host: 127.0.0.1 -- Generation Time: Apr 05, 2020 at 05:51 AM -- Server version: 5.6.16 -- PHP Version: 5.5.11 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; 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 utf8 */; -- -- Database: `db_daycare` -- -- -------------------------------------------------------- -- -- Table structure for table `tb_kelompok` -- CREATE TABLE IF NOT EXISTS `tb_kelompok` ( `idkelompok` char(3) NOT NULL, `kelompok` varchar(50) DEFAULT NULL, `keterangan` text, PRIMARY KEY (`idkelompok`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `tb_kelompok` -- INSERT INTO `tb_kelompok` (`idkelompok`, `kelompok`, `keterangan`) VALUES ('K01', '1', '1'); /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep><?php require_once '../setting/crud.php'; require_once '../setting/koneksi.php'; require_once '../setting/tanggal.php'; require_once '../setting/fungsi.php'; if(isset($_POST['tambah'])) { //Proses penambahan bunga $stmt = $mysqli->prepare("INSERT INTO tb_bunga (idbunga,lamapinjam,bunga) VALUES (?,?,?)"); $stmt->bind_param("sss", mysqli_real_escape_string($mysqli, $_POST['kode']), mysqli_real_escape_string($mysqli, $_POST['lamapinjam']), mysqli_real_escape_string($mysqli, $_POST['bunga'])); if ($stmt->execute()) { echo "<script>alert('Data Bunga Berhasil Disimpan')</script>"; echo "<script>window.location='index.php?hal=bunga';</script>"; } else { echo "<script>alert('Data Bunga Gagal Disimpan')</script>"; echo "<script>window.location='javascript:history.go(-1)';</script>"; } }else if(isset($_POST['ubah'])){ //Proses ubah data $stmt = $mysqli->prepare("UPDATE tb_bunga SET lamapinjam=?, bunga=? where idbunga=?"); $stmt->bind_param("sss", mysqli_real_escape_string($mysqli, $_POST['lamapinjam']), mysqli_real_escape_string($mysqli, $_POST['bunga']), mysqli_real_escape_string($mysqli, $_POST['kode'])); if ($stmt->execute()) { echo "<script>alert('Data Bunga Berhasil Diubah')</script>"; echo "<script>window.location='index.php?hal=bunga';</script>"; } else { echo "<script>alert('Data Bunga Gagal Diubah')</script>"; echo "<script>window.location='javascript:history.go(-1)';</script>"; } }else if(isset($_GET['hapus'])){ //Proses hapus $stmt = $mysqli->prepare("DELETE FROM tb_bunga where idbunga=?"); $stmt->bind_param("s",mysqli_real_escape_string($mysqli, $_GET['hapus'])); if ($stmt->execute()) { echo "<script>alert('Data Bunga Berhasil Dihapus')</script>"; echo "<script>window.location='index.php?hal=bunga';</script>"; } else { echo "<script>alert('Data Pegawai Gagal Dihapus')</script>"; echo "<script>window.location='javascript:history.go(-1)';</script>"; } } ?><file_sep># si_daycare Sistem Informasi Daycare - Untuk Penitipan Anak <file_sep><?php session_start(); require_once 'setting/crud.php'; require_once 'setting/koneksi.php'; require_once 'setting/tanggal.php'; $user=$_POST['username']; $pass=$_POST['password']; //Pengecekan ada data dalam login tidak $sqlpetugas="Select idpegawai from tb_pegawai where username='$user' and password='$<PASSWORD>' and level='petugas'"; $sqlkepala="Select idpegawai from tb_pegawai where username='$user' and password='$<PASSWORD>' and level='kepala'"; if (CekExist($mysqli,$sqlpetugas)== true){ //JIka data ditemukan $_SESSION['petugas']=caridata($mysqli,$sqlpetugas); echo "<script>alert('Anda login sebagai Petugas')</script>"; echo "<script>window.location='petugas/index.php?hal=beranda';</script>"; }else if (CekExist($mysqli,$sqlkepala)== true){ //JIka data ditemukan $_SESSION['petugas']=caridata($mysqli,$sqlkepala); echo "<script>alert('Anda login sebagai Kepala')</script>"; echo "<script>window.location='kepala/index.php?hal=beranda';</script>"; }else{ //Jika tidak ditemukan echo "<script>alert('Username atau Password tidak terdaftar')</script>"; echo "<script>window.location='index.php';</script>"; } ?><file_sep><?php require_once '../setting/crud.php'; require_once '../setting/koneksi.php'; require_once '../setting/tanggal.php'; require_once '../setting/fungsi.php'; if(isset($_POST['tambah'])) { //Proses penambahan keterangan $stmt = $mysqli->prepare("INSERT INTO tb_kelompok (idkelompok,kelompok,keterangan) VALUES (?,?,?)"); $stmt->bind_param("sss", mysqli_real_escape_string($mysqli, $_POST['kode']), mysqli_real_escape_string($mysqli, $_POST['kelompok']), mysqli_real_escape_string($mysqli, $_POST['keterangan'])); if ($stmt->execute()) { echo "<script>alert('Data Kelompok Usia Berhasil Disimpan')</script>"; echo "<script>window.location='index.php?hal=kelompok';</script>"; } else { echo "<script>alert('Data Kelompok Usia Gagal Disimpan')</script>"; echo "<script>window.location='javascript:history.go(-1)';</script>"; } }else if(isset($_POST['ubah'])){ //Proses ubah data $stmt = $mysqli->prepare("UPDATE tb_kelompok SET kelompok=?, keterangan=? where idkelompok=?"); $stmt->bind_param("sss", mysqli_real_escape_string($mysqli, $_POST['kelompok']), mysqli_real_escape_string($mysqli, $_POST['keterangan']), mysqli_real_escape_string($mysqli, $_POST['kode'])); if ($stmt->execute()) { echo "<script>alert('Data Kelompok Usia Berhasil Diubah')</script>"; echo "<script>window.location='index.php?hal=kelompok';</script>"; } else { echo "<script>alert('Data Kelompok Usia Gagal Diubah')</script>"; echo "<script>window.location='javascript:history.go(-1)';</script>"; } }else if(isset($_GET['hapus'])){ //Proses hapus $stmt = $mysqli->prepare("DELETE FROM tb_kelompok where idkelompok=?"); $stmt->bind_param("s",mysqli_real_escape_string($mysqli, $_GET['hapus'])); if ($stmt->execute()) { echo "<script>alert('Data Kelompok Usia Berhasil Dihapus')</script>"; echo "<script>window.location='index.php?hal=kelompok';</script>"; } else { echo "<script>alert('Data Kelompok Usia Gagal Dihapus')</script>"; echo "<script>window.location='javascript:history.go(-1)';</script>"; } } ?>
d4e5a464ba7bfddad0102a5cd795e5320a58a6e2
[ "Markdown", "SQL", "PHP" ]
5
SQL
fitriyadi/si_daycare
5dd5b91bc98a53d27196fa489dd8d29a99a909bb
a5fcc8b2410bfeed8a9c55bd3ebba75ac2edc75a
refs/heads/main
<repo_name>AyaHanyT/burugesta-1<file_sep>/assets/js/main.js (function() { "use strict"; AOS.init(); const select = (el, all = false) => { el = el.trim() if (all) { return [...document.querySelectorAll(el)] } else { return document.querySelector(el) } } /** * Easy event listener function */ const on = (type, el, listener, all = false) => { let selectEl = select(el, all) if (selectEl) { if (all) { selectEl.forEach(e => e.addEventListener(type, listener)) } else { selectEl.addEventListener(type, listener) } } } /** * Easy on scroll event listener */ const onscroll = (el, listener) => { el.addEventListener('scroll', listener) } /** * Navbar links active state on scroll */ let navbarlinks = select('#navbar .scrollto', true) const navbarlinksActive = () => { let position = window.scrollY + 200 navbarlinks.forEach(navbarlink => { if (!navbarlink.hash) return let section = select(navbarlink.hash) if (!section) return if (position >= section.offsetTop && position <= (section.offsetTop + section.offsetHeight)) { navbarlink.classList.add('active') } else { navbarlink.classList.remove('active') } }) } window.addEventListener('load', navbarlinksActive) onscroll(document, navbarlinksActive) /** * Scrolls to an element with header offset */ const scrollto = (el) => { let header = select('#header') let offset = header.offsetHeight if (!header.classList.contains('header-scrolled')) { offset -= 20 } let elementPos = select(el).offsetTop window.scrollTo({ top: elementPos - offset, behavior: 'smooth' }) } /** * Toggle .header-scrolled class to #header when page is scrolled */ let selectHeader = select('#header') if (selectHeader) { const headerScrolled = () => { if (window.scrollY > 100) { selectHeader.classList.add('header-scrolled') } else { selectHeader.classList.remove('header-scrolled') } } window.addEventListener('load', headerScrolled) onscroll(document, headerScrolled) } /** * Back to top button */ let backtotop = select('.back-to-top') if (backtotop) { const toggleBacktotop = () => { if (window.scrollY > 100) { backtotop.classList.add('active') } else { backtotop.classList.remove('active') } } window.addEventListener('load', toggleBacktotop) onscroll(document, toggleBacktotop) } /** * Mobile nav toggle */ on('click', '.mobile-nav-toggle', function(e) { select('#navbar').classList.toggle('navbar-mobile') this.classList.toggle('fa-bars') this.classList.toggle('fa-times') }) /** * Mobile nav dropdowns activate */ on('click', '.navbar .dropdown > a', function(e) { if (select('#navbar').classList.contains('navbar-mobile')) { e.preventDefault() this.nextElementSibling.classList.toggle('dropdown-active') } }, true) /** * Scrool with ofset on links with a class name .scrollto */ on('click', '.scrollto', function(e) { if (select(this.hash)) { e.preventDefault() let navbar = select('#navbar') if (navbar.classList.contains('navbar-mobile')) { navbar.classList.remove('navbar-mobile') let navbarToggle = select('.mobile-nav-toggle') navbarToggle.classList.toggle('bi-list') navbarToggle.classList.toggle('bi-x') } scrollto(this.hash) } }, true) /** * Scroll with ofset on page load with hash links in the url */ window.addEventListener('load', () => { if (window.location.hash) { if (select(window.location.hash)) { scrollto(window.location.hash) } } }); /** * Preloader */ let preloader = select('#preloader'); if (preloader) { window.addEventListener('load', () => { preloader.remove() }); } /** * Initiate gallery lightbox */ const galleryLightbox = GLightbox({ selector: '.gallery-lightbox' }); /** * Animation on scroll */ window.addEventListener('load', () => { AOS.init({ duration: 1000, easing: 'ease-in-out', once: true, mirror: false }) }); $("#casher").click(function () { $(this).css("background"," #fe97074d") $("#casher-span").css("color","#fe9807") }) $("#delivery").click(function () { $(this).css("background"," #fe97074d") $("#delivery-span").css("color","#fe9807") }) $("#chief").click(function () { $(this).css("background"," #fe97074d") $("#chief-span").css("color","#fe9807") }) ///////////////////\\\\\\\\\\\\\\\ $("#order-details").click(function () { $("#done-1").hide() $("#label-1").show() $("#success-1").hide() $("#order-details-window").show() $("#order-details-window-2").hide() $("#order-details-window-3").hide() $("#add-client-window").hide() }) $("#order-details-2").click(function () { $("#done-1").show() $("#label-1").hide() $("#success-1").show() $("#order-details-window-2").show() $("#order-details-window").hide() $("#add-client-window").hide() }) $("#order-details-3").click(function () { $("#order-details-2").addClass("Done") $("#done-2").show() $("#label-2").hide() $("#success-2").show() $("#order-details-window-2").hide() $("#order-details-window-3").show() $("#order-details-window").hide() $("#add-client-window").hide() }) $("#add-client-btn").click(function(){ $("#add-client-window").show() $("#order-details-3").addClass("Done") $("#order-details-window-3").hide() }) $("#submit-client").click(function(){ $("#order-details-window-2").show() $("#add-client-window").hide() $("#btn-1").hide() $("#btn-2").hide() $("#btn-3").show() $("#client-data").show() }) $("#btn-3").click(function(){ $("#order-details-window-4").show() $("#label-3").hide() $("#success-3").show() $("#order-details-window-2").hide() $("#btn-1").hide() }) $("#confirm-btn").click(function(){ $(".stopped").addClass("shipping") }) $("#order-chiken-1").click(function () { $("#details-1").show() }) $("#delete-details-1").click(function () { $("#details-1").hide() }) // // $("#order-beef-1").click(function () { $("#details-beef-1").show() }) $("#delete-details-be1").click(function () { $("#details-beef-1").hide() }) ////////// $("#order-sideP-1").click(function () { $("#details-sideP-1").show() }) $("#delete-details-sp1").click(function () { $("#details-sideP-1").hide() }) /////////////////\\\\\\\\\\\\\\\ $("#order-appetizers-1").click(function () { $("#details-appetizers-1").show() }) $("#delete-details-ap1").click(function () { $("#details-appetizers-1").hide() }) /////////////////\\\\\\\\\\\\\\\ $("#search-number").on('keyup', function (event) { if (event.keyCode === 13) { document.getElementById("result-table").style.display = "block"; } }) })() function incrementCH1() { document.getElementById('ch-quantity-1').stepUp(); } function decrementCH1() { document.getElementById('ch-quantity-1').stepDown(); } function incrementBE1() { document.getElementById('be-quantity-1').stepUp(); } function decrementBE1() { document.getElementById('be-quantity-1').stepDown(); } ///////////////\\\\\\\\\\\\\\\\\\ function incrementSP1() { document.getElementById('sp-quantity-1').stepUp(); } function decrementSP1() { document.getElementById('sp-quantity-1').stepDown(); } /////////////\\\\\\\\\\\\\\\\\ function incrementAP1() { document.getElementById('ap-quantity-1').stepUp(); } function decrementAP1() { document.getElementById('ap-quantity-1').stepDown(); } /////////////////\\\\\\\\\\\\\\\\\ function incrementD1() { document.getElementById('d-quantity-1').stepUp(); } function decrementD1() { document.getElementById('d-quantity-1').stepDown(); } ///////////////////\\\\\\\\\\\\\\\\\\\ function retrive() { var x = document.getElementById("client-name").value; document.getElementById("clientname").innerHTML = x; var y = document.getElementById("phone-number").value; document.getElementById("phone").innerHTML = y; var z = document.getElementById("inputStreet").value; document.getElementById("address").innerHTML = z; }
e0797df732f5cbc2411057ebd77753630e69189d
[ "JavaScript" ]
1
JavaScript
AyaHanyT/burugesta-1
7ee0b0e85a2d7951a1982db7c28929118e78d0b4
5ab3f4f63ac73b3c95198632597066b958c0871b
refs/heads/master
<repo_name>slincastro/conference-demo<file_sep>/src/main/resources/application-ci.properties spring.datasource.url=jdbc:postgresql://localhost:5431/conference_app spring.datasource.username=slin spring.datasource.password=<PASSWORD> spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect spring.jpa.hibernate.ddl-auto= none spring.jpa.hibernate.show-sql=true spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true server.port=5657 management.endpoint.metrics.enabled=true management.endpoints.web.exposure.include=* management.endpoint.prometheus.enabled=true management.metrics.export.prometheus.enabled=true logging.level.org=TRACE<file_sep>/src/main/java/slin/castro/testing/conferencedemo/repositories/SpeakerRepository.java package slin.castro.testing.conferencedemo.repositories; import org.springframework.data.jpa.repository.JpaRepository; import slin.castro.testing.conferencedemo.models.Speaker; public interface SpeakerRepository extends JpaRepository<Speaker, Long> { } <file_sep>/src/main/java/slin/castro/testing/conferencedemo/repositories/SessionRepository.java package slin.castro.testing.conferencedemo.repositories; import org.springframework.data.jpa.repository.JpaRepository; import slin.castro.testing.conferencedemo.models.Session; public interface SessionRepository extends JpaRepository<Session, Long> { }
e57f8efc4cb55ccea467a3651af0cd5c280deedc
[ "Java", "INI" ]
3
INI
slincastro/conference-demo
61cdd65dd66b3c1996420eb3cbee85396a227423
667601d2d90a80c597e16daae6adc8d0065125ac
refs/heads/main
<file_sep>--- title: 'Estadistica Avanzada: PEC1 - A2 - Estadística inferencial: tests de hipótesis de una y dos muestras' author: "Autor: <NAME>" date: "Octubre 2020" output: html_document: highlight: default code_folding: show # mostrar boton para mostrar o no el código number_sections: yes theme: cosmo toc: yes toc_float: true # tabla contenidos flotante toc_depth: 2 includes: in_header: header.html pdf_document: latex_engine: xelatex highlight: zenburn toc: yes word_document: default --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` ****** ## Introducción *********** #### Preparamos nuestro workspace ```{r} # Limpiamos el workspace, por si hubiera algun dataset o informacion cargada rm(list = ls()) # Limpiamos la consola cat("\014") # Cambiar el directorio de trabajo setwd("~/Documentos/R/opendata") setwd(dirname(rstudioapi::getActiveDocumentContext()$path)) ``` #### Instalamos librerias ```{r} packages <- c("dplyr", "tidyr", "skimr", "lubridate", "ggplot2", 'purrr') new <- packages[!(packages %in% installed.packages()[,"Package"])] if(length(new)) install.packages(new) a=lapply(packages, require, character.only=TRUE) ``` ```{r} demografia <- read.csv("https://www.donostia.eus/datosabiertos/recursos/demografia-origen/demografianacionalidadbarriockan.csv", sep=",") vehiculos <- read.csv("https://www.donostia.eus/datosabiertos/recursos/vehiculos_barrio/vehiculosbarrio.csv", sep=",") tasas <- read.csv("https://www.donostia.eus/datosabiertos/recursos/tasas_tipo/pfitasastipobarriockan.csv", sep=",") recibos <- read.csv("https://www.donostia.eus/datosabiertos/recursos/impuestos_tipo/pfiimpuestostipobarriockan.csv", sep=",") habitantes <- read.csv("https://www.donostia.eus/datosabiertos/recursos/habitantes-barrios/habitantesporbarrio.csv", sep=",") renta <- read.csv("https://www.donostia.eus/datosabiertos/recursos/eustat_renta/eustatrentabarrio.csv", sep=",") indices_demografia <- read.csv("https://www.donostia.eus/datosabiertos/recursos/demografia-indices/demografiaindicesbarriockan.csv", sep=",") paro <- read.csv("https://www.donostia.eus/datosabiertos/recursos/eustat_paro/eustatparobarrio.csv", sep=",") extranjeros <- read.csv("https://www.donostia.eus/datosabiertos/recursos/demografia-extranjeros/demografiaextranjerosbarriockan.csv", sep=",") estudios <- read.csv("https://www.donostia.eus/datosabiertos/recursos/demografia-nivelestudios/demografianivelestudiosbarriockan.csv", sep=",") ``` ```{r} colnames(demografia)= c('año','barrio','nacido','habitantes','habit_M','habit_H') colnames(estudios)= c('año','barrio','est_eusk','estudios','est_Tot','Mujer','Hombre') colnames(extranjeros)= c('año','barrio','extr_M','ext_H','ext_Total') colnames(habitantes)= c('barrio','habitantes') colnames(indices_demografia)= c('año','barrio','tasa_nac_total','tasa_nac_M','tasa_nac_H','fecundidad','tasa_tendencia_total','tasa_tendencia_M','tasa_tendencia_H','tasa_envejecimiento_total','tasa_envejecimiento_M','tasa_envejecimiento_H') colnames(paro)= c('año','barrio','tasa','tasa_paro_H','tasa_paro_M','paro_16_39','paro_40_64','paro_>65','paro_nac','paro_extra') colnames(recibos)= c('año','barrio','recibos_eus','recibos_cast','importe') colnames(renta)= c('año','barrio','renta_Tot','renta_H','renta_M','renta', 'renta_18_39','renta_40_64', 'renta_65', 'renta_nac','renta_ext') colnames(tasas)= c('año','barrio','tasa_eus','tasa_cast','importe') colnames(vehiculos)= c('barrio','vehi_total','turismos','motos','indic_motorizacion') ``` ```{r} estu_barrio_genero <- estudios %>% filter(año==2019) %>% select(-año,-est_eusk,-est_Tot)%>% gather('genero', 'estudiantes', 'Mujer':'Hombre')%>% reshape(idvar=c('barrio',"genero"), v.names = "estudiantes", timevar = "estudios", direction="wide")%>% arrange(barrio) ``` ```{r} habitantes <- habitantes %>% mutate(barrio = toupper(barrio)) demo_barrio <- demografia %>% filter(año==2019) %>% select(-año,-nacido) estu_barrio <- estudios %>% filter(año==2019) %>% select(-año,-est_eusk)%>% reshape(idvar = "barrio",timevar = "estudios", direction = "wide")%>% select(barrio, starts_with("est_Tot")) extr_barrio <- extranjeros %>% filter(año==2019) %>% select(barrio, ext_Total) indi_barrio <- indices_demografia %>% filter(año==2019) %>% select(barrio, tasa_nac_total, fecundidad, tasa_tendencia_total, tasa_envejecimiento_total) paro_barrio <- paro %>% filter(año==2017) %>% select(barrio, tasa, paro_16_39 , paro_40_64 , `paro_>65`) reci_barrio <- recibos %>% filter(año==2019) %>% select(-año, -recibos_eus)%>% reshape(idvar = "barrio",timevar = "recibos_cast", direction = "wide") renta_barrio <- renta %>% filter(año==2017)%>% select(barrio, renta, renta_18_39, renta_40_64, renta_65) tasa_barrio <- tasas %>% filter(año==2019) %>% select(-año, -tasa_eus)%>% rename(tasa = tasa_cast)%>% reshape(idvar = "barrio",timevar = "tasa", direction = "wide") vehi_barrio <- vehiculos %>% mutate(Tasa_Moto_x100 = format(round(indic_motorizacion/1000, digits = 2), nsmall = 2)) %>% select(-indic_motorizacion) ``` ```{r} vehi_barrio$Tasa_Moto_x100 <- as.numeric(vehi_barrio$Tasa_Moto_x100) ``` ```{r} ab <- merge(demo_barrio, estu_barrio, by = "barrio", all.x = TRUE) abc <- merge (ab, extr_barrio, by = 'barrio', all.x = TRUE) abcd <- merge (abc, habitantes, by = 'barrio', all.x = TRUE) ``` ```{r} abcde <- merge (abcd, indi_barrio, by = 'barrio', all.x = TRUE) abcdef <- merge (abcde, paro_barrio, by = 'barrio', all.x = TRUE) abcdefg <- merge (abcdef, reci_barrio, by = 'barrio', all.x = TRUE) abcdefgh <- merge (abcdefg, renta_barrio, by = 'barrio', all.x = TRUE) abcdefghi <- merge (abcdefgh, tasa_barrio, by = 'barrio', all.x = TRUE) abcdefghij <- merge (abcdefghi, vehi_barrio, by = 'barrio', all.x = TRUE) total <- abcdefghij ``` ```{r} # Convert na to 0 total[is.na(total)] <- 0 # ``` ```{r} total <- select(total, -'habitantes.y') ``` ```{r} colnames(total)= c('BARRIO', 'POBLACION', 'MUJERES', 'HOMBRES', 'ED.SECUNDARIA', 'SIN_ESTUDIOS_PREES_SECUND', 'PROFESIONALES', 'UNIVERSITARIOS', 'EXTRANJEROS', 'TASA_NACIMIENTOS', 'TASA_FECUNDIDAD', 'TASA_TENDENCIA', 'TASA_ENVEJECIMIENTO', 'TASA_PARO', 'PARO<39', 'PARO39-64', 'PARO>65', 'IBI', 'IAE', 'SANCION_URBA', 'OBLIGA_URBANIS', 'RENTA_FAMILIA', 'RENTA>39', 'RENTA40-64', 'RENTA>65', 'AGUA', 'LICENCIA_CONST', 'BASURA', 'VADO', 'MESAS/SILLAS', 'VALLAS', 'OCUPA_DOM','APERTURA', 'N_VEHICULOS', 'N_TURISMOS', 'N_MOTOS', 'MOTORIZ_X_1000') ``` ```{r} for(col in names(total)[3:8]) { total[paste0(col, "_%_xBarrio")] = ((total[col] / total$POBLACION)*100) } for(col in names(total)[3:8]) { total[paste0(col, "_%_s/total")] = (total[col] / sum(total[col])*100) } total$VEHICxPERSONA = total$N_VEHICULOS/total$POBLACION for(col in names(total)[18:21]) { total[paste0("ingreso", col, "_X_PERS")] = ((total[col] / total$POBLACION)*100) } for(col in names(total)[26:33]) { total[paste0("ingreso", col, "_X_PERS")] = ((total[col] / total$POBLACION)*100) } total$'EXTR_%' = (total$EXTRANJEROS/total$POBLACION)*100 for(col in names(total)[47:48]) { total[paste0(col, "_%_s/total")] = (total[col] / sum(total[col])*100) } total$AGUA_PERSONA = (total$AGUA/total$POBLACION)*100 total$BASURA_PERSONA = (total$BASURA/total$POBLACION)*100 for(col in names(total)[62:63]) { total[paste0(col, "_%_s/total")] = (total[col] / sum(total[col])*100) } total$'COCHES/MOTOS' <- (total$N_MOTOS/total$N_TURISMOS) total$'VADO/VEHICULOS' <- (total$VADO/total$N_VEHICULOS) ``` ```{r} # Convert na to 0 total[is.na(total)] <- 0 # ``` ```{r} Percentile_00 = min(total$RENTA_FAMILIA) Percentile_33 = quantile(total$RENTA_FAMILIA, 0.33333) Percentile_67 = quantile(total$RENTA_FAMILIA, 0.66667) Percentile_100 = max(total$RENTA_FAMILIA) RB = rbind(Percentile_00, Percentile_33, Percentile_67, Percentile_100) dimnames(RB)[[2]] = "Value" RB total$SITUACION_RENTA[total$RENTA_FAMILIA >= Percentile_00 & total$RENTA_FAMILIA < Percentile_33] = "RENTA BAJA" total$SITUACION_RENTA[total$RENTA_FAMILIA >= Percentile_33 & total$RENTA_FAMILIA < Percentile_67] = "RENTA MEDIA" total$SITUACION_RENTA[total$RENTA_FAMILIA >= Percentile_67 & total$RENTA_FAMILIA <= Percentile_100] = "RENTA ALTA" ``` ```{r} Percentile_00 = min(total$VEHICxPERSONA) Percentile_33 = quantile(total$VEHICxPERSONA, 0.33333) Percentile_67 = quantile(total$VEHICxPERSONA, 0.66667) Percentile_100 = max(total$VEHICxPERSONA) RB = rbind(Percentile_00, Percentile_33, Percentile_67, Percentile_100) dimnames(RB)[[2]] = "Value" RB total$MOTORIZACION[total$VEHICxPERSONA >= Percentile_00 & total$VEHICxPERSONA < Percentile_33] = "POCO MOTORIZADO" total$MOTORIZACION[total$VEHICxPERSONA >= Percentile_33 & total$VEHICxPERSONA < Percentile_67] = "MOTORIZADO" total$MOTORIZACION[total$VEHICxPERSONA >= Percentile_67 & total$VEHICxPERSONA <= Percentile_100] = "MUY MOTORIZADO" ``` ```{r} total <- total %>% select(BARRIO,SITUACION_RENTA,MOTORIZACION, everything()) ``` ```{r} summary(total) ``` ```{r} glimpse(total) ``` ```{r} skim(total) ``` ```{r} funModeling::df_status(total) ``` ```{r} write.csv(total,"total.csv") write.csv(total,"shinyapp/www/total.csv") ``` ```{r} total %>% select(-HABI_TOTAL)%>% mutate('%_POBL_X_BARRIO' = format(round((POBLACION/sum(POBLACION))*100, digits = 3), nsmall =3), '%_EXTRANJEROS'= format(round((EXTRANEJEROS/sum(EXTRANEJEROS))*100, digits = 3), nsmall =3))%>% ``` ```{r} total_genero_estudios <- total %>% gather('GENERO', 'POBLACIÓN', 'MUJERES':'HOMBRES')%>% gather('ESTUDIOS', 'ESTUDIANTES', 'ED.SECUNDARIA':'UNIVERSITARIOS')%>% arrange('GENERO') ``` ```{r} summary(total) ``` ```{r} glimpse(total) ``` ```{r} skim(total) ``` ```{r} funModeling::total_status(total) ``` ```{r} df$Operator <- as.factor(df$Operator) df$Failure <- as.factor(df$Failure) ``` ```{r} df <- df %>% mutate(Measure2 = as.factor(Measure2), Measure3 = as.factor(Measure3))%>% filter(Temperature > 50) ``` ```{r} boxplot(df) ``` ```{r} df %>% dplyr::select(c(-Operator,-Measure2,-Measure3,-Failure)) %>% keep(is.numeric) %>% gather() %>% ggplot(aes(value)) + facet_wrap(~ key, scales = "free") + geom_histogram() ``` ```{r} df %>% select_if(is.integer) %>% cor() %>% round(digits = 2) ``` ```{r} df %>% select_if(is.integer) %>% gather() %>% ggplot(aes(value)) + geom_density()+ facet_wrap(~key,scales='free')+ theme(axis.text = element_text(size = 6)) ``` <file_sep>library(rvest) library(ggplot2) library(dplyr) library(RColorBrewer) # Página de Wiki url1 <- "https://es.wikipedia.org/wiki/Anexo:Estad%C3%ADsticas_de_la_Copa_América" tmp1 <- read_html(url1) tmp1 <- html_nodes(tmp1, "table") length(tmp1) # Hay en total 27 tablas sapply(tmp1, function(x) dim(html_table(x, fill = TRUE))) Copa <- html_table(tmp1[[7]], fill = TRUE) url2 <- "https://es.wikipedia.org/wiki/Selección_de_fútbol_de_Colombia" tmp2 <- read_html(url2) tmp2 <- html_nodes(tmp2, "table") length(tmp2) # Hay en total 21 tablas sapply(tmp2, function(x) dim(html_table(x, fill = TRUE))) Colombia <- html_table(tmp2[[7]], fill = TRUE) Colombia <- Colombia[-16, c(-1,-7)] Colombia$Partidos <- as.numeric(Colombia$Partidos) Colombia <- Colombia %>% arrange(desc(Partidos)) colores <- colorRampPalette(brewer.pal(12, "Paired"))(15) ggplot(Colombia, aes(x = reorder(Nombre,(-Partidos)), y = Partidos, fill = Nombre)) + geom_bar(stat = "identity", position = "stack", width = 1) + scale_fill_manual(values = colores) + theme_void() + theme(legend.position = "none") + coord_polar(direction = -1) + geom_bar(aes(y = I(8)), stat = "identity", width = 1, fill = "white") + # Agregar dos aros blancos transparentes en la mitad de la gráfica geom_bar(aes(y = I(20)), stat="identity", width = 1, fill = "white", alpha = 0.2) + geom_bar(aes(y = I(40)), stat="identity", width = 1, fill = "white", alpha = 0.1) + # Agregar el número de los partidos jugados geom_text(aes(label = Partidos, y = Partidos * 0.8), data = Colombia, color = "white", fontface = "bold", vjust = 1, family = "Helvetica", size = seq(4, 2, length.out=15)) + # Agregar nombre de los jugadores geom_text(aes(label = Nombre, y = Partidos * 1.3), # color = "blue", vjust = seq(1.3, 0.2, length.out = 15), # hjust = c(0.4, 0.2, 0.1, 0.15, 0.1), fontface = "bold", family = "Helvetica", size = c(7, seq(4, 2, length.out = 14))) + # Colocar títulos, subtítulos, etc. labs(title = "Jugadores con más participaciones", caption = "Datos tomados de: https://es.wikipedia.org/wiki/Selección_de_fútbol_de_Colombia") + # Apariencia de títulos, subtítulos, etc. theme(plot.title=element_text(size=26, hjust=0.5, face="bold", vjust=-100), plot.caption = element_text(size=8, hjust=0.5, face="bold", color='grey', vjust=14))<file_sep>--- title: "Final Report Exercise" author: "<NAME>" date: "`r format(Sys.time(), '%d %B, %Y')`" output: html_document: highlight: default code_folding: show # mostrar boton para mostrar o no el código number_sections: no theme: cosmo fig_caption: yes df_print: paged toc: yes toc_float: true # tabla contenidos flotante toc_depth: 3 pdf_document: latex_engine: xelatex highlight: zenburn toc: yes toc_depth: 3 number_sections: no fig_caption: yes df_print: kable --- \pagebreak ```{r setup, include=FALSE} #####DO NOT MODIFY THIS CODE knitr::opts_chunk$set(echo = TRUE) library(tidyverse) library(knitr) #####DO NOT MODIFY THIS CODE - This will import the survey data we have been working with in this course. dat <- drop_na(read.csv(url("https://www.dropbox.com/s/uhfstf6g36ghxwp/cces_sample_coursera.csv?raw=1"))) ``` ### Bookcode id_number: respondent ID number region: In which census region do you live? 1 Northwest 2 Midwest 3 South 4 West gender: Are you... 1 Male 2 Female educ: What is the highest level of education you have completed? 1 No high school 2 High school graduate 3 Some college 4 2-year 5 4-year 6 Post-grad edloan: Are you currently responisble for paying off a student loan? 1 Yes 2 No race: What racial or ethnic group best describes you? 1 White 2 Black 3 Hispanic 4 Asian 5 Native American 6 Mixed 7 Other 8 Middle Eastern hispanic: Are you of Spanish, Latino, or Hispanic origin or descent? 1 Yes 2 No employ: Which of the following best describes your current employment status? 1 Full-time 2 Part-time 3 Temporarily laid off 4 Unemployed 5 Retired 6 Permanently disabled 7 Homemaker 8 Student 9 Other marstat: What is you marital status? 1 Married 2 Separated 3 Divorced 4 Widowed 5 Never married 6 Domestic/civil partnership pid7: Generally speaking, do you think of yourself as a...? 1 Strong Democrat 2 Not very strong Democrat 3 Lean Democrat 4 Independent 5 Lean Republican 6 Not very strong Republican 7 Strong Republican ideo5: In general, how would you describe your own political viewpoint? 1 Very liberal 2 Liberal 3 Moderate 4 Conservative 5 Very conservative pew_religimp: How important is religion in yuor life? 1 Very important 2 Somewhat important 3 Not too important 4 Not at all important newsint: Some people seem to follow what's going on in government and public affairs most of the time, whether there's an election going on or not. Others aren't that interested. Would you say you follow what's going on in government and public affairs... 1 Most of the time 2 Some of the time 3 Only now and then 4 Hardly at all faminc_new: Thinking back over the last year, what was your family’s annual income? 1 Less than $10,000 2 $10,000 - $19,999 3 $20,000 - $29,999 4 $30,000 - $39,999 5 $40,000 - $49,999 6 $50,000 - $59,999 7 $60,000 - $69,999 8 $70,000 - $79,999 9 $80,000 - $99,999 10 $100,000 - $119,999 11 $120,000 - $149,999 12 $150,000 - $199,999 13 $200,000 - $249,999 14 $250,000 - $349,999 15 $350,000 - $499,999 16 $500,000 or more union: Are you a member of a labor union? 1 Yes, I am currently a member of a labor union 2 I formerly was a member of a labor union 3 I am not now, nor have I been, a member of a labor union investor: Do you personally (or jointly with a spouse), have any money invested in the stock market right now, either in an individual stock or in a mutual fund? 1 Yes 2 No CC18_308a Job approval – President Trump Do you approve or disapprove of the way each is doing their job... 1 Strongly approve 2 Somewhat approve 3 Somewhat disapprove 4 Strongly disapprove CC18_310a Party Recall + Name Recognition - Governor Please indicate whether you’ve heard of this person and if so which party he or she is affiliated with... 1 Never heard of person 2 Republican 3 Democrat 4 Other Party / Independent 5 Not sure CC18_310b Party Recall + Name Recognition - Senator 1 Please indicate whether you’ve heard of this person and if so which party he or she is affiliated with... 1 Never heard of person 2 Republican 3 Democrat 4 Other Party / Independent 5 Not sure CC18_310c Party Recall + Name Recognition - Senator 2 Please indicate whether you’ve heard of this person and if so which party he or she is affiliated with... 1 Never heard of person 2 Republican 3 Democrat 4 Other Party / Independent 5 Not sure CC18_310d Party Recall + Name Recognition - Representative Please indicate whether you’ve heard of this person and if so which party he or she is affiliated with... 1 Never heard of person 2 Republican 3 Democrat 4 Other Party / Independent 5 Not sure CC18_325a Taxes – Cut the Corporate Income Tax rate from 39 percent to 21 percent. Congress considered many changes in tax law over the past two years. Do you support or oppose each of the following? 1 Support 2 Oppose CC18_325b Taxes – Reduce the mortgage interest deduction. Allow people to deduct the interest on no more than $500,000 of mortgage debt. The previous limit was $1 million. Congress considered many changes in tax law over the past two years. Do you support or oppose each of the following? 1 Support 2 Oppose CC18_325c Taxes – Limit the amount of state and local taxes that can be deducted to $10,000 (previously there was no limit). Congress considered many changes in tax law over the past two years. Do you support or oppose each of the following? 1 Support 2 Oppose CC18_325d Taxes – Increase the standard deduction on federal income taxes from $12,000 to to $25,000 Congress considered many changes in tax law over the past two years. Do you support or oppose each of the following? 1 Support 2 Oppose \pagebreak --- # Problem 1 Create a vector of five numbers of your choice between 0 and 10, save that vector to an object, and use the sum() function to calculate the sum of the numbers. Crea un vector de cinco números de tu elección entre 0 y 10, guarda ese vector en un objeto y utiliza la función sum() para calcular la suma de los números. ```{r,problem1} #Put your code here, then delete this commented line before submission. Don't modify the setup code for this chunk - you want your code and output to both display. vector <- sample.int(10,5) vector sum.vector <- sum(vector) sum.vector ``` \pagebreak # Problem 2 Create a data frame that includes two columns. One column must have the numbers 1 through 5, and the other column must have the numbers 6 through 10. The first column must be named "alpha" and the second column must be named "beta". Name the object "my_dat". Display the data. Put your code and solution here: ```{r,problem2} #Put your code here, then delete this commented line before submission. Don't modify the setup code for this chunk - you want your code and output to both display. alfa <- c(1,2,3,4,5) beta <- c(6,7,8,9,10) my_data <- cbind(alfa,beta) my_data <- as.data.frame(my_data) my_data ``` \pagebreak # Problem 3 Using the data frame created in Problem 2, use the summary() command a create a five-number summary for the column named "beta". Put your code and solution here: ```{r,problem3} #Put your code here, then delete this commented line before submission. Don't modify the setup code for this chunk - you want your code and output to both display. summary(my_data$beta) ``` \pagebreak # Problem 4 There is code for importing the example survey data that will run automatically in the setup chunk for this report (Line 13). Using that data, make a boxplot of the Family Income column using the Base R function (not a figure drawn using qplot). Include your name in the title for the plot. Your name should be in the title. Relabel that x-axis as "Family Income". Hint: consult the codebook to identify the correct column name for the family income question. Put your code and solution here: ```{r,problem4} #Put your code here, then delete this commented line before submission. Don't modify the setup code for this chunk - you want your code and output to both display. data <- read.csv("https://d3c33hcgiwev3.cloudfront.net/D1LYDGZLRAmS2AxmSxQJHw_244a6af25c32479990d299bf82de1a67_cces_sample_coursera.csv?Expires=1625702400&Signature=cbdUKPrTcmaFj3-k55bWKm7mOiT3PSIr0jI46NGJShiAjzd-uMtUCtAbg5NHFDYsIi-VbLGF7jeHH3ADeCyLgckXt<KEY>aq<KEY>&Key-Pair-Id=<KEY>") boxplot(data$faminc_new, main="Family Income") ``` \pagebreak # Problem 5 Using the survey data, filter to subset the survey data so you only have male survey respondents who live in the northwest or midwest of the United States, are married, and identify as being interested in the news most of the time. Use the str() function to provide information about the resulting dataset. Put your code and solution here: ```{r problem5,include=TRUE,echo=TRUE} #Put your code here, then delete this commented line before submission. Don't modify the setup code for this chunk - you want your code and output to both display. data <- read.csv("https://d3c33hcgiwev3.cloudfront.net/D1LYDGZLRAmS2AxmSxQJHw_244a6af25c32479990d299bf82de1a67_cces_sample_coursera.csv?Expires=1625702400&<KEY>&Key-Pair-Id=<KEY>") str.data <- data%>%filter(gender==1 & marstat==1 & newsint==1)%>%filter(region==1 | region==2) str(str.data) ``` \pagebreak # Problem 6 Filter the data the same as in Problem 5. Use a R function to create a frequency table for the responses for the question asking whether these survey respondents are invested in the stock market. Put your code and solution here: ```{r problem6,include=TRUE,echo=TRUE} #Put your code here, then delete this commented line before submission. Don't modify the setup code for this chunk - you want your code and output to both display. table(str.data$investor) ``` \pagebreak # Problem 7 Going back to using all rows in the dataset, create a new column in the data using mutate that is equal to either 0, 1, or 2, to reflect whether the respondent supports increasing the standard deduction from 12,000 to 25,000, supports cutting the corporate income tax rate from 39 to 21 percent, or both. Name the column "tax_scale". Hint: you'll need to use recode() as well. Display the first twenty elements of the new column you create. Put your code and solution here: ```{r problem7,include=TRUE,echo=TRUE} #Put your code here, then delete this commented line before submission. Don't modify the setup code for this chunk - you want your code and output to both display. problem_6 <- data %>% mutate(tax_scale= ifelse(CC18_325a==1,0, ifelse(CC18_325d==1,1,2))) problem_6 %>% head(20)%>% select(tax_scale) ``` \pagebreak # Problem 8 Use a frequency table command to show how many 0s, 1s, and 2s are in the column you created in Problem 7. Put your code and solution here: ```{r problem8,include=TRUE,echo=TRUE} #Put your code here, then delete this commented line before submission. Don't modify the setup code for this chunk - you want your code and output to both display. table(problem_6$tax_scale) ``` \pagebreak # Problem 9 Again using all rows in the original dataset, use summarise and group_by to calculate the average (mean) job of approval for President Trump in each of the four regions listed in the "region" column. Put your code and solution here: ```{r problem9} #Put your code here, then delete this commented line before submission. Don't modify the setup code for this chunk - you want your code and output to both display. data %>% filter(CC18_308a==1 | CC18_308a==2)%>% group_by(region) ``` \pagebreak # Problem 10 Again start with all rows in the original dataset, use summarise() to create a summary table for survey respondents who are not investors and who have an annual family income of between $40,000 and $119,999 per year. The table should have the mean, median and standard deviations for the importance of religion column. Put your code and solution here: ```{r problem10} #Put your code here, then delete this commented line before submission. Don't modify the setup code for this chunk - you want your code and output to both display. data %>% filter(faminc_new>4 & faminc_new<11)%>% summarise(mean_in=mean(pew_religimp), median_in = median(pew_religimp), std_dev=sd(pew_religimp)) ``` \pagebreak # Problem 11 Use kable() and the the summarise() function to create a table with one row and three columns that provides the mean, median, and standard deviation for the column named faminc_new in the survey data. Put your code and solution here: ```{r problem11} #Put your code here, then delete this commented line before submission. Don't modify the setup code for this chunk - you want your code and output to both display. data %>% summarise(mean_in=mean(faminc_new), median_in = median(faminc_new), std_dev=sd(faminc_new))%>% kable() ``` \pagebreak # Problem 12 With the survey data, use qplot() to make a histogram of the column named pid7. Change the x-axis label to "Seven Point Party ID" and the y-axis label to "Count". Note: you can ignore the "stat_bin()" message that R generates when you draw this. The setup for the code chunk will suppress the message. Put your code and solution here: ```{r problem12,message=FALSE} #Put your code here, then delete this commented line before submission. Don't modify the setup code for this chunk - you want your code and output to both display. ggplot(data=data, aes(pid7)) + geom_histogram()+ labs(x="Seven Point Party ID", y = "Count") ``` <file_sep># r_files This repository contains some projects en R
171196db003cf2b6782af88aa18cac2c571e4441
[ "Markdown", "R", "RMarkdown" ]
4
RMarkdown
zumaia/r_files
0c876a65c5ebbf44830101c60fdde56cc598de5f
c76e746e782e721d62514eb9172b19829a89444b
refs/heads/master
<repo_name>Codeko/technical-support<file_sep>/technical-support.php <?php /* Plugin Name: Technical Support Plugin URI: http://kovshenin.com/wordpress/plugins/technical-support/ Description: Enhance your clients' websites with a bug reporting tool. Author: <NAME> Version: 0.1.1 Author URI: http://kovshenin.com/ */ /* License Technical Support for WordPress Copyright (C) 2010 <NAME> (<EMAIL>) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ add_action ('init', 'ts_localize_init'); function ts_localize_init () { load_plugin_textdomain ('ts', '/wp-content/plugins/technical-support/languages'); } class TechnicalSupport { var $settings = array(); var $defaultsettings = array(); var $notices = array(); function __construct() { $this->defaultsettings = array( "provider_name" => "", "provider_email" => "", "provider_logo" => "", "provider_url" => "", "topics" => __('Theme Layout', 'ts') . "\n" . __('Admin Panel', 'ts') ."\n" . __('Plugin Issue', 'ts') . "\n" . __('Core Functionality', 'ts') . "\n" . __('Core Upgrade Request', 'ts') . "\n" . __('Plugin Upgrade Request', 'ts') . "\n" . __('Theme Modification Request', 'ts') . "\n" . __('General Support', 'ts') . "\n" . __('Other (please state below)', 'ts'), "subject_format" => __('New Support Ticket:', 'ts') . '[title]' , "message_format" => __('Attention! A support ticket has been submitted at', 'ts') . '[url].' . __(' Details follow:', 'ts') . "\n\n" . __('Name:', 'ts') . " [firstname] [lastname] ([email])\n" . __('Related to:', 'ts') . " [topic]\n\n[title]\n\n[message]\n\n~ " . __('Technical Support for WordPress (http://kovshenin.com/1992)', 'ts') ); // Setup the settings by using the default as a base and then adding in any changed values // This allows settings arrays from old versions to be used even though they are missing values $usersettings = (array) get_option("technical_support"); $this->settings = $this->defaultsettings; if ( $usersettings !== $this->defaultsettings ) { foreach ( (array) $usersettings as $key1 => $value1 ) { if ( is_array($value1) ) { foreach ( $value1 as $key2 => $value2 ) { $this->settings[$key1][$key2] = $value2; } } else { $this->settings[$key1] = $value1; } } } // Register general hooks add_action("admin_notices", array(&$this, "admin_notices")); add_action("admin_menu", array(&$this, "admin_menu")); // Let's see if there's an HTTP POST request if (isset($_POST["technical-support-submit"])) $this->process_post(); // If there are not settings shoot an admin notice if (empty($this->settings["provider_name"]) || empty($this->settings["provider_email"])) $this->notices[] = __('The <strong>Technical Support</strong> plugin requires configuration.', 'ts') .' '. __('Please proceed to the', 'ts') . ' ' . '<a href="options-general.php?page=technical-support/technical-support.php">' . __('plugin settings page', 'ts') . '</a>.'; // If everything's fine, load the working hooks else { // Register working hooks add_action('wp_dashboard_setup', array(&$this, 'dashboard_setup')); add_action('admin_head', array(&$this, 'admin_js')); add_action('wp_ajax_technical_support_submit', array(&$this, 'submit')); } } // Javascript for the dashboard widget function admin_js() { ?> <script type="text/javascript"> jQuery(document).ready(function($) { jQuery("#technical-support-form").submit(function() { // Format the request var data = { action: 'technical_support_submit', formdata: jQuery(this).serialize() }; // Let's disable the form for a while and show the loading image jQuery(':input','#technical-support-form').attr("disabled", "disabled"); jQuery(".technical-support-loader").show(); // Post the request and handle the response jQuery.post(ajaxurl, data, function(response) { jQuery(".technical-support-loader").hide(); jQuery(':input','#technical-support-form').not(':button, :submit, :reset, :hidden').val('').removeAttr('checked').removeAttr('selected'); jQuery(':input','#technical-support-form').removeAttr("disabled"); alert(response); }); // Don't leave the page return false; }); }); </script> <?php } // AJAX submit response function function submit() { // Organize form data into an array $form_data = array(); $fields = explode('&', $_POST["formdata"]); foreach ($fields as $field) { $key_value = explode('=', $field); $key = urldecode($key_value[0]); $value = urldecode($key_value[1]); $form_data[$key] = $value; } // If we've got an empty title and en empty message.. Whaa? if (strlen($form_data["title"]) < 1 && strlen($form_data["content"]) < 1) die(__('Please don\'t submit empty reports!', 'ts')); // Let's use these global $current_user; get_currentuserinfo(); // Format the headers $headers = 'From: ' . get_bloginfo('title') . ' <ticket@' . $_SERVER["SERVER_NAME"] . '>' . "\r\n\\"; $headers .= 'Reply-To:' . $current_user->user_firstname . ' ' . $current_user->user_lastname . ' <' . $current_user->user_email . '>' . "\r\n"; // Shortcode arrays for str_replace $shortcodes = array( "[title]", "[message]", "[topic]", "[url]", "[firstname]", "[lastname]", "[email]", "[useragent]", ); $shortcodes_replace = array( $form_data["title"], $form_data["content"], $form_data["relatedto"], get_bloginfo('home'), $current_user->user_firstname, $current_user->user_lastname, $current_user->user_email, $_SERVER['HTTP_USER_AGENT'], ); // Format the subject and message $subject = str_replace($shortcodes, $shortcodes_replace, $this->settings["subject_format"]); $message = str_replace($shortcodes, $shortcodes_replace, $this->settings["message_format"]); // Send the mail and echo the response if (wp_mail($this->settings["provider_email"], $subject, $message, $headers)) _e('Your e-mail has been sent!', 'ts'); else _e('E-mail could not be sent, please contact support directly:', 'ts') . $this->settings["provider_email"]; die(); } // Setup the dashboard widget function dashboard_setup() { wp_add_dashboard_widget("technical-support-dashboard", __('Technical Support', 'ts') , array(&$this, "technical_support"), $control_callback = null); } // This is how the dashboard widget looks and feels function technical_support() { global $current_user; get_currentuserinfo(); ?> <p><?php _e('Please use this form to report encountered bugs, issues and other support requests directly to', 'ts');?> <strong><?php echo $this->settings["provider_name"]; ?></strong>. <?php _e('Note that a response e-mail will be sent to the address associated with your profile', 'ts');?> (<a href="mailto:<?php echo $current_user->user_email; ?>"><?php echo $current_user->user_email; ?></a>). <?php _e('In order to change that please visit your', 'ts');?> <a href="profile.php"><?php _e('profile page', 'ts');?></a>.</p> <style> #technical-support-form table { border-collapse: collapse; } #technical-support-form span.description { line-height: 16px; } #technical-support-form table td { padding-top: 10px; } .technical-support-left { vertical-align: top; padding-top: 14px !important; width: 130px; text-align: right; padding-right: 8px; } .technical-support-right { width: 90%; } .technical-support-right p { margin-top: 0; margin-bottom: 3px; } .technical-support-footer { text-align: right; } .technical-support-loader { display: none; margin-right: 8px; position: relative; top: 5px; } .rtlfix { text-align:left !important; } </style> <form id="technical-support-form"> <table> <tr> <td class="technical-support-left"><label for="title"><?php _e('Title', 'ts');?></label></td> <td class="technical-support-right"> <p><input type="text" value="" autocomplete="off" tabindex="1" id="title" name="title" style="width:99%"></p> <span class="description"><?php _e('Give your issue a short name', 'ts');?></span> </td> </tr> <tr> <td class="technical-support-left"><label for="relatedto"><?php _e('Related to', 'ts');?></label></td> <td class="technical-support-right"> <p> <select name="relatedto" id="relatedto"> <?php $topics = explode("\n", $this->settings["topics"]); foreach($topics as $topic) echo "<option>" . $topic . "</option>"; ?> </select> </p> <span class="description"><?php _e('Pick one that suits your issue.', 'ts');?></span> </td> </tr> <tr> <td class="technical-support-left"><label for="content"><?php _e('Description', 'ts');?></label></td> <td class="technical-support-right"> <p><textarea tabindex="2" class="mceEditor" id="content" name="content" style="width:99%; height: 100px;"></textarea></p> <span class="description"><?php _e('Please describe your issue as detailed as possible. If it\'s plugin related, please provide the full name of the plugin as well.', 'ts');?></span> </td> </tr> <tr> <td class="technical-support-left"></td> <td class="technical-support-right"> <p class="submit"> <input type="submit" value="<?php _e('Send Report', 'ts');?>" class="button-primary" tabindex="5" accesskey="p" id="publish" name="publish"> <span class="description"><img class="technical-support-loader" src="<?php echo plugins_url();?>/technical-support/ajax-loader.gif" alt="Loading" /><?php _e('This report will be sent by e-mail to', 'ts');?> <a href="mailto:<?php echo $this->settings["provider_email"]; ?>"><?php echo $this->settings["provider_email"]; ?></a></span> </p> </td> </tr> </table> </form> <p class="technical-support-footer <?php if (get_bloginfo('text_direction') == "rtl") echo 'rtlfix';?>"><?php _e('Support provided by','ts');?> <a href="<?php echo $this->settings["provider_url"]; ?>"><img src="<?php echo $this->settings["provider_logo"]; ?>" alt="<?php echo $this->settings["provider_name"]; ?>" /></a></p> <?php } // Handle and output admin notices function admin_notices() { $this->notices = array_unique($this->notices); foreach($this->notices as $key => $value) echo "<div id='technical-support-info' class='updated fade'><p>" . $value . "</p></div>"; } // Register an admin menu entry function admin_menu() { add_options_page(__('Technical Support', 'ts'), __('Technical Support', 'ts'), 8, __FILE__, array(&$this, 'options')); } // Use this to save the settings array function save_settings() { update_option("technical_support", $this->settings); return true; } // Process the HTTP POST data if there's any function process_post() { if (isset($_POST["technical-support-submit"])) { $this->settings["provider_name"] = $_POST["provider_name"]; $this->settings["provider_email"] = $_POST["provider_email"]; $this->settings["provider_logo"] = $_POST["provider_logo"]; $this->settings["provider_url"] = $_POST["provider_url"]; $this->settings["topics"] = $_POST["topics"]; $this->settings["subject_format"] = $_POST["subject_format"]; $this->settings["message_format"] = $_POST["message_format"]; $this->save_settings(); $this->notices[] = __('Your <strong>Technical Support</strong> settings have been saved.', 'ts'); } } // Here's the Technical Support settings screen function options() { global $current_user; $provider_name = $this->settings["provider_name"]; $provider_email = $this->settings["provider_email"]; $provider_logo = $this->settings["provider_logo"]; $provider_url = $this->settings["provider_url"]; $topics = $this->settings["topics"]; $subject_format = $this->settings["subject_format"]; $message_format = $this->settings["message_format"]; ?> <div class="wrap"> <h2><?php _e('Technical Support Settings', 'ts');?></h2> <h3><?php _e('Support Provider', 'ts');?></h3> <p><?php _e('Make sure you test e-mail sending after setup. Also note that if WordPress cannot send e-mails, then neither can this plugin, so make sure WordPress e-mail settings are correctly configured. Also note that the e-mails will be sent from', 'ts');?> <a href="mailto:<?php echo $current_user->user_email; ?>"><?php echo $current_user->user_email; ?></a> <?php _e('so make sure you add it to your contacts. If you\'re encountering problems receiving e-mails, try setting up', 'ts');?> <a href="http://en.wikipedia.org/wiki/Sender_Policy_Framework">SPF</a> <?php _e('for this domain', 'ts');?>.</p> <form method="post"> <input type="hidden" value="1" name="technical-support-submit"/> <table class="form-table" style="margin-bottom:10px;"> <tbody> <tr valign="top"> <th scope="row"><label for="provider_name"><?php _e('Provider Name', 'ts');?></label></th> <td> <input class="regular-text" type="text" value="<?php echo $provider_name; ?>" id="provider_name" name="provider_name" /><br /> <span class="description"><?php _e('Use your company name, for instance: Microsoft', 'ts');?></span> </td> </tr> <tr valign="top"> <th scope="row"><label for="provider_email"><?php _e('Provider E-mail', 'ts');?></label></th> <td> <input class="regular-text" type="text" value="<?php echo $provider_email; ?>" id="provider_email" name="provider_email"/><br /> <span class="description"><?php _e('All reports will be sent to this address:', 'ts');?> <EMAIL></span> </td> </tr> <tr valign="top"> <th scope="row"><label for="provider_logo"><?php _e('Provider Logo', 'ts');?></label></th> <td> <input class="regular-text" type="text" value="<?php echo $provider_logo; ?>" id="provider_logo" name="provider_logo"/><br /> <span class="description"><?php _e('The URL of the provider logo. Recommended size is 74x22 pixels', 'ts');?></span> </td> </tr> <tr valign="top"> <th scope="row"><label for="provider_url"><?php _e('Provider URL', 'ts');?></label></th> <td> <input class="regular-text" type="text" value="<?php echo $provider_url; ?>" id="provider_url" name="provider_url"/><br /> <span class="description"><?php _e('The URL of the provider homepage, please start with http', 'ts');?></span> </td> </tr> </tbody> </table> <h3><?php _e('Topics', 'ts');?> &amp; <?php _e('E-mail Formatting', 'ts');?></h3> <p><?php _e('Customize your technical support widget: topics and email formatting.', 'ts');?></p> <table class="form-table"> <tbody> <tr valign="top"> <th scope="row"><label for="topics"><?php _e('Topics', 'ts');?></label></th> <td> <textarea class="regular-text" id="topics" name="topics" style="width: 25em; height:15em;"><?php echo htmlspecialchars($topics); ?></textarea><br /> <span class="description"><?php _e('Provide a return separated list of what topics you provide support on', 'ts');?></span> </td> </tr> <tr valign="top"> <th scope="row"><label for="subject_format"><?php _e('E-mail Subject', 'ts');?></label></th> <td> <input class="regular-text" type="text" value="<?php echo htmlspecialchars($subject_format); ?>" id="subject_format" name="subject_format"/><br /> <span class="description"><?php _e('Customize the subject format, use the', 'ts'); ' [title] ' . _e('short-tag, for instance: New Ticket', 'ts');?> - [title] </span> </td> </tr> <tr valign="top"> <th scope="row"><label for="message_format"><?php _e('Message Format', 'ts');?></label></th> <td> <textarea class="regular-text" id="message_format" name="message_format" style="width: 25em; height: 15em;"><?php echo htmlspecialchars($message_format); ?></textarea><br /> <span class="description"><?php _e('This is what you will receive by e-mail. Use the following tags:', 'ts');?> [title], [message], [topic], [url], [firstname], [lastname], [email]</span> </td> </tr> </tbody> </table> <p class="submit"> <input type="submit" value="<?php _e('Save Changes', 'ts');?>" class="button-primary" name="Submit"/> </p> </form> </div> <?php } } // Initiate the plugin add_action("init", "TechnicalSupport"); function TechnicalSupport() { global $TechnicalSupport; $TechnicalSupport = new TechnicalSupport(); } ?>
3cb79a9dee63a6e53822405a04e6ee9efadafa3b
[ "PHP" ]
1
PHP
Codeko/technical-support
fac70472f16c1194b82adf2764f7f1f2109fc32c
1f2c5d2c7cb5b3311d73e3498564d0571f717333
refs/heads/master
<repo_name>bloggertom/StarlingSimulation<file_sep>/src/SimulatorInterface.java public interface SimulatorInterface { public void runSimulation(); } <file_sep>/src/v2/Vector.java package v2; public class Vector { private double x; private double y; private double z; public Vector(){ } public Vector(double x, double y, double z){ this.x = x; this.y = y; this.z = z; } //Setting information about this starling public void setX(double x){ this.x = x; } public void setY(double y){ this.y = y; } public void setZ(double z){ this.z = z; } public double getX(){ return x; } public double getY(){ return y; } public double getZ(){ return z; } public double getMagnitude(){ return Vector.vectorMagnitude(this); } public static Vector divideVectorsByScaler(Vector aVector, double d){ Vector vector = new Vector(); vector.setX(aVector.getX()/d); vector.setY(aVector.getY()/d); vector.setZ(aVector.getZ()/d); return vector; } public static Vector multiplyByScaler(Vector aVector, double speedCap){ Vector vector = new Vector(); vector.setX(aVector.getX()*speedCap); vector.setY(aVector.getY()*speedCap); vector.setZ(aVector.getZ()*speedCap); return vector; } public static Vector addVectors(Vector vector1, Vector vector2){ Vector vector = new Vector(); vector.setX(vector1.getX() + vector2.getX()); vector.setY(vector1.getY() + vector2.getY()); vector.setZ(vector1.getZ() + vector2.getZ()); return vector; } public static Vector subtractVectors(Vector vector1, Vector vector2){ Vector vector = new Vector(); vector.setX(vector1.getX() - vector2.getX()); vector.setY(vector1.getY() - vector2.getY()); vector.setZ(vector1.getZ() - vector2.getZ()); return vector; } public static double vectorMagnitude(Vector v){ double d = Math.sqrt((v.getX() * v.getX())+(v.getY()*v.getY())+(v.getZ()*v.getZ())); return d; } } <file_sep>/src/v2/MouseActionListener.java package v2; import java.awt.Toolkit; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; public class MouseActionListener implements MouseListener, MouseMotionListener{ private Model model = Model.getInstance(); private boolean entered = false; public MouseActionListener(){ } @Override public void mouseClicked(MouseEvent click) { } @Override public void mouseEntered(MouseEvent mouse) { entered = true; model.setMouseOnScreen(entered); } @Override public void mouseExited(MouseEvent mouse) { entered = false; model.setMouseOnScreen(entered); model.setMouseX((int) (Toolkit.getDefaultToolkit().getScreenSize().width * 0.75)); model.setMouseY((int)(Toolkit.getDefaultToolkit().getScreenSize().height * 0.25)); System.out.println("Mouse Exit"); } @Override public void mousePressed(MouseEvent click) { System.out.println("x="+click.getX()+", y="+click.getY()); } @Override public void mouseReleased(MouseEvent mouse) { } @Override public void mouseDragged(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseMoved(MouseEvent mouse) { if(entered){ model.setMouseX(mouse.getXOnScreen()); model.setMouseY(mouse.getYOnScreen()); } } } <file_sep>/src/v2/Boid.java package v2; import java.awt.image.BufferedImage; public class Boid { Vector possition; Vector velocity; double heading; public Boid(){ possition = new Vector(); velocity = new Vector(); } public Vector getPossition(){ return possition; } public Vector getVelocity(){ return velocity; } public void setPossition(Vector possition){ this.possition = possition; } public void setVelocity(Vector velocity){ this.velocity = velocity; } public double getHeading(){ return heading; } public void setHeading(double h){ this.heading = h; } } <file_sep>/src/v2/CheckboxChangeListener.java package v2; import javax.swing.JCheckBox; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; public class CheckboxChangeListener implements ChangeListener{ private Model model = Model.getInstance(); @Override public void stateChanged(ChangeEvent state) { System.out.println("StateChanged"); if(state.getSource() instanceof JCheckBox){ System.out.println("Is instance of JCheckBox"); JCheckBox checker = (JCheckBox) state.getSource(); if(checker.getText().equals("Simulate Peir")){ System.out.println(checker.getText()); model.setSimulatePear(checker.isSelected()); }else if(checker.getText().equals("Simulate Preditors")){ System.out.println(checker.getText()); model.setSimulatePreditors(checker.isSelected()); if(checker.isSelected()){ model.createPreditors(1); }else{ model.removeAllPreditors(); } } } } } <file_sep>/src/v2/Simulator.java package v2; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.TextField; import java.awt.Toolkit; import java.util.Hashtable; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.JToggleButton; import javax.swing.SwingConstants; public class Simulator implements Runnable{ private Model model; private JFrame window; private MainView mainview; private JPanel userInterface; private TextField numOfStarlings; //private TextField agility; private JSlider cohesion; private JSlider alignment; private JSlider distance; //private TextField distance; private JSlider speedSlider; private boolean running = false; private final int MAXSPEED = 150; private final int MINSPEED = 50; private JCheckBox simulatePeir = new JCheckBox("Simulate Peir"); private JCheckBox simulatePreditors = new JCheckBox("Simulate Preditors"); public Simulator(){ model = Model.getInstance(); window = new JFrame(); mainview = new MainView(); userInterface = new JPanel(); this.setUpViews(); } private void setUpViews(){ window.setLayout(new BorderLayout()); window.setPreferredSize(Toolkit.getDefaultToolkit().getScreenSize()); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); MouseActionListener mouseListener = new MouseActionListener(); mainview.addMouseListener(mouseListener); mainview.addMouseMotionListener(mouseListener); window.add(BorderLayout.CENTER, mainview); mainview.addStarlings(model.getStarlings()); mainview.addPreditors(model.getPreditors()); Dimension d = new Dimension(); d.setSize(Toolkit.getDefaultToolkit().getScreenSize().width, (int) (Toolkit.getDefaultToolkit().getScreenSize().height*0.15)); userInterface.setPreferredSize(d); JButton simulate = new JButton("Stimulate"); UserInterfaceActionListener uiActionlistener = new UserInterfaceActionListener(this); simulate.addActionListener(uiActionlistener); userInterface.add(simulate); JLabel numOfStarlingsLabel = new JLabel("Starlings Num: "); userInterface.add(numOfStarlingsLabel); numOfStarlings = new TextField("200",5); userInterface.add(numOfStarlings); cohesion = new JSlider(JSlider.HORIZONTAL, 20, 200, 100); cohesion.setBorder(BorderFactory.createTitledBorder("Cohesion")); cohesion.setName("cohesion"); SliderListener listener = new SliderListener(); cohesion.addChangeListener(listener); userInterface.add(cohesion); alignment = new JSlider(JSlider.HORIZONTAL, 5, 50, 20); alignment.setBorder(BorderFactory.createTitledBorder("Alignment")); alignment.setName("alignment"); alignment.addChangeListener(listener); userInterface.add(alignment); //JLabel distanceLabel = new JLabel("Separation"); //userInterface.add(distanceLabel); //distance = new TextField("10", 5); distance = new JSlider(JSlider.HORIZONTAL, 0, 30, 7); distance.setBorder(BorderFactory.createTitledBorder("Separation")); distance.setName("distance"); distance.addChangeListener(listener); userInterface.add(distance); speedSlider = new JSlider(JSlider.HORIZONTAL, MINSPEED, MAXSPEED, 100); speedSlider.setBorder(BorderFactory.createTitledBorder("Refresh Rate:")); Hashtable<Integer, JLabel> sliderLabels = new Hashtable<Integer, JLabel>(); sliderLabels.put(new Integer(MINSPEED), new JLabel("Slow")); sliderLabels.put(new Integer(MAXSPEED), new JLabel("Fast")); speedSlider.setLabelTable(sliderLabels); speedSlider.setPaintLabels(true); userInterface.add(speedSlider); JPanel borderPanel = new JPanel(); CheckboxChangeListener changeListener = new CheckboxChangeListener(); borderPanel.setLayout(new GridLayout(0,1)); borderPanel.setBorder(BorderFactory.createEtchedBorder()); simulatePeir.setSelected(true); simulatePeir.addChangeListener(changeListener); simulatePreditors.setSelected(false); simulatePreditors.addChangeListener(changeListener); borderPanel.add(simulatePreditors); borderPanel.add(simulatePeir); userInterface.add(borderPanel); JButton resetButton = new JButton("Stop"); resetButton.addActionListener(uiActionlistener); userInterface.add(resetButton); userInterface.setBorder(BorderFactory.createRaisedBevelBorder()); window.add(BorderLayout.SOUTH, userInterface); //window.validate(); window.pack(); window.setVisible(true); System.out.println("Created user interface"); } public void runSimulator(){ if(!running){ running = true; model.setSimulatePear(simulatePeir.isSelected()); model.setPercievedVelocity(alignment.getValue()); model.setStarlingDistance(distance.getValue()); model.createStarlings(Integer.parseInt(numOfStarlings.getText())); model.setCohesion(cohesion.getValue()); if(simulatePreditors.isSelected()){ model.createPreditors(1); } Thread runner = new Thread(this); runner.start(); } } @Override public void run() { System.out.println("Running Simulation"); while(running){ try{ Thread.sleep(MAXSPEED + MINSPEED - speedSlider.getValue()); }catch(InterruptedException e){ System.out.println("Runner thread interrupted:\n"+e); } model.updateStarlings(); if(simulatePreditors.isSelected()){ model.updatePreditors(); } window.repaint(); } } public void stop(){ running = false; model.removeAllStarlings(); model.removeAllPreditors(); window.repaint(); } } <file_sep>/src/v2/SliderListener.java package v2; import javax.swing.JSlider; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; public class SliderListener implements ChangeListener{ private Model model = Model.getInstance(); @Override public void stateChanged(ChangeEvent arg0) { JSlider slider = (JSlider)arg0.getSource(); if(slider.getName().equals("alignment")){ System.out.println("alignment "+slider.getValue()); model.setPercievedVelocity(slider.getValue()); } else if(slider.getName().equals("cohesion")){ System.out.println("cohesion "+slider.getValue()); model.setCohesion(slider.getValue()); } else if(slider.getName().equals("distance")){ System.out.println("distnace"); model.setDistance(slider.getValue()); } } } <file_sep>/src/Starling.java /* * Copyright <NAME> 2012 * * This class holds all the information about a starling */ import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; public class Starling{ private int x; private int y; private int z; private int vx; private int vy; private int vz; private double heading; private BufferedImage starlingBuffImage; private int size; public Starling(){ File file = new File("images/twitter_bird.png"); if(file.exists()){ System.out.println("found file"); } try { starlingBuffImage = ImageIO.read(file); } catch (IOException e) { System.out.println("Couldn't create buffered image from file: "+file.getPath()); e.printStackTrace(); } } // Getting information about this starling public int getX(){ return x; } public int getY(){ return y; } public int getz(){ return z; } public double getHeading(){ return heading; } public BufferedImage getStarlingImage(){ return starlingBuffImage; } public int getVelocityX(){ return vx; } public int getVelocityY(){ return vy; } public int getVelocityZ(){ return vz; } //Setting information about this starling public void setX(int x){ this.x = x; } public void setY(int y){ this.y = y; } public void setZ(int z){ this.z = z; } public void setHeading(double h){ this.heading = h; } public void setVelocityX(int vx){ this.vx = vx; } public void setVelocityY(int vy){ this.vy = vy; } public void setVelocityZ(int vz){ this.vz = vz; } } <file_sep>/src/Model.java /* * Copyright <NAME> 2012 * * This class holds information about all the starlings. */ import java.awt.Toolkit; import java.util.ArrayList; public class Model { private ArrayList<Starling> starlings; private static Model model; private Model(){ starlings = new ArrayList<Starling>(); Starling s = new Starling(); s.setX((int)Toolkit.getDefaultToolkit().getScreenSize().width/2); s.setY((int)Toolkit.getDefaultToolkit().getScreenSize().height/2); s.setHeading(1); starlings.add(s); } public static Model getInstance(){ if(model == null){ model = new Model(); } return model; } public ArrayList<Starling> getStarlings(){ return starlings; } public void updateStarlings(){ for(Starling s : starlings){ if(s.getHeading()>0){ s.setX(s.getX()+1); }else{ s.setX(s.getX()-1); } } } } <file_sep>/src/v2/UserInterfaceActionListener.java package v2; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class UserInterfaceActionListener implements ActionListener{ private Simulator simulator; public UserInterfaceActionListener(Simulator simulator){ this.simulator = simulator; } @Override public void actionPerformed(ActionEvent action) { String actionCommand = action.getActionCommand(); if(actionCommand.equals("Stimulate")){ System.out.println("Starting simulation"); simulator.runSimulator(); }else if(actionCommand.equals("Stop")){ System.out.println("Reseting simulation"); simulator.stop(); } } } <file_sep>/src/OptionsPanelController.java import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class OptionsPanelController implements ActionListener{ private OptionsPanel view; private Model model; private SimulatorInterface delegate; public OptionsPanelController(){ view = new OptionsPanel(this); model = Model.getInstance(); delegate = Simulator.getInstance(); } public OptionsPanelController(OptionsPanel op){ model = Model.getInstance(); view = op; } @Override public void actionPerformed(ActionEvent arg0) { } public void setOptionsPanel(OptionsPanel op){ view = op; } }
581f5d7ad1eddcd93b89d23a909c1967e5ca9d11
[ "Java" ]
11
Java
bloggertom/StarlingSimulation
34e4877355e327a301312491214069531044cfc7
d33af71e2088dee7aa1a58f87794651e3f1ca985
refs/heads/master
<file_sep>package com.todo.Todo.list.Model; import javax.validation.constraints.NotBlank; import java.util.UUID; public class Todo { private final UUID id; @NotBlank private final String title; @NotBlank private final String body; private final boolean isActive; public Todo(UUID id, String title, String body, boolean isActive) { this.id = id; this.title = title; this.body = body; this.isActive = isActive; } public UUID getId() { return id; } public String getTitle() { return title; } public String getBody() { return body; } public boolean isActive() { return isActive; } }
d87d37e3693275ebcc086d685cd3d08f6b8a8f54
[ "Java" ]
1
Java
OrestasM/coding-challenge-backend-v2
87d19887ad08041f497f121fba5748fbb483ec07
c9cd3a12afa43bd3e4f622f321dab79f91664dae
refs/heads/master
<repo_name>donghunee/youtubeNav<file_sep>/content.js function onWindowLoad() { console.log("팝업 페이지의 DOM 접근 : ", $("#product_name").text()); // 위 결과는 위 html 파일에서 product_name 아이디의 태그 값인 Injecting Product Name.... 이 된다. } window.onload = onWindowLoad; <file_sep>/getSource.js chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) { const result = request.result; const params = request.params; location.href = `/watch?v=${params}&t=${result}s`; sendResponse({ farewell: "제발" }); });
37ec9091fd40ace85995ee5e4ac82ba8b1a4f9d9
[ "JavaScript" ]
2
JavaScript
donghunee/youtubeNav
47eb0ff2479889fe31652b2f11e7b0654529b788
05322936436fdb75c293c52e4a14e9ece5320f3d
refs/heads/master
<repo_name>jfletcher98/lab_3<file_sep>/lab3_script.sh #!/bin/bash # Authors: <NAME> & <NAME> # Date: 2/7/2020 #Problem 1 Code: #Make sure to document how you are solving each problem! echo "Input a Filename: " read fileName echo "Number of phone numbers in the file: " grep -c '...-...-....' $fileName echo "List of all the phone numbers in the 303 area code: " grep '303-...-....' $fileName echo "Number of the number of emails in the file: " grep -c '@' $fileName grep '@<EMAIL>' $fileName >>email_results.txt
203aae54bdbfdd854120d4407a9ad6e88947b2b3
[ "Shell" ]
1
Shell
jfletcher98/lab_3
5deb168d2bbacebfcfc0349a932ca9827941cf16
1038dbb8f48a64d1d507823db5835432ef421fed
refs/heads/master
<repo_name>yfor/SomeCode<file_sep>/serach/README.md 简单jdbc 使用,只是单机版的玩具而已。 全文搜索其实就是简单的每个字段进行like操作,然后显示时用括号包裹(高亮)。<file_sep>/test/src/data/Parser.java package data; public class Parser { Lexer lexer; Token current_token; public Parser(Lexer lexer) throws Exception { this.lexer = lexer; this.current_token = lexer.get_next_token(); } private void error() throws Exception { throw new Exception("格式错误的表达式"); } private AST term() throws Exception { AST node = factor(); while (current_token.type == TokenType.DIV || current_token.type == TokenType.MUL) { Token token = current_token; if (current_token.type == TokenType.MUL) { eat(TokenType.MUL); } else if (current_token.type == TokenType.DIV) { eat(TokenType.DIV); } node = new BinAST(node, token, factor()); } return node; } private AST factor() throws Exception { if (current_token.type == TokenType.PLUS) { Token token = current_token; eat(TokenType.PLUS); return new UnaryOp(token, factor()); } else if (current_token.type == TokenType.MINUS) { Token token = current_token; eat(TokenType.MINUS); return new UnaryOp(token, factor()); } else if (current_token.type == TokenType.INTEGER) { Token token = current_token; eat(TokenType.INTEGER); return new NumAST(token); } else if (current_token.type == TokenType.LPAREN) { eat(TokenType.LPAREN); AST node = expr(); eat(TokenType.RPAREN); return node; } error(); return null; } private AST expr() throws Exception { AST node = term(); while (current_token.type == TokenType.PLUS || current_token.type == TokenType.MINUS) { Token op = current_token; if (current_token.type == TokenType.PLUS) { eat(TokenType.PLUS); } else if (current_token.type == TokenType.MINUS) { eat(TokenType.MINUS); } node = new BinAST(node, op, term()); } return node; } private void eat(TokenType type) throws Exception { if (this.current_token.type == type) { current_token = lexer.get_next_token(); return; } error(); } public AST parse() throws Exception { AST expr = expr(); if (current_token.type != TokenType.EOF) { error(); } return expr; } } <file_sep>/日常的坑/README.md 会贴出一些日志 svn日志 github日志 日常备份数据的treeList 重点的分析这些数据<file_sep>/lsbasi/test/lsbasi/TestDebug.java package lsbasi; public class TestDebug { public static void main(String[] args) throws Exception { Lexer lexer = new Lexer("{number=2;a=number;b=10*a+10;c=a--b};x=11;y=x*10"); Parser p = new Parser(lexer); Interpreter i = new Interpreter(p); i.debugger(); System.out.println(i.GLOBAL_SCOPE); } } <file_sep>/maven/README.md 测试不容易 自动构建不容易 知易行难!!<file_sep>/lsbasi/src/lsbasi/ast/AssignmentAST.java package lsbasi.ast; public class AssignmentAST extends StatementAST { String id; AST expr; public String getId() { return id; } public AST getExpr() { return expr; } public AssignmentAST(String id, AST expr) { super(); this.id = id; this.expr = expr; } @Override public String toString() { return "AssignmentAST [id=" + id + ", expr=" + expr + "]"; } } <file_sep>/lsbasi/test/lsbasi/TestParser.java package lsbasi; import java.util.List; import org.junit.Test; import lsbasi.ast.StatementAST; import lsbasi.ast.StatementListAST; public class TestParser { @Test public void test1() throws Exception { Lexer lexer = new Lexer("{number=2;a=number;b=10*a+10;c=a--b};x=11;"); Parser p = new Parser(lexer); StatementListAST a = p.parser(); List<StatementAST> list = a.getList(); for (StatementAST statementAST : list) { System.out.println(statementAST); } } } <file_sep>/test/src/data/README.md SIMPLE Interpreter add IR(AST) lispStyle backOperateStyle<file_sep>/coding/README.md [https://wangqiang_bdb.coding.me/](https://wangqiang_bdb.coding.me/) ##jenkins 没有jenkins 拉去代码 打包 运行(关掉老的服务) git 地址 多长时间检查一次 gradle clean build 复制到对应文件夹 杀掉老进程 启动新进程 (看文件日期 看日志 看进程号) docker 构建镜像(build image)删除老的镜像 删除容器 启动新的容器 docker的配置 注意这里没有改代码 ## docker<file_sep>/python/qqGroup/qq.py import sys for line in sys.stdin: list=line.split("\t") print '''BEGIN:VCARD VERSION:3.0 N:{0};{0};;; FN:{0} TEL;TYPE=CELL:{1} END:VCARD'''.format(list[0],list[1][:-1])<file_sep>/python/INNO6toarea/io.py import sys for line in sys.stdin: print 'INSERT INTO `idno6toarea` VALUES ({0}, {0}, {1});'.format("'"+line[11:17]+"'","'"+line[21:-3]+"'")<file_sep>/下载博客/download.js cli = require('./crawler'), parser = require('./parsehtmljs'); var url='http://www.yinwang.org/'; cli.crawler(url,parser.parseArticleTopic); //node download.js >wangyin-blogs.html<file_sep>/lsbasi/src/lsbasi/visit/BinVisitor.java package lsbasi.visit; import java.util.Map; import lsbasi.Token; import lsbasi.TokenType; import lsbasi.ast.BinOpAST; public class BinVisitor { public static int visit(BinOpAST node, Map<String, Integer> scope) throws Exception { Token op = node.op; int left = NodeVisitor.visit(node.left, scope); int right = NodeVisitor.visit(node.right, scope); if (op.getType() == TokenType.PLUS) { return left + right; } else if (op.getType() == TokenType.MINUS) { return left - right; } else if (op.getType() == TokenType.MULTI) { return left * right; } else { return left / right; } } } <file_sep>/气井检测图片应用/qjjc/src/com/qjjc/test/LoginActivity.java package com.qjjc.test; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.Window; /** * 登录界面 * @author wangqiangae * */ public class LoginActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.requestWindowFeature(Window.FEATURE_NO_TITLE);// 鍘绘�?��囬鏍� setContentView(R.layout.login); } public void loginBtnclick(View view) { Intent in = new Intent(this, MianActivity.class); startActivity(in); } }<file_sep>/键盘事件/start.c //#include <stdio.h> #include <stdlib.h> #include <windows.h> void open();//打开浏览器 void close();//关闭浏览器 void input(char *c);//输入文字 void click();//点击鼠标 main() { //定义需要搜索的 计数 长度 char *sa[]={"JAVA","XIANHUA","NIUREN","C","MEINV"}; int i=0,len=5; while(1){ open(); input(sa[i%len]); click(); close(); i++; } } void open(){ ShellExecute(0,"open","www.baidu.com",0,0,1);//异步打开 Sleep(1500);//等待打开 } void input(char *c){ Sleep(1000); char temc='n'; while(*c){ temc=*c++; //printf("%c",temc); keybd_event( temc,0,0,0 ); keybd_event( temc,0,2,0); Sleep(20);//输入字符 等待键盘 } Sleep(500); keybd_event( ' ',0,0,0 );//输入空格 keybd_event( ' ',0,2,0); Sleep(500); keybd_event( 0x0D,0,0,0 );//点击回车 确定输入 keybd_event( 0x0D,0,2,0); Sleep(500); keybd_event( 0x0D,0,0,0 );//点击回车 搜索 keybd_event( 0x0D,0,2,0); } void click(){ Sleep(2000); SetCursorPos(170,240);//等待结果 移动鼠标 Sleep(40); mouse_event(MOUSEEVENTF_LEFTDOWN,0,0,0,0); Sleep(20); mouse_event(MOUSEEVENTF_LEFTUP,0,0,0,0);//点击鼠标 } void close(){ Sleep(4000); //system("taskkill /f /im QQBrowser.exe");//关闭进程 } <file_sep>/python/INNO6toarea/IDNO6toArea.sql /* Navicat MySQL Data Transfer Source Server : localhost Source Server Version : 50538 Source Host : localhost:3306 Source Database : hanhua Target Server Type : MYSQL Target Server Version : 50538 File Encoding : 65001 Date: 2015-12-30 14:19:31 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for idno6toarea -- ---------------------------- DROP TABLE IF EXISTS `idno6toarea`; CREATE TABLE `idno6toarea` ( `id` int(6) DEFAULT NULL, `IDNO6` int(6) DEFAULT NULL, `area` varchar(20) DEFAULT NULL ) ENGINE=MyISAM DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of idno6toarea -- ---------------------------- <file_sep>/气井检测图片应用/qjjc/src/com/qjjc/test/MySimpleAdapter.java /*author:conowen * date:2012.4.2 * MySimpleCursorAdapter */ package com.qjjc.test; import java.util.List; import java.util.Map; import android.content.Context; import android.database.Cursor; import android.graphics.Color; import android.view.View; import android.view.ViewGroup; import android.widget.SimpleAdapter; import android.widget.SimpleCursorAdapter; public class MySimpleAdapter extends SimpleAdapter { public MySimpleAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) { super(context, data, resource, from, to); // TODO Auto-generated constructor stub } @Override public View getView(final int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub // listview每次得到一个item,都要view去绘制,通过getView方法得到view // position为item的序号 View view = null; if (convertView != null) { view = convertView; // 使用缓存的view,节约内存 // 当listview的item过多时,拖动会遮住一部分item,被遮住的item的view就是convertView保存着。 // 当滚动条回到之前被遮住的item时,直接使用convertView,而不必再去new view() } else { view = super.getView(position, convertView, parent); } int[] colors = { Color.WHITE, Color.rgb(219, 238, 244) };//RGB颜色 view.setBackgroundColor(colors[position % 2]);// 每隔item之间颜色不同 return super.getView(position, view, parent); } }<file_sep>/misc/resultToJson数据库查询结果转JSON.java package cn.outofmemory.json; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import com.google.gson.*; public class ResultSetToJson { public static final JsonArray ResultSetToJsonArray(ResultSet rs) { JsonObject element = null; JsonArray ja = new JsonArray(); ResultSetMetaData rsmd = null; String columnName, columnValue = null; try { rsmd = rs.getMetaData(); while (rs.next()) { element = new JsonObject(); for (int i = 0; i < rsmd.getColumnCount(); i++) { columnName = rsmd.getColumnName(i + 1); columnValue = rs.getString(columnName); element.addProperty(columnName, columnValue); } ja.add(element); } } catch (SQLException e) { e.printStackTrace(); } return ja; } public static final JsonObject ResultSetToJsonObject(ResultSet rs) { JsonObject element = null; JsonArray ja = new JsonArray(); JsonObject jo = new JsonObject(); ResultSetMetaData rsmd = null; String columnName, columnValue = null; try { rsmd = rs.getMetaData(); while (rs.next()) { element = new JsonObject(); for (int i = 0; i < rsmd.getColumnCount(); i++) { columnName = rsmd.getColumnName(i + 1); columnValue = rs.getString(columnName); element.addProperty(columnName, columnValue); } ja.add(element); } jo.add("result", ja); } catch (SQLException e) { e.printStackTrace(); } return jo; } public static final String ResultSetToJsonString(ResultSet rs) { return ResultSetToJsonObject(rs).toString(); } }<file_sep>/codeForReadBook/linuxC/memory1.c #include <unistd.h> #include <stdlib.h> #include <stdio.h> #define A_MEGABYTE (1025*1024) #define PHY_MEM_MEGS 2048 int main(){ char *some_memory; size_t size_to_allocate = A_MEGABYTE; int megs_obtained = 0; //THIS !!!!!!!! will out memory while (megs_obtained <(PHY_MEM_MEGS * 200)){ some_memory = (char *) malloc(size_to_allocate); if(some_memory != NULL){ megs_obtained++; sprintf(some_memory,"hello world!"); printf("%s -now allocated %d Megabytes\n",some_memory,megs_obtained); } else{ exit(EXIT_FAILURE); } } exit(EXIT_SUCCESS); } <file_sep>/lsbasi/src/lsbasi/visit/AssignVisitor.java package lsbasi.visit; import java.util.Map; import lsbasi.ast.AssignmentAST; public class AssignVisitor { public static void visit(AssignmentAST node, Map<String, Integer> scope) throws Exception { scope.put(node.getId(), NodeVisitor.visit(node.getExpr(), scope)); } } <file_sep>/lsbasi/src/lsbasi/ast/VarAST.java package lsbasi.ast; public class VarAST implements AST { public String id; public VarAST(String id) { this.id = id; } } <file_sep>/serach/src/xuankexitong/messages.properties Mian.0=-------\u6B22\u8FCE\u8FDB\u5165\u4FE1\u606F\u4E2D\u5FC3 ---------- Mian.1=\u9009\u62E9\u4F60\u60F3\u8981\u7684\u64CD\u4F5C Mian.2=\u8F93\u5165\u4F60\u7684\u7528\u6237\u540D Mian.3=\u8F93\u5165\u4F60\u7684\u5BC6\u7801 Mian.4=0 Mian.5=0 Mian.6=\u4E0D\u5339\u914D\u7684\u5BC6\u7801,\u91CD\u65B0\u8F93\u5165 News.0= News.1=com.mysql.jdbc.Driver News.10=email News.11=\t News.12=\n News.13= News.14=\n News.15={ News.16=} News.2=jdbc:mysql://localhost:3306/test??useUnicode=true&amp;characterEncoding=utf-8&user=root&password=<PASSWORD> News.3=select * from users_ui News.4=Id News.5=\t News.6=name News.7=\t News.8=phone News.9=\t <file_sep>/下载博客/parsehtmljs.js /** * Created by youxiachai on 14-1-20. */ var request = require('request'), cheerio = require('cheerio'), debug = require('debug')('parse: article') crawler = require('./crawler'); function parseItem($item){ var a = $item.find('a') var text = a.text() var herf = a.attr("href") console.log("<h1>" +text + "<h1>") crawler.crawler(herf,parseArticle) } function parseArticleTopic(html){ var $ = cheerio.load(html); // 获取list var $list = $('.list-group'); $list.children().each(function (){ parseItem(cheerio(this)) }) } function parseArticle(html){ var $ = cheerio.load(html); var $body = $('body'); console.log($body.toString()) console.log('<h1>=======================================================<h1>') } exports.parseArticleTopic = parseArticleTopic<file_sep>/test/src/test/os.java package test; public class os { public static void main(String[] args) { print("ac\n\tbc\n\nss\nsss\naaaaaaaa\nssa"); show(); } /** * 格式化字符串 * * @param format * @param args */ static void print(String format, Object... args) { for (int i = 0; i < format.length(); i++) { char ci = format.charAt(i); if (ci == '%') { ci = format.charAt(++i); if (ci >= '0' && ci <= '9') { int size = ci - '0'; ci = format.charAt(++i); } if (ci == 'd') { // java 用正则表达式做的 晕! // TODO // https://github.com/SamyPesse/How-to-Make-a-Computer-Operating-System/tree/master/Chapter-5 } } else { putChar(ci); } } } // 回显 static void show() { // 应该就上汇编了 写到某个地址就可以了 for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { System.out.print(screen_buffer[i][j]); } System.out.println(); } } /** * 实现了字符的转意 输出char * * @param c */ static void putChar(char c) { if (c == '\n') { x = 0; y++; // back space } else if (c == '\b') { if (x > 0) { x--; } // horizontal tab } else if (c == '\t') { x = x + 8 - (x % 8); // carriage return } else if (c == '\r') { x = 0; } else { // 真正的赋值在c里面是一个指针 screen_buffer[y][x] = c; x++; if (x > w - 1) { x = 0; y++; } } if (y > h - 1) { y = 0; // 暂时清空 很大c语音标准库的应用 // 这里应该要保存 可能就是bash的功能了 screen_buffer = new char[h][w]; } } // 屏幕大小和数组 static int h = 7; static int w = 40; static char[][] screen_buffer = new char[h][w]; // 屏幕位置 static int x = 0; static int y = 0; } <file_sep>/codeForReadBook/README.md 一些书籍阅读的代码,包括示例,习题或者扩展。 现在还比较少,慢慢会有所增加。<file_sep>/lsbasi/src/lsbasi/Debugger.java package lsbasi; import java.util.List; import java.util.Map; import java.util.Scanner; import lsbasi.ast.StatementAST; import lsbasi.visit.NodeVisitor; public class Debugger { Scanner s = new Scanner(System.in); private Map<String, Integer> scope; private List<StatementAST> list; private int index; public Debugger(List<StatementAST> list, Map<String, Integer> scope) { this.list = list; this.scope = scope; this.index = 0; } public void help() { System.out.println("h:help"); System.out.println("n:next"); System.out.println("w:watch"); } public String waitUser() { return s.next(); } public void debugger() throws Exception { help(); while (index < list.size() ) { switch (waitUser()) { case "n": NodeVisitor.visit(list.get(index), scope); index++; break; case "h": help(); break; case "w": System.out.println(scope); break; default: break; } } } } <file_sep>/下载博客/lagou_javaJobs.js var request = require('request'); var cheerio = require('cheerio'); var crawler = require('./crawler'); //post请求数据 function postInfo(httpRequet, parser) { request.post(httpRequet, function optionalCallback(err, httpResponse, body) { if (err) { return console.error('upload failed:', err); } //console.log('Upload successful! Server responded with:', body ); parser(body.toString()) }); //数据id数组 function parseIdsThenCrawler(body) { var jsonD = JSON.parse(body); var idList = jsonD.content.result; for (var i = 0; i < idList.length; i++) { var resultIndex = idList[i]; var id = resultIndex.positionId; var jobsUrl = "http://www.lagou.com/jobs/" + id + ".html?source=search&i=search-13"; //详情页 var pa = { salary : resultIndex.salary, companyName : resultIndex.companyName, jobsUrl : jobsUrl }; crawler.crawler(jobsUrl, parseJobRequire, pa); } } //拉钩网java工作要求 function parseJobRequire(html, parserArguments) { var $ = cheerio.load(html); var jobRequire = $('.job_bt'); var li = "<li><div class='h'><h3><a href='" + parserArguments.jobsUrl + "'>" + parserArguments.companyName + ":" + parserArguments.salary + "</a></h3></div>"; console.log(li); console.log(jobRequire.toString() + "</li>"); } function htmlFrame() { var htmlHead = '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>拉钩网java工作要求20151026</title>'; var style = '<style>.h{}.h a{background-color: #00b38a;color: #fff;} dd{padding: 6px 16px;color: #777;' + 'font: 14px/22px "Hiragino Sans GB","微软雅黑","宋体";}</style>'; console.log(htmlHead + style + '</head><body><ol>'); } //启动器 function download() { /* 根据浏览器xhr请求分析的数据 url:拉钩网请求地址 城市北京 cookie:浏览器的 */ var cookie = 'user_trace_token=<KEY>; fromsite=www.google.com.hk; utm_source=""; ' + 'JSESSIONID=63EAFAACA77EF2941663BB6F9BFF2ED4; _gat=1; PRE_UTM=; PRE_HOST=; PRE_SITE=; PRE_LAND=http%3A%2F%2Fwww.lagou.com%2F;' + 'LGUID=20151026154208-0fca14e9-7bb5-11e5-8fd0-5254005c3644; index_location_city=%E5%8C%97%E4%BA%AC;' + 'SEARCH_ID=fd70b79dba0c470e896032658e506867; _ga=GA1.2.950822083.1445845323; Hm_lvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1445845323;' + 'Hm_lpvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1445845339; LGSID=20151026154208-0fca1208-7bb5-11e5-8fd0-5254005c3644;' + 'LGRID=20151026154223-18645bdf-7bb5-11e5-8fd0-5254005c3644' function parseJobRequire (html){ var $ = cheerio.load(html); var jobRequire = $('.job_bt');//工作要求所在div console.log("<h3>"+counts+"</h3>"); counts++; console.log(jobRequire.toString()); } //拉钩网请求地址 city=北京 var url='http://www.lagou.com/jobs/positionAjax.json?city=%E5%8C%97%E4%BA%AC'; // 从浏览器分析的xhr数据所得 //请求数据构成 分页形式的数据 var pn=0; first="true" var data = {first:first,pn:pn,kd:"java"}; var first = "true"; var pn = 0; var data = { first : first, pn : pn, kd : "java" }; var httpRequet = { url : 'http://www.lagou.com/jobs/positionAjax.json?city=%E5%8C%97%E4%BA%AC', formData : data, headers : { 'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:26.0) Gecko/20100101 Firefox/26.0', Cookie : cookie, Referer : 'http://www.lagou.com/zhaopin/Java/?labelWords=label', 'Accept' : 'application/json, text/javascript, */*; q=0.01', 'Accept-Encoding' : 'gzip, deflate', 'Accept-Language' : 'zh-CN,zh;q=0.8', 'Cache-Control' : 'max-age=0', 'Connection' : 'keep-alive', 'Content-Length' : '23', 'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8', 'Host' : 'www.lagou.com', 'Origin' : 'http://www.lagou.com', 'X-Requested-With' : 'XMLHttpRequest' } }; htmlFrame(); function time() { if (pn < 30) { postInfo(httpRequet, parseIdsThenCrawler) first = "false"; pn = pn + 1; setTimeout(function () { time(); }, 1000*20) } } time(); download(); <file_sep>/键盘事件/README.md 用百度搜索关键字,对结果连接进行点击 利用c语言api 打开浏览器(system) 操作键盘 点击鼠标 关闭浏览器<file_sep>/xmlappend/TestXMl.java import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.List; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.XMLWriter; /** * 将样式变成类 * 你可以尝试将类的形式合并成css * 比较两种形式的好坏 不要极端 看看大网站的代码猜一猜知道一些原因 * 是dom4j-1.61 * @author xiaoqiang * */ public class TestXMl { // 最终生成的css输出 private static StringBuffer cssOut = new StringBuffer(); public static void main(String[] args) throws DocumentException, IOException { // 输出 // 输出到控制台 XMLWriter xmlWriter = new XMLWriter(); xmlWriter.write(changStyleToClass(mockresponseXMLStart())); System.out.println(); System.out.println(getCssOut()); } /** * 假的xml测试数据 * * @return */ public static String mockresponseXMLStart() { StringBuffer sb = new StringBuffer(); sb.append("<Packet type=\"REQUEST\" version=\"1.0\">"); sb.append("<Head>"); sb.append("<ResquestType>WX110</ResquestType>"); sb.append("<ResponseCode>0000</ResponseCode>"); sb.append("<ErrorMessage>成功</ErrorMessage>"); sb.append("</Head>"); sb.append("<Body>"); sb.append("<table id='idtest' style='width:200;height:100' >"); sb.append("<TD id='idtest' style='width:100;height:100' >"); sb.append("xx"); sb.append("</TD>"); sb.append("<TD id='idtest' style='width:100;height:100' >"); sb.append("yy"); sb.append("</TD>"); sb.append("</table>"); sb.append("<div style='color:blue;float:left'>"); sb.append("<div style='color:red;float:right'>ii"); sb.append("</div>"); sb.append("</div>"); sb.append("</Body>"); sb.append("</Packet>"); return sb.toString(); } // <Packet type="REQUEST" version="1.0"> // <Head> // <ResquestType>WX110</ResquestType> // <ResponseCode>0000</ResponseCode> // <ErrorMessage>成功</ErrorMessage> // </Head> // <Body> // <table id='idtest' style='width:200;height:100'> // <TD id='idtest' style='width:100;height:100'>xx</TD> // <TD id='idtest' style='width:100;height:100'>yy</TD> // </table> // </Body> // </Packet> // <style>.c1595502228{width:200;height:100}.c1089943603{width:100;height:100}.c1089943603{width:100;height:100}<style> // <?xml version="1.0" encoding="UTF-8"?> // <Packet type="REQUEST" version="1.0"> // <Head> // <ResquestType>WX110</ResquestType> // <ResponseCode>0000</ResponseCode> // <ErrorMessage>成功</ErrorMessage> // </Head> // <Body> // <table id="idtest" class="c1595502228"> // <TD id="idtest" class="c1089943603">xx</TD> // <TD id="idtest" class="c1089943603">yy</TD> // </table> // </Body> // </Packet> /** * 将样式变成类 * * @param xml * @return * @throws DocumentException * @throws UnsupportedEncodingException */ public static Document changStyleToClass(String xml) throws DocumentException, UnsupportedEncodingException { Document document = DocumentHelper.parseText(xml); Element root = document.getRootElement(); changElementThenChildren(root); return document; } /** * 先对节点进行处理,再对子节点进行递归 * @param root * @return */ private static Element changElementThenChildren(Element root) { changStyleToClass(root); List<?> elements = root.elements(); for (Object object : elements) { changElementThenChildren((Element) object); } return root; } /** * 返回完整style * @return */ public static String getCssOut() { return "<style>"+cssOut+"</style>"; } /** * 对节点进行操作 * 如果存在style属性 移除属性 * 根据样式的内容生产class名 并增加class属性 * 生成样式 * 入参 : <TD id='idtest' style='width:100;height:100'>xx</TD> * 处理后:<TD id="idtest" class="c1089943603">yy</TD> * 附带增加 cssOut: .c1595502228{width:200;height:100} * * @param root */ private static void changStyleToClass(Element root) { String style = root.attributeValue("style"); if (style != null) { root.remove(root.attribute("style")); String className = ".c" + Math.abs(style.hashCode()); root.addAttribute("class", className); cssOut.append(className + "{").append(style).append("}"); } } }<file_sep>/下载博客/README.md #类爬虫应用(主要是对网页的请求与解析): +使用:node xx.js >oo.ht ##抓取网页要点 *crawler:http *parsehtmljs:query *htmlHead *httpRequet #现在包含: 1.下载王垠的博客 2.抓起拉购网的java相关工作要求 1.[查看工作要求!](https://rawgit.com/yfor/SomeCode/master/%E4%B8%8B%E8%BD%BD%E5%8D%9A%E5%AE%A2/%E6%8B%89%E9%92%A9%E7%BD%91java%E5%B7%A5%E4%BD%9C%E8%A6%81%E6%B1%8220151026.html) 2.[查看博客!](https://rawgit.com/yfor/SomeCode/master/%E4%B8%8B%E8%BD%BD%E5%8D%9A%E5%AE%A2/wangyin-blogs.html) 3.[test markdown edit](https://cdn.rawgit.com/yfor/SomeCode/master/%E4%B8%8B%E8%BD%BD%E5%8D%9A%E5%AE%A2/index.html). <file_sep>/codeForReadBook/SICP/greet.py ##http://www-inst.eecs.berkeley.edu/~cs61a/sp12/book/index.html print "Ctr-x-s; save" print "Ctr-x o change window" print "Ctr-c-c run buffer" print "HELLO" print "ctr-c-z open python" print "move ctr b f p n ;m " my_name = "wq" def greet(): print my_name print "python" print "Ctr + v: next page;Alt + v pre page" <file_sep>/气井检测图片应用/qjjc/src/com/qjjc/test/DataHelper.java /*author:conowen * date:2012.4.2 * DataHelper */ package com.qjjc.test; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; public class DataHelper extends SQLiteOpenHelper { @Override public synchronized void close() { // TODO Auto-generated method stub super.close(); } public DataHelper(Context context, String name, CursorFactory factory, int version) { super(context, name, factory, version); // TODO Auto-generated constructor stub } @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub String sql = "CREATE TABLE JobChecker (_id INTEGER PRIMARY KEY , department VARCHAR, job VARCHAR,teacher VARCHAR,address VARCHAR,student VARCHAR,isworking VARCHAR)"; db.execSQL(sql); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub } }<file_sep>/lsbasi/src/lsbasi/Parser.java package lsbasi; import lsbasi.ast.AST; import lsbasi.ast.AssignmentAST; import lsbasi.ast.BinOpAST; import lsbasi.ast.NopoAST; import lsbasi.ast.NumberAST; import lsbasi.ast.StatementAST; import lsbasi.ast.StatementListAST; import lsbasi.ast.UnaryOpAST; import lsbasi.ast.VarAST; public class Parser { private Lexer lexer; private Token currentToken; public Parser(Lexer lexer) throws Exception { this.lexer = lexer; currentToken = lexer.getNextToken(); } public StatementListAST parser() throws Exception { StatementListAST expr = program(); eat(TokenType.EOF); return expr; } StatementListAST program() throws Exception { StatementListAST node = statementList(); return node; } private StatementListAST statementList() throws Exception { StatementListAST list = new StatementListAST(statement()); while (currentToken.type == TokenType.SEMI) { if (currentToken.type == TokenType.SEMI) { eat(TokenType.SEMI); } if (currentToken.type != TokenType.EOF) list.add(statement()); } return list; } private StatementAST statement() throws Exception { StatementAST node; if (currentToken.type == TokenType.BEGIN) { eat(TokenType.BEGIN); StatementAST statementList = statementList(); eat(TokenType.END); node = statementList; } else if (currentToken.type == TokenType.ID) { node = assignmentStatement(); } else { node = new NopoAST(); } return node; } private StatementAST assignmentStatement() throws Exception { Token token = currentToken; eat(TokenType.ID); eat(TokenType.ASSIGN); AST expr = expr(); return new AssignmentAST(token.value, expr); } private AST expr() throws Exception { AST node = term(); while (currentToken.type == TokenType.PLUS || currentToken.type == TokenType.MINUS) { Token token = currentToken; eat(token.type); AST right = term(); node = new BinOpAST(node, token, right); } return node; } private AST term() throws Exception { AST node = factor(); while (currentToken.type == TokenType.DIV || currentToken.type == TokenType.MULTI) { Token token = currentToken; eat(token.type); AST right = factor(); node = new BinOpAST(node, token, right); } return node; } private AST factor() throws Exception { Token token = currentToken; if (token.type == TokenType.PLUS || token.type == TokenType.MINUS) { eat(token.type); return new UnaryOpAST(token, factor()); } else if (token.type == TokenType.INTEGER) { eat(TokenType.INTEGER); return new NumberAST(Integer.parseInt(token.value)); } else if (token.type == TokenType.LPAREN) { eat(TokenType.LPAREN); AST r = expr(); eat(TokenType.RLPAREN); return r; } else if (token.type == TokenType.ID) { return variable(); } throw new Exception("parse error"); } AST variable() throws Exception { VarAST varAST = new VarAST(currentToken.getValue()); eat(TokenType.ID); return varAST; } private void eat(TokenType type) throws Exception { if (currentToken.type == type) { currentToken = lexer.getNextToken(); return; } throw new Exception("parse error"); } } <file_sep>/test/src/data/Interpreter.java package data; public class Interpreter { Lexer lexer; Token current_token; public Interpreter(Lexer lexer) throws Exception { this.lexer = lexer; this.current_token = lexer.get_next_token(); } public void error() { try { throw new Exception("格式错误的表达式"); } catch (Exception e) { e.printStackTrace(); } } public int term() throws Exception { int result = factor(); while (current_token.type == TokenType.DIV || current_token.type == TokenType.MUL) { if (current_token.type == TokenType.MUL) { eat(TokenType.MUL); result *= factor(); } else if (current_token.type == TokenType.DIV) { eat(TokenType.DIV); result /= factor(); } } return result; } public int factor() throws Exception { if (current_token.type == TokenType.INTEGER) { int value = Integer.parseInt(current_token.value); eat(TokenType.INTEGER); return value; } else if (current_token.type == TokenType.LPAREN) { eat(TokenType.LPAREN); int result = expr(); eat(TokenType.RPAREN); return result; } error(); return 0; } public int expr() throws Exception { int result = term(); while (current_token.type == TokenType.PLUS || current_token.type == TokenType.MINUS) { if (current_token.type == TokenType.PLUS) { eat(TokenType.PLUS); result += term(); } else if (current_token.type == TokenType.MINUS) { eat(TokenType.MINUS); result -= term(); } } return result; } public void eat(TokenType type) throws Exception { if (this.current_token.type == type) { current_token = lexer.get_next_token(); return; } error(); } }<file_sep>/气井检测图片应用/README.md # SomeCode android平台 主要利用webview,当时想着肯能也要做ios,展示的后端的代码就可以共用一套。 里边涉及一些布局的知识。 icharts组件的使用。 线程的利用。 一些自带api利用。 这次郭松处理的图片相当nice。 最后的兼容测试带来了很大的问题,当然都怪我(一方面是屏幕适配,更严重的是编码问题引发的运行失败,不同机器有不同的表现)。 开发过程查资料还是比较辛苦,不过两天时间基本完成了预期的效果。<file_sep>/xmlappend/README.md #java表达数据的能力太弱 ##javaPoint *''' ''' --一些脚本语言引入 ==类似Xmlappend 才有了配置文件== *{} 之类数据字面值 ==dom4j-xml-object-json 才有了配置文件== *函数不能传递 处理数据和表示数据的能力都很差 ==各种设计模式== **折腾数据结构** *这个文件夹下是xml的一些操作*<file_sep>/my-WEBSITE/README.md 是我托管在sae上的网站代码 不同的目录代表不同的版本使用了不同的技术 1:2015/08/12<file_sep>/maven/tdg/src/main/java/com/github/yfor/bigdata/tdg/MainC.java package com.github.yfor.bigdata.tdg; public class MainC { public static void main(String[] args) { KafkaConsumer consumerThread = new KafkaConsumer(KafkaProperties.topic); consumerThread.start(); } } <file_sep>/lsbasi/src/lsbasi/visit/NumberVisitor.java package lsbasi.visit; import lsbasi.ast.NumberAST; public class NumberVisitor { public static int visit(NumberAST node) { return node.val; } } <file_sep>/coding/index.md # 务工帮及相关产品介绍 ``` 安全生产云平台(CPSP Cloud platform for safety production),为企业和务工人员解决安全生产难题 ``` ## 一产品介绍 1. 为啥要做 .. 2. 客户 适合各个行业 交通施工 生产车间 3. 架构 ![Alt text](arc.png) 4. 参与角色 ![Alt text](role.png) ## 二.已有功能介绍 1. 主要看务工帮公众号app ![Alt text](home.png) 2. admin ![Alt text](admin.png) 3. 安质宝工经员审核 ![Alt text](shenhe.png) 安全方面 安全培训 安全资讯 隐患提报 班组人员审核 入场工种 技能 ## 三.相关产品 主要看安质宝的系统 ![Alt text](app.png) ![Alt text](anzhibao.png) ## 四.未来规划 主要是看2.1app原型 1. 考勤 工资 工种和工资的关系 2. 找工作 工作履历 体检资料 3. 朋友圈 用户的黏性 4. 保险 主要是意外险 团体险 工种和保险的关系 <file_sep>/气井检测图片应用/qjjc/src/com/qjjc/test/SplashActivity.java package com.qjjc.test; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; /** * 进入程序的闪屏 * @author wangqiangae * */ public class SplashActivity extends Activity { private Intent intent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.splash); startMainAvtivity(); } private void startMainAvtivity() { new Handler().postDelayed(new Runnable() { public void run() { intent=new Intent(SplashActivity.this,LoginActivity.class); startActivity(intent); SplashActivity.this.finish();//结束本Activity } }, 1000);//设置执行时间 } } <file_sep>/test/src/data/json/Parser.java package data.json; import java.util.ArrayList; import java.util.HashMap; import org.junit.Test; public class Parser { Lexer lexer; Token current_token; public Parser() throws Exception { Lexer lexer = new Lexer( "{ \"k\" : [{\"1\":1},2,3],\"k1\":{\"tt\":1} }");//test json this.lexer = lexer; this.current_token = lexer.get_next_token(); } private void eat(JsonTokenType type) throws Exception { if (this.current_token.type == type) { current_token = lexer.get_next_token(); return; } error(); } private void error() throws Exception { throw new Exception("格式错误的表达式"); } private ArrayList<Object> getList() throws Exception { ArrayList<Object> list = new ArrayList<>(); list.add(getJson()); while (current_token.type == JsonTokenType.COMMA) { eat(JsonTokenType.COMMA); list.add(getJson()); } return list; } // private Object getJson() throws Exception { /** * JSON:{key:v}|number|array|string * key:string|(canbeJOSN) * v:JOSN * number:(0..9)+ * string:"(c)+" * array:[json(,josn)*] * 没有实现布尔值 应该很简单 增加词法分析 */ while (current_token.type != JsonTokenType.EOF) { if (current_token.type == JsonTokenType.NUMBER) { int i = Integer.parseInt(current_token.value); eat(JsonTokenType.NUMBER); return i; } if (current_token.type == JsonTokenType.LEFTBRACKET) { eat(JsonTokenType.LEFTBRACKET); ArrayList<Object> list = getList(); eat(JsonTokenType.RIGHTBRACKET); return list; } if (current_token.type == JsonTokenType.LEFTbrace) { eat(JsonTokenType.LEFTbrace); HashMap<Object, Object> jo = getKVmap(); eat(JsonTokenType.RIGHTbrace); return jo; } if (current_token.type == JsonTokenType.STRING) { return current_token.value; } } return null; } private HashMap<Object, Object> getKVmap() throws Exception { HashMap<Object, Object> jo = new HashMap<>(); Object k = getJson(); eat(JsonTokenType.STRING); eat(JsonTokenType.COLON); Object v = getJson(); jo.put(k, v); while (current_token.type == JsonTokenType.COMMA) { eat(JsonTokenType.COMMA); k = getJson(); eat(JsonTokenType.STRING);//(canbeJOSN) eat(JsonTokenType.COLON); v = getJson(); jo.put(k, v); } return jo; } public Object parser() throws Exception{ Object json = getJson(); if(current_token.type!=JsonTokenType.EOF){ error(); } return json; } @Test public void testJson() throws Exception { Parser p = new Parser(); System.out.println(p.getJson()); } } <file_sep>/maven/maventest/src/test/java/com/yfor/AppTest.java package com.companyname.bank; import org.junit.Test; import static org.junit.Assert.*; /** * Unit test for simple App. */ public class AppTest { @Test public void testApp() { System.out.println("hi"); assertTrue( true ); } @Test public void testUtils() throws Exception { //198 long nanoTime = System.nanoTime(); for (int i = 0; i < 1000; i++) { String vehicleFrameNo="LV3LD830473894821"; StringBuffer sb = new StringBuffer(198); sb.append("<?xml version=\"1.0\" encoding=\"GBK\"?>"); sb.append("<Packet type=\"REQUEST\" version=\"1.0\">"); sb.append("<Head>"); sb.append("<RequestType>V020</RequestType>"); sb.append("</Head>"); sb.append("<Body>"); sb.append("<VehicleFrameNo>"); sb.append(vehicleFrameNo); sb.append("</VehicleFrameNo>"); sb.append("</Body>"); sb.append("</Packet>"); } System.out.println( (System.nanoTime()- nanoTime)/1000); System.out.println( "-------------------------------------"); nanoTime = System.nanoTime(); for (int i = 0; i < 1000; i++) { String vehicleFrameNo="LV3LD830473894821"; StringBuffer sb = new StringBuffer(198); sb.append("<?xml version=\"1.0\" encoding=\"GBK\"?>"); sb.append("<Packet type=\"REQUEST\" version=\"1.0\">"); sb.append("<Head>"); sb.append("<RequestType>V020</RequestType>"); sb.append("</Head>"); sb.append("<Body>"); sb.append("<VehicleFrameNo>"); sb.append(vehicleFrameNo); sb.append("</VehicleFrameNo>"); sb.append("</Body>"); sb.append("</Packet>"); } System.out.println( (System.nanoTime()- nanoTime)/1000); nanoTime = System.nanoTime(); for (int i = 0; i < 1000; i++) { String vehicleFrameNo="LV3LD830473894821"; StringBuilder sb = new StringBuilder(); sb.append("<?xml version=\"1.0\" encoding=\"GBK\"?>"); sb.append("<Packet type=\"REQUEST\" version=\"1.0\">"); sb.append("<Head>"); sb.append("<RequestType>V020</RequestType>"); sb.append("</Head>"); sb.append("<Body>"); sb.append("<VehicleFrameNo>"); sb.append(vehicleFrameNo); sb.append("</VehicleFrameNo>"); sb.append("</Body>"); sb.append("</Packet>"); } System.out.println( (System.nanoTime()- nanoTime)/1000); } } <file_sep>/lsbasi/src/lsbasi/visit/NodeVisitor.java package lsbasi.visit; import java.util.List; import java.util.Map; import lsbasi.ast.AST; import lsbasi.ast.AssignmentAST; import lsbasi.ast.BinOpAST; import lsbasi.ast.NumberAST; import lsbasi.ast.StatementAST; import lsbasi.ast.StatementListAST; import lsbasi.ast.UnaryOpAST; import lsbasi.ast.VarAST; public class NodeVisitor { public static int visit(AST node, Map<String, Integer> scope) throws Exception { if (node instanceof NumberAST) { return NumberVisitor.visit((NumberAST) node); } else if (node instanceof BinOpAST) { return BinVisitor.visit((BinOpAST) node, scope); } else if (node instanceof UnaryOpAST) { return UnaryVisitor.visit((UnaryOpAST) node, scope); } else if (node instanceof VarAST) { return VarVisitor.visit((VarAST) node, scope); } throw new Exception("error"); } public static void visit(StatementListAST node, Map<String, Integer> scope) throws Exception { List<StatementAST> list = node.getList(); for (StatementAST statementAST : list) { visit(statementAST, scope); } } public static void visit(StatementAST node, Map<String, Integer> scope) throws Exception { if (node instanceof AssignmentAST) { AssignVisitor.visit((AssignmentAST) node, scope); } else if (node instanceof StatementListAST) { visit((StatementListAST) node, scope); } } public static int visit(AST node) throws Exception { return visit(node, null); } } <file_sep>/my-WEBSITE/1/11index.php <h1>Yfor</h1> <?php $mysql = new SaeMysql(); $sql = "SELECT * FROM `user` LIMIT 0,30"; $result = $mysql->getData( $sql ); foreach ($result as $row) { foreach ($row as $key=>$value) { echo $key."=>".$value."<br/>"; } echo "===================<br/>"; } $mysql->closeDb(); ?><file_sep>/test/src/data/AST.java package data; public abstract class AST { public abstract int visit(); public abstract String toLispStyle(); public abstract String toBackStyle(); } <file_sep>/lsbasi/src/lsbasi/visit/UnaryVisitor.java package lsbasi.visit; import java.util.Map; import lsbasi.Token; import lsbasi.TokenType; import lsbasi.ast.UnaryOpAST; public class UnaryVisitor { public static int visit(UnaryOpAST node, Map<String, Integer> scope) throws Exception { Token op = node.getOp(); if (op.getType() == TokenType.PLUS) { return NodeVisitor.visit(node.getValNode(), scope); } else { return 0 - NodeVisitor.visit(node.getValNode(), scope); } } } <file_sep>/test/src/data/json/JsonTokenType.java package data.json; public enum JsonTokenType { STRING, NUMBER, LEFTBRACKET, RIGHTBRACKET, LEFTbrace, RIGHTbrace, EOF,COMMA,COLON; // [ ] { , : } <file_sep>/README.md # SomeCode 1. [我的个人网站。](http://yfor.sinaapp.com/),会尽可能更新。 2. [简书](http://www.jianshu.com/users/239b78e02402/latest_articles) <file_sep>/lsbasi/src/lsbasi/ast/StatementListAST.java package lsbasi.ast; import java.util.LinkedList; import java.util.List; public class StatementListAST extends StatementAST { List<StatementAST> list; public List<StatementAST> getList() { return list; } public StatementListAST(StatementAST first) { super(); this.list = new LinkedList<>(); list.add(first); } public void add(StatementAST s) { list.add(s); } @Override public String toString() { return "StatementListAST [list=" + list + "]"; } } <file_sep>/lsbasi/src/lsbasi/visit/VarVisitor.java package lsbasi.visit; import java.util.Map; import lsbasi.ast.VarAST; public class VarVisitor { public static int visit(VarAST node, Map<String, Integer> scope) throws Exception { Integer integer = scope.get(node.id); if (integer != null) { return integer; } throw new Exception(node.id + "is undefined"); } } <file_sep>/test/README.md #一些测试的代码** ##平时的自由代码练习 +*一个简单控制台屏幕及格式化实现:os implementation +*几个多线程的测试:cs50 #还包括: +1.打印文件目录树的实现 +1.1 tree(cmd) +2.有一个解释器实现 +2.1 expr:term((plus|minus)term)* +2.2 term:facter((mul|div)factor)* +2.3factor:(plus|minus)*factor|Interger|lparen expr rparen +3.有一个简单json解释实现 1.[简单解释器!](https://github.com/rspivak/lsbasi) 2.[上面文章的中文翻译!](http://www.oschina.net/translate/lsbasi-part6) 其实主要是一些一直以来想实现的东西,基本都是网上抄的,由其他语言改写过来的,或者自己的想法试验结果。 <file_sep>/codeForReadBook/c/hello.c #include<stdio.h> int main(){ /** int start,stop,step; int c;float f; start =0,stop=300,step=20;c=start; while(c<stop){ f=(c-32)*5/9.0; printf("%d\t%f\n",c,f); c=c+step; } int ch; while((ch=getchar())!=EOF)putchar(ch); // ./a.out <hello.c >text printf("%d,%c\n",EOF,EOF); **/ int ch, chs=2,lines=0; while((ch=getchar())!=EOF){ if(ch=='\n')lines++; chs++; } printf("%dL\t%dC\n",lines,chs); printf("--------------------------\n"); } <file_sep>/lsbasi/src/lsbasi/Interpreter.java package lsbasi; import java.util.HashMap; import java.util.List; import java.util.Map; import lsbasi.ast.AST; import lsbasi.ast.StatementAST; import lsbasi.ast.StatementListAST; import lsbasi.visit.NodeVisitor; public class Interpreter { Parser parser; Map<String, Integer> GLOBAL_SCOPE = new HashMap<>(); public Interpreter(Parser parser) { this.parser = parser; } public Parser getParser() { return parser; } int eval() throws Exception { AST node = parser.parser(); int r = NodeVisitor.visit(node); return r; } void run() throws Exception { StatementListAST node = parser.parser(); NodeVisitor.visit(node, GLOBAL_SCOPE); } void debugger() throws Exception { StatementListAST node = parser.parser(); List<StatementAST> list = node.getList(); Debugger debugger = new Debugger(list, GLOBAL_SCOPE); debugger.debugger(); } } <file_sep>/misc/isdivablle3.js //不使用除法和模运算计算一个数是否被三整除 // 数字字符串的求和 "121" =>4 function sumofA(a) { sum = 0; for (var i = 0; i < a.length; i++) { sum += parseInt(a[i]) } return sum } function isd(n) { if (n < 10) { if (n == 3 || n == 6 || n == 9) return true else return false } else { return isd( sumofA( (n + '').split(''))) } } isd(20) isd(21) isd(210) //开始google的一个题目,可以用小学知识解决,也是一本树上的习题
ac98ec1312cfdf910acebec4fe01daf959bb77f2
[ "SQL", "Markdown", "JavaScript", "INI", "Java", "Python", "PHP", "C" ]
55
Markdown
yfor/SomeCode
f237409f5ac5ab7bb3dcd81b33e980826c6bf338
a8bb5ee50300b7f7219247736c25776a6fe0355e
refs/heads/master
<repo_name>kpate262/lab7<file_sep>/lab7.cpp #include "stdio.h" #include "iostream" struct Node{ int d; Node *next; }; void printL(Node *list){ Node *p = list; while(p != NULL){ printf("%d\n", p->d); p = p->next; } } int main(){ int i = 0; Node *list = new Node; list->d = i; list->next = NULL; Node *p = list; while(i != 5){ i++; Node *temp = new Node; temp->d = i; temp->next = NULL; p->next = temp; p = temp; temp = NULL; delete(temp); } printL(list); return 0; }
1e980d0140570107e88a6d805bc2b1aee367df57
[ "C++" ]
1
C++
kpate262/lab7
ec2858b99b29b68c25ed3b347d9b0aa7a209797d
747d9b6da60aaf5cc2debabb639993fe4b2b9429
refs/heads/master
<file_sep>package com.atguigu.redis; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; /** * @author MingYue * @create 2020-10-27 15:39 */ public class test2 { public static void main(String[] args) { JedisPool pool = new JedisPool("hadoop102", 6379); Jedis jedis = pool.getResource(); System.out.println(jedis.get("abc")); System.out.println("this is master"); System.out.println("11111"); pool.close(); } }
b71c314ae6314aa7fa5564b3d9652503c6092349
[ "Java" ]
1
Java
shilei9708/88888888
458355dc72f47f955b8385e1745bd6aa674bad5e
83f885c9ed8b8d3e4e83299894537419e399abde
refs/heads/master
<repo_name>jkrehm/todotxt-cli-addons<file_sep>/README.md ## Todo.txt Add-ons For using todotxt-cli, please see: [https://github.com/ginatrapani/todo.txt-cli](https://github.com/ginatrapani/todo.txt-cli). ### Reminders *Requirements* - Python 2.7+ - [Requests](http://docs.python-requests.org/en/latest/user/install/) This add-on allows you to schedule reminders of your todo items. You do this by including a date or a date/time with the item, using the format: [YYYY-MM-DD] or [YYYY-MM-DD HH:MI] where "hours" are in 24-hour time, e.g. (A) Destroy the Death Star +Rebellion [2012-12-21] or (C) Take out the trash @Home [2012-12-21 18:45] Note: If you do not include a time with the date, it will assume 8am (08:00). Notifications go out via: - [Push Bullet](https://www.pushbullet.com//) (requires API key) - [Pushover](https://pushover.net/) (requires API and user keys) The notification service configuration is set in the todo.cfg file, e.g. export API_TYPE="PUSHBULLET" export API_TOKEN="<PASSWORD>apikey" You call the add-on like so: todo.sh remind I have mine set as a [cron job](http://www.adminschoice.com/crontab-quick-reference) that runs every minute and sends the notifications as needed.<file_sep>/remind #!/usr/bin/env python # Script looks for [[date]] and if it finds it and it matches the # current minute, then it will send a notification to your devices. import json, os, re, requests from datetime import datetime, date, time todo_file = os.environ.get('TODO_FILE') api_type = os.environ.get('API_TYPE') api_token = os.environ.get('API_TOKEN') api_user = os.environ.get('API_USER') today = datetime.today() todayDt = str(today.date()) todayDttm = today.strftime('%Y-%m-%d %H:%M') f = open(todo_file) for line in f: m = re.search('\[(.*?)\]', line) if m is not None: dttm = m.group(1) # No time found, so assume 8am if dttm.find(':') == -1: dttm += ' 08:00' if dttm == todayDttm: if api_type == 'PUSHBULLET': r = requests.post('https://api.pushbullet.com/v2/pushes', data=json.dumps({ 'type' : 'note', 'title' : 'Reminder', 'body' : line }), auth=(api_token, ''), headers={'content-type' : 'application/json'}); elif api_type == 'PUSHOVER': r = requests.post('https://api.pushover.net/1/messages.json', data={ 'token' : api_token, 'user' : api_user, 'message' : line }); else: print 'Invalid API type specified' f.close()
f18f8ebd15f6edeb344e73247ecb64df066123bc
[ "Markdown", "Python" ]
2
Markdown
jkrehm/todotxt-cli-addons
bd696cfc66c7cff9a7abe462dc40a0c765a94a12
071c546cf1ef02a885ca22cf2fffd6eadb5785b4
refs/heads/master
<file_sep># K-means K-means Clusting Plot is only available for 2D data Initialize the cluster centers randomly <file_sep># -*- coding: utf-8 -*- """ Created on Tue Jun 13 09:34:33 2017 @author: wu """ import numpy import matplotlib.pyplot def main(): dataset=[] print("step1:loading data...") datasetfile=open(input("Enter the file path: "),'r')#raw clusting data for line in datasetfile: samplelist=line.strip().split() samplelist=map(float,samplelist)#str to float dataset.append(samplelist) dataset=numpy.mat(dataset) global num,dim,k num,dim=dataset.shape k=int(input("Enter the number of cluster: ")) maxiter=int(input("Enter the maximum number of iterations: ")) print("step2:clusting...") centers_result,clusterassignment_result=kmeans(dataset,maxiter) print("step3:show the clusting result...") if dim==2: showcluster(dataset,centers_result,clusterassignment_result) else: print("The dimension of data is too large to plot") def kmeans(dataset,maxiter): itercount=0 clusterassignment=numpy.zeros(num) clusterchange=True centers=initcenters(dataset) while clusterchange and itercount<maxiter: clusterchange=False itercount+=1 for i in range(num): dis2cen=distance2centers(dataset[i],centers) minindex=numpy.argmin(dis2cen) if clusterassignment[i]!=minindex: clusterchange=True clusterassignment[i]=minindex for j in range(k): pointsincenterk=dataset[numpy.nonzero(clusterassignment==j)] centers[j,:]=numpy.mean(pointsincenterk,axis=0) return centers,clusterassignment def initcenters(dataset): centers=numpy.zeros((k,dim)) for i in range(k): index=numpy.random.randint(0,num) centers[i]=dataset[index] print(centers) return centers def distance2centers(sample,centers): dis2cen=numpy.zeros(k) for i in range(k): dis2cen[i]=numpy.sqrt(numpy.sum(numpy.square(sample-centers[i,:]))) return dis2cen def showcluster(dataset,centers,clusterassignment): mark=['or','ob','og','om','oc','ok','ow','oy'] for i in range(num): markindex=int(clusterassignment[i]) matplotlib.pyplot.plot(dataset[i,0],dataset[i,1],mark[markindex]) for i in range(k): matplotlib.pyplot.plot(centers[i,0],centers[i,1],mark[i],markersize=17) matplotlib.pyplot.show() if __name__=="__main__": main()
23e17d4e3846d6ffa4d9083a8b0f52e69981dc1f
[ "Markdown", "Python" ]
2
Markdown
WuKongy/K-means
10e783da9d2221f359ecde343a6f1c38bac2b1d1
24c4a6a67f01a25a130cdf46c4db48614fcbef1e
refs/heads/master
<repo_name>uityh/Beginner-Project-Solutions<file_sep>/README.md # Beginner-Project-Solutions Just getting used to github <file_sep>/Hangman.py import random incorrect = 6 counter = 0 guessed_letters = [] guessed_words = [] correct_letters = [] words = ["happy", "small", "huge", "large","short","good","funny"] word = random.choice(words) word_length = list(word) for i in range(0,len(word)): correct_letters.append("_") print("\n") while(incorrect>-1): if(incorrect == 0): print("\n") print("You lose") print("The word was " + str(word)) break if(counter == len(word_length)): print("You've won!") break print("\n") print(correct_letters) print("\n") print("The incorrect words you have guessed: " + str(guessed_words)) print("\n") print("The incorrect letters you have guessed: " + str(guessed_letters)) print("You have " + str(incorrect) + " tries left\n") print("\n") guess = input("Do you want to guess a letter or the entire word?\n") if(guess == "word"): print("\n") guess_word = input("Guess the word\n") if(guess_word != word): print("Incorrect") guessed_words.append(guess_word) incorrect = incorrect - 1 else: print("Correct!") break elif(guess == "letter"): print("\n") letter = input("Guess the letter\n") if(word.count(letter) > 0): for i in range(0,len(word)): if(letter == word[i]): print("Correct") counter = counter + 1 correct_letters[i] = word[i] else: incorrect = incorrect - 1 guessed_letters.append(letter) print("\nIncorrect!") else: print("You didn't enter 'letter' or 'word'.") <file_sep>/pythagorean_checker.py print("Enter the values for each side of the triangle: ") one = "" two = "" three = "" while(one != "quit" and two != "quit" and three != "quit"): try: one = int(input("Enter a side: ")) two = int(input("Enter another side: ")) three = int(input("Enter the final side: ")) except ValueError: print("Invalid input") continue if(one ** 2 + two ** 2 == three ** 2): print("It is a triple!") elif(one ** 2 + three ** 2 == two ** 2): print("It is a triple!") elif(two ** 2 + three ** 2 == one ** 2): print("It is a triple!") else: print("Not a triple :(") continue <file_sep>/fib.py def fib(n): if(n == 1): return 1 if(n == 0): return 0 return fib(n-1) + fib(n-2) num = int(input("Enter the nth fib term: ")) print( str(fib(num)))
2290001131ca95051e2cdb2551bfb39bd6303345
[ "Markdown", "Python" ]
4
Markdown
uityh/Beginner-Project-Solutions
c8092715585bc4aebe26f1f391780168c4119d06
3d4bd0ef8d2ba67aaf0503d43972180394729852
refs/heads/master
<file_sep>package chess; import java.util.List; import tablebases.Tablebase; import com.google.common.collect.BiMap; import com.google.common.collect.EnumBiMap; /** * Algorithm generating random squares for pieces in the specified tablebase. * * @author Kestutis * */ public class RandomSquareGenerator { /** * Generates random squares for the pieces of the provided tablebase. * * @param tablebase * computerized database containing all possible legal chess * positions and their evaluations, given the set of specific * chess pieces * @return the bidirectional map from the pieces present in this chess * position, to the squares they occupy */ static BiMap<Piece, Square> generateRandomSquaresForPieces( Tablebase tablebase) { BiMap<Piece, Square> piecesWithSquares = EnumBiMap.create(Piece.class, Square.class); List<Piece> pieces = tablebase.getAllPieces(); MersenneTwisterFast numberGenerator = new MersenneTwisterFast(); Square randSquare = null; for (Piece piece : pieces) { do { if (piece.getPieceType() == PieceType.PAWN) { int pRand = numberGenerator.nextInt(Squares.PAWN_SQUARES .numberOfSquares()); randSquare = Squares.PAWN_SQUARES.getSquaresAsList().get( pRand); } else { int allRand = numberGenerator.nextInt(Squares.ALL_SQUARES .numberOfSquares()); randSquare = Squares.ALL_SQUARES.getSquaresAsList().get( allRand); } } while (piecesWithSquares.containsValue(randSquare)); piecesWithSquares.put(piece, randSquare); } return piecesWithSquares; } } <file_sep>package chess.patterns; import java.util.Set; import tablebases.TablebaseWithSTM; /** * An idea in chess that can be comprehended and used by a chess player. * * @author Kestutis * */ interface ChessConcept { /** * Generates all the chess patterns for this concept, given the tablebase * with the side-to-move. * * @param tablebaseWithStm * the tablebase positions with the specified side-to-move only * @return the set of patterns relevant to the combination of this chess * concept, tablebase, and the side-to-move */ abstract Set<ChessPattern> generateChessPatterns(TablebaseWithSTM tablebaseWithStm); @Override abstract String toString(); } <file_sep>package chess.patterns; import chess.ChessPosition; /** * Chess pattern concerned with one chess entity (the "controller") being able * to control another chess entity (the "controllable). * * @author Kestutis * */ public class ControlPattern implements ChessPattern { /** The chess entity that is able to control some other (controllable) chess entity. */ private ControllerEntity controller; /** The chess entity that can be under control by some other (controller) chess entity. */ private ControllableEntity controllable; /** The name of this pattern. */ private String name; /** * Instantiates a new control pattern. * * @param controller * the chess entity that is able to control some other * (controllable) chess entity * @param controllable * the chess entity that can be under control by some other * (controller) chess entity * @param name * the String representation of this pattern */ ControlPattern(ControllerEntity controller, ControllableEntity controllable, String name) { this.controller = controller; this.controllable = controllable; this.name = name; } @Override public boolean isPresent(ChessPosition chessPosition) { return controller.getControlSquares(chessPosition) .containsAll( controllable.getControllableSquares(chessPosition)); } @Override public String toString() { return name; } } <file_sep>package tablebases.gaviotaTablebases; import chess.ChessPositionEvaluation; import chess.ChessPositionEvaluation.ChessPositionEvaluationWithDTM; /** * Container for the native methods used to initialize and probe the Gaviota * tablebases. * * @author Kestutis * */ public class GaviotaTablebasesLibrary { static { try { System.loadLibrary("GaviotaTablebasesProbingAPI"); } catch (Exception e) { System.out.println("GaviotaTablebasesProbingAPI could not be loaded."); e.printStackTrace(); } } /** * Prepares the Gaviota tablebases API for probing. * * @param path * full path to the directory where tablebases are located. If * there are multiple paths, separate them with semicolons, for * example, "C:/tablebases/path1;C:/tablebases/path2" */ public static native void initializeGaviotaTablebases(String path); /** * Queries the Gaviota tablebases for the game-theoretical result * ("White wins" / "Black wins" / "Draw" / "Illegal position") only. * * @param sideToMove * - integer corresponding to one of the TB_return_values in the * the Gaviota Tablebases API * @param enpassantSquare * - integer corresponding to one of the TB_squares in the the * Gaviota Tablebases API * @param castlingOption * - integer corresponding to one of the TB_castling options in * the the Gaviota Tablebases API * @param whiteSquares * - integer array corresponding to the array of TB_squares in * the the Gaviota Tablebases API * @param blackSquares * - integer array corresponding to the array of TB_squares in * the the Gaviota Tablebases API * @param whitePieces * - byte array corresponding to the array of TB_pieces in the * the Gaviota Tablebases API * @param blackPieces * - byte array corresponding to the array of TB_pieces in the * the Gaviota Tablebases API * @return the game-theoretical value of the chess position obtained from * the tablebases */ public static native ChessPositionEvaluation queryGaviotaTablebasesForResultOnly( int sideToMove, int enpassantSquare, int castlingOption, int[] whiteSquares, int[] blackSquares, byte[] whitePieces, byte[] blackPieces); /** * Queries the Gaviota tablebases for the game-theoretical result * ("White wins" / "Black wins" / "Draw" / "Illegal position"), and the * distance-to-mate information. * * @param sideToMove * - integer corresponding to one of the TB_return_values in the * the Gaviota Tablebases API * @param enpassantSquare * - integer corresponding to one of the TB_squares in the the * Gaviota Tablebases API * @param castlingOption * - integer corresponding to one of the TB_castling options in * the the Gaviota Tablebases API * @param whiteSquares * - integer array corresponding to the array of TB_squares in * the the Gaviota Tablebases API * @param blackSquares * - integer array corresponding to the array of TB_squares in * the the Gaviota Tablebases API * @param whitePieces * - byte array corresponding to the array of TB_pieces in the * the Gaviota Tablebases API * @param blackPieces * - byte array corresponding to the array of TB_pieces in the * the Gaviota Tablebases API * @return the game-theoretical value of the chess position obtained from * the tablebases, and the distance to mate (a non-negative number * in case the evaluation is "White wins" / "Black wins", zero * otherwise) */ public static native ChessPositionEvaluationWithDTM queryGaviotaTablebasesForResultAndDistanceToMate( int sideToMove, int enpassantSquare, int castlingOption, int[] whiteSquares, int[] blackSquares, byte[] whitePieces, byte[] blackPieces); }<file_sep>package tablebases; import java.util.ArrayList; import java.util.List; import chess.Piece; import chess.PieceColour; import chess.PieceType; /** * Computerized database containing all possible legal chess positions and their * evaluations, given the set of specific chess pieces. * * @author Kestutis * */ public enum Tablebase { KK(0, 0), KRK(175168, 223944), KPK(163328, 168024), KRKR(10780728, 10780728), KRKP(8100040, 9963008), KRPK(7877172, 10249464), KRPKR(476609388, 490095548) // TODO all the remaining tablebases ; /** The number of white-to-move positions in this tablebase. */ private final long totalWhiteToMovePositions; /** The number of black-to-move positions in this tablebase. */ private final long totalBlackToMovePositions; /** * Instantiates a new tablebase. * * @param wCount * the number of white-to-move positions in this tablebase * @param bCount * the number of black-to-move positions in this tablebase */ private Tablebase(long wCount, long bCount) { totalWhiteToMovePositions = wCount; totalBlackToMovePositions = bCount; } /** * Gets the total of white-to-move positions in this tablebase. * * @return the number of white-to-move positions in the tablebase */ public long getWhiteToMovePositionCount() { return totalWhiteToMovePositions; } /** * Gets the total of black-to-move positions in this tablebase. * * @return the number of black-to-move positions in the tablebase */ public long getBlackToMovePositionCount() { return totalBlackToMovePositions; } /** * Gets all the White pieces that are present in the chess positions * contained in this tablebase. * * @return the list of White pieces for this tablebase */ public List<Piece> getWhitePieces() { char[] whitePiecesAsChars = getPiecesAsCharsFromTablebase(PieceColour.WHITE); List<Piece> whitePieces = new ArrayList<Piece>(); whitePieces = convertCharsToPieces(whitePiecesAsChars, PieceColour.WHITE); return whitePieces; } /** * Gets the pieces as characters from this tablebase. <br/> <br/> * * Tablebases' names consist of lists of upper-case letters, corresponding * to the abbreviations of abstract pieces. The White pieces are listed * first, and followed by the Black pieces; also, for both sides, pieces are * listed from the relatively most valuable piece - King, to the least * valuable - Pawn. Thus this method splits the tablebase's name into two * substrings, and returns the one that corresponds to the specified piece * colour. * * @param pieceColour * the chess piece colour - either White, or Black * @return the array of chars, each char representing a piece type. E.g., * 'K' for King, 'Q' for Queen, etc. */ protected char[] getPiecesAsCharsFromTablebase(PieceColour pieceColour) { String tablebaseName = this.name(); return extractCharsFromTablebaseName(pieceColour, tablebaseName); } /** * Extracts characters from this tablebase's name, representing the pieces * of the specified colour. * * @param pieceColour * the chess piece colour - either White, or Black * @param tablebaseName * the tablebase's name as a String object * @return the array of chars, each char representing a piece type. E.g., * 'K' for King, 'Q' for Queen, etc. */ private char[] extractCharsFromTablebaseName(PieceColour pieceColour, String tablebaseName) { int blackKingsIndex = tablebaseName.lastIndexOf("K"); return pieceColour == PieceColour.WHITE ? tablebaseName.substring(0, blackKingsIndex).toCharArray() : tablebaseName.substring(blackKingsIndex).toCharArray(); } /** * Converts characters, representing the pieces, to pieces of the specified * colour. * * @param piecesAsChars * the character array, representing the pieces * @param pieceColour * the chess piece colour - either White, or Black * @return the list of pieces corresponding to the provided characters */ protected static List<Piece> convertCharsToPieces(char[] piecesAsChars, PieceColour pieceColour) { List<Piece> pieces = new ArrayList<Piece>(); String pieceCol = pieceColour.name(); for (int i = 0; i < piecesAsChars.length; i++) { char ch = piecesAsChars[i]; String pieceName = pieceCol; pieceName += "_"; pieceName += PieceType.getPieceTypeFromAbbreviation(ch).name(); int consequtiveDuplicateCharsInArrayUpToIndex = getConsequtiveDuplicateCharsInArrayUpToIndex(piecesAsChars, i); if (consequtiveDuplicateCharsInArrayUpToIndex > 1) { pieceName += "_"; pieceName += consequtiveDuplicateCharsInArrayUpToIndex; } pieces.add(Piece.valueOf(pieceName)); } return pieces; } /** * Gets the consequtive duplicate characters in the character array, * starting at the specified index, and going backwards. * * @param chars * the character array * @param index * the index in the array * @return the number of the consequtive duplicate characters in the array * up to (and including) the specified index */ protected static int getConsequtiveDuplicateCharsInArrayUpToIndex( char[] chars, int index) { if (index == 0) return 1; int count = 1; for (int j = index-1; chars[index] == chars[j] && j >= 0; j--) { count++; } return count; } /** * Gets all the Black pieces that are present in the chess positions * contained in this tablebase. * * @return the list of Black pieces for this tablebase */ public List<Piece> getBlackPieces() { char[] blackPiecesAsChars = getPiecesAsCharsFromTablebase(PieceColour.BLACK); List<Piece> blackPieces = new ArrayList<Piece>(); blackPieces = convertCharsToPieces(blackPiecesAsChars, PieceColour.BLACK); return blackPieces; } /** * Gets all the pieces (White followed by Black) that are present in the * chess positions contained in this tablebase. * * @return the list of all the pieces for this tablebase */ public List<Piece> getAllPieces() { List<Piece> allPieces = new ArrayList<Piece>(); allPieces.addAll(getWhitePieces()); allPieces.addAll(getBlackPieces()); return allPieces; } /** * Removes the specified piece from this tablebase. This results in the new * tablebase, with the same pieces as the original tablebase, except the * removed piece. * * @param piece * the representation of the chess piece * @return the tablebase obtained by removing the specified piece from this * tablebase */ public Tablebase removePiece(Piece piece) { if (piece.getPieceType() == PieceType.KING) throw new IllegalArgumentException("Cannot remove " + piece); char ch = piece.getPieceType().getPieceTypeAbbreviation(); char kingCh = PieceType.KING.getPieceTypeAbbreviation(); String oldTB = this.name(); String newTB = oldTB; if (piece.getPieceColour() == PieceColour.WHITE) { for (int i = 1; oldTB.charAt(i) != kingCh; i++) { if (oldTB.charAt(i) == ch) { newTB = deleteCharAt(oldTB, i); break; } } } else for (int i = oldTB.length() - 1; oldTB.charAt(i) != kingCh; i--) { if (oldTB.charAt(i) == ch) { newTB = deleteCharAt(oldTB, i); break; } } if (!whitePiecesAreRelativelyMoreValuableThanBlackPiecesIn(newTB)) newTB = reverseWhiteAndBlackPieces(newTB); return valueOf(newTB); } /** * Deletes the character from the String at the specified position. * * @param originalString * the specified String * @param index * the position in the originalString (the first character in the * originalString is at position zero) * @return the new String object, obtained by removing one character from * the originalString */ private String deleteCharAt(String originalString, int index) { StringBuffer buf = new StringBuffer(originalString.length() - 1); buf.append(originalString.substring(0, index)).append(originalString.substring(index + 1)); return buf.toString(); } /** * Determines if the White pieces are relatively more valuable than the * Black pieces in the provided String, that represents the (potential) * tablebase name. <br/> <br/> * * By convention, White pieces are relatively more valuable in tablebases. * For example, there is no tablebase KPKQ ("White King + White Pawn vs. * Black King + Black Queen"), since the Queen is relatively more valuable * than the Pawn - instead the KQKP tablebase is used and the chessboard * symmetry is exploited. * * @param tablebaseName * the name of the potential tablebase * @return true, if the White pieces <b>are</b> relatively more valuable * than the Black ones */ private boolean whitePiecesAreRelativelyMoreValuableThanBlackPiecesIn( String tablebaseName) { char[] whitePiecesAsChars = extractCharsFromTablebaseName( PieceColour.WHITE, tablebaseName); char[] blackPiecesAsChars = extractCharsFromTablebaseName( PieceColour.BLACK, tablebaseName); int whitePiecesCount = whitePiecesAsChars.length; int blackPiecesCount = blackPiecesAsChars.length; int smallerOrEqualOfWhitePiecesCountAndBlackPiecesCount = whitePiecesCount < blackPiecesCount ? whitePiecesCount : blackPiecesCount; for (int i = 1 /* both 0th elements are Kings */; i < smallerOrEqualOfWhitePiecesCountAndBlackPiecesCount; i++) { char whitePieceAbbreviation = whitePiecesAsChars[i]; char blackPieceAbbreviation = blackPiecesAsChars[i]; PieceType whitePc = PieceType.getPieceTypeFromAbbreviation(whitePieceAbbreviation); PieceType blackPc = PieceType.getPieceTypeFromAbbreviation(blackPieceAbbreviation); if (whitePc.ordinal() < blackPc.ordinal()) return true; if (whitePc.ordinal() > blackPc.ordinal()) return false; } return whitePiecesCount >= blackPiecesCount ? true : false; } /** * Reverses the substrings representing the White and Black pieces in the * specified String. * * @param tablebaseName * the String representing the tablebase name * @return the new String, obtained by switching the characters representing * the White pieces, and the characters representing the Black * pieces */ private String reverseWhiteAndBlackPieces(String tablebaseName) { char[] whitePiecesAsChars = extractCharsFromTablebaseName( PieceColour.WHITE, tablebaseName); char[] blackPiecesAsChars = extractCharsFromTablebaseName( PieceColour.BLACK, tablebaseName); return new String(blackPiecesAsChars) + new String (whitePiecesAsChars); } /* (non-Javadoc) * @see java.lang.Enum#toString() */ @Override public String toString() { List<Piece> whitePieces = getWhitePieces(); List<Piece> blackPieces = getBlackPieces(); String output = ""; output += whitePieces.get(0).getPieceType().name(); for (int i = 1; i < whitePieces.size(); i++) { output += " + "; output += whitePieces.get(i).getPieceType().name(); } output += " vs. "; output += blackPieces.get(0).getPieceType().name(); for (int i = 1; i < blackPieces.size(); i++) { output += " + "; output += blackPieces.get(i).getPieceType().name(); } return output; } }<file_sep>package chess.patterns; import static org.junit.Assert.*; import java.util.HashSet; import java.util.Set; import org.junit.Test; import chess.SideToMove; import tablebases.Tablebase; import tablebases.TablebaseWithSTM; public class ControlConceptTest { @Test public void test_PieceControllingPiecePatternGeneration_ForKpkTablebase() { TablebaseWithSTM tablebaseWithStm = new TablebaseWithSTM(Tablebase.KPK, SideToMove.BLACK); Set<String> expectedPatternNames = new HashSet<>(); expectedPatternNames.add("WHITE_KING defends WHITE_PAWN"); expectedPatternNames.add("BLACK_KING attacks WHITE_PAWN"); expectedPatternNames.add("WHITE_PAWN attacks BLACK_KING"); Set<ChessPattern> patterns = ControlConcept.PIECE_CONTROLS_PIECE .generateChessPatterns(tablebaseWithStm); Set<String> actualPatternNames = new HashSet<>(); for (ChessPattern cp : patterns) { actualPatternNames.add(cp.toString()); } assertEquals(expectedPatternNames, actualPatternNames); } } <file_sep>Endgame-Oracle ============== A program to experiment with chess endgame tablebases and machine learning algorithms. The ultimate goal is to develop an "intelligent" chess endgame engine, that would mainly rely on symbolic strategies, rules and patterns, rather than brute-force algorithms.<file_sep>package chess; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.junit.Before; import org.junit.Test; import com.google.common.collect.BiMap; import com.google.common.collect.EnumBiMap; import tablebases.Tablebase; public class ChessPositionTest { private ChessPosition mockedChessPosition; private ChessPosition chessPositionFromKRPKR, chessPositionFromKBNKPPP; @Before public void setUp() throws Exception { mockedChessPosition = mock(ChessPosition.class); List<Square> squaresKRPKR = new ArrayList<Square>(); squaresKRPKR.add(Square.E5); squaresKRPKR.add(Square.E3); squaresKRPKR.add(Square.D5); squaresKRPKR.add(Square.H8); squaresKRPKR.add(Square.D1); chessPositionFromKRPKR = ChessPosition.createFromTablebase( Tablebase.KRPKR, squaresKRPKR, SideToMove.WHITE); BiMap<Piece, Square> piecesWithSquaresKBNKPPP = EnumBiMap.create(Piece.class, Square.class); piecesWithSquaresKBNKPPP.put(Piece.WHITE_KING, Square.A3); piecesWithSquaresKBNKPPP.put(Piece.WHITE_BISHOP, Square.E5); piecesWithSquaresKBNKPPP.put(Piece.WHITE_KNIGHT, Square.E3); piecesWithSquaresKBNKPPP.put(Piece.BLACK_KING, Square.G2); piecesWithSquaresKBNKPPP.put(Piece.BLACK_PAWN, Square.H4); piecesWithSquaresKBNKPPP.put(Piece.BLACK_PAWN_2, Square.H3); piecesWithSquaresKBNKPPP.put(Piece.BLACK_PAWN_3, Square.G6); chessPositionFromKBNKPPP = ChessPosition.createFromPiecesToSquaresBiMap( piecesWithSquaresKBNKPPP, SideToMove.BLACK); } @Test public void testGetPiecesAndSquaresMap() { mockedChessPosition.getPiecesWithSquares(); verify(mockedChessPosition).getPiecesWithSquares(); } @Test(expected = IllegalArgumentException.class) public void testGetSquaresToPiecesMapThrowsIllegalArgumentException() { List<Square> squares2 = new ArrayList<Square>(); squares2.add(Square.E5); squares2.add(Square.E5); squares2.add(Square.D5); squares2.add(Square.H8); squares2.add(Square.D1); ChessPosition chessPositionFromTbDuplicateSquares = ChessPosition.createFromTablebase( Tablebase.KRPKR, squares2, SideToMove.WHITE); Map<Piece,Square> actualMap = chessPositionFromTbDuplicateSquares.getPiecesWithSquares(); assertEquals(5, actualMap.keySet().size()); } @Test(expected = IllegalArgumentException.class) public void testGetPiecesToSquaresThrowsIllegalArgumentException() { List<Square> squares3 = new ArrayList<Square>(); squares3.add(Square.E3); squares3.add(Square.D5); squares3.add(Square.H8); squares3.add(Square.D1); ChessPosition chessPositionFromTbTooFewSquares = ChessPosition.createFromTablebase( Tablebase.KRPKR, squares3, SideToMove.WHITE); Map<Piece,Square> actualMap = chessPositionFromTbTooFewSquares.getPiecesWithSquares(); assertEquals(4, actualMap.keySet().size()); } @Test public void testGetWhitePieces() { List<Piece> expectedWhitePiecesKRPKR = new ArrayList<Piece>(); expectedWhitePiecesKRPKR.add(Piece.WHITE_KING); expectedWhitePiecesKRPKR.add(Piece.WHITE_ROOK); expectedWhitePiecesKRPKR.add(Piece.WHITE_PAWN); List<Piece> actualWhitePiecesKRPKR = chessPositionFromKRPKR.getWhitePieces(); assertEquals(expectedWhitePiecesKRPKR, actualWhitePiecesKRPKR); List<Piece> expectedWhitePiecesKBNKPPP = new ArrayList<Piece>(); expectedWhitePiecesKBNKPPP.add(Piece.WHITE_KING); expectedWhitePiecesKBNKPPP.add(Piece.WHITE_BISHOP); expectedWhitePiecesKBNKPPP.add(Piece.WHITE_KNIGHT); List<Piece> actualWhitePiecesKBNKPPP = chessPositionFromKBNKPPP.getWhitePieces(); assertEquals(expectedWhitePiecesKBNKPPP, actualWhitePiecesKBNKPPP); } @Test public void testGetBlackPieces() { List<Piece> expectedBlackPiecesKRPKR = new ArrayList<Piece>(); expectedBlackPiecesKRPKR.add(Piece.BLACK_KING); expectedBlackPiecesKRPKR.add(Piece.BLACK_ROOK); List<Piece> actualBlackPiecesKRPKR = chessPositionFromKRPKR.getBlackPieces(); assertEquals(expectedBlackPiecesKRPKR, actualBlackPiecesKRPKR); List<Piece> expectedBlackPiecesKBNKPPP = new ArrayList<Piece>(); expectedBlackPiecesKBNKPPP.add(Piece.BLACK_KING); expectedBlackPiecesKBNKPPP.add(Piece.BLACK_PAWN); expectedBlackPiecesKBNKPPP.add(Piece.BLACK_PAWN_2); expectedBlackPiecesKBNKPPP.add(Piece.BLACK_PAWN_3); List<Piece> actualBlackPiecesKBNKPPP = chessPositionFromKBNKPPP.getBlackPieces(); assertEquals(expectedBlackPiecesKBNKPPP, actualBlackPiecesKBNKPPP); } @Test public void testGetWhiteSquares() { List<Square> expectedWhiteSquaresKRPKR = new ArrayList<Square>(); expectedWhiteSquaresKRPKR.add(Square.E5); expectedWhiteSquaresKRPKR.add(Square.E3); expectedWhiteSquaresKRPKR.add(Square.D5); List<Square> actualWhiteSquaresKRPKR = chessPositionFromKRPKR.getWhiteSquares(); assertEquals(expectedWhiteSquaresKRPKR, actualWhiteSquaresKRPKR); List<Square> expectedWhiteSquaresKBNKPPP = new ArrayList<Square>(); expectedWhiteSquaresKBNKPPP.add(Square.A3); expectedWhiteSquaresKBNKPPP.add(Square.E5); expectedWhiteSquaresKBNKPPP.add(Square.E3); List<Square> actualWhiteSquaresKBNKPPP = chessPositionFromKBNKPPP.getWhiteSquares(); assertEquals(expectedWhiteSquaresKBNKPPP, actualWhiteSquaresKBNKPPP); } @Test public void testGetBlackSquares() { List<Square> expectedBlackSquaresKRPKR = new ArrayList<Square>(); expectedBlackSquaresKRPKR.add(Square.H8); expectedBlackSquaresKRPKR.add(Square.D1); List<Square> actualBlackSquaresKRPKR = chessPositionFromKRPKR.getBlackSquares(); assertEquals(expectedBlackSquaresKRPKR, actualBlackSquaresKRPKR); List<Square> expectedBlackSquaresKBNKPPP = new ArrayList<Square>(); expectedBlackSquaresKBNKPPP.add(Square.G2); expectedBlackSquaresKBNKPPP.add(Square.G6); expectedBlackSquaresKBNKPPP.add(Square.H3); expectedBlackSquaresKBNKPPP.add(Square.H4); List<Square> actualBlackSquaresKBNKPPP = chessPositionFromKBNKPPP.getBlackSquares(); assertEquals(expectedBlackSquaresKBNKPPP, actualBlackSquaresKBNKPPP); } @Test public void testCreateFromTextualDrawing() throws IncorrectChessDiagramDrawingException { String drawing = " _______________________________________________________ \n" + " | | | | | | | | | \n" + " 8| | | | | | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 7| | | | | | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 6| | | | | | | BP3 | | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 5| | | | | WB | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 4| | | | | | | | BP | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 3| WK | | | | WN | | | BP2 | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 2| | | | | | | BK | | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 1| | | | | | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " a b c d e f g h \n" ; ChessPositionDiagram cpDiagram = ChessPositionDiagram.createFromTextDiagram(drawing); ChessPosition chessPosition = ChessPosition .createFromTextualDrawing(cpDiagram, SideToMove.BLACK); List<Piece> expectedWhitePieces = new ArrayList<Piece>(); expectedWhitePieces.add(Piece.WHITE_KING); expectedWhitePieces.add(Piece.WHITE_BISHOP); expectedWhitePieces.add(Piece.WHITE_KNIGHT); List<Piece> actualWhitePieces = chessPosition.getWhitePieces(); assertEquals(expectedWhitePieces, actualWhitePieces); List<Square> expectedBlackSquares = new ArrayList<Square>(); expectedBlackSquares.add(Square.G2); expectedBlackSquares.add(Square.G6); expectedBlackSquares.add(Square.H3); expectedBlackSquares.add(Square.H4); List<Square> actualBlackSquares = chessPosition.getBlackSquares(); assertEquals(expectedBlackSquares, actualBlackSquares); } @Test(expected = IncorrectChessDiagramDrawingException.class) public void testCreateFromTextDiagramThrowsIncorrectChessDiagramDrawingException() throws IncorrectChessDiagramDrawingException, InterruptedException { String incorrectDrawingWithTheTopShiftedOnePositionToTheRight = " _______________________________________________________ \n" + " | | | | | | | | | \n" + " 8| | | | | | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 7| | | | | | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 6| | | | | | | BP3 | | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 5| | | | | WB | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 4| | | | | | | | BP | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 3| WK | | | | WN | | | BP2 | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 2| | | | | | | BK | | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 1| | | | | | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " a b c d e f g h \n" ; ChessPositionDiagram cpDiagram = ChessPositionDiagram.createFromTextDiagram( incorrectDrawingWithTheTopShiftedOnePositionToTheRight); cpDiagram.wait(); } @Test public void testIfContainsPiece() throws IncorrectChessDiagramDrawingException { String drawing = " _______________________________________________________ \n" + " | | | | | | | | | \n" + " 8| | | | | | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 7| | | | | | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 6| | | | | | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 5| | | | | WB | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 4| | | | | | | | BP | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 3| WK | | | | WN | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 2| | | | | | | BK | | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 1| | | | | | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " a b c d e f g h \n" ; ChessPositionDiagram cpDiagram = ChessPositionDiagram.createFromTextDiagram(drawing); ChessPosition chessPosition = ChessPosition .createFromTextualDrawing(cpDiagram, SideToMove.BLACK); assertTrue(chessPosition.containsPiece(Piece.BLACK_KING)); assertTrue(chessPosition.containsPiece(Piece.WHITE_KNIGHT)); assertFalse(chessPosition.containsPiece(Piece.BLACK_QUEEN)); assertFalse(chessPosition.containsPiece(Piece.WHITE_ROOK_2)); } @Test public void testGetSquareOfPiece() throws IncorrectChessDiagramDrawingException { String drawing = " _______________________________________________________ \n" + " | | | | | | | | | \n" + " 8| BK | | | | | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 7| | | | | | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 6| | | | | | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 5| | | | WB | WB2 | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 4| | | | | | | | BP | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 3| WK | | | | | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 2| | | | | | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 1| | | | | | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " a b c d e f g h \n" ; ChessPositionDiagram cpDiagram = ChessPositionDiagram.createFromTextDiagram(drawing); ChessPosition chessPosition = ChessPosition .createFromTextualDrawing(cpDiagram, SideToMove.BLACK); Square expectedSquareOfWhiteBishop = Square.D5; Square expectedSquareOfWhiteBishop2 = Square.E5; Square expectedSquareOfBlacKing = Square.A8; Square actualSquareOfWhiteBishop = chessPosition.getSquareOfPiece(Piece.WHITE_BISHOP); Square actualSquareOfWhiteBishop2 = chessPosition.getSquareOfPiece(Piece.WHITE_BISHOP_2); Square actualSquareOfBlacKing = chessPosition.getSquareOfPiece(Piece.BLACK_KING); assertEquals(expectedSquareOfWhiteBishop, actualSquareOfWhiteBishop); assertEquals(expectedSquareOfWhiteBishop2, actualSquareOfWhiteBishop2); assertEquals(expectedSquareOfBlacKing, actualSquareOfBlacKing); } @Test public void testGetAllPieces() throws IncorrectChessDiagramDrawingException { String drawing = " _______________________________________________________ \n" + " | | | | | | | | | \n" + " 8| | | | | | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 7| | | | | WK | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 6| | | | | | | | WR | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 5| | | | WB | WB2 | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 4| | | | | | | | BP | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 3| | | | | | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 2| | | | | BK | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 1| | | | | | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " a b c d e f g h \n" ; ChessPositionDiagram cpDiagram = ChessPositionDiagram.createFromTextDiagram(drawing); ChessPosition chessPosition = ChessPosition .createFromTextualDrawing(cpDiagram, SideToMove.BLACK); List<Piece> expectedPieces = new ArrayList<>(); expectedPieces.add(Piece.WHITE_KING); expectedPieces.add(Piece.WHITE_ROOK); expectedPieces.add(Piece.WHITE_BISHOP); expectedPieces.add(Piece.WHITE_BISHOP_2); expectedPieces.add(Piece.BLACK_KING); expectedPieces.add(Piece.BLACK_PAWN); List<Piece> actualPieces = chessPosition.getAllPieces(); assertEquals(expectedPieces, actualPieces); } @Test public void testEqualityOfTwoPositions() throws IncorrectChessDiagramDrawingException { String drawing1 = " _______________________________________________________ \n" + " | | | | | | | | | \n" + " 8| | | | | | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 7| | | | | WK | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 6| | | | | | | | WR | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 5| | | | | | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 4| | | | | | | | BR | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 3| | | | | | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 2| | | | | BK | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 1| | | | | | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " a b c d e f g h \n" ; ChessPositionDiagram cpDiagram1 = ChessPositionDiagram.createFromTextDiagram(drawing1); ChessPosition chessPosition1 = ChessPosition .createFromTextualDrawing(cpDiagram1, SideToMove.BLACK); String drawing2 = " _______________________________________________________ \n" + " | | | | | | | | | \n" + " 8| | | | | | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 7| | | | | WK | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 6| | | | | | | | WR | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 5| | | | | | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 4| | | | | | | | BR | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 3| | | | | | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 2| | | | | BK | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 1| | | | | | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " a b c d e f g h \n" ; ChessPositionDiagram cpDiagram2 = ChessPositionDiagram.createFromTextDiagram(drawing2); ChessPosition chessPosition2 = ChessPosition .createFromTextualDrawing(cpDiagram2, SideToMove.BLACK); String drawing3 = " _______________________________________________________ \n" + " | | | | | | | | | \n" + " 8| | | | | | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 7| | | | | WK | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 6| | | | | | | | WR | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 5| | | | | | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 4| | | | | | | | BR | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 3| | | | | | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 2| | | | | BK | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 1| | | | | | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " a b c d e f g h \n" ; ChessPositionDiagram cpDiagram3 = ChessPositionDiagram.createFromTextDiagram(drawing3); ChessPosition chessPosition3 = ChessPosition .createFromTextualDrawing(cpDiagram3, SideToMove.WHITE); String drawing4 = " _______________________________________________________ \n" + " | | | | | | | | | \n" + " 8| | | | | | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 7| | | | | WK | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 6| | | | | | | | WR | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 5| | BP3 | BP2 | BP | | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 4| | | | | | | | WR2 | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 3| | WP | WP3 | WP2 | | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 2| | | | | BK | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 1| | | | | | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " a b c d e f g h \n" ; ChessPositionDiagram cpDiagram4 = ChessPositionDiagram.createFromTextDiagram(drawing4); ChessPosition chessPosition4 = ChessPosition .createFromTextualDrawing(cpDiagram4, SideToMove.BLACK); String drawing5 = " _______________________________________________________ \n" + " | | | | | | | | | \n" + " 8| | | | | | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 7| | | | | WK | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 6| | | | | | | | WR2 | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 5| | BP2 | BP3 | BP | | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 4| | | | | | | | WR | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 3| | WP2 | WP3 | WP | | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 2| | | | | BK | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " | | | | | | | | | \n" + " 1| | | | | | | | | \n" + " |______|______|______|______|______|______|______|______| \n" + " a b c d e f g h \n" ; ChessPositionDiagram cpDiagram5 = ChessPositionDiagram.createFromTextDiagram(drawing5); ChessPosition chessPosition5 = ChessPosition .createFromTextualDrawing(cpDiagram5, SideToMove.BLACK); assertTrue(chessPosition1.equals(chessPosition2)); assertFalse(chessPosition1.equals(chessPosition3)); assertFalse(chessPosition1.equals(chessPosition4)); assertTrue(chessPosition4.equals(chessPosition5)); } } <file_sep>package chess; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; import java.util.Set; /** * Set of chessboard squares. Useful when only a subset of the 64 squares (i.e., * not necessarily all of them) is needed. * * @author Kestutis * */ public enum Squares { /** The set of all 64 chessboard squares. */ ALL_SQUARES, /** * In chess positions containing pawns, possible squares for the White King * can be limited to the left side of the chessboard (32 squares in total), * in order to exploit the chessboard symmetry in the d-e axis. */ WHITE_KING_SQUARES_FOR_POSITIONS_WITH_PAWNS, /** * In chess positions containing no pawns, possible squares for the White * King can be limited to the a1-d1-d4 triangle of the chessboard, in order * to exploit the horizontal reflection (symmetry in file d - file e axis), * vertical reflection (symmetry in rank 4 - rank 5 axis), and diagonal * reflection (symmetry in diagonal a1-h8). */ WHITE_KING_SQUARES_FOR_PAWNLESS_POSITIONS, /** Possible squares for the pawns are all squares on ranks 2 to 7. */ PAWN_SQUARES, /** Squares A1, B2, C3, ..., H8. */ DIAGONAL_A1_H8, /** Chessboard squares above diagonal A1-H8. */ SQUARES_ABOVE_DIAGONAL_A1_H8 ; /** * Collects the set of squares and returns it as a list. (Conversion to list * is useful, as some client classes need to pick squares randomly). * * @return list of different squares */ public Set<Square> collectSquares() { switch (this) { case ALL_SQUARES: return EnumSet.allOf(Square.class); case WHITE_KING_SQUARES_FOR_POSITIONS_WITH_PAWNS: EnumSet<Square> whiteKingSquaresForPositionsWithPawns = EnumSet.range( Square.A1, Square.D1); whiteKingSquaresForPositionsWithPawns.addAll(EnumSet.range( Square.A2, Square.D2)); whiteKingSquaresForPositionsWithPawns.addAll(EnumSet.range( Square.A3, Square.D3)); whiteKingSquaresForPositionsWithPawns.addAll(EnumSet.range( Square.A4, Square.D4)); whiteKingSquaresForPositionsWithPawns.addAll(EnumSet.range( Square.A5, Square.D5)); whiteKingSquaresForPositionsWithPawns.addAll(EnumSet.range( Square.A6, Square.D6)); whiteKingSquaresForPositionsWithPawns.addAll(EnumSet.range( Square.A7, Square.D7)); whiteKingSquaresForPositionsWithPawns.addAll(EnumSet.range( Square.A8, Square.D8)); return whiteKingSquaresForPositionsWithPawns; case WHITE_KING_SQUARES_FOR_PAWNLESS_POSITIONS: return EnumSet.of(Square.A1, Square.B1, Square.C1, Square.D1, Square.B2, Square.C2, Square.D2, Square.C3, Square.D3, Square.D4); case PAWN_SQUARES: return EnumSet.range(Square.A7, Square.H2); case DIAGONAL_A1_H8: return EnumSet.of(Square.A1, Square.B2, Square.C3, Square.D4, Square.E5, Square.F6, Square.G7, Square.H8); case SQUARES_ABOVE_DIAGONAL_A1_H8: EnumSet<Square> squaresAbove_A1_H8 = EnumSet.of(Square.A2); squaresAbove_A1_H8.addAll(EnumSet.of( Square.A3, Square.B3)); squaresAbove_A1_H8.addAll(EnumSet.range(Square.A4, Square.C4)); squaresAbove_A1_H8.addAll(EnumSet.range(Square.A5, Square.D5)); squaresAbove_A1_H8.addAll(EnumSet.range(Square.A6, Square.E6)); squaresAbove_A1_H8.addAll(EnumSet.range(Square.A7, Square.F7)); squaresAbove_A1_H8.addAll(EnumSet.range(Square.A8, Square.G8)); return squaresAbove_A1_H8; default: throw new AssertionError("Unknown square set type: " + this); } } /** * Wraps the set of squares and returns it as a list. (Conversion to list * is useful, as some client classes need to pick squares randomly). * * @return list of different squares */ public List<Square> getSquaresAsList() { return new ArrayList<Square>(collectSquares()); } /** * Computes the total number of squares this set contains. * * @return the int */ public int numberOfSquares() { return collectSquares().size(); } } <file_sep>package tablebases; import chess.ChessPosition; import chess.ChessPositionEvaluation; import chess.ChessPositionEvaluation.ChessPositionEvaluationWithDTM; /** * Software, typically written in C/C++, to generate, compress, access and probe * endgame tablebases. * * @author Kestutis * */ public interface EndgameTablebasesProbingCodeAPI { /** * Probes tablebases for the basic evaluation of the specified chess * position. * * @param chessPosition * representation of the chess position: side to move (White / * Black), White and Black pieces, and their respective squares * @return the game-theoretical value of the chess position obtained from * the tablebase */ public abstract ChessPositionEvaluation queryTablebaseForResultOnly(ChessPosition chessPosition); /** * Probes tablebases for the advanced evaluation of the specified chess * position. * * @param chessPosition * representation of the chess position: side to move (White / * Black), White and Black pieces, and their respective squares * @return the game-theoretical value of the chess position obtained from * the tablebases, and distance to mate (a non-negative number in * case the evaluation is "White wins" / "Black wins", zero * otherwise) */ public abstract ChessPositionEvaluationWithDTM queryTablebaseForResultAndDTM(ChessPosition chessPosition); }<file_sep>package chess.patterns; import java.util.Set; import chess.ChessPosition; import chess.Square; /** * Chess entity that can be under control by some other (controller) chess * entity. Here "controllable" means that all the squares that are in some way * related to this entity, are attacked by the controller. <br/> * <br/> * * For example, in the pattern "White King defends White Rook", the White Rook * is the controllable - the square it occupies is controlled by the White King. * * @author Kestutis * */ public interface ControllableEntity extends ChessEntity { /** * Gets the squares that are in some way related (e.g., occupied by) to this * controllable entity. Those squares may (or may not) be controlled * (attacked) by some controller entity. * * @param chessPosition * representation of the chess position: side to move (White / * Black), White and Black pieces, and their respective squares * @return the set of controllable squares */ public abstract Set<Square> getControllableSquares(ChessPosition chessPosition); }<file_sep>package chess; import static org.junit.Assert.*; import org.junit.Test; public class SquaresTest { @Test public void testIfSetContainsCorrectNumberOfSquares() { Squares squares = Squares.ALL_SQUARES; assertEquals("Set should contain all 64 squares of the chessboard", 64, squares.numberOfSquares()); squares = Squares.PAWN_SQUARES; assertEquals("Set should contain the 48 squares on ranks 2 to 7 of the chessboard", 48, squares.numberOfSquares()); squares = Squares.WHITE_KING_SQUARES_FOR_PAWNLESS_POSITIONS; assertEquals("Set should contain the 10 squares in the A1-D1-D4 triangle of the chessboard", 10, squares.numberOfSquares()); squares = Squares.WHITE_KING_SQUARES_FOR_POSITIONS_WITH_PAWNS; assertEquals("Set should contain the 32 squares on the left half of the chessboard", 32, squares.numberOfSquares()); squares = Squares.DIAGONAL_A1_H8; assertEquals("Set should contain the 8 squares on the A1-H8 diagonal", 8, squares.numberOfSquares()); squares = Squares.SQUARES_ABOVE_DIAGONAL_A1_H8; assertEquals("Set should contain the 28 squares above the A1-H8 diagonal", 28, squares.numberOfSquares()); } }
09a55e4e64f8efe285bc356c9385934d7f65fac7
[ "Markdown", "Java" ]
12
Java
Kestutis-Z/Endgame-Oracle
a59e8b1cc25989f73a05f5db843cd371ba93bd3f
879409bf22d14a6cf8cc04a44c992b8dcd35f02e
refs/heads/master
<repo_name>ParallelProgramming-UARK-BAPD/Minimum-Spanning-Tree<file_sep>/src/mst.cpp /* * mst.cpp * * Created on: Feb 5, 2016 * Authors: <NAME>, <NAME> Parallel Boruvka pseudocode size(V)=6,400 max degree of vertex = 1000 P0 reads “graph.txt” and constructs a matrix of adjacencies this matrix is scattered P0 constructs the head node array each Pi constructs local adjacency list for each local V P0 allocates space for the MST which is an array of edges of size V-1 while size of MST < V-1 P0 broadcasts the head node array each Pi updates the use of each edge from each of its vertices, finds light edge, and sends that edge to P0 P0 receives the edges to be added to the MST, updates the head node array (pointer jumping), and broadcasts the updated array note that some processors will become idle P0 writes the edges in he MST to the file “mst.txt” */ #include "mpi.h" #include <string> #include <iostream> #include <fstream> #include <istream> #include <stdio.h> #include <stdlib.h> #include <cstring> #include <vector> #include <queue> #include <climits> //int max using namespace std; //flags for quick debugging #define PRINTING false #define DETAILED false //flags for quick shortcuts #define MINT MPI_INTEGER #define MCOMM MPI_COMM_WORLD #define MIGN MPI_STATUS_IGNORE MPI_Datatype mpi_edge; #define V 6400 #define MD 1000 #define inputFile "graph.txt" //where V is number vertices and MD is max degree of any vertex struct edge { int v1, v2; int weight; int use; }; class compareEdgeWeights { public: compareEdgeWeights(){} bool operator()(const edge& a, const edge& b) { return a.weight > b.weight; } }; //print HEad node array void printHNA(int headNodeArray[]){ cout << "HNA: "; for(int x = 0; x < V; x++){ cout << x<<"="<<headNodeArray[x] << " ,"; } cout << endl; } typedef priority_queue<edge, vector<edge>, compareEdgeWeights> edgepq; //true if usable, combine flag true if we should go ahead and combine them //on the head node array bool check_edge(edge e, int headNodeArray[], bool combineFlag) { int v1Head = e.v1; int v2Head = e.v2; int index; if(e.v1 == e.v2) return false; //find v1's head for set while(headNodeArray[v1Head] != v1Head){ v1Head = headNodeArray[v1Head]; } //find v2's head for set while(headNodeArray[v2Head] != v2Head){ v2Head = headNodeArray[v2Head]; } if(v1Head == v2Head){ return false; //same head so unusable }else if (combineFlag) { headNodeArray[v2Head] = v1Head; } return true; //not same set (but it is now) } //print final MST void printMST(vector<edge>& MST){ for (int x = 0; x < MST.size(); x++) cout << "MST Edge from v" << MST[x].v1 << " to v" << MST[x].v2 << ", weight "<<MST[x].weight << endl; cout << "MST Size: " << MST.size() << endl; } /*send an edge to process 0*/ void pass_change(edge e) { int edgedata[] = {e.v1, e.v2, e.weight}; MPI_Send(edgedata, 3, MINT, 0, 0, MCOMM); //send data to process 0 } /*returns true if still valid edges, false if all done , receive edges from processors and update them all with the edges from other processors*/ bool dist_change(int size, int headNodeArray[], edge localEdge, vector<edge>& MST) { int recbuff[3]; edge tempEdge; int validEdges = 0; //keeps track of how many procs are sending real edges priority_queue<edge, vector<edge>, compareEdgeWeights> edgepq; //p0 gets each edge if(localEdge.v1 != localEdge.v2) { tempEdge.v1 = localEdge.v1; tempEdge.v2 = localEdge.v2; tempEdge.weight = localEdge.weight; edgepq.push(tempEdge); validEdges++; } for (int x = 1; x < size; x++) { //receive data from each processor, x MPI_Recv(recbuff, 3, MINT, x, 0, MCOMM, MIGN); //if valid edge if(recbuff[0] != recbuff[1]){ tempEdge.v1 = recbuff[0]; tempEdge.v2 = recbuff[1]; tempEdge.weight = recbuff[2]; edgepq.push(tempEdge); validEdges++; if (PRINTING) cout << "P0 received v"<<tempEdge.v1<<" v"<<tempEdge.v2<<" w"<<tempEdge.weight<<" from p"<<x<<" Qsize "<<edgepq.size()<<endl; } } //if all edges were fake if (validEdges == 0){ return false; } //p0 grabs least weight edge, checks sets and updates headNodeArray while( !edgepq.empty()){ tempEdge = edgepq.top(); //if not already in the same set if (check_edge(tempEdge, headNodeArray, true)){ MST.push_back(tempEdge); //add the edge to the MST! if (PRINTING && DETAILED) cout << "combined v"<<tempEdge.v1<<" v"<<tempEdge.v2<<", "<<headNodeArray[tempEdge.v1]<<"="<<headNodeArray[tempEdge.v2]<<endl; if (PRINTING && DETAILED) cout << "MST SIZE : " << MST.size()<<endl; } edgepq.pop(); } return true; }//end dist_change void MSTSort(int* list, int rank, int size, int localV) { //head node array for each process int headNodeArray[V+1]; //the last element of head node array tells the processes to continue or are they all done (0 == done) int localEdgeCount = 0; edge fakeEdge; //construct MST = array of edges of size V - 1 vector<edge> MST; //process 0 if (rank == 0) { //construct head node array for p0 for (int x = 0; x < V; x++) { //each vertex points to itself initially headNodeArray[x] = x; } headNodeArray[V] = 1; //flag for continuing }//end if rank 0 //local matrix for each proc's vertices it gets int localArraySize = localV * (MD * 2); int localList[localArraySize]; //scatter the data into the local array(s) MPI_Scatter(list, localArraySize, MPI_INT, localList, localArraySize, MPI_INT, 0, MPI_COMM_WORLD); //broadcast the head node array MPI_Bcast(headNodeArray, V, MPI_INT, 0, MPI_COMM_WORLD); //MPI_Barrier(MPI_COMM_WORLD); //PRINT LOCAL list (only non zero edges for each process) if( PRINTING && DETAILED){ cout << "\nPROCESS " << rank << ":: localArraySize::" << localArraySize << ":: localV::" << localV; for (int x = 0; x < localArraySize; x+=2) { if (x % (MD*2) == 0 ) cout << "\n"; if (localList[x+1] != 0){ cout << localV * rank + (x / (MD*2)) << "->" << localList[x] << ":" << localList[x+1] << " "; } } cout << "\n\n"; }//end print */ //priority q for each process' edges priority_queue<edge, vector<edge>, compareEdgeWeights> edgepq; int x = 0; //array offset //for each vertex locally owned for (int i = 0; i < localArraySize; i += MD*2){ x = i; //jump to vertex i data in local array //while non zero weight from array while (localList[x+1] != 0){ edge temp; temp.v1 = (localV * rank + (x / (MD*2))); //vertex 1 temp.v2 = localList[x]; temp.weight = localList[x+1]; temp.use = 2; edgepq.push(temp); x+=2; localEdgeCount++; } } //while processor has more edges //while(! edgepq.empty() ){ while(headNodeArray[V] != 0){ edge least; fakeEdge.v1 = 0; fakeEdge.v2 = 0; fakeEdge.weight = INT_MAX; //processor is done with valid edges if (edgepq.empty()){ least = fakeEdge; }else{ //find least weight, usable edge least = edgepq.top(); while( !check_edge(least, headNodeArray, false) && !edgepq.empty()){ edgepq.pop(); if( edgepq.empty() ) { least = fakeEdge; }else { least = edgepq.top(); } } } //temp printing of found least edges //if(PRINTING) cout << "p" << rank<< " found weight " << least.weight <<" "<< least.v1 << "->"<< least.v2 << endl; //send least edge to p0 if(rank != 0){ //SEND EDGE pass_change(least); } else if(rank == 0){ //receive edges, and passes it's own leasst weight edge as well if( !dist_change(size, headNodeArray, least, MST)){ headNodeArray[V] = 0; //all done flag } } //remove edge if (!edgepq.empty()) edgepq.pop(); localEdgeCount--; //update new Head node array to procs MPI_Bcast(headNodeArray, V+1, MPI_INT, 0, MPI_COMM_WORLD); } //print the final MST if (PRINTING && rank == 0) { printMST(MST); } else if(!PRINTING && rank == 0) { ofstream outfile; outfile.open("mst.txt"); for (int ab = 0; ab < MST.size(); ab++) outfile << "MST Edge from v" << MST[ab].v1 << " to v" << MST[ab].v2 << ", weight "<<MST[ab].weight << "\n"; outfile << "MST size =" << MST.size(); } }//end MSTSort int main(int argc, char** argv) { int numVert; int nedge; int *elist; int v1, v2, weight; int rank = 0, size = 0; MPI_Init(&argc, &argv); MPI_Type_contiguous(3, MPI_INT, &mpi_edge); MPI_Type_commit(&mpi_edge); double starttime, endtime; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); if (rank == 0) { ifstream graphfile(inputFile); string line; if (graphfile.is_open()) { graphfile >> numVert; graphfile >> nedge; elist = new int[V * (MD * 2)]; int x = 0; for (int i = 0; i < nedge; i++) { int v1, v2, w; graphfile >> v1 >> v2 >> w; int offset = 0; while (elist[(v1 * MD * 2) + offset] != 0) { offset += 2; } elist[(v1 * MD * 2) + offset] = v2; elist[(v1 * MD * 2) + offset + 1] = w; offset = 0; while (elist[(v2 * MD * 2) + offset] != 0) { offset += 2; } elist[(v2 * MD * 2) + offset] = v1; elist[(v2 * MD * 2) + offset + 1] = w; x++; }//end for if (PRINTING) cout << "File loaded " << inputFile << endl; graphfile.close(); starttime = MPI_Wtime(); }//end if open }//end if rank 0 //vertices per process int localNumVert = V / size; MSTSort(elist, rank, size, localNumVert); //finish timing if (rank == 0){ endtime = MPI_Wtime(); cout << endtime - starttime << "s timing." << endl; } MPI_Finalize(); return 0; }//EOF
56a977cef67ad39a0b7cfba28c544f8f27d3c766
[ "C++" ]
1
C++
ParallelProgramming-UARK-BAPD/Minimum-Spanning-Tree
9c15f1295b2dc5e86798a8aa466c559c20b0aafa
7caea96e6173ca5794ae7fec64684c34706488ee
refs/heads/master
<file_sep> module.exports = function (vehicle){ if(vehicle.endsWith("GP")){ return true; }else{ return false; } }<file_sep>let assert = require("assert"); let yearsAgo = require("../yearsAgo"); describe("The yearsAgo function ", function(){ it ("should say that 1996 is 24 years ago", function() { assert.equal(24, yearsAgo(1996)); }); it ("should say that 2000 is a 20 years ago", function() { assert.equal(20, yearsAgo(2000)); }); });<file_sep>module.exports = function (day){ var dayUppercase = day.toUpperCase(); return !dayUppercase.startsWith("S"); }<file_sep>let assert = require("assert"); let findItemsOver20= require("../findItemsOver20"); describe("The findItemsOver20 function ", function(){ it("should return 4", function() { var itemList = [ {name : 'apples', qty : 10}, {name : 'pears', qty : 37}, {name : 'bananas', qty : 27}, {name : 'apples', qty : 3}, ]; var Item = [ {name : 'pears', qty : 37}, {name : 'bananas', qty : 27}, ] assert.deepEqual(findItemsOver20(itemList,20), Item); }) });<file_sep>module.exports = function (registrationstr,town){ var regarry= registrationstr.split(','); var arylast = []; for(var i =0;i<regarry.length;i++){ //var arylast=regarry[i].trim(); if(regarry[i].trim().startsWith(town)){ arylast.push(regarry); } } return arylast.length }<file_sep>module.exports = function (registration){ var regn = registration.split(','); console.log(regn); var regnumm = []; for (var i=0;i<regn.length;i++){ var regnum = regn[i].trim(); if (regnum.startsWith('CJ')){ regnumm.push(regnum); console.log(regnumm.length) } }; return regnumm.length; }<file_sep>module.exports = function(listItem,y){ var list=[] for(i=0;i<listItem.length;i++){ var torch = listItem[i]; if(torch.qty>y){ list.push(torch); } } return list }<file_sep>module.exports = function(listItem){ var ab= 20 var quantity=[] for(var i=0;i<listItem.length;i++){ var items =listItem[i]; if(items.qty>ab){ quantity.push(items); } // console.log(items) } return quantity }; function findItemsOver(listItem,y){ var list=[] for(i=0;i<listItem.length;i++){ var torch = listItem[i]; if(torch.qty>y){ list.push(torch); } } return list }
228b790376348dbfe777ce9cb92b5d1a18680b2f
[ "JavaScript" ]
8
JavaScript
ptawuringa/bootcamp-terminal-tests
993190da2019a5447f54d17faa53869f5bcf7b10
6328f4a5c791fffb2e8637649e395d5b2e3de0df
refs/heads/master
<repo_name>altamee/Levenshtein-Distance-Search<file_sep>/README.md # Levenshtein Distance Search (LDS) <file_sep>/levenshteindistance.cpp #include "levenshteindistance.h" #include <algorithm> /** * @brief LevenshteinDistance::LevenshteinDistance constructor */ LevenshteinDistance::LevenshteinDistance() { } /** * @brief LevenshteinDistance::GetDistance get the levenshtein distance between two words recursivley * @param firstWord The first word * @param secondWord The second word * @return The distance between the two words */ int LevenshteinDistance::GetDistance(QString firstWord, int lengthFirst, QString secondWord, int lengthSecond) { int distance = 0; // empty string if (lengthFirst == 0) return lengthFirst; if (lengthSecond == 0) return lengthSecond; // check if last letter needs to be changed if (firstWord[lengthFirst - 1] != secondWord[lengthSecond - 1]) distance = 1; int deleteFirst = GetDistance(firstWord, lengthFirst - 1, secondWord, lengthSecond); int deleteSecond = GetDistance(firstWord, lengthFirst, secondWord, lengthSecond - 1); int deleteBoth = GetDistance(firstWord, lengthFirst - 1, secondWord, lengthSecond - 1); return minimum(deleteFirst + 1, deleteSecond + 1, deleteBoth + distance); } /** * @brief LevenshteinDistance::minimum get the minimum of three numbers * @param firstNum the first number to compare * @param secondNum the second number to compare * @param thirdNum the third number ot compare * @return the smallest of the three */ int LevenshteinDistance::minimum(int firstNum, int secondNum, int thirdNum) { int min = (firstNum < secondNum) ? firstNum : secondNum; min = (thirdNum < min) ? thirdNum : min; return min; } <file_sep>/levenshteindistance.h #ifndef LEVENSHTEINDISTANCE_H #define LEVENSHTEINDISTANCE_H #include <qstring.h> class LevenshteinDistance { public: LevenshteinDistance(); int GetDistance(QString firstWord, int lengthFirst, QString secondWord, int lengthSecond); int minimum(int firstNum, int secondNum, int thirdNum); private: }; #endif // LEVENSHTEINDISTANCE_H
60ef3e43f2b4299f42d1655438bd8b173238d8bf
[ "Markdown", "C++" ]
3
Markdown
altamee/Levenshtein-Distance-Search
ea6e22e6e22b67fb9d48b7c0b98144edffb6db5b
9527af3c00779e1d3215b94a55646689f61bb977
refs/heads/master
<repo_name>ConstructiveLurker/HelpfulCode<file_sep>/HelpfulCode - Unity/Assets/Scripts/DragonAnimationTransition.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class DragonAnimationTransition : MonoBehaviour { Animator dragonAnim; // Use this for initialization void Start () { dragonAnim = GetComponent <Animator> (); } // Update is called once per frame void Update () { if (Input.GetKeyDown (KeyCode.Alpha1)) { dragonAnim.SetInteger ("AnimationState", 0); } if (Input.GetKeyDown (KeyCode.Alpha2)) { dragonAnim.SetInteger ("AnimationState", 1); } if (Input.GetKeyDown (KeyCode.Alpha3)) { dragonAnim.SetInteger ("AnimationState", 2); } } } <file_sep>/HelpfulCode - Unity/Assets/Scripts/UI/MainMenu.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class MainMenu : MonoBehaviour { // load the next scene in the build index public void Play () { // make sure your scenes are in your build settings! SceneManager.LoadScene (SceneManager.GetActiveScene ().buildIndex + 1); } // close the game public void Quit () { Application.Quit (); } } <file_sep>/HelpfulCode - Unity/Assets/Scripts/UI/SettingsMenu.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Audio; using UnityEngine.UI; public class SettingsMenu : MonoBehaviour { // make sure you're using UnityEngine.Audio public AudioMixer audioMixer; // lets us add our resolutionDropdown to our script to reference public Dropdown resolutionDropdown; // lets us add our graphicsDropdown to our script to reference public Dropdown graphicsDropdown; // resolution array Resolution[] resolutions; void Start () { // recieve a list of the resolutions we can use resolutions = Screen.resolutions; // cleans up our resolution dropdown for our new resolutions resolutionDropdown.ClearOptions (); // turns our array of resolutions into a list of strings List <string> options = new List <string> (); // by default, currentResolutionIndex is 0 int currentResolutionIndex = 0; // loop through each item in our resolution array and turn it into a string // then add it to our list for (int i = 0; i < resolutions.Length; i++) { string option = resolutions[i].width + " x " + resolutions[i].height; options.Add (option); // check if the resolution we're looking at is = to our resolution // we have to compare both the width and the height if (resolutions [i].width == Screen.currentResolution.width && resolutions [i].height == Screen.currentResolution.height) { // if it is, set our resolution index to i currentResolutionIndex = i; } } // adds our list of resolutions to our dropdown resolutionDropdown.AddOptions (options); // set our dropdown to our resolution index resolutionDropdown.value = currentResolutionIndex; // ensure our dropdown value matches our index resolutionDropdown.RefreshShownValue(); // ensure our graphics start off at high graphicsDropdown.RefreshShownValue (); } //make sure you're using UnityEngine.UI (only need it for this) // go to Edit > Project Settings > Player > Resolution and Presentation > // Standalone Player Options > then set the Display Resolution Dialogue to disabled // ***this gets rid of the initial resolution select window upon starting the game public void SetResolution (int resolutionIndex) { // we need to grab our resolution index Resolution resolution = resolutions [resolutionIndex]; // set our resolution to the resolution we choose Screen.SetResolution (resolution.width, resolution.height, Screen.fullScreen); } // set the volume public void SetVolume (float volume) { // recieve the audioMixer and set it to our float audioMixer.SetFloat ("Volume", volume); } // set the graphics quality public void SetQuality (int qualityIndex) { // look at the quality index, then change it to the index of our dropdown selection // can watch this by going Edit > Project Settings > Quality QualitySettings.SetQualityLevel (qualityIndex + 1); } // set if the game is fullscreen or not public void SetFullscreen (bool isFullscreen) { // change our fullscreen value to our isFullscreen bool Screen.fullScreen = isFullscreen; } } <file_sep>/HelpfulCode - Unity/Assets/Scripts/Practice Code/RecursionAssignment.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class RecursionAssignment : MonoBehaviour { // Use this for initialization void Start () { int num1 = One (100); int num2 = Two (4); int num3 = Three (3); } // Update is called once per frame void Update () { } // Create a function that calls itself (recursion) that will add all the numbers from 1 up to the passed variable // Num1 would be equal to the sum of all the numbers from 1 to 100 public int One (int num) { if (num == 0) { return num; } return num + One (num - 1); } // Create a function that calls itself (recursion) that will find the factorial of a given number. // Num2 would be equal to 4!, or 4*3*2*1 public int Two (int num) { if (num == 1) { return num; } return num * One (num - 1); } // Create a recursive function that gives you the Fibbonacci number at a given index. // Fibbonacci Sequence: // 0 1 2 3 4 5 6 7 8 // 0 1 1 2 3 5 8 13 21 // The fibbonacci sequence is found by adding the previous two indicies. // E.g. The 4th value in the Fib. Sequence is found by adding the 3rd and 2nd values together, or 2+1 // The first two values of the Fib. Sequence are given as their index, so index 0 has a value of 0, and index 1 has a value of 1 // Num3 would have a value of 34 public int Three (int num) { if (num <= 1) { return num; } return Three (num - 1) + Three (num - 2); } } <file_sep>/HelpfulCode - Unity/Assets/Scripts/LagScript.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class LagScript : MonoBehaviour { // Use this for initialization public int loops = 10; void Start () { } // Update is called once per frame void Update () { for (int i = 0; i < loops; i++) { Debug.Log ("foo"); } } } <file_sep>/HelpfulCode - Unity/Assets/Scripts/Practice Code/MathFunctions.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class MathFunctions { // return the value for pi // to calculate pi, pi = circumference / diameter public float Pi () { return 3.141593f; } // convert degrees to radians public float DegreeToRadian (float degree) { return (degree * Pi () / 180); } // convert radians to degrees public float RadianToDegree (float radian) { return (Pi () * 180 / radian); } // return the absolute value of a float public float AbsoluteValueFloat (float num1) { if (num1 >= 0) { return num1; } else { return -num1; } } // return the absolute value of an int public int AbsoluteValueInt (int num1) { if (num1 >= 0) { return num1; } else { return -num1; } } // compares two numbers (floats) and returns true if they're approximately the same public bool Approximately (float num1, float num2) { if (num1 >= num2 - 1 && num1 <= num2 + 1) { return true; } else { return false; } } // recieves two numbers, and returns the largest of the two public float MaxFloat (float num1, float num2) { if (num1 >= num2) { return num1; } else { return num2; } } // recieves two numbers, and returns the largest of the two public int MaxInt (int num1, int num2) { if (num1 >= num2) { return num1; } else { return num2; } } // recieves two numbers, and returns the smallest of the two public float MinFloat (float num1, float num2) { if (num1 <= num2) { return num2; } else { return num1; } } // recieves two numbers, and returns the smallest of the two public int MinInt (int num1, int num2) { if (num1 <= num2) { return num2; } else { return num1; } } // recieves a number (int) and a power (int) and returns the number raised to the power given public int Pow (int num1, int power) { int total = num1; if (power > 0) { for (int i = 0; i < power - 1; i++) { total = total * num1; } return total; } if (power < 0) { for (int i = 0; i < power - 1; i++) { total = total * num1; } return 1 / total; } else { return 1; } } // calculates the square root of the given number (int) public float SquareRoot (int num1) { float squareRoot = 0; double stageUpper = 0; double stageLower = 0; // step 1 // if the number is <= 0, return 0 if (num1 <= 0) { return 0; } // while the square root is < 100, see if the number is greather than the squareRoot * squareRoot, and get the first upper and lower umbers while (squareRoot < 100) { // if the number is greater than the squareRoot, increase num if (num1 > squareRoot * squareRoot) { num1++; // otherwise, set upper and lower values to find the square root } else { stageUpper = squareRoot; stageLower = squareRoot - 1; //do a check to see if either is the actual solution before doing more math if(squareRoot * squareRoot == num1) { return squareRoot; } break; } } // step 2 int num2 = 0; // while the square root doesn't equal the number your finding the square root for, do this while (!(((stageLower + stageUpper / 2.0) * (stageLower + stageUpper / 2.0)) == num1)) { num2++; // stop after a certain number of iterations if (num2 > 15) { break; } //if (midpoint between upper and lower)^2 is greater than the desired value, need to shrink upper if ((((stageLower + stageUpper) / 2.0)*(stageLower + stageUpper)/2) > num1) { stageUpper = ((((stageLower + stageUpper) / 2.0) +(stageUpper))/2.0); } //if (midpoint between upper and lower)^2 is less than the desired value, increase the lower else { stageLower = ((((stageLower + stageUpper) / 2.0) + (stageLower)) / 2.0); } // if the square root is within a small percent error, return if ((((stageLower + stageUpper / 2.0) * (stageLower + stageUpper / 2.0)) >= num1 - .00001f && (((stageLower + stageUpper / 2.0) * (stageLower + stageUpper / 2.0)) <= num1 + .000001f))) { break; } } // return the square root return ((float)((stageLower + stageUpper) / 2.0)); } }<file_sep>/HelpfulCode - Unity/Assets/Scripts/Player/AnimationControls.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class AnimationControls : MonoBehaviour { // global variable, but not public Animator anim; // Use this for initialization void Start () { anim = GetComponent <Animator> (); } // Update is called once per frame void Update () { // GetAxisRaw : You're either -1 , 0 , 1 float inputX = Input.GetAxisRaw ("Horizontal"); float inputY = Input.GetAxisRaw ("Vertical"); // do we have any x or y input (if so, true) bool isWalking = (Mathf.Abs (inputX) + Mathf.Abs (inputY) > 0); // set variables anim.SetBool ("IsWalking", isWalking); if (isWalking) { anim.SetFloat ("x", inputX); anim.SetFloat ("y", inputY); } } } <file_sep>/HelpfulCode - Unity/Assets/Scripts/Practice Code/PublicFunctionPractice.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class PublicFunctionPractice : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { } /* // recieve 3 ints and return their sum public int Return3Integers (int num1, int num2, int num3) { return num1 + num2 + num3; } // recieve 3 floats and return them as vector3 public Vector3 ReturnVector3 (float one, float two, float three) { return new Vector3 (one, two, three); } // recieve a string and float, if string is empty retun float, otherwise return 0 public float ReturnIfEmpty (string words, float empty) { // variables are lowercase if (words == "") { return empty; } else { return 0; } } // recieve a boolean and return the opposite of the boolean public bool ReturnOpposite (bool StartValue) { if (StartValue == true) { return !StartValue; } } */ } <file_sep>/HelpfulCode - Unity/Assets/Scripts/Player/PositionMovement.cs using UnityEngine; using System.Collections; public class PositionMovement : MonoBehaviour { // starting speed float startSpeed = 1.0f; float speed; // speed multiplier float sprintSpeed = 1.5f; // Use this for initialization void Start () { } // Update is called once per frame void Update () { Vector3 movement = transform.position; // sprint if(Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)) { speed = startSpeed * sprintSpeed; } else { speed = startSpeed; } // basic movement if (Input.GetKey (KeyCode.W)) { movement.y += speed; } if (Input.GetKey (KeyCode.A)) { movement.x -= speed; } if (Input.GetKey (KeyCode.S)) { movement.y -= speed; } if (Input.GetKey (KeyCode.D)) { movement.x += speed; } transform.position = movement; } } <file_sep>/HelpfulCode - Unity/Assets/Scripts/Practice Code/CreatingFunctions.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class CreatingFunctions : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { } // write a function to take a number and double it, then return the value public float Banananana (float number) { return number * 2; } // write a function that will take two numbers, add them together, then return the value public float ChaosTheory (float number1, float number2) { return number1 + number2; } // EXAMPLE public float CalculateDamage (float dmg, float def, float crit, float evaison) { // roll a die to see if they evade // if they don't evade, roll a die to see if you crit // calculate damage // return damage return 0; } // write a function that recieves a string, if the string is "Hello World!" returns true public bool World (string words) { if (words == "Hello World!") { return true; } else { return false; } } } <file_sep>/HelpfulCode - Unity/Assets/Scripts/Player/RotationMovement.cs using UnityEngine; using System.Collections; public class RotationMovement : MonoBehaviour { public float rotationSpeed = 2.0f; public float moveSpeed = 2.0f; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if (Input.GetKey ("a")) { //rotate counter-clockwise transform.RotateAround(transform.position, new Vector3(0f,0f,1f), rotationSpeed); } if (Input.GetKey ("d")) { //rotate counter-clockwise transform.RotateAround(transform.position, new Vector3(0f,0f,1f), - rotationSpeed); } if (Input.GetKey ("w")) { // move forward (up) GetComponent<Rigidbody2D> ().velocity = transform.up * moveSpeed; } else { GetComponent<Rigidbody2D> ().velocity = new Vector2 (0f, 0f); } } } <file_sep>/HelpfulCode - Unity/Assets/Scripts/Practice Code/CallingMath.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class CallingMath : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { MathFunctions math = new MathFunctions(); float pi = math.Pi(); float radian = math.DegreeToRadian (180); float degree = math.RadianToDegree (pi / 2); float absFloat = math.AbsoluteValueFloat (-5.25f); int absInt = math.AbsoluteValueInt (-5); bool approx = math.Approximately (5, 5.1f); float maxFloat = math.MaxFloat (5.2f, 9.3f); int maxInt = math.MaxInt (4, 7); float minFloat = math.MinFloat (5.2f, 9.3f); int minInt = math.MinInt (4, 7); int pow = math.Pow (5, 2); float squareRoot = math.SquareRoot (5); } } <file_sep>/HelpfulCode - Unity/Assets/Scripts/Player/ForceMovement.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class ForceMovement : MonoBehaviour { // starting speed float startSpeed = 1.0f; float speed; // speed multiplier float sprintSpeed = 1.5f; // Use this for initialization void Start () { // Instantiate (prefab, new Vector3 (0, 0, 0), Quaternion.identity); } // Update is called once per frame void Update () { // create a new force Vector2 Vector2 force = new Vector2 (0, 0); // sprint if(Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)) { speed = startSpeed * sprintSpeed; } else { speed = startSpeed; } // basic movement if (Input.GetKey (KeyCode.W)) { force.y += speed; } if (Input.GetKey (KeyCode.A)) { force.x -= speed; } if (Input.GetKey (KeyCode.S)) { force.y -= speed; } if (Input.GetKey (KeyCode.D)) { force.x += speed; } // make the object move GetComponent<Rigidbody2D> ().velocity = force; } }
0fe82d3ff3073d3510476ac1378dac8103972525
[ "C#" ]
13
C#
ConstructiveLurker/HelpfulCode
781d36e0ee24735f638b0464253a96d66bd0c0d9
09d97e73c94743b276df785b229385dd29a4de5a
refs/heads/master
<file_sep># akhan227.github.io Last updated: July 19, 2019 Link to portfolio: https://ahmednkhan24.github.io/ <file_sep>/* DATA FOR OTHER PROJECTS TO DISPLAY IF NEED BE PRIVATE REPO: REQUEST PERMISSION TO VIEW https://www.1and1.com/favicon-generator */ // array of objects for the different projects var arr = [ { title:"RESTful Chess Webservice", tech:"Java", description:"Dockerized RESTful web microservice using Java Spring Boot to play chess with VAPs", repo:"https://github.com/ahmednkhan24/Engineering-Distributed-Objects-For-Cloud-Computing/tree/master/Project%203%20-%20Spring%20Boot%20RESTful%20Web%20Service", page:"#" }, { title:"AI Pacman Classification", tech:"Python", description:"A team project to create three classifiers for a Pacman agent.", repo:"https://github.com/ahmednkhan24/Pacman-Artificial-Intelligence/tree/master/Project%203%20-%20Classification", page:"#" }, { title:"Arduino Smart Clock", tech:"C++, INO", description:"A cool alarm clock that has tons of features. Software written, tested, and implemented on the Arduino UNO hardware with 2 other partners.", repo:"https://github.com/ahmednkhan24/Computer-Design/tree/master/Smart-Clock", page:"#" }, { title:"mySet: C++ Container", tech:"C++", description:"My own implementation of the standard set container in C++", repo:"https://github.com/ahmednkhan24/Programming-Language-Design-and-Implementation/tree/master/mySet%20Container%20Implementation", page:"#" }, { title:"Crypto Ticker", tech:"Java", description:"Semester long group application to track various relevant crypto currency data", repo:"https://github.com/ahmednkhan24/Crypto-Ticker/tree/master/CodingProject", page:"#" }, { title:"YelpCamp", tech:"HTML, CSS, JavaScript, NodeJS", description:"Yelp-like application for campgrounds", repo:"https://github.com/ahmednkhan24/YelpCamp", page:"https://frozen-castle-47525.herokuapp.com/" } ]; // get the div that we will be adding all of the project cards to var projectSection = $(".projectSection .container"); // get the original row that's in the html file var originalRow = $(".projectSection #originalRow"); // clone the original row var row = $(originalRow).clone(); // change the id of the cloned row var id = "#row1"; $(row).attr("id", id); // add the cloned row to the DOM projectSection.append(row); // variable to keep track of how many rows there are var numRows = 1; // for loop to add each project to the row, and each row to the DOM for (var i = 0; i < arr.length; i++) { // I want 3 cards per row, so if the number of iterations // of this loop is a multiple of 3, that means make a new row if (i % 3 === 0) { // increment the number of rows counter numRows++; // reclone the original row row = $(originalRow).clone(); // change the id of the cloned row id = "#row" + numRows; $(row).attr("id", id); // add the cloned row to the DOM projectSection.append(row); } // clone the original card var card = originalRow.find("#originalCard").clone(); // change the id of the cloned card to the current iteration var id = "#card" + i; $(card).attr("id", id); // add the data for this project to the card $(card).find(".card-header").text(arr[i].title); $(card).find(".card-title").text(arr[i].tech); $(card).find(".card-text").text(arr[i].description); // check if there are actual links to display for the repo and the page if (arr[i].repo === "#") $(card).find(".repoBtn").toggleClass("screen"); else $(card).find(".repoBtn").attr("href", arr[i].repo); if (arr[i].page === "#") $(card).find(".pageBtn").toggleClass("screen"); else $(card).find(".pageBtn").attr("href", arr[i].page); // turn the visibility of the card on card.toggleClass("screen"); // add the card to the row row.append(card); }
2abeb9d0f0b5aa7d104a3cd49daef667fc621e69
[ "Markdown", "JavaScript" ]
2
Markdown
ahmednkhan24/ahmednkhan24.github.io
550e166753dfafcb2c72d478e45841c0f0dc28ac
f1ed382cdf2eb22d0443f46c0162bda3673ec898
refs/heads/master
<file_sep>using SundiresDeliverApp.Core.Database_Entity; using SundiresDeliverApp.Core.Repository_Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SundiresDeliverApp.Core.AppRepository { public class MS_ADITMCATRepository : IAD_MSITMCATRepository { private SundriesMarketEntities _entityManager; public MS_ADITMCATRepository(SundriesMarketEntities DbContext) { _entityManager = DbContext; } public List<AD_MSITMCAT> GetItemCategory() { return _entityManager.AD_MSITMCAT.ToList(); } } } <file_sep>using SundiresDeliverApp.Core.AppRepository; using SundiresDeliverApp.Core.Database_Entity; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace SundriesDeliver.API.Controllers { public class UserController : ApiController { private ReportManager reportManager; public UserController() { reportManager = new ReportManager(); } [HttpGet] [Route("api/User/GetItemCategory")] public List<AD_MSITMCAT> GetItemCategory() { return reportManager.GetItemCategory(); } } } <file_sep>import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Global } from '../model/global'; @Component({ selector: 'app-show-product-category', templateUrl: './show-product-category.component.html', styleUrls: ['./show-product-category.component.scss'], }) export class ShowProductCategoryComponent implements OnInit { itemType: any[] = []; itemCategory: any[] = []; // tslint:disable-next-line:variable-name constructor(private http: HttpClient) { // this.ngOnInit(); } ngOnInit() { debugger; this.productCategoryList(); this.itemType.push('Test 1', 'Test 2', 'Test 3'); } productCategoryList() { const urlString = Global.APIURL + 'api/UserLevel/GetItemCategory'; const urlSearchParams = new URLSearchParams(); urlSearchParams.append('compId', '7AF0D3AA-698E-44B4-8042-68EE81C8EABA'); this.http.get(urlString).subscribe( res => { console.log(res); } ); } openItemType(btnValue) { alert(btnValue); } } <file_sep>using SundiresDeliverApp.Core.AppRepository; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SundiresDeliverApp.Core { class Program { public static void Main(string[] args) { ReportManager reportManager = new ReportManager(); reportManager.GetItemCategory(); } } } <file_sep>export class Global { public static APIURL = 'http://localhost:63420/'; } <file_sep>using SundiresDeliverApp.Core.Database_Entity; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SundiresDeliverApp.Core.Repository_Interfaces { public interface IAD_MSITMCATRepository { List<AD_MSITMCAT> GetItemCategory(); } } <file_sep>using SundiresDeliverApp.Core.Database_Entity; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SundiresDeliverApp.Core.AppRepository { public class ReportManager { private readonly DBManager _dBManager; public ReportManager() { _dBManager = new DBManager(); } public List<AD_MSITMCAT> GetItemCategory() { var itemCategory = _dBManager.ItemCategoryRepository.GetItemCategory(); return itemCategory; } } } <file_sep>using SundiresDeliverApp.Core.Database_Entity; using SundiresDeliverApp.Core.Repository_Interfaces; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SundiresDeliverApp.Core.AppRepository { public class Repository<TEntity> : IRepository<TEntity> where TEntity : class { private readonly SundriesMarketEntities Context; private IDbSet<TEntity> dbEntity; public Repository() { Context = new SundriesMarketEntities(); dbEntity = Context.Set<TEntity>(); } public void Add(TEntity entity) { Context.Set<TEntity>().Add(entity); } public TEntity Get(int id) { return Context.Set<TEntity>().Find(id); } public IEnumerable<TEntity> GetAll() { return dbEntity.ToList(); } public void Remove(TEntity entity) { Context.Set<TEntity>().Remove(entity); } } } <file_sep>using SundiresDeliverApp.Core.Database_Entity; using SundiresDeliverApp.Core.Repository_Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SundiresDeliverApp.Core.AppRepository { public class DBManager { private readonly SundriesMarketEntities _dbContext; public MS_ADITMCATRepository ItemCategoryRepository; public DBManager() { _dbContext = new SundriesMarketEntities(); ItemCategoryRepository = new MS_ADITMCATRepository(_dbContext); } } }
630d66aec94ffe5deff55fb273943034af5eb6fb
[ "C#", "TypeScript" ]
9
C#
sundriesdelivermarket/UserApplication
6e919b75b1a74235f874d3176078dc0521c0cc18
e77749d2dcdd1c6777ababb4322c81eb6b242ab5
refs/heads/master
<file_sep># Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) ## [Unreleased] - watch this space ## 2019-02-21 ### Security - Upgraded `requests` and `flask` to fix security issues. ### Added - This changelog!<file_sep>import requests from datetime import datetime def find_url(): current_year = datetime.now().year year_lookback = 0 status_code = 0 while status_code != 200: year = current_year - year_lookback ebird_url = (f'http://www.birds.cornell.edu/clementschecklist/wp-content/uploads/{year}/' f'08/Clements-Checklist-v{year}-August-{year}.csv') status_code = requests.head(ebird_url).status_code year_lookback += 1 return ebird_url<file_sep>import csv import re import requests import predict_bird_url from flask_sqlalchemy import SQLAlchemy from birdverse import app db = SQLAlchemy(app) match_spuh = re.compile('\(.+\)') from models import Bird ebird_url = predict_bird_url.find_url() local_bird_storage = 'birdverse/temp/raw_bird_data.csv' def get_csv(url): r = requests.get(url, stream=True) print(r.status_code) with open(local_bird_storage, 'wb') as handle: for block in r.iter_content(1024): handle.write(block) return local_bird_storage def process_csv(bird_storage): # Consider using yield here instead of return; it creates an iterable first_line = True with open(bird_storage, 'rU', encoding='mac_latin2') as bird_csv: bird_reader = csv.reader(bird_csv) while True: try: if first_line: # skip the first row, which is headers first_line = False continue else: bird_data = bird_reader.__next__() if bird_data[1] == 'species': print(bird_data) # only load species data create_bird(bird_data) else: continue except UnicodeDecodeError as error: print('ERROR {}'.format(error)) except StopIteration: print("Finished loading birds") break def create_bird(bird): common_name = bird[3] species_name = bird[4].split()[1] genus_name = bird[4].split()[0] family_name = bird[5] spuh = extract_spuh(bird[6]) order_name = bird[6].split()[0] new_bird = Bird( common_name = common_name, species_name = species_name, genus_name = genus_name, family_name = family_name, order_name = order_name, spuh = spuh ) db.session.add(new_bird) db.session.commit() def extract_spuh(spuh_raw): spuh = '' matched = match_spuh.findall(spuh_raw) if matched: spuh = matched[0].strip('()') return spuh def populate_the_database(): process_csv(get_csv(ebird_url))<file_sep>"""empty message Revision ID: 42b54ecf4b7b Revises: Create Date: 2017-08-09 09:47:04.424098 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '<KEY>' down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('birds', sa.Column('id', sa.Integer(), nullable=False), sa.Column('common_name', sa.String(), nullable=True), sa.Column('species_name', sa.String(), nullable=True), sa.Column('genus_name', sa.String(), nullable=True), sa.Column('family_name', sa.String(), nullable=True), sa.Column('order_name', sa.String(), nullable=True), sa.Column('spuh', sa.String(), nullable=True), sa.PrimaryKeyConstraint('id') ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table('birds') # ### end Alembic commands ### <file_sep>from birdverse import db from sqlalchemy.dialects.postgresql import JSON class Bird(db.Model): __tablename__ = 'birds' id = db.Column(db.Integer, primary_key=True) common_name = db.Column(db.String()) species_name = db.Column(db.String()) genus_name = db.Column(db.String()) family_name = db.Column(db.String()) order_name = db.Column(db.String()) spuh = db.Column(db.String()) def __init__( self, common_name, species_name, genus_name, family_name, order_name, spuh ): self.common_name = common_name self.species_name = species_name self.genus_name = genus_name self.family_name = family_name self.order_name = order_name self.spuh = spuh def __repr__(self): return ('<id {} common name {} species name {} genus name').format( self.id, self.common_name, self.species_name, self.genus_name ) def connect_to_db(app): """Connect the database to our Flask app.""" db.app = app db.init_app(app)<file_sep>alembic==0.9.4 certifi==2018.11.29 chardet==3.0.4 click==6.7 Flask==1.0.2 Flask-Migrate==2.1.0 Flask-Script==2.0.5 Flask-SQLAlchemy==2.2 gunicorn==19.7.1 idna==2.8 itsdangerous==0.24 Jinja2==2.10 Mako==1.0.7 MarkupSafe==1.0 nose==1.3.7 psycopg2==2.7.3 python-dateutil==2.6.1 python-editor==1.0.3 requests==2.21.0 six==1.10.0 SQLAlchemy==1.1.13 urllib3==1.24.1 Werkzeug==0.14.1 <file_sep># birdverse: a universe of birds! An API for bird taxonomic data. This module uses Python 3 TODO: - Clean up imports of DB methods to centralize DB code - Write tests for new routes - Add a proper logger <file_sep>taxon_levels = [ 'common_name', 'species_name', 'genus_name', 'family_name', 'order_name', 'spuh' ]<file_sep>import json # 'common_name', 'family_name', 'genus_name', 'id', 'order_name', 'species_name', 'spuh' def create_dto(birds): dto = [] for bird in birds: bird_obj = {'id': bird.id, 'common_name': bird.common_name, 'family_name': bird.family_name, 'species_name': bird.species_name, 'order_name': bird.order_name, 'spuh': bird.spuh } dto.append(bird_obj) return dto<file_sep>import os from flask import (Flask, request, session, g, redirect, url_for, abort, render_template, flash) from flask_sqlalchemy import SQLAlchemy import import_birds from taxon_levels import taxon_levels from formatter import create_dto app = Flask(__name__) app.config.from_object(os.environ['APP_SETTINGS']) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy(app) from models import Bird print('Running with {}'.format(os.environ['APP_SETTINGS'])) @app.route('/') def default(): return 'Welcome to Birdverse' @app.route('/populate') def populate_bird_data(): stale_birds = db.session.query(Bird).delete() db.session.commit() print("Deleted {} stale birds".format(stale_birds)) import_birds.populate_the_database() return 'This route fetches fresh bird data from outside source' @app.route('/bird') def bird_query(): for key in request.args.keys(): return get_a_bird(key, request.args[key]) def get_a_bird(taxon_level, bird): if taxon_level in taxon_levels: print('Searching for {}: {}'.format(taxon_level, bird)) kwargs = {taxon_level: bird} birds = Bird.query.filter_by(**kwargs).all() formatted_birds = create_dto(birds) for this_bird in formatted_birds: print(this_bird) else: print('request made with invalid taxon level: {}'.format(taxon_level)) abort(400, 'errors: taxon_level: invalid taxon') return 'getting a bird: {} {}'.format(taxon_level, bird) if __name__ == '__main__': app.run()<file_sep>import unittest from birdverse.birdverse import app class BirdverseTest(unittest.TestCase): @classmethod def setUpClass(cls): pass @classmethod def tearDownClass(cls): pass def setUp(self): # creates a test client self.app = app.test_client() # propagate the exceptions to the test client self.app.testing = True def tearDown(self): pass def test_home_status_code(self): # sends HTTP GET request to root and assert status is 200 result = self.app.get('/') # assert the status code of the response self.assertEqual(result.status_code, 200) def test_home_default_response(self): # sends HTTP GET request to root and assert correct default response result = self.app.get('/') # assert the data of the response self.assertEqual(result.data, 'Welcome to Birdverse') def test_home_get_a_bird(self): # sends HTTP GET request to root with a bird, get that bird back bird = 'tinamou' result = self.app.get('/{}'.format(bird)) # assert the data of the response self.assertEqual(result.data, 'getting a bird: {}'.format(bird))
e285fc351f3762a9ff14932c36db687456069896
[ "Markdown", "Python", "Text" ]
11
Markdown
dovekie/birdverse
050c28cbcf2e1b6d2005b5acb39f9be4039dc870
69f89c71b781e50c9084150bc77e8059f32a3b0c
refs/heads/master
<file_sep>use std::fs::File; use std::io::prelude::*; struct Forest { rows: Vec<String> } impl From<String> for Forest { fn from(input: String) -> Self { let rows = input.split("\n").map(|s| String::from(s)).collect(); Forest { rows } } } impl<'a> Forest { fn zoom(&'a self, xvel: usize, yvel: usize) -> ForestIter<'a> { ForestIter { forest: self, column: 0, row: 0, xvel, yvel } } } struct ForestIter<'a> { row: usize, column: usize, xvel: usize, yvel: usize, forest: &'a Forest } impl<'a> ForestIter<'a> { fn total(&mut self) -> usize { self.filter(|v| *v).count() } } impl<'a> Iterator for ForestIter<'a> { type Item = bool; fn next(&mut self) -> Option<Self::Item> { if self.row >= self.forest.rows.len() { return None } let row_len = self.forest.rows.get(0).unwrap().len(); let current_character = self .forest.rows .get(self.row) .unwrap() .chars() .nth(self.column % row_len) .unwrap(); let result = match current_character { '#' => true, '.' => false, _ => panic!("Non tree or ground. Are you in space? {}", current_character) }; self.row += self.yvel; self.column += self.xvel; Some(result) } } fn main() { let mut file = File::open("src/index.txt").unwrap(); let mut forest_string = String::new(); file.read_to_string(&mut forest_string).unwrap(); let forest = Forest::from(forest_string); let tree_count = forest .zoom(1, 3) .total(); println!("Encountered {} trees", tree_count); let mult_total: usize = vec![ forest.zoom(1, 1).total(), forest.zoom(3, 1).total(), forest.zoom(5, 1).total(), forest.zoom(7, 1).total(), forest.zoom(1, 2).total() ].iter().product(); println!("Total product: {}", mult_total); } <file_sep>use itertools::Itertools; mod input; use input::input; fn main() { let part_one_result = input .iter() .tuple_combinations() .filter(|(a, b)| *a + *b == 2020) .map(|(a, b)| a * b) .next() .unwrap(); println!("Result: {}", &part_one_result); let part_two_result = input .iter() .tuple_combinations() .filter(|(a, b, c)| *a + *b + *c == 2020) .map(|(a, b, c)| a * b * c) .next() .unwrap(); println!("Part two result: {}", &part_two_result); } <file_sep>pub const input: [&str; 1000] = [ "1-9 x: xwjgxtmrzxzmkx", "4-6 r: rrrkrgr", "4-5 v: vvfvvvn", "5-16 m: pxmrtmbmqmcldmmm", "15-16 s: bsshsszslssssslqdsss", "10-12 g: gggggggggzgvg", "2-7 n: dntnrng", "11-14 j: xrjflbmjszzjbjjh", "2-6 r: frxrrrfjnmr", "6-7 h: hplhgcsphh", "4-5 w: wwwwz", "1-6 g: ggdggnggg", "3-4 c: cccc", "5-8 k: kjgmkkfwxkwqkkgfnv", "14-15 h: xpwhdjhhjhrdjkhfh", "6-7 g: vgggggdhgsp", "1-3 r: rtdcrthphrkzxh", "15-16 j: jjjjjjstjjjjhjjjjj", "8-10 k: kkkkpkkqkv", "1-4 s: sssssj", "2-3 d: hdbmbpswddwkkr", "6-7 s: ssscssnss", "8-9 z: zzzzzzzftz", "7-8 t: glwvkgtn", "3-10 n: nnnnnnnnnnn", "5-7 z: lzzzzfhj", "8-9 l: llllllltn", "1-2 p: dpcppp", "2-5 d: hcfdltbgt", "13-16 r: rrdrrqrrrrrsbrrr", "7-16 l: lllltllllllllllllrll", "9-14 z: vzzzpzfzdzzzzzzfczz", "3-5 f: ffffb", "6-8 s: csssssjrbdsgs", "9-18 r: rrrrrrbrrrjzdrrrcrr", "2-5 d: fdzxdj", "13-14 c: cclcccccccccmc", "9-10 z: zzvszszjbnzzz", "5-9 s: ssqshwsss", "4-11 x: hxxxxjvdxcqplp", "4-6 t: mxtrtttttttttt", "3-8 w: wmwwwnbmtw", "5-6 x: xsczxd", "2-7 w: pwvtgkwwwrpjr", "7-9 w: wwwwwwwwj", "3-9 h: hhhhbhhhschhh", "1-4 p: tlwx", "4-5 w: lhzjwwwwmv", "6-7 p: ppppglprp", "2-16 m: jqmmmmmzmmmmmjmbxmw", "8-10 g: zhggpgrrlctggg", "7-18 z: pltbcznlvtzgzczzchbz", "10-11 t: jttttgtttttt", "3-8 k: kkkkkkkkkkk", "19-20 x: xxxxxxxxxxxxxxxxxxwr", "9-16 l: llllllflllllxpllzl", "10-12 m: mmjmmmmmmvms", "1-4 c: cdxvxczcc", "7-10 n: nnnnfnvpncn", "10-17 z: zszzzrzczxzfzzzzlz", "4-9 k: kkkdkkkkfk", "12-13 m: mmgmmqfgmmtmm", "4-6 s: tdmmcs", "10-16 n: nkfpnncncnnntmtc", "2-3 w: vwhwf", "7-17 w: wwfwwwqhwwwwcwwww", "5-8 q: tkqrtqqsqkwq", "9-10 p: ptpppppppd", "1-5 f: cnncnmnf", "2-9 k: kkjdsnsqkgprtqb", "9-11 n: nplnnnnnnnmnn", "4-6 r: rrkrzrr", "3-5 z: zzzzsq", "17-18 r: rrrrrrrrrrrrrrrrrx", "5-8 c: rcccdcclc", "1-9 c: vcccccccbc", "9-10 x: xxxxcbxxxm", "2-5 c: cccfn", "8-9 c: cccccnctc", "4-8 l: flrhfzwllm", "1-5 l: fllfllrklx", "5-10 j: jrjkrjjjjxgjqj", "5-10 v: dsxvmvvjtsc", "4-6 v: bsqvdghvnzdfvjcfvvv", "6-11 m: mmmmmmmmmmpm", "6-9 q: qqgqkcccsgqqjspj", "2-5 n: nvsrc", "14-15 n: nnnnnnnnnnnbnms", "3-4 m: mmbm", "3-11 h: hhbhhhhhhhhhhhhhhhh", "7-9 k: kkkkbknkjv", "11-15 g: ggvgggfgbgvvzjgxghgg", "3-4 z: zzzz", "2-5 w: wwwhww", "9-14 j: jjjjjjjjtjjjjw", "2-4 j: jjbljsj", "6-9 w: bwtkbttwqvwk", "1-3 l: lllpjl", "9-10 g: ggfmggggsrggggg", "3-5 t: ttwzxl", "5-7 k: kkwtbckkk", "9-11 r: rbgrrhrrrrrr", "9-12 g: ggggggsggglnggg", "1-5 b: bbbwjs", "6-7 m: xkjmdmm", "6-8 g: gggggwgw", "12-15 v: vrvvvqvvpvzvvvvrhqv", "15-17 s: hsnjsrsdxpjswsxsss", "9-12 r: rnhnrrsrrrrr", "1-3 d: ddnd", "1-11 m: mmtxkcdrvcmx", "1-18 k: kxkkkskkkkkktkkmkc", "5-9 h: vfxhhshhvhhbhr", "2-3 k: wtrcckttcqrj", "2-7 q: wnqcqqxw", "1-9 s: sqsssslsssssssssss", "4-6 p: mwvpppzp", "1-4 v: qlvnvv", "10-11 z: lzzzzzzzznt", "2-14 q: qwqqqqqqqqqqqfqqr", "15-20 d: dddddzddddddddlddddt", "11-15 m: fvsqwbnqmbnmgcm", "3-4 c: fncnfdjzcxwbpcrn", "4-7 z: jsxzzszzqtwzmcznfs", "5-6 x: glxxxxrxfxxwl", "5-13 b: pdbvhwjwnbdwbrbbjwf", "7-8 h: hhthhhvvt", "8-11 f: pfffffxffpbf", "5-6 n: ndtlxnnnqdmcnv", "10-12 s: sssssswssdshssss", "15-16 s: ssssssssssqsssss", "4-5 s: sssss", "3-4 g: ggggg", "3-4 c: ccjv", "7-12 v: rrrngfwhslsbpvbmwnn", "4-10 n: nxnbnnnbxnnn", "7-15 d: fggdddpgslqgdwhdndw", "6-10 h: hhzzghhfdchhjnm", "8-9 c: cccccccnc", "9-10 h: hhhhhhhhll", "2-16 w: nwfwwwzwvrbmwwww", "10-13 k: kkkksjkkskqtkkmkknks", "4-9 f: fffwfffbkc", "4-11 v: gcfkvvvvfvv", "2-5 l: llflftlmlglc", "7-10 l: llldljllgsbl", "10-19 g: svcsnlshppvrxzghhzg", "3-8 d: dddwdzvmddd", "3-5 m: kpmmjpmmmdz", "13-14 n: nnnnnnnnnnnnns", "3-8 b: bkbbbbbbbbbbbbbd", "2-4 g: jghfggh", "8-11 m: mmmmmmrmmmm", "9-12 j: pbjjpjnjxjjfsjzsjps", "6-7 r: rrrrrrrr", "8-13 v: vvvvvvvbbvvvvvw", "4-17 p: tpppppprzpspbpplppr", "2-3 h: wbhhzxhllh", "2-15 c: nvbcckcpccrtccwccsc", "12-13 j: jjjjjjjjjjjzhj", "4-10 p: dznzpnxzppl", "5-8 r: jrrrsrrrrr", "7-10 q: gjqjcqqqqsqfqqq", "8-12 k: kkkkkkkkkkkg", "3-14 m: mmtmmmmmmmmmmmmmm", "3-12 t: khgttqtcltshttwqgt", "14-15 b: bbbbbbbbbbbbbqb", "14-15 f: fffqfmffpnffffg", "5-16 j: jlghwmmrbdvdfjbj", "7-8 v: vvkbvvrv", "2-11 m: qmcgxcshgwmfm", "11-12 m: cmmmzfmcmmzmmmmjmr", "6-7 n: hnnbnnnw", "4-8 m: mvdtmstm", "4-7 m: bcrmmjbpmmmsdnrmm", "1-4 w: wwwww", "12-14 j: jjjjjjjjjjjrjhj", "2-9 h: ghhczbhblx", "2-11 v: vmvvvvvggvjpvchvvpc", "6-7 f: ffwfflghpwfl", "3-14 k: krkmjkgkzcckjbkkk", "1-2 c: cfcp", "15-17 z: ztzzzdzzzzzzzzzzt", "4-13 p: bmrpdwphzqvppktz", "4-5 j: jjvjtj", "14-20 h: hvchvhhhhbhthlhhhhhh", "1-3 j: kqjp", "9-13 x: fsxxxkxxbpkxmhlrdtfx", "13-14 w: wwpxwwwwwwgtwwcwwww", "2-5 p: wppxkq", "13-15 x: xxxzxxxbxxxxxxvxs", "5-11 q: qvqqqqxqqqqfqqq", "8-12 q: qqqqqqqvqqqq", "8-10 m: mmmmmmmjmn", "17-18 t: ttttrttttsttttttttt", "9-13 h: hhhhhqhjlvhhqhhwh", "8-9 s: ssssshsst", "9-10 v: qvvtvsvcmzvvnpgvv", "7-12 d: djcpndppsdddfdsdd", "2-3 z: dgzwvbrzzbgw", "1-4 k: kwkl", "1-9 d: dkdmdsdwdzvlpv", "10-11 h: hhhhhhhhhhh", "9-10 f: ffffffffff", "4-7 d: ssddddxp", "18-19 j: jjjjjjjjjjjjjjjjjsj", "7-11 m: mkmmrmmlrzsmgm", "1-7 k: kkkkkkknk", "4-5 w: wwwwj", "6-13 s: xslmsfgsssssmslsstqd", "4-5 z: zzzch", "9-11 j: jjjjjjjjjjj", "4-7 h: hjhhkdh", "5-14 v: vvvvglvvdvvvvv", "5-6 q: shqnjdqqq", "1-5 q: dqqqq", "5-7 z: zzznzzz", "5-9 s: vwsfsxssd", "4-5 f: sffffv", "5-7 b: xllbbdb", "1-14 j: rtzjqkpnkjlrhjcjqj", "8-10 w: wwwwwwwfwxz", "3-6 g: sggtlggswf", "11-14 n: nnbnnncnnsgnnmknn", "6-15 c: cclcnccctcrcxqmd", "5-8 l: lmllxwpl", "4-11 p: pppppppcpkdp", "1-4 w: zwwx", "1-3 g: nlfpgfzqkzn", "11-12 w: vbwwgwvwrwlwwmwwwjw", "4-12 j: vzfjgjrkzdrxqfh", "1-2 r: frrq", "1-4 k: vkkkkk", "11-13 d: pndlftgdpdhld", "1-4 r: prrvrrrrfrrrrr", "8-9 m: fmmxmmmmmmm", "1-2 x: xcpxc", "4-16 n: rhbndvjnnsnfnwnnm", "2-10 g: fkzwxtqmgm", "11-19 p: bpppqpppppplpppphpsr", "9-13 g: ggggthggggpjgqgslggq", "4-5 m: mzmmxcfwmdpz", "2-13 t: tttttttptttts", "3-7 q: qqvqqqcqq", "6-9 j: jsjjjjccjwjcjjj", "7-10 r: rdlrrrrrrr", "9-12 r: wrrzsrcrgcbrhqvrhlp", "6-7 j: jjxjjzhxj", "6-7 m: mmmmmmmm", "1-3 m: mldvdmxmbk", "10-11 f: ffffnffffkqf", "5-17 f: ffffsfffftfffkffn", "4-5 b: fbwbhvx", "14-16 g: ggggggggthgggggsvd", "2-3 s: cvsbw", "5-10 g: qltgnfghgcrgpnzdsvng", "5-6 p: ppjbpnppxg", "3-8 j: lgjrzwdvdnwvrnj", "2-4 c: cdcc", "6-7 l: llflrhlllgklh", "1-2 p: tppp", "16-17 g: gggggggvggggggggg", "3-14 f: fhfdffftfbggpkfgf", "16-18 b: bbbbbbbbbbbbbbbbbbbb", "5-10 v: thqvvkvlwvdvjzzst", "13-14 p: ppppppppppppptc", "11-14 t: tkttczttttsttmcnltm", "3-4 w: nvxl", "4-6 f: fpflfwftk", "4-6 h: xhhhhh", "15-17 t: tttttttttttttttlv", "10-17 j: jjjjjjjjjsjjjjjjd", "2-4 s: jcgs", "7-9 q: qsqqjhqndsqkqqpvqqr", "2-3 p: tnpplcmdpfn", "2-5 c: crvmk", "1-7 d: tsmzcgddnddddrdxsq", "8-9 c: rlfcpctpncv", "6-9 f: tkzfhffdf", "13-15 s: sssmsscfvsssdsg", "6-8 s: ssjsssjrscsss", "7-10 f: fffffffkfff", "1-6 k: jqtdhpknkkk", "11-12 t: tttttttttttf", "9-16 d: swjbddfpfbntmprdd", "18-19 v: dvvvvvvvvvvvvvvvkvvv", "2-5 j: kjjcqjj", "11-12 d: dddddddcddld", "14-16 f: fffffffffffffffk", "4-7 x: nxxxxxxn", "10-18 p: pppppppppppppppppr", "8-9 k: ktkjkkkkfvklkz", "9-15 h: hhhhhhhhchhhhhhhhh", "18-19 v: hvkvvvvvvvvvvvvvvqc", "1-8 s: xzbxgsxshgl", "2-6 p: ppsjpglptchpzbdhj", "6-7 n: nnnnnnnc", "2-7 j: jhtjjjjj", "11-12 b: vnblqbxkbbwb", "4-5 z: czzzcztsz", "4-9 x: wxpvxxxfxfxx", "9-12 w: wwwwwwwwwgwwww", "2-5 k: cntkkq", "10-12 l: vljplljlllllllll", "1-4 t: tfmvst", "6-7 d: rddddddwd", "2-6 h: bhvwhl", "5-8 c: ccsgccncwgjtcbhccckk", "5-6 r: rrrrmr", "3-8 h: hcrhhjrbhh", "2-4 s: xndshswk", "2-7 m: mmrqmmlp", "7-9 n: nnnbfpmnfnknxnndn", "6-7 f: fvffffb", "6-8 h: vhhhhhtk", "6-7 j: jjjjjwjjs", "1-5 r: rwrrrr", "3-4 t: tlzk", "2-7 k: kkkkkkk", "6-11 q: rqqqqqwflqqjqq", "5-7 l: llllglll", "6-14 r: rrkrrxrmrrrrrc", "1-8 w: lrwpzvhhcwtbrwwpwww", "3-13 b: kbjhskpbrwqpbcbbkb", "6-9 d: ddddbddhdddddddddmg", "14-15 n: nnnnnnnntnnnnhf", "2-18 k: cgjpktthdbfxrclqwzpl", "5-14 w: wwwwwbfwzwcwcwz", "5-7 s: tfhssgrsnbssfl", "1-18 l: wdkwkdlslbllllgzfm", "1-17 h: jhhhhhhhhhhhthhhhh", "7-13 w: wwvwwwwwrwwww", "1-3 r: rgrdrx", "9-11 t: dnxckkwpttv", "2-12 c: cgqxrszcckcd", "4-13 q: qkchpbqqtrtdztrq", "2-9 d: ddddsddddd", "9-19 p: pppppgppppqpppppppp", "8-9 l: lllhlllll", "7-8 h: hhhhhkhvwbhmh", "11-12 w: wwwwwwwwwwwnwwww", "2-3 d: jhcd", "13-16 n: nnnnnnnnnnnnndnnmnn", "6-7 d: dllpddkdd", "6-7 n: nnnnnkp", "7-14 v: vvbcvrvvkmvvsv", "5-7 j: jjjjcjs", "4-10 l: ldllllllll", "4-5 x: rxxxx", "15-16 q: qqqqqqqqqqqlqqqw", "13-15 m: mmmmmmmmmbmmzmbm", "7-10 k: skkkkkkkkq", "9-15 m: mghxpjzqdhjcbmdl", "2-4 t: ttsnwzbdj", "6-7 s: hqtkgtr", "3-4 n: twpknn", "1-3 l: wrldlsdl", "5-6 l: qlxncf", "4-5 s: dvsxs", "7-9 t: rktsrfwttttgwtzgft", "1-3 l: flsf", "6-10 c: cchczccccj", "1-3 k: bktw", "2-4 h: zdqxgrfkfhljhqhkgmfc", "16-17 s: sssssssssssssssvs", "4-8 p: plpfmnhsppnpwnx", "5-10 k: kkkkknkqkk", "4-11 s: nsqnssssvqsm", "6-14 j: jjjzjwczkjjjxjjcjjxj", "3-7 t: tnnbjjhtd", "7-8 l: llllllll", "4-11 z: cwsvrtszxrgh", "2-11 x: sxcxxxjxrxkxdxx", "11-15 m: mmxmbxmmdmmmmfmmfmm", "10-13 l: tllllwzlzlrbllllhnp", "5-6 k: kkkjkmkkkg", "4-7 f: wqqfmffffkp", "1-9 b: bbbbbmbbbbhbbdzbbtn", "10-12 h: hhhhdwbhhqrhhhdnxhr", "1-8 r: qfpnfrrrrz", "16-20 b: bbbbbbbbbbbbbbbbbbbb", "1-5 c: hwqccmwcctcnclcb", "6-13 c: clccccqqcccjczpgj", "13-14 j: jjjjjjjjjjjjjh", "2-4 j: jkfp", "2-7 d: qqxdcdjqg", "5-6 r: prrrrd", "7-8 l: llllllll", "2-3 w: nwlm", "9-12 v: vnknxncvgvrww", "6-16 s: sjnwfsksnszcglxs", "5-17 z: zzmkzzzzzntzjzbwpdjz", "12-17 j: ljjjjjjhjjwtjjjjdjwj", "8-10 s: dnnjlfkxls", "2-6 m: jmmqmdkjm", "9-11 m: mmmcmmmfsmmm", "14-16 p: ppppptpppphrpxpppp", "4-15 d: dfkfxdddldddddddlddp", "12-14 q: qqqqqqqqqqqwwgq", "1-6 g: tgggggmggggdg", "10-18 w: wwwwwwwwwbwjwwwwwt", "8-9 t: ttkttcttsrgrzlftpt", "3-5 j: jjjjjjjjjjjjjl", "17-18 c: ccccccczcccccccccs", "4-9 d: hjddddddddm", "2-4 x: lxjfp", "11-12 v: vvvvvvvvvvjv", "1-4 z: fmzblzvzm", "4-5 h: hhshhh", "3-6 t: ptvrtt", "7-15 k: kkkjzkckgckskpkk", "12-15 w: wwwwwwwwwwwftwdw", "3-5 z: jrhns", "5-6 n: pxmnzn", "1-3 b: bbbkbbbbbbwb", "1-10 r: rrjrqrrwrrrqv", "11-12 w: wwwwwwwwwwwwwww", "5-6 j: jsjjjp", "6-11 h: lhbbvmhwrhh", "18-19 q: qqqqqqqcxqqqqqqqqxwq", "17-18 l: llllllllllllllllxql", "3-4 j: jjljjn", "8-10 z: zzzzwnzlzggz", "6-7 t: tttttft", "11-12 f: ffffffffffnf", "2-8 b: hqbbbbbsbb", "4-5 w: stljwbxpw", "1-2 z: grxfpw", "6-8 w: wwwwpwwxw", "8-14 z: zqzzzzzvzzzzzzgz", "4-11 b: cckgrcmbpvbbw", "2-9 d: xqxbdddjds", "3-6 x: xxrxxx", "15-16 n: nnnnnnnnnnnnnndnn", "6-11 x: lqmxxxsxxfxxxxlx", "1-12 s: vssssshssmsk", "1-16 m: bmgkkmwmmzvmmmmmwflv", "3-15 t: thkvttsltnbgztt", "9-17 z: zzzzzzzzzzzzzzzzzz", "4-6 f: fjwfff", "3-9 d: ddddddddd", "6-10 k: kjkbkkckxkknqkkdc", "6-7 n: nsnckwnmn", "7-13 t: ptbtjqttwwtftpntdq", "7-10 r: wrhhrrrrrwrrrrvqrms", "2-3 c: zcrwhtccb", "5-7 m: nnwmmdmmmccv", "3-5 j: rtjjmjrjl", "5-6 s: dssjhsdmbksrks", "16-18 c: ccccclcccclccccccc", "7-16 b: qpzgqxdbssmzptrv", "6-8 b: bnsbbgdbggxbbszbm", "1-10 h: lrpstqvhhhhf", "4-6 s: tvssppwvss", "3-4 g: qqqhcd", "4-7 c: qxcqzccckxcpcxcw", "1-13 m: nbwdmspmmwbbmm", "1-2 j: xjrczrk", "9-10 w: wwwwwwwwwd", "2-4 h: hhhq", "7-10 j: bjmrrjsjthjnnjjxjjd", "3-7 f: srfwwfvf", "3-4 b: nbbzb", "3-5 n: nnnnn", "7-8 f: fxfnfffzpqffgdf", "10-12 k: kkpkkkpnkkmkjbkk", "9-10 k: jkkkkkkkwqk", "4-6 z: rzzzzs", "4-7 v: vvvtvvjq", "6-12 z: dzjnzczzpzgzzzx", "6-8 s: smsvbkswslssrdfjsc", "5-7 b: bwbbbbbbr", "1-3 d: kddbsmmbv", "3-4 b: bbbb", "5-8 r: rqrrdrrr", "7-8 m: mmmmmmzm", "9-11 q: xvnlfvhxqfql", "3-4 w: wfwj", "1-3 q: gqqcqg", "1-2 q: cqlxrq", "6-12 s: swwjjssjsstmqfssdh", "2-4 q: bqqq", "5-6 c: ccccbscgfc", "14-15 x: xxcxxxxxxxxxxxm", "6-12 f: fzfchfnrxfrdffhfl", "14-17 g: gggggggggggggjgpgg", "5-8 n: njkcngznn", "10-13 d: dddlqddddvddr", "2-4 c: xgcg", "2-10 s: sxsnsdmszwmsss", "6-12 q: qbcqspqqqkqrq", "6-16 n: xnnnnnnnnnnnnnnfnnn", "6-12 s: tssnssmsssssssssnhr", "1-4 v: vwvvv", "8-10 h: rzmhhjvqhht", "1-4 t: ttjdjftfctt", "1-4 k: nkkz", "1-2 q: vkvqkqq", "9-19 n: qxmjqxnxnblqnnqfgsrd", "15-16 h: hhhhhhhhhhhhhhghz", "2-5 g: jggpxdgwjpsrv", "12-13 c: xccccpccrcccc", "1-13 g: nfgbghqrljstggcgq", "14-17 g: gggggggggggggmggggg", "4-14 s: sssbsssssssssgs", "1-10 d: rcxvxcgddnhwd", "4-14 g: vccvdldqdgzltq", "8-10 z: zzdczzvrzzzzr", "5-10 t: ctgtttftqtrbt", "3-5 v: vvrvx", "9-10 w: wwwwwwwwwwwww", "4-6 c: hgccmcccc", "16-18 s: ssssssssssstssscsh", "2-7 z: zzflfrtdx", "4-10 v: vvlsvvvvkrc", "10-16 d: ddddwddddbdgdddwd", "3-4 v: gkbqbtrv", "3-4 h: cjdqvwhhththvx", "3-5 b: bbbkbrb", "3-5 m: ptkqdgsmbcmmblwp", "4-17 q: mlqqgsqqqfqkcqqxqq", "6-17 m: mdvqvmmxlmzmvmmdm", "1-3 r: hrrtrrrrrrrrrwlr", "3-5 j: jjjjhj", "11-12 q: dqpqqqqqqnzlqq", "8-11 d: dddnddnddtdddd", "3-16 d: dpddxtlqsqldrpddq", "7-13 z: szhzmmzzzzmzzzz", "6-18 h: mkxxqtbnnjgnvxnhhhc", "4-5 n: nknfrhpn", "16-17 d: dddddddgdddddddddd", "14-16 w: wwwwwwwwwwwwwwwww", "2-3 t: rttfdstqpdtg", "3-4 s: gghrfxbfshqssj", "1-9 j: bjjjjjjjhjjj", "1-2 p: xmpgppppppp", "9-14 k: vqpxrkmskfpnxq", "1-5 x: xxxxx", "1-14 p: bsxnwvpkphdppphpkwp", "5-12 d: xdddmzddfddc", "9-10 v: gvvvvvgvhnvw", "2-7 x: xxxxxwgsvmqnkxv", "3-15 c: ccscccccwccccccc", "5-8 w: nsvgwzdf", "7-14 w: wwwwwwwwwwwfwswcw", "5-10 r: qrrlwcrrwz", "7-12 f: hfnphfpjffstff", "2-6 h: hqjhmph", "3-13 x: cpxxxzcrbjxxxb", "4-8 k: kkkkktkkkkfkf", "7-10 g: gggghghsgwf", "8-9 s: sswswssggss", "6-10 l: qlllljllhlll", "8-11 c: cccwccrbcbccc", "5-6 x: xxxxxxg", "1-3 w: cwpww", "8-11 v: vvvvvvvvvwvv", "1-2 b: bbgl", "7-10 b: zbkbcbbbsbb", "13-15 t: tttttgtttttttktttt", "12-14 x: xxxxxxxxxxxxxqf", "6-7 k: kmrkkwmk", "4-5 m: mmxjmdrhzkmxxphjmz", "2-3 t: tnvtndw", "4-5 x: xxtxxtxzf", "1-3 m: nwmglfscmwrjtzp", "10-11 c: cnccckcckcwdc", "14-19 b: tvbmrqtchwblbqbbqbb", "9-10 x: fxxxxxxxjxx", "4-5 g: gggggkggx", "8-12 k: kkkkkfkpkqkwkkk", "2-6 v: chpvkvt", "4-10 r: rmbjmcrgrrfrtmblhw", "4-6 n: rnnwtn", "3-10 v: htclcjhjkdv", "10-13 w: wwwhhwwwrwwzww", "18-20 w: wwwwwwjwwwwwwwwvwtww", "7-8 w: phrwbwwmc", "16-17 q: qqqqqqqqqqqqqqqqx", "2-5 k: kzknsxkkgtvmwlfrmrg", "3-4 b: zbbbb", "5-8 v: hfclvvpc", "3-15 t: ctfthpmgznjnhgtth", "1-6 t: httttq", "5-6 w: wwxhgww", "3-5 m: fmtnmmm", "11-17 n: xnnchnzpsmcslvzcn", "5-6 m: mmmmcm", "1-7 r: rwsgcgvjmtxwkqtr", "6-16 m: mmmmmmmmmmmqmmmmmm", "5-10 s: sssggssssjsssmsss", "9-14 p: ppfppzppnvmpqdvpp", "2-4 l: wclwrlrdvh", "6-17 g: gggmkglggwgpgkmglt", "5-7 z: zzzbzpz", "4-5 q: qbqqlzpqg", "10-19 h: hhhhhhhhhrhhqhhhhhhh", "6-7 m: nfnxmsmhtmhsmmmmgmsl", "2-3 m: mkfmmm", "8-10 j: xrjdnjjjnjjcjjjjjj", "3-6 x: xwrjxhjxx", "6-7 z: zzzzzzzg", "8-17 k: kkkkkkkkkkkkkkkkk", "6-9 n: rnnxnnbwnsnnwn", "6-8 m: mkmmmsmm", "4-6 q: qqfxqqq", "2-8 s: hxmfbkszk", "6-7 r: rrrrrrr", "2-5 h: hhqzhhhh", "5-15 b: bhbvnrbrbblbbhh", "12-13 d: ddddddtdddvhddd", "5-6 f: fmfcfwf", "4-7 j: njqfxjjjqjjvdj", "6-9 g: fggkggzgghrv", "9-12 b: vbblbxpfrbjbgpwxb", "1-8 s: tzcdrktsqjsxssfsssh", "10-14 f: fffffffffcffffffffff", "13-17 p: pqpppppcpbwpppnprppk", "16-17 n: nnnmnnnnnnnnnnnsj", "10-16 k: kkkkkkkkkkkkkkktk", "8-11 w: wwwwwwwwwwm", "2-5 q: qqqqqq", "2-7 m: mmmmmxg", "2-9 m: mmvlggdmr", "3-9 s: wxdbmlcrlpnzmkfdfs", "12-16 z: zlxzgznqqfzsqtwc", "6-7 f: flvmfffjffbmgfzfgfp", "2-3 g: cgggqgxqgv", "2-3 f: rffvf", "1-8 h: vhhhhhhvhhvhhhhf", "6-12 x: vzdxxxgxtxzxxxqc", "4-5 w: rwwwwww", "7-10 r: brwrcrrkcsj", "6-10 q: jvqqqqqqqmq", "5-18 v: lvhvvwvvvvvlvlvvmv", "6-9 z: zzvzcwlzslhlzqsf", "3-6 x: sdknfxvwtcfcjgmv", "8-9 l: lqcwlllsllll", "1-4 k: dgklv", "2-6 q: qqqptfqqqqq", "4-7 m: mrmcmmmm", "4-5 r: rrrblg", "1-8 c: qcccccvntc", "6-7 m: mzbxmmmnhmqcmmqvbmcp", "2-4 t: ptvqx", "9-10 s: gpssssssgss", "4-18 b: bbbbbbbbbbbbbbbbbfb", "4-5 f: ffffgf", "3-6 l: lslglw", "1-5 l: ltzlllsdlmrllkvbztvr", "15-19 l: llllllllllllllnllll", "10-11 j: jjjjpjjjjjncj", "2-3 w: wfwgd", "1-7 r: vrrrzrr", "3-7 k: kkkjckkkgkbtvm", "9-12 k: kkkkkrckcrkk", "1-6 b: hpbjbvb", "6-8 s: ssssssvss", "2-4 x: mpxk", "6-10 x: xxxmrwhgxxxjx", "7-8 x: xxphxxxxx", "6-19 n: mdrlnnpnjndqgnkfwnnn", "2-5 q: qjwtbmkhtnxm", "15-17 j: xjjjjjbjqjjjjjjqjjjw", "5-7 x: pxxxxsxxsxx", "3-6 t: ttttrp", "8-11 f: fffffffffrkzf", "6-8 r: glsprkbp", "10-12 m: mmmmmmmmmmmsm", "13-14 z: zzszzzszzbzzzplzzz", "19-20 c: ccccchwccccccccccncb", "7-12 z: qzggglzlhshnrwt", "12-14 z: zzzzzzzzhzzwzc", "1-2 s: sssl", "1-3 q: fsqmwq", "1-6 z: zmzztzkzznmflqffz", "9-11 b: bwbbjbbbtlbbn", "4-6 s: nktszz", "2-5 j: nqjhjkb", "7-16 l: lrlllllllmllswlsl", "2-3 f: fjqvfff", "7-15 w: hwxghddqwwwwwww", "2-4 z: zgzfx", "5-6 h: vhhjhthh", "13-14 h: hhhhhhfhhhhhhhphhhh", "16-17 k: kkkkkkkkkkkkkkknx", "7-15 l: dllllllmlllfllf", "2-6 w: mtkwwwww", "2-7 k: zpkkgldk", "7-9 d: htmtjddddddqvddcd", "4-9 v: rvfbbwzdwcvvqv", "6-11 m: mmvmbvmmmsmmlmmm", "3-8 p: xpxppsgpbxp", "2-6 f: vffbszhvvrdfkxc", "8-11 v: lvrrlvvqqvr", "5-17 h: hdhhbhhzhhhhhhsbl", "8-10 f: fhgffgfrfqtf", "9-12 s: ssssfssdpssswf", "9-12 m: mmmmmmmmpzgmmm", "7-9 l: zlmllvwlllldl", "8-11 m: mmdmfmmdxbmxbmm", "1-4 m: fklssmffwzgqcvdpm", "13-14 c: cczcccccccccccc", "5-9 f: frtkfpffsfff", "5-8 f: ffffgffr", "3-8 m: mmxsmmmb", "1-6 m: mdmmmm", "1-2 h: hhdtmhwfpt", "4-14 d: dmrkdvddmdsdddbsgd", "6-7 c: cxccgcccc", "6-12 v: xcqvjvvsdvvvpv", "11-14 d: gltkjvddwjdkrln", "2-13 f: ggffllflfbfffqkfmf", "10-13 c: xkvcccccrmccccc", "17-19 q: qqsqqqqqqqqqqqqqfqmq", "8-10 t: ttttlttwtlt", "4-5 f: wffrd", "2-16 v: tvhvvqvrvvvvvvqvvf", "2-4 c: cccc", "3-8 z: zrzzpzlzzhsdxqqfx", "6-10 k: kkkkkkkkkk", "5-7 r: rvrrvrz", "14-15 w: wwwwwwwlwwwwncwvwjk", "6-11 q: qfhxqqgqqqsvcpr", "4-7 f: kflfffzff", "2-14 t: rtttttptlxsttt", "11-15 t: ttttttttttftbvqttt", "6-10 c: cckwlchltchcczgw", "3-8 s: ssssvsqnss", "1-8 h: mhhhhrhhh", "13-15 b: bbbbbbbbbbbbbbnb", "15-17 p: dpppppppppspppcps", "5-12 l: xbfjglklphtl", "2-4 v: vvvvbvwpvvvrv", "3-5 k: plhjkkqkskz", "6-12 z: zzzzzczzzzzk", "2-3 j: xvjljj", "6-7 r: rlrrrrrrzrrzrrr", "1-12 t: mqrkgpktbsqxg", "10-13 z: pzmzzxpnzxpgzzzhzz", "5-13 s: gslsskvgxssssnpj", "10-14 m: mmmmmmsmmmmmmk", "2-5 b: tnbdsfwdzxrkjdb", "2-15 h: hnxhzhmhhhhhwwb", "1-4 c: ccccccc", "9-10 b: bbbbbbbbbl", "4-5 j: jsjjj", "3-6 n: xmmnppbn", "11-12 m: mmmmmmmmmmmm", "2-4 r: jrgrcpvgctrrr", "3-4 g: gggr", "14-17 n: nhnpnnnnznnnnnnnknnm", "4-5 k: krkkf", "11-17 h: hhdhhhhhhhhghhkhx", "5-19 q: dqbcqqqqsqqzqqqqqqv", "5-16 t: ttrkttttstwttttqdt", "11-18 h: dhhhhhhhhjhtjhhhhhh", "5-8 c: ccccrccfc", "1-3 v: nvvnv", "7-12 m: prmmzmtmmmssdmmmmt", "15-16 r: rrrrrrrrrrrrrqfr", "7-19 b: djbbbbqjbdtbslbgbbmb", "10-13 w: wwwwwwwwwwwwww", "5-15 p: mbpcjqmmhpppkfmrbcww", "2-4 n: nxbjknms", "5-11 s: hxhcsldmxshdksvsss", "12-16 q: qqqqqqqpqcdqqtwkqvq", "2-7 j: tjlpcjjjjnj", "6-7 s: ssssskm", "1-4 t: tttttx", "5-10 q: pqmnqrlqchbjzqqvq", "11-15 q: qqqqqqqqqqhqrqqrqq", "3-5 k: jhkgkxkqfskg", "14-15 f: ffvffmfffffffsffqm", "4-5 x: xxfxhfxx", "2-4 b: ktbv", "3-4 t: wjtwxvxctrcttb", "1-3 s: shssg", "8-12 z: skkzbdpzdkzzz", "1-3 f: rlfffqft", "5-8 s: fsrcnjsgsmgs", "7-17 v: vvvvvvvvvvvvvvvvvvv", "4-5 k: kklmq", "8-17 h: hhhhhlvghwkhrfzhxh", "17-18 n: nnnnnnnnnnnnnnnnnn", "3-10 h: mhhhhrhznwvhh", "8-9 x: xmxxxxxxx", "4-5 p: ppppk", "11-13 t: tttttttttttjtcn", "3-4 q: qqvhz", "3-8 l: gbpqclnkwlhdlml", "12-13 f: fffffffffffrf", "3-11 s: ssjssssssslssss", "6-7 b: bbbbbwbb", "7-9 r: krrrrrfrj", "13-14 b: bbbbbbbbbvbbbp", "2-4 x: ltgbx", "7-10 r: smrrrrkjrrr", "3-7 n: vnqpngjdgrw", "7-18 t: ttltqtsktrjgxtqhtt", "2-5 v: dvvxbvvvnk", "2-5 n: nnnnnpn", "1-3 t: nttmtx", "3-4 z: zpszz", "1-12 p: pmpxphlpppppppqppp", "3-4 v: qvvvvvv", "9-12 g: gwgggggggtgqgg", "2-4 n: knpn", "3-13 d: hncbdrvpddddcfddd", "5-9 s: ssnspslslsfkpskss", "1-2 s: ssczgkvtlp", "5-6 p: pmvpzpppkm", "1-4 j: jjhr", "5-6 s: ssssxl", "1-3 t: ttrt", "16-18 n: nnpnnnnnnnnnnnnnnnn", "4-5 n: nnfnl", "1-4 b: bbbb", "7-8 l: nljlllkhl", "11-12 n: nnnnnsnnnnnnnpn", "5-10 k: kkkkckkkkhkkkkk", "7-10 s: zfsssfldxsvqsxdsqs", "5-6 q: qqqqqp", "6-7 q: qqqqqqq", "14-16 w: wwdhmwwjwwwwnwwlwwwv", "8-9 l: llllllldll", "12-14 c: ccrccccccccrcccccccc", "1-3 n: qnwnh", "1-4 l: mlll", "1-3 s: sssssss", "4-15 h: mhclhhhjllhhhgh", "15-16 x: xxxxxxtxxxxxtxttxx", "2-4 r: rmjh", "6-9 z: zzzzzpszt", "17-18 n: nnwnnnnnnnnnnnnnppnn", "8-11 v: vmvmvlvbvvvvv", "7-8 b: bbbbbbdf", "2-5 k: kkdkk", "8-9 d: dddsldddvxlhd", "7-8 h: hhhhkhxshxhn", "12-14 c: vcchpxcnmgkctpqcc", "1-5 w: wwwwww", "1-2 x: xdmk", "1-9 p: pbfvrdpqqn", "2-4 s: mtnvzhnzs", "4-6 t: cttxvtttx", "4-8 t: qttmtzttkwftrjk", "7-9 c: cccccccccc", "2-18 j: zjjqxjfqqlmjrjhjqx", "2-5 q: qmkqgq", "5-11 k: kkkkkkslzkkkkkrx", "16-18 h: hhhhhhhhhqhthhhvhh", "5-13 h: hhfhhhhhmhhshhhhhhh", "10-12 r: rkrrrrrmrrrrrr", "8-10 n: rnnckhmjnxmfggsgtnnn", "19-20 c: qsccznccccccnccccccq", "1-4 k: wtkck", "7-8 s: sssmssjssss", "3-5 l: llslv", "3-7 t: tvgjqgjbvtgpkt", "13-15 b: bbbbbbbbqbblrbbb", "9-10 z: zzzzzznzzb", "6-16 c: kpcnsccgccxfwccl", "2-3 d: ddbd", "10-16 v: vvvvqrvvsvvvvvvl", "3-12 d: dzdxxhddnlkddddk", "8-9 b: khbbbfbbbbb", "11-12 z: zzzzzzzzzzzz", "5-15 n: bnlvnnrjbnqlnnn", "1-2 q: mqqpzjc", "11-13 h: hhhhhhchhhhjhh", "8-11 x: nxfcxbjqxdlcxxxkxxx", "14-18 v: vvbqvvvvvvvvvvvvvvvv", "7-8 f: pgtlfffmjffnt", "10-18 m: mnkrmmmmmqmmmmmmmjm", "1-4 l: lghlhcnwprlgvw", "3-4 p: npxplpwl", "12-15 s: sfkwnvsssvssssfsssrp", "3-7 z: ztqnzlxjmzzbjfnxcw", "17-18 q: qqqqqqqqqqqqqqqqqq", "3-6 z: jczztzzbhmzzw", "3-7 f: skffttjffqfnchfrf", "4-6 m: hmqmcrmw", "10-11 t: dftttqttttttl", "7-13 p: spxnpgtzpppjpwppptp", "8-9 q: jqxqqqqxqq", "3-4 h: hhhh", "10-13 z: pgzxhxxpzzssj", "5-9 x: xfrdmjxmrxrqjpxbfxxx", "8-17 d: ddpddddddddsgddzddn", "1-4 g: vggdggggggggggggggg", "10-12 m: mmdqsmwvjjmv", "2-7 s: ssqsssk", "13-14 n: nnvnnnnnnnnnsgnn", "2-16 k: kkkkkkkkkkknkkkk", "3-6 p: dprphc", "2-10 k: mpkstkxkdb", "2-3 s: ssxs", "9-19 t: ttjttjttrtsqtmttttt", "4-5 j: jrjjtsjjd", "6-7 x: xxxpxjx", "13-15 q: fqfqqqqhqcqfqqbqqq", "1-3 z: zfgrzl", "6-8 n: nnnnnphm", "1-8 b: bbbbbbbbb", "4-5 h: thhgj", "4-8 v: vvvcvvvp", "8-9 t: ktttttttt", "3-4 f: wftbcfnmhkfdpjbns", "6-7 v: vvvvvlv", "16-17 z: zzzzhfzzzzzzkzzzwzzz", "1-2 q: qqqfq", "10-11 p: zpjzcppvcppppppppj", "10-15 c: vlccbcgcclcczfcfcc", "11-17 t: tsntktwzhsfttfwtx", "1-7 h: nhhhhhb", "6-13 b: bbbphnbbwbbbb", "8-9 x: xgxxxlxfxx", "14-16 m: mmmmmmmmmmmmmmmm", "3-4 x: xxbxx", "6-9 c: xkccsfccrccv", "10-18 h: jphhbshwghrxpnhnlhxh", "6-10 f: nlxbgvftfh", "3-4 p: ppwf", "1-6 s: kjwjwshcnqwxgwslvl", "2-3 m: mmlk", "2-3 g: gmgg", "3-6 r: rrrvrmr", "1-6 s: szgpksczqd", "12-14 t: ttttttpjvtqwtltt", "1-2 r: hrrrrvrrzj", "1-13 m: xmmmmmsmmmcsnmmmmfmm", "10-11 f: fffffffffsf", "13-15 d: ddddddddddddhdq", "7-14 k: jkkkkkkkrkmkkkk", "6-9 g: ggggggggg", "14-16 l: lllllllvlllllwtx", "1-3 g: ggggt", "3-4 m: mmkd", "5-10 g: jgsgvggwggj", "17-18 p: ppppppppppppppphpp", "1-2 q: qqjwhq", "2-6 q: qqgqqzk", "11-16 t: ttwttttttctttthgt", "1-5 m: zmmmsm", "12-16 r: rrrrrrrrrqrgrrrj", "4-5 v: xcvvghvrczpcgn", "1-3 x: xbfmxxfxxf", "3-5 j: hjbjm", "5-14 l: lllltlllllqllll", "3-4 x: xsxnxgtx", "6-18 g: gggggggggggggggggd", "8-12 t: tgttttqtcttttt", "4-6 p: pppppd", "6-7 x: xxxxxxx", "3-4 c: fdcclrccccvg", "11-12 v: vnvvvvzdvcrk", "1-9 z: zztzqzzzzcz", "1-12 v: vmvvvvvvvvvmvvvv", "9-16 v: vvvvvvvvvvvvvvvf", "2-7 h: xhtsfmvthhhrhdhhbbc", "5-6 c: qkccccd", "8-12 z: zzzzzzzjzzhbzz", "2-4 n: shlnnkxn", "19-20 v: vvvvvvvvvvvvvvvvvvcv", "7-8 h: hhkhhhkhh", "5-19 p: sxslgwvkszswqxtqpvf", "5-8 m: mmmmmrmbm", "2-5 j: jrnjjzjfhjdkjqjtkwk", "7-13 f: ffffffsfffffwfff", "6-9 w: wmwwdwwwsz", "12-15 f: nsffpfsdsjsfsffk", "13-16 k: kkkkkkkkkkkkkkhw", "6-17 s: ssssslssssssssssss", "3-5 c: srdscnncclqqcncsw", "9-11 p: pkppppppppp", "5-10 q: qqqqqqqqqpqq", "12-14 n: nnnnnnnnnnnnnn", "6-11 h: hhhhhqhhhhhvhhhh", "2-12 f: fgfrpzcstfffffxff", "2-12 n: nnxmnmnnnnknrpmnv", "6-7 m: jmmmmcnpkm", "4-6 v: mvkcwvmvvjvrvlv", "18-20 h: hhrmbrhhhhlhhvhmhhhb", "9-13 g: ggggggzgggsgfgxg", "9-15 m: pmmxmmmmmmmmmmm", "1-7 l: zlmsmlxpvvlzv", "2-15 g: sslggkdglqgxpgkx", "17-18 c: ccccccccccccccccmc", "10-11 w: wwwwwpcwwwpwwd", "3-5 w: wwwwk", "8-9 f: vfbvffsfcf", "4-6 r: rrrrrr", "2-4 n: nrnknn", "1-4 l: lxllllll", "10-11 f: qdfwvfffdfvwffgfkfgf", "3-4 b: xgxbdqxbfvzrl", "2-8 b: pbbkbbgbxr", "1-2 d: ddxdnv", "4-8 d: dndfcnhd" ]; <file_sep>use parse_display::{Display, FromStr}; mod input; use input::input; #[derive(Display, FromStr, PartialEq, Debug)] #[display("{lowest}-{highest} {character}: {password}")] struct PasswordValidator { lowest: usize, highest: usize, character: char, password: String } impl PasswordValidator { fn is_valid(&self) -> bool { let count = self.password .chars() .filter(|c| *c == self.character) .collect::<Vec<char>>() .len(); count >= self.lowest && count <= self.highest } fn is_valid_two(&self) -> bool { let first_char = self.password.chars().nth(self.lowest - 1).unwrap(); let second_char = self.password.chars().nth(self.highest - 1).unwrap(); (first_char == self.character) ^ (second_char == self.character) } } fn main() { let result = input .iter() .filter(|i| i.parse::<PasswordValidator>().expect("Failed to parse line.").is_valid()) .count(); println!("Result: {}", result); let result = input .iter() .filter(|i| i.parse::<PasswordValidator>().expect("Failed to parse line.").is_valid_two()) .count(); println!("Second result: {}", result); } <file_sep>use std::{fs::File, collections::HashSet}; use std::io::prelude::*; const REQUIRED_KEYS: [&str; 7] = [ "byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid" ]; fn is_passport_valid(passport_string: &str) -> bool { passport_string .trim() .split_ascii_whitespace() .map(|entry| entry.split(":").next().unwrap()) .collect::<HashSet<&str>>() .into_iter() .filter(|key| REQUIRED_KEYS.contains(key)) .count() == 7 } fn main() { let mut file = File::open("src/input.txt").unwrap(); let mut passports_string = String::new(); file.read_to_string(&mut passports_string).unwrap(); let valid_passport_count = passports_string.split("\n\n") .filter(|passport_string| is_passport_valid(&passport_string)) .count(); println!("There are {} valid passports", valid_passport_count); }
303b228c53cf61a2b94cc29fee40cc9428423e9b
[ "Rust" ]
5
Rust
curlywurlycraig/advent-of-code-2020
61aa7ea59aa6f226ffd24dfea7a9ea830a94973d
05194f9230b62b18ce826934788d1f8a91550599
refs/heads/master
<file_sep>INGREDIENTS = [ ["agave", [0, 1, 0, 0, 0]], ["angostura bitters", [0, 0, 0, 1, 0]], ["peychauds bitters", [0, 0, 0, 1, 0]], ["chocolate bitters", [0, 0, 0, 1, 0]], ["orange bitters", [0, 0, 0, 1, 0]], ["bourbon", [1, 0, 0, 0, 0]], ["galliano", [0.5, 0.5, 0, 0, 0]], ["campari", [0.5, 0.5, 0, 1, 0]], ["triple sec", [0.5, 0.5, 0, 0, 0]], ["frangelico", [0.5, 0.5, 0, 0, 0]], ["gin", [1, 0, 0, 0, 0]], ["grenadine", [0, 1, 0, 0, 0]], ["kahlua", [0.5, 0.5, 0, 0, 0]], ["orange", [0, 0.8, 0.25, 0, 0]], ["lime", [0, 0.3, 0.7, 0, 0]], ["lemon", [0, 0, 1, 0, 0]], ["scotch", [1, 0, 0, 0, 0]], ["pimms", [0.5, 0.5, 0, 0, 0]], ["rum", [1, 0, 0, 0, 0]], ["rye", [1, 0, 0, 0, 0]], ["simple", [0, 1, 0, 0, 0]], ["stoli", [1, 0, 0, 0, 0]], ["tequila", [1, 0, 0, 0, 0]], ["triple sec", [0.5, 0.5, 0, 0, 0]], ["vodka", [1, 0, 0, 0, 0]], ["dry vermouth", [0, 0, 0, 1, 0]], ["sweet vermouth", [0, 0, 0, 1, 0]], ["soda", [0, 0, 0, 1, 1]], ["tonic", [0, 0.2, 0, 1, 1]], ["cola", [0, 0.5, 0.3, 0, 1]], ]; /* * Shuffles the array. */ function shuffle(arr) { for (var i = 0; i < arr.length - 1; i++) { var r = Math.floor(Math.random() * (arr.length - i)); var t = arr[i]; arr[i] = arr[r]; arr[r] = t; } } function is_all_zeros(vec) { for (var i = 0; i < vec.length; i++) { if (vec[i] != 0) { return false; } } return true; } /* * CreateRandomRecipe returns an array of ingredients totaling to oz and * weights. */ function CreateRandomRecipe(weights) { if (weights.length != 5) { console.log("Bad weights provided: ", weights); }; if (is_all_zeros(weights)) return []; /* Finished */ var candidates = INGREDIENTS.filter(function(ingredient) { for (var j = 0; j < weights.length; j++) { if (weights[j] == 0 && ingredient[1][j] > 0) return false; } return true; }) if (candidates.length == 0) return undefined; /* Won't work */ shuffle(candidates); for (var i = 0; i < candidates.length; i++) { var name = candidates[i][0]; var ingredient_weights = candidates[i][1]; /* Figure out the maximum amount we can add without going over any weight */ var amount = 1000; for (var j = 0; j < weights.length; j++) { if (ingredient_weights[j] == 0) continue; var amount_j = weights[j] / ingredient_weights[j]; if (amount_j < amount) amount = amount_j; } /* Calculate the new weights = weights - amount * ingredient_weights */ var new_weights = new Array(weights.length); for (var j = 0; j < weights.length; j++) { new_weights[j] = weights[j] - amount * ingredient_weights[j]; } /* Recursively find ingredients to fill the remaining weights */ var remaining_ingredients = CreateRandomRecipe(new_weights); if (remaining_ingredients == undefined) { continue; // This ingredient won't work. } // We found a recipe! var ingredient = {'name': name}; if (name.indexOf('itters') != -1) { ingredient.drops = amount; } else { ingredient.parts = amount; } console.log("Found ", ingredient, remaining_ingredients, " for ", weights); return [ingredient].concat(remaining_ingredients); } return undefined; /* We failed to find ingredients to satisfy weights */ } <file_sep>angular.module('nebree8.drink-detail', []) .config(['$routeProvider', function($routeProvider) { $routeProvider. when('/drinks/random', { templateUrl: 'drink-detail/drink-detail.html', controller: 'RandomDrinkCtrl', }). when('/drinks/:drinkName', { templateUrl: 'drink-detail/drink-detail.html', controller: 'NamedDrinkCtrl', }); } ]) .controller('DrinkDetailCtrl', ['$scope', '$http', '$mdDialog', '$routeParams', '$location', function($scope, $http, $mdDialog, $routeParams, $location) { var originalDrink = {}; $scope.selected_drink = {}; $scope.parts_max = 10; $scope.setRecipe = function(recipe) { originalDrink = recipe; $scope.reset(); var parts_max = 4; for (var j = 0; j < originalDrink.ingredients.length; j++) { var parts = originalDrink.ingredients[j].parts; if (parts && parts > parts_max) { parts_max = parts; } } $scope.parts_max = parts_max * 1.5; } function sendOrder(user_name, order) { var order = angular.copy(order); order.user_name = user_name; $scope.drink_id = 'unknown'; $http({ 'method': 'POST', 'url': '/api/order', 'params': { 'recipe': $scope.selected_drink }, 'responseType': 'json' }).then(function(response) { console.log("response", response) $scope.drink_id = response.data.id; }) } $scope.confirmRecipe = function(event) { var EnterNameController = ['$scope', '$mdDialog', function($scope, $mdDialog) { $scope.closeDialog = function() { console.log("closeDialog called", $scope.user_name); $mdDialog.hide(); }; $scope.cancelDialog = function() { $mdDialog.cancel(); } }]; $mdDialog.show({ controller: EnterNameController, targetEvent: event, scope: $scope, preserveScope: true, templateUrl: 'drink-detail/enter-name-dialog.html', clickOutsideToClose: true, }) .then(function(answer) { if (!answer) { console.log("got falsy answer", answer); return; } sendOrder($scope.user_name, $scope.selected_drink); console.log("Making drink ", $scope.selected_drink); $scope.cancel(); }, function() { console.log("dialog cancelled"); }); } $scope.cancel = function() { $location.path("/drinks"); } $scope.reset = function() { $scope.selected_drink = angular.copy(originalDrink); } $scope.is_modified = function() { return !angular.equals($scope.selected_drink, originalDrink); } } ]) .controller('NamedDrinkCtrl', ['$scope', '$http', '$controller', '$routeParams', function($scope, $http, $controller, $routeParams) { $controller('DrinkDetailCtrl', {$scope: $scope}); // Look up the drink by name. var drinkName = $routeParams.drinkName; $http.get('/all_drinks', { cache: true }).success(function(data) { for (var i = 0; i < data.length; i++) { if (slugifyDrink(data[i].drink_name) == drinkName) { $scope.setRecipe(data[i]); } } console.log("Didn't find drink, redirecting", drinkName, data); $location.path('/drinks').replace(); }); } ]) .controller('RandomDrinkCtrl', ['$scope', '$controller', '$mdToast', function($scope, $controller, $mdToast) { $controller('DrinkDetailCtrl', {$scope: $scope}); var name, weights; switch (Math.floor(Math.random() * 4)) { case 0: name = 'Random Sour'; weights = [2, 1, 1, 0, 0]; break; case 1: name = 'Random Spirituous'; weights = [4, 1, 0, 1, 0]; break; case 2: name = 'Random Bubbly Spirituous'; weights = [4, 1, 0, 1, 1]; break; case 3: name = 'Random Bubbly Sour'; weights = [2, 1, 1, 0, 1]; break; } var ingredients; for (var i = 0; ingredients == undefined && i < 5; i++) { ingredients = CreateRandomRecipe(weights); } if (!ingredients) { $mdToast.simple().hideDelay(5000). content("Oops, that didn't work. Try again"); $location.path('/drinks'); } $scope.setRecipe({'drink_name': name, 'ingredients': ingredients}); } ]); <file_sep>package nebree8 import ( "encoding/json" "fmt" "net/http" "strconv" "time" "appengine" "appengine/datastore" //"appengine/user" ) const ( secret = "SECRET" orderEntityType = "Order" ) type Ingredient struct { Parts int `json:"parts,omitempty"` Drops int `json:"drops,omitempty"` Name string `json:"name"` } type Order struct { DrinkName string `json:"drink_name"` UserName string `json:"user_name"` Ingredients []Ingredient `json:"ingredients"` OrderTime time.Time `json:"order_time"` ProgressPercent int `json:"progress_percent"` DoneTime time.Time `json:"done_time"` Approved bool `json:"approved"` TotalOz float32 `json:"total_oz"` } type KeyedOrder struct { Order key *datastore.Key } func (o *Order) Key(c appengine.Context) *datastore.Key { return datastore.NewIncompleteKey(c, orderEntityType, nil) } func (k *KeyedOrder) Put(c appengine.Context) error { _, err := datastore.Put(c, k.key, &k.Order) return err } func findOrder(c appengine.Context, encoded_key string) (*KeyedOrder, error) { key, err := datastore.DecodeKey(encoded_key) if err != nil { c.Infof("Bad key %v", encoded_key) return nil, err } order := &KeyedOrder{} order.key = key if err = datastore.Get(c, key, &order.Order); err != nil { c.Infof("Failed to find key %v", encoded_key) return nil, err } return order, nil } func mutateAndReturnOrder(w http.ResponseWriter, r *http.Request, f func(*Order) error) { c := appengine.NewContext(r) order, err := findOrder(c, r.FormValue("key")) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } if err := f(&order.Order); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } if err := order.Put(c); err != nil { c.Infof("Failed to write back to datastore key=%v", order.key.Encode()) http.Error(w, err.Error(), http.StatusInternalServerError) return } json.NewEncoder(w).Encode(order) } func unpreparedDrinkQueryNewestFirst() *datastore.Query { return datastore.NewQuery(orderEntityType).Filter("DoneTime =", time.Time{}).Order("OrderTime") } func init() { // External. http.HandleFunc("/api/order", orderDrink) http.HandleFunc("/api/order_status", orderStatus) http.HandleFunc("/api/drink_queue", drinkQueue) // Internal. http.HandleFunc("/api/next_drink", nextDrink) http.HandleFunc("/api/finished_drink", finishedDrink) http.HandleFunc("/api/set_drink_progress", drinkProgress) http.HandleFunc("/api/approve_drink", approveDrink) http.HandleFunc("/api/archive_drink", archiveDrink) } func orderDrink(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) var order Order if err := json.Unmarshal([]byte(r.FormValue("recipe")), &order); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } order.OrderTime = time.Now() key, err := datastore.Put(c, order.Key(c), &order) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } fmt.Fprintf(w, "{\"id\": \"%v\"}", key.Encode()) } func orderStatus(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) order, err := findOrder(c, r.FormValue("key")) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } status := "unknown" if !order.DoneTime.IsZero() { status = "Done" } else if order.ProgressPercent > 0 { status = fmt.Sprintf("%v%% done", order.ProgressPercent) } else if !order.Approved { status = "Insert coins to continue" } fmt.Fprintf(w, "%v", status) } func nextDrink(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) q := unpreparedDrinkQueryNewestFirst().Filter("Approved=", true).Limit(10) var orders []Order if _, err := q.GetAll(c, &orders); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } enc := json.NewEncoder(w) enc.Encode(orders) } func drinkQueue(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) q := unpreparedDrinkQueryNewestFirst() var orders []Order type Item struct { Order Id string `json:"id"` } var items []Item keys, err := q.GetAll(c, &orders) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } for i, o := range orders { items = append(items, Item{Order: o, Id: keys[i].Encode()}) } enc := json.NewEncoder(w) enc.Encode(items) } func finishedDrink(w http.ResponseWriter, r *http.Request) { mutateAndReturnOrder(w, r, func(o *Order) error { o.DoneTime = time.Now() return nil }) } func approveDrink(w http.ResponseWriter, r *http.Request) { mutateAndReturnOrder(w, r, func(o *Order) error { o.Approved = true return nil }) } func archiveDrink(w http.ResponseWriter, r *http.Request) { mutateAndReturnOrder(w, r, func(o *Order) error { o.DoneTime = time.Date(2000, time.January, 1, 0, 0, 0, 0, time.UTC) return nil }) } func drinkProgress(w http.ResponseWriter, r *http.Request) { // Validate progress argument. c := appengine.NewContext(r) progress, err := strconv.ParseInt(r.FormValue("progress"), 10, 32) if err != nil { c.Infof("Bad value \"%v\" for progress: %v", r.FormValue("progress"), err) http.Error(w, err.Error(), http.StatusBadRequest) } mutateAndReturnOrder(w, r, func(o *Order) error { o.ProgressPercent = int(progress) return nil }) } <file_sep>angular.module('nebree8.drink-list', []) .config(['$routeProvider', function($routeProvider) { $routeProvider. when('/drinks', { templateUrl: 'drink-list/drink-list.html', controller: 'DrinkListCtrl', }); } ]) .controller('DrinkListCtrl', ['$scope', '$http', '$mdDialog', '$location', function($scope, $http, $mdDialog, $location) { $scope.searching = false; $scope.query = ''; $http.get('/all_drinks', { cache: true }).success(function(data) { $scope.db = data; }); $scope.drinkUrl = slugifyDrink; $scope.ingredientsCsv = function(drink) { var names = []; for (var i = 0; i < drink.ingredients.length; i++) { names.push(drink.ingredients[i].name); } return names.join(", "); } $scope.selectDrink = function(drink) { $location.path('/drinks/' + slugifyDrink(drink.drink_name)); } $scope.toggleSearch = function(state) { $scope.searching = state; } $scope.randomDrink = function(drink) { $location.path('/drinks/random'); } } ]);
516880567d0c0671f2373fbf3cb0504cfd61bc12
[ "JavaScript", "Go" ]
4
JavaScript
wgmfisch/nebree8.com
2a7879be3e797d5a0eef2d9941fe885045aec53d
e094ae1a15d55f24bd974d5bbe304766412280b3
refs/heads/master
<file_sep># react-static-components Unit 3 hm 1 <file_sep>const Visitors = (props) => { return ( <div> Website Visitors <br /> 821 </div> ); } export default Visitors;<file_sep>const Reviews = (props) => { return ( <div> Reviews <br /> 1,281 </div> ); } export default Reviews;<file_sep>const Sentiment = (props) => { return ( <div> Sentiment Analysis <br /> <ul id='sentiment-list'> <li>960</li> <li>122</li> <li>321</li> </ul> </div> ); } export default Sentiment;<file_sep> import NavBar from './components/NavBar'; import Rating from './components/Rating'; import Reviews from './components/Reviews'; import Sentiment from './components/Sentiment'; import Visitors from './components/Visitors'; import './styles.css'; const App = () => { return ( <div className="parent"> <h4 className="div1"><NavBar /></h4> <h4 className="div2"><Reviews /></h4> <h4 className="div3"> <Rating /></h4> <h4 className="div4"><Sentiment /> </h4> <h4 className="div5"><Visitors /></h4> </div> ) } export default App;
151f8c1cb68d750360dc5f0c7aad2c37385f4ef6
[ "Markdown", "JavaScript" ]
5
Markdown
zacharyboelter/react-static-components
221fa811151c7c07bb1ba380037785cb6e6cbac0
270d9b131fa70cab54dc399aa4f8e341c6626a24
refs/heads/master
<file_sep>#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Mon Mar 19 22:40:47 2018 @author: sathu """ #loading libraries import re import numpy as np import tensorflow as tf import collections from collections import Counter import pandas as pd #Loading the raw dataset df = pd.read_csv('mbti_1.csv') print(df.head(10)) print("*"*40) print(df.info()) #creating new column with words per tweet of each person df['words_per_comment'] = df['posts'].apply(lambda x: len(x.split())/50) print(df.head()) #creating 4 new columns dividing the people by introversion/extroversion, intuition/sensing, and so on. map1 = {"I": 0, "E": 1} map2 = {"N": 0, "S": 1} map3 = {"T": 0, "F": 1} map4 = {"J": 0, "P": 1} df['I-E'] = df['type'].astype(str).str[0] df['I-E'] = df['I-E'].map(map1) df['N-S'] = df['type'].astype(str).str[1] df['N-S'] = df['N-S'].map(map2) df['T-F'] = df['type'].astype(str).str[2] df['T-F'] = df['T-F'].map(map3) df['J-P'] = df['type'].astype(str).str[3] df['J-P'] = df['J-P'].map(map4) print(df.head(10)) #creating new columns showing the amount of questionmarks per comment, exclamations or other types, which might be useful later df['http_per_comment'] = df['posts'].apply(lambda x: x.count('http')) df['music_per_comment'] = df['posts'].apply(lambda x: x.count('music')) df['question_per_comment'] = df['posts'].apply(lambda x: x.count('?')) df['img_per_comment'] = df['posts'].apply(lambda x: x.count('jpg')) df['excl_per_comment'] = df['posts'].apply(lambda x: x.count('!')) df['ellipsis_per_comment'] = df['posts'].apply(lambda x: x.count('...')) print(df.head(10)) #Saving csv with the new columns created along with already existing data df.to_csv('mbti_normalized.csv') <file_sep>#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Wed Mar 21 17:17:26 2018 @author: sathu """ import numpy as np import pandas as pd import re df = pd.DataFrame() # Loading the dataset text = pd.read_csv("/Users/sathu/Desktop/Text Classification/mbti_normalized.csv", index_col='type') #print(text.shape) #print(text[0:5]) #print(text.iloc[2]) # Function to clean data ... will be useful later def post_cleaner(post): """cleans individual posts`. Args: post-string Returns: cleaned up post`. """ # Covert all uppercase characters to lower case print "executing" post = post.lower() # Remove ||| post = post.replace('|||', "") # Remove URLs, links etc post = re.sub( r'''(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))''', '', post, flags=re.MULTILINE) # This would have removed most of the links but probably not all # Remove puntuations puncs1 = ['@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '_', '+', '=', '{', '}', '[', ']', '|', '\\', '"', "'", ';', ':', '<', '>', '/'] for punc in puncs1: post = post.replace(punc, '') puncs2 = [',', '.', '?', '!', '\n'] for punc in puncs2: post = post.replace(punc, ' ') # Remove extra white spaces post = re.sub('\s+', ' ', post).strip() return post # Clean up posts # Covert pandas dataframe object to list. I prefer using lists for prepocessing. posts = text.posts.tolist() print "list made" posts = [post_cleaner(post) for post in posts] print "cleaning done" df = pd.DataFrame({'col': posts}) print df df.to_csv("finaloutput.csv", sep=',')
b67977698a12167577c52673d8b5542044e0ce77
[ "Python" ]
2
Python
sathu95/LSTM_SVM_mbtidataset
aa64d9b7c454a5055564ba69e5bd32916654c299
f64717b5599c99aece212c9731f5842a64997ff2
refs/heads/master
<file_sep>/* * Copyright 2002-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.bia.gmailjava; /** * <p> EmailService uses Gmail smtp to send mails to one or more recipients. <p> * <p> sendEmail() method is async and no of worker threads can be configured during instantiation</p> * <p> Use one of the four constructor's to instantiate EmailService </p> * <p> EmailService can also be instantiated using google-domain email e.g <EMAIL> <p> * @author <NAME> <EMAIL> */ import java.util.Properties; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import javax.mail.*; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import org.apache.commons.validator.GenericValidator; import org.apache.commons.validator.routines.EmailValidator; // uncomment log4j if you already have //import org.apache.log4j.Logger; public class EmailService { final static String EMAIL_CONTENT_TYPE = "text/html"; final static String SMTP_HOST_NAME = "smtp.gmail.com"; final static String SMTP_PORT = "465"; final static String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; final static String TRUE = "true"; final static String FALSE = "false"; final static int ONE = 1; private Session session; private InternetAddress[] bcc; //private static Logger logger = Logger.getLogger(EmailService.class); private ExecutorService executor; private String username; private String password; private String[] bccs; /** * <p> Use this constructor if you want to set bcc and executor </p> * @param username cannot be null, should be valid gmail or google-domain username * @param password cannot be null, * @param bccs cannot be null * @param executor cannot be null */ public EmailService(String username, String password, String[] bccs, ExecutorService executor) { this.username = username; this.password = <PASSWORD>; this.bccs = bccs; this.executor = executor; } /** * <p> Use this constructor if you want to set executor </p> * <p> Instantiate with username, password and executor </p> * @param username cannot be null * @param password cannot be null * @param executor cannot be null */ public EmailService(String username, String password, ExecutorService executor) { this.username = username; this.password = <PASSWORD>; this.executor = executor; } /** * <p> Minimalist constructor, sets executor to default </p> * @param username cannot be null * @param password cannot be null */ public EmailService(String username, String password) { this.username = username; this.password = <PASSWORD>; this.executor = Executors.newFixedThreadPool(ONE); } /** * <p> Use this constructor to just set bcc, sets executor to default </p> * @param username cannot be null * @param password cannot be null */ public EmailService(String username, String password, String[] bccs) { this.username = username; this.password = <PASSWORD>; this.bccs = bccs; } /** * Sends async email to one recipient Returns true if email send * successfully, otherwise returns false for all errors including invalid * input * * @param toAddress * @param subject * @param body * @return true email send, false invalid input */ public void sendEmail(String toAddress, String subject, String body) { String[] toAddresses = {toAddress}; validate(subject, toAddresses); // Aysnc send email Runnable emailServiceAsync = new EmailServiceAsync(toAddresses, subject, body); executor.execute(emailServiceAsync); } /** * Sends async email to multiple recipients Returns true if email send * successfully, otherwise returns false for all errors including invalid * input * * @param toAddresses * @param subject * @param body * @return */ public void sendEmail(String[] toAddresses, String subject, String body) { validate(subject, toAddresses); // Aysnc send email Runnable emailServiceAsync = new EmailServiceAsync(toAddresses, subject, body); executor.execute(emailServiceAsync); } /** * call this method from ServletContextListener.contextDestroyed() This will * release all work thread's when your app is undeployed */ public void shutdown() { // releasing executor executor.shutdown(); // logger.trace("EmailService executor released!"); System.out.println("EmailService exector released!"); } /** * session is created only once * * @return */ private Session createSession() { if (session != null) { return session; } Properties props = new Properties(); props.put("mail.smtp.host", SMTP_HOST_NAME); props.put("mail.smtp.auth", TRUE); props.put("mail.debug", FALSE); props.put("mail.smtp.port", SMTP_PORT); props.put("mail.smtp.socketFactory.port", SMTP_PORT); props.put("mail.smtp.socketFactory.class", SSL_FACTORY); props.put("mail.smtp.socketFactory.fallback", FALSE); session = Session.getDefaultInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); session.setDebug(false); return session; } /** * bcc -- incase you need to be copied on emails * * @return * @throws AddressException */ private InternetAddress[] getBCC() throws AddressException { if (bcc != null) { return bcc; } if (bccs != null && bccs.length > 0) { bcc = new InternetAddress[bccs.length]; int index = 0; for (String email : bccs) { bcc[index++] = new InternetAddress(email); } } else { bcc = new InternetAddress[0]; } return bcc; } /** * * @param recipients * @param subject * @param message * @param from * @throws MessagingException */ private void sendSSMessage(String recipients[], String subject, String message) { try { InternetAddress[] addressTo = new InternetAddress[recipients.length]; for (int i = 0; i < recipients.length; i++) { if (recipients[i] != null && recipients[i].length() > 0) { addressTo[i] = new InternetAddress(recipients[i]); } } send(addressTo, subject, message); } catch (Exception ex) { //logger.warn(ex.getMessage(), ex); throw new RuntimeException("Error sending email, please check to and from emails are correct!"); } } /** * * @param addressTo * @param subject * @param message * @throws AddressException * @throws MessagingException */ private void send(InternetAddress[] addressTo, String subject, String message) throws AddressException, MessagingException { Message msg = new MimeMessage(createSession()); InternetAddress addressFrom = new InternetAddress(username); msg.setFrom(addressFrom); msg.setRecipients(Message.RecipientType.TO, addressTo); // set bcc InternetAddress[] bcc_ = getBCC(); if (bcc_ != null && bcc_.length > 0) { msg.setRecipients(Message.RecipientType.BCC, bcc_); } // Setting the Subject and Content Type msg.setSubject(subject); //String message = comment; msg.setContent(message, EMAIL_CONTENT_TYPE); Transport.send(msg); } /** * validates subject and to email addresses * * @param subject * @param emails */ private void validate(String subject, String... emails) { StringBuilder stringBuilder = new StringBuilder(); boolean valid = true; if (!isValidSubject(subject)) { stringBuilder.append("Invalid subject, "); valid = false; } if (!isValidEmail(emails)) { stringBuilder.append("Invalid email address"); valid = false; } if (!valid) { throw new RuntimeException(stringBuilder.toString()); } } /** * validates email/emails * * @param emails * @return */ private boolean isValidEmail(String... emails) { if (emails == null) { return false; } for (String email : emails) { if (!EmailValidator.getInstance().isValid(email)) { return false; } } return true; } /** * checks for blank and null * * @param subject cannot be empty * @return */ private boolean isValidSubject(String subject) { return !GenericValidator.isBlankOrNull(subject); } /** * * @throws Throwable */ @Override protected void finalize() throws Throwable { try { shutdown(); } finally { super.finalize(); } } /** * * Send aysnc emails using command pattern * */ private class EmailServiceAsync implements Runnable { private String recipients[]; private String subject; private String message; EmailServiceAsync(String recipients[], String subject, String message) { this.recipients = recipients; this.subject = subject; this.message = message; } @Override public void run() { EmailService.this.sendSSMessage(recipients, subject, message); } } }
a9bc760abfae704d275acbeef530f1fc1888f569
[ "Java" ]
1
Java
luiz158/GMailJava
94b43633406837502f669f1ba38275f72a854541
a0205bd26b4bd8bb1072b4a9f0a40d822a1a66c8
refs/heads/master
<repo_name>kladouh/flask_app_2<file_sep>/requirements.txt beautifulsoup4==4.5.1 bs4==0.0.1 click==6.6 cookies==2.2.1 Flask==0.11.1 future==0.15.2 geopy==1.11.0 giphypop==0.2 googlefinance==0.7 httplib2==0.9.2 itsdangerous==0.24 Jinja2==2.8 MarkupSafe==0.23 oauth2==1.9.0.post1 oauthlib==2.0.0 python-dotenv==0.6.0 python-forecastio==1.3.4 python-twitter==3.1 requests==2.11.1 requests-oauthlib==0.7.0 responses==0.5.1 six==1.10.0 slacker==0.9.25 Werkzeug==0.11.11 yelp==1.0.2<file_sep>/final_project.py from flask import Flask, render_template, request import giphypop import os #Sets up the flask module app = Flask(__name__) #Registers url of main page @app.route('/') def index(): return render_template('index.html') #Registers url of about page @app.route("/about") def about(): return render_template('about.html') #Registers url of results page @app.route('/results') def results(): #Gets the variable 'gif_name' (an input variable on the main page) gif_name = request.values.get('gif_name') #Runs a giphy search for 'gif_name' g = giphypop.Giphy() results = g.search_list(gif_name) #Passes the variables 'results' and 'gif_name' to the html code return render_template('results.html', gif_name=gif_name, results=results) if __name__ == "__main__": #Necessary to deploy to port = int(os.environ.get("PORT", 5000)) app.run(host="0.0.0.0", port=port) <file_sep>/README.md https://cbs-ipp-g12.herokuapp.com/ Note to Appraiser: Just writing to point out this app will also display the appropriate error message for the situation when no gifs are found for the given search terms (e.g if gibberish is entered)
7aec6fbc2f54e598808a00be1ece46cafc698018
[ "Markdown", "Python", "Text" ]
3
Text
kladouh/flask_app_2
910a3491f19bff748b5d5caa0f17dd1b751fdb12
5f387a87e2e73665d67ecb8f11cf69ef8373c554
refs/heads/master
<file_sep>var assetTemplate = ` <form id="TableEdit"> <strong>Desktop</strong> <div> repeat: <input name="repeat" class="repeat" value="<%= repeat %>" placeholder="repeat"> </div> <div> in: <input name="in" class="in" value="<%= data_in %>" placefolder="in"> </div> <div> ng_click: <input name="ng_click" class="ng-click" value="<%= ng_click %>" placefolder="ng click"> </div> <div> ng_if: <input name="ng_if" class="ng-if" value="<%= ng_if %>" placefolder="ng if"> </div> <div> ng-class: <input name="ng_class" class="ng-class" value="<%= ng_class %>" placefolder="ng class"> </div> <div> Has search: <input type="checkbox" name="has_search" class="has-search"<% if (has_search == 'true') { %> checked="checked"<% } %>> </div> <div> search-class: <input name="search_class" class="search-class" value="<%= search_class %>" placefolder="search class"> </div> <div> Has pagination: <input type="checkbox" name="has_pagination" class="has-pagination" <% if (has_pagination == 'true') { %> checked="checked"<% } %>> </div> <div> pagination-class: <input name="pagination_class" class="pagination-class" value="<%= pagination_class %>" placefolder="pagination class"> </div> <div> pagination-per-page: <input name="pagination_per_page" type="number" class="pagination-per-page" value="<%= pagination_per_page %>" placefolder="10"> </div> <table width="100"> <tr> <td>Column #</strong></td> <td><strong>Rank</strong></td> <td><strong>Name</strong></td> <td><strong>Content</strong></td> <td><strong>Editor View</strong></td> <td><strong>Width</strong></td> <td><strong>Class</strong></td> <td><strong>Actuons</strong></td> </tr> <% _.each(columns, function(col, index) { %> <tr data-row="<%= index %>"> <td><%= index + 1 %></td> <td> <select name="rank[<%= index %>]"> <option <%= col.rank == '1' ? 'selected="selected"' : '' %>>1</option> <option <%= col.rank == '2' ? 'selected="selected"' : '' %>>2</option> <option <%= col.rank == '3' ? 'selected="selected"' : '' %>>3</option> <option <%= col.rank == '4' ? 'selected="selected"' : '' %>>4</option> </select> </td> <td> <textarea name="name[<%= index %>]"><%= col.name %></textarea> </td> <td> <textarea name="content[<%= index %>]"><%= col.content %></textarea> </td> <td> <textarea name="editor[<%= index %>]"><%= col.editor %></textarea> </td> <td> <input type="number" name="width[<%= index %>]" value="<%= col.width %>"> </td> <td> <input type="text" name="class[<%= index %>]" value="<%= col.class %>"> </td> <td> <button type="button" class="remove-col" data-index="<%= index %>">Remove</button> </td> </tr> <% }); %> </table> <button id="addColBtn" type="button" class="btn btn-primary">Add Column</button> <button id="addTableBtn" type="button" class="submitTable btn btn-primary">Submit</button> </form> `; module.exports = { template: _.template(assetTemplate), run(editor, sender, opts) { var that = this; that.opt = opts || {}; // var config = editor.getConfig(); that.modal = editor.Modal; that.modal.setTitle(that.opt.modalTitle || 'Table Editor'); var cols = atob(that.opt.target.get('attributes').datatable || 'W10=') var ng_click = atob(that.opt.target.get('attributes').ng_click || 'IA==') var ng_if = atob(that.opt.target.get('attributes').ng_if || 'IA==') var ng_class = atob(that.opt.target.get('attributes').ng_class || 'IA==') var has_search = atob(that.opt.target.get('attributes').has_search || 'IA==') var search_class = atob(that.opt.target.get('attributes').search_class || 'IA==') var has_pagination = atob(that.opt.target.get('attributes').has_pagination || 'IA==') var pagination_class = atob(that.opt.target.get('attributes').pagination_class || 'IA==') var pagination_per_page = atob(that.opt.target.get('attributes').pagination_per_page || 'IA==') that.columns = cols ? JSON.parse(cols) : [{}]; var content = this.template({ columns: that.columns, repeat: that.opt.target.get('attributes').repeat, data_in: that.opt.target.get('attributes').in, ng_click: ng_click, ng_if: ng_if, ng_class: ng_class, has_search: has_search, search_class: search_class, has_pagination: has_pagination, pagination_class: pagination_class, pagination_per_page: pagination_per_page, }); // $(that.modal.getContentEl()).html(content); that.modal.setContent($('<div>').html(content)); that.modal.open(); that.events(); }, events: function() { var that = this; $('#addColBtn').click(function(e) { that.mapColumn(); setTimeout(function() { that.columns.push({}); var content = that.template({ columns: that.columns, repeat: $('#TableEdit .repeat').val(), data_in: $('#TableEdit .in').val(), ng_click: $('#TableEdit .ng-click').val(), ng_if: $('#TableEdit .ng-if').val(), ng_class: $('#TableEdit .ng-class').val(), has_search: $('#TableEdit .has-search')[0].checked, search_class: $('#TableEdit .search-class').val(), has_pagination: $('#TableEdit .has-pagination')[0].checked, pagination_class: $('#TableEdit .pagination-class').val(), pagination_per_page: $('#TableEdit .pagination-per-page').val(), }); // $(that.modal.getContentEl()).html(content); that.modal.setContent($('<div>').html(content)); that.events(); }, 0); }); $('.remove-col').click(function(e) { var j = $(this); that.mapColumn(); setTimeout(function() { that.columns.splice(parseInt(j.data('index')), 1); var content = that.template({ columns: that.columns, repeat: $('#TableEdit .repeat').val(), data_in: $('#TableEdit .in').val(), ng_click: $('#TableEdit .ng-click').val(), ng_if: $('#TableEdit .ng-if').val(), ng_class: $('#TableEdit .ng-class').val(), has_search: $('#TableEdit .has-search')[0].checked, search_class: $('#TableEdit .search-class').val(), has_pagination: $('#TableEdit .has-pagination')[0].checked, pagination_class: $('#TableEdit .pagination-class').val(), pagination_per_page: $('#TableEdit .pagination-per-page').val(), }); that.modal.setContent($('<div>').html(content)); // $(that.modal.getContentEl()).html(content); that.events(); }, 1); }); // alert(that.opt.target.get('datatable')); $('#addTableBtn').click(function(e) { that.mapColumn(); setTimeout(function() { that.opt.target.get('attributes').datatable = btoa(JSON.stringify(that.columns)); that.opt.target.get('attributes').repeat = $('#TableEdit .repeat').val(); that.opt.target.get('attributes').in = $('#TableEdit .in').val(); that.opt.target.get('attributes').ng_click = btoa($('#TableEdit .ng-click').val()); that.opt.target.get('attributes').ng_if = btoa($('#TableEdit .ng-if').val()); that.opt.target.get('attributes').ng_class = btoa($('#TableEdit .ng-class').val()); that.opt.target.get('attributes').has_search = btoa($('#TableEdit .has-search')[0].checked); that.opt.target.get('attributes').search_class = btoa($('#TableEdit .search-class').val()); that.opt.target.get('attributes').has_pagination = btoa($('#TableEdit .has-pagination')[0].checked); that.opt.target.get('attributes').pagination_class = btoa($('#TableEdit .pagination-class').val()); that.opt.target.get('attributes').pagination_per_page = btoa($('#TableEdit .pagination-per-page').val()); e.preventDefault(); that.modal.close(); }, 1); }); }, mapColumn: function() { var that = this; var form = $.extend({}, $('#TableEdit').serializeArray()); var fields = {}; for (var n in form) { fields[form[n].name] = form[n].value; } for (var n = 0; n < that.columns.length; n++) { var col = that.columns[n]; col.rank = fields['rank[' + n + ']']; col.width = fields['width[' + n + ']']; col.class = fields['class[' + n + ']']; col.content = fields['content[' + n + ']']; col.editor = fields['editor[' + n + ']']; col.name = fields['name[' + n + ']']; } }, }; <file_sep>var Component = require('./Component'); module.exports = Component.extend( { defaults: _.extend({}, Component.prototype.defaults, { type: 'layout', tagName: 'div', }), initialize(o, opt) { Component.prototype.initialize.apply(this, arguments); }, }, { isComponent(el) { var result = ''; if($(el).attr('data-layout') ){ result = {type: 'layout'}; } return result; }, } ); <file_sep>var parse_str = require('locutus/php/strings/parse_str'); require('utils/ColorPicker'); module.exports = { template: ` <% _(styles).each(function(style, property) { %> <div> <label><strong><%= property %></strong></label> <input class='colorpicker' data-property='<%= property %>' data-color="<%= style %>" name="<%= property %>"/> </div> <% }) %> <div> <label><strong>Add Color</strong></label> <input type="text" class="new-color" name="new_color"/> <button class="new-color-submit">Add Color</button> </div> `, run(editor, sender) { var that = this; this.render(editor); // alert(editor.trigger); }, render(editor) { var that = this; var template = _.template(that.template); for (var i = 0; i < editor.CssComposer.getAll().models.length; i++) { if (editor.CssComposer.getAll().models[i].attributes.selectorsAdd === ':root') { var root_style = editor.CssComposer.getAll().models[i]; } } this.modal = editor.Modal || null; this.modal.setTitle('Color Manager'); this.modal.setContent(template({ styles: root_style.attributes.style, })); function setValue(that, color) { var property = $(that).data('property'); root_style.attributes.style[property] = color; root_style.setStyle(root_style.attributes.style, {}); var iframe = window.$('.gjs-frame')[0]; var innerDoc = iframe.contentDocument || iframe.contentWindow.document; // innerDoc.documentElement.style.setProperty('--hello', color); innerDoc.documentElement.style.setProperty(property, color); } $(".colorpicker").each(function() { var that = this; $(this).spectrum({ color: $(this).data('color'), preferredFormat: "hex", showInput: true, showPalette: true, move: function(color) { setValue(that, color); }, change: function(color) { setValue(that, color); }, show: function(color) { setValue(that, color); }, hide: function(color) { setValue(that, color); }, }); }); $('.new-color-submit').click(function() { var name = $('.new-color').val(); if (name) { root_style.attributes.style['--' + name] = undefined; root_style.setStyle(root_style.attributes.style, {}); that.render(editor); } }) this.modal.open(); }, }; <file_sep>/** * * * [add](#add) * * [get](#get) * * [has](#has) * * You can init the editor with all necessary commands via configuration * * ```js * var editor = grapesjs.init({ * ... * commands: {...} // Check below for the properties * ... * }); * ``` * * Before using methods you should get first the module from the editor instance, in this way: * * ```js * var commands = editor.Commands; * ``` * * @module Commands * @param {Object} config Configurations * @param {Array<Object>} [config.defaults=[]] Array of possible commands * @example * ... * commands: { * defaults: [{ * id: 'helloWorld', * run: function(editor, sender){ * alert('Hello world!'); * }, * stop: function(editor, sender){ * alert('Stop!'); * }, * }], * }, * ... */ import { isFunction } from 'underscore'; module.exports = () => { let em; var c = {}, commands = {}, defaultCommands = {}, defaults = require('./config/config'), AbsCommands = require('./view/CommandAbstract'); // Need it here as it would be used below var add = function(id, obj) { if (isFunction(obj)) { obj = { run: obj }; } delete obj.initialize; commands[id] = AbsCommands.extend(obj); return this; }; return { /** * Name of the module * @type {String} * @private */ name: 'Commands', /** * Initialize module. Automatically called with a new instance of the editor * @param {Object} config Configurations * @private */ init(config) { c = config || {}; for (var name in defaults) { if (!(name in c)) c[name] = defaults[name]; } em = c.em; var ppfx = c.pStylePrefix; if (ppfx) c.stylePrefix = ppfx + c.stylePrefix; // Load commands passed via configuration for (var k in c.defaults) { var obj = c.defaults[k]; if (obj.id) this.add(obj.id, obj); } const ViewCode = require('./view/ExportTemplate'); defaultCommands['select-comp'] = require('./view/SelectComponent'); defaultCommands['create-comp'] = require('./view/CreateComponent'); defaultCommands['delete-comp'] = require('./view/DeleteComponent'); defaultCommands['image-comp'] = require('./view/ImageComponent'); defaultCommands['move-comp'] = require('./view/MoveComponent'); defaultCommands['text-comp'] = require('./view/TextComponent'); defaultCommands['insert-custom'] = require('./view/InsertCustom'); defaultCommands['export-template'] = ViewCode; defaultCommands['sw-visibility'] = require('./view/SwitchVisibility'); defaultCommands['open-layers'] = require('./view/OpenLayers'); defaultCommands['open-sm'] = require('./view/OpenStyleManager'); defaultCommands['open-tm'] = require('./view/OpenTraitManager'); defaultCommands['open-blocks'] = require('./view/OpenBlocks'); defaultCommands['open-assets'] = require('./view/OpenAssets'); defaultCommands['show-offset'] = require('./view/ShowOffset'); defaultCommands['select-parent'] = require('./view/SelectParent'); defaultCommands.fullscreen = require('./view/Fullscreen'); defaultCommands.preview = require('./view/Preview'); defaultCommands.resize = require('./view/Resize'); defaultCommands.drag = require('./view/Drag'); //custom defaultCommands['build-component'] = require('./view/BuildComponent'); defaultCommands['open-table-editor'] = require('./view/OpenTableEditor'); defaultCommands['open-region-editor'] = require('./view/OpenRegionEditor'); defaultCommands['tlb-delete'] = { run(ed) { var sel = ed.getSelected(); if (!sel || !sel.get('removable')) { console.warn('The element is not removable'); return; } ed.select(null); sel.destroy(); } }; defaultCommands['maincolor'] = require('./view/mainColorPicker'); defaultCommands['save'] = { run(editor) { var assetTemplate = ` <div style="overflow: hidden;"> <div style="float: left; width: 50%;"> <h4>New. Layout</h4> <form id="NewLayoutForm" enctype="multipart/form-data"> <div class="form_item"> <label>Block <i style="color: red;">*</i></label> <select name="block_id" required="required"> <% _.each(blocks, function(block) { %> <option value="<%= block.id %>"><%= block.name %></option> <% }); %> </select> </div> <div class="form_item"> <label>Name <i style="color: red;">*</i></label> <input type="text" name="name" required="required"> </div> <div class="form_item"> <label>Name <i style="color: red;">*</i></label> <input type="file" name="image" required="required"> </div> <div class="form_item"> <input type="submit" name="Save Layout"> </div> </form> </div> <div style="float: left; width: 50%;"> <h4>New Block</h4> <form id="NewBlockForm"> <div class="form_item"> <label>Category <i style="color: red;">*</i></label> <select name="category_id" required="required"> <% _.each(categories, function(cat) { %> <option value="<%= cat.id %>"><%= cat.name %></option> <% }); %> </select> </div> <div class="form_item"> <label>Name <i style="color: red;">*</i></label> <input type="text" name="name" required="required"> </div> <div class="form_item"> <label>Icon <i style="color: red;">*</i></label> <select name="icon" required="required"> <option value="fa-glass">&#xf000 icon-glass</option> <option value="fa-music">&#xf001 icon-music</option> <option value="fa-search">&#xf002 icon-search</option> <option value="fa-envelope-alt">&#xf003 icon-envelope-alt</option> <option value="fa-heart">&#xf004 icon-heart</option> <option value="fa-star">&#xf005 icon-star</option> <option value="fa-star-empty">&#xf006 icon-star-empty</option> <option value="fa-user">&#xf007 icon-user</option> <option value="fa-film">&#xf008 icon-film</option> <option value="fa-th-large">&#xf009 icon-th-large</option> <option value="fa-th">&#xf00a icon-th</option> <option value="fa-th-list">&#xf00b icon-th-list</option> <option value="fa-ok">&#xf00c icon-ok</option> <option value="fa-remove">&#xf00d icon-remove</option> <option value="fa-zoom-in">&#xf00e icon-zoom-in</option> <option value="fa-zoom-out">&#xf010 icon-zoom-out</option> <option value="fa-off">&#xf011 icon-off</option> <option value="fa-signal">&#xf012 icon-signal</option> <option value="fa-cog">&#xf013 icon-cog</option> <option value="fa-trash">&#xf014 icon-trash</option> <option value="fa-home">&#xf015 icon-home</option> <option value="fa-file-alt">&#xf016 icon-file-alt</option> <option value="fa-time">&#xf017 icon-time</option> <option value="fa-road">&#xf018 icon-road</option> <option value="fa-download-alt">&#xf019 icon-download-alt</option> <option value="fa-download">&#xf01a icon-download</option> <option value="fa-upload">&#xf01b icon-upload</option> <option value="fa-inbox">&#xf01c icon-inbox</option> <option value="fa-play-circle">&#xf01d icon-play-circle</option> <option value="fa-repeat">&#xf01e icon-repeat</option> <option value="fa-refresh">&#xf021 icon-refresh</option> <option value="fa-list-alt">&#xf022 icon-list-alt</option> <option value="fa-lock">&#xf023 icon-lock</option> <option value="fa-flag">&#xf024 icon-flag</option> <option value="fa-headphones">&#xf025 icon-headphones</option> <option value="fa-volume-off">&#xf026 icon-volume-off</option> <option value="fa-volume-down">&#xf027 icon-volume-down</option> <option value="fa-volume-up">&#xf028 icon-volume-up</option> <option value="fa-qrcode">&#xf029 icon-qrcode</option> <option value="fa-barcode">&#xf02a icon-barcode</option> <option value="fa-tag">&#xf02b icon-tag</option> <option value="fa-tags">&#xf02c icon-tags</option> <option value="fa-book">&#xf02d icon-book</option> <option value="fa-bookmark">&#xf02e icon-bookmark</option> <option value="fa-print">&#xf02f icon-print</option> <option value="fa-camera">&#xf030 icon-camera</option> <option value="fa-font">&#xf031 icon-font</option> <option value="fa-bold">&#xf032 icon-bold</option> <option value="fa-italic">&#xf033 icon-italic</option> <option value="fa-text-height">&#xf034 icon-text-height</option> <option value="fa-text-width">&#xf035 icon-text-width</option> <option value="fa-align-left">&#xf036 icon-align-left</option> <option value="fa-align-center">&#xf037 icon-align-center</option> <option value="fa-align-right">&#xf038 icon-align-right</option> <option value="fa-align-justify">&#xf039 icon-align-justify</option> <option value="fa-list">&#xf03a icon-list</option> <option value="fa-indent-left">&#xf03b icon-indent-left</option> <option value="fa-indent-right">&#xf03c icon-indent-right</option> <option value="fa-facetime-video">&#xf03d icon-facetime-video</option> <option value="fa-picture">&#xf03e icon-picture</option> <option value="fa-pencil">&#xf040 icon-pencil</option> <option value="fa-map-marker">&#xf041 icon-map-marker</option> <option value="fa-adjust">&#xf042 icon-adjust</option> <option value="fa-tint">&#xf043 icon-tint</option> <option value="fa-edit">&#xf044 icon-edit</option> <option value="fa-share">&#xf045 icon-share</option> <option value="fa-check">&#xf046 icon-check</option> <option value="fa-move">&#xf047 icon-move</option> <option value="fa-step-backward">&#xf048 icon-step-backward</option> <option value="fa-fast-backward">&#xf049 icon-fast-backward</option> <option value="fa-backward">&#xf04a icon-backward</option> <option value="fa-play">&#xf04b icon-play</option> <option value="fa-pause">&#xf04c icon-pause</option> <option value="fa-stop">&#xf04d icon-stop</option> <option value="fa-forward">&#xf04e icon-forward</option> <option value="fa-fast-forward">&#xf050 icon-fast-forward</option> <option value="fa-step-forward">&#xf051 icon-step-forward</option> <option value="fa-eject">&#xf052 icon-eject</option> <option value="fa-chevron-left">&#xf053 icon-chevron-left</option> <option value="fa-chevron-right">&#xf054 icon-chevron-right</option> <option value="fa-plus-sign">&#xf055 icon-plus-sign</option> <option value="fa-minus-sign">&#xf056 icon-minus-sign</option> <option value="fa-remove-sign">&#xf057 icon-remove-sign</option> <option value="fa-ok-sign">&#xf058 icon-ok-sign</option> <option value="fa-question-sign">&#xf059 icon-question-sign</option> <option value="fa-info-sign">&#xf05a icon-info-sign</option> <option value="fa-screenshot">&#xf05b icon-screenshot</option> <option value="fa-remove-circle">&#xf05c icon-remove-circle</option> <option value="fa-ok-circle">&#xf05d icon-ok-circle</option> <option value="fa-ban-circle">&#xf05e icon-ban-circle</option> <option value="fa-arrow-left">&#xf060 icon-arrow-left</option> <option value="fa-arrow-right">&#xf061 icon-arrow-right</option> <option value="fa-arrow-up">&#xf062 icon-arrow-up</option> <option value="fa-arrow-down">&#xf063 icon-arrow-down</option> <option value="fa-share-alt">&#xf064 icon-share-alt</option> <option value="fa-resize-full">&#xf065 icon-resize-full</option> <option value="fa-resize-small">&#xf066 icon-resize-small</option> <option value="fa-plus">&#xf067 icon-plus</option> <option value="fa-minus">&#xf068 icon-minus</option> <option value="fa-asterisk">&#xf069 icon-asterisk</option> <option value="fa-exclamation-sign">&#xf06a icon-exclamation-sign</option> <option value="fa-gift">&#xf06b icon-gift</option> <option value="fa-leaf">&#xf06c icon-leaf</option> <option value="fa-fire">&#xf06d icon-fire</option> <option value="fa-eye-open">&#xf06e icon-eye-open</option> <option value="fa-eye-close">&#xf070 icon-eye-close</option> <option value="fa-warning-sign">&#xf071 icon-warning-sign</option> <option value="fa-plane">&#xf072 icon-plane</option> <option value="fa-calendar">&#xf073 icon-calendar</option> <option value="fa-random">&#xf074 icon-random</option> <option value="fa-comment">&#xf075 icon-comment</option> <option value="fa-magnet">&#xf076 icon-magnet</option> <option value="fa-chevron-up">&#xf077 icon-chevron-up</option> <option value="fa-chevron-down">&#xf078 icon-chevron-down</option> <option value="fa-retweet">&#xf079 icon-retweet</option> <option value="fa-shopping-cart">&#xf07a icon-shopping-cart</option> <option value="fa-folder-close">&#xf07b icon-folder-close</option> <option value="fa-folder-open">&#xf07c icon-folder-open</option> <option value="fa-resize-vertical">&#xf07d icon-resize-vertical</option> <option value="fa-resize-horizontal">&#xf07e icon-resize-horizontal</option> <option value="fa-bar-chart">&#xf080 icon-bar-chart</option> <option value="fa-twitter-sign">&#xf081 icon-twitter-sign</option> <option value="fa-facebook-sign">&#xf082 icon-facebook-sign</option> <option value="fa-camera-retro">&#xf083 icon-camera-retro</option> <option value="fa-key">&#xf084 icon-key</option> <option value="fa-cogs">&#xf085 icon-cogs</option> <option value="fa-comments">&#xf086 icon-comments</option> <option value="fa-thumbs-up-alt">&#xf087 icon-thumbs-up-alt</option> <option value="fa-thumbs-down-alt">&#xf088 icon-thumbs-down-alt</option> <option value="fa-star-half">&#xf089 icon-star-half</option> <option value="fa-heart-empty">&#xf08a icon-heart-empty</option> <option value="fa-signout">&#xf08b icon-signout</option> <option value="fa-linkedin-sign">&#xf08c icon-linkedin-sign</option> <option value="fa-pushpin">&#xf08d icon-pushpin</option> <option value="fa-external-link">&#xf08e icon-external-link</option> <option value="fa-signin">&#xf090 icon-signin</option> <option value="fa-trophy">&#xf091 icon-trophy</option> <option value="fa-github-sign">&#xf092 icon-github-sign</option> <option value="fa-upload-alt">&#xf093 icon-upload-alt</option> <option value="fa-lemon">&#xf094 icon-lemon</option> <option value="fa-phone">&#xf095 icon-phone</option> <option value="fa-check-empty">&#xf096 icon-check-empty</option> <option value="fa-bookmark-empty">&#xf097 icon-bookmark-empty</option> <option value="fa-phone-sign">&#xf098 icon-phone-sign</option> <option value="fa-twitter">&#xf099 icon-twitter</option> <option value="fa-facebook">&#xf09a icon-facebook</option> <option value="fa-github">&#xf09b icon-github</option> <option value="fa-unlock">&#xf09c icon-unlock</option> <option value="fa-credit-card">&#xf09d icon-credit-card</option> <option value="fa-rss">&#xf09e icon-rss</option> <option value="fa-hdd">&#xf0a0 icon-hdd</option> <option value="fa-bullhorn">&#xf0a1 icon-bullhorn</option> <option value="fa-bell">&#xf0a2 icon-bell</option> <option value="fa-certificate">&#xf0a3 icon-certificate</option> <option value="fa-hand-right">&#xf0a4 icon-hand-right</option> <option value="fa-hand-left">&#xf0a5 icon-hand-left</option> <option value="fa-hand-up">&#xf0a6 icon-hand-up</option> <option value="fa-hand-down">&#xf0a7 icon-hand-down</option> <option value="fa-circle-arrow-left">&#xf0a8 icon-circle-arrow-left</option> <option value="fa-circle-arrow-right">&#xf0a9 icon-circle-arrow-right</option> <option value="fa-circle-arrow-up">&#xf0aa icon-circle-arrow-up</option> <option value="fa-circle-arrow-down">&#xf0ab icon-circle-arrow-down</option> <option value="fa-globe">&#xf0ac icon-globe</option> <option value="fa-wrench">&#xf0ad icon-wrench</option> <option value="fa-tasks">&#xf0ae icon-tasks</option> <option value="fa-filter">&#xf0b0 icon-filter</option> <option value="fa-briefcase">&#xf0b1 icon-briefcase</option> <option value="fa-fullscreen">&#xf0b2 icon-fullscreen</option> <option value="fa-group">&#xf0c0 icon-group</option> <option value="fa-link">&#xf0c1 icon-link</option> <option value="fa-cloud">&#xf0c2 icon-cloud</option> <option value="fa-beaker">&#xf0c3 icon-beaker</option> <option value="fa-cut">&#xf0c4 icon-cut</option> <option value="fa-copy">&#xf0c5 icon-copy</option> <option value="fa-paper-clip">&#xf0c6 icon-paper-clip</option> <option value="fa-save">&#xf0c7 icon-save</option> <option value="fa-sign-blank">&#xf0c8 icon-sign-blank</option> <option value="fa-reorder">&#xf0c9 icon-reorder</option> <option value="fa-list-ul">&#xf0ca icon-list-ul</option> <option value="fa-list-ol">&#xf0cb icon-list-ol</option> <option value="fa-strikethrough">&#xf0cc icon-strikethrough</option> <option value="fa-underline">&#xf0cd icon-underline</option> <option value="fa-table">&#xf0ce icon-table</option> <option value="fa-magic">&#xf0d0 icon-magic</option> <option value="fa-truck">&#xf0d1 icon-truck</option> <option value="fa-pinterest">&#xf0d2 icon-pinterest</option> <option value="fa-pinterest-sign">&#xf0d3 icon-pinterest-sign</option> <option value="fa-google-plus-sign">&#xf0d4 icon-google-plus-sign</option> <option value="fa-google-plus">&#xf0d5 icon-google-plus</option> <option value="fa-money">&#xf0d6 icon-money</option> <option value="fa-caret-down">&#xf0d7 icon-caret-down</option> <option value="fa-caret-up">&#xf0d8 icon-caret-up</option> <option value="fa-caret-left">&#xf0d9 icon-caret-left</option> <option value="fa-caret-right">&#xf0da icon-caret-right</option> <option value="fa-columns">&#xf0db icon-columns</option> <option value="fa-sort">&#xf0dc icon-sort</option> <option value="fa-sort-down">&#xf0dd icon-sort-down</option> <option value="fa-sort-up">&#xf0de icon-sort-up</option> <option value="fa-envelope">&#xf0e0 icon-envelope</option> <option value="fa-linkedin">&#xf0e1 icon-linkedin</option> <option value="fa-undo">&#xf0e2 icon-undo</option> <option value="fa-legal">&#xf0e3 icon-legal</option> <option value="fa-dashboard">&#xf0e4 icon-dashboard</option> <option value="fa-comment-alt">&#xf0e5 icon-comment-alt</option> <option value="fa-comments-alt">&#xf0e6 icon-comments-alt</option> <option value="fa-bolt">&#xf0e7 icon-bolt</option> <option value="fa-sitemap">&#xf0e8 icon-sitemap</option> <option value="fa-umbrella">&#xf0e9 icon-umbrella</option> <option value="fa-paste">&#xf0ea icon-paste</option> <option value="fa-lightbulb">&#xf0eb icon-lightbulb</option> <option value="fa-exchange">&#xf0ec icon-exchange</option> <option value="fa-cloud-download">&#xf0ed icon-cloud-download</option> <option value="fa-cloud-upload">&#xf0ee icon-cloud-upload</option> <option value="fa-user-md">&#xf0f0 icon-user-md</option> <option value="fa-stethoscope">&#xf0f1 icon-stethoscope</option> <option value="fa-suitcase">&#xf0f2 icon-suitcase</option> <option value="fa-bell-alt">&#xf0f3 icon-bell-alt</option> <option value="fa-coffee">&#xf0f4 icon-coffee</option> <option value="fa-food">&#xf0f5 icon-food</option> <option value="fa-file-text-alt">&#xf0f6 icon-file-text-alt</option> <option value="fa-building">&#xf0f7 icon-building</option> <option value="fa-hospital">&#xf0f8 icon-hospital</option> <option value="fa-ambulance">&#xf0f9 icon-ambulance</option> <option value="fa-medkit">&#xf0fa icon-medkit</option> <option value="fa-fighter-jet">&#xf0fb icon-fighter-jet</option> <option value="fa-beer">&#xf0fc icon-beer</option> <option value="fa-h-sign">&#xf0fd icon-h-sign</option> <option value="fa-plus-sign-alt">&#xf0fe icon-plus-sign-alt</option> <option value="fa-double-angle-left">&#xf100 icon-double-angle-left</option> <option value="fa-double-angle-right">&#xf101 icon-double-angle-right</option> <option value="fa-double-angle-up">&#xf102 icon-double-angle-up</option> <option value="fa-double-angle-down">&#xf103 icon-double-angle-down</option> <option value="fa-angle-left">&#xf104 icon-angle-left</option> <option value="fa-angle-right">&#xf105 icon-angle-right</option> <option value="fa-angle-up">&#xf106 icon-angle-up</option> <option value="fa-angle-down">&#xf107 icon-angle-down</option> <option value="fa-desktop">&#xf108 icon-desktop</option> <option value="fa-laptop">&#xf109 icon-laptop</option> <option value="fa-tablet">&#xf10a icon-tablet</option> <option value="fa-mobile-phone">&#xf10b icon-mobile-phone</option> <option value="fa-circle-blank">&#xf10c icon-circle-blank</option> <option value="fa-quote-left">&#xf10d icon-quote-left</option> <option value="fa-quote-right">&#xf10e icon-quote-right</option> <option value="fa-spinner">&#xf110 icon-spinner</option> <option value="fa-circle">&#xf111 icon-circle</option> <option value="fa-reply">&#xf112 icon-reply</option> <option value="fa-github-alt">&#xf113 icon-github-alt</option> <option value="fa-folder-close-alt">&#xf114 icon-folder-close-alt</option> <option value="fa-folder-open-alt">&#xf115 icon-folder-open-alt</option> <option value="fa-expand-alt">&#xf116 icon-expand-alt</option> <option value="fa-collapse-alt">&#xf117 icon-collapse-alt</option> <option value="fa-smile">&#xf118 icon-smile</option> <option value="fa-frown">&#xf119 icon-frown</option> <option value="fa-meh">&#xf11a icon-meh</option> <option value="fa-gamepad">&#xf11b icon-gamepad</option> <option value="fa-keyboard">&#xf11c icon-keyboard</option> <option value="fa-flag-alt">&#xf11d icon-flag-alt</option> <option value="fa-flag-checkered">&#xf11e icon-flag-checkered</option> <option value="fa-terminal">&#xf120 icon-terminal</option> <option value="fa-code">&#xf121 icon-code</option> <option value="fa-reply-all">&#xf122 icon-reply-all</option> <option value="fa-mail-reply-all">&#xf122 icon-mail-reply-all</option> <option value="fa-star-half-empty">&#xf123 icon-star-half-empty</option> <option value="fa-location-arrow">&#xf124 icon-location-arrow</option> <option value="fa-crop">&#xf125 icon-crop</option> <option value="fa-code-fork">&#xf126 icon-code-fork</option> <option value="fa-unlink">&#xf127 icon-unlink</option> <option value="fa-question">&#xf128 icon-question</option> <option value="fa-info">&#xf129 icon-info</option> <option value="fa-exclamation">&#xf12a icon-exclamation</option> <option value="fa-superscript">&#xf12b icon-superscript</option> <option value="fa-subscript">&#xf12c icon-subscript</option> <option value="fa-eraser">&#xf12d icon-eraser</option> <option value="fa-puzzle-piece">&#xf12e icon-puzzle-piece</option> <option value="fa-microphone">&#xf130 icon-microphone</option> <option value="fa-microphone-off">&#xf131 icon-microphone-off</option> <option value="fa-shield">&#xf132 icon-shield</option> <option value="fa-calendar-empty">&#xf133 icon-calendar-empty</option> <option value="fa-fire-extinguisher">&#xf134 icon-fire-extinguisher</option> <option value="fa-rocket">&#xf135 icon-rocket</option> <option value="fa-maxcdn">&#xf136 icon-maxcdn</option> <option value="fa-chevron-sign-left">&#xf137 icon-chevron-sign-left</option> <option value="fa-chevron-sign-right">&#xf138 icon-chevron-sign-right</option> <option value="fa-chevron-sign-up">&#xf139 icon-chevron-sign-up</option> <option value="fa-chevron-sign-down">&#xf13a icon-chevron-sign-down</option> <option value="fa-html5">&#xf13b icon-html5</option> <option value="fa-css3">&#xf13c icon-css3</option> <option value="fa-anchor">&#xf13d icon-anchor</option> <option value="fa-unlock-alt">&#xf13e icon-unlock-alt</option> <option value="fa-bullseye">&#xf140 icon-bullseye</option> <option value="fa-ellipsis-horizontal">&#xf141 icon-ellipsis-horizontal</option> <option value="fa-ellipsis-vertical">&#xf142 icon-ellipsis-vertical</option> <option value="fa-rss-sign">&#xf143 icon-rss-sign</option> <option value="fa-play-sign">&#xf144 icon-play-sign</option> <option value="fa-ticket">&#xf145 icon-ticket</option> <option value="fa-minus-sign-alt">&#xf146 icon-minus-sign-alt</option> <option value="fa-check-minus">&#xf147 icon-check-minus</option> <option value="fa-level-up">&#xf148 icon-level-up</option> <option value="fa-level-down">&#xf149 icon-level-down</option> <option value="fa-check-sign">&#xf14a icon-check-sign</option> <option value="fa-edit-sign">&#xf14b icon-edit-sign</option> <option value="fa-external-link-sign">&#xf14c icon-external-link-sign</option> <option value="fa-share-sign">&#xf14d icon-share-sign</option> <option value="fa-compass">&#xf14e icon-compass</option> <option value="fa-collapse">&#xf150 icon-collapse</option> <option value="fa-collapse-top">&#xf151 icon-collapse-top</option> <option value="fa-expand">&#xf152 icon-expand</option> <option value="fa-eur">&#xf153 icon-eur</option> <option value="fa-gbp">&#xf154 icon-gbp</option> <option value="fa-usd">&#xf155 icon-usd</option> <option value="fa-inr">&#xf156 icon-inr</option> <option value="fa-jpy">&#xf157 icon-jpy</option> <option value="fa-cny">&#xf158 icon-cny</option> <option value="fa-krw">&#xf159 icon-krw</option> <option value="fa-btc">&#xf15a icon-btc</option> <option value="fa-file">&#xf15b icon-file</option> <option value="fa-file-text">&#xf15c icon-file-text</option> <option value="fa-sort-by-alphabet">&#xf15d icon-sort-by-alphabet</option> <option value="fa-sort-by-alphabet-alt">&#xf15e icon-sort-by-alphabet-alt</option> <option value="fa-sort-by-attributes">&#xf160 icon-sort-by-attributes</option> <option value="fa-sort-by-attributes-alt">&#xf161 icon-sort-by-attributes-alt</option> <option value="fa-sort-by-order">&#xf162 icon-sort-by-order</option> <option value="fa-sort-by-order-alt">&#xf163 icon-sort-by-order-alt</option> <option value="fa-thumbs-up">&#xf164 icon-thumbs-up</option> <option value="fa-thumbs-down">&#xf165 icon-thumbs-down</option> <option value="fa-youtube-sign">&#xf166 icon-youtube-sign</option> <option value="fa-youtube">&#xf167 icon-youtube</option> <option value="fa-xing">&#xf168 icon-xing</option> <option value="fa-xing-sign">&#xf169 icon-xing-sign</option> <option value="fa-youtube-play">&#xf16a icon-youtube-play</option> <option value="fa-dropbox">&#xf16b icon-dropbox</option> <option value="fa-stackexchange">&#xf16c icon-stackexchange</option> <option value="fa-instagram">&#xf16d icon-instagram</option> <option value="fa-flickr">&#xf16e icon-flickr</option> <option value="fa-adn">&#xf170 icon-adn</option> <option value="fa-bitbucket">&#xf171 icon-bitbucket</option> <option value="fa-bitbucket-sign">&#xf172 icon-bitbucket-sign</option> <option value="fa-tumblr">&#xf173 icon-tumblr</option> <option value="fa-tumblr-sign">&#xf174 icon-tumblr-sign</option> <option value="fa-long-arrow-down">&#xf175 icon-long-arrow-down</option> <option value="fa-long-arrow-up">&#xf176 icon-long-arrow-up</option> <option value="fa-long-arrow-left">&#xf177 icon-long-arrow-left</option> <option value="fa-long-arrow-right">&#xf178 icon-long-arrow-right</option> <option value="fa-apple">&#xf179 icon-apple</option> <option value="fa-windows">&#xf17a icon-windows</option> <option value="fa-android">&#xf17b icon-android</option> <option value="fa-linux">&#xf17c icon-linux</option> <option value="fa-dribbble">&#xf17d icon-dribbble</option> <option value="fa-skype">&#xf17e icon-skype</option> <option value="fa-foursquare">&#xf180 icon-foursquare</option> <option value="fa-trello">&#xf181 icon-trello</option> <option value="fa-female">&#xf182 icon-female</option> <option value="fa-male">&#xf183 icon-male</option> <option value="fa-gittip">&#xf184 icon-gittip</option> <option value="fa-sun">&#xf185 icon-sun</option> <option value="fa-moon">&#xf186 icon-moon</option> <option value="fa-archive">&#xf187 icon-archive</option> <option value="fa-bug">&#xf188 icon-bug</option> <option value="fa-vk">&#xf189 icon-vk</option> <option value="fa-weibo">&#xf18a icon-weibo</option> <option value="fa-renren">&#xf18b icon-renren</option> </select> </div> <div class="form_item"> <input type="submit" name="Save Block"> </div> </form> </div> </div> `; var template = _.template(assetTemplate); // var config = editor.getConfig(); var modal = editor.Modal; modal.setTitle('Save Layout Or Block'); var content = template({ categories:categories, blocks:blocks, }); modal.setContent(content); modal.open(); var sel = editor.getSelected(); var html = sel.toHTML(); var allClasses = []; var allElements = sel.view.el.querySelectorAll('*'); for (var i = 0; i < allElements.length; i++) { var classes = allElements[i].className.toString().split(/\s+/); for (var j = 0; j < classes.length; j++) { var cls = classes[j]; if (cls && allClasses.indexOf(cls) === -1) allClasses.push(cls); } } function elem_css(a, o) { var iframe = window.$('.gjs-frame')[0]; var innerDoc = iframe.contentDocument || iframe.contentWindow.document; var a = $(innerDoc).find('.' + a)[0] var sheets = innerDoc.styleSheets, o = o || []; a.matches = a.matches || a.webkitMatchesSelector || a.mozMatchesSelector || a.msMatchesSelector || a.oMatchesSelector; for (var i in sheets) { if (!sheets[i].href) { var rules = sheets[i].rules || sheets[i].cssRules; if (rules) { for (var r in rules) { if (a.matches(rules[r].selectorText)) { if (rules[r].cssText.indexOf('*') > -1 || rules[r].cssText.indexOf('.gjs') > -1) { continue; } if (o.indexOf(rules[r].cssText) === -1) { if (rules[r].cssText[0] == '.' || rules[r].cssText[0] == '#') { o.push(rules[r].cssText); } } } } } } } return o; } var result = []; for (var i = 0; i < allClasses.length; i++) { elem_css(allClasses[i], result); } var css = result.join('\n') $("#NewLayoutForm").submit(function(e) { e.preventDefault(); var formData = new FormData(this); formData.set('html', html) formData.set('css', css) $.ajax({ url: base_url + '/save-layout', type: 'POST', data: formData, success: function (data) { var attr = editor.getSelected().getAttributes(); attr['data-layout'] = data.id; editor.getSelected().setAttributes(attr); modal.close(); }, cache: false, contentType: false, processData: false }); }); $("form#NewBlockForm").submit(function(e) { e.preventDefault(); var data = {}; var formData = new FormData(this); for (var pair of formData.entries()) { data[pair[0]] = pair[1]; } data.html = html; data.css = css; $.ajax({ url: base_url + '/save-block', type: 'POST', data: data, success: function (data) { modal.close(); } }); }); }, }; defaultCommands['tlb-clone'] = { run(ed) { var sel = ed.getSelected(); if (!sel || !sel.get('copyable')) { console.warn('The element is not clonable'); return; } var collection = sel.collection; var index = collection.indexOf(sel); const added = collection.add(sel.clone(), { at: index + 1 }); sel.emitUpdate(); ed.trigger('component:clone', added); } }; defaultCommands['tlb-move'] = { run(ed, sender, opts) { let dragger; const em = ed.getModel(); const event = opts && opts.event; const sel = ed.getSelected(); const toolbarStyle = ed.Canvas.getToolbarEl().style; const nativeDrag = event.type == 'dragstart'; const hideTlb = () => { toolbarStyle.display = 'none'; em.stopDefault(); }; if (!sel || !sel.get('draggable')) { console.warn('The element is not draggable'); return; } // Without setTimeout the ghost image disappears nativeDrag ? setTimeout(() => hideTlb, 0) : hideTlb(); const onStart = (e, opts) => { console.log('start mouse pos ', opts.start); console.log('el rect ', opts.elRect); var el = opts.el; el.style.position = 'absolute'; el.style.margin = 0; }; const onEnd = (e, opts) => { em.runDefault(); em.setSelected(sel); sel.emitUpdate(); dragger && dragger.blur(); }; const onDrag = (e, opts) => { console.log('Delta ', opts.delta); console.log('Current ', opts.current); }; if (em.get('designerMode')) { // TODO move grabbing func in editor/canvas from the Sorter dragger = editor.runCommand('drag', { el: sel.view.el, options: { event, onStart, onDrag, onEnd } }); } else { if (nativeDrag) { event.dataTransfer.setDragImage(sel.view.el, 0, 0); //sel.set('status', 'freezed'); } const cmdMove = ed.Commands.get('move-comp'); cmdMove.onEndMoveFromModel = onEnd; cmdMove.initSorterFromModel(sel); } sel.set('status', 'freezed-selected'); } }; // Core commands defaultCommands['core:undo'] = e => e.UndoManager.undo(); defaultCommands['core:redo'] = e => e.UndoManager.redo(); defaultCommands['core:canvas-clear'] = e => { e.DomComponents.clear(); // e.CssComposer.clear(); }; defaultCommands['core:copy'] = ed => { const em = ed.getModel(); const model = ed.getSelected(); if (model && model.get('copyable') && !ed.Canvas.isInputFocused()) { em.set('clipboard', model); } }; defaultCommands['core:paste'] = ed => { const em = ed.getModel(); const clp = em.get('clipboard'); const model = ed.getSelected(); const coll = model && model.collection; if (coll && clp && !ed.Canvas.isInputFocused()) { const at = coll.indexOf(model) + 1; coll.add(clp.clone(), { at }); } }; if (c.em) c.model = c.em.get('Canvas'); this.loadDefaultCommands(); return this; }, /** * Add new command to the collection * @param {string} id Command's ID * @param {Object|Function} command Object representing your command, * By passing just a function it's intended as a stateless command * (just like passing an object with only `run` method). * @return {this} * @example * commands.add('myCommand', { * run(editor, sender) { * alert('Hello world!'); * }, * stop(editor, sender) { * }, * }); * // As a function * commands.add('myCommand2', editor => { ... }); * */ add, /** * Get command by ID * @param {string} id Command's ID * @return {Object} Object representing the command * @example * var myCommand = commands.get('myCommand'); * myCommand.run(); * */ get(id) { var el = commands[id]; if (typeof el == 'function') { el = new el(c); commands[id] = el; } return el; }, /** * Check if command exists * @param {string} id Command's ID * @return {Boolean} * */ has(id) { return !!commands[id]; }, /** * Load default commands * @return {this} * @private * */ loadDefaultCommands() { for (var id in defaultCommands) { this.add(id, defaultCommands[id]); } return this; } }; }; <file_sep>var Component = require('./Component'); module.exports = Component.extend( { defaults: _.extend({}, Component.prototype.defaults, { type: 'full-width', tagName: 'full-width', style: { "max-width": '100%', // "display": 'block', "min-height": '10px', }, }), initialize(o, opt) { Component.prototype.initialize.apply(this, arguments); }, }, { /** * Detect if the passed element is a valid component. * In case the element is valid an object abstracted * from the element will be returned * @param {HTMLElement} * @return {Object} * @private */ isComponent(el) { var result = ''; if (el.tagName == 'FULL-WIDTH' || $(el).hasClass('full-width')) { result = { type: 'full-width' }; } return result; } } ); <file_sep>require('utils/ColorPicker'); const Input = require('./Input'); const $ = Backbone.$; module.exports = Input.extend({ template() { const ppfx = this.ppfx; return ` <div class="${this.holderClass()}"></div> <div class="${ppfx}field-colorp"> <div class="${ppfx}field-colorp-c" data-colorp-c> <div class="${ppfx}checker-bg"></div> </div> </div> `; }, inputClass() { const ppfx = this.ppfx; return `${ppfx}field ${ppfx}field-color`; }, holderClass() { return `${this.ppfx}input-holder`; }, /** * Set value to the model * @param {string} val * @param {Object} opts */ setValue(val, opts = {}) { const model = this.model; var original_val = val; if (window.editor) { for (var i = 0; i < window.editor.CssComposer.getAll().models.length; i++) { if (window.editor.CssComposer.getAll().models[i].attributes.selectorsAdd === ':root') { var root_style = window.editor.CssComposer.getAll().models[i]; if (val.indexOf('var(') > -1) { var variable = val.replace('var(', '').replace(')', ''); val = root_style.attributes.style[variable]; } } } } const value = val || model.get('defaults'); const inputEl = this.getInputEl(); const colorEl = this.getColorEl(); const valueClr = value != 'none' ? value : ''; inputEl.value = original_val; colorEl.get(0).style.backgroundColor = valueClr; // This prevents from adding multiple thumbs in spectrum if (opts.fromTarget) { colorEl.spectrum('set', valueClr); this.noneColor = value == 'none'; } }, /** * Get the color input element * @return {HTMLElement} */ getColorEl() { if (!this.colorEl) { const self = this; const ppfx = this.ppfx; var model = this.model; var colorEl = $(`<div class="${this.ppfx}field-color-picker"></div>`); var cpStyle = colorEl.get(0).style; var elToAppend = this.em && this.em.config ? this.em.config.el : ''; var colorPickerConfig = this.em && this.em.getConfig && this.em.getConfig("colorPicker") || {}; const getColor = color => { let cl = color.getAlpha() == 1 ? color.toHexString() : color.toRgbString(); return cl.replace(/ /g, ''); } let changed = 0; let previousColor; this.$el.find(`[data-colorp-c]`).append(colorEl); // aryeh edits window.css_map = {}; var palette = []; var iframe = window.$('.gjs-frame')[0]; if (iframe) { var innerDoc = iframe.contentDocument || iframe.contentWindow.document; var allCSS = [].slice.call(innerDoc.styleSheets) .reduce(function(prev, styleSheet) { if (!styleSheet.href) { return prev + [].slice.call(styleSheet.cssRules) .reduce(function(prev, cssRule) { if (cssRule.selectorText == ':root') { var css = cssRule.cssText.split('{'); css = css[1].replace('}','').split(';'); for (var i = 0; i < css.length; i++) { var prop = css[i].split(':'); if (prop.length == 2 && prop[0].indexOf('--') == 1) { palette.push(prop[1]); window.css_map[prop[1]] = prop[0]; } } } }, ''); } }, ''); } // end edits colorEl.spectrum({ containerClassName: `${ppfx}one-bg ${ppfx}two-color`, appendTo: elToAppend || 'body', maxSelectionSize: 8, showPalette: true, showAlpha: true, chooseText: 'Ok', cancelText: '⨯', palette: [ palette ], // config expanded here so that the functions below are not overridden ...colorPickerConfig, move(color) { const cl = getColor(color); cpStyle.backgroundColor = cl; model.setValueFromInput(window.css_map[cl] ? 'var(' + window.css_map[cl] + ')' : cl, 0); }, change(color) { changed = 1; const cl = getColor(color); cpStyle.backgroundColor = cl; model.setValueFromInput(window.css_map[cl] ? 'var(' + window.css_map[cl] + ')' : cl); self.noneColor = 0; }, show(color) { changed = 0; previousColor = getColor(color); }, hide(color) { if (!changed && previousColor) { if (self.noneColor) { previousColor = ''; } cpStyle.backgroundColor = previousColor; colorEl.spectrum('set', previousColor); model.setValueFromInput( window.css_map[previousColor] ? 'var(' + window.css_map[previousColor] + ')' : previousColor , 0); } } }); this.colorEl = colorEl; } return this.colorEl; }, render() { Input.prototype.render.call(this); // This will make the color input available on render this.getColorEl(); return this; } }); <file_sep>module.exports = require('./PropertyView').extend({ templateInput() { const pfx = this.pfx; const ppfx = this.ppfx; return ` <div class="${ppfx}field ${ppfx}field-radio"> <span id="${pfx}input-holder"></span> </div> `; }, onRender() { const pfx = this.pfx; const ppfx = this.ppfx; const itemCls = `${ppfx}radio-item-label`; const model = this.model; const prop = model.get('property'); const options = model.get('list') || model.get('options') || []; if (!this.$input) { if(options && options.length) { let inputStr = ''; options.forEach(el => { let cl = el.className ? `${el.className} ${pfx}icon ${itemCls}` : ''; let id = `${prop}-${el.value}`; let labelTxt = el.name || el.value; let titleAttr = el.title ? `title="${el.title}"` : ''; inputStr += ` <div class="${ppfx}radio-item"> <input type="radio" class="${pfx}radio" id="${id}" name="${prop}" value="${el.value}"/> <label class="${cl || itemCls}" ${titleAttr} for="${id}">${cl ? '' : labelTxt}</label> </div>`; }); this.$inputEl = $(inputStr); this.input = this.$inputEl.get(0); this.$el.find(`#${pfx}input-holder`).html(inputStr); this.$input = this.$el.find(`#${pfx}input-holder input[name="${prop}"]`); } } this.onChange = function(target, that, opt) { var value = $('input[name=position]:checked').val(); // var value = that.$input.parent().find('input:checked').val(); var selected = window.editor.getSelected(); if (!selected.view.$el.closest('.flex-start > div').length) { return; } var parent = selected.view.$el.closest('.flex-start > div').data('model'); // window.editor.select(parent); if (parent.attributes.classes && parent.attributes.classes.models.length === 0) { var sm = parent.view.em.get('SelectorManager'); var labelmodel = sm.add({label: 'col' + parseInt(Math.random()*10000000000)}); if (parent) { var compCls = parent.get('classes'); var lenB = compCls.length; compCls.add(labelmodel); var lenA = compCls.length; window.asfsafsafsaf.add(labelmodel); parent.view.em.trigger('targetClassAdded'); // this.updateStateVis(); } } var modelToStyle = parent.view.em.get('StyleManager').getModelToStyle(parent); var style = modelToStyle.getStyle(); switch (value) { case "none": delete style['margin-left']; delete style['margin-right']; break; case "right": style['margin-left'] = 'auto'; delete style['margin-right']; break; case "center": style['margin-left'] = 'auto'; style['margin-right'] = 'auto'; break; case "left": style['margin-right'] = 'auto'; delete style['margin-left']; break; default: delete style['margin-left']; delete style['margin-right']; } modelToStyle.setStyle(style, {avoidStore: 0}); //window.editor.select(selected); }; }, getInputValue() { return this.$input ? this.$el.find('input:checked').val() : ''; }, setValue(value) { if (!window.editor || !window.editor.getSelected()) { return; } const model = this.model; var selected = window.editor.getSelected(); if (!selected.view.$el.closest('.flex-start > div').length) { return; } var parent = selected.view.$el.closest('.flex-start > div').data('model'); var modelToStyle = parent.view.em.get('StyleManager').getModelToStyle(parent); var style = modelToStyle.getStyle(); var pre_selected = 'none'; if (style['margin-left'] === 'auto' && style['margin-right'] === 'auto') { pre_selected = 'center'; } else if(style['margin-left'] === 'auto' ) { // finsih this ok pre_selected = 'right'; } else if(style['margin-right'] === 'auto') { pre_selected = 'left'; } if (value) { v = value; } var v = model.get('value') || pre_selected; if(this.$input) { var that = this; setTimeout(function (args) { that.$input.filter(`[value="${v}"]`).prop('checked', true); }, 100) } }, });
624080191052e76fe7d24cb0299e224a3acb7648
[ "JavaScript" ]
7
JavaScript
roeef/grapesjs
4465a8c39ef4d7b8da4712bae691ffb4c1e4c59b
ba7d272a67122c588cbc4ba54ad4d5278777e8f4
refs/heads/master
<file_sep>/*eslint-env browser*/ var x, y, z; function calculate(x, y, z) { "use strict"; x = Number(x); y = Number(y); z = z.toUpperCase(); window.console.log(z); var result; switch (z) { case "ADD": result = x + y; window.alert(x + " plus " + y + " = " + result); break; case "SUBTRACT": result = x - y; window.alert(x + " minus " + y + " = " + result); break; case "MULTIPLY": result = x * y; window.alert(x + " multiplied by " + y + " = " + result); break; case "DIVIDE": result = x / y; window.alert(x + " divided by " + y + " = " + result); break; default: ask(); } return; } function ask() { "use strict"; x = window.prompt("Please enter a number"); y = window.prompt("Please enter another number"); z = window.prompt("Please enter an operation to perform - add, subtract multiply, or divide."); calculate(x, y, z); } ask(); <file_sep>///*eslint-env browser*/ ////STEP 1 //function halfNumber(number) { // 'use strict'; // var result = parseFloat( Number(number) / 2); // return "Half of " + number + " is " + result; //} //window.console.log(halfNumber(100)); ////STEP 2 //function squareNumber(number){ // number = Number(number); // var result = number*number; // return "The result of squaring the number " + number + " is " +result; //} // //window.console.log(squareNumber(10)); // ////STEP 3 //function percentOf(x,y){ // x = parseFloat(x); // y = parseFloat(y); // var result = (x / y) * 100; // return x + " is " + result + "% of " + y; //} //window.console.log(percentOf(4,2)); ////STEP 4 // //function findModulus(x,y){ // x = Number(x), y = Number(y); // var result = y%x; // return result + " is the modulus of " + x + " and " + y; //} //window.console.log(findModulus(4,10)); //STEP 5 function calculate() { var numbers = window.prompt("Numbers").split(","); var sum = 0; for (var i = 0; i < numbers.length; i = i + 1) { sum += Number(numbers[i]); } window.console.log(sum); } calculate(); <file_sep>/*eslint-env browser*/ function fortuneTeller(children,partner,geo, job){ window.document.write("You will be a " + job + " in " + geo +", and married to " + partner + " with " + children + " kids.</br>"); } fortuneTeller(2,"Suzy","Seattle","Painter"); fortuneTeller(0,"Your Hand","Your Couch","Bum"); fortuneTeller(5,"Jim","Alaska","Ice Man");
53fa75f30c5d0b46efb515b9191dbe405a6c902c
[ "JavaScript" ]
3
JavaScript
alexstolznut/Assignment03
43f91cc12391bbc9853612dbf5c7b2b37fdca5bd
b63d836ce6a38f6ea9e8b72b8a8dbae89daeffcc
refs/heads/master
<repo_name>sebasz1000/todo-app<file_sep>/server.js let express = require('express'); let mongodb = require('mongodb'); let server = express(); let path = require('path'); let dbName = 'todoApp-db' let connectionString = `mongodb+srv://sebasz1000:<EMAIL>/${dbName}?retryWrites=true&w=majority`; //offered by MongoAtlas(cloud) let db = null; server.use(express.urlencoded({ extended: false })); mongodb.connect(connectionString, {useNewUrlParser: true, useUnifiedTopology: true} , function(err, client){ if(err){ console.log('Mongo Db Connection Error') }else{ db = client.db(); db != null && server.listen(3000); } }); server.get('/', function(req, res){ db.collection('Items').find().toArray(function(err, items){ //!err && res.sendFile(path.join(__dirname + '/index.html')); !err && res.send(`<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Simple To-Do App</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> </head> <body> <div class="container"> <h1 class="display-4 text-center py-1">To-Do App</h1> <div class="jumbotron p-3 shadow-sm"> <form action="/create-item" method="POST"> <div class="d-flex align-items-center"> <input autofocus name="itemName" autocomplete="off" class="form-control mr-3" type="text" style="flex: 1;"> <button class="btn btn-primary">Add New Item</button> </div> </form> </div> <ul class="list-group pb-5"> ${items.map(function(item){ return `<li class="list-group-item list-group-item-action d-flex align-items-center justify-content-between"> <span class="item-text">${item.itemName}</span> <div> <button class="edit-me btn btn-secondary btn-sm mr-1">Edit</button> <button class="delete-me btn btn-danger btn-sm">Delete</button> </div> </li>` }).join("")} </ul> </div> </body> </html>`); }) }); server.post('/create-item', function(req, res){ db.collection('Items').insertOne({ itemName: req.body.itemName }, function(){ res.redirect('/'); }) });
db8ae321223dcd11b75740d32e6462b60d04e33e
[ "JavaScript" ]
1
JavaScript
sebasz1000/todo-app
e97a8102556b0863877cb2374e75806e8df4281e
a9d107ee7e5728865978f8cca3f69dc86ec261d4
refs/heads/master
<file_sep> class PigLatinizer attr_accessor :text #if starts with vowel, add way to end #if startswith consonant movie first to last and add ay def initialize(text) @text = text end def text_converter words = self.text.split(" ") # binding.pry #just checking if vowel or not, but should adda catch for some weird start other than vowel or consonant words.map! do |word| if word[0].scan(/[aeiou]/).length == 0 # binding.pry word = word.split("") word = word.push(word[0]) word.shift word = word.join() word = word + "ay" else word + "way" end end # binding.pry words.join(" ") end # def word_latinizer(word) end #end of class
dc5124b4006c350973cf2d5274575ccd8dc6f79b
[ "Ruby" ]
1
Ruby
josh-sea/sinatra-mvc-lab-nyc-web-111918
c65ccd5aee15868a8e01d1d54969653c24541605
bfea3692511132ddd3e67984f31bc026098600a5
refs/heads/master
<file_sep>import { NgModule } from '@angular/core'; import { Component, OnInit } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { ChartsModule } from 'ng2-charts/ng2-charts'; import { BsDropdownModule } from 'ngx-bootstrap/dropdown'; import { ButtonsModule } from 'ngx-bootstrap/buttons'; import {ViprahubService} from '../../viprahub.service'; import {HttpClient} from '@angular/common/http'; import { DashboardComponent } from './dashboard.component'; import { DashboardRoutingModule } from './dashboard-routing.module'; import {MatButtonModule} from '@angular/material'; import { OrderPipe } from 'ngx-order-pipe'; import {Router} from '@angular/router'; @NgModule({ imports: [ FormsModule, DashboardRoutingModule, ChartsModule, BsDropdownModule, MatButtonModule, ButtonsModule.forRoot() ], declarations: [ DashboardComponent ] }) export class DashboardModule { constructor(private orderPipe: OrderPipe, private vipraService: ViprahubService, private http: HttpClient) { this.vipraService.getMetadata().subscribe(res => { this.vipraService.searchResults = res; }, err => { console.log(err); }); } } <file_sep>import { Component, OnInit, Inject } from '@angular/core'; import { FileUploader, FileItem } from 'ng2-file-upload'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material'; import { FilesService } from '../files.service'; import { ViprahubService } from '../viprahub.service'; import { ModelsService } from '../models.service'; import { LoggedinUserInfoService } from '../services/loggedin-user-info.service'; @Component({ selector: 'app-upload-download', templateUrl: './upload.component.html', styleUrls: ['./upload.component.css'] }) export class UploadDownloadComponent implements OnInit { constructor() {} ngOnInit() { } }
f9e053f74e66b4a46c73bd807adab59c8408b555
[ "TypeScript" ]
2
TypeScript
pavankotas/VipraHubUI
ca8e690854e8c7293f23e306b3cac934511df021
781a9123b5f16935da958f251b3a1cd9147d57d5
refs/heads/master
<file_sep>var scoops = 10; while (scoops >= 0) { if (scoops == 3) { alert ("Ice cream is running low!"); } else if (scoops >9) { alert ("Eat faster, the ice cream is going to melt"); } else if (scoops == 2) { alert ("Going once!"); } else if (scoops == 1) { alert ("Going twice"); } else if (scoops == 0) { alert ("Gone!"); } else { alert("Still lots of ice cream left, come and get it.") } scoops = scoops - 1; } alert ("life without ice cream isn't the same");
428d4f294c1c7e832dbf04ca8de329460deec516
[ "JavaScript" ]
1
JavaScript
mrvmix/hf_html5
0dad4bc5bafc8c84981cbbf57ecbb59cf0f2172e
a3de3f9a6ffc2cd089a5a7fa0f81539f55910b91
refs/heads/master
<file_sep>/** * @ignore * 数组操作类 */ var undef var AP = Array.prototype var indexOf = AP.indexOf var lastIndexOf = AP.lastIndexOf var filter = AP.filter var every = AP.every var some = AP.some var util = require('./base') var map = AP.map var array = { /** * 返回在数组中可以找到一个给定元素的第一个索引,如果不存在,则返回-1 * @method * @param {Array} arr -被查找数组 * @param {*} item -要查找的元素 * @param {Number} [fromIndex=0] -开始查找的位置 * {@link https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf MDN} * @return {Number} * @member util */ indexOf: indexOf ? function (arr, item, fromIndex) { return fromIndex === undef ? indexOf.call(arr, item) : indexOf.call(arr, item, fromIndex) } : function (arr, item, fromIndex) { for (var i = fromIndex || 0, len = arr.length; i < len; ++i) { if (arr[i] === item) { return i } } return -1 }, /** * 返回指定元素(也即有效的 JavaScript 值或变量)在数组中的最后一个的索引,如果不存在则返回 -1。 * 从数组的后面向前查找,从 fromIndex 处开始 * @method * @param {Array} arr -被查找数组 * @param {*} item -被查找的元素 * @param {Number} [fromIndex=arr.length-1] -从此位置开始逆向查找,默认为数组的长度减 1 * @return {number} * {@link https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf MDN} * @member util */ lastIndexOf: (lastIndexOf) ? function (arr, item, fromIndex) { return fromIndex === undef ? lastIndexOf.call(arr, item) : lastIndexOf.call(arr, item, fromIndex) } : function (arr, item, fromIndex) { if (fromIndex === undef) { fromIndex = arr.length - 1 } for (var i = fromIndex; i >= 0; i--) { if (arr[i] === item) { break } } return i }, /** * 返回一个数组的副本,删除重复的条目 * @param {Array} a -数组找到独特的子集 * @param {Boolean} [override] -是否保留组后重复数据,例如 override == true, util.unique([a, b, a]) => [b, a]. * 如果 override == false, util.unique([a, b, a]) => [a, b] * @return {Array} -一个数组中删除重复的条目的副本 * @member util */ unique: function (a, override) { let b = a.slice() if (override) { b.reverse() } let i = 0 let n let item while (i < b.length) { item = b[i] while ((n = util.lastIndexOf(b, item)) !== i) { b.splice(n, 1) } i += 1 } if (override) { b.reverse() } return b }, /** * 检索指定的值是否存在数组中 * @param {*} item -要搜索的单个项目 * @param {Array} arr -项目将被搜索的项目的数组 * @return {Boolean} -是否存在 * @member util */ inArray: function (item, arr) { return util.indexOf(arr, item) > -1 }, /** * 方法创建一个新数组, 其包含通过所提供函数实现的测试的所有元素,不会改变原数组 * @member util * @method * @param {Array} arr -数组 * @param {Function} fn -用来测试数组的每个元素的函数。调用时使用参数 (element, index, array),返回true表示保留该元素(通过测试),false则不保留 * @param {Object} [context] -可选。执行 fn 时的用于 this 的值 * @return {Array} -一个新的通过测试的元素的集合的数组 * {@link https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/filter MDN} * @example * var filtered = util.filter([1,2,3,4],function(element, index, array){return element >= 2;}) * //filtered is [3, 4] */ filter: filter ? function (arr, fn, context) { return filter.call(arr, fn, context || this) } : function (arr, fn, context) { let ret = [] util.each(arr, function (item, i, arr) { if (fn.call(context || this, item, i, arr)) { ret.push(item) } }) return ret }, /** * 创建一个新数组,其结果是该数组中的每个元素都调用一个提供的函数后返回的结果 * 返回一个新数组,每个元素都是回调函数的结果 * @method * @param {Array} arr -被调用的数组 * @param {Function} fn -生成新数组元素的函数fn(currentValue, index, array) * @param {Object} [context] -执行 fn 函数时 使用的this 值 * {@link https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/map MDN} * @return {Array} 一个新数组,每个元素都是回调函数的结果 * @member util * @example * var doubles = util.map([1, 5, 10, 15],function(currentValue, index, array){return currentValue * 2;}); * //doubles is now [2, 10, 20, 30] */ map: map ? function (arr, fn, context) { return map.call(arr, fn, context || this) } : function (arr, fn, context) { let len = arr.length let res = new Array(len) for (let i = 0; i < len; i++) { let el = typeof arr === 'string' ? arr.charAt(i) : arr[i] if (el || i in arr) { // ie < 9 in invalid when typeof arr == string res[i] = fn.call(context || this, el, i, arr) } } return res }, /** * 对累加器和数组中的每个元素(从左到右)应用一个函数,将其减少为单个值 * 返回函数累计处理的结果 * @method * @param {Array} arr -被调用的数组 * @param {Function} callback -执行数组中每个值的函数 * @param {number} [initialValue] -[可选] 用作第一个调用 callback的第一个参数的值。 如果没有提供初始值,则将使用数组中的第一个元素。 在没有初始值的空数组上调用 reduce 将报错 * {@link https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce MDN} * @return {Array} 返回函数累计处理的结果 * @member util * @example * var reduce = util.reduce([0, 1, 2, 3, 4],(prev, curr) => prev + curr ); * //reduce is 10 * var reduce = util.reduce([0, 1, 2, 3, 4],(prev, curr) => prev + curr ,10); * // reduce is 20 */ reduce: function (arr, callback, initialValue) { var len = arr.length if (typeof callback !== 'function') { throw new TypeError('callback is not function!') } // 如果没有初始值和空数组, 抛出错误 if (len === 0 && arguments.length === 2) { throw new TypeError('arguments invalid') } let k = 0 let accumulator if (arguments.length >= 3) { accumulator = initialValue } else { do { if (k in arr) { accumulator = arr[k++] break } // 如果数组不包含值, 则抛出错误 k += 1 if (k >= len) { throw new TypeError() } } while (true) } while (k < len) { if (k in arr) { accumulator = callback.call(undef, accumulator, arr[k], k, arr) } k++ } return accumulator }, /** * 测试数组的所有元素是否都通过了指定函数的测试 * every 方法为数组中的每个元素执行一次 callback 函数, * 直到它找到一个使 callback 返回 false(表示可转换为布尔值 false 的值)的元素。 * 如果发现了一个这样的元素,every 方法将会立即返回 false。 * 否则,callback 为每一个元素返回 true,every 就会返回 true。 * callback 只会为那些已经被赋值的索引调用。不会为那些被删除或从来没被赋值的索引调用。 * every 不会改变原数组。 * @method * @param {Array} arr -受测数组 * @param {Function} callback -用来测试每个元素的函数 * @param {Object} [context] -执行 callback 时使用的 this 值 * @return {Boolean} -数组中的所有元素是否都通过所提供的函数实现的测试则返回true,否则false * @member util * {@link https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/every MND} * @example * var passed = util.every([12, 5, 8, 130, 44],(element, index, array)=> element >= 10); * //passed is false */ every: every ? function (arr, fn, context) { return every.call(arr, fn, context || this) } : function (arr, fn, context) { let len = arr && (arr.length || 0) for (let i = 0; i < len; i++) { if (i in arr && !fn.call(context, arr[i], i, arr)) { return false } } return true }, /** * 测试数组中的某些元素是否通过由提供的函数实现的测试 * 为数组中的每一个元素执行一次 callback 函数,直到找到一个使得 callback 返回一个“真值”(即可转换为布尔值 true 的值) * 如果找到了这样一个值,some 将会立即返回 true。否则,some 返回 false。 * callback 只会在那些”有值“的索引上被调用,不会在那些被删除或从来未被赋值的索引上调用。 * some 被调用时不会改变数组。 * @method * @param {Array} arr -受测数组 * @param {Function} callback -用来测试每个元素的函数 * @param {Object} [context] -执行 callback 时使用的 this 值 * @member util * @return {Boolean} whether some element in the array passes the test implemented by the provided function. * {@link https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/some MND} * @example * var passed = util.some([2, 5, 8, 1, 4],(element, index, array)=> element >= 10;); * // passed is false * var passed = util.some([2, 5, 8, 1, 4],(element, index, array)=> element >= 4;); * // passed is true */ some: some ? function (arr, fn, context) { return some.call(arr, fn, context || this) } : function (arr, fn, context) { let len = arr && (arr.length || 0) for (let i = 0; i < len; i++) { if (i in arr && fn.call(context, arr[i], i, arr)) { return true } } return false }, /** * 将对象转换为真正的数组 * @param o {object|Array} -对象或者数组 * @return {Array} 数组 * @member util * @example * var arr = util.makeArray({a:1,b:2,c:2}); * //arr is [1,2,2] */ makeArray: function (o) { if (o == null) { return [] } if (util.isArray(o)) { return o } let lengthType = typeof o.length let oType = typeof o if (lengthType !== 'number' || typeof o.nodeName === 'string' || (o != null && o === o.window) || oType === 'string' || (oType === 'function' && !('item' in o && lengthType === 'number'))) { return [o] } let ret = [] for (let i = 0, l = o.length; i < l; i++) { ret[i] = o[i] } return ret }, // /** // * 将一个嵌套多层的数组 array(数组) (嵌套可以是任何层数)转换为只有一层的数组。 如果你传递 shallow参数,数组将只减少一维的嵌套。 // * @param {Array} array -数组 // * @param {Boolean} shallow -数组是否只减少一维的嵌套 // * @example // * flatten([1, [2], [3, [[4]]]]); => [1, 2, 3, 4]; // * flatten([1, [2], [3, [[4]]]], true); =>[1, 2, 3, [[4]]]; // */ // flatten: function(array, shallow) { // return _.flatten(array, shallow, false); // }, /** * 返回传入的 arrays(数组)并集:按顺序返回,返回数组的元素是唯一的,可以传入一个或多个 arrays(数组)。 * 仅一唯数组才能去重 * @param {...Array} arrays -多个数组 * @example * union([1, 2, 3], [101, 2, 1, 10], [2, 1]); => [1, 2, 3, 101, 10] * union([1, 2, 3], [101, 2, 1, [2,1]], [2, [2,1]]); => [1, 2, 3, 101, 10] */ union: function (...arrays) { var list = [] for (let i = 0; i < arrays.length; i++) { list = list.concat(arrays[i]) } return this.unique(list) }, /** * 类似于without,但返回的值来自array参数数组,并且不存在于rest 数组. * @param {Array} array -被检索数组 * @param {Array} rest -对比数组 * @return {Array} 返回array中不包含rest数组的项 * @example * difference([1, 2, 3, 4, 5], [5, 2, 10])=> [1, 3, 4] */ difference: function (array, ...rest) { return util.filter(array, function (value) { return !util.contains(...rest, value) }) }, /** * 返回一个删除所有...args 值后的 array副本。 * @param {Array} array -被检索数组 * @param {...arguments} args -对比的项 * @return {Array} 删除所有otherArrays 值后的 array副本 * @example * without([1, 2, 1, 0, 3, 1, 4], 0, 1) => [2, 3, 4] */ // without: _.restArgs(function(array, otherArrays) { // return util.difference(array, otherArrays); // }), without: function (array, ...args) { return util.difference(array, args) } } util.mix(util, array) <file_sep>/** * @ignore * 数据类型检测 */ var util = require('./base') var class2type = {} var FALSE = false var undef var OP = Object.prototype var toString = OP.toString function hasOwnProperty (o, p) { return OP.hasOwnProperty.call(o, p) } function shallowProperty (key) { return function (obj) { return obj === null ? void 0 : obj[key] } } var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1 var getLength = shallowProperty('length') /** * 集合方法的帮助器, 用于确定集合是否应作为数组或对象进行迭代 * @param collection * @returns {boolean} */ function isArrayLike (collection) { var length = getLength(collection) return typeof length === 'number' && length >= 0 && length <= MAX_ARRAY_INDEX } util.mix(util, { /** * 获取对象类型 * @member util */ isType: function (o) { return o == null ? String(o) : class2type[toString.call(o)] || 'object' }, /** * 检查对象是否为纯对象 (created using '{}' or 'new Object()' but not 'new FunctionClass()') * @member util */ isPlainObject: function (obj) { if (!obj || util.isType(obj) !== 'object' || obj.nodeType || obj.window === obj) { return FALSE } let key let objConstructor try { if ((objConstructor = obj.constructor) && !hasOwnProperty(obj, 'constructor') && !hasOwnProperty(objConstructor.prototype, 'isPrototypeOf')) { return FALSE } } catch (e) { return FALSE } for (key in obj) { } return ((key === undef) || hasOwnProperty(obj, key)) }, /** * 给定的数组、字符串或对象是否为空?"空" 对象没有可枚举的属性。 * @param obj * @returns {boolean} */ isEmpty: function (obj) { if (obj === null || obj === undef) return true if (util.isNumber(obj) || util.isBoolean(obj)) return false; if (isArrayLike(obj) && (util.isArray(obj) || util.isString(obj) || util.isArguments(obj))) return obj.length === 0 return util.keys(obj).length === 0 }, /** * 给定值是否为 DOM 元素? * @param obj * @returns {boolean} */ isElement: function (obj) { return !!(obj && obj.nodeType === 1) }, /** * 是否有限数值 * @param obj * @returns {boolean} */ isFinite: function (obj) { return isFinite(obj) && !isNaN(parseFloat(obj)) }, isWindow: function (obj) { return obj != null && obj === obj.window; } }) var types = 'Boolean Number String Function Date RegExp Object Array Null Undefined'.split(' ') for (let i = 0; i < types.length; i++) { (function (name, lc) { class2type['[object ' + name + ']'] = (lc = name.toLowerCase()) util['is' + name] = function (o) { return util.isType(o) === lc } })(types[i], i) } /** * 是否是参数类型 */ util.isArguments = function (arg) { let result = Object.prototype.toString.call(arg) === '[object Arguments]' if (!result) { result = arg != null && hasOwnProperty(arg, 'callee') } return result } util.isArray = Array.isArray || util.isArray <file_sep>import core from '../core/index' const config = core.config const fetch = core.fetch const noop = function (res) { return res } class Server { filter(ajax, intelligent = noop){ return new Promise((resolve, reject) => { ajax.then(res => { console.log(res.data) if (res.code == '300008' || res.code == '300010') { //token过期或无效 this.getToken(function (res) { //重新发起请求 filter(ajax, intelligent) }); } else { resolve(intelligent(res.data)) } }).catch(err => { reject(err) }) }) } /** *登录获取配置信息 * @param {*} params * @param {*} [intelligent=noop] * @memberof Service */ GetConfig(params, intelligent = noop) { let url = config.LoginUrl return this.filter(fetch({url: url, method: 'get'}), intelligent) } /** *更新Token * @param {*} params * @memberof Server */ getToken(params){ console.log('更新token') } } export default new Server() <file_sep>/** * @ignore * number 操作类 */ var util = require('./base') var number = { /** * @description 为目标数字添加逗号分隔 * @function * @name util.comma * @param {Number} source -需要处理的数字 * @param {Number} length -两次逗号之间的数字位数,默认为3位 * @return {String} 添加逗号分隔后的字符串 * @example util.comma(source,length) */ comma: function (source, length) { if (!length || length < 1) { length = 3 } source = String(source).split('.') source[0] = source[0].replace(new RegExp('(\\d)(?=(\\d{' + length + '})+$)', 'ig'), '$1,') return source.join('.') }, /** * @description 对目标数字进行0补齐处理 * @function * @name util.pad * @param {Number} -source 需要处理的数字 * @param {Number} -len 需要输出的长度 * @return {String} 对目标数字进行0补齐处理后的结果 * @example util.pad(source,len) */ pad: function (source, length) { let pre = '' let negative = (source < 0) let string = String(Math.abs(source)) if (string.length < length) { pre = (new Array(length - string.length + 1)).join('0') } return (negative ? '-' : '') + pre + string }, //生成从minNum到maxNum的随机数 randomNum: function (minNum, maxNum) { switch (arguments.length) { case 1: return parseInt(Math.random() * minNum + 1, 10); break; case 2: return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10); break; default: return 0; break; } } } util.mix(util, { number: number }) <file_sep>// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' import router from './router' import './static/style/index.css' Vue.config.productionTip = false //通用组件模块 import * as Packages from './packages/index' Vue.use(Packages) //数据模块 import lib from './static/libs/index' Vue.prototype.$api = lib.core Vue.prototype.$util = lib.utils Vue.prototype.$service = lib.service //配置AiagainUI模块 import comm from './components/index' Vue.prototype.$comm = comm // import Vconsole from 'vconsole' // let vConsole = new Vconsole(); new Vue({ router, render: h => h(App) }).$mount('#app')<file_sep>/* eslint-disable */ import * as PIXI from "pixi.js" import TWEEN from "tween.js" const Application = PIXI.Application const Container = PIXI.Container const Sprite = PIXI.Sprite const loader = new PIXI.Loader() let app let gameScene let plane let texture let bullets = [] // 子弹组 let obstacles = [] // 障碍物组 let tweens = [] let total_score = 50 //分数达到才算通过 let score = 0 // 分数 let scorePanel // 分数记录 let comm = null let game = { gameInit: gameInit, start: gameStart, end: () => {} } //静态资源 const sources = { bg: require("@/static/images/bg.jpg"), boom: "./img/boom/boom.json", plane: require("@/static/images/plane.png"), bullet: require("@/static/images/bullet.png"), enemy1: require("@/static/images/enemy1.png"), enemy2: require("@/static/images/enemy2.png"), enemy3: require("@/static/images/enemy3.png"), } // 加载资源 function gameLoad() { for (let i in sources) { loader.add(i, sources[i]) } loader.load((loader, resources) => { // 加载完毕回调 gameSetup(resources) //执行创建精灵等操作 texture = resources }) } /** * 初始化 * @param {*} dom */ function gameInit(dom, func) { app = new Application({ width: getWidth(100), height: getHeight(100), antialiasing: true, // 抗锯齿 transparent: false, // 背景透明 resolution: 2 // 渲染倍数,避免模糊 }) dom.append(app.view) comm = func gameLoad() } /** * 初始化后调用函数 * @param {*} resources */ function gameSetup(resources) { // 创建场景 gameScene = new Container() gameScene.name = "gameScene" gameScene.width = getWidth(100) gameScene.height = getHeight(100) gameScene.x = 0 gameScene.y = 0 app.stage.addChild(gameScene) // 创建背景 let bg = new Sprite(resources.bg.texture) bg.width = getWidth(100) bg.height = getHeight(100) bg.x = 0 bg.y = 0 gameScene.addChild(bg) // 创建分数 scorePanel = new PIXI.Text("得分:" + score, { fontSize: 10, fill: "#fff" }) scorePanel.x = 10 scorePanel.y = 10 scorePanel.name = "scorePanel" gameScene.addChild(scorePanel) // 创建飞机 plane = createPlane(resources) gameScene.addChild(plane) gameStart() } /** * 调用pixi ticker定时器开启游戏 */ function gameStart() { app.ticker.add(function() { return gameLoop() }) } /** * 定时操作函数 */ function gameLoop() { // 生成子弹 plane.shut(gameScene, bullets) // 生成障碍物 createobstacle(gameScene, texture, obstacles, TWEEN, tweens) // 子弹逻辑处理 bulletsEvents() // 障碍物逻辑处理 obstaclesEvents() } /** * 子弹碰撞检测 */ function bulletsEvents() { for (let i = 0; i < bullets.length; ) { let hit = false for (let o = 0; o < obstacles.length; ) { // 子弹与障碍物碰撞检测 if (hitTest(obstacles[o], bullets[i])) { hit = true // 加分 score = score+obstacles[o].score scorePanel.text = "得分:" + score // 移除障碍物 obstaclesBoom(o) continue } else if (hitTest(obstacles[o], plane)) { // 飞机与障碍物碰撞检测 let _obstacle = obstacles.splice(o, 1)[0] _obstacle.destroy() gameOver() continue } else { o++ } } // 根据碰撞状态做处理 if (hit) { // 如果碰撞了 // 移除当前子弹 let _bullet = bullets.splice(i, 1)[0] _bullet.destroy() } else { // 如果子弹飞出屏幕,则移除;如果没有,Y轴位移 if (bullets[i].y < -bullets[i].height) { let _bullet = bullets.splice(i, 1)[0] _bullet.destroy() } else { bullets[i].y -= 10 i++ } } } } /** * 子弹碰撞后移除障碍物 * @param {*} o */ function obstaclesBoom(o) { let container = obstacles[o].parent let _obstacle = obstacles.splice(o, 1)[0] _obstacle.destroy() container.children[0].play() container.children[1].visible = false } /** * 障碍物更新位置移动 */ function obstaclesEvents() { TWEEN.update() } /** * 生成我方飞机类 * @param {*} resources */ let delay = 0 let createSpeed = 0.2 function createPlane(resources) { // 创建 let plane = new PIXI.Sprite(resources.plane.texture) plane.name = "plane" plane.width = 80 plane.height = 60 plane.x = document.body.clientWidth / 2 plane.y = document.body.clientHeight - plane.height // 拖动 plane.interactive = true plane.on("pointermove", onDragMove) // 射击 plane.shut = shut function shut(gameScene, bullets) { if (delay > createSpeed) { delay = 0 let bullet = new PIXI.Sprite(resources.bullet.texture) bullet.width = 10 bullet.height = 20 bullet.x = plane.x + plane.width * 0.5 - bullet.width * 0.5 bullet.y = plane.y gameScene.addChild(bullet) bullets.push(bullet) } else { delay += 1 / 60 } } return plane } /** * 我方飞机移动 * @param {*} event */ function onDragMove(event) { let currentTarget = event.currentTarget let newPosition = event.data.global // 获取拖动到的位置 // 划分范围 if (newPosition.x > 0 && newPosition.x < getWidth(100)) { currentTarget.x = newPosition.x - currentTarget.width * 0.5 } if (newPosition.y > 0 && newPosition.y < getHeight(100)) { currentTarget.y = newPosition.y - currentTarget.height * 0.5 } } /** * 生成敌机障碍物 * @param {*} gameScene * @param {*} texture * @param {*} obstacles * @param {*} TWEEN * @param {*} tweens */ let enemy_delay = 0 let enemy_createSpeed = 3 let obstacleTime = 6000 function createobstacle(gameScene, texture, obstacles, TWEEN, tweens) { if (enemy_delay > enemy_createSpeed) { enemy_createSpeed -= enemy_createSpeed * 0.05 enemy_delay = 0 let container = new PIXI.Container() // 图案-随机生成敌机(小飞机,中飞机,大飞机) let enemyType = Math.floor(Math.random() * 3) let enemySprite,enemyWidth,enemyHeight,enemyScore if(enemyType==1){ enemySprite = texture.enemy1.texture enemyWidth = 50 enemyHeight = 50 enemyScore = 1 }else if(enemyType==2){ enemySprite = texture.enemy2.texture enemyWidth = 70 enemyHeight = 70 enemyScore = 2 }else{ enemySprite = texture.enemy3.texture enemyWidth = 80 enemyHeight = 80 enemyScore = 3 } let obstacle = new PIXI.Sprite(enemySprite) obstacle.name = "obstacle" obstacle.width = enemyWidth obstacle.height = enemyHeight obstacle.x = 0 obstacle.y = 0 obstacle.score = enemyScore obstacle.anchor.set(0.5, 0.5) // 碰撞区域 let circle = new PIXI.Sprite() circle.width = obstacle.width * 0.5 circle.height = circle.width circle.name = "circle" circle.circular = true circle.x = -circle.width * 0.5 circle.y = -circle.height * 0.5 circle.score = enemyScore container.addChild(circle) // 爆炸效果 let fireClip = [] for (let i = 0; i <= 23; i++) { fireClip.push(texture.boom.textures["boom" + i + ".png"]) } let boom = new PIXI.AnimatedSprite(fireClip) boom.width = obstacle.width * 2.5 boom.height = obstacle.height * 2.5 boom.x = -boom.width * 0.5 boom.y = -boom.height * 0.5 boom.name = "boom" boom.loop = false container.addChild(boom) container.addChild(obstacle) container.addChild(circle) container.x = getWidth(Math.random() * 100) container.y = -obstacle.height // 位移设定 let tween = new TWEEN.Tween(container) .to( { x: getWidth(Math.random() * 100), y: getHeight(100) + obstacle.height }, obstacleTime // tween持续时间 ) .easing(TWEEN.Easing.Linear.None) .onComplete(function() { // 到底 container.destroy() }) tween.start() // 插入场景 container.tween = tween obstacles.push(circle) tweens.push(tween) gameScene.addChild(container) } else { enemy_delay += 1 / 60 } } /** * 子弹碰撞检测 * @param {*} r1 * @param {*} r2 */ function hitTest(r1, r2) { let b = new Bump(PIXI) if (b.hitTestCircleRectangle(r1, r2, true) !== false) { return true } else { return false } } function getWidth(precent) { let w = document.body.clientWidth > 720 ? 720 : document.body.clientWidth return ((precent / 50) * w) / 2 } function getHeight(precent) { let h = document.body.clientHeight return ((precent / 50) * h) / 2 } /** * 游戏结束 */ function gameOver() { console.log("游戏结束") app.ticker.stop() let type,list if (score > total_score) { type = 1 list = ["恭喜您挑战成功!", "你的得分为:" + score] } else { type = 2 list = ["挑战失败,挑战过关需达到" + total_score + "分"] } const challengeData = { type: type, list: list, toAgain: function() { location.reload(true); }, toFollow: function() { //关注我们 comm.Follow() } } comm.Challenge(challengeData) } export default game <file_sep>import config from './config.js' import fetch from './fetch.js' import wechat from './wechat.js' import store from './store.js' export default { config, fetch, wechat, store, }<file_sep> class store { constructor () { this.prefix = '20190626' } /** * 写入本地localStorage * @param {String} key -key * @param {*} val -值 */ setItem (key, val) { let tmp = { val: val } key = this.prefix + key window.localStorage.setItem(key, JSON.stringify(tmp)) } /** * 读取本地localStorage信息 * @param {String} key * @returns {*} */ getItem (key) { let val = null key = this.prefix + key let item = window.localStorage.getItem(key) if (item !== null) { try { val = JSON.parse(item).val } catch (e) { val = item } } return val } /** * 删除本地localStorage信息 * @param {String} key * @returns {*} */ remove (key) { let val = null key = this.prefix + key window.localStorage.removeItem(key) } /** * 清空localStorage信息 * @param {String} key * @returns {*} */ clear () { window.localStorage.clear() } } export default new store() <file_sep>/** * @ignore * escape of lang */ var util = require('./base') var EMPTY = '' var htmlEntities = { '&amp;': '&', '&gt;': '>', '&lt;': '<', '&#x60;': '`', '&#x2F;': '/', '&quot;': '"', /* jshint quotmark:false */ '&#x27;': "'" } var reverseEntities = {} for (let k in htmlEntities) { reverseEntities[htmlEntities[k]] = k } var escapeHtmlReg = getEscapeReg() var unEscapeHtmlReg = getUnEscapeReg() function getEscapeReg () { let str = EMPTY for (let e in htmlEntities) { let entity = htmlEntities[e] str += entity + '|' } str = str.slice(0, -1) escapeHtmlReg = new RegExp(str, 'g') return escapeHtmlReg } function getUnEscapeReg () { let str = EMPTY for (let e in reverseEntities) { let entity = reverseEntities[e] str += entity + '|' } str += '&#(\\d{1,5});' unEscapeHtmlReg = new RegExp(str, 'g') return unEscapeHtmlReg } var escape = { /** * 将字符串经过 html 转义得到适合在页面中显示的内容, 例如替换 < 为 < Note * 此函数只会对以下符号进行 escape:& > < / " '` * @param str {string} text2html 要显示在页面中的真实内容 * @member util * @return {String} 经过 html 转义后的字符串 */ escapeHtml: function (str) { if (!str && str !== 0) { return '' } str = '' + str if (!/[&<>"'`]/.test(str)) { return str } return (str + '').replace(escapeHtmlReg, function (m) { return reverseEntities[m] }) }, /** * 获取用于构造 regexp 的转义 regexp 字符串。 * @param str * @member util * @return {String} regexp 字符串 */ escapeRegExp: function (str) { return str.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&') }, /** * un-escape html 转 string. * 仅仅使用 unescape * &amp; &lt; &gt; &#x60; &#x2F; &quot; &#x27; &#\d{1,5} * @param str {string} html字符串 * @member util * @return {String} 去除html后的字符串 */ unEscapeHtml: function (str) { return str.replace(unEscapeHtmlReg, function (m, n) { return htmlEntities[m] || String.fromCharCode(+n) }) } } util.mix(util, {escape: escape}) <file_sep>import Vue from "vue" export const state = Vue.observable({ active: null, //活动信息 drawsnumber: 3, //活动抽奖次数 appConfig: null, //系统配置信息 userConfig: null, //用户配置信息 }) export const mutations = { setActive(v) { state.active = v }, setDrawsnumber(v) { state.drawsnumber = v }, setAppConfig(v) { state.appConfig = v }, setUserConfig(v) { state.active = v.active state.userConfig = v } }<file_sep>import Vue from 'vue' import Active from './active/index' import challenge from './challenge/index' //添加活动模板 Vue.component(Active.name, Active); let doData = function(data,val){ Object.keys(val).forEach(function(key) { if(val[key]){ data[key] = val[key]; } }) return data } /** * 挑战成功 * @param {*} value */ let Challenge = function(value={}){ var data = { type : 1, userimg: 'http://10.0.4.19/marketing/images/mole/manImg.jpg', } var config = doData(data,value) challenge.open(config); } export default { Active, Challenge, } <file_sep>// import service from '../service/index' /** * @class * 微信操作类 */ class Wechat { /** *通过config接口注入权限验证配置 *debug 开启调试模式 *appId 公众号的唯一标识 *timestamp 生成签名的时间戳 *nonceStr 生成签名的随机串 *signature 签名 *jsApiList 需要使用的JS接口列表 * @param {*} config * @memberof Wechat */ init(config) { wx.config(config); } /** *分享接口 *title 分享标题 *desc 分享描述 *link 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致 *imgUrl分享图标 * @param {*} data * @memberof Wechat */ share(data, callback) { wx.ready(function () { //自定义分享给朋友 wx.updateAppMessageShareData({ title: data.title, desc: data.desc, link: data.link, imgUrl: data.imgUrl, success: function () { // 设置成功 callback && callback() } }) //自定义分享到朋友圈 wx.updateTimelineShareData({ title: data.title, desc: data.desc, link: data.link, imgUrl: data.imgUrl, success: function () { // 设置成功 callback && callback() } }) }); } /** *获取地理位置 *latitude 纬度,浮点数,范围为90 ~ -90 *longitude 经度,浮点数,范围为180 ~ -180。 *speed 速度,以米/每秒计 *accuracy 位置精度 * @memberof Wechat * @memberof Wechat */ getLocation(callback) { wx.getLocation({ type: 'wgs84', // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02' success: function (res) { callback && callback(res) } }); } /** *使用微信内置地图查看位置 *latitude 纬度,浮点数,范围为90 ~ -90 *longitude 经度,浮点数,范围为180 ~ -180 *name 位置名 *address 地址详情说明 *scale 地图缩放级别,整形值,范围从1~28。默认为最大 *infoUrl 在查看位置界面底部显示的超链接,可点击跳转 * @param {*} data * @memberof Wechat */ openLocation(data) { wx.openLocation({ latitude: data.latitude, longitude: data.longitude, name: data.name, address: data.address, scale: 18, infoUrl: data.infoUrl }); } /** *拍照或从手机相册中选图上传图片 *count {number} 上传图片个数 * @param {*} count * @param {*} callback * @memberof Wechat */ chooseImage(count, callback) { wx.chooseImage({ count: count, // 默认9 sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有 sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有 success: function (res) { var localIds = res.localIds; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片 var uploadCount = 0; var localIdLength = localIds.length; var uploadpic = []; var data = []; data['localIds'] = localIds; var upload = function () { //串行上传 wx.uploadImage({ localId: localIds[uploadCount], isShowProgressTips: 1, // 默认为1,显示进度提示 success: function (res) { //上传图片接口 service.uploadImage({ "mediaId": res.serverId }).then(json => { let img = json.result.img_url //图片ID对应图片路径 uploadpic.push(img); uploadCount++; //如果还有照片,继续上传 if (uploadCount < localIdLength) { upload(); } else { callback && callback(uploadpic) } }); } }); }; upload(); } }); } /** *current {string} 当前显示图片的http链接 *urls {array} 需要预览的图片http链接列表 * @param {*} data * @memberof Wechat */ previewImage(data) { wx.previewImage({ current: data.current, urls: data.urls }); } /** *微信扫一扫 * @param {*} callback * @memberof Wechat */ scanQRCode(callback) { wx.scanQRCode({ needResult: 0, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果, scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码,默认二者都有 success: function (res) { var result = res.resultStr; // 当needResult 为 1 时,扫码返回的结果 callback && callback(result) } }); } /** *vue 非history模式,请在url链接#前加入?号 *微信内H5调起支付 *appId 公众号id *timeStamp 时间戳 *nonceStr 随机字符串 *package 订单详情扩展字符串 *signType 签名方式 *paySign 签名 *返回值说明 *get_brand_wcpay_request:ok 支付成功 *get_brand_wcpay_request:cancel 支付过程中用户取消 *get_brand_wcpay_request:fail 支付失败 * @param {*} config * @memberof Wechat */ pay(config,callback) { WeixinJSBridge.invoke('getBrandWCPayRequest', config, function (res) { //WeixinJSBridge.log(res.err_msg); callback && callback(res.err_msg) }); } /** *微信支付 *timestamp 支付签名时间戳,注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符 *nonceStr 支付签名随机串,不长于 32 位 *package 统一支付接口返回的prepay_id参数值,提交格式如:prepay_id=\*\*\*) *signType 签名方式,默认为'SHA1',使用新版支付需传入'MD5' *paySign 支付签名 * @param {*} config * @memberof Wechat */ chooseWXPay(config,callback) { wx.chooseWXPay({ timestamp: config.timestamp, nonceStr: config.nonceStr, package: config.package, signType: config.signType, paySign: config.paySign, success: function (res) { // 支付成功后的回调函数 callback && callback(res.err_msg) } }); } } export default new Wechat();<file_sep>const fs = require('fs') module.exports = { devServer: { port: 8888,// 端口 }, // 部署应用包时的基本 URL publicPath: process.env.NODE_ENV === 'production' ? './' : '/', // 当运行 vue-cli-service build 时生成的生产环境构建文件的目录。注意目标目录在构建之前会被清除 (构建时传入 --no-clean 可关闭该行为)。 outputDir: 'dist', // 放置生成的静态资源 (js、css、img、fonts) 的 (相对于 outputDir 的) 目录。 assetsDir: './', //配置sass全局变量 css: { loaderOptions: { sass: { data: `@import "@/static/style/mixin.scss";` } } }, lintOnSave:false } <file_sep># aircrift vue cli3 + pixi.js 搭建 h5飞机大战小游戏 ## Project setup ``` npm install ``` ## Compiles and hot-reloads for development ``` npm run serve ``` ## Compiles and minifies for production ``` npm run build ``` ## pixi.js 简介 Pixi.js使用WebGL,是一个超快的HTML5 2D渲染引擎。作为一个Javascript的2D渲染器,Pixi.js的目标是提供一个快速的、轻量级而且是兼任所有设备的2D库。提供无缝 Canvas 回退,支持主流浏览器,包括桌面和移动。 Pixi渲染器可以开发者享受到硬件加速,但并不需要了解WebGL。 ## 创建pixi实例 流程 1.创建一个应用(application)(包含舞台stage)<br> 2.加载资源(loader)<br> 3.创建游戏场景<br> 4.将场景插入舞台(addchild)<br> 5.把画布插入dom(append)<br> 6.创建精灵(sprite)<br> 7.把精灵加入画布(addchild)<br> 8.刷新舞台(ticker)<br> 9.游戏结束,销毁应用(destroy) ``` import * as PIXI from 'pixi.js'; let gameApp = new PIXI.Application({ width: xxxx, height: xxxx, antialiasing: true, // 抗锯齿 transparent: false, // 背景透明 resolution: 2 // 渲染倍数,避免模糊 }); //加载资源 let loader = new PIXI.Loader(); loader .add('bg', 'img/bg.jpg') ..... .load((loader, resources) => { // 加载完毕回调 setUp(); //执行创建精灵等操作 }); //创建游戏场景并插入舞台 画布插入dom let gameScene = new PIXI.Container(); gameScene.width = xxx; gameScene.height = xxx; gameApp.stage.addchild(gameScene); document.getElementById('xxx').appendChild(gameApp.view); ``` ## 加载飞机大战静态资源 ``` const sources = { bg: require("@/static/images/bg.jpg"), boom: "./img/boom/boom.json", plane: require("@/static/images/plane.png"), bullet: require("@/static/images/bullet.png"), enemy1: require("@/static/images/enemy1.png"), enemy2: require("@/static/images/enemy2.png"), enemy3: require("@/static/images/enemy3.png"), } function gameLoad() { for (let i in sources) { loader.add(i, sources[i]) } loader.load((loader, resources) => { // 加载完毕回调 gameSetup(resources) //执行创建精灵等操作 texture = resources }) } ``` ## 生成飞机类 ``` let delay = 0 let createSpeed = 0.2 function createPlane(resources) { // 创建 let plane = new PIXI.Sprite(resources.plane.texture) plane.name = "plane" plane.width = 80 plane.height = 60 plane.x = document.body.clientWidth / 2 plane.y = document.body.clientHeight - plane.height // 拖动 plane.interactive = true plane.on("pointermove", onDragMove) // 射击 plane.shut = shut function shut(gameScene, bullets) { if (delay > createSpeed) { delay = 0 let bullet = new PIXI.Sprite(resources.bullet.texture) bullet.width = 10 bullet.height = 20 bullet.x = plane.x + plane.width * 0.5 - bullet.width * 0.5 bullet.y = plane.y gameScene.addChild(bullet) bullets.push(bullet) } else { delay += 1 / 60 } } return plane } /** * 我方飞机移动 * @param {*} event */ function onDragMove(event) { let currentTarget = event.currentTarget let newPosition = event.data.global // 获取拖动到的位置 // 划分范围 if (newPosition.x > 0 && newPosition.x < getWidth(100)) { currentTarget.x = newPosition.x - currentTarget.width * 0.5 } if (newPosition.y > 0 && newPosition.y < getHeight(100)) { currentTarget.y = newPosition.y - currentTarget.height * 0.5 } } ``` ## 生成敌机 ``` let enemy_delay = 0 let enemy_createSpeed = 3 let obstacleTime = 6000 function createobstacle(gameScene, texture, obstacles, TWEEN, tweens) { if (enemy_delay > enemy_createSpeed) { enemy_createSpeed -= enemy_createSpeed * 0.05 enemy_delay = 0 let container = new PIXI.Container() // 图案-随机生成敌机(小飞机,中飞机,大飞机) let enemyType = Math.floor(Math.random() * 3) let enemySprite,enemyWidth,enemyHeight,enemyScore if(enemyType==1){ enemySprite = texture.enemy1.texture enemyWidth = 50 enemyHeight = 50 enemyScore = 1 }else if(enemyType==2){ enemySprite = texture.enemy2.texture enemyWidth = 70 enemyHeight = 70 enemyScore = 2 }else{ enemySprite = texture.enemy3.texture enemyWidth = 80 enemyHeight = 80 enemyScore = 3 } let obstacle = new PIXI.Sprite(enemySprite) obstacle.name = "obstacle" obstacle.width = enemyWidth obstacle.height = enemyHeight obstacle.x = 0 obstacle.y = 0 obstacle.score = enemyScore obstacle.anchor.set(0.5, 0.5) // 碰撞区域 let circle = new PIXI.Sprite() circle.width = obstacle.width * 0.5 circle.height = circle.width circle.name = "circle" circle.circular = true circle.x = -circle.width * 0.5 circle.y = -circle.height * 0.5 circle.score = enemyScore container.addChild(circle) // 爆炸效果 let fireClip = [] for (let i = 0; i <= 23; i++) { fireClip.push(texture.boom.textures["boom" + i + ".png"]) } let boom = new PIXI.AnimatedSprite(fireClip) boom.width = obstacle.width * 2.5 boom.height = obstacle.height * 2.5 boom.x = -boom.width * 0.5 boom.y = -boom.height * 0.5 boom.name = "boom" boom.loop = false container.addChild(boom) container.addChild(obstacle) container.addChild(circle) container.x = getWidth(Math.random() * 100) container.y = -obstacle.height // 位移设定 let tween = new TWEEN.Tween(container) .to( { x: getWidth(Math.random() * 100), y: getHeight(100) + obstacle.height }, obstacleTime // tween持续时间 ) .easing(TWEEN.Easing.Linear.None) .onComplete(function() { // 到底 container.destroy() }) tween.start() // 插入场景 container.tween = tween obstacles.push(circle) tweens.push(tween) gameScene.addChild(container) } else { enemy_delay += 1 / 60 } } ``` ## 子弹碰撞检测 ``` function hitTest(r1, r2) { let b = new Bump(PIXI) if (b.hitTestCircleRectangle(r1, r2, true) !== false) { return true } else { return false } } ``` ## 思路 首先遍历子弹池,内部遍历所有障碍物,通过hitTest做碰撞检测 如果子弹和障碍物碰撞,子弹消失,障碍物消失/爆炸,得分+1; 如果飞机和障碍物碰撞,障碍物消失/爆炸,游戏结束 如果都没有,检测下一个子弹 如果子弹自下而上,飞出屏幕,则子弹移除,否则影响性能 <file_sep>/** * @ignore * string 操作类 */ var util = require('./base') var undef // IE 的字符不包括非空间 (0xa0) // 类 (根据 ECMAScript 规范7.2 节的要求), 我们明确 // 将其包括在 regexp 中以强制执行一致的跨浏览器行为。 var SUBSTITUTE_REG = /\\?\{([^{}]+)\}/g var EMPTY = '' var RE_TRIM = /^[\s\xa0]+|[\s\xa0]+$/g var trim = String.prototype.trim var RE_DASH = /-([a-z])/ig function upperCase () { return arguments[1].toUpperCase() } var string = { /** * 判断 str 是否以 prefix 开头 * @param {String} str 查找字符串 * @param {String} 前缀字符串 * @return {Boolean} str 是否以 prefix 开头 * @member util */ startsWith: function (str, prefix) { return str.lastIndexOf(prefix, 0) === 0 }, /** * 判断str是否已suffix结尾 * @param {String} str 查找的字符串 * @param {String} 后缀字符创 * @return {Boolean} str是否以suffix结尾 * @member util */ endsWith: function (str, suffix) { var ind = str.length - suffix.length return ind >= 0 && str.indexOf(suffix, ind) === ind }, /** * 去除字符串两端的空白字符 * @param {String} str -原始字符串 * @return {String} 去除空白后新的字符串 * @method * @member util */ trim: trim ? function (str) { return str == null ? EMPTY : trim.call(str) } : function (str) { return str == null ? EMPTY : (str + '').replace(RE_TRIM, EMPTY) }, /** * 调用 encodeURIComponent 对 url 组件进行编码 * @param {String} s url * @return {String} 编码后的URL地址 * @member util */ urlEncode: function (s) { return encodeURIComponent(String(s)) }, /** * 调用 decodeURIComponent 以解码 url 组件, 并将 "+" 替换为空格 * @param {String} s 需要解码的URL * @return {String} 解码后的url * @member util */ urlDecode: function (s) { return decodeURIComponent(s.replace(/\+/g, ' ')) }, camelCase: function (name) { if (name.indexOf('-') === -1) { return name } return name.replace(RE_DASH, upperCase) }, /** * 将字符串中的占位符替换为对应的键值 * @param {String} str -包含数据占位符的模板字符串, 占位符用 {} 包起来 * @param {Object} o -Json 数据 * @param {RegExp} [regexp] -自定义正则匹配 * @return {String} 模板和数据结合起来的最终字符串 * @member util * @example * var str = '{name} is {prop_1} and {prop_2}.', * obj = {name: '<NAME>', prop_1: 'our lord', prop_2: 'savior'}; * * Util.substitute(str, obj); // => '<NAME> is our lord and savior.' */ substitute: function (str, o, regexp) { if (typeof str !== 'string' || !o) { return str } return str.replace(regexp || SUBSTITUTE_REG, function (match, name) { if (match.charAt(0) === '\\') { return match.slice(1) } return (o[name] === undef) ? EMPTY : o[name] }) }, /** 大写的第一个字符 * @member util * @param {String} s 原字符串 * @return {String} 第一个字符大写后的字符串 */ ucfirst: function (s) { s += '' return s.charAt(0).toUpperCase() + s.substring(1) }, /** * @description 对目标字符串进行格式化 * @function * @name util.format * @param {String} str 目标字符串 * @param {String|Object} options 提供相应数据的对象或多个字符串,参数为object时,替换目标字符串中的#{property name}部分;参数为String时,替换目标字符串中的#{0}、#{1}...部分 * @return {String} 格式化后的字符串 * @example * util.format(str, options) * util.format('要格式化{0},{1}的内容',...,1) */ format: function (str, args) { let result = str if (typeof (args) === 'object') { for (let key in args) { if (args[key] !== undef) { let reg = new RegExp('({' + key + '})', 'g') result = result.replace(reg, args[key]) } } } else { for (let i = 1; i < arguments.length; i++) { if (arguments[i] !== undef) { let reg = new RegExp('({[' + i + ']})', 'g') result = result.replace(reg, arguments[i]) } } } return result }, /** * @description -计算字符串长度(英文占一个字符,中文汉字占2个字符) * @function * @name util.getLength(str) * @return {int} -字符串的长度 * @example * util.getLength('获取字符串长度Get string length include chinese') */ getLength: function (str) { if (typeof str === 'undefined' || str === null) return 0 let len = 0 for (let i = 0; i < str.length; i++) { let c = str.charCodeAt(i) if ((c >= 0x0001 && c <= 0x007e) || (c >= 0xff60 && c <= 0xff9f)) { len++ } else { len += 2 } } return len }, isEmptyOrNull: function (str) { return (str === '' || str === null || str === undef) } } util.mix(util, {string: string}) <file_sep>export { default } from './active.vue'; <file_sep>/** * @ignore * 常用工具类 */ require('./array') require('./object') require('./string') require('./number') require('./escape') require('./type') require('./date') require('./compute') module.exports = require('./base')<file_sep>import Vue from 'vue'; import TemplateComponent from './index.vue' const Follow = Vue.extend(TemplateComponent); let instance; export default { open(options = {}) { if (!instance) { instance = new Follow({ el: document.createElement('div'), }); } instance.data = options if (instance.visible) return; instance.vm = instance.$mount() document.body.appendChild(instance.vm.$el) Vue.nextTick(() => { instance.visible = true; }); }, close() { if (instance) { instance.visible = false; } } }; <file_sep>import core from './core/index.js' import utils from './utils/index.js' import service from './service/index.js' export default { core, utils, service, }
20f61f56dfad340f28520da5ed4d0e17b8dabab9
[ "JavaScript", "Markdown" ]
19
JavaScript
springwindyike/aircrift
01c4fea8509060d88421c159bfd00979150ecb26
c8a58f075d91b14ab79173b5734190ce30f8455e
refs/heads/master
<repo_name>Gauravpratapsinghjadon/ASKME<file_sep>/models/question.js const mongoose = require('mongoose') const questionSchema = mongoose.Schema({ question: { type: String, required: true }, createdOn: { type: Date, default: Date.now() }, answers: [{ name:String, answer:String }] }) const nn =mongoose.model("questions", questionSchema) module.exports = nn<file_sep>/controllers/question.js const router = require('express').Router() const bodyParser = require('body-parser') const { check, validationResult } = require('express-validator') const Question = require('../models/question') router.use(bodyParser.json()) router.use(bodyParser.urlencoded({ extended: true })) router.post('/', [ check('question').not().isEmpty().trim().escape() ], (req, res) => { const errors = validationResult(req) if (!errors.isEmpty()) { return res.status(422).json({ message: "success", status: false, error: errors.array(), data: req.body }) } Question.create({ question: req.body.question }, (err, result) => { if (err) { return res.status(422).json({ message: "success", status: false, error: errors.array() }) } return res.status(200).json({ message: 'success', status: 200, data: req.body }) }) }) router.put('/answer', [ check('answer').not().isEmpty().trim().escape() ], (req, res) => { const errors = validationResult(req) if (!errors.isEmpty()) { return res.status(422).json({ message: "success", status: false, error: errors.array(), data: req.body }) } Question.findByIdAndUpdate(req.body.id, { $push: { answers: { answer: req.body.answer, name: req.body.name } } } , (err, result) => { if (err) { return res.status(422).json({ message: "success", status: false, error: errors.array() }) } return res.status(200).json({ message: 'success update', status: 200, data: result }) }) }) router.get('/', (req, res) => { Question.aggregate((err, result) => { if (err) { return res.status(422).json({ message: "success", status: false, error: errors.array() }) } return res.status(200).json({ message: 'success', status: 200, data: result }) }).sort({question: 1 }).exec(); }) router.get('/:id', (req, res) => { Question.findOne({ _id: req.params.id }, (err, result) => { if (err) { return res.status(422).json({ message: "success", status: false, error: errors.array() }) } return res.status(200).json({ message: 'success', status: 200, data: result }) }) }) router.all('/', (req, res) => { return res.status(200).json({ message: 'success', status: 200 }) }) module.exports = router
d61d6397a3d3aba8fd461dd0d989e9b35f77bfa9
[ "JavaScript" ]
2
JavaScript
Gauravpratapsinghjadon/ASKME
e1a728cef48e94ac4328929230b9c2a091f02ba7
166e5031b9cc92d360712a0a1672aac2397cb75b
refs/heads/master
<file_sep>source 'https://rubygems.org' gem 'rake' gem 'json' gem 'kramdown' gem 'retriable' gem 'aws-sdk-s3' gem 'rest-client'<file_sep>#!/usr/bin/env ruby require 'rubygems' %w(rake rake/file_utils).each do |f| begin require f rescue LoadError => e puts "Unable to require #{f}, continuing" end end include FileUtils current_core_commit='' pipeline_counter='' stage_counter='' cd("../gocd/core") do current_core_commit=%x[git log -1 --format=%H].strip puts "current core commit:#{current_core_commit}" end cd("../gocd_build_map") do commit_to_build_mapping_cmd="grep '#{current_core_commit}' commit_build_map | tail -n 1" puts "Get mapping : [#{commit_to_build_mapping_cmd}]" commit_to_build_mapping=%x[#{commit_to_build_mapping_cmd}].strip if commit_to_build_mapping.nil? || commit_to_build_mapping.empty? puts "Did not find mapping build for #{current_core_commit}" exit 1 end puts "Mapping found: [#{commit_to_build_mapping}]" pipeline_counter = commit_to_build_mapping.split(':')[1].split('/')[0] stage_counter = commit_to_build_mapping.split(':')[1].split('/')[1] puts "pipeline counter:#{pipeline_counter} stage counter:#{stage_counter}" end rm_rf 'zip' mkdir_p 'zip' require 'open-uri' require 'json' urls = JSON.parse(open("#{ENV['GOCD_BUILD_PACKAGE']}/#{pipeline_counter}/dist/#{stage_counter}/dist/dist/zip.json", 'r', http_basic_authentication: [ENV['GOCD_USER'], ENV['GOCD_PASSWORD']]).read).collect {|f| f['url']} cd 'zip' do urls.each do |url| sh("curl --silent --fail --user #{ENV['GOCD_USER']}:#{ENV['GOCD_PASSWORD']} #{url} -O") end end <file_sep>const pg = require('pg'); const request = require('request'); const BUILD_GOCD_URL = process.env.BUILD_GOCD_URL; const BUILD_GOCD_USERNAME = process.env.BUILD_GOCD_USERNAME; const BUILD_GOCD_PASSWORD = process.env.BUILD_GOCD_PASSWORD; const USAGE_DATA_COLLECTOR_APP_URL = process.env.USAGE_DATA_COLLECTOR_APP_URL; const USAGE_DATA_COLLECTOR_APP_DB = process.env.USAGE_DATA_COLLECTOR_APP_DB; const USAGE_DATA_COLLECTOR_APP_DB_PORT = process.env.USAGE_DATA_COLLECTOR_APP_DB_PORT; const USAGE_DATA_COLLECTOR_APP_USERNAME = process.env.USAGE_DATA_COLLECTOR_APP_USERNAME; const USAGE_DATA_COLLECTOR_APP_PASSWORD = process.env.USAGE_DATA_COLLECTOR_APP_PASSWORD; const pgClient = () => { const dbHost = USAGE_DATA_COLLECTOR_APP_URL; const username = USAGE_DATA_COLLECTOR_APP_USERNAME; const password = <PASSWORD>; const dbName = USAGE_DATA_COLLECTOR_APP_DB; const dbPort = USAGE_DATA_COLLECTOR_APP_DB_PORT; const connectionString = "postgres://" + username + ":" + password + "@" + dbHost + ":" + dbPort + "/" + dbName; return new pg.Client({connectionString}); }; const getBuildGoCDDataSharingInformation = (data) => { const requestConfig = { 'url': `${BUILD_GOCD_URL}/api/internal/data_sharing/usagedata`, 'method': 'GET', 'auth': { 'username': BUILD_GOCD_USERNAME, 'password': <PASSWORD> }, 'headers': {'Accept': 'application/vnd.go.cd.v3+json'} }; console.log("Fetching data sharing server id information from build.gocd.org..."); return new Promise((fulfil, reject) => request(requestConfig, (err, res) => { if (err || res.statusCode >= 400) { const msg = err ? err : res.body; return reject(msg); } data.gocd_data_sharing_info = JSON.parse(res.body); fulfil(data); })); }; const getBuildGoCDVersion = (data) => { const requestConfig = { 'url': `${BUILD_GOCD_URL}/api/version`, 'method': 'GET', 'auth': { 'username': BUILD_GOCD_USERNAME, 'password': <PASSWORD> }, 'headers': {'Accept': 'application/vnd.go.cd.v1+json'} }; console.log("Fetching currently deployed build.gocd.org version information..."); return new Promise((fulfil, reject) => request(requestConfig, (err, res) => { if (err || res.statusCode >= 400) { const msg = err ? err : res.body; return reject(msg); } data.gocd_version = JSON.parse(res.body); fulfil(data); })); }; const getUsageDataInformationFromDB = (data) => { const gocdDataSharingInformation = data.gocd_data_sharing_info; const queryString = `SELECT * FROM usagedata WHERE serverid='${gocdDataSharingInformation.server_id}' ORDER BY id DESC limit 10;`; console.log("Fetching build.gocd.org's usage data information from usage-data-collector-app db..."); return new Promise((fulfil, reject) => { const client = pgClient(); client.connect().then(() => { client.query(queryString, (error, result) => { client.end(); if (error) { return reject(error); } data.usage_data_info = result.rows; fulfil(data); }); }); }); }; const isToday = function (otherDay) { const TODAY = new Date(); return otherDay.toDateString() === TODAY.toDateString(); }; const assertUsageDataExists = function (data) { console.log("Start verifying build.gocd.org usage data reporting.."); const GoCDVersion = `${data.gocd_version.version}-${data.gocd_version.build_number}`; const lastTenUsageData = data.usage_data_info; const usageDataReportedToday = lastTenUsageData.filter((usageData) => { return isToday(new Date(usageData.timestamp)) }); if (usageDataReportedToday.length === 0) { throw new Error(`build.gocd.org hasn't reported usage data on date: ${new Date().toString()}`); } const usageDataMatchingVersion = usageDataReportedToday.filter((usageData) => { return (usageData.gocdversion === GoCDVersion); }); if (usageDataMatchingVersion.length === 0) { console.warn(`build.gocd.org hasn't reported usage data for currently deployed version: ${GoCDVersion}`); } console.log("Done verifying build.gocd.org usage data reporting.."); }; const printError = (err) => { let errMsg = `Failed Verifying Usage Data Reporting for build.gocd.org server.\n Reason: ${err}`; console.error(errMsg); process.exit(1); }; getBuildGoCDVersion({}) .then(getBuildGoCDDataSharingInformation) .then(getUsageDataInformationFromDB) .then(assertUsageDataExists) .catch(printError);
1590f378bf46e0ce493e16aa5cc686f37b78910f
[ "JavaScript", "Ruby" ]
3
Ruby
gocd/build_utilities
7cba07f86a1d0eff1877fc87fef7b843afa9a883
338af3f0cc578ba702ccb307e36bf4a57a654a3a
refs/heads/master
<repo_name>Bildos/ToDoFire<file_sep>/ToDoFire/Controllers/LoginViewController.swift // // ViewController.swift // ToDoFire // // Created by Андрей on 9/3/19. // Copyright © 2019 <NAME>. All rights reserved. // import UIKit import Firebase class LoginViewController: UIViewController { @IBOutlet var notExist: UILabel! @IBOutlet var userPassword: UITextField! @IBOutlet var userEmail: UITextField! var ref: DatabaseReference! override func viewDidLoad() { super.viewDidLoad() ref = Database.database().reference(withPath: "users") NotificationCenter.default.addObserver(self, selector: #selector(kbDidShow), name: UIResponder.keyboardDidShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(kbDidHide), name: UIResponder.keyboardDidHideNotification, object: nil) notExist.alpha = 0 Auth.auth().addStateDidChangeListener { (auth, user) in if user != nil { self.performSegue(withIdentifier: "tasks", sender: nil) } } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) userPassword.text = "" userEmail.text = "" } @objc func kbDidShow(notification: Notification) { guard let userInfo = notification.userInfo else { return } let kbFrameSize = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue (self.view as! UIScrollView).contentSize = CGSize(width: self.view.bounds.size.width, height: self.view.bounds.size.height + kbFrameSize.height) (self.view as! UIScrollView).scrollIndicatorInsets = UIEdgeInsets(top: 0, left: 0, bottom: kbFrameSize.height, right: 0) } @objc func kbDidHide() { (self.view as! UIScrollView).contentSize = CGSize(width: self.view.bounds.size.width, height: self.view.bounds.size.height) } func displayWarning(_ text: String){ notExist.text = text UIView.animate(withDuration: 3, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseInOut, animations: {[weak self] in self?.notExist.alpha = 1 }) { [weak self] completion in self?.notExist.alpha = 0 } } @IBAction func login(_ sender: UIButton) { guard let email = userEmail.text, let password = userPassword.text, email != "", password != "" else { displayWarning("Info is incorrect") return } Auth.auth().signIn(withEmail: email, password: <PASSWORD>) { [weak self] (user, error) in if error != nil { self?.displayWarning("Error occured") return } if user != nil { self?.performSegue(withIdentifier: "tasks", sender: nil) return } self?.displayWarning("No such User") } } @IBAction func register(_ sender: Any) { guard let email = userEmail.text, let password = <PASSWORD>.text, email != "", password != "" else { displayWarning("Info is incorrect") return } // Auth.auth().createUser(withEmail: email, password: <PASSWORD>, completion: { (user, error) in // guard error == nil, user != nil else { // print(error!.localizedDescription) // return // } // let userRef = self?.ref.child((user?.uid)!) // userRef?.setValue(["email": user?.email]) // print(user) // }) Auth.auth().createUser(withEmail: email, password: <PASSWORD>) { authResult, error in guard error == nil, authResult != nil else { print(error!.localizedDescription) return } let userRef = self.ref.child((authResult?.user.uid)!) userRef.setValue(["email": authResult?.user.email]) } } }
8c4151892ecf2495631aeba774e6f579e2abcc73
[ "Swift" ]
1
Swift
Bildos/ToDoFire
2154b775575ff0724462e066f790e69d440ff729
2f570bbf0ba8dd966ce7a16a69b5c55265594323
refs/heads/master
<repo_name>adellhk/burrito_generator<file_sep>/burrito_gen/app/models/list.rb class Combination < ActiveRecord::Base belongs_to :burrito belongs_to :ingredient end <file_sep>/burrito_gen/app/controllers/controller.rb class Controller def initialize @view = View.new @my_batch = BurritoGenerator.new end def launch @view.show_welcome_page gets make_burrito end def make_burrito @my_batch.pick_ingredients @view.cooking_burrito @view.render_burrito(@my_batch.ingredient_list) save_burrito want_another end # def launch # @my_batch.pick_ingredients # @view.show_welcome_page # gets # @view.cooking_burrito # @view.render_burrito(@my_batch.ingredient_list) # decide # end def want_another input = @view.prompt_for_action if input != "exit" make_burrito else abort("Thanks for generating burritos!") end end # def another_burrito # @my_batch.pick_ingredients # @view.cooking_burrito # @view.render_burrito(@my_batch.ingredient_list) # decide # end def save_burrito @view.save? end end <file_sep>/burrito_gen/app/models/ingredient.rb class Ingredient < ActiveRecord::Base has_many :combinations has_many :burritos, through: :combinations end <file_sep>/burrito_gen/app/models/burrito_generator.rb # Input: burrito ingredient table # Output: randomly generated burrito.new # require_relative 'burrito' class BurritoGenerator attr_accessor :ingredient_list def initialize @valid_burrito = false # @ingredient_list = [] end def pick_ingredients new_ingredients = Ingredient.all.sample(7) @ingredient_list = new_ingredients.map(&:name) end def new_batch!(num_burritos = 1) num_burritos.times do ingredients = [] until @valid_burrito ingredients = pick_ingredients @valid_burrito = true end save_burrito(ingredients) end end # def substantive? # @ingredients.any?{|ingredient| ingredient.substantive == true} # end def save_burrito(ingredients) Burrito.create(ingredients) end end <file_sep>/burrito_gen/db/migrate/20150129184935_create_combinations.rb # require_relative '../../config/application.rb' class CreateCombinations < ActiveRecord::Migration def change create_table :combinations do |t| t.integer :burrito_id t.integer :ingredient_id t.timestamps end end end <file_sep>/burrito_gen/app/views/view.rb class View def cooking_burrito puts "We are cooking your burrito...." sleep(1) puts "Your burrito is ready!" sleep(0.5) end def save? puts "If you want to save your burrito please enter a name for it! Otherwise, please press \"enter\"." name = gets.chomp if name.length > 0 Burrito.create(name: name) end end # def save? # puts "do you want to save this burrito combination?" # input = gets.chomp # if input == "yes" # puts "Pick a name for your burrito!" # name = gets.chomp # end # end def prompt_for_action puts "Still hungry? Want another burrito? Press \"ENTER\" for another burrito or \"exit\"" input = gets.chomp end def display_all_saved_burritos Burrito.all.each do |burrito, index| puts "#{index + 1}. #{burrito.name}" end end def show_welcome_page format = <<-FORMAT ========================================================= Do you want to generate a burrito?!?!?! )--------------------( ) | | ( ) | ( ) ----- ( )_____________________( LETS GET STARTED!!!! PRESS ******ENTER******TO START ========================================================= FORMAT puts format end def render_burrito(ingredients) #array of ingredients # ingredients= %W{beef salsa onion cheese} format = <<-FORMAT )--------------------------------------------------------------------------------------------------------( ((((((((((())))))))))) X (((((((()))))))) ((((((((((())))))))))) X ((((((((((())))))))))) ((((((((((())))))))))) X ((((((((((())))))))))) ((((((((((())))))))))) X X ((((((((((())))))))))) X X )--------------------------------------------------------------------------------------------------------( FORMAT ingredients.each do |value| format=format.sub("X", value) #format=format.sub("X", value == 0? " ": value.to_s) end puts format end end <file_sep>/README.md # burrito_generator Use the Command Line Interface to generate random burritos from an ingredient database in Ruby! <file_sep>/burrito_gen/app/models/burrito.rb class Burrito < ActiveRecord::Base has_many :combinations has_many :ingredients, through: :combinations def total_calories total = 0 self.ingredients.each do |ingredient| total += ingredient.calories end return total end def vegan? self.ingredients.each do |ingredient| if ingredient.vegan == false return false end end return true end end <file_sep>/burrito_gen/db/ingredient_importer.rb require_relative '../app/models/ingredient' class IngredientImporter def self.import(filename = File.dirname(__FILE__) + "/seed_burrito_ingredients.csv") field_names = nil Ingredient.transaction do File.open(filename).each do |line| data = line.chomp.split(',') if field_names.nil? field_names = data else attribute_hash = Hash[field_names.zip(data)] ingredient = Ingredient.create!(attribute_hash) end end end end end IngredientImporter.import <file_sep>/burrito_gen/db/migrate/20150129184931_create_ingredients.rb # require_relative '../../config/application.rb' class CreateIngredients < ActiveRecord::Migration def change create_table :ingredients do |t| t.string :name t.boolean :vegan t.integer :calories t.boolean :substantive t.timestamps end end end <file_sep>/burrito_gen/db/migrate/20150129184930_create_burritos.rb # require_relative '../../config/application.rb' class CreateBurritos < ActiveRecord::Migration def change create_table :burritos do |t| t.string :name t.boolean :completely_vegan t.integer :total_calories t.timestamps end end end
d53e07190160be82ad35c42980040d436a25318c
[ "Markdown", "Ruby" ]
11
Ruby
adellhk/burrito_generator
61b7a7c7c9875d343cda2db918339aff516d445e
1f391138ff82fece22d612e262fe29b34283ea80
refs/heads/master
<repo_name>VodkaBears/wifideath<file_sep>/README.md # wifideath Shutdown Wi-Fi APs <file_sep>/wifideath.py #!/usr/bin/env python import sys import logging import scapy.all as scapy logging.getLogger('scapy.runtime').setLevel(logging.ERROR) def broadcast_flood(interface, bssid): packet = scapy.Dot11( addr1='ff:ff:ff:ff:ff:ff', addr2=bssid, addr3=bssid ) / scapy.Dot11Deauth() scapy.sendp(packet, iface=interface, loop=1, verbose=0) def main(): if len(sys.argv) != 3: print('%s <Interface> <BSSID>' % sys.argv[0]) sys.exit(1) print('Flooding is started...') broadcast_flood(sys.argv[1], sys.argv[2]) if __name__ == '__main__': main()
3b9742d9cd40458ddbc07328dacb49ab4ad65339
[ "Markdown", "Python" ]
2
Markdown
VodkaBears/wifideath
16a894ad3dd568a0236b385946eac43b334e1866
fd415692fe3788bd4917944247eee5c914ae5c02
refs/heads/master
<repo_name>FloreauLuca/SAE_4200_S1<file_sep>/Assets/Script/EndMenu.cs using System.Collections; using System.Collections.Generic; using TMPro; using UnityEngine; using UnityEngine.Playables; using UnityEngine.SceneManagement; public class EndMenu : MonoBehaviour { [SerializeField] private TextMeshProUGUI winText; [SerializeField] private PlayableDirector timeLineLoose; [SerializeField] private PlayableDirector timeLineWin; // Use this for initialization void Start () { if (GlobalGameManager.Instance.Win) { winText.text = "Win"; timeLineWin.Play(); } else { winText.text = "GameOver"; timeLineLoose.Play(); } } // Update is called once per frame void Update () { if (Input.GetButtonDown("Start")) { SceneManager.LoadScene("MenuStart"); } } } <file_sep>/Assets/Script/StartMenu.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Playables; using UnityEngine.SceneManagement; public class StartMenu : MonoBehaviour { [SerializeField] private PlayableDirector timeline; [SerializeField] private GameObject panel; // Use this for initialization void Start () { GlobalGameManager.Instance.Win = false; } // Update is called once per frame void Update () { if (Input.GetButtonDown("Start")) { panel.SetActive(false); timeline.Play(); Invoke("LoadScene", 1.6f); } } void LoadScene() { SceneManager.LoadScene("MainScene"); } } <file_sep>/Assets/Script/Cloud.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Cloud : MonoBehaviour { private float parallaxSpeed = 1; // Use this for initialization void Start () { } // Update is called once per frame void FixedUpdate () { transform.position = new Vector2(transform.position.x, transform.position.y + GameManager.Instance.Speed*parallaxSpeed); } public void SetParallaxSpeed (float size) { parallaxSpeed /= size; GetComponentInChildren<SpriteRenderer>().sortingOrder = 10- (int)size; } } <file_sep>/Assets/Script/Player.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Player : MonoBehaviour { enum Type { EXACT, INERTIE, VELOCITY } private Rigidbody2D rigidbody2D; [SerializeField] private float playerSpeed; [SerializeField] private bool type; [SerializeField] private float maxSpeed; [SerializeField] private float decreasevalue; [SerializeField] private int life; [SerializeField] private float hitCooldown; [SerializeField] private Type currentType; [SerializeField] private Sprite playerIdle; [SerializeField] private Sprite playerLeft; [SerializeField] private Sprite playerRight; [SerializeField] private Sprite playerUp; [SerializeField] private Sprite playerDown; private Animator animator; private AudioSource audioSource; // Use this for initialization void Start () { animator = GetComponent<Animator>(); rigidbody2D = GetComponent<Rigidbody2D>(); audioSource = GetComponent<AudioSource>(); } // Update is called once per frame void Update () { if (currentType == Type.EXACT) { float v = Input.GetAxis("Vertical"); Vector2 myVelocityY = Vector2.up; myVelocityY *= v * playerSpeed; float h = Input.GetAxis("Horizontal"); Vector2 myVelocityX = Vector2.right; myVelocityX *= h * playerSpeed; rigidbody2D.velocity = myVelocityX + myVelocityY; } if (currentType == Type.INERTIE) { float v = Input.GetAxis("Vertical"); if (v * rigidbody2D.velocity.y < maxSpeed) { rigidbody2D.AddForce(Vector2.up * v * playerSpeed); } float h = Input.GetAxis("Horizontal"); if (h * rigidbody2D.velocity.x < maxSpeed) { rigidbody2D.AddForce(Vector2.right * h * playerSpeed); } if (Mathf.Abs(rigidbody2D.velocity.y) > maxSpeed) { rigidbody2D.velocity = new Vector2(Mathf.Sign(rigidbody2D.velocity.x) * maxSpeed, Mathf.Sign(rigidbody2D.velocity.y) * maxSpeed); } if (Mathf.Abs(rigidbody2D.velocity.y) > maxSpeed) { while (rigidbody2D.velocity.y > 0.001 || rigidbody2D.velocity.y > 0.001 || rigidbody2D.velocity.y > 0.001 || rigidbody2D.velocity.y > 0.001) { float xdecrease = 0; float ydecrease = 0; if (rigidbody2D.velocity.x > 0) { xdecrease = -decreasevalue; } else { xdecrease = +decreasevalue; } if (rigidbody2D.velocity.y > 0) { ydecrease = -decreasevalue; } else { ydecrease = +decreasevalue; } rigidbody2D.velocity = new Vector2(rigidbody2D.velocity.x + xdecrease, rigidbody2D.velocity.y + ydecrease); } } } if (currentType == Type.VELOCITY) { float v = Input.GetAxis("Vertical"); Vector2 myVelocityY = Vector2.up; myVelocityY *= v * playerSpeed; float h = Input.GetAxis("Horizontal"); Vector2 myVelocityX = Vector2.right; myVelocityX *= h * playerSpeed; rigidbody2D.velocity += myVelocityX + myVelocityY; } if (Input.GetAxis("Vertical") > 0) { GetComponentInChildren<SpriteRenderer>().sprite = playerUp; } else if (Input.GetAxis("Vertical") < 0) { GetComponentInChildren<SpriteRenderer>().sprite = playerDown; } else if (Input.GetAxis("Horizontal") > 0) { GetComponentInChildren<SpriteRenderer>().sprite = playerRight; } else if (Input.GetAxis("Horizontal") < 0) { GetComponentInChildren<SpriteRenderer>().sprite = playerLeft; } else { GetComponentInChildren<SpriteRenderer>().sprite = playerIdle; } } public void Hit(int damage, AudioClip audio) { if (!animator.GetBool("HitCooldown")) { life -= damage; GameManager.Instance.SetUILife(life); audioSource.PlayOneShot(audio); if (life <= 0) { animator.SetTrigger("Death"); GlobalGameManager.Instance.Death(); } else { StartCoroutine(Animation("HitCooldown", hitCooldown)); } } } IEnumerator Animation(string animName, float time) { animator.SetBool(animName, true); yield return new WaitForSecondsRealtime(time); animator.SetBool(animName, false); } } <file_sep>/Assets/Script/Wall.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Wall : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void FixedUpdate () { GetComponent<Transform>().position = new Vector2(GetComponent<Transform>().position.x, GetComponent<Transform>().position.y + GameManager.Instance.Speed); } } <file_sep>/Assets/Script/SpawnWall.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class SpawnWall : MonoBehaviour { [SerializeField] private GameObject[] wallClassicPrefab; private GameObject currentWall; private GameObject nextWall; [SerializeField] private float startDelay; public float StartDelay { get { return startDelay; } set { startDelay = value; } } // Use this for initialization void Start() { StartCoroutine(SpawnDelay()); nextWall = wallClassicPrefab[Random.Range(0,wallClassicPrefab.Length)]; currentWall = Instantiate(nextWall, transform); } // Update is called once per frame void Update () { if (currentWall.transform.position.y >= nextWall.GetComponent<BoxCollider2D>().size.y/2+currentWall.GetComponent<BoxCollider2D>().size.y/2 + transform.position.y) { currentWall = Instantiate(nextWall, new Vector2(currentWall.transform.position.x, currentWall.transform.position.y - (nextWall.GetComponent<BoxCollider2D>().size.y / 2 + currentWall.GetComponent<BoxCollider2D>().size.y /2)), Quaternion.identity, transform); nextWall = wallClassicPrefab[Random.Range(0, wallClassicPrefab.Length)]; } } IEnumerator SpawnDelay() { yield return new WaitForSecondsRealtime(startDelay); while (true) { yield return new WaitForSecondsRealtime(GameManager.Instance.EnemyDelay); nextWall = GameManager.Instance.EnemyPrefab[Random.Range(0, GameManager.Instance.EnemyPrefab.Length)]; } } } <file_sep>/Assets/Script/Sky.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Sky : MonoBehaviour { // Use this for initialization void Start () { transform.localScale = new Vector2(transform.localScale.x, transform.localScale.y * ((GameManager.Instance.Speed/Time.fixedDeltaTime)*GameManager.Instance.EndTime)+transform.position.y + 5); } // Update is called once per frame void FixedUpdate () { transform.position = new Vector2(transform.position.x, transform.position.y + GameManager.Instance.Speed); } } <file_sep>/Assets/Script/EnemyScript/EnemyParent.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyParent : MonoBehaviour { [SerializeField] protected int damage; [SerializeField] protected AudioClip hitSound; // Use this for initialization protected void Start () { } // Update is called once per frame protected void Update () { } private void OnTriggerEnter2D(Collider2D other) { if (other.tag == "Player") { other.GetComponent<Player>().Hit(damage, hitSound); } } } <file_sep>/Assets/Script/GameManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class GameManager : MonoBehaviour { [SerializeField] private GameObject camera; public GameObject Camera { get { return camera; } set { camera = value; } } [SerializeField] private float speed = 1; public float Speed { get { return speed; } set { speed = value; } } [SerializeField] private GameObject[] enemyPrefab; public GameObject[] EnemyPrefab { get { return enemyPrefab; } set { enemyPrefab = value; } } [SerializeField] private float enemyDelay; public float EnemyDelay { get { return enemyDelay; } set { enemyDelay = value; } } [SerializeField] private bool paused = false; public bool Paused { get { return paused; } set { paused = value; } } [SerializeField] private GameObject[] lifeUI; public GameObject[] LifeUI { get { return lifeUI; } set { lifeUI = value; } } [SerializeField] private Sprite eggBreakSprite; [SerializeField] private GameObject cursorUI; public GameObject CursorUI { get { return cursorUI; } set { cursorUI = value; } } [SerializeField] private float endTime; public float EndTime { get { return endTime; } set { endTime = value; } } private float currentTime; [SerializeField] private GameObject pauseCanvas; private static GameManager instance; public static GameManager Instance { get { return instance; } } // Use this for initialization void Awake () { instance = this; GlobalGameManager.Instance.Win = false; } // Update is called once per frame void Update () { if (currentTime >= endTime) { GlobalGameManager.Instance.End(); } else if (!paused) { currentTime += Time.deltaTime; } if (currentTime % 1 <= 0.1) { SetCursor(); } if (Input.GetButtonDown("Pause")) { if (paused) { Time.timeScale = 1; paused = false; pauseCanvas.SetActive(false); } else { Time.timeScale = 0; paused = true; pauseCanvas.SetActive(true); } } } public void SetUILife(int life) { StartCoroutine(LooseLife(life)); } IEnumerator LooseLife(int life) { lifeUI[life].GetComponent<Image>().sprite = eggBreakSprite; yield return new WaitForSecondsRealtime(1); Destroy(lifeUI[life]); } public void SetCursor() { cursorUI.GetComponent<Slider>().value = currentTime / endTime; } } <file_sep>/Assets/Script/EnemyScript/Desk.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Desk : EnemyParent { [SerializeField] private float launchingSpeed; private float timeSinceSpawn; // Use this for initialization protected void Start() { base.Start(); timeSinceSpawn = 0; } // Update is called once per frame protected void Update() { base.Update(); GetComponent<Transform>().position = new Vector2(GetComponent<Transform>().position.x+(launchingSpeed* GetComponent<Transform>().lossyScale.x), GetComponent<Transform>().position.y); GetComponent<Transform>().position = new Vector2(GetComponent<Transform>().position.x, GetComponent<Transform>().position.y - timeSinceSpawn); timeSinceSpawn += Time.deltaTime; } } <file_sep>/Assets/Script/GlobalGameManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Audio; using UnityEngine.SceneManagement; public class GlobalGameManager : MonoBehaviour { private bool win = false; public bool Win { get { return win; } set { win = value; } } private AudioMixer audiomixer; private static GlobalGameManager instance; public static GlobalGameManager Instance { get { return instance; } } // Use this for initialization void Awake() { if (instance) { Destroy(gameObject); } else { instance = this; DontDestroyOnLoad(gameObject); } win = false; } // Update is called once per frame void Update () { } public void Death() { win = false; SceneManager.LoadScene("MenuEnd"); } public void End() { win = true; SceneManager.LoadScene("MenuEnd"); } } <file_sep>/Assets/Script/EnemyScript/DeskLauncher.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class DeskLauncher : EnemyParent { [SerializeField] private GameObject[] furniturePrefab; [SerializeField] private float launcherRate; // Use this for initialization void Start () { StartCoroutine(DeskLaunching()); } protected void Update() { base.Update(); } IEnumerator DeskLaunching() { while (gameObject) { yield return new WaitForSecondsRealtime(launcherRate); Instantiate(furniturePrefab[Random.Range(0, furniturePrefab.Length)], transform); } } } <file_sep>/Assets/Script/CloudSpawner.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class CloudSpawner : MonoBehaviour { [SerializeField] private GameObject[] cloudPrefab; [SerializeField] private float cloudDelay; // Use this for initialization void Start () { StartCoroutine(SpawnDelay()); } // Update is called once per frame void Update () { } IEnumerator SpawnDelay() { while (true) { yield return new WaitForSecondsRealtime(cloudDelay); GameObject newCloud = Instantiate(cloudPrefab[Random.Range(0, cloudPrefab.Length)], new Vector2(Random.Range(-5, 5), transform.position.y), Quaternion.identity, transform); float size = Random.Range(1, 5); newCloud.transform.localScale = new Vector3(size, size); newCloud.GetComponent<Cloud>().SetParallaxSpeed(size); } } }
ea3893f29251b0ab15d8cf543b62db9e39d873c8
[ "C#" ]
13
C#
FloreauLuca/SAE_4200_S1
ef1b38cdbdb636fff742da7d27c9a98d28b70bf8
be5d7840c1b3b78ad355d2f53d2b2e525a1e4e48
refs/heads/master
<file_sep><?php $term = $_GET["term"]; $con = mysqli_connect('localhost','root','kone5566','literatures'); if (!$con) { die('Could not connect: ' . mysqli_error($con)); } /*-------------search term in Term-Table-------------*/ mysqli_select_db($con,"term"); $sql = "SELECT * FROM term WHERE term = '$term'"; $sqlRes = mysqli_query($con, $sql); while ( $row = mysqli_fetch_array($sqlRes)) { //echo $row['content']; echo "<div class="."panel panel-default".">"; echo "<div class="."panel-heading".">"; echo $term; echo "<button class="."editTerm".">編輯</button>"; echo "</div>"; echo "<div class="."panel-body".">"; echo $row['content']; echo "</div>"; echo "</div>"; } ?><file_sep><?php include("TTOC.php"); ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <?php set_time_limit(0); $con = mysqli_connect('localhost','root','kone5566','literatures'); if (!$con) { die('Could not connect: ' . mysqli_error($con)); } mysqli_select_db($con,"term"); $sql = "SELECT * FROM term WHERE '1'"; $result = mysqli_query($con,$sql); $i = 0; while($row = mysqli_fetch_array($result)) { $i++; $termgref = $row['guid']; $urlinput = urlencode($row['term']); echo "------------------------------------------------------------"; echo "</br>"; $mystring = system("python crawler_wiki.py $urlinput", $retval); echo "</br>"; echo "------------------------------------------------------------"; echo "</br>"; $mystring = strip_tags($mystring); $mystring = json_decode("\"".$mystring."\""); $termContentRef = substr($mystring,-2); $mystring = substr($mystring, 0, strlen($mystring)-2); echo $row['term']; echo "</br>"; //echo $mystring; $utf8_chinese_str = new utf8_chinese; $mystring = $utf8_chinese_str->gb2312_big5($mystring); echo $mystring; echo "</br>"; echo $termContentRef; echo "</br>"; $secsql="UPDATE term SET content='$mystring',contentref='$termContentRef' WHERE guid='$termgref'"; mysqli_query($con,$secsql); } ?> <body><file_sep><!DOCTYPE html> <html> <head> </head> <script type="text/javascript"> function checkResult() { var xmlhttp; if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }v xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("txtHint").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","checkResult.php?t="+ Math.random(),true); xmlhttp.send(); } </script> <body> <?php $urlinput = urlencode('魏延'); //system("python crawler_wiki.py https://zh.wikipedia.org/wiki/$urlinput> /tmp/null &"); //system("python crawler_wiki.py https://zh.wikipedia.org/wiki/$urlinput>> tmp.txt &"); //$mystring = system("python crawler_wiki.py https://zh.wikipedia.org/wiki/$urlinput", $retval); //wiki $mystring = system("python crawler_wiki.py $urlinput"); //taiwan wiki echo "</br>"; echo "</br>"; $mystring = strip_tags($mystring); if (empty($mystring)) echo "empty"; else { // $mystring = '"\u4e9b\u7c97\u7b28\u7684\u751f\u6d3b\u3002"'; //echo $mystring; $mystring = "\"".$mystring."\""; echo json_decode($mystring); } ?> ... <p id='txtHint'> ... <script> //checkResult(); </script> </body> <html><file_sep># -*- coding: UTF-8 -*- import sys option = sys.argv[1]# 取出sys.argv[1]的數值但是忽略掉'--'這兩個字元 print option sys.exit() <file_sep><?php include("TTOC.php"); ?> <?php set_time_limit(0); $book = $_GET['book']; $cag = $_GET['cag']; $term = $_GET['term']; $isNew = $_GET['new']; $log = ""; //echo $term; $termArray = explode("@",$term); //------------------------------------------------- $con = mysqli_connect('localhost','root','kone5566','literatures'); if (!$con) { die('Could not connect: ' . mysqli_error($con)); } //------------------------------------------------- echo "<div id="."txtHint"." class = "."txtHint panel panel-default"."><div class="."panel-body".">"; if ( $isNew == '1' ) { mysqli_select_db($con,"termindex"); //get guid------------------------------------------------------- $gusql = "SELECT uuid();"; $guidresult = mysqli_query($con,$gusql); while ($gurow = $guidresult->fetch_assoc()) { $newCagGuid = $gurow['uuid()']; } $newCagGuid= strtoupper($newCagGuid); //----------------------------------------------------------------- $comsql = "SELECT * FROM termindex WHERE class='$cag' AND bookgref = '$book';"; $comresult = mysqli_query($con, $comsql); if ( mysqli_num_rows($comresult) == 1 ) { echo "類別 重複新增"; $isNew = 0; } else { $bookName = ""; $findBookSql = "SELECT * FROM termindex WHERE bookgref = '$book';"; $findBookRes = mysqli_query($con, $findBookSql); while($row = mysqli_fetch_array($findBookRes)) { $bookName = $row['booktitle']; echo $bookName; } $sql = "INSERT INTO termindex (guid,bookgref,booktitle,class) VALUES ('".$newCagGuid."','".$book."','".$bookName."','".$cag."');"; mysqli_query($con,$sql)or die ("無法新增".mysql_error()); } $cagRegularSql = "SELECT * FROM termindex WHERE class = '$cag' AND bookgref = '$book';"; $cagRegularRes = mysqli_query($con,$cagRegularSql); echo $cag; while($row = mysqli_fetch_array($cagRegularRes)) { $cag = $row['guid']; echo "</br>"; //echo $cag; echo "</br>"; } } foreach($termArray as $term) { if ($term == "") { continue; } //------------------------------------------------- mysqli_select_db($con,"term"); //get guid------------------------------------------------------- $gusql = "SELECT uuid();"; $guidresult = mysqli_query($con,$gusql); while ( $gurow = $guidresult -> fetch_assoc() ) { $guid = $gurow['uuid()']; } $guid = strtoupper($guid); //--------------------------------------------------------------- $comsql = "SELECT * FROM term WHERE termindexgref='$cag' AND term = '$term';"; $comresult = mysqli_query($con, $comsql); if ( mysqli_num_rows($comresult) == 1 ) { echo $term." 重複新增"."</br>"; } else { $sql = "INSERT INTO term (guid,termindexgref,term) VALUES ('".$guid."','".$cag."','".$term."');"; mysqli_query($con,$sql)or die ("無法新增".mysql_error()); //---------------------------------------------------------------------------------------------- $termgref = $guid; $urlinput = urlencode($term); //echo "------------------------------------------------------------"; //echo "</br>"; $mystring = system("python crawler_wiki.py $urlinput", $retval); //echo "</br>"; //echo "------------------------------------------------------------"; //echo "</br>"; $mystring = strip_tags($mystring); $mystring = json_decode("\"".$mystring."\""); $termContentRef = substr($mystring,-2); $mystring = substr($mystring, 0, strlen($mystring)-2); //echo $row['term']; //echo "</br>"; //echo $mystring; $utf8_chinese_str = new utf8_chinese; $mystring = $utf8_chinese_str->gb2312_big5($mystring); $secsql="UPDATE term SET content='$mystring',contentref='$termContentRef' WHERE guid='$termgref'"; mysqli_query($con,$secsql); //---------------------------------------------------------------------------------------------- //新增段詞統計表(Phterm)------------------------------------------------------------------------ $newsql="SELECT guid,ROUND((CHAR_LENGTH(realtext)-CHAR_LENGTH(Replace(realtext,'".$term."','')))/(".strlen($term)."/3)) AS count FROM paragraph where bookgref = '$book' AND realtext LIKE '%".$term."%';"; $result=mysqli_query($con,$newsql); mysqli_select_db($con,"phterm"); while ($row = $result->fetch_assoc()) { //get guid $gusql = "SELECT uuid();"; $guidresult = mysqli_query($con,$gusql); while ($gurow = $guidresult->fetch_assoc()) { $guid = $gurow['uuid()']; } $guid = strtoupper($guid); //insert data to phterm $sql="INSERT INTO phterm (guid,phgref,termgref,count) VALUES ('".$guid."','".$row['guid']."','".$termgref."','".$row['count']."');"; //echo $row['count']; mysqli_query($con,$sql)or die ("無法新增".mysql_error()); } //---------------------------------------------------------------------------------------------- echo $term." 新增成功"."</br>"; } } echo "</div></div>"; ?><file_sep><!DOCTYPE html> <html> <head> <script language="javascript" type="text/javascript"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <link rel = "stylesheet" type="text/css" href="termadd.css"> <script> inputstring = ""; newflag = 0; window.onload = function() { document.getElementById('myfile').onchange = readFile; document.getElementById("test").onclick = function fun() { var cag = document.getElementById("termcategory").value; var book = document.getElementById("bookname").value; alert( book + "\n" + cag + "\n" + newflag ); } } function readFile() { file = this.files[0]; var fReader = new FileReader(); fReader.onload = function(event){ document.getElementById('fileContent').value = event.target.result; inputstring = event.target.result; }; fReader.readAsText(file); } function showtext() { var splitStr = inputstring.split("\r\n"); var outPutTermArray=""; //var splitStr = inputstring; if (newflag == 0) { var cag = document.getElementById("termcategory").value; } if (newflag == 1) { var cag = document.getElementById('other').value; } var book = document.getElementById("bookname").value; for ( i = 0; i < splitStr.length; i++ ) { if (splitStr[i] != "") { outPutTermArray+=splitStr[i]; outPutTermArray+='@'; } } //------------------------------------------------------------ if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { document.getElementById("txtHint").innerHTML = xmlhttp.responseText; } }; xmlhttp.open("GET","insertTerm.php?term="+outPutTermArray+"&cag="+cag+"&book="+book+"&new="+newflag,true); xmlhttp.send(); //------------------------------------------------------------ // } //} } function check(val) { if (val == "其他") { document.getElementById('other').style.display='block'; newflag = 1; } else { document.getElementById('other').style.display='none'; newflag = 0; } } function renew(value) { id_numbers = new Array(); $.ajax ({ url:'selectcategory.php', data:{bookguid:value}, type :'POST', success:function(response) { id_numbers = response; id_numbers = JSON.parse(id_numbers); var newOptions = {}; for (var j = 0; j < id_numbers.length; j+=2 ) { newOptions[id_numbers[j]] = id_numbers[j+1]; } var $el = $("#termcategory"); $el.empty(); // remove old options $.each(newOptions, function(key,value) { $el.append($("<option></option>") .attr("value", value).text(key)); }); $el.append($("<option></option>").attr("其他", "其他").text("其他")); } }); } </script> </head> <body> <div class="index-top"> <?php if (isset($_SESSION['username'])): ?> <p>Welcome&nbsp <strong><?php echo $_SESSION['username'];?> [<?php echo $_SESSION['access']?>]</strong> <button type="button" class="log-btn" style="width:60px;height:40px;" id="bt5"> 登出 </button> </p> <?php endif ?> </div> <div class = "centerContent"> <div id = "inputArea" class="inputArea panel panel-default"> <p>書名:</p><?php include("selectsql.php"); ?><br/><br/> <p>類別:</p><select id = "termcategory" onchange='check(this.value)'></select><br/><br/> <input type="text" name="other" id="other" style='display:none'/><br/> <!--<button id = "test" type = "submit">測</button>--> <p><input id='myfile' type="file"/></p><br/><br/> <textarea id="fileContent" cols="30" rows="10"></textarea><br/> <button onclick="showtext()">上傳資料</button> </div> <div id="txtHint"></div> </div> </body> </html><file_sep><?php include('server.php'); if(empty($_SESSION['username'])) { header('location: login.php'); } ?> <!DOCTYPE html> <html> <title>同位詞大典</title> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <script language="Javascript" ></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script src="js/bootstrap.min.js"></script> <script src="js/bootstrap.js"></script> <link href="css/bootstrap-theme.css" rel="stylesheet"> <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <link rel = "stylesheet" type="text/css" href="style.css"> <script> window.onload = function() { document.getElementById("bt1").onclick = function() { window.location.href = 'ftsdemo.php'; } document.getElementById("bt2").onclick = function() { window.location.href = 'uploadterm.php'; } document.getElementById("bt3").onclick = function() { window.location.href = 'phterm.php'; } document.getElementById("bt4").onclick = function() { window.location.href = 'termsearch.php'; } document.getElementById("bt5").onclick = function() { window.location.href = "index.php?logout=1"; } } </script> </head> <body> <div class="index-top"> <?php if (isset($_SESSION['username'])): ?> <p>Welcome&nbsp <strong><?php echo $_SESSION['username'];?> [<?php echo $_SESSION['access']?>]</strong> <button type="button" class="btn" style="width:60px;height:40px;" id="bt5"> 登出 </button> </p> <?php endif ?> </div> <div class= "index-middle"> <div class= "index-left"> <p> <button type="button" class="index-btn btn btn-lg btn-Primary" style="width:140px;height:50px;" id="bt1"> <span style="font-family:Microsoft JhengHei;color:white;font-size:0.7cm;">全文檢索</span> </button> </p> <p> <button type="button" class="index-btn btn btn-lg btn-Primary" style="width:140px;height:50px;" id="bt2"> <span style="font-family:Microsoft JhengHei;color:white;font-size:0.7cm;">字詞上傳</span> </button> </p> <p> <button type="button" class="index-btn btn btn-lg btn-Primary" style="width:140px;height:50px;" id="bt3"> <span style="font-family:Microsoft JhengHei;color:white;font-size:0.7cm;">段詞輸入</span> </button> </p> <p> <button type="button" class="index-btn btn btn-lg btn-Primary" style="width:140px;height:50px;" id="bt4"> <span style="font-family:Microsoft JhengHei;color:white;font-size:0.7cm;">字詞搜尋</span> </button> </p> </div> <div class="index-center"> <div class="index-header header"> <h2>同位詞大典</h2> </div> <div class="index-content content"> <?php if (isset($_SESSION['success'])): ?> <div class="error success"> <h3> <p class="message"> <?php echo $_SESSION['success']; unset($_SESSION['success']); ?> </p> </h3> </div> <?php endif ?> </div> </div> </div> </body> </html><file_sep><?php //------------------------------------------------- $option_title = []; $option_guid = []; //------------------------------------------------- $con = mysqli_connect('localhost','root','kone5566','literatures'); if (!$con) { die('Could not connect: ' . mysqli_error($con)); } //------------------------------------------------- array_push($option_title,"請選擇"); array_push($option_guid,""); mysqli_select_db($con,"book"); $sql = "SELECT title,guid FROM book"; $result = mysqli_query($con, $sql); while($row = mysqli_fetch_array($result)) { array_push($option_title,$row['title']); array_push($option_guid,$row['guid']); } echo "<select id = "."bookname"." onChange=renew(this.value);>"; for ($i = 0; $i < sizeof($option_title); $i++ ) { echo "<option value = $option_guid[$i]>$option_title[$i]</option>"; } echo "</select>"; ?><file_sep><?php $con = mysqli_connect('localhost','root','kone5566','literatures'); if (!$con) { die('Could not connect: ' . mysqli_error($con)); } //------------------------------------------------- if (isset($_GET['uni_term'])) { $keyword_set = mysqli_real_escape_string($con, $_GET['uni_term']); mysqli_select_db($con,"paragraph"); $keyword_set = str_replace ("+","",$keyword_set); $arrays = explode("20",$keyword_set); array_filter($arrays); $sqls = "SELECT *,Match(unitext) AGAINST ('$keyword_set' IN BOOLEAN MODE) from paragraph WHERE"; for($i = 0; $i < sizeof($arrays); $i++) { if ($arrays[$i] == " ")continue; $arrays[$i] = trim($arrays[$i]); if (preg_match("/ 7c /", $arrays[$i])) { $orArrays = explode("7c", $arrays[$i]); if ($i == 0) { for ( $j = 0; $j < sizeof($orArrays); $j++ ) { if ($j == 0) $sqls = $sqls." ((unitext) LIKE '%$orArrays[0]%'"; else $sqls = $sqls." OR (unitext) LIKE '%$orArrays[1]%'"; } $sqls = $sqls.")"; } else { for ( $j = 0; $j < sizeof($orArrays); $j++ ) { if ($j == 0) $sqls = $sqls." AND ((unitext) LIKE '%$orArrays[0]%'"; else $sqls = $sqls." OR (unitext) LIKE '%$orArrays[1]%'"; } $sqls = $sqls.")"; } } else if (substr($arrays[$i],0,2) == "2d") { $noterm = substr($arrays[$i],3,sizeof($arrays[$i])-3); if ($i == 0) $sqls = $sqls." (unitext) NOT LIKE '%$noterm%'"; else $sqls = $sqls." AND (unitext) NOT LIKE '%$noterm%'"; } else { if ($i == 0) $sqls = $sqls." (unitext) LIKE '%$arrays[$i]%'"; else $sqls = $sqls." AND (unitext) LIKE '%$arrays[$i]%'"; } } //-------------------------------------------------- $result = mysqli_query($con,$sqls); $paragraph_output_array = array(); while($row = mysqli_fetch_array($result)) { mysqli_select_db($con,"book"); $bookid = $row['bookgref']; $sql="SELECT title FROM book WHERE guid = '".$row['bookgref']."';"; $titleFind = mysqli_query($con,$sql); $title=""; while($titleInTableResult = mysqli_fetch_array($titleFind)) { $title = $titleInTableResult['title']; //data 1 } $paragraph_chapter = $row['chapter']; //data 2 $paragraph_graf = $row['bookgref']; //data 3 $paragraph_text = $row['realtext']; //data 4 $element_in_output_arr = array( 'title' => $title, 'chapter' => $paragraph_chapter, 'text' => $paragraph_text ); array_push($paragraph_output_array, $element_in_output_arr); } echo json_encode($paragraph_output_array); } if (isset($_GET['get_phterm_count'])) { echo "OK"; } //$ptsql="SELECT guid FROM paragraph WHERE MATCH(unitext) AGAINST('".$q."'IN BOOLEAN MODE);"; $ptsql = $sqls; $ptresult = mysqli_query($con,$ptsql); $c=mysqli_num_rows($ptresult); mysqli_select_db($con,"phterm"); $findptsql = "SELECT termgref,count,guid, sum(count) as count FROM phterm WHERE"; //select guid,termgref, sum(count) as count from phterm group by termgref while($row = mysqli_fetch_array($ptresult)) { $c-=1; $findptsql=$findptsql." phgref='".$row['guid']."'"; if($c!=0) $findptsql=$findptsql." OR"; } $findptsql=$findptsql." group by termgref ORDER BY count DESC;"; $findptresult=mysqli_query($con,$findptsql); /* echo "<div>"; echo "<ul class='nav nav-tabs'>"; echo "<li class="."active"."><a data-toggle="."tab"." href="."#home".">總覽</a></li>"; echo "<li><a data-toggle="."tab"." href="."#menu1".">人名</a></li>"; echo "<li><a data-toggle="."tab"." href="."#menu2".">地名</a></li>"; echo "<li><a data-toggle="."tab"." href="."#menu3".">其他</a></li>"; echo "</ul>"; echo "<div class="."tab-content".">"; echo "<div id="."home"." class='tab-pane fade in active'>"; //echo "<h3>HOME</h3>"; echo "<table style='"."text-align:center;width:100%;float:right;border:2px #D9D9D9 solid;background-color:#FFFFFF;"."'>"; echo "<tr>"; echo "<th style='"."width:60%;border:2px #D9D9D9 solid;text-align:center;"."'>詞</th>";/*Realtext echo "<th style='"."width:40%;border:2px #D9D9D9 solid;text-align:center;"."'>次數</th>";/*Score echo "</tr>"; */ /* $character = array(); $character_count = array(); $local = array(); $local_count = array(); $other = array(); $other_count = array(); while($row = mysqli_fetch_array($findptresult)) { $realterm = ""; mysqli_select_db($con,"term"); $findterm = "SELECT term,termindexgref FROM term WHERE guid='".$row['termgref']."';"; $termresult = mysqli_query($con,$findterm); $classgerf =" "; while ($trow = mysqli_fetch_array($termresult)) { $realterm = $trow['term']; $classgerf = $trow['termindexgref']; } /* echo "<tr style='"."width:60%;border:2px #D9D9D9 solid;"."'>"; echo "<td style='"."width:20%;border:2px #D9D9D9 solid;"."'> <a id="."termA"." href="."#"." onclick="."termAdd('".$realterm."');return false;".">"."+"."</a> <a id="."termA"." href="."#"." onclick="."newTerm('".$realterm."');return false;".">"."$realterm"."</a> <a id="."termA"." href="."#"." onclick="."termAdd('-".$realterm."');return false;".">"."-"."</a> </td>"; echo "<td style='"."width:60%;border:2px #D9D9D9 solid;"."'>" . $row['count'] . "</td>"; echo "</tr>"; */ /* mysqli_select_db($con,"termindex"); $findclass = "SELECT class FROM termindex WHERE guid='".$classgerf."';"; $classresult = mysqli_query($con,$findclass); while($crow = mysqli_fetch_array($classresult)) { if( $crow['class'] == "人名") { array_push($character, $realterm); array_push($character_count, $row['count']); } else if( $crow['class'] == "地名") { array_push($local, $realterm); array_push($local_count, $row['count']); } else { array_push($other, $realterm); array_push($other_count, $row['count']); } } } /* echo "</table>"; echo "</div>"; echo "<div id="."menu1"." class='tab-pane fade'>"; echo "<table style='"."text-align:center;width:100%;border:2px #D9D9D9 solid;background-color:#FFFFFF;"."'>"; echo "<tr>"; echo "<th style='"."width:60%;border:2px #D9D9D9 solid;text-align:center;"."'>詞</th>";/*Realtext echo "<th style='"."width:40%;border:2px #D9D9D9 solid;text-align:center;"."'>次數</th>";/*Score echo "</tr>"; */ /* for($x = 0;$x<sizeof($character);$x++){ $partition[0] = $character[$x]; $partition[1] = $character_count[$x]; echo "<tr style='"."width:60%;border:2px #D9D9D9 solid;"."'>"; echo "<td style='"."width:20%;border:2px #D9D9D9 solid;"."'> <a id="."termA"." href="."#"." onclick="."termAdd('".$partition[0]."');return false;".">"."+"."</a> <a id="."termA"." href="."#"." onclick="."newTerm('".$partition[0]."');return false;".">".$partition[0]."</a> <a id="."termA"." href="."#"." onclick="."termAdd('-".$realterm."');return false;".">"."-"."</a> </td>"; echo "<td style='"."width:20%;border:2px #D9D9D9 solid;"."'>".$partition[1]."</td>"; echo "</tr>"; } echo "</table>"; echo "</div>"; echo "<div id="."menu2"." class='tab-pane fade'>"; echo "<table style='"."text-align:center;width:100%;border:2px #D9D9D9 solid;background-color:#FFFFFF;"."'>"; echo "<tr>"; echo "<th style='"."width:60%;border:2px #D9D9D9 solid;text-align:center;"."'>詞</th>";/*Realtext echo "<th style='"."width:40%;border:2px #D9D9D9 solid;text-align:center;"."'>次數</th>";/*Score echo "</tr>"; */ /* for($x = 0;$x<sizeof($local);$x++) { $partition[0] = $local[$x]; $partition[1] = $local_count[$x]; echo "<tr style='"."width:60%;border:2px #D9D9D9 solid;"."'>"; echo "<td style='"."width:20%;border:2px #D9D9D9 solid;"."'> <a id="."termA"." href="."#"." onclick="."termAdd('".$partition[0]."');return false;".">"."+"."</a> <a id="."termA"." href="."#"." onclick="."newTerm('".$partition[0]."');return false;".">".$partition[0]."</a> <a id="."termA"." href="."#"." onclick="."termAdd('-".$realterm."');return false;".">"."-"."</a> </td>"; echo "<td style='"."width:20%;border:2px #D9D9D9 solid;"."'>".$partition[1]."</td>"; echo "</tr>"; } echo "</table>"; echo "</div>"; echo "<div id="."menu3"." class='tab-pane fade'>"; echo "<table style='"."text-align:center;width:100%;border:2px #D9D9D9 solid;background-color:#FFFFFF;"."'>"; echo "<tr>"; echo "<th style='"."width:60%;border:2px #D9D9D9 solid;text-align:center;"."'>詞</th>";/*Realtext echo "<th style='"."width:40%;border:2px #D9D9D9 solid;text-align:center;"."'>次數</th>";/*Score echo "</tr>"; for($x = 0;$x<sizeof($other);$x++) { $partition[0] = $other[$x]; $partition[1] = $other_count[$x]; echo "<tr style='"."width:60%;border:2px #D9D9D9 solid;"."'>"; echo "<td style='"."width:20%;border:2px #D9D9D9 solid;"."'> <a id="."termA"." href="."#"." onclick="."termAdd('".$partition[0]."');return false;".">"."+"."</a> <a id="."termA"." href="."#"." onclick="."newTerm('".$partition[0]."');return false;".">".$partition[0]."</a> <a id="."termA"." href="."#"." onclick="."termAdd('-".$realterm."');return false;".">"."-"."</a> </td>"; echo "<td style='"."width:20%;border:2px #D9D9D9 solid;"."'>".$partition[1]."</td>"; echo "</tr>"; } echo "</table>"; echo "</div>"; echo "</div>"; echo "</div>"; //---------------------------------------------------------- echo "</div>"; */ mysqli_close($con); ?><file_sep><?php include('server.php'); if(empty($_SESSION['username'])) { header('location: login.php'); } ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script language="javascript" type="text/javascript"></script> <link rel = "stylesheet" type="text/css" href="getresult.css"> <script type="text/javascript" src="https://code.jquery.com/jquery-latest.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <script> function getTextSearchResult(str) { document.getElementById('txtHint').innerHTML = ""; unicode = str; $.ajax ({ url:'fulltextsearch/getresult.php', data:{uni_term:unicode}, dataType: "json", type :'GET', success:function(response) { var htmls = []; for (key in response) { htmls.push('<div class="panel panel-default">'); htmls.push('<div class="panel-heading">' + response[key]['title']); htmls.push('<a href="#" onclick = "chapterSearch(\''+ response[key]['chapter'] +'\',\''+ response[key]['bookid'] +'\')">' + response[key]['chapter'] + '</a>'); htmls.push('</div>'); htmls.push('<div class="panel-body">' + response[key]['text'] + '</div>'); htmls.push('</div>'); } document.getElementById('txtHint').innerHTML = htmls.join(''); } }); } function getPhtermCountTable(str) { document.getElementById('phtermTable').innerHTML = ""; unicode = str; $.ajax ({ url:'fulltextsearch/getphtermcount.php', data:{get_phterm_count:unicode}, dataType: "json", type :'GET', success:function(response) { var html = []; html.push('<ul class="nav nav-tabs">'); html.push('<li class="active"><a data-toggle="tab" href="#home">總覽</a></li>'); html.push('<li><a data-toggle="tab" href="#menu1">人名</a></li>'); html.push('<li><a data-toggle="tab" href="#menu2">地名</a></li>'); html.push('<li><a data-toggle="tab" href="#menu3">其他</a></li>'); html.push('</ul>'); html.push('<div class="tab-content">'); for (key in response) { if ( key == "total" ) { html.push('<div id="home" class="tab-pane fade in active">'); } else if ( key == "character") { html.push('<div id="menu1" class="tab-pane fade">'); } else if ( key == "local") { html.push('<div id="menu2" class="tab-pane fade">'); } else if ( key == "other") { html.push('<div id="menu3" class="tab-pane fade">'); } html.push('<table style="text-align:center;width:100%;float:right;border:2px #D9D9D9 solid;background-color:#FFFFFF;">'); html.push('<tr>'); html.push('<th style="border:2px #D9D9D9 solid;text-align:center;">詞</th>'); html.push('<th style="border:2px #D9D9D9 solid;text-align:center;">次數</th>'); html.push('</tr>'); for ( keys in response[key]) { name = response[key][keys]['name']; html.push('<tr style="border:2px #D9D9D9 solid;">'); html.push('<td>'); html.push('<a id="termA" href="#" onclick="termAdd(\''+ name +'\')";return false;">'+ "+" +'</a>'); html.push('<a id="termA" href="#" onclick="newTerm(\''+ name +'\')";return false;">'+ name +'</a>'); html.push('<a id="termA" href="#" onclick="termAdd(\'-'+ name +'\')";return false;">'+ "-" +'</a>'); html.push('</td>'); html.push('<td style="border:2px #D9D9D9 solid;">' + response[key][keys]['count'] + '</td>'); html.push('</tr>'); } html.push('</table>'); html.push('</div>'); } html.push('</div>'); document.getElementById('phtermTable').innerHTML = html.join(''); } }); } function geturl() { //URL var url = location.href; //取得問號之後的值 var temp = url.split("?"); //將值再度分開 var vars = temp[1].split("&"); //一一顯示出來 for (var i = 0; i < vars.length; i++) { var res = decodeURI(vars[i]).split("="); document.getElementById("keyword").value = res[1]; } showUser(); } function showUser() { var str=encodeURIComponent(document.getElementById("keyword").value); str=document.getElementById("keyword").value; var unicode=""; for(var i=0;i<str.length;i++) { unicode+="+"+parseInt(str[i].charCodeAt(0),10).toString(16)+" "; } getTextSearchResult(unicode); getPhtermCountTable(unicode); } window.onload = function() { document.getElementById("Save").onclick = function fun() { showUser(); } document.getElementById("bt5").onclick = function() { window.location.href = "index.php?logout=1"; } } </script> <script> function chapterSearch(chapter,bookid){ var chapter1 = (chapter.split("-"))[0]; var chapter2 = (chapter.split("-"))[1]; var bookguid = bookid; open('showchapter.php?chapter='+chapter1+'&pharagraph='+chapter2+'&bookid='+bookguid+"#target",'_blank', 'result', config='height=600,width=600'); } function termAdd(term){ document.getElementById("keyword").value= document.getElementById("keyword").value + " " + term; showUser(); } function newTerm(term){ document.getElementById("keyword").value = term; showUser(); } </script> </head> <body> <div class="index-top"> <?php if (isset($_SESSION['username'])): ?> <p>Welcome&nbsp <strong><?php echo $_SESSION['username'];?> [<?php echo $_SESSION['access']?>]</strong> <button type="button" class="log-btn" style="width:60px;height:40px;" id="bt5"> 登出 </button> </p> <?php endif ?> </div> <div class="searchbar"> <table> <tr> <td> <div class="search"><input type="text" id="keyword" name="keyword" style="font-size:30px;width:600px;"></div> </td> <td> <div class="btn"><input type="submit" class="btn btn-primary" id="Save" name="Save" value="檢索" style="font-size:0.6cm;"></div> </td> </tr> </table> </div> <div id="phtermTable" class="phtermTable"></div> <div id="txtHint" class = "container" style="width:50%"></div> </body> </html><file_sep> # coding: utf-8 # -*- coding: utf-8 -*- import re import sys from bs4 import BeautifulSoup import requests def cleanhtml(raw_html): cleanr = re.compile('<[^<]+?>') cleantext = re.sub(cleanr,'', raw_html) return cleantext #$mystring = system("python crawler_wiki.py https://zh.wikipedia.org/wiki/$urlinput", $retval); //wiki #$mystring = system("python crawler_wiki.py http://www.twwiki.com/wiki/$urlinput", $retval); //taiwan wiki wikiPediaUrl = "https://zh.wikipedia.org/wiki/"; taiwanWikiUrl = "http://www.twwiki.com/wiki/"; taiwanWordUrl = "http://www.twword.com/wiki/"; termUrl = sys.argv[1]; wikiPediaUrl += termUrl; taiwanWikiUrl += termUrl; taiwanWordUrl += termUrl; WikiPediaRes = requests.get(wikiPediaUrl); taiwanWikiRes = requests.get(taiwanWikiUrl); taiwanWordRes = requests.get(taiwanWordUrl); #-----------------------------------------wikipedia WPediaSoup = BeautifulSoup(WikiPediaRes.text,'html5lib'); termContent = WPediaSoup.p.encode('utf-8') termContent = str(termContent); termContent = cleanhtml(termContent); termContent = termContent.strip(); if termContent != "": print (termContent+"WP"); else: #-----------------------------------------Taiwan wiki TWikiSoup = BeautifulSoup(taiwanWikiRes.text,'html5lib') termContent = TWikiSoup.find_all('p',{'class':'mb10'}) termContent = str(termContent); termContent = cleanhtml(termContent); termContent = termContent.replace("[",""); termContent = termContent.replace("]",""); termContent = termContent.strip(); if termContent != "": print (termContent+"TW"); else: termContent = TWikiSoup.find_all('div',{'class':'mb15'}) termContent = str(termContent); termContent = cleanhtml(termContent); termContent = termContent.replace("\\xa0",""); termContent = termContent.replace("[",""); termContent = termContent.replace("]",""); if termContent !="": print(termContent+"TW"); #else: #-----------------------------------------Taiwan word #print ("to do"); #TWordSoup = BeautifulSoup(taiwanWordRes.text,'html5lib') #----------------------------------------- #print(s); #f = open('res.txt','a') #f.write(str)<file_sep><?php $timeflag = True; while($timeflag) { sleep(3); if (file_exists("tmp.txt")) { $timeflag = False; $response = "Success!!!"; break; } } echo $response; ?><file_sep><?php if (empty($_SESSION['username'])){ header('location: login.php'); } ?> <html> <title>段詞輸入</title> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <script language="Javascript" ></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script src="js/bootstrap.min.js"></script> <script src="js/bootstrap.js"></script> <link href="css/bootstrap-theme.css" rel="stylesheet"> <style type="text/css"> body { margin: 15px; background-color: #E8FFE8; } .form{ position: absolute; left: 25%; top: 20%; } .line{ border:2px #D9D9D9 solid; text-align: 10px; font-family:Microsoft JhengHei; background-color: #F2FFF2; width: 600px; height: 600px; } .font{ font-family:Microsoft JhengHei; text-align: 10px; } .BOX{ position: absolute; left: 65%; top: 20%; } .btn{ position: absolute; left: 37%; top: 33%; } </style> <script> function addata() { var booktitle = document.getElementById("booktitle").value; var term = document.getElementById("term").value; if ( booktitle=="" || term=="" ) { document.getElementById("txtHint").innerHTML = "資料缺少"; return; } else { if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { document.getElementById("txtHint").innerHTML = xmlhttp.responseText; } }; xmlhttp.open("GET","insertphterm.php?title="+booktitle+"&term="+term,true); xmlhttp.send(); } } </script> <script> function send(){ addata(); } </script> </head> <body> <h1 align="center">段詞輸入</h1> <form class="form"> <p><font class="font">書名: </font><input type="text" id="booktitle"/></p> <p><font class="font">詞 : </font><input type="text" id="term"/></p> </form> <button class="btn" onclick="send()">送出</button> <div class="BOX" id="txtHint">........</div> <body> </html><file_sep><?php $term = $_GET['term']; $termGuid = array(); $termIndexGref = array(); $con = mysqli_connect('localhost','root','kone5566','literatures'); if (!$con) { die('Could not connect: ' . mysqli_error($con)); } /*-------------search term in Term-Table-------------*/ mysqli_select_db($con,"term"); $sql = "SELECT * FROM term WHERE term = '$term'"; $result = mysqli_query($con,$sql); while ( $row = mysqli_fetch_array($result)) { array_push($termGuid, $row['guid']); array_push($termIndexGref, $row['termindexgref']); } /* echo $termGuid; echo "<br/>"; echo $termIndexGref; */ /*-------------processing and calculating confidence in Phterm-Table-------------*/ foreach (array_combine($termGuid,$termIndexGref) as $termGuid => $termIndexGref) { mysqli_select_db($con,"phterm"); //echo $termGuid." ".$termIndexGref; $termCounter = 0; $termCountArray = array(); $sql = "SELECT * FROM phterm WHERE termgref = '$termGuid'"; $result = mysqli_query($con, $sql); while ($row = mysqli_fetch_array($result)) { $termCounter += $row['count']; $phgref = $row['phgref']; $sqlCountTerm = "SELECT * FROM phterm WHERE phgref = '$phgref'"; $sqlCountTermRes = mysqli_query($con, $sqlCountTerm); while ($rowT = mysqli_fetch_array($sqlCountTermRes)) { $addr = 0; if ($rowT['count'] >= $row['count']) $addr = $row['count']; else if ($rowT['count'] < $row['count']) $addr = $rowT['count']; if (array_key_exists($rowT['termgref'], $termCountArray)) $termCountArray[$rowT['termgref']]+= $addr; else $termCountArray[$rowT['termgref']] = $addr; /* if (array_key_exists($rowT['termgref'], $termCountArray)) $termCountArray[$rowT['termgref']]+= $rowT['count']; else $termCountArray[$rowT['termgref']] = $rowT['count']; */ } } arsort($termCountArray); $limit = 0; echo "<table class="."table".">"; echo "<thead>"; echo "<tr>"; echo "<th>詞</th>"; echo "<th>相關性</th>"; echo "</tr>"; echo "</thead>"; echo "<tbody>"; foreach ( $termCountArray as $key => $value) { if ( $limit >= 10 ) break; $limit++; mysqli_select_db($con,"term"); $sql = "SELECT * FROM term WHERE guid = '$key'"; $sqlRes = mysqli_query($con, $sql); while ($row = mysqli_fetch_array($sqlRes)) { $confidenceTerm = $row['term']; } $confidenceCal = ($value/$termCounter)*(100); echo "<tr>"; echo "<td>".$confidenceTerm."</td>"; echo "<td>".$confidenceCal."</td>"; echo "</tr>"; } echo "</tbody>"; echo "</table>"; } ?><file_sep># Termindex 很厲害的東東 <file_sep><!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script language="javascript" type="text/javascript"></script> <script src="mark.min.js"></script> <link rel="stylesheet" type="text/css" href="/css/result-light.css"> <script type="text/javascript" src="https://code.jquery.com/jquery-latest.min.js"></script> <script type="text/javascript" src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script> <script type="text/javascript" src="https://cdn.jsdelivr.net/mark.js/7.0.0/mark.min.js"></script> <style type="text/css"> body { margin: 15px; background-color: #E8FFE8; } div.search span, div.search input[name="keyword"] { display: block; } div.search input[name="keyword"] { margin-top: 4px; } div.panel { margin-bottom: 15px; } div.panel .panel-body p:last-child { margin-bottom: 0; } mark { padding: 0; } .line{ border:2px #D9D9D9 solid; text-align: 10px; font-family:Microsoft JhengHei; background-color: #F2FFF2; } </style> </head> <body> <?php $booknum = $_GET['b']; $chapter = $_GET['c']; $paragraph = $_GET['p']; $text = $_GET['t']; $unicode = $_GET['u']; $cha=$chapter."-".$paragraph; $con = mysqli_connect('localhost','root','kone5566','literatures'); if (!$con) { die('Could not connect: ' . mysqli_error($con)); } //echo $booknum; //echo $chapter; //get guid $gusql = "SELECT uuid();"; $guidresult = mysqli_query($con,$gusql); while ($gurow = $guidresult->fetch_assoc()) { $guid = $gurow['uuid()']; } $guid = strtoupper($guid); echo $booknum." "; echo $chapter."-"; echo $paragraph; echo $text; echo $unicode; mysqli_select_db($con,"paragraph"); $sql = "INSERT INTO paragraph (guid,bookgref,chapter,realtext,unitext) VALUES ('".$guid."','".$booknum."','".$cha."','".$text."','".$unicode."');"; mysqli_query($con,$sql)or die ("無法新增".mysql_error()); mysqli_close($con); /* $sql="SELECT *, MATCH (unitext) AGAINST ('".$q."') AS score FROM book WHERE MATCH (unitext) AGAINST ('".$q."'IN BOOLEAN MODE) ORDER BY score DESC;"; $result = mysqli_query($con,$sql); */ /* echo "<div style='"."text-align:left;font-family:Microsoft JhengHei"."'>"."共 ".mysqli_num_rows($result)." 筆結果"."</div>"; //echo $q; echo "<table class='"."line"."' style='"."text-align:center"."'>"; echo "<tr class='"."line"."'>"; echo "<th class='"."line"."' style='"."width:5%"."'>序號</th>";/*ID*/ /* echo "<th class='"."line"."' style='"."width:5%"."'>章節</th>";/*chapter*/ /* echo "<th class='"."line"."' style='"."width:75%"."'>內文</th>";/*Realtext*/ /* echo "<th class='"."line"."' style='"."width:15%"."'>結果分數</th>";/*Score*/ /* echo "</tr>"; while($row = mysqli_fetch_array($result)) { echo "<tr class='"."line"."'>"; echo "<td class='"."line"."'>" . $row['id'] . "</td>"; echo "<td class='"."line"."'>" . $row['chapter'] . "</td>"; echo "<td class='"."line"."'>" . $row['realtext'] . "</td>"; // echo "<td>" . $row['unitext'] . "</td>"; echo "<td class='"."line"."'>" . $row['score'] . "</td>"; echo "</tr>"; } echo "</table>"; mysqli_close($con); */ ?> </body> </html><file_sep><?php $con = mysqli_connect('localhost','root','kone5566','literatures'); if (!$con) { die('Could not connect: ' . mysqli_error($con)); } //------------------------------------------------- $keyword_set = mysqli_real_escape_string($con, $_GET['uni_term']); mysqli_select_db($con,"paragraph"); $keyword_set = str_replace ("+","",$keyword_set); $arrays = explode("20",$keyword_set); array_filter($arrays); $sqls = "SELECT *,Match(unitext) AGAINST ('$keyword_set' IN BOOLEAN MODE) from paragraph WHERE"; for($i = 0; $i < sizeof($arrays); $i++) { if ($arrays[$i] == " ")continue; $arrays[$i] = trim($arrays[$i]); if (preg_match("/ 7c /", $arrays[$i])) { $orArrays = explode("7c", $arrays[$i]); if ($i == 0) { for ( $j = 0; $j < sizeof($orArrays); $j++ ) { if ($j == 0) $sqls = $sqls." ((unitext) LIKE '%$orArrays[0]%'"; else $sqls = $sqls." OR (unitext) LIKE '%$orArrays[1]%'"; } $sqls = $sqls.")"; } else { for ( $j = 0; $j < sizeof($orArrays); $j++ ) { if ($j == 0) $sqls = $sqls." AND ((unitext) LIKE '%$orArrays[0]%'"; else $sqls = $sqls." OR (unitext) LIKE '%$orArrays[1]%'"; } $sqls = $sqls.")"; } } else if (substr($arrays[$i],0,2) == "2d") { $noterm = substr($arrays[$i],3,sizeof($arrays[$i])-3); if ($i == 0) $sqls = $sqls." (unitext) NOT LIKE '%$noterm%'"; else $sqls = $sqls." AND (unitext) NOT LIKE '%$noterm%'"; } else { if ($i == 0) $sqls = $sqls." (unitext) LIKE '%$arrays[$i]%'"; else $sqls = $sqls." AND (unitext) LIKE '%$arrays[$i]%'"; } } //-------------------------------------------------- $result = mysqli_query($con,$sqls); $paragraph_output_array = array(); while($row = mysqli_fetch_array($result)) { mysqli_select_db($con,"book"); $bookid = $row['bookgref']; $sql="SELECT title FROM book WHERE guid = '".$row['bookgref']."';"; $titleFind = mysqli_query($con,$sql); $title=""; while($titleInTableResult = mysqli_fetch_array($titleFind)) { $title = $titleInTableResult['title']; //data 1 } $paragraph_chapter = $row['chapter']; //data 2 $paragraph_graf = $row['bookgref']; //data 3 $paragraph_text = $row['realtext']; //data 4 $element_in_output_arr = array( 'title' => $title, 'chapter' => $paragraph_chapter, 'text' => $paragraph_text ,'bookid' => $paragraph_graf); array_push($paragraph_output_array, $element_in_output_arr); } echo json_encode($paragraph_output_array); mysqli_close($con); ?><file_sep><?php //session_start(); $username = ""; $email = ""; $password_1 = ""; $errors = array(); $db = mysqli_connect('localhost','root','kone5566', 'literatures'); if (isset($_POST['register'])) { $username = mysqli_real_escape_string($db, $_POST['username']); $email = mysqli_real_escape_string($db, $_POST['email']); $password_1 = mysqli_real_escape_string($db, $_POST['password_1']); $password_2 = mysqli_real_escape_string($db, $_POST['password_2']); if (empty($username)){ array_push($errors, "Username is required"); } if (empty($email)){ array_push($errors, "Email is required"); } if (empty($password_1)){ array_push($errors, "Password is required"); } if ($password_1 != $password_2){ array_push($errors, "The two passwords do not match"); } //--------------------------------------------------------------------// //27~36 check the username. $sql = "SELECT COUNT(*) FROM users WHERE username LIKE ('$username')"; $compareresult = mysqli_query($db,$sql); while($row = mysqli_fetch_array($compareresult)){ $counter = $row['COUNT(*)']; } if ( $counter != 0 && $username != "" ){ array_push($errors, "The username is exist"); } //-------------------------------------------------------------------// if (count($errors) == 0 && $username != "" ) { $gusql = "SELECT uuid();"; $result = mysqli_query($db,$gusql); while ($row = $result->fetch_assoc()) { $guid = $row['uuid()']; $guid = strtoupper($guid); } $password = md5($<PASSWORD>); $sql = "INSERT INTO users (guid, username, email, password) VALUES('$guid', '$username', '$email', '$password')"; mysqli_query($db,$sql); //session_start(); $_SESSION['username'] = $username; $_SESSION['success'] = "You are logged in"; header('location: index.php'); } } if(isset($_POST['login'])){ $username = mysqli_real_escape_string($db, $_POST['username']); $password = mysqli_real_escape_string($db, $_POST['password']); if (empty($username)){ array_push($errors, "Username is required"); } if (empty($password)){ array_push($errors, "Password is required"); } if (count($errors) == 0){ $password = md5($<PASSWORD>); $query = "SELECT * FROM users WHERE username = '$username' AND password='$<PASSWORD>'"; $result = mysqli_query($db, $query); if ( mysqli_num_rows($result) == 1 ){ $_SESSION['username'] = $username; $_SESSION['success'] = "You are logged in"; $row = mysqli_fetch_array($result); $access = $row['access']; $_SESSION['access'] = $access; header('location: index.php'); } } else{ array_push($errors, "The username/password combination"); } } if (isset($_GET['logout'])){ session_destroy(); unset($_SESSION['username']); header('location: login.php'); } ?><file_sep><?php $term = $_GET['term']; $con = mysqli_connect('localhost','root','kone5566','literatures'); if (!$con) { die('Could not connect: ' . mysqli_error($con)); } $sql = "SELECT guid,termindexgref FROM term WHERE term = '$term'"; $sqlRes = mysqli_query($con, $sql); while ( $row = mysqli_fetch_array($sqlRes) ) { $frequencyarray = array(); $termguid = $row['guid']; $termindexgref = $row['termindexgref']; $sqlfindbook = "SELECT bookgref FROM termindex WHERE guid = '$termindexgref'"; $sqlfindbookres = mysqli_query($con, $sqlfindbook); while ( $rowfb = mysqli_fetch_array( $sqlfindbookres ) ) { $bookguid = $rowfb['bookgref']; } //$sqlfindpart = "SELECT guid,chapter FROM paragraph WHERE bookgref = '$bookguid'"; $sqlfindpart="SELECT guid,chapter, CONVERT(SUBSTRING_INDEX(chapter,'-',-1),UNSIGNED INTEGER) AS part ,CONVERT(SUBSTRING_INDEX(chapter,'-',1),UNSIGNED INTEGER) AS para FROM paragraph WHERE bookgref = '$bookguid' ORDER BY para,part"; $sqlfindpartres = mysqli_query($con, $sqlfindpart); while ( $rowfpart = mysqli_fetch_array($sqlfindpartres)) { $paraguid = $rowfpart['guid']; $sqlfindfre = "SELECT * FROM phterm WHERE phgref = '$paraguid' AND termgref = '$termguid'"; $sqlfindfreres = mysqli_query($con, $sqlfindfre); while ($rowcountfre = mysqli_fetch_array($sqlfindfreres)) { if ( array_key_exists($rowfpart['para'], $frequencyarray) ) $frequencyarray[$rowfpart['para']] += $rowcountfre['count']; else $frequencyarray[$rowfpart['para']] = $rowcountfre['count']; } } echo json_encode($frequencyarray); //echo $frequencyarray; } ?><file_sep><!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script language="javascript" type="text/javascript"></script> <script src="mark.min.js"></script> <link rel="stylesheet" type="text/css" href="/css/result-light.css"> <script type="text/javascript" src="https://code.jquery.com/jquery-latest.min.js"></script> <script type="text/javascript" src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script> <script type="text/javascript" src="https://cdn.jsdelivr.net/mark.js/7.0.0/mark.min.js"></script> <style type="text/css"> body { margin: 15px; background-color: #E8FFE8; } div.search span, div.search input[name="keyword"] { display: block; } div.search input[name="keyword"] { margin-top: 4px; } div.panel { margin-bottom: 15px; } div.panel .panel-body p:last-child { margin-bottom: 0; } mark { padding: 0; } .line{ border:2px #D9D9D9 solid; text-align: 10px; font-family:Microsoft JhengHei; background-color: #F2FFF2; } </style> </head> <body> <?php $booktitle = $_GET['title']; $termindex = $_GET['tid']; $term = $_GET['term']; //$tag = $_GET['tag']; //$utag = $_GET['utag']; $parent=$booktitle." ".$termindex; $con = mysqli_connect('localhost','root','kone5566','literatures'); if (!$con) { die('Could not connect: ' . mysqli_error($con)); } //echo $booknum; //echo $chapter; /* echo $booktitle."<br/>"; echo $termindex."<br/>"; echo $term."<br/>"; echo $tag."<br/>"; echo $utag."<br/>"; echo $parent; */ mysqli_select_db($con,"term"); $def = "SELECT * FROM term WHERE term='".$term."';"; $result = mysqli_query($con,$def); if (mysqli_num_rows($result)<1){ mysqli_select_db($con,"termindex"); $gusql = "SELECT uuid();"; $result = mysqli_query($con,$gusql); while ($row = $result->fetch_assoc()) { $guid = $row['uuid()']; } $tidgref_sql="SELECT guid FROM termindex WHERE booktitle = '".$booktitle."' AND class='".$termindex."';"; $result = mysqli_query($con,$tidgref_sql); while ($row = $result->fetch_assoc()) { $gref = $row['guid']; } echo "guid: ".$guid."<br/>"; echo "termgref: ".$gref."<br/>"; //echo $gref; mysqli_select_db($con,"term"); $gref = strtoupper($gref); $guid = strtoupper($guid); $sql = "INSERT INTO term (guid,termindexgref,parent,term) VALUES ('".$guid."','".$gref."','".$parent."','".$term."');"; mysqli_query($con,$sql)or die ("無法新增".mysql_error()); } else echo "資料已存在"; mysqli_close($con); /* $sql="SELECT *, MATCH (unitext) AGAINST ('".$q."') AS score FROM book WHERE MATCH (unitext) AGAINST ('".$q."'IN BOOLEAN MODE) ORDER BY score DESC;"; $result = mysqli_query($con,$sql); */ /* echo "<div style='"."text-align:left;font-family:Microsoft JhengHei"."'>"."共 ".mysqli_num_rows($result)." 筆結果"."</div>"; //echo $q; echo "<table class='"."line"."' style='"."text-align:center"."'>"; echo "<tr class='"."line"."'>"; echo "<th class='"."line"."' style='"."width:5%"."'>序號</th>";/*ID*/ /* echo "<th class='"."line"."' style='"."width:5%"."'>章節</th>";/*chapter*/ /* echo "<th class='"."line"."' style='"."width:75%"."'>內文</th>";/*Realtext*/ /* echo "<th class='"."line"."' style='"."width:15%"."'>結果分數</th>";/*Score*/ /* echo "</tr>"; while($row = mysqli_fetch_array($result)) { echo "<tr class='"."line"."'>"; echo "<td class='"."line"."'>" . $row['id'] . "</td>"; echo "<td class='"."line"."'>" . $row['chapter'] . "</td>"; echo "<td class='"."line"."'>" . $row['realtext'] . "</td>"; // echo "<td>" . $row['unitext'] . "</td>"; echo "<td class='"."line"."'>" . $row['score'] . "</td>"; echo "</tr>"; } echo "</table>"; mysqli_close($con); */ ?> </body> </html><file_sep><html> <?php $chapter = $_GET['chapter']; $bookgref = $_GET['bookid']; $pharagraph = $_GET['pharagraph']; $con = mysqli_connect('localhost','root','kone5566','literatures'); if (!$con) { die('Could not connect: ' . mysqli_error($con)); } mysqli_select_db($con,"paragraph"); $sql="SELECT realtext,chapter , CONVERT(SUBSTRING_INDEX(chapter,'-',-1),UNSIGNED INTEGER) AS num FROM paragraph WHERE bookgref = '$bookgref' AND chapter LIKE '$chapter-%' ORDER BY num"; $result = mysqli_query($con,$sql); mysqli_select_db($con,"book"); $sql_findbook="SELECT title FROM book WHERE guid='$bookgref'"; $book_result = mysqli_query($con,$sql_findbook); $article=""; while($bookrow = mysqli_fetch_array($book_result)) { $article = $bookrow['title']; } $article = $article." "."第".$chapter."回"; echo "<div style="."text-align:center;"."><h1>".$article."</h1></div>"; echo "<table>"; while($row = mysqli_fetch_array($result)) { $targetParagraph = $chapter.'-'.$pharagraph; echo "<tr>"; if ( $targetParagraph == $row['chapter']) { echo "<td bgcolor='#FFBB00'><a id=".'target'.">".$row['realtext']."<a></td>"; } else { echo "<td>".$row['realtext']."</td>"; } echo "</tr>"; } echo "</table>"; ?> </html> <file_sep><?php //------------------------------------------------- $con = mysqli_connect('localhost','root','kone5566','literatures'); if (!$con) { die('Could not connect: ' . mysqli_error($con)); } //------------------------------------------------- /* $cars = []; array_push($cars, "123"); $guid = $_POST["bookguid"]; echo json_encode($cars); */ $index = []; $indexguid = []; $bookgref = $_POST["bookguid"]; mysqli_select_db($con,"termindex"); $sql = "SELECT * FROM termindex WHERE bookgref = '$bookgref'"; $result = mysqli_query($con, $sql); while ( $row = mysqli_fetch_array($result) ) { array_push($index, $row['class']); array_push($index, $row['guid']); } echo json_encode($index); ?><file_sep><?php $con = mysqli_connect('localhost','root','kone5566','literatures'); if (!$con) { die('Could not connect: ' . mysqli_error($con)); } //------------------------------------------------- $keyword_set = mysqli_real_escape_string($con, $_GET['get_phterm_count']); mysqli_select_db($con,"paragraph"); $keyword_set = str_replace ("+","",$keyword_set); $arrays = explode("20",$keyword_set); array_filter($arrays); $sqls = "SELECT *,Match(unitext) AGAINST ('$keyword_set' IN BOOLEAN MODE) from paragraph WHERE"; for($i = 0; $i < sizeof($arrays); $i++) { if ($arrays[$i] == " ")continue; $arrays[$i] = trim($arrays[$i]); if (preg_match("/ 7c /", $arrays[$i])) { $orArrays = explode("7c", $arrays[$i]); if ($i == 0) { for ( $j = 0; $j < sizeof($orArrays); $j++ ) { if ($j == 0) $sqls = $sqls." ((unitext) LIKE '%$orArrays[0]%'"; else $sqls = $sqls." OR (unitext) LIKE '%$orArrays[1]%'"; } $sqls = $sqls.")"; } else { for ( $j = 0; $j < sizeof($orArrays); $j++ ) { if ($j == 0) $sqls = $sqls." AND ((unitext) LIKE '%$orArrays[0]%'"; else $sqls = $sqls." OR (unitext) LIKE '%$orArrays[1]%'"; } $sqls = $sqls.")"; } } else if (substr($arrays[$i],0,2) == "2d") { $noterm = substr($arrays[$i],3,sizeof($arrays[$i])-3); if ($i == 0) $sqls = $sqls." (unitext) NOT LIKE '%$noterm%'"; else $sqls = $sqls." AND (unitext) NOT LIKE '%$noterm%'"; } else { if ($i == 0) $sqls = $sqls." (unitext) LIKE '%$arrays[$i]%'"; else $sqls = $sqls." AND (unitext) LIKE '%$arrays[$i]%'"; } } $ptsql = $sqls; $ptresult = mysqli_query($con,$ptsql); $c=mysqli_num_rows($ptresult); mysqli_select_db($con,"phterm"); $findptsql = "SELECT termgref,count,guid, sum(count) as count FROM phterm WHERE"; //select guid,termgref, sum(count) as count from phterm group by termgref while($row = mysqli_fetch_array($ptresult)) { $c-=1; $findptsql=$findptsql." phgref='".$row['guid']."'"; if($c!=0) $findptsql=$findptsql." OR"; } $findptsql=$findptsql." group by termgref ORDER BY count DESC;"; $findptresult=mysqli_query($con,$findptsql); /* echo "<div>"; echo "<ul class='nav nav-tabs'>"; echo "<li class="."active"."><a data-toggle="."tab"." href="."#home".">總覽</a></li>"; echo "<li><a data-toggle="."tab"." href="."#menu1".">人名</a></li>"; echo "<li><a data-toggle="."tab"." href="."#menu2".">地名</a></li>"; echo "<li><a data-toggle="."tab"." href="."#menu3".">其他</a></li>"; echo "</ul>"; echo "<div class="."tab-content".">"; echo "<div id="."home"." class='tab-pane fade in active'>"; //echo "<h3>HOME</h3>"; echo "<table style='"."text-align:center;width:100%;float:right;border:2px #D9D9D9 solid;background-color:#FFFFFF;"."'>"; echo "<tr>"; echo "<th style='"."width:60%;border:2px #D9D9D9 solid;text-align:center;"."'>詞</th>"; echo "<th style='"."width:40%;border:2px #D9D9D9 solid;text-align:center;"."'>次數</th>"; echo "</tr>"; */ $total = array(); $total_name = array(); $total_count = array(); $character = array(); $character_name = array(); $character_count = array(); $local = array(); $local_name = array(); $local_count = array(); $other = array(); $other_name = array(); $other_count = array(); while($row = mysqli_fetch_array($findptresult)) { $realterm = ""; mysqli_select_db($con,"term"); $findterm = "SELECT term,termindexgref FROM term WHERE guid='".$row['termgref']."';"; $termresult = mysqli_query($con,$findterm); $classgerf =""; while ($trow = mysqli_fetch_array($termresult)) { $realterm = $trow['term']; $classgerf = $trow['termindexgref']; } /* echo "<tr style='"."width:60%;border:2px #D9D9D9 solid;"."'>"; echo "<td style='"."width:20%;border:2px #D9D9D9 solid;"."'> <a id="."termA"." href="."#"." onclick="."termAdd('".$realterm."');return false;".">"."+"."</a> <a id="."termA"." href="."#"." onclick="."newTerm('".$realterm."');return false;".">"."$realterm"."</a> <a id="."termA"." href="."#"." onclick="."termAdd('-".$realterm."');return false;".">"."-"."</a> </td>"; echo "<td style='"."width:60%;border:2px #D9D9D9 solid;"."'>" . $row['count'] . "</td>"; echo "</tr>"; */ mysqli_select_db($con,"termindex"); $findclass = "SELECT class FROM termindex WHERE guid='".$classgerf."';"; $classresult = mysqli_query($con,$findclass); while($crow = mysqli_fetch_array($classresult)) { $total_element = array('name' => $realterm, 'count' => $row['count'] , 'class' => $crow['class'] ); array_push( $total ,$total_element ); if( $crow['class'] == "人名") { $character_element = array( 'name' => $realterm , 'count' => $row['count'] , 'class' => $crow['class'] ); array_push( $character, $character_element ); } else if( $crow['class'] == "地名") { $local_element = array( 'name' => $realterm , 'count' => $row['count'] , 'class' => $crow['class'] ); array_push( $local, $local_element ); } else { $other_element = array( 'name' => $realterm , 'count' => $row['count'] , 'class' => $crow['class'] ); array_push( $other, $other_element ); } } } $output_array = array( 'total' => $total, 'character' => $character, 'local' => $local, 'other' => $other); echo json_encode($output_array); mysqli_close($con); ?><file_sep><?php $text = $_GET['text']; $con = mysqli_connect('localhost','root','kone5566','literatures'); if (!$con) { die('Could not connect: ' . mysqli_error($con)); } mysqli_select_db($con,"book"); $sql = "SELECT * FROM book WHERE title = '$text'"; $result = mysqli_query($con, $sql); if(mysqli_num_rows($result) == 1) echo "book"; else echo "term"; ?><file_sep><?php header('Content-Type: text/html; charset=utf-8'); $servername = "localhost"; $username = "root"; $password = "<PASSWORD>"; $dbname = "literatures"; // Create connection //mysql_query("SET NAMES UTF8"); $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "SELECT * FROM book WHERE MATCH (unitext) AGAINST ('4e00 65e5');"; $result = $conn->query($sql); if ($result->num_rows > 0) { // output data of each row while($row = $result->fetch_assoc()) { echo "ID: " .$row["id"]. " Book_NO.: " . $row["book_number"]." chapter: ".$row["chapter"]."<br>"." - realtext: " . $row["realtext"]."<br>"; } } else { echo "0 results"; } $conn->close(); ?><file_sep> var term_seed = {}; var term_cand = {}; var term_trash = {}; var clip_seed = {}; var clip_cand = {}; var clip_trash = {}; var term_location = {}; window.onload = function() { document.getElementById('myfile').onchange = readFile; } $(document).ready(function(){ $(this).click(function(){ $(this).remove(); }); }); function readFile() { file = this.files[0]; var fReader = new FileReader(); fReader.onload = function(event){ var str = event.target.result; document.getElementById('fileContent').value = str; } fReader.readAsText(file); } function WriteToFile() { } function GetText() { return document.getElementById('fileContent').value; } function GetClip() { var text = GetText(); var frontword =parseInt(document.getElementById('frontword').value); var backword = parseInt(document.getElementById('backword').value); var subtext = text; var prefix = 0; var index; for ( keyword in term_seed ) { index = new Array(); subtext = text; var keyword_len = keyword.length; prefix = 0; while ( subtext.search(keyword) != -1 ) { index_value = subtext.search(keyword) + prefix; index.push( index_value ); prefix += subtext.search(keyword) + keyword_len; subtext = subtext.substring(subtext.search(keyword)+keyword_len); } for ( i = 0; i < index.length; i++ ) { var term_clip_front = text.substring(index[i]-frontword,index[i]); var term_clip_back = text.substring(index[i]+keyword_len,index[i]+keyword_len+backword); var term_clip_mix = term_clip_front+"╫"+term_clip_back; clip_cand[term_clip_mix]= 1; } } for ( key in clip_cand) { if ( $("#"+key+"cc").length == 0) { var loc = "┴cand"; $('#clipCandContent'). append("<p id = \""+key+"cc\">"+"<button onclick=ClipMoveToSeed(this.value) value=\""+key+loc+"\">+</button>" +"<button onclick=ClipMoveToTrash(this.value) value=\""+key+loc+"\">-</button>"+key+"</p>"); } } } function ClipMoveToSeed(str) { var loc = "┴seed"; var s = str.split("┴"); var val = s[0]; var from = s[1]; $('#seedClip'). append("<p id = \""+val+"cs\">"+"<button onclick=ClipMoveToCandidate(this.value) value=\""+val+loc+"\">C</button>" +"<button onclick=ClipMoveToTrash(this.value) value=\""+val+loc+"\">-</button>"+val+"</p>"); clip_seed[val]= 1; if ( from == "cand" ) { delete clip_cand[val]; $( "p" ).remove("#"+val+"cc"); } if ( from == "trash" ) { delete clip_trash[val]; $( "p" ).remove("#"+val+"ct"); } } function ClipMoveToTrash(str) { var loc = "┴trash"; var s = str.split("┴"); var val = s[0]; var from = s[1]; $( "p" ).remove("#"+val); $('#trashClip'). append("<p id = \""+val+"ct\">"+"<button onclick=ClipMoveToSeed(this.value) value=\""+val+loc+"\">+</button>"+val+"</p>"); clip_trash[val]= 1; if ( from == "cand" ) { delete clip_cand[val]; $( "p" ).remove("#"+val+"cc"); } if ( from == "seed" ) { delete clip_seed[val]; $( "p" ).remove("#"+val+"cs"); } } function ClipMoveToCandidate(str) { var loc = "┴cand"; var s = str.split("┴"); var val = s[0]; var from = s[1]; //alert(val); $( "p" ).remove("#"+val); $('#clipCandContent'). append("<p id = \""+val+"cc\">"+"<button onclick=ClipMoveToSeed(this.value) value=\""+val+loc+"\">+</button>" +"<button onclick=ClipMoveToTrash(this.value) value=\""+val+loc+"\">-</button>"+val+"</p>"); clip_cand[val]= 1; if ( from == "seed") { delete clip_seed[val]; $( "p" ).remove("#"+val+"cs"); } if ( from == "trash") { delete clip_trash[val]; $( "p" ).remove("#"+val+"ct"); } } function GetTerm() { var counter = 0; term_location = {}; for (key in clip_seed) { var splitClip = key.split("╫"); var frontclip =splitClip[0]; var backclip = splitClip[1]; //frontclip = frontclip.replace(/\s+/g,""); //backclip = backclip.replace(/\s+/g,""); var regExpTwo = frontclip+".{2,3}"+backclip; var re = new RegExp(regExpTwo); var getTermText = GetText(); var matches; var c = 0; do { re = new RegExp(regExpTwo); var matches = re.exec(getTermText); if(matches) { var realText = matches[0].substring(frontclip.length,matches[0].length-backclip.length); if (term_location[realText] == null) term_location[realText] = new Array(); term_location[realText].push(getTermText.substring(matches.index-10,matches.index+10)); getTermText = getTermText.substring(matches.index + matches[0].length); term_cand[realText]= 1; c = 1; } } while ( matches ); } for ( key in term_cand ) { if ( $("#"+key+"tc").length == 0) { var loc = "┴cand"; $('#termCandContent'). append("<p id = \""+key+"tc\">"+"<button onclick=TermMoveToSeed(this.value) value=\""+key+loc+"\">+</button>"+"<button onclick=TermMoveToTrash(this.value) value=\""+key+loc+"\">-</button>"+"<a onclick=ShowDetail(\""+key+"\")>"+key+"</a>"+"</p>"); } } } function TermMoveToSeed(str) { var loc = "┴seed"; var s = str.split("┴"); var val = s[0]; var from = s[1]; $('#seedTerm'). append("<p id = \""+val+"ts\">"+"<button onclick=TermMoveToCandidate(this.value) value=\""+val+loc+"\">C</button>" +"<button onclick=TermMoveToTrash(this.value) value=\""+val+loc+"\">-</button>"+val+"</p>"); term_seed[val] = 1; if ( from == "cand") { delete term_cand[val]; $( "p" ).remove("#"+val+"tc"); } if ( from == "trash") { delete term_trash[val]; $( "p" ).remove("#"+val+"tt"); } } function TermMoveToTrash(str) { var loc = "┴trash"; var s = str.split("┴"); var val = s[0]; var from = s[1]; $( "p" ).remove("#"+val); $('#trashTerm'). append("<p id = \""+val+"tt\">"+"<button onclick=TermMoveToSeed(this.value) value=\""+val+loc+"\">+</button>"+val+"</p>"); term_trash[val] = 1; if ( from == "cand") { delete term_cand[val]; $( "p" ).remove("#"+val+"tc"); } if ( from == "seed") { delete term_seed[val]; $( "p" ).remove("#"+val+"ts"); } } function TermMoveToCandidate(str) { var loc = "┴cand"; var s = str.split("┴"); var val = s[0]; var from = s[1]; $( "p" ).remove("#"+val); $('#termCandContent'). append("<p id = \""+val+"tc\">"+"<button onclick=TermMoveToSeed(this.value) value=\""+val+loc+"\">+</button>" +"<button onclick=TermMoveToTrash(this.value) value=\""+val+loc+"\">-</button>"+val+"</p>"); term_cand[val] = 1; if ( from == "seed") { delete term_seed[val]; $( "p" ).remove("#"+val+"ts"); } } function Clean(tar) { document.getElementById(tar).innerHTML=""; if ( tar == "clipCandContent" ) { clip_cand = {}; } if ( tar == "termCandContent" ) { term_cand = {}; } } function AddSeedTerm() { var str = document.getElementById("keyword").value; if ( str == "" )return; $('#seedTerm'). append("<p id = \""+str+"ts\">"+"<button onclick=TermMoveToCandidate(this.value) value=\""+str+"┴seed"+"\">C</button>" +"<button onclick=TermMoveToTrash(this.value) value=\""+str+"┴seed"+"\">-</button>"+str+"</p>"); term_seed[str] = 1; document.getElementById("keyword").innerHTML = ""; } function ShowDetail(str) { var myWindow = window.open("", "", " scrollbars=1, width=400, height=400"); for ( key in term_location[str]) { var numbering = parseInt(key)+1; var strIncludeTerm = term_location[str][key]; var index = strIncludeTerm.indexOf(str); myWindow.document.write(numbering +" . "+strIncludeTerm.substring(0,index)+"<span style=\"color:red\">"+strIncludeTerm.substring(index,index + str.length)+"</span>"+strIncludeTerm.substring(index+str.length)+"<br /><br />"); } myWindow.document.title = str+"於文本的出現位置"; }<file_sep>window.onload = function() { document.getElementById('myfile').onchange = readFile; } function readFile() { file = this.files[0]; var fReader = new FileReader(); fReader.onload = function(event) { var str = event.target.result; document.getElementById('fileContent').value = str; } fReader.readAsText(file); } function GetText() { return document.getElementById('fileContent').value; } function UniqueText() { text = GetText(); obj = {}; alert(text); splitStr = text.split(/\r?\n/); for ( i = 0; i < splitStr.length; i++ ) { obj[splitStr[i]] = 1; } count = 0; for ( key in obj ) { count++; } alert(count); } <file_sep><?php if (empty($_SESSION['username'])){ header('location: login.php'); } ?> <!DOCTYPE html> <html> <title>字詞上傳</title> <head> <meta charset="utf-8"> <script language="javascript" type="text/javascript"></script> <script src="mark.min.js"></script> <link rel="stylesheet" type="text/css" href="/css/result-light.css"> <script type="text/javascript" src="https://code.jquery.com/jquery-latest.min.js"></script> <script src="js/bootstrap.min.js"></script> <script src="js/bootstrap.js"></script> <link href="css/bootstrap-theme.css" rel="stylesheet"> <script type="text/javascript" src="https://cdn.jsdelivr.net/mark.js/7.0.0/mark.min.js"></script> <style type="text/css"> body { margin: 15px; background-color: #E8FFE8; } .BOX{ position: absolute; left: 50%; top: 5%; } .line{ border:2px #D9D9D9 solid; text-align: 10px; font-family:Microsoft JhengHei; background-color: #F2FFF2; width: 600px; height: 600px; } </style> <script> function addata() { title = document.getElementById("booktitle").value; tid = document.getElementById("termindex").value; term = document.getElementById( "term" ).value; //tag = document.getElementById( "tag" ).value; //var unitag=encodeURIComponent(document.getElementById("tag").value); //unistr=document.getElementById("tag").value; //var unicode=""; /* for(var i=0;i<unistr.length;i++) { unicode+=parseInt(unistr[i].charCodeAt(0),10).toString(16); if (unistr[i]==' ')unicode+=" "; } var unicode=encodeURIComponent(unicode).toUpperCase();; */ if ( booktitle=="" || termindex=="" || term=="" ) { document.getElementById("txtHint").innerHTML = "資料缺少"; return; } else { if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { document.getElementById("txtHint").innerHTML = xmlhttp.responseText; } }; xmlhttp.open("GET","insertterm.php?title="+title+"&tid="+tid+"&term="+term,true); xmlhttp.send(); } } </script> <script> function showtext(){ addata(); //alert("OK"); } </script> </head> <body> <p>書 名:</p><p><input id='booktitle' type="text"/></p> <p>詞集名:</p><p><input id='termindex' type="text"/></p> <p> 詞:</p><p><input id='term' type="text"/></p> <div> <button onclick="showtext()">提交</button> </div> <div id="txtHint" class="BOX"><b><table class="line"><table></b></div> </body> </html><file_sep><!DOCTYPE html> <html> <head> <title>字詞搜尋</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <link rel = "stylesheet" type="text/css" href="termsearch.css"> <style> </style> <script> function getTerm() { var str=encodeURIComponent(document.getElementById("keyword").value); str=document.getElementById("keyword").value; if (str == "") { document.getElementById("txtHint").innerHTML = ""; return; } else { if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { document.getElementById("txtHint").innerHTML = xmlhttp.responseText; } }; xmlhttp.open("GET","termsearchback.php?str="+str,true); xmlhttp.send(); } } function getConfidence() { var str=encodeURIComponent(document.getElementById("keyword").value); str=document.getElementById("keyword").value; if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { document.getElementById("rightConfidence").innerHTML = xmlhttp.responseText; } }; xmlhttp.open("GET","termdetail/confidence.php?term="+str,true); xmlhttp.send(); } function getChart() { chartdata = new Array(); var str=encodeURIComponent(document.getElementById("keyword").value); str=document.getElementById("keyword").value; $.ajax ({ url:'termdetail/getFrequency.php', data:{term:str}, dataType: "json", type :'GET', success:function(response) { chartdata = response; //document.getElementById("centerFrequency").innerHTML = chartdata; //alert(typeof response); google.charts.load('current', {'packages':['line']}); google.charts.setOnLoadCallback(drawChart); function drawChart() { var dataTable = new google.visualization.DataTable(); var newData = [['章節',str]]; for(var i in chartdata){ newData.push([ i, parseInt(chartdata[i]) ]); } var newDatas = [['Year', 'Sales'], ['2004', 1000], ['2005', 1170], ['2006', 660], ['2007', 1030], ['2008', 1530]]; var numRows = newData.length; var numCols = newData[0].length; dataTable.addColumn('string', newData[0][0]); for (var i = 1; i < numCols; i++) dataTable.addColumn('number', newData[0][i]); for (var i = 1; i < numRows; i++) dataTable.addRow(newData[i]); var options = { chart: { title: '詞彙出現分布圖', subtitle: '' }, legend: { position: 'bottom' }, width: window.innerWidth*0.495, height: 500, axes: { x: { 0: {side: 'top'} } } }; var chart = new google.charts.Line(document.getElementById('chart_div')); chart.draw(dataTable, google.charts.Line.convertOptions(options)); $(window).resize(function(){ options['width'] = window.innerWidth*0.495; chart.draw(dataTable, google.charts.Line.convertOptions(options)); }); } } }); } function getContent() { var str=encodeURIComponent(document.getElementById("keyword").value); str=document.getElementById("keyword").value; $.ajax ({ url:'termdetail/getcontent.php', data:{term:str}, type :'GET', success:function(response) { document.getElementById("txtHint").innerHTML = response; } }); } function getTermDetail() { getContent(); getConfidence(); getChart(); } confirmFlag = ""; function Confirm() { var str=encodeURIComponent(document.getElementById("keyword").value); str=document.getElementById("keyword").value; if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { confirmFlag = xmlhttp.responseText; if (confirmFlag == "book") { getTerm(); $('#rightConfidence').css('display', 'none'); $('#chart_div').css('display', 'none'); $('#foot').css('display', 'none'); } else { getTermDetail(); $('#rightConfidence').css('display', 'block'); $('#chart_div').css('display', 'block'); $('#foot').css('display', 'block'); } } }; xmlhttp.open("GET","confirm.php?text="+str,true); xmlhttp.send(); } function fullText(term) { // alert(term); location.href="ftsdemo.php?term="+term; } window.onload = function() { document.getElementById("bt5").onclick = function() { window.location.href = "index.php?logout=1"; } document.getElementById("Save").onclick = function trigger() { Confirm(); } } </script> </head> <body> <div class="index-top"> <?php if (isset($_SESSION['username'])): ?> <p>Welcome<strong><?php echo $_SESSION['username'];?> [<?php echo $_SESSION['access']?>]</strong> <button type="button" class="btn" id="bt5"> 登出 </button> </p> <?php endif ?> </div> <div class="term-search-bar"> <div class="search"><input type="text" id="keyword" name="keyword"></div> <div class="search-btn-div"><input type="submit" class="termsearch-btn" id="Save" name="Save" value="檢索"></div> </div> <div id="rightConfidence" class="right-confidence"></div> <div id="txtHint" class="search-view"></div> <!--<div id="centerFrequency" class="center-frequency"></div>--> <div id="container"> <div id="foot"></div> <div id="chart_div" class="chart_div"></div> </div> <div id="centerDistributed" class="center-distributed"></div> </body> </html><file_sep><html> <head> <meta charset="utf-8"> <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <link rel = "stylesheet" type="text/css" href="style.css"> </head> <body> <?php $str = $_GET['str']; // echo $str; $db = mysqli_connect('localhost','root','kone5566','literatures'); if (!$db) { die('Could not connect: ' . mysqli_error($db)); } //-------------------------------------------------------------------------- $sql = "SELECT * FROM book WHERE title LIKE ('$str')"; $bookresult = mysqli_query($db,$sql); while($row = mysqli_fetch_array($bookresult)) { $bookguid = $row['guid']; } // echo $bookguid; $sql = "SELECT * FROM termindex WHERE bookgref LIKE ('$bookguid')"; $termindexguid = mysqli_query($db,$sql); $indexarray = array(); while($row = mysqli_fetch_array($termindexguid)) { array_push($indexarray, $row['guid']); } foreach($indexarray as $value) { $sql = "SELECT * FROM term WHERE termindexgref LIKE ('$value')"; $termresult = mysqli_query($db,$sql); while($row = mysqli_fetch_array($termresult)) { //"<div class='"."Tdiv"."' style='"."text-align:center;font-family:Microsoft JhengHei;"."'>"; //wikiPediaUrl = "https://zh.wikipedia.org/wiki/"; //taiwanWikiUrl = "http://www.twwiki.com/wiki/"; $cRef = $row['contentref']; $refUrl = ""; $urlText = ""; $termUrl = urlencode($row['term']); if ($cRef == 'WP') { $refUrl = "https://zh.wikipedia.org/wiki/".$termUrl; $urlText = "...(Wikipedia)"; } else if ($cRef == 'TW') { $refUrl = "http://www.twwiki.com/wiki/".$termUrl; $urlText = "...(TaiwanWiki)"; } echo "<div class="."panel panel-default".">"; echo "<div class="."panel-heading".">"; echo $row['term']; echo "<button class="."btn fulltextbtn"." style="."float: right;"." onclick="."fullText('".$row['term']."');>全文檢索</button>"; echo "</div>"; echo "<div class="."panel-body".">"; echo $row['content']."<a target="."_blank"." href=$refUrl>$urlText</a>"; echo "</div>"; echo "</div>"; } } ?> </body> </html><file_sep><?php header("Content-Type:text/html; charset=utf-8"); $to = "<EMAIL>"; $subject="系統認證信"; $msg="test"; $headers = "From: <EMAIL>"; if (mail("$to","subject","$msg","$headers")) { echo "信件已發送成功"; } else { echo "信件發送失敗"; } ?>
adbdfa0cd44041644b360d863549306828152762
[ "Markdown", "Python", "JavaScript", "PHP" ]
31
PHP
10oscar01/Termindex
a0e852ff052c61314164da4868b43041eb2623c9
c7fe163c6591035325428857a2561c6f37d2a1dc
refs/heads/main
<file_sep>import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from flask import Flask,request,redirect app = Flask(__name__) @app.route('/data/', methods=['POST','GET']) def data(): mail = smtplib.SMTP_SSL("smtp.gmail.com",465) email = "" password = "" mail.login(email,password) sentby = request.form['name'] sentbyemail = request.form['email'] messagebody = request.form['message'] message = MIMEMultipart() message.set_charset("utf-8") message['To'] = email message['From'] = email message['Subject'] = f"A message from {sentby} <{sentbyemail}> via portfolio form" messagebody= MIMEText(messagebody) message.attach(messagebody) mail.sendmail(email,email,message.as_string()) mail.close() return f'''<meta http-equiv="refresh" content="0; URL=http://vivek.nsavjani.co.uk/Vivek.html" /><script>alert("Thank you for your message {sentby}. I look forward to reading and replying to it.")</script>''' @app.route('/test/', methods=['POST','GET']) def test(): return "cgi is running" @app.route('/testdata/',methods=["GET","POST"]) def testdata(): return(request.form['name']) ##run flask local server ##set FLASK_APP=sendmail.py ##set FLASK_ENV=development ##py -m flask run <file_sep># Portfolio My portfolio First properly desighned personal website made with desighn in mind not time. Please don't be too harsh. WIP <file_sep>$.getJSON("https://api.github.com/users/Vivek-Savjani/repos", function(data){ var repo_data = ''; $.each(data, function(key, value){ var url = "https://raw.githubusercontent.com/" + value.full_name + "/main/images/preview.png"; repo_data += '<div class = "projcard"> '; repo_data += '<img src="'+url +' " onerror="this.src=`alt.png`" alt = `project image`>'; repo_data += '<div class = "info">'; repo_data += '<h2>'+value.name+'</h2>'; repo_data += ' <p>'+value.description; repo_data += '</br>Language: '+ value.language+'</p>'; repo_data += '<button onclick="window.location.href=`'+value.html_url+'`;" >Go to project page</button>'; repo_data += '</div></div>'; }); $('#repo_table').prepend(repo_data); }); $.getJSON("https://api.github.com/users/CSCoursework/repos", function(data){ var repo_data = ''; $.each(data, function(key,value){ var string = value.description + "no longer empty"; var substring = "Vivek:"; var bool = checksubstring (string,substring); var url = "https://raw.githubusercontent.com/" + value.full_name + "/main/images/preview.png"; if (bool == true) { repo_data += '<div class = "projcard"> '; repo_data += '<img src="'+url +' " onerror="this.src=`alt.png`" alt = `project image`>'; repo_data += '<div class = "info">'; repo_data += '<h2>'+value.name+'</h2>'; repo_data += ' <p>'+value.description; repo_data += '</br> Language:'+ value.language+'</p>'; repo_data += '<button onclick="window.location.href=`'+value.html_url+'`;" >Go to project page</button>'; repo_data += '</div></div>'; } }); $('#repo_table').prepend(repo_data); }); var myvar; function pageload() { myVar = setTimeout(swapelements, 3000); } function swapelements() { document.getElementById("loadpage-wrap").style.display = "none"; document.getElementById("nav").style.display = "block"; document.getElementById("content").style.display="block"; } function checksubstring(string,substring) {return (string.indexOf(substring) !== -1)} <file_sep>#!/usr/bin/python3.7 from wsgiref.handlers import CGIHandler import sys sys.path.append('/kunden/homepages/42/d862915577/htdocs/.local/lib/python3.7/site-packages/') from contact_form import app class ProxyFix(object): def __init__(self, app): self.app = app def __call__(self, environ, start_response): environ['SERVER_NAME'] = "" environ['SERVER_PORT'] = "80" environ['REQUEST_METHOD'] = "POST" environ['SCRIPT_NAME'] = "" environ['QUERY_STRING'] = "" environ['SERVER_PROTOCOL'] = "HTTP/1.1" return self.app(environ, start_response) if __name__ == '__main__': app.wsgi_app = ProxyFix(app.wsgi_app) CGIHandler().run(app)
738e64390541548a40e3bc5912513e9133c8dc74
[ "Markdown", "Python", "JavaScript" ]
4
Python
Vivek-Savjani/Portfolio
765d35526192d97c3c1d7b71e53ed6676e604018
7f171872aa2477c36b0e040c6f07d2d48d642984
refs/heads/master
<file_sep>package com.example.denny.cyanogen; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.ImageView; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class MainActivity extends AppCompatActivity { ImageView imageViewProfil; final private int REQUEST_CAMERA = 1; final private int SELECT_FILE = 2; final private int CROP_IMG = 3; String userChoosenTask; Uri uri; Intent CropIntent ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageViewProfil = (ImageView) findViewById(R.id.imageViewProfil); event(); ViewPager pager = (ViewPager) findViewById(R.id.viewpager); pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager(), getApplicationContext())); pager.setCurrentItem(0); TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs); tabLayout.setupWithViewPager(pager); } private void event() { imageViewProfil.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { selectImage(v); } }); } private void selectImage(View v) { final CharSequence[] items = { "Take Photo", "Choose from Library", "Cancel" }; AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext()); builder.setTitle("Add Photo!"); builder.setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int item) { boolean result= Utility.checkPermission(getApplicationContext()); if (items[item].equals("Take Photo")) { userChoosenTask="Take Photo"; if(result) cameraIntent(); } else if (items[item].equals("Choose from Library")) { userChoosenTask="Choose from Library"; if(result) galleryIntent(); } else if (items[item].equals("Cancel")) { dialog.dismiss(); } } }); builder.show(); } private void cameraIntent() { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(intent, REQUEST_CAMERA); } private void galleryIntent() { Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(Intent.createChooser(intent, "Select File"),SELECT_FILE); } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { switch (requestCode) { case Utility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE: if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { if(userChoosenTask.equals("Take Photo")) cameraIntent(); else if(userChoosenTask.equals("Choose from Library")) galleryIntent(); } else { //code for deny } break; } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == Activity.RESULT_OK) { if (requestCode == CROP_IMG) { onSelectFromGalleryResult(data); } else if (requestCode == SELECT_FILE) { uri = data.getData(); ImageCropFunction(); } else if (requestCode == REQUEST_CAMERA) onCaptureImageResult(data); } } @SuppressWarnings("deprecation") private void onSelectFromGalleryResult(Intent data) { Bundle extras = data.getExtras(); //get the cropped bitmap from extras Bitmap bm = extras.getParcelable("data"); imageViewProfil.setImageBitmap(getCroppedBitmap(bm)); } private void onCaptureImageResult(Intent data) { Bitmap thumbnail = (Bitmap) data.getExtras().get("data"); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes); File destination = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".jpg"); FileOutputStream fo; try { destination.createNewFile(); fo = new FileOutputStream(destination); fo.write(bytes.toByteArray()); fo.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } imageViewProfil.setImageBitmap(thumbnail); } public void ImageCropFunction() { // Image Crop Code try { CropIntent = new Intent("com.android.camera.action.CROP"); CropIntent.setDataAndType(uri, "image/*"); CropIntent.putExtra("crop", "true"); CropIntent.putExtra("outputX", 180); CropIntent.putExtra("outputY", 180); CropIntent.putExtra("aspectX", 3); CropIntent.putExtra("aspectY", 4); CropIntent.putExtra("scaleUpIfNeeded", false); CropIntent.putExtra("circleCrop",true); CropIntent.putExtra("return-data", true); startActivityForResult(CropIntent, CROP_IMG); } catch (ActivityNotFoundException e) { } } public Bitmap getCroppedBitmap(Bitmap bitmap) { Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(output); final int color = 0xff424242; final Paint paint = new Paint(); final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); paint.setAntiAlias(true); canvas.drawARGB(0, 0, 0, 0); paint.setColor(color); // canvas.drawRoundRect(rectF, roundPx, roundPx, paint); canvas.drawCircle(bitmap.getWidth() / 2, bitmap.getHeight() / 2, bitmap.getWidth() / 2, paint); paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); canvas.drawBitmap(bitmap, rect, rect, paint); //Bitmap _bmp = Bitmap.createScaledBitmap(output, 60, 60, false); //return _bmp; return output; } }
3400322d4a18704e4aceffd36fd2fa2d8e7edfdd
[ "Java" ]
1
Java
dennyviriya/AlphatoneGit
f6593d9243dd054448339c8ac0ac39b84cf7e58a
28adacfa68117804121f0983a63721586e88741f
refs/heads/master
<repo_name>McCouman/FAMOUS-website<file_sep>/FAMOS-Webpage/FAMOS-markdown-webpage/inc/rands/rand1.php <div class="col-lg-2"> <?php echo $options['prject_1']; ?> </div> <div class="col-lg-2"> <?php echo $options['prject_2']; ?> </div> <div class="col-lg-2"> <?php echo $options['prject_3']; ?> </div> <div class="col-lg-2"> <?php echo $options['prject_4']; ?> </div> <div class="col-lg-2"> <?php echo $options['prject_5']; ?> </div> <div class="col-lg-2"> <?php echo $options['prject_6']; ?> </div><file_sep>/FAMOS-Webpage/FAMOS-markdown-webpage/docs/100_Examples/readme.md #Podcast Information System \* **think big** **and different** ##Name \* **Podcast Information System** (PIS) ist nur ein Codename und wird sich noch ändern Da es evtl. später Sinn macht, dieses System auch für Blogs zu verwenden und andere Systeme mit Metadaten anzureichern würde ich von dem Wort Podcast im Projektnamen Abstand nehmen, obwohl es anfangs sicherlich nur Podcasts betrifft. Auch die Einzelteile sollten benannt werden um bei Gesprächen auf bestimmte Bereiche zu referenzieren. Beim Podlove Projekt gibt es immer wieder das Problem, dass Nutzer Bug-Reports im falschen Repo posten bzw. den Unterschied zwischen PPP und PWP nicht kennen. Wenn wir dies verhindern könnten würde das bei künftigen Diskussionen vieles einfacher machen. Ein möglicher Name für den JSON Datenaustausch, also sozusagen das Frontend wäre JSON Objects Data Allocation und das Backbone Netzwerk könnte man Peer Operation Redemption Network nennen. Ich würde bei solchen Akronymen immer eine einfache Aussprechbarkeit bevorzugen. ##Konzept Das PIS ist ein System und Format zum Austausch von Metadaten. Anfangs ist PIS für Multimedia Inhalte (wie Podcasts) gedacht, eine Erweiterung auf Blogs und andere Textinhalte ist nicht ausgeschlossen. ###Dateiformat Das Dateiformat muss möglichst von vielen Programmiersprachen verwendet werden können, deshalb habe ich mich dort für JSON entschieden. Ausserdem müssen folgende Eigenschaften vom Dateiformat ermöglicht werden: * verlinken/weiterleiten auf andere Orte (bei Verwendung von 3rd Party Diensten) * cryptografische public key Signierung (+ evtl. Verschlüsselung) * dezentrale + redundante Speicherung der Daten (Verifizierung durch Signatur) * Haltbarkeitsangabe (ttl) * Erweiterbarkeit auf andere Entitäten * Anreicherbarkeit mit Zusatzinformationen * auch in XML darstellbar * trotz moderner Formate kompatibel zu [RDF](http://de.wikipedia.org/wiki/RDF-Schema), [VCF](http://de.wikipedia.org/wiki/VCard), [GND](http://de.wikipedia.org/wiki/Gemeinsame_Normdatei), [FoaF](http://de.wikipedia.org/wiki/FOAF), ... bleiben (also durch Converter) * ... ###Entitätentypen Da über die PIS Dateien verschiedenste Daten übertragen werden können/sollten ist eine Kategorisierung in Entitäten sinnvoll. Ähnlich wie in anderen Datensammlungen werden folgende Entitäten vorgeschlagen, diese Liste sollte jedoch erweiterbar sein, falls notwendig: <img src="https://raw.github.com/McCouman/PIS-draft/master/diagramme/Podcast%20Information%20System.png" /> * [**redirect**](https://github.com/SimonWaldherr/PIS-draft/blob/master/beispieldateien/redirect.json) Weiterleitung (Weiterleitung auf andere PIS Dateien (zu verwenden auf Systemen die keine Weiterleitung (HTTP 301/2) unterstützen)) * [**overview**](https://github.com/SimonWaldherr/PIS-draft/blob/master/beispieldateien/overview.json) Übersicht (um alle unter dieser Domain verfügbaren PIS Dateien aufzulisten) * Namen (als Übersicht ähnlich der Wikipedia Begriffsklärungsseiten (Diese Seite ist eine Begriffsklärung zur Unterscheidung mehrerer mit demselben Wort bezeichneter Begriffe.)) * [**person**](https://github.com/SimonWaldherr/PIS-draft/blob/master/beispieldateien/person.json) Personen (ausschließlich natürliche Personen und keine juristische Personen) * [**project**](https://github.com/McCouman/PIS-draft/blob/master/beispieldateien/project.json) Körperschaften, Firmen, Projekte, Vereinigungen, Communitys * Events (im Podcast Bezug hauptsächlich Hörertreffen und Workshops) * [**produce**](https://github.com/SimonWaldherr/PIS-draft/blob/master/beispieldateien/produce.json) Werke (Veröffentlichungen jeglicher Art, sowohl live als auch Aufzeichnungen) * [**geo**](https://github.com/SimonWaldherr/PIS-draft/blob/master/beispieldateien/geo.json) Geografika (Um Ortsdaten bei Dauerhaften Ereignissen zu übermitteln, bei zeitlich begrenzten Ereignissen bitte Events verwenden) * **recepie** um Arbeitsabläufe zu beschreiben * [**base**](https://github.com/McCouman/PIS-draft/blob/master/beispieldateien/base.json) Idee für die Standarddaten des Podcasts (Grundeinstellung) * [**meta**](https://github.com/McCouman/PIS-draft/blob/master/beispieldateien/meta.json) Informationen zu den jeweilig aktiven Modulen (Standard erst einmal Backbone) Die [Beispieldateien](beispieldateien/) sind nur ein vorläufiger Entwurf. Die Dateien wurden als JSON gespeichert, enthalten jedoch mit // gekennzeichnete Kommentare, diese sind für gewöhnlich nicht in JSON erlaubt und dienen nur der Dokumentation. ###Verbreitung Um die Daten an andere Systeme zu übergeben ist ein Push-Dienst geplant, jeder Hoster von PIS-Daten kann selbst Pushen oder aber auch einen Push-Dienst verwenden. Beim Push von PIS-Daten wird nur die URL des Objekts übergeben, das nutzende System muss die Daten dann selbst abrufen. Durch diese Art des Push wird es vereinfacht, die ursprüngliche Herkunft der Daten zu verifizieren. Zusätzlich zum Push ist auch eine Eintragung in Feeds, als DNS Eintrag und mittels einer PIS Datei im Root Verzeichnis der Webseite (wie auch bei robots.txt, humans.txt, sitemap.xml, favicon.ico, apple-touch-icon-precomposed.png, ...) möglich. Neben der Verbreitung als JSON Datei ist auch ein Transfer der Daten im PIS-Backbone geplant. ###API Der Zugriff auf die Daten auf Frontend Ebene erfolgt ausschließlich über HTTP GET Requests. Um neue Daten ans Backend zu schicken wird ein HTTP POST verwendet. Im Backbone wird XMPP zur Übertragung von Daten verwendet. ###Kryptographie, Signierung und Hashing Die Daten sollten verschlüsselt, signiert und gehasht werden können. Verschlüsselung ist wichtig für folgende Anwendungsfälle: * Austausch von nicht öffentlichen Daten (Firmenintern) Signierung: * Um Accounts und Adressen als valide und geprüft kennzeichnen zu können * ich würde eine PKCS7 entsprechende Signierungsmethode bevorzugen Hashing: * Um auch bei nicht öffentlichen Adressen diese zum durchsuchen zu verwenden * Ich schlage folgende Hashingalgos vor: * CRC32 * MD5 * Whirlpool * SHA512 ich würde gerne über diese Algos und die Implementierung in verschiedenen Sprachen in der Conf sprechen. Welche Algos sind sicher, schnell und in allen wichtigen Sprachen vorhanden bzw. leicht implementierbar? Für JavaScript würde ich [CRC32, MD5 und Whirlpool Hashingalgos](https://github.com/SimonWaldherr/cryptofoo) zur Verfügung stellen. In PHP können wir ebenfalls alle aufgelisteten Algos verwenden (wird von PHP mitgeliefert). Bei Python sind MD5 und CRC32 ebenfalls direkt verfügbar. ##Nutzer/Participanten Das PIS liefert Daten bzw. bietet Daten an, mögliche Nutzer und Anbieter dieser Daten wären: * Podlove Publisher (Anbieter) * Firtz (Anbieter) * hoersuppe.de (Nutzer + Anbieter) * Shownot.es (Nutzer + Anbieter) * Xenim Streaming (Nutzer + Anbieter) * Event-Datenbank/Suchmaschine X (Nutzer) * Podunion (Nutzer) * Podbe (Nutzer + Anbieter) * ReliveRadio (Nutzer) ##PIS-Backbone-Network Ein separates Backbone-Netz würde eine Möglichkeit bieten, Informationen zwischen verschiedenen Services dezentral auszutauschen. Es würde den Datenabgleich der einzelnen Services untereinander von der Präsentations-Schicht klar trennen. So muss nicht jeder Services eine eigene RESTful-API zur Verfügung stellen, sondern kann wie alle anderen auch eine fest definierte API zum Backbone-Service nutzen. Sicher ließe sich diese auch als lokaler REST-Service ausführen. So könnte man wie gewohnt auf bestimmte Komponenten(zum Beispiel Inhaltssuche) des Backbones via Request zugreifen. Eine weitere Möglichkeit wäre, dem Application-Server direkt Zugriff auf eine Datenbank zu geben, welche das Backbone dann zum ablegen und abrufen von Informationen nutzt. Eine grobe Skizze der Idee findet ihr [hier](diagramme/diagramm_big.png "Darstellung PIS") im unteren Bereich der Abbildung. Eine kurze Erklärung wird ggf. in der Konferenz folgen. ### Ein kurzer Abriss der Idee in Stichpunkten: * Dezentraler Informationsverteiler Dienst als eigener Application Server * Erweitert das von cato vorgeschlagene Mischprinzip und macht es flexibler * Aggregiert Informationen über andere Server - Peering Netzwerk * Verbindung der Systeme bspw. über XMPP/Jabber - Subscription/Push möglich * Aufbau von eigenen Message-Typen möglich - Dadurch flexibel * (Jabber nutzt einen XML-Daten-Stream) * Datenformat der JSON als Grundlage nutzbar ### Vorteile: * Getrennte mehrfach vorhandene Systeme möglich - Podcaster können ihren bevorzugten Service nutzen * Dennoch Datenaustausch zwischen verschiedenen allen Services möglich, wenn diese am Peering-Netz teilnehmen * Daten müssen nicht über Crawler gesucht werden, sondern könnten über das Peer-Netzwerk jedem angeboten werden * Crawler dennoch möglich. Als eigene Systeme die wieder Daten in das Peer-Netzwerk weitergeben * Aufwendige Requests auf viele verschiedene APIs würden entfallen, da das Backbone-Netz diese direkt zur Verfügung stellt. * Vollständig eigene Schicht und somit unabhängig von den anderen PIS-Layern (Kein wesentlicher Umbau der alten Strukturen) ### Nachteile: * Aufwendige Implementierung des Peer-Netzwerkes * Komplexere Konfiguration des Services. * Vertrauens Frage bei Peer-Teilnehmern (sowohl als Informationsanbieter als auch Nutzer) <file_sep>/FAMOS-Webpage/FAMOS-markdown-webpage/inc/random.php <?php //Random Handler $Podlove = $options['prject_1']; $Firtz = $options['prject_2']; $Hoersuppe = $options['prject_3']; $Shownot = $options['prject_4']; $Xenim = $options['prject_5']; $Podunion = $options['prject_6']; $Podbe = $options['prject_7']; $ReliveRadio = $options['prject_8']; $Auphonic = $options['prject_9']; #################################### $anzahl = 3; #### $url[0] = ' <!--Podlove--> <div class="col-lg-2">'. $Podlove .'</div> <!--Firtz--> <div class="col-lg-2">'. $Firtz .'</div> <!--Hoersuppe--> <div class="col-lg-2">'. $Hoersuppe .'</div> <!--Shownot--> <div class="col-lg-2">'. $Shownot .'</div> <!--Xenim--> <div class="col-lg-2">'. $Xenim .'</div> <!--Podunion--> <div class="col-lg-2">'. $Podunion .'</div>'; $url[1] = ' <!--Podbe--> <div class="col-lg-2">'. $Podbe .'</div> <!--ReliveRadio--> <div class="col-lg-2">'. $ReliveRadio .'</div> <!--Auphonic--> <div class="col-lg-2">'. $Auphonic .'</div> <!--Podlove--> <div class="col-lg-2">'. $Podlove .'</div> <!--Firtz--> <div class="col-lg-2">'. $Firtz .'</div> <!--Hoersuppe--> <div class="col-lg-2">'. $Hoersuppe .'</div>'; $url[2] = ' <!--Shownot--> <div class="col-lg-2">'. $Shownot .'</div> <!--Xenim--> <div class="col-lg-2">'. $Xenim .'</div> <!--Podunion--> <div class="col-lg-2">'. $Podunion .'</div> <!--Podbe--> <div class="col-lg-2">'. $Podbe .'</div> <!--ReliveRadio--> <div class="col-lg-2">'. $ReliveRadio .'</div> <!--Hoersuppe--> <div class="col-lg-2">'. $Auphonic .'</div>'; #### srand(time()); $random = rand(0, $anzahl - 1); //out echo $url[$random]; ?><file_sep>/FAMOS-Webpage/FAMOS-markdown-webpage/docs/03_Contribute/01_Contribute.md #Mach mit! Du überlegst also mitzumachen? Du hast sicherlich schon gesehen, das wir eine freies Projekt sind. Das heißt du kannst jeder Zeit mitmachen. Wenn du noch nicht genau weißt was du machen willst, schau doch einfach mal in einer unserer Konferenzen oder im Chat vorbei //LINK zur ORGA oder KONTAKT ##Wobei kann ich helfen? Du musst nicht unbedingt programmieren können oder besonders gut in Webentwicklung sein. Es reicht eigentlich, wenn du die Idee hinter dem Projekt verstehst. Auch wenn du gut darin bist über spezielle Themen zu berichten oder gerne Texte darüber verfassen möchtest bist du herzlich willkommen. **Wir brauchen Hilfe an jeder Ecke!** Wenn du schon weißt ungefähr weißt, was du machen willst schau doch mal in die entsprechende Kategorie unten. Die Kategorien sind natürlich keine Festlegungen. Jeder kann gerne überall mit anpacken. ###Als Hörer Sag uns was für Informationen du gerne bei den Podcasts finden möchtest. Jede Idee ist willkommen, mag sie noch so abstrakt klingen. Berichte deinem Lieblingspodcast von uns, wenn du findest dieser hätte etwas beizutragen. ###Als Podcaster Haben wir was vergessen? Bietest du Informationen an, die im $PIS nicht abgebildet sind? Mach deinen Vorschlag hier: //LINK ZUR ORGA bzw zu den JSON ARRAYS Du würdest gerne mit uns über $PIS sprechen wende dich an: //LINK zur PRESSE-SEITE ###Als Blogger Du würdest gerne über $PIS was schreiben oder hast Ideen wie man Blogbeiträge im $PIS abbilden kann? Stelle und deine Fragen hier: LINK PRESSE-SEITE Oder reiche etwas ein: LINK ORGA ###Als Administrator Du hast lust dich als Admin an der Seite zu beteiligen? Wir brauchen immer jemanden, der ein Teilsystem des Projektes im Auge behält. Seien es Foren, Blog, mumble-server, jabber-server,... Frag uns einfach wo du helfen kannst: LINK ORGA-SEITE ###Als Programmierer oder Datenbank-Administrator Du würdest gerne auf Systemseite am Backbone arbeiten oder hast Vorschläge, was wir besser machen könnten? Dann sprich mit den Entwicklern: LINK BACKBONE-TEAM ###Als Webentwickler oder Wordpressentwickler Du hast Ideen für die API oder Vorschläge zu deren Erweiterung? Du möchtest eine eigene Implementation der API für dein System schreiben? Hier findest du Hilfe und Ansprechpartner: LINK WEB-TEAM-BACKEND ## Fehlt hier was? Du findest hier müsste noch etwas stehen. Sag uns einfach Bescheid :) <file_sep>/FAMOS-Webpage/FAMOS-markdown-webpage/docs/100_Examples/01_Examples.md Überschriften -------------- #h1 ##h2 ###h3 ####h4 #####h5 ######h6 <hr /> Blockquote -------------- <blockquote> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer posuere erat a ante.</p> <small>Someone famous in <cite title="Source Title">Source Title</cite></small> </blockquote> <blockquote class="pull-right"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer posuere erat a ante.</p> <small>Someone famous in <cite title="Source Title">Source Title</cite></small> </blockquote> <hr /> List -------------- - huhu <hr /> Code -------------- &lt;code&gt;: For example, <code>&lt;section&gt;</code> should be wrapped as inline. &lt;pre&gt;: <pre>&lt;p&gt;Sample text here...&lt;/p&gt;</pre> &lt;mark pre&gt;: huhuhuhu <hr /> Tabellen -------------- **Tab1** <table class="table"> <thead> <tr> <th>#</th> <th>First Name</th> <th>Last Name</th> <th>Username</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Mark</td> <td>Otto</td> <td>@mdo</td> </tr> <tr> <td>2</td> <td>Jacob</td> <td>Thornton</td> <td>@fat</td> </tr> <tr> <td>3</td> <td>Larry</td> <td>the Bird</td> <td>@twitter</td> </tr> </tbody> </table> **Tab2** <table class="table table-striped"> <thead> <tr> <th>#</th> <th>First Name</th> <th>Last Name</th> <th>Username</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Mark</td> <td>Otto</td> <td>@mdo</td> </tr> <tr> <td>2</td> <td>Jacob</td> <td>Thornton</td> <td>@fat</td> </tr> <tr> <td>3</td> <td>Larry</td> <td>the Bird</td> <td>@twitter</td> </tr> </tbody> </table> <hr /> Forms -------------- <form role="form"> <div class="form-group"> <label for="exampleInputEmail1">Email address</label> <input type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email"> </div> <div class="form-group"> <label for="exampleInputPassword1">Password</label> <input type="<PASSWORD>" class="form-control" id="exampleInputPassword1" placeholder="<PASSWORD>"> </div> <div class="form-group"> <label for="exampleInputFile">File input</label> <input type="file" id="exampleInputFile"> <p class="help-block">Example block-level help text here.</p> </div> <div class="checkbox"> <label> <input type="checkbox"> Check me out </label> </div> <button type="submit" class="btn btn-default">Submit</button> </form> <hr /> Buttons -------------- <div class="btn-group"> <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown"> Action <span class="caret"></span> </button> <ul class="dropdown-menu" role="menu"> <li><a href="#">Action</a></li> <li><a href="#">Another action</a></li> <li><a href="#">Something else here</a></li> <li class="divider"></li> <li><a href="#">Separated link</a></li> </ul> </div> <div class="btn-group"> <button type="button" class="btn btn-danger">Action</button> <button type="button" class="btn btn-danger dropdown-toggle" data-toggle="dropdown"> <span class="caret"></span> </button> <ul class="dropdown-menu" role="menu"> <li><a href="#">Action</a></li> <li><a href="#">Another action</a></li> <li><a href="#">Something else here</a></li> <li class="divider"></li> <li><a href="#">Separated link</a></li> </ul> </div> <hr /> Tabs & Navs -------------- <div class="bs-example bs-example-tabs"> <ul id="myTab" class="nav nav-tabs"> <li class=""><a href="#home" data-toggle="tab">Home</a></li> <li class="active"><a href="#profile" data-toggle="tab">Profile</a></li> <li class="dropdown"> <a href="#" id="myTabDrop1" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a> <ul class="dropdown-menu" role="menu" aria-labelledby="myTabDrop1"> <li><a href="#dropdown1" tabindex="-1" data-toggle="tab">@fat</a></li> <li><a href="#dropdown2" tabindex="-1" data-toggle="tab">@mdo</a></li> </ul> </li> </ul> <div id="myTabContent" class="tab-content"> <div class="tab-pane fade" id="home"> <p>Raw denim you probably haven't heard of them jean shorts Austin. Nesciunt tofu stumptown aliqua, retro synth master cleanse. Mustache cliche tempor, williamsburg carles vegan helvetica. Reprehenderit butcher retro keffiyeh dreamcatcher synth. Cosby sweater eu banh mi, qui irure <NAME> ex squid. Aliquip placeat salvia cillum iphone. Seitan aliquip quis cardigan american apparel, butcher voluptate nisi qui.</p> </div> <div class="tab-pane fade active in" id="profile"> <p>Food truck fixie locavore, accusamus mcsweeney's marfa nulla single-origin coffee squid. Exercitation +1 labore velit, blog sartorial PBR leggings next level wes anderson artisan four loko farm-to-table craft beer twee. Qui photo booth letterpress, commodo enim craft beer mlkshk aliquip jean shorts ullamco ad vinyl cillum PBR. Homo nostrud organic, assumenda labore aesthetic magna delectus mollit. Keytar helvetica VHS salvia yr, vero magna velit sapiente labore stumptown. Vegan fanny pack odio cillum wes anderson 8-bit, sustainable jean shorts beard ut DIY ethical culpa <NAME> biodiesel. Art party scenester stumptown, tumblr butcher vero sint qui sapiente accusamus tattooed echo park.</p> </div> <div class="tab-pane fade" id="dropdown1"> <p>Etsy mixtape wayfarers, ethical wes anderson tofu before they sold out mcsweeney's organic lomo retro fanny pack lo-fi farm-to-table readymade. Messenger bag gentrify pitchfork tattooed craft beer, iphone skateboard locavore carles etsy salvia banksy hoodie helvetica. DIY synth PBR banksy irony. Leggings gentrify squid 8-bit cred pitchfork. Williamsburg banh mi whatever gluten-free, carles pitchfork biodiesel fixie etsy retro mlkshk vice blog. Scenester cred you probably haven't heard of them, vinyl craft beer blog stumptown. Pitchfork sustainable tofu synth chambray yr.</p> </div> <div class="tab-pane fade" id="dropdown2"> <p>Trust fund seitan letterpress, keytar raw denim keffiyeh etsy art party before they sold out master cleanse gluten-free squid scenester freegan cosby sweater. Fanny pack portland seitan DIY, art party locavore wolf cliche high life echo park Austin. Cred vinyl keffiyeh DIY salvia PBR, banh mi before they sold out farm-to-table VHS viral locavore cosby sweater. Lomo wolf viral, mustache readymade thundercats keffiyeh craft beer marfa ethical. Wolf salvia freegan, sartorial keffiyeh echo park vegan.</p> </div> </div> </div> <ul class="nav nav-tabs"> <li class="active"><a href="#">Home</a></li> <li><a href="#">Profile</a></li> <li><a href="#">Messages</a></li> </ul> <nav class="navbar navbar-default" role="navigation"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">Brand</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse navbar-ex1-collapse"> <ul class="nav navbar-nav"> <li class="active"><a href="#">Link</a></li> <li><a href="#">Link</a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a> <ul class="dropdown-menu"> <li><a href="#">Action</a></li> <li><a href="#">Another action</a></li> <li><a href="#">Something else here</a></li> <li><a href="#">Separated link</a></li> <li><a href="#">One more separated link</a></li> </ul> </li> </ul> <form class="navbar-form navbar-left" role="search"> <div class="form-group"> <input type="text" class="form-control" placeholder="Search"> </div> <button type="submit" class="btn btn-default">Submit</button> </form> <ul class="nav navbar-nav navbar-right"> <li><a href="#">Link</a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a> <ul class="dropdown-menu"> <li><a href="#">Action</a></li> <li><a href="#">Another action</a></li> <li><a href="#">Something else here</a></li> <li><a href="#">Separated link</a></li> </ul> </li> </ul> </div><!-- /.navbar-collapse --> </nav> <hr /> Infos -------------- <span class="label label-default">Default</span> <span class="label label-primary">Primary</span> <span class="label label-success">Success</span> <span class="label label-info">Info</span> <span class="label label-warning">Warning</span> <span class="label label-danger">Danger</span> <hr /> Images ---------------- <div class="row"> <div class="col-sm-6 col-md-3"> <a href="#" class="thumbnail"> <img data-src="holder.js/100%x180" alt="100%x180" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAKsAAAC0CAYAAADraNxXAAAHAElEQVR4Xu2Y6UuUbxSGj2aZLSZSlvWhiDDcIiFtUfRfr<KEY> style="height: 180px; width: 100%; display: block;"> </a> </div> <div class="col-sm-6 col-md-3"> <a href="#" class="thumbnail"> <img data-src="holder.js/100%x180" alt="100%x180" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAKsAAAC0CAYAAADraNxX<KEY>2Y6<KEY>DiCrDCqCIisOyHQAWWVQERRZcUCmA8gqg4qgyIoDMh1AVhlUBEVWHJDpALLKoCIosuKATA<KEY> style="height: 180px; width: 100%; display: block;"> </a> </div> <div class="col-sm-6 col-md-3"> <a href="#" class="thumbnail"> <img data-src="holder.js/100%x180" alt="100%x180" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAKsAAAC0CAYAAADraNxXAAAHAElEQ<KEY>5zTzOfc51zZnneZt<KEY>JprZGR1JS9YN7IKQnONjKyu5AXr/gUOUq5FswkbEwAAAABJRU5ErkJggg==" style="height: 180px; width: 100%; display: block;"> </a> </div> <div class="col-sm-6 col-md-3"> <a href="#" class="thumbnail"> <img data-src="holder.js/100%x180" alt="100%x180" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAKsAAAC0CAYAAADraNxXAAAHAElEQVR4Xu2Y6UuUbxSGj2aZLSZSlvWhiDDcIiFtUfRfrw8tSCWCZpbYLkFuRZu2WOeBV8Z+M9nH3+19vSA5zTzOfc51zZnneZtWV1e3gosOCHSgCVkFKBGxdABZEUGmA8gqg4qgyIoDMh1AVhlUBEVWHJDpALLKoCIosuKATAeQVQYVQZEVB2Q6gKwyqAiKrDgg0wFklUFFUGTFAZkOIKsMKoIiKw7Id<KEY>QKYDyCqDiqDIigMyHUBWGVQERVYckOkAssqgIiiy4oBMB5BVBhVBkRUHZDqArDKoCIqsO<KEY>ZMUBmQ4gqwwqgiIrDsh0AFllUBEUWXFApgPIKoOKoMiKAzIdQFYZVARFVhyQ6QCyyqAiKLLigEwHkFUGFUGRFQdkOoCsMqgIiqw4INMBZJVBRVBkxQGZDiCrDCqCIisOyHQAWWVQERRZcUCmA8gqg4qgyIoDMh1AVhlUBEVWHJDpALLKoCIosuKATAeQVQYVQZEVB2Q6gKwyqAiKrDgg0wFklUFFUGTFAZkOIKsMKoIiKw7IdABZZVARFFlx<KEY> style="height: 180px; width: 100%; display: block;"> </a> </div> </div> <hr /> Infos ---------------- <div class="alert alert-dismissable"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button> <strong>Warning!</strong> Best check yo self, you're not looking too good. </div> <div class="alert alert-success"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button> <strong>Warning!</strong> Best check yo self, you're not looking too good. </div> <div class="alert alert-info"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button> <strong>Warning!</strong> Best check yo self, you're not looking too good. </div> <div class="alert alert-warning"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button> <strong>Warning!</strong> Best check yo self, you're not looking too good. </div> <div class="alert alert-danger"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button> <strong>Warning!</strong> Best check yo self, you're not looking too good. </div> <hr /> Prozessing ---------------- **Pro1** <div class="progress"> <div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style="width: 40%"> <span class="sr-only">40% Complete (success)</span> </div> </div> <div class="progress"> <div class="progress-bar progress-bar-info" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100" style="width: 20%"> <span class="sr-only">20% Complete</span> </div> </div> <div class="progress"> <div class="progress-bar progress-bar-warning" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%"> <span class="sr-only">60% Complete (warning)</span> </div> </div> <div class="progress"> <div class="progress-bar progress-bar-danger" role="progressbar" aria-valuenow="80" aria-valuemin="0" aria-valuemax="100" style="width: 80%"> <span class="sr-only">80% Complete</span> </div> </div> **Pro2** <div class="progress progress-striped"> <div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style="width: 40%"> <span class="sr-only">40% Complete (success)</span> </div> </div> <div class="progress progress-striped"> <div class="progress-bar progress-bar-info" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100" style="width: 20%"> <span class="sr-only">20% Complete</span> </div> </div> <div class="progress progress-striped"> <div class="progress-bar progress-bar-warning" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%"> <span class="sr-only">60% Complete (warning)</span> </div> </div> <div class="progress progress-striped"> <div class="progress-bar progress-bar-danger" role="progressbar" aria-valuenow="80" aria-valuemin="0" aria-valuemax="100" style="width: 80%"> <span class="sr-only">80% Complete (danger)</span> </div> </div> **Pro3** <div class="progress progress-striped active"> <div class="progress-bar" role="progressbar" aria-valuenow="45" aria-valuemin="0" aria-valuemax="100" style="width: 45%"> <span class="sr-only">45% Complete</span> </div> </div> <div class="progress progress-striped active"> <div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style="width: 40%"> <span class="sr-only">40% Complete (success)</span> </div> </div> <div class="progress progress-striped active"> <div class="progress-bar progress-bar-info" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100" style="width: 20%"> <span class="sr-only">20% Complete</span> </div> </div> <div class="progress progress-striped active"> <div class="progress-bar progress-bar-warning" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%"> <span class="sr-only">60% Complete (warning)</span> </div> </div> <div class="progress progress-striped active"> <div class="progress-bar progress-bar-danger" role="progressbar" aria-valuenow="80" aria-valuemin="0" aria-valuemax="100" style="width: 80%"> <span class="sr-only">80% Complete (danger)</span> </div> </div> **Pro4** <div class="progress"> <div class="progress-bar progress-bar-success" style="width: 35%"> <span class="sr-only">35% Complete (success)</span> </div> <div class="progress-bar progress-bar-warning" style="width: 20%"> <span class="sr-only">20% Complete (warning)</span> </div> <div class="progress-bar progress-bar-danger" style="width: 10%"> <span class="sr-only">10% Complete (danger)</span> </div> </div> **Pro5** <div class="progress progress-striped active"> <div class="progress-bar progress-bar-success" style="width: 35%"> <span class="sr-only">35% Complete (success)</span> </div> <div class="progress-bar progress-bar-warning" style="width: 20%"> <span class="sr-only">20% Complete (warning)</span> </div> <div class="progress-bar progress-bar-danger" style="width: 10%"> <span class="sr-only">10% Complete (danger)</span> </div> </div> <hr /> Boxing ----------- <ul class="media-list"> <li class="media"> <a class="pull-left" href="#"> <img class="media-object" data-src="holder.js/64x64" alt="64x64" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAACsUlEQVR4Xu2Y24upYRTGl0PI0JSimHDjMIVETVMzpvzrziLSTIkiLpTcjJLzcfaziuz2Njufsb8La93o+3jX+65nHX55NZ+fnzu6YdOIAFIB0gIyA254BpIMQaGAUEAoIBQQCtywAoJBwaBgUDAoGLxhCMifIcGgYFAwKBgUDAoGb1iBizHYbDap3+/Tbrcjp9NJwWCQNBrNQdJfl<KEY>lisdhv353S/Ro+T+11kQCNRoN6v<KEY>vyev1kt/v52eIkk<KEY>off3d9LpdBSPx2k8HhOCNhqNFIlEKJvNnu3zuOLO7WbFAiyXSz7sdrvloOfzObdAIBDgM8xmM8rlcuTxeGg0GtF0OmWhcNhKpULD4ZBsNhuvw3eoGqxX6vPcwPe/VywAertarbIftADKHIYgQqEQB4nAk8kklUolWiwWBwGOxcOa+/t7enp6okt8/ncBkOF8Ps+l+/LywlksFovc6+FwmMW5u7sj<KEY> style="width: 64px; height: 64px;"> </a> <div class="media-body"> <h4 class="media-heading">Media heading</h4> <p>Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis.</p> <!-- Nested media object --> <div class="media"> <a class="pull-left" href="#"> <img class="media-object" data-src="holder.js/64x64" alt="64x64" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAACsUlEQVR4Xu2Y24upYRTGl0PI0JSimHDjMIVETVMzpvzrziLSTIkiLpTcjJLzcfaziuz2Njufsb8La93o+3jX+65nHX55NZ+fnzu6Yd<KEY>9hQJCAa<KEY>KqD2J1dxfK<KEY>hb<KEY>II=" style="width: 64px; height: 64px;"> </a> <div class="media-body"> <h4 class="media-heading">Nested media heading</h4> Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. <!-- Nested media object --> <div class="media"> <a class="pull-left" href="#"> <img class="media-object" data-src="holder.js/64x64" alt="64x64" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAACsUlEQVR4Xu2Y24upYRTGl0PI0JSimHDjMIVETVMzpvzrziLSTIkiLpTcjJLzcfaziuz2Njufsb8La93o+3jX+65nHX55NZ+fnzu6YdOIAFIB0gIyA254BpIMQaGAUEAoIBQQCtywAoJBwaBgUDAoGLxhCMifIcGgYFAwKBgUDAoGb1iBizHYbDap3+/Tbrcjp9NJwWCQNBrNQdJflKF6vU5ms5lisdhv353S/Ro+T+11kQCNRoN6vR7p9Xr2v16vyev1kt/v52eIkkql+L3BYKBEIkFarfbberuGz+82VCzAZrOhdDrNGX17e6PVakXdbpesVis9PDzwnq1Wi9/BTCYTvb6+0mQyoff3d9LpdBSPx2k8HhOCNhqNFIlEKJvNnu3zuOLO7WbFAiyXSz7sdrvloOfzObdAIBDgM<KEY> style="width: 64px; height: 64px;"> </a> <div class="media-body"> <h4 class="media-heading">Nested media heading</h4> Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. </div> </div> </div> </div> <!-- Nested media object --> <div class="media"> <a class="pull-left" href="#"> <img class="media-object" data-src="holder.js/64x64" alt="64x64" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAACsUlEQVR4Xu2Y24upYRTGl0PI0JSimHDjMIVETVMzpvzrziLSTIkiLpTcjJLzcfaziuz2Njufsb8La93o+3jX+65nHX55NZ+fnzu6YdOIAFIB0gIyA254BpIMQaGAUEAoIBQQCtywAoJBwaBgUDAoGLxhCMifIcGgYFAwKBgUDAoGb1iBizHYbDap3+/Tbrcjp9NJwWCQNBrNQdJflKF6vU5ms5lisdhv353S/Ro+T+11kQCNRoN6vR7p9Xr2v16vyev1kt/v52eIkkql+L3BYKBEIkFarfbberuGz+82VCzAZrOhdDrNGX17e6PVakXdbpesVis9PDzwnq1Wi9/BTCYTvb6+0mQyoff3d9LpdBSPx2k8HhOCNhqNFIlEKJvNnu3zuOLO7WbFAiyXSz7sdrvloOfzObdAIBDgM8xmM8rlcuTxeGg0GtF0OmWhcNhKpULD4ZBsNhuvw3eoGqxX6vPcwPe/VywAertarbIftADKHIYgQqEQB4nAk8kklUolWiwWBwGOxcOa+/t7enp6okt8/ncBkOF8Ps+l+/LywlksFovc6+FwmMW5u7sjt9tN7XabK8Xn8/EzrNPp8HvY8/MzV9GlPpWIoLgCkHHMAPQ2BNg/Q4DHx0eq1Wp/nAcDEBWB4ZjJZA5VY7fbKRqNHnwo8fmv4XpKHMUCIAhUALLmcrn4E33tcDi4AlDmMBysXC5zcMg0g<KEY> style="width: 64px; height: 64px;"> </a> <div class="media-body"> <h4 class="media-heading">Nested media heading</h4> Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. </div> </div> </div> </li> <li class="media"> <a class="pull-right" href="#"> <img class="media-object" data-src="holder.js/64x64" alt="64x64" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAACsUlEQVR4Xu2Y24upYRTGl0PI0JSimHDjMIVETVMzpvzrziLSTIkiLpTcjJLzcfaziuz2Njufsb8La93o+3jX+65nHX55NZ+fnzu6YdOIAFIB0gIyA254BpIMQaGAUEAoIBQQCtywAoJBwaBgUDAoGLxhCMifIcGgYFAwKBgUDAoGb1iBizHYbDap3+/Tbrcjp9NJwWCQNBrNQdJflKF6vU5ms5lisdhv353S/Ro+T+11kQCN<KEY> style="width: 64px; height: 64px;"> </a> <div class="media-body"> <h4 class="media-heading">Media heading</h4> Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. </div> </li> </ul> <hr /> Pannel ------- <div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title">Panel title</h3> </div> <div class="panel-body"> Panel content </div> </div> <div class="panel panel-success"> <div class="panel-heading"> <h3 class="panel-title">Panel title</h3> </div> <div class="panel-body"> Panel content </div> </div> <div class="panel panel-info"> <div class="panel-heading"> <h3 class="panel-title">Panel title</h3> </div> <div class="panel-body"> Panel content </div> </div> <div class="panel panel-warning"> <div class="panel-heading"> <h3 class="panel-title">Panel title</h3> </div> <div class="panel-body"> Panel content </div> </div> <div class="panel panel-danger"> <div class="panel-heading"> <h3 class="panel-title">Panel title</h3> </div> <div class="panel-body"> Panel content </div> </div> <file_sep>/FAMOS-Webpage/FAMOS-markdown-webpage/starting.php <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="author" content=""> <meta name="creator" content="famos-cms"> <title><?php echo $System_Name; ?> - Home</title> <style> @font-face { font-family: 'Glyphicons Halflings'; src: url('<?php echo $Server_Link; ?>/fonts/glyphicons-halflings-regular.eot'); src: url('<?php echo $Server_Link; ?>/fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('<?php echo $Server_Link; ?>/fonts/glyphicons-halflings-regular.woff') format('woff'), url('<?php echo $Server_Link; ?>/fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('<?php echo $Server_Link; ?>/fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg'); } </style> <link href="<?php echo $Server_Link; ?>/podlove-web-player/static/podlove-web-player.css" rel="stylesheet" media="screen" type="text/css" /> <script src="<?php echo $Server_Link; ?>/podlove-web-player/libs/jquery-1.9.1.min.js"></script> <script src="<?php echo $Server_Link; ?>/podlove-web-player/static/podlove-web-player.js"></script> <!-- Bootstrap core CSS --> <link href="<?php echo $Server_Link; ?>/css/bootstrap.css" rel="stylesheet"> <link href="<?php echo $Server_Link; ?>/css/home.css" rel="stylesheet"> <!--[if lt IE 9]> <script src="<?php echo $Server_Link; ?>/js/html5shiv.js"></script> <script src="<?php echo $Server_Link; ?>/js/respond.min.js"></script> <![endif]--> <!--Icon--> <link rel="shortcut icon" href="<?php echo $Server_Link; ?>/img/favicon.png"> </head> <body> <div id="main"> <div class="container"> <div id="login-members"><a id="log-in" href="<?php echo $User_Login_Link; ?>">Login <span class="glyphicon glyphicon-log-in"></span></a></div> <!-- Navigation --> <div class="masthead"> <h3 class="text-muted"><a href="<?php echo $Server_Link.'/'; ?>"><img style="width:200px;" src="https://raw.github.com/SimonWaldherr/PIS-draft/master/logodrafts/d01.png" alt="<?php echo System_Name; ?>"></a></h3> <ul class="nav nav-justified"> <li class="active"><a href="#"><b>Home</b></a></li> <?php echo build_nav($tree); ?> </ul> </div> <!-- Start Infos --> <div class="jumbotron" style=" background:url(img/bg.png) center center transparent no-repeat;"> <br> <h1 style="padding-bottom:12px;"><?php echo $options['wellcome_h1']; ?></h1> <p class="lead"><?php echo $options['wellcome_p']; ?></p> </div> <?php if ($options['podlove'] == "true" ) { ?> <div class="row"> <div class="col-md-2"></div> <div class="col-md-8" style="margin-top: -52px;"><?php include("podlove.php"); ?></div> <div class="col-md-2"></div> </div> <?php } ?> </div> <div class="container marketing"> <?php if ($options['podlove'] == "true" ) { //experimentel echo '<div style="background: url(./img/bt-sh.png) top center no-repeat #fff; height: 32px; position: relative; margin-top: -18px; margin-bottom: 52px;"> <hr class="featurette-divider" style="margin-top: -13px; height: 2px;"> </div>'; } else { echo '<hr class="featurette-divider" style="margin-top: -30px;">'; } ?> <div class="row"> <div class="col-lg-4"> <img class="img-circle" style="width:140px;" src="<?php echo $options['market_img1']; ?>"> <h2 class="caddy"><?php echo $options['market_h1']; ?></h2> <p><?php echo $options['market_1']; ?></p> <p><a class="btn btn-default" href="<?php echo $options['market_link1']; ?>">Erfahre mehr &raquo;</a></p> </div> <div class="col-lg-4"> <img class="img-circle" style="width:140px;" src="<?php echo $options['market_img2']; ?>"> <h2 class="caddy"><?php echo $options['market_h2']; ?></h2> <p><?php echo $options['market_2']; ?></p> <p><a class="btn btn-default" href="<?php echo $options['market_link2']; ?>">Erfahre mehr &raquo;</a></p> </div> <div class="col-lg-4"> <img class="img-circle" style="width:140px;" src="<?php echo $options['market_img3']; ?>"> <h2 class="caddy"><?php echo $options['market_h3']; ?></h2> <p><?php echo $options['market_3']; ?></p> <p><a class="btn btn-default" href="<?php echo $options['market_link3']; ?>">Erfahre mehr &raquo;</a></p> </div> </div> </div> <div class="container" style="margin-top:-30px;"> <?php echo load_page($tree); ?> </div> <div class="container marketing"> <div class="row"> <?php //Random Projekte include("./inc/random.php"); ?> </div> </div> <br><br /> <br><br /> </div> <footer> <ul> <li> <p class="services"><span class="glyphicon glyphicon-bookmark"></span> Services</p> <ul> <li><a href="#">Link</a></li> <li><a href="#">Link</a></li> <li><a href="#">Link</a></li> <li><a href="#">Link</a></li> </ul> </li> <li> <p class="reachus"><span class="glyphicon glyphicon-globe"></span> Reach us</p> <ul> <li><a href="#">Link</a></li> <li><a href="#">Link</a></li> <li><a href="#">Link</a></li> <li>555-123456789</li> </ul> </li> <li> <p class="clients"><span class="glyphicon glyphicon-cloud"></span> Clients</p> <ul> <li><a href="#">Link</a></li> <li><a href="#">Link</a></li> <li><a href="#">Link</a></li> </ul> </li> <li> <p class="home"><span class="glyphicon glyphicon-home"></span> Home</p> <ul> <li class="home-link">Copyright &copy; <?php echo date('Y'); ?>, <a style="color:#7D8691 !important;" href="<?php echo $options['copy_url']; ?>"><?php echo $options['copyright']; ?></a> <br>All rights reserved</li> </ul> <br /> </li> </ul> </footer><file_sep>/FAMOS-Webpage/FAMOS-markdown-webpage/docs/index.md <hr class="featurette-divider"> <div class="row featurette"> <div class="col-md-5"> <h2 class="caddylight featurette-heading">First featurette heading. <span class="text-muted">It'll blow your mind.</span></h2> <br> <p class="lead">Praesent commodo cursus magna, vel scelerisque nisl consectetur. Fusce dapibus, tellus ac cursus commodo.</p> <p><a class="btn btn-default" style="font-size:20px;" href="#">Erfahre mehr &raquo;</a></p> </div> <div class="col-md-7"> <img src="img/right.png" class="img-rounded img-responsive"> </div> </div> <hr class="featurette-divider"> <div class="row featurette"> <div class="col-md-7"> <img src="img/left.png" class="img-rounded img-responsive"> </div> <div class="col-md-5"> <h2 class="caddylight featurette-heading">First featurette heading. <span class="text-muted">It'll blow your mind.</span></h2> <br> <p class="lead">Donec ullamcorper nulla non metus auctor fringilla. Vestibulum id ligula porta felis euismod semper. </p> <p><a class="btn btn-default" style="font-size:20px;" href="#">Erfahre mehr &raquo;</a></p> </div> </div> <hr class="featurette-divider"> <div class="row featurette"> <div class="col-md-5"> <h2 class="caddylight featurette-heading">First featurette heading. <span class="text-muted">It'll blow your mind.</span></h2> <br> <p class="lead">Praesent commodo cursus magna, vel scelerisque nisl consectetur. Fusce dapibus, tellus ac cursus commodo.</p> <p><a class="btn btn-default" style="font-size:20px;" href="#">Erfahre mehr &raquo;</a></p> </div> <div class="col-md-7"> <img src="img/right.png" class="img-rounded img-responsive"> </div> </div> <hr class="featurette-divider"><file_sep>/FAMOS-Webpage/FAMOS-markdown-webpage/index.php <?php //libery require_once('libs/functions.php'); $options = get_options(); $tree = get_tree("docs", $base_url); $homepage_url = homepage_url($tree); $docs_url = docs_url($tree); // Redirect to docs, if there is no homepage if ($homepage && $homepage_url !== '/') { header('Location: '.$homepage_url); } //include Server Pfad require_once('setup.php'); ?> <?php ########################################### Homeseite if ($homepage) { //Startpage include('starting.php'); ########################################### Hilfeseiten } else { //Hilfeseiten include('pages.php'); } ?> <!-- Bootstrap core JavaScript ================================================== --> <!-- Placed at the end of the document so the pages load faster --> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script src="<?php echo $Server_Link; ?>/js/bootstrap.min.js"></script> <script src="<?php echo $Server_Link; ?>/js/holder.js"></script> <?php if ($options['piwik_analytics']) { ?> <script type="text/javascript"> var _paq = _paq || []; _paq.push(["trackPageView"]); _paq.push(["enableLinkTracking"]); (function() { var u=(("https:" == document.location.protocol) ? "https" : "http") + "://<?php echo $options['piwik_analytics'];?>/"; _paq.push(["setTrackerUrl", u+"piwik.php"]); _paq.push(["setSiteId", "1"]); var d=document, g=d.createElement("script"), s=d.getElementsByTagName("script")[0]; g.type="text/javascript"; g.defer=true; g.async=true; g.src=u+"piwik.js"; s.parentNode.insertBefore(g,s); })(); </script> <?php } ?> </body> </html><file_sep>/FAMOS-Webpage/FAMOS-markdown-webpage/setup.php <?php //Install Pfad: $Server_Link = 'http://localhost:8888/FAMOS-markdown-webpage'; //no "/" please ;) //Standards $System_Name = "FAMOS"; $System_Mail = "<EMAIL>"; $System_Language = "de_DE"; //Logins $User_Login_Link = "#"; ?> <file_sep>/FAMOS-Webpage/FAMOS-markdown-webpage/inc/rands/rand3.php <div class="col-lg-2"> <?php echo $options['prject_4']; ?> </div> <div class="col-lg-2"> <?php echo $options['prject_5']; ?> </div> <div class="col-lg-2"> <?php echo $options['prject_6']; ?> </div> <div class="col-lg-2"> <?php echo $options['prject_7']; ?> </div> <div class="col-lg-2"> <?php echo $options['prject_8']; ?> </div> <div class="col-lg-2"> <?php echo $options['prject_9']; ?> </div><file_sep>/FAMOS-Webpage/FAMOS-markdown-webpage/pages.php <!doctype html> <!--[if lt IE 7]> <html class="no-js ie6 oldie" lang="en"> <![endif]--> <!--[if IE 7]> <html class="no-js ie7 oldie" lang="en"> <![endif]--> <!--[if IE 8]> <html class="no-js ie8 oldie" lang="en"> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang="en"> <!--<![endif]--> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="description" content="<?php echo $options['tagline'];?>" /> <meta name="author" content="<?php echo $options['title']; ?>"> <meta name="creator" content="famos-cms"> <title><?php echo $System_Name; ?> - <?php echo $options['title']; ?></title> <!-- Mobile --> <meta name="apple-mobile-web-app-capable" content="yes" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> @font-face { font-family: 'Glyphicons Halflings'; src: url('<?php echo $Server_Link; ?>/fonts/glyphicons-halflings-regular.eot'); src: url('<?php echo $Server_Link; ?>/fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('<?php echo $Server_Link; ?>/fonts/glyphicons-halflings-regular.woff') format('woff'), url('<?php echo $Server_Link; ?>/fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('<?php echo $Server_Link; ?>/fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg'); } </style> <!-- Bootstrap core CSS --> <link href="<?php echo $Server_Link; ?>/css/bootstrap.css" rel="stylesheet"> <link href="<?php echo $Server_Link; ?>/css/home.css" rel="stylesheet"> <!-- Navigation --> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script> <script src="<?php echo $base_url ?>/js/custom.js"></script> <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <script src="<?php echo $Server_Link; ?>/js/respond.min.js"></script> <![endif]--> <!--Icon--> <link rel="shortcut icon" href="<?php echo $Server_Link; ?>/img/favicon.png"> </head> <body> <div class="container"> <div class="masthead"> <h3 class="text-muted"><a href="<?php echo $Server_Link.'/'; ?>"><img style="width:200px;" src="https://raw.github.com/SimonWaldherr/PIS-draft/master/logodrafts/d01.png" alt=""></a></h3> </div> <nav class="navbar navbar-default nav nav-justified" role="navigation"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse"> <span class="sr-only">Handy Navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand glyphicon glyphicon-home" href="<?php echo $Server_Link; ?>/"> </a> </div> <div class="collapse navbar-collapse navbar-ex1-collapse"> <ul class="nav navbar-nav"> <?php echo build_nav($tree); ?> </ul> </div> </nav> <div class="container marketing"> <?php echo load_page($tree); ?> <br><br> </div> <!-- /container --> </div><!-- /main --> <style> .caddy-footer { background: #31353A !important; background-color: #31353A !important; background-image: -webkit-linear-gradient(top, #31353A, #2F3337) !important; background-image: -moz-linear-gradient(top, #31353a, #2f3337) !important; background-image: linear-gradient(top, #31353a, #2f3337) !important; } </style> <div id="footer" class="caddy-footer"> <div class="container caddy-footer"> <ul class="nav nav-pills"> <?php if (!empty($options['links']) || !empty($options['twitter'])) { ?> <?php foreach($options['links'] as $name => $url) { ?> <li><a style="color:#fff;" class="caddy-footer" href="<?php echo $url;?>" target="_blank"><?php echo $name;?></a> </li> <?php } ?> <?php } ?> <!-- Twitter --> <?php foreach($options['twitter'] as $handle) { ?> <li><iframe allowtransparency="true" frameborder="0" scrolling="no" style="margin-top: 10px; width:162px; height:20px;" src="https://platform.twitter.com/widgets/follow_button.html?screen_name=<?php echo $handle;?>&amp;show_count=false"></iframe> <li> <?php } ?> </ul> </div> </div> <file_sep>/FAMOS-Webpage/FAMOS-markdown-webpage/docs/00_About.md #FAMOUS Das FAMOUS ist ein System und Format zum Austausch von Metadaten. Anfangs ist FAMOUS für Multimedia Inhalte (wie Podcasts) gedacht, eine Erweiterung auf Blogs und andere Textinhalte ist nicht ausgeschlossen. ##Am Anfang war das Wort und schon sind wir beim Problem, die menschliche Sprache ist in vielerlei Hinsicht uneindeutig und in nicht schriftlicher Form sogar noch schwieriger durch Computer zu verarbeiten. Bereits in den 90ern wurde Versucht, dem Web mehr [Semantik](http://de.wikipedia.org/wiki/Semantik) bei zu bringen. Das heißt die Bedeutung der Texte und ihre Beziehungen untereinander sollten automatisch ausgewertet werden. ["Resource Description Framework"](http://de.wikipedia.org/wiki/Resource_Description_Framework) und ["Semantic Web"](http://de.wikipedia.org/wiki/Semantic_Web) sind da die Stichworte. Viele waren sehr überzeugt von der Idee eines durchsuchbaren Netzes, aber anscheinend war die Zeit noch nicht reif. Seit einiger Zeit wächst die Idee der Semantik auch wieder im Bereich der Blogs und Podcasts, jedoch stammen die Möglichkeiten/Technologien, diese Semantik anzubieten noch immer aus den 90ern. Deshalb haben wir (Personen aus den verschiedensten Projekten und Gruppen, allerdings alle mit Bezug auf Podcasts) uns dazu entschlossen, dieses nun schon so lange ungelöstes Problem erneut in den Fokus zu rücken und sowohl mit Vorschlägen und Standards, als auch mit richtigen Code der diese Ideen dann auch umsetzt, dem Problem Herr zu werden. ##Because we can? Einige werden sich nun fragen, "wieso das ganze?". Ist das Metadatenproblem nicht nur ein Akademisches, welches gar keine wirklichen Auswirkungen auf unseren Alltag hat? Nein! Mehr Semantik und Metadaten machen vieles einfacher und bedeuten (wenn es vernünftige Software dafür gibt) nur einen geringen bis gar keinen Mehraufwand. Unser Ziel ist es, durch möglichst vielseitige Automatisierung, den Aufwand beim Erstellen und Durchsuchen von Multimediainhalten sogar noch zu senken. ##Was ist der Nutzen? Die semantische Auswertung und Verknüpfung von Multimediainhalten, also in diesem Fall von Podcasts, bringt für alle Seiten wesentlich Vorteile in der Nutzung. Welche das für die einzelnen Gruppen sind soll unten weiter ausgeführt werden. ###für Podcaster Wie bereits erwähnt, ist eines der Ziele, die "Arbeit" von Podcastern zu vereinfachen. Durch die Abbildung von Semantik und Metadaten im Podcastingsystem können viele Dinge automatisierter ablaufen. Sei es der Workflow von der Aufnahme, über die Vershownotung, bis hin zur Veröffentlichung oder auch die Erkennung zusammenhängender Informationen. Je mehr ein System von den Inhalten versteht, desto mehr kann es Arbeiten automatisieren und Aufgaben erleichtern. Ein leichterer Produktionsablauf des Podcasters etwa lässt diesem mehr Zeit für seine eigentliche Aufgabe, das Aufzeichnen von Podcasts. Von dieser zusätzlichen Zeit profitiert dann auch wieder der Hörer in Form von mehr, längeren oder besser vorbereiteten Podcastepisoden. ###für Hörer Je mehr eine Podcast-Software über den Inhalt eines Podcasts weiß, desto mehr kann es auch dem/der HörerIn helfen, Dinge zu hören, die ihm/ihr gefallen. Mit mehr Semantik lassen sich auch Abfragen über Podcasts, in welchen das selbe Thema, Produkt oder Event besprochen wurde, machen. Durch FAMOUS verbessert sich die Aktualität und der Umfang der leicht verfügbaren Information. Die Durchsuchbarkeit sowohl der Podcasts selbst, aber auch von zusätzlichen Inhalten, wie z.B. Chatlogs oder zugehörige Nachrichten in "sozialen" Netzwerken wird dadurch nicht nur ermöglicht, sondern auch zum Kinderspiel. ###für Drittdienste Da die Meisten der im Augenblick Beteiligten bei diversen Podcast bezogenen Drittdiensten mithelfen, bietet das Projekt in erster Linie auch den Drittdiensten die meisten Vorteile. Es muss jedoch erwähnt werden, dass sowohl Podcaster, als auch Hörer von besser funktionierenden Drittdiensten profitieren. Egal ob Podcatcher ([Instacast](http://instaca.st/)) oder Streamingdienste ([Xenim](http://xenim.de/)), ob Audiobearbeitung ([Auphonic](https://auphonic.com/)) oder Crowdsourced Sendungsnotizen ([Shownot.es](http://shownot.es/)), alle profitieren sie von mehr Semantik. Durch FAMOUS verbessert sich die Aktualität und der Umfang der leicht verfügbaren Information. Drittanbieter können so fundierte Informationen über jeden Podcast liefern und sogar Beziehungen zwischen verschiedenen Podcasts herstellen. Des weiteren, kann durch Drittdienste eine schnelle und effiziente Verteilung der einzelnen Episoden und deren Inhalt über verschiedenste Wege vereinfacht werden. Dies wird dazu führen, dass potenzielle Hörer eher den richtigen Podcast für sich zum Hören finden. ##Unser Plan Dem [KISS Prinzip](http://de.wikipedia.org/wiki/KISS-Prinzip) (Keep it simple, stupid) entsprechend, möchten wir das ganze zum einen soweit wie möglich auf bereits bestehender Technologie basieren lassen. Es gibt einen schönen Spruch, der besagt, dass Perfektion nicht ist, wenn man nichts mehr hinzufügen kann, sondern wenn man nichts mehr weglassen kann. Aus diesem Grund suchen wir nach dem kleinsten gemeinsamen Nenner all unserer Probleme, die wir bei der Automatisierung haben. Mit unserem Konzept auf Basis moderner Technologien glauben wir, die seit den 90ern erfolglosen Anstrengungen um ein semantisches Web, endlich umzusetzen. Ein uns ebenfalls wichtiger Punkt ist die möglichst breite Unterstützung von Technologien, die wir durch unseren Fokus auf Webtechnologien erreichen. Man kann in so ziemlich jeder wichtigen Programmiersprache HTTP Requests senden und JSON verarbeiten. Weitere Details zu unserem Vorhaben und wie wir gedenken, es umzusetzen folgen in Kürze. ##Jeder packt mit an Da es kein einfaches Unterfangen ist und wir möglichst bald erste in Software gegossene Problemlösungen veröffentlichen wollen sind wir über jegliche Hilfe dankbar. Jeder der unser Vorhaben unterstützen und Teil des Projekts werden will ist herzlich dazu eingeladen. Jegliche Hilfe ist jederzeit willkommen, egal ob Programmierer oder Admins, ob Designer oder Podcaster und deren Hörer, die über uns berichten und unsere Software testen wollen. <file_sep>/FAMOS-Webpage/README.md Webpage -------- Die Website parst automatisch Markdown basierende Dateien. <br> Ihr findet diese unter dem Ordner: [docs](FAMOS-markdown-webpage/docs) dieser kann dort auch [verändert und angepasst](FAMOS-markdown-webpage/index.php#L6) werden. **Testpage**: [hier als Test zu finden (Wikibyte)](http://dev.wikibyte.org/FAMOS/) Im Footer ist ein random für die Projekt Cover (Werbung muss sein?). Zusätzlich klappt am Ende der Seite ein Info Footer mit den wichtigsten Links zum Projekt auf. ![Screenschot](home-podlove.png "Screenshot") ###Navigation Navigation & Links passen sich automatisch der Ordnung: "00"_"Page"_"Name" der Dateien aus dem Ordner [docs](FAMOS-markdown-webpage/docs) an. ![Navigation](Navi.png "Navigation") ###Startseite Die Einstellungen der Startseite befinden sich hierbei in der [index.md](FAMOS-markdown-webpage/docs/index.md) und können dort geändert und angepasst werden. ###Funktionen Es können die Funktionen von [Bootstrap](http://getbootstrap.com/css/) Bootstrap genutzt werden. Es gibt auch ein [Example](FAMOS-markdown-webpage/docs/100_Examples/01_Examples.md). ![Example](example.png) ##Einrichten **Settings:** Siehe unter [setup.php](FAMOS-markdown-webpage/setup.php) **Zum bearbeiten der Hauptseite:** Siehe unter [config.json](FAMOS-markdown-webpage/config.json) ##Übersicht (Standard ohne Podlove) ![Ohne Podlove](full.png) ###Responsive Design mit Bootstraps ![Mit Bootstrap 1](responsive.png) ![Mit Bootstrap 1](responsive2.png)
dd16c0b8b257451076ddb30b9e258fc0a0084704
[ "Markdown", "PHP" ]
13
PHP
McCouman/FAMOUS-website
4d0df1d498f4b887d58dec59ccd5db5f9e415cda
7e2f65b47c848c3858a994828bd62b949652f32e
refs/heads/master
<repo_name>YNursultan/Snippetbox-SE09<file_sep>/pkg/models/postgres/snippets.go package postgres import ( "context" "errors" "github.com/jackc/pgx/v4" "github.com/jackc/pgx/v4/pgxpool" "se09.com/pkg/models" "strconv" "time" ) type SnippetModel struct { DB *pgxpool.Pool } func (m *SnippetModel) Insert(title, content, expires string) (int, error) { stmt := "INSERT INTO snippets (title, content, created, expires)" + "VALUES($1, $2, $3, $4) RETURNING id" date, err := strconv.Atoi(expires) if err != nil { return 0, err } var id int result := m.DB.QueryRow(context.Background(), stmt, title, content, time.Now(), time.Now().AddDate(0, 0, date)).Scan(&id) if result != nil { return 0, err } return int(id), nil } func (m *SnippetModel) Get(id int) (*models.Snippet, error) { stmt := "SELECT id, title, content, created, expires FROM snippets WHERE expires > CLOCK_TIMESTAMP() AND id = $1" s := &models.Snippet{} err := m.DB.QueryRow(context.Background(), stmt, id).Scan(&s.ID, &s.Title, &s.Content, &s.Created, &s.Expires) if err != nil { if errors.Is(err, pgx.ErrNoRows) { return nil, models.ErrNoRecord } else { return nil, err } } return s, nil } func (m *SnippetModel) Latest() ([]*models.Snippet, error) { stmt := "SELECT id, title, content, created, expires FROM snippets WHERE expires > CLOCK_TIMESTAMP() ORDER BY created DESC LIMIT 10" rows, err := m.DB.Query(context.Background(), stmt) if err != nil { return nil, err } defer rows.Close() snippets := []*models.Snippet{} for rows.Next() { s := &models.Snippet{} err = rows.Scan(&s.ID, &s.Title, &s.Content, &s.Created, &s.Expires) if err != nil { return nil, err } snippets = append(snippets, s) } if err = rows.Err(); err != nil { return nil, err } return snippets, nil } <file_sep>/Dockerfile FROM golang:1.15 RUN mkdir -p /usr/src/app/ ADD . /usr/src/app/ WORKDIR /usr/src/app/ EXPOSE 4000 EXPOSE 5432 EXPOSE 8989 COPY . /usr/src/app/ RUN go mod download #CMD go run ./cmd/web #FROM golang:1.15 # #RUN mkdir -p /app #ADD . /app #WORKDIR /app #ENTRYPOINT /app # #EXPOSE 4000 #EXPOSE 5432 #EXPOSE 8989 # #COPY . /app #RUN go mod download # #FROM alpine:latest #RUN apk --no-cache add ca-certificates #WORKDIR /root/ #COPY --from=0 /app . #CMD ./app
169f15c7ef23bb0142430b386a021a68ed9455fe
[ "Go", "Dockerfile" ]
2
Go
YNursultan/Snippetbox-SE09
2dfc5bee29f8a2ff23c3467ad8d98331c0810c74
ca90bb8371e9be8c5db07aaf18349c87a7b8c497
refs/heads/master
<file_sep>package com.company; public class Main { public static void main(String[] args) { System.out.println("bu-ha-ha-ha"); } }
3811bb2f4e7cf972a5ed9830d96f0d9d3b200a24
[ "Java" ]
1
Java
odzio33/javaBean
a353e5a28bf658512673b74e995b5e0e5b962636
0046c3752588dae523ae70e5a0e65ca767f077e5
refs/heads/master
<repo_name>BaobabHealthTrust/MalawiBLIS<file_sep>/htdocs/update/db/update_scripts/29.CultureWorksheet_Table.sql CREATE TABLE `culture_worksheet` ( `id` int(11) NOT NULL AUTO_INCREMENT, `userId` int(11) DEFAULT NULL, `testId` int(11) DEFAULT NULL, `observation` varchar(1000) NOT NULL, `time_stamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ); <file_sep>/htdocs/ajax/lab_config_lifespan_update.php <?php # # Baobab Health Trust, Lilongwe, Dev: <NAME> # Updates goal Lifespan values for tests # Called via Ajax from lab_config_home.php # include("../includes/db_lib.php"); $lab_config_id = $_REQUEST['lid']; $lab_config = get_lab_config_by_id($lab_config_id); $t_s = $_REQUEST['stype']; $lsp_value_list = $_REQUEST['lsp']; $lsp_unit_list = $_REQUEST['unit']; $count = 0; foreach($t_s as $key) { $t_id = explode('|', $key)[0]; $s_id = explode('|', $key)[1]; $curr_lsp_value = $lsp_value_list[$count]; $curr_lsp_value = preg_replace("/[^0-9]/" ,"", $curr_lsp_value); if(trim($curr_lsp_value) == "") { # Empty lifespan entry $count++; continue; } if($lsp_unit_list[$count] == 2) { # Multiply by 24 to store in hours $curr_lsp_value *= 24; } echo $lab_config->updateGoalLifespanValue($t_id, $s_id, $curr_lsp_value).'<br />'; $count++; } ?> <file_sep>/htdocs/update/baobab_update/add_custom_test_type_columns.sql SET FOREIGN_KEY_CHECKS=0; CREATE TABLE IF NOT EXISTS `container_type` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` VARCHAR(255) NOT NULL, `description`VARCHAR(255), PRIMARY KEY (`id`) ) ENGINE=InnoDB; CREATE TABLE IF NOT EXISTS `department` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` VARCHAR(255) NOT NULL, `test_category_id` int(11) unsigned REFERENCES test_category(`test_category_id`), `active` tinyint DEFAULT 0, `description` VARCHAR(255), PRIMARY KEY (`id`) ) ENGINE=innoDB; CREATE TABLE IF NOT EXISTS `location` ( `id` int(11) NOT NULL AUTO_INCREMENT, `department_id` int(11) NOT NULL FOREIGN KEY REFERENCES department(`department_id`), `device_mac_addr` VARCHAR(255), `active` tinyint DEFAULT 0, PRIMARY KEY (`id`) ) ENGINE=innoDB; CREATE TABLE IF NOT EXISTS `state` ( `state_id` int(11) NOT NULL AUTO_INCREMENT, `name` VARCHAR(255) NOT NULL, `description` VARCHAR(255), PRIMARY KEY (`state_id`) ) ENGINE=innoDB; DROP TABLE IF EXISTS `activity_state`; CREATE TABLE IF NOT EXISTS `activity_state` ( `activity_state_id` int(11) NOT NULL AUTO_INCREMENT, `state_id` int(11) NOT NULL, `test_id` int(10) unsigned FOREIGN KEY REFERENCES test(`test_id`), `specimen_id` int(10) unsigned FOREIGN KEY REFERENCES specimen(`specimen_id`), `date` datetime DEFAULT NULL, `reason` VARCHAR(255), `location` VARCHAR(255), `user_id` int(10) FOREIGN KEY REFERENCES user(`user_id`), `doctor` VARCHAR(255), `comments` VARCHAR(255), PRIMARY KEY (`activity_state_id`) ) ENGINE=innoDB; ALTER TABLE `test_type` ADD COLUMN `loinc_code` VARCHAR(45) NULL DEFAULT NULL AFTER `description`; ALTER TABLE `test_type` ADD COLUMN `test_code` VARCHAR(45) NULL DEFAULT NULL AFTER `loinc_code`; ALTER TABLE `test_type` ADD COLUMN `container_type` int(11) NOT NULL FOREIGN KEY REFERENCES container_type(`id`); set FOREIGN_KEY_CHECKS=1; <file_sep>/htdocs/api/remote_login.php <?php require_once "authenticate.php"; $result = array(); $result['token'] = session_id(); $result['name'] = $_SESSION['user_actualname']; $result['username'] = $_SESSION['username']; echo json_encode($result); ?> <file_sep>/README.md BLIS-Malawi ==== BLIS-Malawi is a customized version of C4G BLIS, specifically for Malawian Public Hospital Laboratories. <file_sep>/htdocs/update/db/update_scripts/24.Test_measure.sql -- phpMyAdmin SQL Dump -- version 4.0.4.1 -- http://www.phpmyadmin.net -- -- Host: 127.0.0.1 -- Generation Time: Feb 27, 2014 at 08:55 AM -- Server version: 5.5.32 -- PHP Version: 5.4.19 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; 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 utf8 */; -- -- Database: `blis_301` -- -- -------------------------------------------------------- -- -- Table structure for table `test_measure` -- CREATE TABLE IF NOT EXISTS `test_measure` ( `tm_id` int(11) NOT NULL AUTO_INCREMENT, `test_id` int(11) NOT NULL, `lab_no` int(11) NOT NULL, `measure_id` int(11) NOT NULL, `result` text NOT NULL, PRIMARY KEY (`tm_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=281 ; /*!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>/htdocs/api/Net.old/HL7/Types/FN.php <?php class Net_HL7_Types_FN { private $surname; private $ownSurnamePrefix; private $ownSurname; private $surnamePrefixFromPartnerSpouse; private $surnameFromPartnerSpouse; public function __construct($components) { $this->surname = (empty($components[0])) ? "" : $components[0]; $this->ownSurnamePrefix = (empty($components[1])) ? "" : $components[1]; $this->ownSurname = (empty($components[2])) ? "" : $components[2]; $this->surnamePrefixFromPartnerSpouse = (empty($components[3])) ? "" : $components[3]; $this->surnameFromPartnerSpouse = (empty($components[4])) ? "" : $components[4]; } /** * @return Net_HL7_Types_FN */ public static function template() { return new Net_HL7_Types_FN(array()); } /** * @return array */ public function toArray() { $components = array(); $components[0] = $this->surname; $components[1] = $this->ownSurnamePrefix; $components[2] = $this->ownSurname; $components[3] = $this->surnamePrefixFromPartnerSpouse; $components[4] = $this->surnameFromPartnerSpouse; return $components; } /** * @param $surname string */ public function setSurname($surname) { $this->surname = $surname; } /** * @return string */ public function getSurname() { return $this->surname; } /** * @param $ownSurnamePrefix string */ public function setOwnSurnamePrefix($ownSurnamePrefix) { $this->ownSurnamePrefix = $ownSurnamePrefix; } /** * @return string */ public function getOwnSurnamePrefix() { return $this->ownSurnamePrefix; } /** * @param $ownSurname string */ public function setOwnSurname($ownSurname) { $this->ownSurname = $ownSurname; } /** * @return string */ public function getOwnSurname() { return $this->ownSurname; } /** * @param $surnamePrefixFromPartnerSpouse string */ public function setSurnamePrefixFromPartnerSpouse($surnamePrefixFromPartnerSpouse) { $this->surnamePrefixFromPartnerSpouse = $surnamePrefixFromPartnerSpouse; } /** * @return string */ public function getSurnamePrefixFromPartnerSpouse() { return $this->surnamePrefixFromPartnerSpouse; } /** * @param $surnameFromPartnerSpouse string */ public function setSurnameFromPartnerSpouse($surnameFromPartnerSpouse) { $this->surnameFromPartnerSpouse = $surnameFromPartnerSpouse; } /** * @return string */ public function getSurnameFromPartnerSpouse() { return $this->surnameFromPartnerSpouse; } } ?> <file_sep>/htdocs/ajax/rejection_reason_update.php <?php # # Main page for rejection phase info # Called via Ajax from rejection_reason_edit.php # include("../includes/db_lib.php"); include("../lang/lang_xml2php.php"); putUILog('rejection_reason_update', 'X', basename($_SERVER['REQUEST_URI'], ".php"), 'X', 'X', 'X'); $updated_entry = new SpecimenRejectionReasons(); $updated_entry->reasonId = $_REQUEST['tcid']; $updated_entry->description = $_REQUEST['description']; $updated_entry->phase = $_REQUEST['phase']; $reff = 1; update_rejection_reason($updated_entry); # Update locale XML and generate PHP list again. if($CATALOG_TRANSLATION === true) update_rejection_reason_xml($updated_entry->reasonId, $updated_entry->description); ?><file_sep>/htdocs/update/db/update_scripts/30. Drugs_susceptibility.sql -- -- Table structure for table `drugs` -- CREATE TABLE IF NOT EXISTS `drugs` ( `drug_id` int(11) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(45) NOT NULL DEFAULT '', `description` varchar(100) DEFAULT NULL, `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `disabled` int(10) unsigned NOT NULL DEFAULT '0', PRIMARY KEY (`drug_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Table structure for table `drug_susceptibility` -- CREATE TABLE IF NOT EXISTS `drug_susceptibility` ( `id` int(11) NOT NULL AUTO_INCREMENT, `userId` int(11) NOT NULL, `testId` int(11) NOT NULL, `drugId` int(11) NOT NULL, `zone` int(11) NOT NULL, `interpretation` varchar(1) NOT NULL, `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `drug_test` -- CREATE TABLE IF NOT EXISTS `drug_test` ( `test_type_id` int(11) unsigned NOT NULL DEFAULT '0', `drug_id` int(11) unsigned NOT NULL DEFAULT '0', `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, KEY `test_type_id` (`test_type_id`), KEY `drug_id` (`drug_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; <file_sep>/htdocs/api/Net.old/HL7/Types/TS.php <?php class Net_HL7_Types_TS { private $ts; private $year, $month, $day, $hour, $minute, $seconds; public function __construct() { $this->ts = strftime("%Y%m%d%H%M%S"); } public function setDateTime($year, $month, $day, $hour = 0, $minute = 0, $seconds = 0) { $this->year = $year; $this->month = $month; $this->day = $day; $this->hour = $hour; $this->minute = $minute; $this->seconds = $seconds; $this->updateTs(); } private function updateTs() { $unixTime = mktime($this->hour, $this->minute, $this->seconds, $this->month, $this->day, $this->year); $this->ts = strftime("%Y%m%d%H%M%S", $unixTime); } /** * @return String **/ function toTsString() { return $this->ts; } }<file_sep>/BLIS_Kenya_Tables_Truncate.sql SET foreign_key_checks = 0; TRUNCATE TABLE access_log; TRUNCATE TABLE access_type; TRUNCATE TABLE audit_trail; TRUNCATE TABLE bills; TRUNCATE TABLE bills_test_association; TRUNCATE TABLE comment; TRUNCATE TABLE custom_field_type; TRUNCATE TABLE delay_measures; TRUNCATE TABLE external_lab_request; TRUNCATE TABLE import_log; TRUNCATE TABLE inv_reagent; TRUNCATE TABLE inv_supply; TRUNCATE TABLE inv_usage; TRUNCATE TABLE patient; TRUNCATE TABLE patient_custom_data; TRUNCATE TABLE patient_custom_field; TRUNCATE TABLE patient_daily; TRUNCATE TABLE payments; TRUNCATE TABLE rejected_specimen; TRUNCATE TABLE rejection_phases; TRUNCATE TABLE rejection_reasons; TRUNCATE TABLE removal_record; TRUNCATE TABLE specimen; TRUNCATE TABLE stock_content; TRUNCATE TABLE stock_details; TRUNCATE TABLE test; TRUNCATE TABLE unit; DELETE FROM user WHERE username <> 'testlab1_admin'; TRUNCATE TABLE version_data; TRUNCATE TABLE worksheet_custom; TRUNCATE TABLE worksheet_custom_test; TRUNCATE TABLE worksheet_custom_userfield; SET foreign_key_checks = 1; <file_sep>/htdocs/api/Net.old/HL7/Types/generatePhpType.sh #!/bin/bash ./generatePhpType.pl CE identifier,text,nameOfCodingSystem,alternateIdentifier,alternateTest,nameOfAlternateCodingSystem > CE.php ./generatePhpType.pl CQ quantity,units > CQ.php ./generatePhpType.pl CWE identifier,text,nameOfCodingSystem,alternateIdentifier,alternateText,nameOfAlternateCodingSystem,codingSystemVersionId,alternateCodingSystemVersionId,originalText >CWE.php ./generatePhpType.pl CX idNumber,checkDigit,checkDigitScheme,assigningAuthority,identifierTypeCode,assigningFacility,effectiveDate > CX.php ./generatePhpType.pl ED sourceApplication,typeOfData,dataSubtype,encoding,data >ED.php ./generatePhpType.pl EI entityIdentifier,namespaceID,universalId,universalIdType > EI.php ./generatePhpType.pl EIP placerAssignedIdentifier,fillerAssignedIdentifier > EIP.php ./generatePhpType.pl FN surname,ownSurnamePrefix,ownSurname,surnamePrefixFromPartnerSpouse,surnameFromPartnerSpouse > FN.php ./generatePhpType.pl HD namespaceId,universalId,universalIdType > HD.php ./generatePhpType.pl MSG messageCode,triggerEvent,messageStructure > MSG.php ./generatePhpType.pl PL pointOfCare,room,bed,facility,locationStatus,personLocationType,building,floor,locationDescription,comprehensiveLocationIdentifier,assigningAuthorityForLocation > PL.php ./generatePhpType.pl PRL parentObservationIdentifier,parentObservationSubIdentifier,parentObservationValueDescriptor > PRL.php ./generatePhpType.pl PT processingId,processingMode > PT.php ./generatePhpType.pl RP pointer,applicationId,namespaceId,universalId,universalIdType,typeOfData,subtype > RP.php ./generatePhpType.pl SAD streetOrMailingAddress,streetName,dwellingNumber > SAD.php ./generatePhpType.pl SN comparator,num1,separatorSuffix,num2 >SN.php ./generatePhpType.pl VID versionId,internationalizationCode,internationalVersionId > VID.php ./generatePhpType.pl XAD streetAddress,otherDesignation,city,stateOrProvince,zipOrPostalCode,country,addressType,otherGeographicDesignation,countyParishCode,censusTract,addressRepresentationCode > XAD.php ./generatePhpType.pl XCN idNumber,familyName,lastNamePrefix,givenName,middleInitialName,suffix,prefix,degree,sourceTable,assigning authority,nameTypeCode,identifierCheckDigit,codeIdentifying,checkDigitSchemeEmployed,identifierTypeCode,assigningFacility,nameRepresentationCode > XCN.php ./generatePhpType.pl XON organizationName,organizationNameTypeCode,checkDigit,checkDigitScheme,assigningAuthority,identifierTypeCode,assigningFacility,nameRepresentationCode,organizationIdentifier > XON.php ./generatePhpType.pl XPN familyName,givenName,middleInitialOrName,Suffix,Prefix,degree,nameTypeCode,nameRepresentationCode,nameContext > XPN.php ./generatePhpType.pl XON namespaceId,universalId,universalIdType > XON.php echo "<?php" > Types.php for i in `ls *.php | grep -v Types`; do echo "include_once(\"Net/HL7/Types/$i\");" >> Types.php done; echo "?>" >> Types.php <file_sep>/htdocs/api/updateHL7Order.php <?php require_once "authenticate.php"; require_once "Net/HL7/Segments/MSH.php"; require_once "Net/HL7/Message.php"; $debug = false; if(!isset($_REQUEST['hl7']) && !$debug) { echo -2; return; } if(!$debug){ $request=$_REQUEST['hl7']; } else { $request = "MSH|^~&||KCH^2.16.840.1.113883.3.5986.2.15^ISO||KCH^2.16.840.1.113883.3.5986.2.15^ISO|20150205215555||ORU^R01^ORU_R01|20150205215555|T|2.5.1\nPID|1||P700809902584||Test Patient ||19660101|M\nPV1|\nORC||||||||||1^Super^User|||^^^^^^^^MEDICINE||||||||KCH\nTQ1|1||||||||R^Routine^HL70485\nOBR|1|||Sputum Tb microscopy^Sputum Tb microscopy^LOINC|||20150205215555||||||Rule out diagnosis|||439234^Moyo^Chris|||||||||Tested\nOBX|1|CE|263^Sputum Tb microscopy^ISO||^Present||||||F|||20150205215555||439234^Moyo^Chris|||20150205215555||||KCH Laboratory|^^Lilongwe^^^Malawi|Limula^Henry\nSPM|1|||Sputum^Sputum"; } $msg = new Net_HL7_Message($request); $msh = $msg->getSegmentsByName("MSH"); $pid = $msg->getSegmentsByName("PID"); $orc = $msg->getSegmentsByName("ORC"); $tq1 = $msg->getSegmentsByName("TQ1"); $obr = $msg->getSegmentsByName("OBR"); $spm = $msg->getSegmentsByName("SPM"); $obx = $msg->getSegmentsByName("OBX"); $spm = $msg->getSegmentsByName("SPM"); $nte = $msg->getSegmentsByName("NTE"); $sendingFacility = $msh[0]->getField(4)[0]; // MSH.04 $receivingFacility = $msh[0]->getField(6)[0]; // MSH.06 $messageDatetime = $msh[0]->getField(7); // MSH.07 $messageType = $msh[0]->getField(9)[2]; // MSH.09 $messageControlID = $msh[0]->getField(10); // MSH.10 $processingID = $msh[0]->getField(11); // MSH.11 $hl7VersionID = $msh[0]->getField(12); // MSH.12 $healthFacilitySiteCodeAndName = (count($orc) > 0 ? $orc[0]->getField(21) : null); // ORC.21 $pidSetID = (count($pid) > 0 ? $pid[0]->getField(1) : null); // PID.01 $nationalID = (count($pid) > 0 ? $pid[0]->getField(3) : null); // PID.03 $patientName = (count($pid) > 0 ? $pid[0]->getField(5)[1] : "") . " " . (count($pid) > 0 ? $pid[0]->getField(5)[2] : "") . " " . (count($pid) > 0 ? $pid[0]->getField(5)[0] : "") . " " . (count($pid) > 0 ? $pid[0]->getField(5)[3] : ""); // PID.05 $dateOfBirth = (count($pid) > 0 ? $pid[0]->getField(7) : null); // PID.07 $gender = (count($pid) > 0 ? $pid[0]->getField(8) : null); // PID.08 $spmSetID = (count($spm) > 0 ? $spm[0]->getField(1) : null); // SPM.01 $accessionNumber = (count($spm) > 0 ? $spm[0]->getField(2) : null); // SPM.02 $typeOfSample = (count($spm) > 0 ? $spm[0]->getField(4)[1] : null); // SPM.04 $rejectionReason = (count($spm) > 0 ? $spm[0]->getField(21)[1] : null); // SPM.21 $enteredBy = (count($orc) > 0 ? $orc[0]->getField(10)[2] : "") . " " . (count($orc) > 0 ? $orc[0]->getField(10)[1] : "") . " (" . (count($orc) > 0 ? $orc[0]->getField(10)[0] : "") . ")"; // ORC.10 $enterersLocation = (count($orc) > 0 ? $orc[0]->getField(13) : null); // ORC.13 $tq1SetID = (count($tq1) > 0 ? $tq1[0]->getField(1) : null); // TQ1.01 $priority = (count($tq1) > 0 ? $tq1[0]->getField(9) : null); // TQ1.09 $obrSetID = (count($obr) > 0 ? $obr[0]->getField(1) : null); // OBR.01 $testCode = (count($obr) > 0 ? $obr[0]->getField(4)[0] : null); // OBR.04 $timestampForSpecimenCollection = (count($obr) > 0 ? $obr[0]->getField(7) : null); // OBR.07 $reasonTestPerformed = (count($obr) > 0 ? $obr[0]->getField(13) : null); // OBR.13 $whoOrderedTest = (count($obr) > 0 ? $obr[0]->getField(16)[2] : "") . " " . (count($obr) > 0 ? $obr[0]->getField(16)[1] : "") . " (" . (count($obr) > 0 ? $obr[0]->getField(1)[0] : "") . ")"; // OBR.16 $testName = (count($obr) > 0 ? $obr[0]->getField(4)[1] : null); $result = (count($obx) > 0 ? $obx[0]->getField(5) : null); $state = (count($nte[0]->getField(3)) > 1 ? $nte[0]->getField(3)[0] : $nte[0]->getField(3)); $comments = (count($nte) > 0 && gettype($nte[0]->getField(3)) == "array" ? $nte[0]->getField(3)[1] : null); $record = array( "state" => $state, "location" => $enterersLocation, "doctor" => $whoOrderedTest, "date" => $messageDatetime, "reason" => $reasonTestPerformed, "user_id" => $_SESSION['user_id'], "result" => $result, "comments" => $comments, "rejectionReason" => $rejectionReason ); $spec = get_specimens_by_accession($accessionNumber); $patient = get_patient_by_sp_id($spec[0]->specimenId); $finalResult = array( "sendingFacility" => $sendingFacility, "receivingFacility" => $receivingFacility, "messageDatetime" => $messageDatetime, "messageType" => $messageType, "messageControlID" => $messageControlID, "processingID" => $processingID, "hl7VersionID" => $hl7VersionID, "tests" => array(), "healthFacilitySiteCodeAndName" => $healthFacilitySiteCodeAndName, "pidSetID" => $pidSetID, "nationalID" => ($nationalID == null ? $patient->surrogateId : $nationalID), "patientName" => ($patientName == null ? $patient->name : $patientName), "dateOfBirth" => ($dateOfBirth == null ? $patient->dob : $dateOfBirth), "gender" => ($gender == null ? $patient->sex : $gender), "spmSetID" => $spmSetID, "accessionNumber" => $accessionNumber, "typeOfSample" => $typeOfSample, "tq1SetID" => $tq1SetID, "priority" => $priority, "whoOrderedTest" => $response["whoOrderedTest"] ); // $result = API::update_order($record, $accessionNumber, $testName); for($i = 0; $i < sizeof($obr); $i++){ $obrSetID = $obr[$i]->getField(1); // OBR.01 $testCode = $obr[$i]->getField(4)[0]; // OBR.04 $timestampForSpecimenCollection = $obr[$i]->getField(7); // OBR.07 $reasonTestPerformed = $obr[$i]->getField(13); // OBR.13 $tq1SetID = (count($tq1) > $i ? $tq1[$i]->getField(1) : null); // TQ1.01 $priority = (count($tq1) > $i ? $tq1[$i]->getField(9) : null); // TQ1.09 $obrSetID = (count($obr) > $i ? $obr[$i]->getField(1) : null); // OBR.01 $testCode = (count($obr) > $i ? $obr[$i]->getField(4)[0] : null); // OBR.04 $timestampForSpecimenCollection = (count($obr) > $i ? $obr[$i]->getField(7) : null); // OBR.07 $reasonTestPerformed = (count($obr) > $i ? $obr[$i]->getField(13) : null); // OBR.13 $whoOrderedTest = (count($obr) > $i ? $obr[$i]->getField(16)[2] : "") . " " . (count($obr) > 0 ? $obr[$i]->getField(16)[1] : "") . " (" . (count($obr) > 0 ? $obr[$i]->getField(1)[0] : "") . ")"; // OBR.16 $testName = (count($obr) > $i ? $obr[$i]->getField(4)[1] : null); $result = (count($obx) > $i ? $obx[$i]->getField(5) : null); // $state = (count($nte[$i]->getField(3)) > $i ? $nte[$i]->getField(3)[0] : $nte[$i]->getField(3)); $state = (count($nte) > $i && gettype($nte[$i]->getField(3)) == "array" ? $nte[$i]->getField(3)[0] : $nte[$i]->getField(3)); $comments = (count($nte) > $i && gettype($nte[$i]->getField(3)) == "array" ? $nte[$i]->getField(3)[1] : null); $set = array( "obrSetID" => $obrSetID, "testCode" => $testCode, "testName" => $testName, "timestampForSpecimenCollection" => $timestampForSpecimenCollection, "reasonTestPerformed" => $reasonTestPerformed, "enteredBy" => $enteredBy, "enterersLocation" => $enterersLocation, "result" => $result, "status" => $state, "comments" => $comments, "rejectionReason" => $rejectionReason ); $record = array( "state" => $state, "location" => $enterersLocation, "doctor" => $whoOrderedTest, "date" => $messageDatetime, "reason" => $reasonTestPerformed, "user_id" => $_SESSION['user_id'], "result" => $result, "comments" => $comments, "rejectionReason" => $rejectionReason ); $result = API::update_order($record, $accessionNumber, $testName); array_push($finalResult["tests"], $set); } if($result){ echo json_encode($finalResult); } else { echo json_encode($result); } ?> <file_sep>/htdocs/api/Net.old/HL7/Types/EIP.php <?php class Net_HL7_Types_EIP { private $placerAssignedIdentifier; private $fillerAssignedIdentifier; public function __construct($components) { $this->placerAssignedIdentifier = (empty($components[0])) ? "" : $components[0]; $this->fillerAssignedIdentifier = (empty($components[1])) ? "" : $components[1]; } /** * @return Net_HL7_Types_EIP */ public static function template() { return new Net_HL7_Types_EIP(array()); } /** * @return array */ public function toArray() { $components = array(); $components[0] = $this->placerAssignedIdentifier; $components[1] = $this->fillerAssignedIdentifier; return $components; } /** * @param $placerAssignedIdentifier string */ public function setPlacerAssignedIdentifier($placerAssignedIdentifier) { $this->placerAssignedIdentifier = $placerAssignedIdentifier; } /** * @return string */ public function getPlacerAssignedIdentifier() { return $this->placerAssignedIdentifier; } /** * @param $fillerAssignedIdentifier string */ public function setFillerAssignedIdentifier($fillerAssignedIdentifier) { $this->fillerAssignedIdentifier = $fillerAssignedIdentifier; } /** * @return string */ public function getFillerAssignedIdentifier() { return $this->fillerAssignedIdentifier; } } ?> <file_sep>/htdocs/update/db/update_scripts/28.showCultureWorksheet_Column.sql ALTER TABLE `test_type` ADD COLUMN `showCultureWorkSheet` VARCHAR(45) NULL DEFAULT NULL <file_sep>/htdocs/api/remote_login_check.php <?php include "../includes/db_lib.php"; $token = $_REQUEST['token']; $username = $_REQUEST['username']; $query = "SELECT cur_token FROM user WHERE username = '$username' AND COALESCE(cur_token, '') != ''"; $cur_token = query_associative_one($query); $result = Array(false); if ($cur_token && $cur_token['cur_token'] == $token){ $result = Array(true); } echo json_encode($result); ?> <file_sep>/htdocs/api/remote_calls.php <?php require_once "authenticate.php"; if(isset($_REQUEST['action'])) { if($_REQUEST['action'] == 'get_panel_tests_by_loinc_code') { if(!isset($_REQUEST['loinc_code'])) { echo -2; return; } else { $result = API::get_panel_tests_by_accession_number($_REQUEST["loinc_code"]); echo json_encode($result); return; } // Expects calls made as: /api/remote_calls?action=get_test_type_measure_by_patient&loinc_code=LOINC_CODE&accession_num=ACCESSION_NUMBER } else if($_REQUEST['action'] == 'get_test_type_measure_by_accession_num') { if(!isset($_REQUEST['loinc_code']) || !isset($_REQUEST['accession_num'])) { echo -2; return; } else { $result = API::get_test_type_measure_ranges($_REQUEST["loinc_code"], $_REQUEST["accession_num"]); echo json_encode($result); return; } // Expects calls made as: /api/remote_calls?action=get_test_type_measure&id=ACCESSION_NUMBER } else if ($_REQUEST['action'] == 'get_test_type_measure') { if(!isset($_REQUEST['id'])) { echo -2; return; } else { getTestTypeMeasure($_REQUEST["id"]); return; } // Expects calls made as: /api/remote_calls?action=get_panel_info&loinc_code=LOINC_CODE&accession_num=ACCESSION_NUMBER } else if ($_REQUEST['action'] == 'get_panel_info'){ if(!isset($_REQUEST['loinc_code']) || !isset($_REQUEST['accession_num'])) { echo -2; return; } else { $result = API::get_panel_info($_REQUEST['loinc_code'], $_REQUEST['accession_num']); echo json_encode($result); return; } }else if($_REQUEST['action'] == 'by_accession_num'){ if(!isset($_REQUEST['id'])) { echo -2; return; } else { getByAccessionNum($_REQUEST["id"]); return; } } else if($_REQUEST['action'] == 'get_patient_by_sp_id') { if(!isset($_REQUEST['id'])) { echo -2; return; } else { getPatientBySpId($_REQUEST["id"]); return; } } else if($_REQUEST['action'] == 'get_tests_by_specimen_id') { if(!isset($_REQUEST['id'])) { echo -2; return; } else { getTestsBySpecimenId($_REQUEST["id"]); return; } //http://localhost/blis/htdocs/api/remote_calls.php?action=get_user_details&username=username }else if($_REQUEST['action'] == 'get_user_details') { if(!isset($_REQUEST['username'])) { echo -2; return; } else { getUserDetails($_REQUEST["username"]); return; } } } function getTestTypeMeasure($id){ $response = get_test_type_measure($id); echo json_encode($response); } function getByAccessionNum($q){ $specimens = search_specimens_by_accession_exact($q); $result = array(); for($i = 0; $i < count($specimens); $i++) { $id = $specimens[$i]->specimenId; $tests = get_tests_by_specimen_id($id); $type = get_specimen_type_by_id($specimens[$i]->specimenTypeId); for($t = 0; $t < count($tests); $t++) { $test = get_test_type_measure($tests[$t]->testTypeId); $name = get_test_name_by_id($tests[$t]->testTypeId); $loincCode = get_loinc_code_by_id($tests[$t]->testTypeId); $params = array( "test_name" => $name, "accession_num" => $q ); $status = API::getStatus($params); $result["$name|".$tests[$t]->testTypeId."|".$type->name."|".$loincCode."|".$status."|".$tests[$t]->isPanel] = $test; } } echo json_encode($result); } function getPatientBySpId($id){ $spec = get_specimens_by_accession($id); $response = get_patient_by_sp_id($spec[0]->specimenId); echo json_encode($response); } function getTestsBySpecimenId($id){ $spec = get_specimens_by_accession($id); echo json_encode($spec); $response = get_tests_by_specimen_id($spec[0]->specimenId); echo json_encode($response); } function getuserDetails($user_id){ $details = API::get_user_details($user_id); echo json_encode($details); } ?> <file_sep>/htdocs/api/remote_logout.php <?php include "../includes/db_lib.php"; $username = $_REQUEST['username']; $query = "UPDATE user SET cur_token = NULL WHERE username = '$username'"; query_update($query); echo json_encode(Array(true)); ?> <file_sep>/htdocs/reports/reports_user_stats_individual.php <?php # # Main page for showing disease report and options to export # Called via POST from reports.php # include("redirect.php"); include("includes/db_lib.php"); include("includes/stats_lib.php"); include("includes/script_elems.php"); LangUtil::setPageId("reports"); $script_elems = new ScriptElems(); $script_elems->enableJQuery(); $script_elems->enableFlotBasic(); $script_elems->enableFlipV(); $script_elems->enableTableSorter(); $script_elems->enableLatencyRecord(); ?> <html> <head> <script type="text/javascript" src="js/table2CSV.js"></script> <script type='text/javascript'> var curr_orientation = 0; function export_as_word(div_id) { var html_data = $('#'+div_id).html(); $('#word_data').attr("value", html_data); //$('#export_word_form').submit(); $('#word_format_form').submit(); } function export_as_pdf(div_id) { var content = $('#'+div_id).html(); $('#pdf_data').attr("value", content); $('#pdf_format_form').submit(); } function export_as_txt(div_id) { var content = $('#'+div_id).html(); $('#txt_data').attr("value", content); $('#txt_format_form').submit(); } function export_as_csv(table_id, table_id2) { var content = $('#'+table_id).table2CSV({delivery:'value'}) + '\n\n' + $('#'+table_id2).table2CSV({delivery:'value'}); $("#csv_data").val(content); $('#csv_format_form').submit(); } function print_content(div_id) { var DocumentContainer = document.getElementById(div_id); var WindowObject = window.open("", "PrintWindow", "toolbars=no,scrollbars=yes,status=no,resizable=yes"); WindowObject.document.writeln(DocumentContainer.innerHTML); WindowObject.document.close(); WindowObject.focus(); WindowObject.print(); WindowObject.close(); //javascript:window.print(); } $(document).ready(function(){ $('#report_content_table').tablesorter(); $("input[name='do_landscape']").click( function() { change_orientation(); }); }); function change_orientation() { var do_landscape = $("input[name='do_landscape']:checked").attr("value"); if(do_landscape == "Y" && curr_orientation == 0) { $('#report_config_content').removeClass("portrait_content"); $('#report_config_content').addClass("landscape_content"); curr_orientation = 1; } if(do_landscape == "N" && curr_orientation == 1) { $('#report_config_content').removeClass("landscape_content"); $('#report_config_content').addClass("portrait_content"); curr_orientation = 0; } } </script> </head> <body> <div id='report_content'> <link rel='stylesheet' type='text/css' href='css/table_print.css' /> <style type='text/css'> div.editable { /*padding: 2px 2px 2px 2px;*/ margin-top: 2px; width:900px; height:20px; } div.editable input { width:700px; } div#printhead { position: fixed; top: 0; left: 0; width: 100%; height: 100%; padding-bottom: 5em; margin-bottom: 100px; display:none; } @media all { .page-break { display:none; } } @media print { #options_header { display:none; } /* div#printhead { display: block; } */ div#docbody { margin-top: 5em; } } .landscape_content {-moz-transform: rotate(90deg) translate(300px); } .portrait_content {-moz-transform: translate(1px); rotate(-90deg) } </style> <form name='word_format_form' id='word_format_form' action='export_word.php' method='post' target='_blank'> <input type='hidden' name='data' value='' id='word_data' /> <input type='hidden' name='lab_id' value='<?php echo $lab_config_id; ?>' id='lab_id'> </form> <form name='pdf_format_form' id='pdf_format_form' action='export_pdf.php' method='post' target='_blank'> <input type='hidden' name='data' value='' id='pdf_data' /> </form> <form name='txt_format_form' id='txt_format_form' action='export_txt.php' method='post' target='_blank'> <input type='hidden' name='data' value='' id='txt_data' /> </form> <form name='csv_format_form' id='csv_format_form' action='export_csv.php' method='post' target='_blank'> <input type='hidden' name='csv_data' id='csv_data'> </form> <input type='radio' name='do_landscape' value='N' <?php //if($report_config->landscape == false) echo " checked "; echo " checked "; ?>>Portrait</input> &nbsp;&nbsp; <input type='radio' name='do_landscape' value='Y' <?php //if($report_config->landscape == true) echo " checked "; ?>>Landscape</input>&nbsp;&nbsp; <input type='button' onclick="javascript:print_content('export_content');" value='<?php echo LangUtil::$generalTerms['CMD_PRINT']; ?>'></input> &nbsp;&nbsp; <!-- <input type='button' onclick="javascript:export_as_word('export_content');" value='<?php echo LangUtil::$generalTerms['CMD_EXPORTWORD']; ?>'></input> --> &nbsp;&nbsp; <input type='button' onclick="javascript:export_as_pdf('export_content');" value='<?php echo LangUtil::$generalTerms['CMD_EXPORTPDF']; ?>'></input> &nbsp;&nbsp; <!--input type='button' onclick="javascript:export_as_txt('export_content');" value='<?php echo LangUtil::$generalTerms['CMD_EXPORTTXT']; ?>'></input> &nbsp;&nbsp;--> <input type='button' onclick="javascript:export_as_csv('report_content_header', 'report_content_table');" value='<?php echo LangUtil::$generalTerms['CMD_EXPORTCSV']; ?>'></input> &nbsp;&nbsp; <!-- <input type='button' onclick="javascript:window.close();" value='<?php echo LangUtil::$generalTerms['CMD_CLOSEPAGE']; ?>'></input> --> </form> <hr> <?php /* <form name='export_word_form' id='export_word_form' action='export_word.php' method='post' target='_blank'> <input type='hidden' value='' id='word_data' name='data'></input> </form> */ ?> <div id='export_content'> <link rel='stylesheet' type='text/css' href='css/table_print.css' /> <div id='report_config_content'> <b><?php echo "User Log"; ?></b> <br><br> <?php $lab_config_id = $_REQUEST['location']; $lab_config = LabConfig::getById($lab_config_id); if($lab_config == null) { echo LangUtil::$generalTerms['MSG_NOTFOUND']; return; } $date_from = $_REQUEST['from-report-date']; $date_to = $_REQUEST['to-report-date']; $ust = new UserStats(); //echo "<pre>"; //echo "</pre>"; $log_type = $_REQUEST['log_type']; $user_id = $_REQUEST['user_id']; $uiinfo = "from=".$date_from."&to=".$date_to."&ud=".$user_id."&ld=".$log_type; putUILog('reports_user_stats_individual', $uiinfo, basename($_SERVER['REQUEST_URI'], ".php"), 'X', 'X', 'X'); $user_obj = get_user_by_id($user_id); ?> <table id='report_content_header' class="print_entry_border draggable"> <tbody> <tr> <td><?php echo LangUtil::$generalTerms['FACILITY']; ?>:</td> <td><?php echo $lab_config->getSiteName(); ?></td> </tr> <tr> <td><?php echo "User"; ?>:</td> <td><b><?php echo $user_obj->actualName; ?></b></td> </tr> <tr> <td><?php echo "User ID"; ?>:</td> <td><?php echo $user_obj->username; ?></td> </tr> <tr> <td><?php echo "Designation"; ?>:</td> <td><?php if ($user_obj->level == 0 || $user_obj->level == 1 || $user_obj->level == 13) echo "Technician"; else if ($user_obj->level == 2) echo "Administrator"; else if ($user_obj->level == 5) echo "Clerk"; ?></td> </tr> <tr> <td><?php echo LangUtil::$pageTerms['REPORT_PERIOD']; ?>:</td> <td> <?php if($date_from == $date_to) { echo DateLib::mysqlToString($date_from); } else { echo DateLib::mysqlToString($date_from)." to ".DateLib::mysqlToString($date_to); } ?> </td> </tr> <tr> <td><?php echo "Log Type"; ?>:</td> <td> <?php if($log_type == 1) echo "Patients Registry Log"; else if($log_type == 2) echo "Specimens Registry Log"; else if($log_type == 3) echo "Tests Registry Log"; else if($log_type == 4) echo "Results Entry Log"; else if($log_type == 5) echo "Inventory Transaction Log"; ?> </td> </tr> </tbody> </table> <?php $table_css = "style='padding: .3em; border: 1px black solid; font-size:14px;'"; ?> <br> <?php if($log_type == 1) { ?> <table id='report_content_table' class="print_entry_border draggable"> <thead> <tr> <th><?php $count = 0; echo "S.No."; ?></th> <th>Patient Name</th> <th>Patient ID</th> <th>Patient Number</th> <th>Patient Gender</th> <th>Patient Age</th> <th>Date of Registration</th> </tr> </thead> <tbody> <?php $all_entries = $ust->getPatientRegLog($user_id, $lab_config_id,$date_from, $date_to); foreach($all_entries as $entry) { ?> <tr> <td> <?php $count++; echo $count; ?> </td> <td> <?php if($entry->name != '') echo $entry->name; else echo '-'; ?> </td> <td> <?php if($entry->surrogateId != '') echo $entry->surrogateId; else echo '-'; ?> </td> <td> <?php $entr = $entry->getDailyNum(); if($entr != '') echo $entr; else echo '-'; ?> </td> <td> <?php if($entry->sex != '') echo $entry->sex; else echo '-'; ?> </td> <td> <?php $entr = $entry->getAge(); if($entr != '') echo $entr; else echo '-'; ?> </td> <td> <?php if($entry->regDate != '') echo $entry->regDate; else echo '-'; ?> </td> </tr> <?php } ?> </tbody> </table> <?php } ?> <?php if($log_type == 2) { ?> <table id='report_content_table' class="print_entry_border draggable"> <thead> <tr> <th><?php $count = 0; echo "S.No."; ?></th> <th>Specimen Name</th> <th>Specimen ID</th> <th>Patient Name</th> <th>Patient ID</th> <th>Date of Registration</th> </tr> </thead> <tbody> <?php $all_entries = $ust->getSpecimenRegLog($user_id, $lab_config_id,$date_from, $date_to); foreach($all_entries as $entry) { ?> <tr> <td> <?php $count++; echo $count; ?> </td> <td> <?php $tname = $entry->getTypeName(); if($tname != '') echo $tname; else echo '-'; ?> </td> <td> <?php if($entry->specimenId != '') echo $entry->specimenId; else echo '-'; ?> </td> <td> <?php $entr2 = get_patient_by_sp_id($entry->specimenId); $entr = $entr2[0]->name; if($entr != '') echo $entr; else echo '-'; ?> </td> <td> <?php $entr = $entry->patientId; if($entr != '') echo $entr; else echo '-'; ?> </td> <td> <?php $entr = $entry->dateCollected; if($entr != '') echo $entr; else echo '-'; ?> </td> </tr> <?php } ?> </tbody> </table> <?php } ?> <?php if($log_type == 3) { ?> <table id='report_content_table' class="print_entry_border draggable"> <thead> <tr> <th><?php $count = 0; echo "S.No."; ?></th> <th>Test Name</th> <th>Test ID</th> <th>Patient Name</th> <th>Patient ID</th> <th>Specimen ID</th> <th>Date of Registration</th> </tr> </thead> <tbody> <?php $all_entries = $ust->getTestRegLog($user_id, $lab_config_id,$date_from, $date_to); foreach($all_entries as $entry) { ?> <tr> <td> <?php $count++; echo $count; ?> </td> <td> <?php $tname = get_test_name_by_id($entry->testTypeId); if($tname != '') echo $tname; else echo '-'; ?> </td> <td> <?php if($entry->testId != '') echo $entry->testId; else echo '-'; ?> </td> <td> <?php $entr2 = get_patient_by_sp_id($entry->specimenId); $entr = $entr2[0]->name; if($entr != '') echo $entr; else echo '-'; ?> </td> <td> <?php $entr = $entr2[0]->patientId; if($entr != '') echo $entr; else echo '-'; ?> </td> <td> <?php $entr = $entry->specimenId; if($entr != '') echo $entr; else echo '-'; ?> </td> <td> <?php $entr = $entry->getTestRegDate(); if($entr != '') echo $entr; else echo '-'; ?> </td> </tr> <?php } ?> </tbody> </table> <?php } ?> <?php if($log_type == 4) { ?> <table id='report_content_table' class="print_entry_border draggable"> <thead> <tr> <th><?php $count = 0; echo "S.No."; ?></th> <th>Test Name</th> <th>Test ID</th> <th>Patient Name</th> <th>Patient ID</th> <th>Specimen ID</th> <th>Date of Result Entry</th> </tr> </thead> <tbody> <?php $all_entries = $ust->getResultEntryLog($user_id, $lab_config_id,$date_from, $date_to); foreach($all_entries as $entry) { ?> <tr> <td> <?php $count++; echo $count; ?> </td> <td> <?php $tname = get_test_name_by_id($entry->testTypeId); if($tname != '') echo $tname; else echo '-'; ?> </td> <td> <?php if($entry->testId != '') echo $entry->testId; else echo '-'; ?> </td> <td> <?php $entr2 = get_patient_by_sp_id($entry->specimenId); $entr = $entr2[0]->name; if($entr != '') echo $entr; else echo '-'; ?> </td> <td> <?php $entr = $entr2[0]->patientId; if($entr != '') echo $entr; else echo '-'; ?> </td> <td> <?php $entr = $entry->specimenId; if($entr != '') echo $entr; else echo '-'; ?> </td> <td> <?php $entr = $entry->timestamp; if($entr != '') echo $entr; else echo '-'; ?> </td> </tr> <?php } ?> </tbody> </table> <?php } ?> <?php if($log_type == 5) { ?> <b>Inventory In-Flow</b> <table id='report_content_table' class="print_entry_border draggable"> <thead> <tr> <th><?php $count = 0; echo "S.No."; ?></th> <th>Reagent</th> <th>Lot</th> <th>Expiry Date</th> <th>Manufacturer</th> <th>Supplier</th> <th>Quantity Supplied</th> <th>Cost Per Unit</th> <th>Date of Supply</th> <th>Remarks</th> <th>Date of Transaction</th> </tr> </thead> <tbody> <?php $all_entries = Inventory::get_inv_supply_by_user($lab_config_id, $user_id); foreach($all_entries as $entry) { ?> <tr> <td> <?php $count++; echo $count; ?> </td> <td> <?php $dat = Inventory::getReagentById($lab_config_id, $entry['reagent_id']); if($dat[name] != '') echo $dat[name]; else echo '-'; ?> </td> <td> <?php if($entry[lot] != '') echo $entry[lot]; else echo '-'; ?> </td> <td> <?php if($entry[expiry_date] != '') echo $entry[expiry_date]; else echo '-'; ?> </td> <td> <?php if($entry[manufacturer] != '') echo $entry[manufacturer]; else echo '-'; ?> </td> <td> <?php if($entry[supplier] != '') echo $entry[supplier]; else echo '-'; ?> </td> <td> <?php if($entry[quantity_supplied] != '') echo $entry[quantity_supplied]; else echo '-'; ?> </td> <td> <?php if($entry[cost_per_unit] != '') echo $entry[cost_per_unit]; else echo '-'; ?> </td> <td> <?php if($entry[date_of_reception] != '') echo $entry[date_of_reception]; else echo '-'; ?> </td> <td> <?php if($entry[remarks] != '') echo $entry[remarks]; else echo '-'; ?> </td> <td> <?php if($entry[ts] != '') echo $entry[ts]; else echo '-'; ?> </td> </tr> <?php } ?> </tbody> </table> <br><br> <b>Inventory Out-Flow</b> <table id='report_content_table' class="print_entry_border draggable"> <thead> <tr> <th><?php $count = 0; echo "S.No."; ?></th> <th>Reagent</th> <th>Lot</th> <th>Quantity Used</th> <th>Date of Use</th> <th>Remarks</th> <th>Date of Transaction</th> </tr> </thead> <tbody> <?php $all_entries = Inventory::get_inv_usage_by_user($lab_config_id, $user_id); foreach($all_entries as $entry) { ?> <tr> <td> <?php $count++; echo $count; ?> </td> <td> <?php $dat = Inventory::getReagentById($lab_config_id, $entry['reagent_id']); if($dat[name] != '') echo $dat[name]; else echo '-'; ?> </td> <td> <?php if($entry[lot] != '') echo $entry[lot]; else echo '-'; ?> </td> <td> <?php if($entry[quantity_used] != '') echo $entry[quantity_used]; else echo '-'; ?> </td> <td> <?php if($entry[date_of_use] != '' && $entry[date_of_use] != '0000-00-00') echo $entry[date_of_use]; else echo '-'; ?> </td> <td> <?php if($entry[remarks] != '') echo $entry[remarks]; else echo '-'; ?> </td> <td> <?php if($entry[ts] != '') echo $entry[ts]; else echo '-'; ?> </td> </tr> <?php } ?> </tbody> </table> <?php } ?> <br><br><br> ............................................ </div> </div> </div> </body> </html><file_sep>/htdocs/api/Net.old/HL7/Types/VID.php <?php class Net_HL7_Types_VID { private $versionId; private $internationalizationCode; private $internationalVersionId; public function __construct($components) { $this->versionId = (empty($components[0])) ? "" : $components[0]; $this->internationalizationCode = (empty($components[1])) ? "" : $components[1]; $this->internationalVersionId = (empty($components[2])) ? "" : $components[2]; } /** * @return Net_HL7_Types_VID */ public static function template() { return new Net_HL7_Types_VID(array()); } /** * @return array */ public function toArray() { $components = array(); $components[0] = $this->versionId; $components[1] = $this->internationalizationCode; $components[2] = $this->internationalVersionId; return $components; } /** * @param $versionId string */ public function setVersionId($versionId) { $this->versionId = $versionId; } /** * @return string */ public function getVersionId() { return $this->versionId; } /** * @param $internationalizationCode string */ public function setInternationalizationCode($internationalizationCode) { $this->internationalizationCode = $internationalizationCode; } /** * @return string */ public function getInternationalizationCode() { return $this->internationalizationCode; } /** * @param $internationalVersionId string */ public function setInternationalVersionId($internationalVersionId) { $this->internationalVersionId = $internationalVersionId; } /** * @return string */ public function getInternationalVersionId() { return $this->internationalVersionId; } } ?> <file_sep>/htdocs/api/get_lab_status.php <?php require_once "authenticate.php"; $rcd = array(); $rcd['date'] = date('Y-m-d H:i:s'); $result = API::get_lab_status($rcd); if($result < 1) echo $result; else echo json_encode($result); ?> <file_sep>/htdocs/update/db/update_scripts/27.CREATE_TABLE_abbreviations.sql CREATE TABLE `abbreviations` ( `id` INT NOT NULL AUTO_INCREMENT , `abbreviation` VARCHAR(45) NULL , `Word` VARCHAR(250) NULL , PRIMARY KEY (`id`)) COMMENT = 'Table that stores abbreviations and their full words';<file_sep>/htdocs/regn/new_patient2.php <?php include("redirect.php"); require_once("includes/db_lib.php"); require_once("includes/page_elems.php"); require_once("includes/script_elems.php"); require_once("includes/user_lib.php"); $page_elems = new PageElems(); $script_elems = new ScriptElems(); LangUtil::setPageId("new_patient"); $script_elems->enableDatePicker(); $script_elems->enableLatencyRecord(); $script_elems->enableJQueryForm(); $script_elems->enableAutocomplete(); ?> <script> App.init(); // init the rest of plugins and elements </script> <table> <tr valign='top'> <div id='patient_new'> <div class='pretty_box' style='width:500px'> <form name="new_record" action="add_patient.php" method="post" id="new_record" class="form-horizontal" role="form"> <?php # Hidden field for db key ?> <input type='hidden' name='card_num' id='card_num' value="<?php echo get_max_patient_id()+1; ?>" ></input> <table cellpadding="2" class='regn_form_table' > <tr<?php if($_SESSION['pname'] == 0) echo " style='display:none;' "; ?>> <td><?php echo LangUtil::$generalTerms['PATIENT_NAME']; ?><?php $page_elems->getAsterisk(); ?> </td> <td><input type="text" name="name" id="name" value="" size="20" class='uniform_width m-wrap tooltips' data-trigger="hover" data-original-title="Please enter patient's full name." /></td> </tr> <tr <?php //if($_SESSION['p_addl'] == 0) //echo " style='display:none;' "; ?>> <td> <?php echo LangUtil::$generalTerms['ADDL_ID']; if($_SESSION['p_addl'] == 2) $page_elems->getAsterisk(); ?> </td> <td><input type="text" name="addl_id" id="addl_id" value="" size="20" class='uniform_width' /></td> </tr> <tr> <td> Date of Registration </td> <td> <div class="input-append date date-picker" data-date="<?php echo date("Y-m-d"); ?>" data-date-format="yyyy-mm-dd"> <input class="m-wrap m-ctrl-medium" size="16" name="patient_reg_date" id="patient_regist_date" type="text" value="<?php echo date("Y-m-d"); ?>" ><span class="add-on"><i class="icon-calendar"></i></span> </div> </td> </tr> <tr style='display:none;'> <!-- Hidden as we are doing away with this --> <td><?php echo LangUtil::$generalTerms['PATIENT_DAILYNUM']; ?> <?php if($_SESSION['dnum'] == 2) $page_elems->getAsterisk(); ?> </td> <td><input type="text" name="dnum" id="dnum" value="<?php echo $daily_num; ?>" size="20" class='uniform_width m-wrap tooltips' /></td> </tr> <tr style='display:none;'> <div class="control-group" <?php if($_SESSION['pid'] == 0) echo " style='display:none;' ";?> > <td width="200"> <?php echo "Registration Number"; ?> <?php if($_SESSION['pid'] == 2) $page_elems->getAsterisk(); ?> </td> <td> <input type="text" name="pid" id="pid" value="" size="20" class='uniform_width form-control' style='background-color:#FFC' disabled> </td> </div> </tr> <tr<?php if($_SESSION['sex'] == 0) echo " style='display:none;' "; ?>> <td><?php echo LangUtil::$generalTerms['GENDER']; ?><?php $page_elems->getAsterisk();?> </td> <td> <div class="controls"> <label class="radio"> <span><input type="radio" name="sex" value="M" > <?php echo LangUtil::$generalTerms['MALE']; ?></span> </label> </div> <div class="controls"> <label class="radio"> <span> <input type="radio" name="sex" value="F"><?php echo LangUtil::$generalTerms['FEMALE']; ?> </span> </label> </div> <br> </td> </tr> <tr valign='top'<?php // if($_SESSION['dob'] != 0) // echo " style='display:none;' "; ?>> <td> <?php echo LangUtil::$generalTerms['DOB']; ?> <?php // if($_SESSION['dob'] == 2) $page_elems->getAsterisk(); ?> </td> <td> <div class="input-append date date-picker" data-date="" data-date-format="yyyy-mm-dd"> <input class="m-wrap m-ctrl-medium" size="16" name="patient_birth_date" id="patient_b_day" type="text" value="" readonly><span class="add-on" id="span_dob"><i class="icon-calendar"></i></span> </div> </td> <td> <a href="" class="btn-default btn " data-toggle="modal" data-target=".bs-example-modal-sm"><span class="add-on" id="span_calcdob"><i class="icon-calendar"></i> From Age</span></a> <!--pop up for dob calc begin--> <div class="modal fade bs-example-modal-sm" id="dobcal" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true"> <div class="modal-dialog modal-sm"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button> <h4 class="modal-title" id="myModalLabel">Calculate Date of Birth</h4> </div> <div class="modal-body"> <div class="form-group"> <label class="col-md-2 control-label" for="body">Age in Years</label> <input id="age" name="age" type="text" maxlength="3" class="form-control input-md"> </div> <div class="form-group"> <label class="col-md-2 control-label" for="by_date">On Date</label> <style> .datepicker{ z-index:1151 !important; } </style> <div class="input-append date date-picker" data-date="" data-date-format="yyyy-mm-dd"> <input class="m-wrap m-ctrl-medium" size="16" name="by_date" id="by_date" type="text" readonly><span class="add-on" id="span_dob"><i class="icon-calendar"></i></span> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button> <button type="button" name="submit_iss" class="btn btn-primary" onclick="javascript:calc_dob();">Submit</button> </div> </div> <!--pop up end--> </td> </tr> <form id='custom_field_form' name='custom_field_form' action='ajax/patient_add_custom.php' method='get'> <input type='hidden' name='pid2' id='pid2' value=''></input> <?php $custom_field_list = get_custom_fields_patient(); foreach($custom_field_list as $custom_field) { if(($custom_field->flag)==NULL) { ?> <tr valign='top'> <td><?php echo $custom_field->fieldName; ?></td> <td><?php $page_elems->getCustomFormField($custom_field); ?></td> </tr> <?php } } ?> </form> <tr> <td></td> <td> <input class="btn green button-submit" type="button" id='submit_button' onclick="add_patient();" value="<?php echo LangUtil::$generalTerms['CMD_SUBMIT']; ?> " /> &nbsp;&nbsp; <a class="btn red icn-only" href='find_patient.php?div=reception'><?php echo LangUtil::$generalTerms['CMD_CANCEL']; ?></i></a> &nbsp;&nbsp; <span id='progress_spinner' style='display:none'> <?php $page_elems->getProgressSpinner(LangUtil::$generalTerms['CMD_SUBMITTING']); ?> </span> </td> </tr> <tr> <td> <small> <span style='float:left'> <?php $page_elems->getAsteriskMessage(); ?> </span> </small> </td> <td> </td> </tr> <tr> <td> </td> </tr> </table> <!--</form>--> </div> </div> </td> </tr> </table> <script type="text/javascript" src="js/check_date_format.js"></script> <script type='text/javascript'> $(document).ready(function(){ //SelectDOBAge(1); $('#progress_spinner').hide(); <?php if(isset($_REQUEST['n'])) { # Prefill patient name field ?> $('#name').attr("value", "<?php echo $_REQUEST['n']; ?>"); <?php } if(isset($_REQUEST['jmp'])) { ?> $('#new_patient_msg').html("<center>'<?php echo $_REQUEST['n']."' - ".LangUtil::$generalTerms['PATIENT_NAME']." ".LangUtil::$generalTerms['MSG_NOTFOUND'].". ".LangUtil::$pageTerms['MSG_ADDNEWENTRY']; ?></center>"); $('#new_patient_msg').show(); <?php } ?> $('#custom_field_form').submit(function() { // submit the form $(this).ajaxSubmit({async:false}); // return false to prevent normal browser submit and page navigation return false; }); }); function calc_dob(){ var age=$('#age').val(); var curr_date=new Date($('#by_date').val()); if(age.trim() == "" || $('#by_date').val()== ""){ alert("Empty field!"); return; } if(isNaN(age)){ alert("Error: Numeric input required for age"); return; } console.log(curr_date); curr_date.setMonth(curr_date.getMonth() -12*age); curr_date=$.datepicker.formatDate('yy-mm-dd',new Date(curr_date)); $('#patient_b_day').attr('value',curr_date); $('#dobcal').modal('hide'); } function add_patient() { var card_num = $("#card_num").val(); $('#pid2').attr("value", card_num); var addl_id = $("#addl_id").val(); var name = $("#name").val(); name = name.replace(/[^a-z ]/gi,''); var pat_reg_date = $('#patient_regist_date').val(); //var age = $("#age").val(); //age = age.replace(/[^0-9]/gi,''); //var age_param = $('#age_param').val(); //age_param = age_param.replace(/[^0-9]/gi,''); var patient_birth_date = $('#patient_b_day').val(); var sex = ""; var pid = $('#pid').val(); var radio_sex = document.getElementsByName("sex"); for(i = 0; i < radio_sex.length; i++) { if(radio_sex[i].checked) sex = radio_sex[i].value; } var email = $("#email").val(); var phone = $("#phone").val(); var error_message = ""; var error_flag = 0; var curr_date = new Date(); var patient_birth_date = $('#patient_b_day').val(); if (patient_birth_date!=""){ /* * Call a function to validate the format of the keyed in format */ if (dt_format_check(patient_birth_date, "Date of Birth") == false) {return;} /* execute if the date is ok echiteri*/ var pt_dob_y = patient_birth_date.slice(0, 4); var pt_dob_m = parseInt(patient_birth_date.slice(5, 7)); var pt_dob_d = patient_birth_date.slice(-2); if (parseInt(pt_dob_y)==0){ error_message += "The year of birth must be greater than zero\n"; error_flag = 1; alert("Error: The year of birth must be greater than zero"); return; } if (parseInt(pt_dob_m)==0){ error_message += "The month of birth must be greater than zero\n"; error_flag = 1; alert("Error: The month of birth must be greater than zero"); return; } if (parseInt(pt_dob_d)==0){ error_message += "The day of birth must be greater than zero\n"; error_flag = 1; alert("Error: The day of birth must be greater than zero"); return; } var pt_dob = new Date(pt_dob_y, pt_dob_m-1, pt_dob_d); if (curr_date<pt_dob){ error_message += "The date of birth cannot be after today\n"; error_flag = 1; alert("Error: The date of birth cannot be after today"); return; } } if (pat_reg_date!=""){ /* * Call a function to validate the format of the keyed in format */ if (dt_format_check(pat_reg_date, "Registration Date") == false) {return;} /* execute if the date is ok echiteri*/ var pt_regdate = new Date(pat_reg_date.slice(0, 4), parseInt(pat_reg_date.slice(5, 7))-1, pat_reg_date.slice(-2)); if (curr_date<pt_regdate){ error_message += "The registration date cannot be after today\n"; error_flag = 1; alert("Error: The registration date cannot be after today"); return; } } for(i = 0; i < radio_sex.length; i++) { if(radio_sex[i].checked) { error_flag = 2; break; } } if(error_flag == 2) { error_flag = 0; } else { //sex not checked error_flag = 1; error_message += "<?php echo LangUtil::$generalTerms['ERROR'].": ".LangUtil::$generalTerms['GENDER']; ?>\n"; } if(card_num == "" || !card_num) { error_message += "<?php echo LangUtil::$generalTerms['ERROR'].": ".LangUtil::$generalTerms['PATIENT_ID']; ?>\n"; error_flag = 1; } if(name.trim() == "" || !name) { alert("<?php echo LangUtil::$generalTerms['ERROR'].": ".LangUtil::$generalTerms['PATIENT_NAME']; ?>"); return; } if(patient_birth_date.trim() == "") { error_message += "Please enter either Age or Date of Birth\n";//<br>"; error_flag = 1; alert("Error: Please enter either Age or Date of Birth"); return; } if(sex == "" || !sex) { alert("<?php echo LangUtil::$generalTerms['ERROR'].": ".LangUtil::$generalTerms['GENDER']; ?>"); return; } var data_string = "card_num="+card_num+"&addl_id="+addl_id +"&name="+name+"&dob="+patient_birth_date+"&sex="+sex +"&pid="+pid+"&receipt_date="+pat_reg_date; if(error_flag == 0) { //alert(data_string); $("#progress_spinner").show(); //Submit form by ajax $.ajax({ type: "POST", url: "ajax/patient_add.php", data: data_string, success: function(data) { //Add custom fields //$('#custom_field_form').ajaxSubmit(); $('#custom_field_form').submit(); $("#progress_spinner").hide(); /* Retrieve actual DB Key used */ var pidStart = data.indexOf("VALUES") + 8; var pidEnd = data.indexOf(",",pidStart); var new_card_num = data.substring(pidStart,pidEnd); card_num = new_card_num; var url = 'regn/new_specimen2.php'; $('.reg_subdiv').hide(); $('#specimen_reg').show(); $('#specimen_reg_body').load(url, {pid: card_num }); } }); //Patient added } else { alert(error_message); } } function reset_new_patient() { $('#new_record').resetForm(); } // function SelectDOBAge(optionval){ // if (optionval==1){ // $('#patient_b_day').show(); // $('#span_dob').show(); // $('#age').hide(); // $('#age_param').hide(); // $('#age').val(''); // } else { // $('#patient_b_day').hide(); // $('#span_dob').hide(); // $('#age').show(); // $('#age_param').show(); // $('#patient_b_day').val(''); // } // } </script> <file_sep>/htdocs/update/db/update_scripts/25. Update_test_type_measure.sql /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; RENAME TABLE `test_type_measure` TO `tmp_test_type_measure`; CREATE TABLE `test_type_measure` ( `ttm_id` int(11) NOT NULL AUTO_INCREMENT, `test_type_id` int(11) unsigned NOT NULL DEFAULT '0', `measure_id` int(11) unsigned NOT NULL DEFAULT '0', `ordering` tinyint(3) unsigned NOT NULL DEFAULT '0', `nesting` tinyint(3) unsigned NOT NULL DEFAULT '0', `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`ttm_id`), KEY `test_type_id` (`test_type_id`), KEY `measure_id` (`measure_id`) ) ENGINE=InnoDB AUTO_INCREMENT=280 DEFAULT CHARSET=latin1; INSERT IGNORE INTO `test_type_measure` (`test_type_id`, `measure_id`, `ts`) SELECT `test_type_id`, `measure_id`, `ts` FROM `tmp_test_type_measure` GROUP BY `test_type_id`, `measure_id`; DROP TABLE `tmp_test_type_measure`; /*!40101 SET character_set_client = @saved_cs_client */; <file_sep>/htdocs/export/export_pdf.php <?php ini_set('memory_limit', '256M'); $_REQUEST['data'] = str_replace('class="print_entry_border draggable"', 'class="print_entry_border draggable" border="1"', $_REQUEST['data']); $_REQUEST['data'] = str_replace('class="print_entry_border"', 'class="print_entry_border" border="1"', $_REQUEST['data']); //echo($_REQUEST['data']); die; require_once("../mpdf/mpdf.php"); $mpdf = new mPDF('','', 0, '', 10, 15, 16, 16, 9, 9, 'L'); $mpdf->WriteHTML($_REQUEST['data']); $mpdf->Output(); ?><file_sep>/blis_def.sql -- phpMyAdmin SQL Dump -- version 4.0.6deb1 -- http://www.phpmyadmin.net -- -- Host: localhost -- Generation Time: Sep 10, 2014 at 09:50 AM -- Server version: 5.5.37-0ubuntu0.13.10.1 -- PHP Version: 5.5.3-1ubuntu2.6 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; 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 utf8 */; -- -- Database: `blis` -- -- -------------------------------------------------------- -- -- Table structure for table `access_log` -- CREATE TABLE IF NOT EXISTS `access_log` ( `idaccess_log` int(11) NOT NULL AUTO_INCREMENT, `user_id` int(11) DEFAULT NULL, `access_log_ts` timestamp NULL DEFAULT CURRENT_TIMESTAMP, `access_type` int(11) DEFAULT NULL, `ip_address` varchar(50) DEFAULT NULL, `user_name` varchar(45) DEFAULT NULL, `access_sessionid` varchar(100) DEFAULT NULL, PRIMARY KEY (`idaccess_log`), KEY `access_type_idx` (`access_type`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1709 ; -- -- Dumping data for table `access_log` -- INSERT INTO `access_log` (`idaccess_log`, `user_id`, `access_log_ts`, `access_type`, `ip_address`, `user_name`, `access_sessionid`) VALUES (1708, 53, '2014-09-10 09:49:06', 1, '127.0.0.1', 'testlab1_admin', '45v41c78n5j9ekubevv38jc0s7'); -- -------------------------------------------------------- -- -- Table structure for table `access_type` -- CREATE TABLE IF NOT EXISTS `access_type` ( `idaccess_type` int(11) NOT NULL AUTO_INCREMENT, `access_typename` varchar(45) DEFAULT NULL, PRIMARY KEY (`idaccess_type`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `audit_trail` -- CREATE TABLE IF NOT EXISTS `audit_trail` ( `audit_trail_id` int(11) NOT NULL AUTO_INCREMENT, `at_userid` int(11) DEFAULT NULL, `at_operationtype` varchar(45) DEFAULT NULL, `at_ts` timestamp NULL DEFAULT CURRENT_TIMESTAMP, `at_dbname` varchar(45) DEFAULT NULL, `at_tablename` varchar(45) DEFAULT NULL, `at_objectid` int(11) DEFAULT NULL, `at_fieldname` varchar(45) DEFAULT NULL, `at_oldvalue` varchar(200) DEFAULT NULL, `at_newvalue` varchar(200) DEFAULT NULL, `at_sessionid` varchar(100) DEFAULT NULL, `at_descript` varchar(45) DEFAULT NULL, PRIMARY KEY (`audit_trail_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1168 ; -- -- Dumping data for table `audit_trail` -- INSERT INTO `audit_trail` (`audit_trail_id`, `at_userid`, `at_operationtype`, `at_ts`, `at_dbname`, `at_tablename`, `at_objectid`, `at_fieldname`, `at_oldvalue`, `at_newvalue`, `at_sessionid`, `at_descript`) VALUES (31, 53, '1', '2013-09-26 07:13:16', 'blis_127', 'patient', 20300, NULL, NULL, NULL, '8s1thte18rrtfghl5qa8djpll6', '1'), -- -------------------------------------------------------- -- -- Table structure for table `bills` -- CREATE TABLE IF NOT EXISTS `bills` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `patient_id` int(11) unsigned NOT NULL, `paid_in_full` bit(1) NOT NULL DEFAULT b'0', PRIMARY KEY (`id`), UNIQUE KEY `id_UNIQUE` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=13 ; -- -------------------------------------------------------- -- -- Table structure for table `bills_test_association` -- CREATE TABLE IF NOT EXISTS `bills_test_association` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `bill_id` int(11) unsigned NOT NULL, `test_id` int(11) unsigned NOT NULL, `discount_type` int(4) unsigned NOT NULL DEFAULT '1000', `discount_amount` decimal(10,2) unsigned NOT NULL DEFAULT '0.00', PRIMARY KEY (`id`), UNIQUE KEY `id_UNIQUE` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=22 ; -- -------------------------------------------------------- -- -- Table structure for table `comment` -- CREATE TABLE IF NOT EXISTS `comment` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `username` varchar(45) NOT NULL DEFAULT '', `page` varchar(45) NOT NULL DEFAULT '', `comment` varchar(150) NOT NULL DEFAULT '', `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `custom_field_type` -- CREATE TABLE IF NOT EXISTS `custom_field_type` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `field_type` varchar(45) DEFAULT NULL, `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `delay_measures` -- CREATE TABLE IF NOT EXISTS `delay_measures` ( `User_Id` varchar(50) NOT NULL DEFAULT '', `IP_Address` varchar(16) NOT NULL DEFAULT '', `Latency` int(11) NOT NULL DEFAULT '0', `Recorded_At` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', `Page_Name` varchar(45) DEFAULT NULL, `Request_URI` varchar(100) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `external_lab_request` -- CREATE TABLE IF NOT EXISTS `external_lab_request` ( `id` int(11) NOT NULL AUTO_INCREMENT, `labNo` varchar(100) DEFAULT NULL, `parentLabNo` varchar(100) DEFAULT NULL, `requestingClinician` varchar(100) DEFAULT NULL, `investigation` varchar(100) DEFAULT NULL, `requestDate` datetime DEFAULT NULL, `orderStage` varchar(45) DEFAULT NULL, `patient_id` varchar(100) DEFAULT NULL, `full_name` varchar(100) DEFAULT NULL, `dateOfBirth` datetime DEFAULT NULL, `age` int(11) DEFAULT NULL, `gender` varchar(45) DEFAULT NULL, `address` varchar(45) DEFAULT NULL, `postalCode` varchar(45) DEFAULT NULL, `phoneNumber` varchar(45) DEFAULT NULL, `city` varchar(45) DEFAULT NULL, `test_status` int(11) DEFAULT '0', `result` varchar(45) DEFAULT NULL, `comments` varchar(100) DEFAULT NULL, `result_returned` bit(1) DEFAULT b'0', `revisitNumber` int(11) DEFAULT NULL, `cost` int(11) DEFAULT NULL, `patientContact` varchar(45) DEFAULT NULL, `receiptNumber` varchar(45) DEFAULT NULL, `receiptType` varchar(45) DEFAULT NULL, `waiverNo` varchar(45) DEFAULT NULL, `provisionalDiagnosis` varchar(45) DEFAULT NULL, `system_id` varchar(45) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=14 ; -- -------------------------------------------------------- -- -- Table structure for table `facility_list` -- CREATE TABLE IF NOT EXISTS `facility_list` ( `Facility_Code` varchar(20) DEFAULT NULL, `Facility_Name` varchar(100) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `facility_list` -- INSERT INTO `facility_list` (`Facility_Code`, `Facility_Name`) VALUES ('18486', 'Afya Health Care'), ('10009', 'Afya Health Services'), ('20380', 'Afya Health System Hospital'), ('18344', 'Afya House Dispensary'), ('10006', 'Afya Link Ngurubani Clinic'), ('18845', 'Afya Medical Centre'), ('10015', 'Afya Medical Clinic'), ('16556', 'Afya Medical Clinic'), ('19621', 'Afya Medical Clinic (Dandora)'), ('13269', 'Afya Medical Clinic (Garissa)'), ('20296', 'Afya Medical Clinic (Gilgil)'), ('19802', 'Afya Medical Clinic (Gwakungu)'), ('11920', 'Afya Medical Clinic (Kangundo)'), ('20265', 'Afya Medical Clinic (Mbaruk)'), ('18730', 'Afya Medical Clinic (Meru)'), ('17566', 'Afya Medical Clinic (Munyaka)'), ('10010', 'Afya Medical Clinic (Muranga North)'), ('18440', 'Afya Medical Clinic (Nakuru)'), ('10013', 'Afya Medical Clinic (Nyeri North)'), ('10014', 'Afya Medical Clinic (Nyeri South)'), ('13270', 'Afya Medical Clinic and Nursing Home (Wajir East)'), ('20250', 'Afya Medical Clinic(Dagoretti Market)'), ('19131', 'Afya Medical Laboratory'), ('19453', 'Afya Medical Services'), ('13471', 'Akala Health Centre'), ('17770', 'Akemo Medical Clinic'), ('14194', 'Akemo Nursing Home'), ('18764', 'Akicha Medical Services'), ('15792', 'Akichelesit Dispensary'), ('13462', 'Akidiva Clinic'), ('20481', 'Akorian Dispensary'), ('10604', 'Akshar Nursing Home'), ('20457', 'Akwichatis Health Centre'), ('19154', 'Al - Azhar Medical Clinic Centre'), ('19149', 'Al - Bushra Medical Centre'), ('19174', 'Al - Hayat Medicare'), ('19204', 'Al - Nasri Medical Care'), ('18996', 'Al Amin Medical Clinic'), ('18769', 'Al Amin Nursing Home'), ('17185', 'Al -Arbrar Medical Clinic'), ('17628', 'Al Azhar Medical Clinic'), ('11208', 'Al Farooq Hospital'), ('18997', 'Al Iklas Nursing Home'), ('19165', 'Al Qudus Clinic'), ('11209', 'Al Riyadh Medical Clinic'), ('11207', 'Al-Agsa Medical Clinic'), ('14195', 'Alakara Medical Clinic'), ('14196', 'Alale (AIC) Health Centre'), ('16367', 'Alale Health Centre'), ('11927', 'Ambalo Dispensary'), ('13476', 'Ambira Sub-District Hospital'), ('10027', 'Amboni Dispensary'), ('14200', 'Amboseli Dispensary'), ('14201', 'Amboseli Serena Lodge Clinic'), ('20136', 'AMEC Laboratories'), ('19022', 'Amina Medical Clinic'), ('20170', 'Among''ura Community Dispensary'), ('16768', 'Amoyo Dispensary'), ('11928', 'Amugaa Health Centre'), ('15798', 'Amukura Health Centre'), ('15799', 'Amukura Mission Health Centre'), ('13288', 'Amuma Dispensary'), ('13289', 'Amuma Mobile Dispensary'), ('11929', 'Amungeti Catholic Dispensary'), ('20116', 'Amurt Health care Centre (Malindi)'), ('12870', 'Amurt Health Centre'), ('11221', 'Amurt Health Centre (Likoni)'), ('17062', 'Amwamba Dispensary'), ('16359', 'Ancilla Catholic Dispensary'), ('14203', 'Andersen Medical Centre'), ('13477', 'Anding''o Opanga Dispensary'), ('18770', 'Andulus Medical Clinic'), ('13478', 'Aneko Dispensary'), ('17050', 'Angaga Dispensary'), ('12872', 'Arrow Web Maternity and Nursing Home'), ('14217', 'Arsim Lutheran Dispensary'), ('19560', 'Artisan Dental Laboratory (Nairobi)'), ('10038', 'Asantey Clinic'), ('13487', 'Asat Beach Dispensary'), ('16783', 'Asayi Dispensary'), ('18039', 'Asembo Bay Health Clinic (Rarieda)'), ('18751', 'Ash Community Health Centre'), ('13294', 'Ashabito Health Centre'), ('17524', 'Ashburn Ohuru Clinic'), ('11226', 'Ashraf Medical Clinic'), ('12873', 'Aski Medical Clinic'), ('15762', 'ASN Upendo Village Dispensary'), ('10039', 'ASPE Medical Clinic'), ('11229', 'Assa Dispensary'), ('18348', 'Association of Physically Disabled of Kenya'), ('10040', 'Assumption of Mary Dispensary'), ('14218', 'Assumption Sisters Dispensary'), ('18661', 'Assumption Sisters Mbooni Clinic'), ('14219', 'Assururiet (SDA) Dispensary'), ('16987', 'Asumbi Annex Dispensary'), ('13488', 'Asumbi Health Centre'), ('18610', 'Atela Dispensary'), ('13489', 'Atemo Health Centre'), ('18169', 'Athi Complex Community Centre'), ('14180', '10 Engineer VCT'), ('17486', '12 Engineers'), ('18393', '3Kl Maternity & Nursing Home'), ('14181', '3Kr Health Centre'), ('11917', '78 Tank Battalion Dispensary'), ('13043', '7Kr Mrs Health Centre'), ('14182', '8Th Street Clinic'), ('18137', 'A To Z Quality Health Family Health Services'), ('20346', 'AAR Adams Health Centre'), ('12861', 'AAR City Centre Clinic'), ('16796', 'AAR Clinic Sarit Centre (Westlands)'), ('18178', 'AAR Eldoret'), ('19958', 'AAR Gwh Health Care Ltd'), ('20405', 'AAR Health Care'), ('18859', 'AAR Healthcare Limited (Karen)'), ('12862', 'AAR Kariobangi Clinic'), ('11194', 'AAR Medical Services (Docks)'), ('20140', 'AAR Mountain mall'), ('14183', 'AAR Nakuru Clinic'), ('11721', 'AAR Nyali Health Care'), ('12863', 'AAR Thika Road Clinic'), ('18821', 'Abakaile Dispensary'), ('13265', 'Abakore Sub District Hospital'), ('12864', 'Abandoned Child Care'), ('19856', 'Abba Medical Clinic'), ('19484', 'Abby Clinic'), ('11938', 'Azimio Medical Clinic (Meru South)'), ('11939', 'B/Valley (PCEA) Clinic'), ('10043', 'Baari Health Centre'), ('17273', 'Baawa Community Dispensary'), ('12875', 'Babadogo (EDARP)'), ('12876', 'Babadogo Health Centre'), ('12877', 'Babadogo Medical Health Centre'), ('19296', 'Babito Medical Centre'), ('16477', 'Badana Dispensary'), ('18423', 'Badan-Rero Dispensary'), ('11940', 'Badassa Dispensary'), ('17586', 'Badilika VCT'), ('19604', 'Badri Medical Clinic'), ('11233', 'Badria Medical Clinic'), ('19557', 'Bafana Medical Centre'), ('14222', 'Bagaria Dispensary'), ('17190', 'Bahai Dispensary'), ('11234', 'Bahari Medical Clinic'), ('18588', 'Bahari Medical Clinic Diani Beach'), ('12878', 'Bahati Clinic'), ('14223', 'Bahati Dispensary'), ('14224', 'Bahati District Hospital'), ('12879', 'Bahati Health Centre'), ('12880', 'Bahati Medical Clinic'), ('18161', 'Bahati Medical Clinic (Lugari)'), ('19088', 'Bahati Medical Clinic (West Pokot)'), ('11248', 'Baricho Dispensary (Malindi)'), ('10049', 'Baricho Health Centre'), ('17352', 'Barnet Memorial Hospital'), ('14234', 'Barotion (AIC) Dispensary'), ('14235', 'Barpello Dispensary'), ('14236', 'Barsaloi Catholic Dispensary'), ('14237', 'Barsaloi GK Dispensary'), ('16785', 'Bar-Sauri Dispensry'), ('17056', 'Barsemoi Dispensary'), ('18071', 'Barsheba Medical Clinic'), ('14238', 'Barsiele Dispensary'), ('14239', 'Barsombe Dispensary'), ('14240', 'Barsombe Dispensary (Turbo)'), ('14241', 'Bartabwa Dispensary'), ('14242', 'Bartolimo Dispensary'), ('17793', 'Barut Dispensary'), ('13301', 'Barwaqo Clinic'), ('13302', 'Barwaqo Dispensary'), ('14243', 'Barwessa Healthcentre'), ('11947', 'Basa Dispensary'), ('14244', 'Base Medical Centre'), ('17855', 'Bashal Islamic Community Health Initiative'), ('13303', 'Basir Dispensary'), ('13304', 'Batalu Dispensary'), ('19701', 'Batian Clinical Services'), ('17193', 'Bituyu Dispensary'), ('13306', 'Biyamadhow Health Centre'), ('10072', 'Blessed Louis Palazzolo Health Centre'), ('19514', 'Blessed Medical Clinic'), ('20233', 'Blue Cross Medical Clicnic'), ('18180', 'Blue Haven Medical Clinic'), ('12885', 'Blue House Dispensary'), ('13307', 'Blue Light Nursing Home'), ('10073', 'Blue Line Clinic'), ('19016', 'Blue Nile Medical Clinic'), ('18837', 'Bluebells Medical Clinic'), ('17609', 'Blueturtle'), ('19144', 'Boarder Medical Clinic Namanga'), ('19561', 'Bodaki Health Centre'), ('18805', 'Bodaki Medical Clinic'), ('16558', 'Boddu Pharmacy Ltd'), ('13308', 'Bodhai Dispensary'), ('13503', 'Bodi Health Centre'), ('11253', 'Bofu Dispensary'), ('13504', 'Bogwendo Health Centre(Manga)'), ('19359', 'Boi Dispensary'), ('13505', 'Boige Health Centre'), ('18280', 'Boito Dispensary'), ('11951', 'Boji Dispensary'), ('17072', 'Boka'), ('16974', 'Bokimai Dispensary'), ('15816', 'Bujumba Dispensary'), ('17156', 'Bukalama Dispensary'), ('15817', 'Bukaya Health Centre'), ('15818', 'Bukaya Medical Centre'), ('15819', 'Bukembe Dispensary'), ('17158', 'Bukhalalire Dispensary'), ('15820', 'Bukura Health Centre'), ('17850', 'Bukura Medical Clinic'), ('18315', 'Bukwala SDA Dispensary'), ('11957', 'Bulesa Dispensary'), ('19002', 'Bulla Game Medical Clinic and Laboratory'), ('19003', 'Bulla Hagar Clinic'), ('19168', 'Bulla Medina Clinic'), ('19214', 'Bulla Mpya Nursing Home'), ('17011', 'Bulla Mzuri Dispensary'), ('19216', 'Bulla Tawakal Medical Clinic'), ('16306', 'Bullampya Medical Clinic'), ('15821', 'Bulondo Dispensary'), ('16285', 'Bultohama Dispensary'), ('15822', 'Bulwani Dispensary'), ('15823', 'Bumala A Health Centre'), ('15824', 'Bumala B Health Centre'), ('15825', 'Bumula Health Centre'), ('15826', 'Bumutiru Dispensary'), ('13312', 'Buna Sub-District Hospital'), ('13518', 'Bunde Dispensary'), ('15827', 'Bungasi Health Centre'), ('10081', '<NAME>'), ('15842', '<NAME>'), ('12891', 'Carolina For Kibera VCT'), ('18043', 'Catholic Archdiocese of Mombasa CHBC & AIDS Relief'), ('11960', 'Catholic Dispensary (Isiolo)'), ('18484', 'Catholic Dispensary Kariobangi'), ('16215', 'Catholic Hospital Laisamis'), ('15769', 'Catholic Hospital Wamba'), ('17922', 'Catholic Mission Dispensary'), ('12456', 'Catholic Mission Dispensary Makueni'), ('12892', 'Catholic University Dispensary'), ('19919', 'Catmag Medical Centre'), ('19689', 'Causqurow Medical Clinic'), ('11272', 'Cbk Staff Clinic (Mombasa)'), ('19072', 'Ccm Kaare'), ('11963', 'Ccs (ACK) Dispensary'), ('11964', 'Ccs Kiritiri Clinic'), ('16242', 'Ccs Macumo Clinic'), ('18378', 'Cdn VCT'), ('14280', 'Cedar Associate Clinic'), ('14281', 'Cedar Medical Clinic (Kimana)'), ('14283', 'Cengalo Dispensary'), ('19974', 'Central Bank Staff Clinic'), ('14309', 'Chelilis Dispensary'), ('17328', 'Chemamit Dispensary'), ('14310', 'Chemamul Dispensary'), ('19207', 'Chemamul Dispensary (Tinderet)'), ('14311', 'Chemaner Dispensary (Bomet)'), ('14312', 'Chemaner Dispensary (Kuresoi)'), ('14313', 'Chemartin Tea Dispensary'), ('14314', 'Chemase Dispensary'), ('14315', 'Chemase Health Centre'), ('15853', 'Chemasiri (ACK) Dispensary'), ('14316', 'Chemasis Maternity Home'), ('20436', 'Chemasusu Dispensary'), ('10091', 'Chemat For Health Solutions Kamweti'), ('14317', 'Chembulet Health Centre'), ('17319', 'Chemegong'), ('14318', 'Chemelil Dispensary'), ('13521', 'Chemelil GOK Dispensary'), ('13522', 'Chemelil Sugar Health Centre'), ('16521', 'Chemichemi Medical Clinic'), ('19837', 'Chemichemi Medical Clinic (Nyandarua)'), ('16267', 'Chemin Clinic'), ('20150', 'Chemobo dispensary'), ('14319', 'Chemogondany Hospital'), ('14320', 'Chemoiben Dispensary'), ('17095', 'Chemoinoi Dispensary'), ('17636', 'Chemokonja Dispensary'), ('14368', 'Chepterit Mission Health Centre'), ('14369', 'Chepterwai Sub-District Hospital'), ('14370', 'Chepterwo Dispensary'), ('20329', 'Cheptiangwa Dispensary'), ('17830', 'Cheptigit Dispensary'), ('14371', 'Cheptil Dispensary'), ('17013', 'Cheptilil Dispensary'), ('17024', 'Cheptingwich Dispensary'), ('14372', 'Cheptobot Dispensary'), ('14373', 'Cheptongei Dispensary'), ('14374', 'Cheptuech Dispensary'), ('14375', 'Cheptuiyet Dispensary'), ('16701', 'Chepturnguny Dispensary'), ('16736', 'Chepturu Dispensary'), ('20327', 'Cheptya Dispensary '), ('14376', 'Chepwostuiyet Dispensary'), ('14377', 'Cheramei Dispensary'), ('14378', 'Cherangan Dispensary'), ('14379', 'Cherangany Health Centre'), ('14380', 'Cherangany Nursing Home'), ('19760', 'Cherangany Nursing Home Outpatient Clinic'), ('14381', 'Cherara Dispensary'), ('17144', 'Cheronget'), ('20240', 'Cherwa Dispensary'), ('20463', 'Chesawach dispensary'), ('16680', 'Chesetan Dispensary'), ('11972', 'Chuka Cottage Hospital'), ('11973', 'Chuka District Hospital'), ('18789', 'Chuka University Dispensary'), ('17769', 'Chuka Unversity Dispensary'), ('14390', 'Chukura Dispensary'), ('13528', 'Chulaimbo Sub-District Hospital'), ('11974', 'Chuluni Dispensary'), ('11288', 'Chumani Medical Clinic'), ('14391', 'Chumvi Dispensary'), ('13529', 'Chuowe Dispensary'), ('18795', 'Church Army Medical Clinic'), ('14392', 'Churo Dispensary'), ('20047', 'Churo GOK Dispensary'), ('13530', 'Chuthber Dispensary'), ('15861', 'Chwele Friends Dispensary'), ('15860', 'Chwele Health Centre'), ('10096', 'Ciagini Health Centre'), ('11975', 'Ciama Medical Clinic'), ('10097', 'Cianda Dispensary'), ('18629', 'Cid Hqs Dispensary'), ('12897', 'Cidi Mukuru Clinic'), ('19641', 'City Point Medical Clinic'), ('14393', 'Civil Servant Dc Headquarter Dispensary'), ('17985', 'Civil Servants Clinic (Nakuru)'), ('18901', 'Clay Hill Hospital'), ('11983', 'Dakabaricha Dispensary'), ('17472', 'Dakarh Medical Services'), ('13319', 'Daley Dispensary'), ('16809', 'Dal-Lahelay Nomadic Clinic'), ('11984', 'Dallas Dispensary'), ('19068', 'Dalsan Medical Clinic'), ('18995', 'Dam Pharmacy and Clinic'), ('13320', 'Damajale Dispensary'), ('11985', 'Dambalafachana Health Centre'), ('13321', 'Dambas Health Centre'), ('19545', 'Damic Dental X-Ray Services'), ('13322', 'Danaba Health Centre'), ('19798', 'Danama Medical Clinic'), ('12911', 'Dandora (EDARP) Clinic'), ('17997', 'Dandora Health Service'), ('12913', 'Dandora I Health Centre'), ('12912', 'Dandora II Health Centre'), ('19617', 'Dandora Medical and Laboratory Services (Kojwang)'), ('18220', 'Dandora Medical Centre'), ('13323', 'Dandu Health Centre'), ('11298', '<NAME>'), ('13324', 'Danyere Health Centre'), ('19703', 'Dap Health Clinic'), ('13531', 'Daraja Medical Clinic'), ('11988', '<NAME>ursing Home'), ('16562', 'Dorjos Health Services'), ('16563', 'Dorjos Laboratory'), ('12921', 'Dorkcare Nursing Home'), ('10116', 'Dr <NAME> Radiological Clinic'), ('11310', 'Dr <NAME>'), ('19549', 'Dr <NAME>'), ('19581', 'Dr <NAME>'), ('10117', 'Dr <NAME> Medical Clinic'), ('19674', 'Dr <NAME>'), ('14405', 'Dr Aluvaala Medical Clinic'), ('16243', 'Dr <NAME>'), ('11312', 'Dr <NAME>'), ('14406', 'Dr Arthur (PCEA) Dispensary'), ('19559', 'Dr <NAME>'), ('19584', 'Dr <NAME>'), ('11313', 'Dr <NAME>'), ('12924', 'Dr <NAME> Medical Clinic'), ('11140', 'Dr <NAME>'), ('19532', 'Dr <NAME>'), ('20086', 'Dr Barnados House clinic'), ('11314', 'Dr <NAME>'), ('19585', 'Dr <NAME>'), ('11316', 'Dr <NAME>'), ('19418', 'Dr Chaundry Dental Services (Nairobi)'), ('19577', 'Dr <NAME>'), ('19558', 'Dr <NAME>'), ('19575', 'Dr <NAME>'), ('19564', 'Dr <NAME>'), ('19117', 'Abby Health Services'), ('12126', 'ABC Thange Dispensary'), ('19354', 'Abdallah Dental Clinic (Barclays Plaza-Nairobi)'), ('17009', 'Abdisamad Dispensary'), ('10001', 'Abel Migwi Johana Laboratory'), ('10003', 'Aberdare Health Services'), ('10002', 'Aberdare Medical & Surgical Clinic'), ('13461', 'Abidha Health Centre'), ('16716', 'Able Medical Clinic'), ('15789', 'Aboloi Dispensary'), ('19441', 'Abra Health Services'), ('19562', 'Abraham Memorial Nursing Home (Westlands)'), ('10004', 'Abrahams Clinic'), ('19897', 'Abundant Life Clinic'), ('19980', 'Acacia Clinic (Westlands)'), ('14415', 'Dr Mugo Medical Clinic'), ('19981', 'Dr Muhindi Clinic (Westlands)'), ('10137', 'Dr Muhiu Medical Clinic'), ('10139', 'Dr Mukui'), ('10141', 'Dr <NAME> K Psychiatric Clinic'), ('10142', 'Dr Mulingwa'), ('10143', 'Dr <NAME>'), ('19979', 'Dr Mureithi Clinic (Westlands)'), ('19221', 'Dr <NAME>'), ('19416', 'Dr <NAME>ic (Afya Centre-Nairobi)'), ('11344', 'Dr <NAME>'), ('14416', 'Dr <NAME>'), ('18728', 'Dr <NAME>'), ('11989', 'Dr Mutuma Medical Clinic'), ('10144', 'Dr Mwangi Medical Clinic'), ('11345', 'Dr <NAME>ic'), ('10145', 'Dr N N Ngugi Dental Clinic'), ('16353', 'Dr <NAME>'), ('11346', 'Dr <NAME>'), ('10146', 'Dr <NAME>ic'), ('19809', 'Dr Ndambuki Clinic'), ('19095', 'Dr Ndanya Medical Clinic'), ('10147', 'Dr <NAME>ic'), ('19569', 'Dr Ngathia Dental Clinic'), ('16565', 'Dr Ngatia''s Clinic'), ('14418', 'Dr Ngotho Medical Clinic'), ('10148', 'Dr Nguhiu'), ('14419', 'Dr <NAME>'), ('19526', 'Eastway Medical Centre'), ('10157', 'Ebenezar Medical Clinic (Muranga North)'), ('11994', 'Ebenezer Dispensary'), ('20179', 'Ebenezer Health Care Dispensary'), ('17496', 'Ebenezer Medical Clinic'), ('10158', 'Ebenezer Medical Clinic (Lari)'), ('11362', 'Ebenezer Medical Clinic (Malindi)'), ('10159', 'Ebenezer Medical Clinic (Nyeri North)'), ('10160', 'Ebenezer Medical Clinic (Nyeri South)'), ('10161', 'Ebenezer Medical Clinic (Thika)'), ('18990', 'Ebenezer Medical Services'), ('16761', 'Ebenezer Nursing Home'), ('13536', 'Eberege Dispensary'), ('13537', 'Ebiosi Dispensary'), ('15865', 'Ebukanga Dispensary'), ('17113', 'Ebukoolo Dispensary'), ('16975', 'Eburi Dispensary'), ('14425', 'Eburru Dispensary'), ('15866', 'Ebusiratsi Health Centre'), ('15867', 'Ebusyubi Dispensary'), ('16499', 'E<NAME>'), ('13220', 'EDARP Donholm Clinic'), ('17719', 'EDARP Komarock Health Centre'), ('17548', 'EDARP Njiru Clinic'), ('13169', 'EDARP Ruai Clinic'), ('18165', 'Emahene Medical Clinic'), ('12467', 'Emali Manchester Medical Clinic'), ('18260', 'Emali Model Health Centre'), ('12002', 'Emali Nursing Home'), ('17409', 'Emalindi Health Centre'), ('19270', 'Emanuel Medical Clinic'), ('14441', 'Emaroro Dispensary'), ('14442', 'Emarti Health Centre'), ('16867', 'Ematiha Dispensary'), ('15875', 'Ematsuli Dispensary'), ('19252', 'Embakasi District Medical Office'), ('12935', 'Embakasi Health Centre'), ('19437', 'Embakasi Medical Centre'), ('18894', 'Embakasi Medical Centre (Aun)'), ('10166', 'Embaringo Dispensary'), ('18073', 'Embomos Dispensary'), ('13543', 'Embonga Health Centre'), ('12003', 'Embori Farm Clinic'), ('12790', 'Embu Children Clinic'), ('16238', 'Embu Kmtc Dispensary'), ('12004', 'Embu Provincial General Hospital'), ('20204', 'Embu Univesity College Health Unit'), ('14445', 'Embul - Bul Catholic Dispensary'), ('17164', 'Embu-Mbeere Hospice'), ('14474', 'Equator Health Centre'), ('15880', 'Equator Nursing and Maternity Home'), ('17916', 'Equity Medical Clinic'), ('20351', 'Equity Medical Clinic Embulbul'), ('13546', 'Eramba Dispensary'), ('15881', 'Eregi Mission Health Centre'), ('12012', 'Eremet Dispensary'), ('18089', 'Eremit Dispensary'), ('14475', 'Ereteti Dispensary'), ('14476', 'Ereto Health Centre'), ('13547', 'Eronge Health Centre'), ('17925', 'Erreteti Dispensary'), ('14477', 'Esageri Health Centre'), ('13548', 'Esani Sub-District Hospital'), ('17263', 'Escarpment Dispensary'), ('19725', 'Escutar Health Partners Medical Clinic'), ('19899', 'Eshiabwali Health Centre'), ('18940', 'Eshibimbi Health Centre'), ('15882', 'Eshikhuyu Dispensary'), ('17217', 'Eshikulu Dispensary'), ('16114', 'Eshimukoko Health Centre'), ('15883', 'Eshiongo Dispensary'), ('17133', 'Eshirembe Dispensary'), ('16763', 'Eshisiru Catholic Dispensary'), ('12017', 'Family Medical Clinic (Machakos)'), ('18568', 'Family Nursing Home and Maternity ( Mwingi Central)'), ('10182', 'Family Planning Association of Kenya Clinic (Nyeri'), ('13553', 'Family Saver Clinic'), ('10183', 'Family Smiles Dental Clinic'), ('18155', 'Fanaka Medical Centre'), ('20454', 'FAO Hope Medical Centre'), ('20078', 'Farmers choice wellness centre clinic'), ('18617', 'Fathers Maternity and Health Services'), ('14493', 'Fatima Health Centre (Lenkism)'), ('14494', 'Fatima Maternity Hospital'), ('17908', 'Favour Primary Health Care'), ('16211', 'Fayaa Medical Clinic'), ('11373', 'Faza Hospital'), ('16392', 'FGC of Kenya Medical Centre'), ('14496', 'Fig Tree Clinic'), ('16569', 'Filhia Medical Clinic'), ('13341', 'Fincharo Dispensary'), ('14497', 'Finlay Flowers Dispensary'), ('14551', 'Finlays Hospital'), ('13340', 'Fino Health Centre'), ('13554', 'Firmview Medical Clinic'), ('18226', 'First Baptist Dispensary'), ('14498', 'Fitc Dispensary'), ('16199', 'Galili Dispensary'), ('13342', 'Galmagalla Health Centre'), ('18332', 'Galmagalla Nomadic Clinic'), ('16540', 'Gama Medical Clinic'), ('19954', 'Gamba Medical Clinic'), ('11382', 'Ganda Dispensary'), ('18300', 'Gandini Dispensary'), ('12028', 'Gangara Dispensary'), ('17224', 'Gankere Dispensary'), ('13343', 'Ganyure Dispensary'), ('11383', 'Ganze Health Centre'), ('11384', 'Garashi Dispensary'), ('12029', 'Garbatulla District Hospital'), ('19718', 'Garden Park Medical Centre'), ('18866', 'Gari Dispensary'), ('20359', 'Garissa Children Hospital'), ('13344', 'Garissa Medical Clinic'), ('17670', 'Garissa Mother and Child Care Nursing Home'), ('13345', 'Garissa Nursing Home'), ('19460', 'Garissa Pride Healthcare'), ('13346', 'Garissa Provincial General Hospital (PGH)'), ('16287', 'Garissa Teacher Training College Dispensary'), ('19079', 'Garlands Medical Centree'), ('12947', 'Garrison Health Centre'), ('10205', 'Garrissa Highway Medical Clinic'), ('19287', 'Genus Medical Services & Diagnostic Lab'), ('17461', 'Gerille Health Centre'), ('16681', 'Gerol'), ('17725', '<NAME>'), ('18585', 'Gertrudes Chidrens Clinic (Ongata Rongai)'), ('19314', 'Gertrudes Chiildren Clinic (Pangani)'), ('18191', 'Gertrudes Children Clinic (Kitengela)'), ('12950', 'Gertrudes Childrens Hospital'), ('12951', 'Gertrudes Othaya Road Dispensary'), ('13558', 'Gesabakwa Health Centre'), ('13559', 'Gesima Health Centre'), ('13560', 'Gesuguri Dispensary'), ('13561', 'Gesure Dispensary (Gucha)'), ('13562', 'Gesure Health Centre (Manga)'), ('13563', 'Gesusu (SDA) Dispensary'), ('13564', 'Gesusu Sub-District Hospital'), ('19151', 'Get Well Clinic and Lab Services'), ('10244', 'Geta Bush Health Centre'), ('14506', 'Geta Dispensary'), ('10245', 'Geta Forest Dispensary'), ('13565', 'Getambwega Dispensary'), ('13566', 'Getare Health Centre(Manga)'), ('14507', 'Getarwet Dispensary'), ('13567', 'Getembe Hospital'), ('10269', 'Githunguri Health Centre'), ('16748', 'Githunguri Health Centre (Ruiru)'), ('10270', 'Githunguri Health Services Clinic'), ('10271', 'Githunguri Heathwatch Clinic'), ('10272', 'Githunguri Medical Plaza Clinic'), ('10273', 'Githurai Community Clinic'), ('19264', 'Githurai Health Care and Dental Hospital'), ('17942', 'Githurai Liverpool VCT'), ('12956', 'Githurai Medical Dispensary'), ('12957', 'Githurai VCT'), ('10274', 'Githure (ACK) Dispensary'), ('20337', 'Githuya Dispensary'), ('10275', 'Gitiha Dispensary'), ('20312', 'Gitimaini dispensary'), ('12042', 'Gitine Dispensary'), ('17259', 'Gitithia Dispensary'), ('18147', 'Gitombani Dispensary'), ('12044', 'Gitoro Dispensary'), ('10020', 'Gituamba (AIPCA) Dispensary'), ('17837', 'Gituamba Community Dispensary'), ('10277', 'Gituamba Dispensary'), ('10278', 'Gituamba Medical Clinic'), ('10279', 'Gitugi Dispensary (Muranga North)'), ('10280', 'Gitugi Dispensary (Nyeri South)'), ('10281', 'Gitundu (ACK) Dispensary'), ('10282', 'Gitunduti Catholic Dispensary'), ('20286', 'Glory Medical Clinic (Gilgil)'), ('16739', 'Glory Medical Clinic (Kangundo)'), ('19120', 'Glory Medical Clinic (Kitui Central)'), ('11399', 'Glory Medical Clinic (Tana River)'), ('17037', 'Glory Ministry Medical Clinic'), ('18282', 'Glovnet VCT'), ('15893', 'Go Down Clinic'), ('13581', 'Gobei Health Centre'), ('13582', 'God Jope Dispensary'), ('13583', 'God Kwer Dispensary'), ('13584', 'Godber Dispensary'), ('13585', 'Godbura Health Centre'), ('11400', 'Godo Dispensary'), ('13351', 'Godoma Health Centre (Nep)'), ('12050', 'Godoma Model Health Centre (Moyale)'), ('13586', 'Gods Will Clinic'), ('19907', 'Gogo Disp'), ('14513', 'GOK Farm (Nahrc) Dispensary'), ('18264', 'GOK Prison Siaya'), ('16676', 'GOK Rumuruti Prisons Dispensary'), ('20131', 'Goldenlife Medical Centre Naivasha'), ('19427', 'Goldmed Chemists & Clinic'), ('12051', 'Golole Dispensary'), ('14542', 'Guyana Medical Clinic'), ('13597', 'Gwitembe Health Centre'), ('12966', 'Gynapaed Dispensary (Kilimani-Westlands)'), ('19205', 'Gynocare Centre Maternity Home'), ('13357', 'Habaswein District Hospital'), ('13358', 'Hadado Health Centre'), ('13359', 'Hagadera Hospital'), ('17336', 'Hagarbul Dispensary'), ('17149', 'Hakati Dspensary'), ('12967', 'Hakati Medical Clinic'), ('18920', 'Hakuna Matata Medical Clinic'), ('14885', 'Halfeez Medical Clinic'), ('19610', 'Hallal Medical Clinic'), ('10306', 'Ham Medical Clinic'), ('18801', 'Hamey Dispensary'), ('15894', 'Hamisi Sub District Hospital'), ('19970', 'Hamsadam Medical Clinic'), ('16753', 'Hamundia Health Centre'), ('19472', 'Hamza Medical Centre'), ('17751', 'Hamza Medical Clinic'), ('13360', 'Handaro Dispensary'), ('13599', 'Happy Magwagwa Clinic'), ('13361', 'Hara Health Centre'), ('19801', 'Haraka Medical Clinic'), ('12055', 'Hardship Medical Clinic'), ('13362', 'Hareri Dispensary'), ('10322', 'Holy Rosary Ikinu Dispensary'), ('14549', 'Holy Spirit Health Centre'), ('17984', 'Holy Transfiguration Orthodox Health Centre'), ('14550', 'Holy Trinity Health Centre (Mai Mahiu)'), ('18063', 'Homa Bay Central Widows VCT'), ('17926', 'Homa Bay Community Medical Clinic'), ('13608', 'Homa Bay District Hospital'), ('13605', 'Homa Clinic'), ('13606', 'Homa Hills Health Centre'), ('13607', 'Homa Lime Health Centre'), ('18056', 'Homebase Medical Clinic'), ('17676', 'Homey Medical Clinic'), ('13609', 'Hongo Ogosa Dispensary'), ('11412', 'Hongwe Catholic Dispensary'), ('11413', 'Hongwe Clinic'), ('12969', 'Hono Clinic'), ('20239', 'Hope and Health Medical Services'), ('12970', 'Hope Community VCT'), ('16983', 'Hope Compassionate (ACK) Dispensary'), ('17446', 'Hope Medical Clinic'), ('19278', 'Hope Medical Clinic ( Githurai)'), ('19234', 'Hope Medical Clinic (Babadogo)'), ('10323', 'Hope Medical Clinic (Gatundu South)'), ('10324', 'Hope Medical Clinic (Kigumo)'), ('11414', 'Hope Medical Clinic (Kilindini)'), ('19693', 'IFACO VCT'), ('13367', 'Ifmaho Medical Clinic and Laboratory'), ('18799', 'Ifo 2 Hospital'), ('13368', 'Ifo Hospital'), ('13263', 'Iftin Medical and Lab Services'), ('19009', 'Iftin Medical Clinic'), ('13369', 'Iftin Sub-District Hospital'), ('16449', 'Igago Dispensary'), ('12069', 'Igamatundu Dispensary'), ('10337', 'Igana Dispensary'), ('12070', 'Igandene Dispensary'), ('15897', 'Igara Dispensary'), ('13613', 'Igare Medical Clinic (Sameta)'), ('18864', 'Igarii Dispensary'), ('10338', 'Igegania Sub-District Hospital'), ('13614', 'Igena-Itambe Dispensary'), ('19489', 'Ignane Health Centre'), ('12071', 'Igoki Dispensary'), ('18340', 'Igorera Medical Clinic'), ('15899', 'Iguhu District Hospital'), ('14557', 'Igure Dispensary'), ('14558', 'Igwamiti Dispensary'), ('19800', 'Igwamiti Medical Clinic'), ('10339', 'Ihuririo Dispensary'), ('10340', 'Ihururu Health Centre'), ('10341', 'Ihururu Medical Clinic'), ('20019', 'Imc Tekeleza Dice - Isebania'), ('19929', 'Imc Tekeleza Dice Clinic Karungu'), ('19930', 'Imc Tekeleza Dice Clinic Muhuru'), ('14572', 'Ime (AIC) Health Centre'), ('19574', 'Imenti Medical Centre'), ('16581', 'Imenti X-Ray Services'), ('18977', 'Im-Hotep Medical Centre'), ('10518', 'Immaculate Heart Hospital Kereita'), ('10349', 'Immaculate Heart of Mary Hospital'), ('10351', 'Immanuel Medical Clinic'), ('14573', 'Immurtot Health Centre'), ('17736', 'Impact Rdo Clinic'), ('18456', 'Impact Research-Tuungane (Nyando)'), ('12983', 'Imperial Clinic'), ('16481', 'Imulama Dispensary'), ('17929', 'Indangalasia Dispensary'), ('19333', 'Index Medical Services'), ('14575', 'Industrial Area Dispensary'), ('15898', 'Ingavira Medical Clinic'), ('13371', 'Ingirir Dispensary'), ('15902', 'Ingotse Dispensary'), ('16329', 'Inkoirienito Dispensary'), ('19458', 'Innercore Medical Clinic'), ('16934', 'Itoloni Dispensary'), ('12099', 'Itongolani Dispensary'), ('19999', 'Itotia Medical Clinic'), ('12100', 'Itugururu Dispensary'), ('13630', 'Itumbe Dispensary'), ('17241', 'Itumbule Dispensary'), ('10361', 'Itundu Dispensary'), ('10362', 'Itundu Medical Clinic'), ('12101', 'Itunduimuni Health Centre'), ('10363', 'Ituramiro Medical Clinic'), ('12102', 'Iuani Health Centre'), ('12103', 'Iuuma Dispensary'), ('19891', 'Ivingoni Dispensary (Kibwezi)'), ('15905', 'Ivona Clinic'), ('12104', 'Ivuusya Dispensary'), ('13631', 'Iyabe District Hospital (Kisii South)'), ('17826', 'J A Comenius Medical Clinic'), ('17222', 'Jabali Dispensary'), ('18559', 'Jacaranda Health Limited (Ruiru)'), ('20403', 'Jacaranda Maternity (Kiamumbi )'), ('18488', 'Jacaranda Special School'), ('18333', 'Jacky Medical Clinic'), ('11421', 'Jadi Medical Clinic'), ('11423', 'Jaffery Medical Clinic'), ('16709', 'Jaggery Medical Clinic'), ('11433', 'Jilore Dispensary'), ('19754', 'Jimron Medical Clinic'), ('12990', 'Jinnah Ave Clinic'), ('10377', 'Jirani Medical Clinic'), ('18854', 'Jirime Dispensary'), ('12991', 'Jkia Health Centre'), ('10378', 'Jkuat Hospital'), ('17702', 'Jkuat Medical Clinic (Taita-Taveta) Campus'), ('20442', 'Jobefar Medical Services'), ('11434', 'Jocham Hospital'), ('18640', 'Johani Chemist'), ('17650', '<NAME> Community Clinic (Kibera)'), ('13636', 'Johpas Clinic'), ('11435', 'Joint Medical Clinic'), ('16455', 'Joint Partner Medical Clinic'), ('18968', 'Jolly Medical Clinic'), ('11437', '<NAME> (MCM) Dispensary'), ('11436', 'Jomvu Model Health Centre'), ('16802', 'Jonalifa Clinic'), ('14598', 'Joppa Medical Clinic'), ('16713', 'Jordan Baptist Medical Clinic'), ('12110', 'Jordan Hospital'), ('11439', 'Jordan Medical Clinic'), ('12111', 'Jordan Medical Clinic (Kangundo)'), ('12993', 'Kabete Approved School Dispensary'), ('12994', 'Kabete Barracks Dispensary'), ('14612', 'Kabetwa Health Centre'), ('14613', 'Kabianga Health Centre'), ('14614', 'Kabianga Tea Research'), ('14615', 'Kabichbich Health Centre'), ('14616', 'Kabichbich Miss Dispensary'), ('14617', 'Kabiemit Dispensary (Keiyo)'), ('14618', 'Kabiemit Dispensary (Mosop)'), ('14619', 'Kabimoi Dispensary'), ('14620', 'Kabinga (CHBC) Dispensary'), ('14630', 'Kabirirsang Dispensary'), ('18065', 'Kabirirsang Youth Centre'), ('12995', 'Kabiro Medical Clinic'), ('10390', 'Kabiruini Health Clinic'), ('14621', 'Kabisaga Dispensary'), ('14622', 'Kabitungu Dispensary'), ('17087', 'Kabiyet Dispensary'), ('14623', 'Kabiyet Health Centre'), ('14624', 'Kabobo Health Centre'), ('20241', 'Kabodo Dispensary'), ('14625', 'Kaboeito Dispensary'), ('20007', 'Kabogor Dispensary'), ('17023', 'Kaboi Dispensary'), ('14626', 'Kabolecho Dispensary'), ('13638', 'Kabondo Sub-District Hospital'), ('14627', 'Kaborok Dispensary'), ('10308', 'Kahawa Wendani Hospital'), ('12997', 'Kahawa West Health Centre'), ('10419', 'Kahembe Health Centre'), ('10420', 'Kaheti Dispensary & Maternity'), ('10421', 'Kahiga Dispensary'), ('10422', 'Kahuhia (ACK) Clinic'), ('10423', 'Kahuho I (AIC) Dispensary'), ('10424', 'Kahuho Private Dispensary'), ('10425', 'Kahuro Medical Clinic'), ('10426', 'Kahuru Dispensary (Nyandarua South)'), ('10427', 'Kahuru Dispensary (Nyeri North)'), ('10428', 'Kahuti Medical Clinic'), ('16961', 'Kaia Dispensary'), ('12127', 'Kaiani (ABC) Dispensary'), ('17049', 'Kaiani Dispensary'), ('14639', 'Kaibei Dispensary'), ('14640', 'Kaiboi Mission Health Centre'), ('14641', 'Kaibos Dipensary'), ('14642', 'Kaigat (SDA) Health Centre'), ('14643', 'Kaikor Health Centre'), ('16930', 'Kaikungu Dispensary'), ('10429', 'Kaimbaga Dispensary'), ('15913', 'Kaimosi Mission Hospital'), ('14644', 'Kaimosi Tea Dispensary'), ('14645', 'Kainuk Health Centre'), ('12152', 'Kalikuvu Dispensary'), ('18479', 'Kaliluni (AIC) Dispensary'), ('18811', 'Kalima Dispensary'), ('12153', 'Kalimani Disensary'), ('17919', 'Kalimani Dispensary'), ('17231', 'Kalimapus Dispensary'), ('17064', 'Kalimbene Dispensary'), ('18200', 'Kalimoni Hospital (Ruiru)'), ('10438', 'Kalimoni Hospital (Thika)'), ('12154', 'Kalisasi Dispensary'), ('12155', 'Kalitini Dispensary'), ('14662', 'Kalobeyei Dispensary'), ('14663', 'Kalokol (AIC) Health Centre'), ('12998', 'Kaloleni Dispensary'), ('12999', 'Kaloleni Health Servics'), ('19664', 'Kaloleni Medical Clinic'), ('18516', 'Kalulini Dispensary'), ('12156', 'Kalulini Dispensary (Kibwezi)'), ('20422', 'Kalulu Dispensary'), ('12157', 'Kalunga Dispensary'), ('13648', 'Kaluo Dispensary'), ('14664', 'Kalwal Dispensary'), ('14665', 'Kalyet Clinic (Kipkelion)'), ('16346', 'Kalyet Clinic (Wareng)'), ('17308', 'Kalyongwet'), ('14883', 'Kamulat Clinic'), ('10453', 'Kamumo Medical Clinic'), ('12164', 'Kamumu Dispensary'), ('15919', 'Kamuneru Dispensary'), ('10454', 'Kamung''ang''a (ACK) Dispensary'), ('10455', 'Kamunyaka Clinic'), ('17913', 'Kamunyange Dispensary'), ('17640', 'Kamurguiywa Dispensary'), ('14678', 'Kamurio Dispensary'), ('12165', 'Kamusiliu Dispensary'), ('19017', 'Kamuskut Clinic'), ('12166', 'Kamutei Health Centre'), ('12167', 'Kamuthanga Dispensary'), ('12168', 'Kamuthatha Clinic'), ('13378', 'Kamuthe Health Centre'), ('18760', 'Kamuthini Dispensary'), ('16588', '<NAME>'), ('12169', 'Kamuwongo Dispensary'), ('17831', 'Kamuyu Dispensary'), ('10456', 'Kamwangi Health Services'), ('12170', 'Kamwathu Dispensary'), ('19989', 'Kamwega Dispensary'), ('19777', 'Kamwenja Teachers Training College'), ('10458', 'Kamweti Dispensary'), ('14679', 'Kamwingi Dispensary'), ('19369', 'Kamwitha Medcal Centre'), ('17317', 'Kapchanga Dispensary'), ('14690', 'Kapchebar Dispensary'), ('14691', 'Kapchebau Dispensary'), ('18064', 'Kapchebwai Dispensary'), ('14692', 'Kapchelal Dispensary'), ('14693', 'Kapchemogen Dispensary'), ('18207', 'Kapchemuta Dispensary'), ('15921', 'Kapchemwani Dispensary'), ('17635', 'Kapchepkok Dispensary'), ('14694', 'Kapchepkor Dispensary'), ('14695', 'Kapcherop Health Centre'), ('14696', 'Kapchorua Tea Dispensary'), ('14697', 'Kapchumba Dispensary'), ('17722', 'Kapchumbe Dispensary'), ('14699', 'Kapedo Sub-District Hospital'), ('14700', 'Kapelibok Dispensary'), ('14701', 'Kapenguria District Hospital'), ('14702', 'Kapindasim Dispensary'), ('18506', 'Kapisimba Dispensary'), ('13655', 'Kapiyo Dispensary'), ('14703', 'Kapkagaron Dispensary'), ('14704', 'Kapkangani Health Centre'), ('19590', 'Kapkara Dispensary'), ('14705', 'Kapkata Dispensary'), ('15922', 'Kapkateny Dispensary'), ('14706', 'Kapkatet District Hospital'), ('14758', 'Kapsetek Dispensary'), ('14917', 'Kapsikak Tea Dispensary'), ('16414', 'Kapsimbeiywo Dispensary'), ('14759', 'Kapsimotwa Dispensary'), ('14760', 'Kapsinendet Dispensary'), ('17631', 'Kapsirichoi Dispensary'), ('14761', 'Kapsisiywo Dispensary'), ('16401', 'Kapsita Dispensary'), ('14762', 'Kapsitwet Dispensary'), ('18209', 'Kapsiw Dispensary'), ('14763', 'Kapsiwon Tea Dispensary'), ('17313', 'Kapsiya'), ('14764', 'Kapsogut Dispensary'), ('17138', 'Kapsoit'), ('19361', 'Kapsoiyo Dispensary'), ('19388', 'Kapsokwony Medicare'), ('14765', 'Kapsomboch Dispensary'), ('19157', 'Kapsongoi Dispensary'), ('14766', 'Kapsorok Dispenasry'), ('14767', 'Kapsowar (AIC) Hospital'), ('14768', 'Kapsowar Dispensary'), ('14769', 'Kapsoya Health Centre'), ('17139', 'Kapsuser'), ('14770', 'Kapsuser Medical Clinic'), ('14772', 'Kaptabuk Dispensary'), ('14771', 'Kaptabuk Dispensary (Marakwet)'), ('14773', 'Kaptagat Forest Dispensary'), ('19100', 'Karengata Community Medical Centre'), ('18452', 'Karerema Dispensary'), ('10492', 'Kareri Medical Clinic'), ('17588', 'Kargeno VCT'), ('12199', 'Kargi Dispensary'), ('17920', 'Kari Dispensary (Kiboko)'), ('13005', 'Kari Health Clinic'), ('12200', 'Karia Dispensary'), ('10493', 'Karia Health Centre'), ('16998', 'Karia Health Centre (Nyeri South)'), ('16462', 'Kariakomo Dispensary'), ('18433', 'Karibaribi Dispensary'), ('16445', 'Kariko Dispensary'), ('10494', 'Kariko Dispensary (Nyeri South)'), ('10495', 'Karima Catholic Dispensary'), ('15927', 'Karima Dispensary'), ('10496', 'Karima Dispensary (Nyeri South)'), ('18670', 'Karimaini Community Dispensary'), ('12201', 'Karimba Dispensary'), ('20344', 'Karimboni Dispensary'), ('12202', 'Karimonga Dispensary'), ('20311', 'Karindundu dispensary'), ('10497', 'Karinga Mission'), ('18743', 'Kariobangi EDARP'), ('13006', 'Kariobangi Health Centre'), ('19992', 'Kathathani Medical Clinic'), ('16434', 'Katheka Dispensary'), ('17382', 'Kathelwa Dispensary'), ('12228', 'Kathelwa Medical Clinic'), ('20417', 'Kathemboni Dispensary'), ('12229', 'Kathera Dispensary'), ('17216', 'Katheri Health Centre'), ('19160', 'Kathiani Clinic'), ('12230', 'Kathiani District Hospital'), ('18902', 'Kathiani Medical Clinic'), ('12232', 'Kathigu Health Centre'), ('20418', 'Kathini Dispensary'), ('12233', 'Kathiranga Dispensary'), ('12234', 'Kathithi Dispensary'), ('18847', 'Kathithine Dispensary'), ('18514', 'Kathome Dispensary'), ('20182', 'Kathome Dispensary (Kangundo)'), ('16251', 'Kathome Medical Clinic'), ('12235', 'Kathonzweni Catholic Dispensary'), ('12236', 'Kathonzweni Health Centre'), ('12237', 'Kathukini Dispensary'), ('12238', 'Kathulumbi Dispensary'), ('19148', 'Kathungi Dispensary'), ('12239', 'Kathunguri Dispensary'), ('12240', 'Kathyaka Dispensary'), ('13663', 'Kegonga District Hospital'), ('13664', 'Kehancha Clinic'), ('13665', 'Kehancha Nursing and Maternity Home'), ('19752', 'Keiyo Dispensary'), ('17504', 'Kema Medical Clinic'), ('20247', 'Kemakoba Dispensary'), ('17083', 'Kembu Dispensary'), ('14825', 'Kemeloi Health Centre'), ('13666', 'Kemera Dispensary (Manga)'), ('18301', 'Kemri Clinic'), ('18505', '<NAME>'), ('11458', 'Kemri Staff Clinic and VCT Centre'), ('13019', 'Kemri VCT'), ('20146', 'KEMRI/CDC Health Services'), ('18357', 'Kemsa Staff Clinic'), ('19084', 'Kemu Medical Clinic'), ('20293', 'Kemunchugu (Nyamira North)'), ('19871', 'Ken Ame Health Centre'), ('18620', 'Kendi Medical Clinic'), ('13667', 'Kendu Adventist Hospital'), ('13668', 'Kendu Sub-District Hospital'), ('14826', 'Kenegut Dispensary'), ('14827', 'Kenene Dispensary'), ('13669', 'Kengen Clinic'), ('17332', 'Kengen Staff Clinic'), ('20282', 'Kenlands Health Services'), ('14843', 'Keturwo Dispensary'), ('13679', 'Keumbu Medical Clinic'), ('13680', 'Keumbu Sub-District Hospital'), ('12269', 'Kevote Catholic Dispensary'), ('16415', 'Kewamoi Dispensary'), ('17327', 'Keyian SDA Dispensary'), ('18695', 'Khaburu Chemist'), ('18644', 'Khaburu Chemist'), ('15929', 'Khachonge Dispensary'), ('16182', 'Khadija Medical Clinic'), ('20321', 'Khairat Medical Centre'), ('15930', 'Khaja Medical Clinic'), ('15931', 'Khalaba Health Centre'), ('17881', 'Khalaba Medical Clinic'), ('18362', 'Khalala Dispensary'), ('13379', 'Khalalio Health Centre'), ('15932', 'Khalumuli Dispensary'), ('15933', 'Khaoya Dispensary'), ('15934', 'Kharanda Dispensary'), ('14844', 'Khartoum Tea Dispensary'), ('15935', 'Khasoko Health Centre'), ('15936', 'Khaunga Dispensary'), ('18240', 'Khayega Community Clinic'), ('15937', 'Khayo Dispensary'), ('19097', 'KHE Farm Dispensary'), ('10564', 'Kianyaga Catholic Health Centre'), ('10565', 'Kianyaga Sub-District Hospital'), ('12281', 'Kiaoni Dispensary (Kibwezi)'), ('20272', 'Kiaora Farm Dispensary'), ('10566', 'Kiaragana Dispensary'), ('12283', 'Kiarago Health Centre (Imenti South)'), ('17571', 'Kiarithaini Dispensary'), ('10567', 'Kiaruhiu (PCEA) Health Centre'), ('10568', 'Kiaruhiu Medical Clinic'), ('13685', 'Kiaruta Dispensary'), ('17060', 'Kiarutara Dispensary'), ('13686', 'Kiasa Dispensary'), ('17935', 'Kiati Dispensary'), ('19110', 'Kiatineni Dispensary'), ('18014', 'Kiawa Medical Clinic'), ('16782', 'Kiawaithanji Medical Clinic'), ('19595', 'Kiawakara Dispensary'), ('10570', 'Kiawarigi Medical Clinic'), ('14847', 'Kibabet Tea Dispensary'), ('15941', 'Kibabii Health Centre'), ('14848', 'Kibagenge Dispensary'), ('18293', 'Kiban Medical Clinic'), ('12285', 'Kiban Medical Clinic (Kangundo)'), ('11464', 'Kibandaongo Dispensary'), ('12280', 'Kibaranyaki Dispensary'), ('15943', 'Kibisi Dispensary'), ('13688', 'Kibogo Dispensary'), ('14855', 'Kiboino Dispensary'), ('12286', 'Kiboko Dispensary (Makindu)'), ('19349', 'Kiboko Medical Clinic'), ('11465', 'Kibokoni Medical Clinic'), ('19839', 'Kibomet Medical Clinic'), ('19364', 'Kibongwa Dispensary'), ('19390', 'Kibonze Dispenary'), ('13689', 'Kibos Sugar Research Dispensary'), ('20440', 'Kiboson Dispensary'), ('10573', 'Kibubuti Dispensary'), ('14856', 'Kibugat Dispensary'), ('12287', 'Kibugu Health Centre'), ('12288', 'Kibugua Health Centre'), ('15944', 'Kibuke Dispensary'), ('12289', 'Kibunga Sub-District Hospital'), ('12290', 'Kiburine Dispensary'), ('10574', 'Kiburu Dispensary'), ('10575', 'Kiburu Laboratory'), ('10577', 'Kibutha Dispensary'), ('10578', 'Kibutha Medical Clinic'), ('11466', 'Kibuyuni Dispensary'), ('14857', 'Kibwareng Health Centre'), ('14858', 'Kibwari Tea Dispensary'), ('12737', 'Kibwezi Catholic Dispensary'), ('12313', 'Kilome Nursing Home'), ('20424', 'Kilonzo Dispensary'), ('19945', 'Kiltamany Dispensary'), ('16926', 'Kilulu Dispensary'), ('12314', 'Kilungu Sub-District Hospital'), ('15946', 'Kima Mission Hospital'), ('12315', 'Kimachia Dispensary'), ('15947', 'Kimaeti Dispensary'), ('10605', 'Kimahuri Medical Clinic'), ('14867', 'Kimalel Health Centre'), ('15948', 'Kimalewa Health Centre'), ('14868', 'Kimana Health Centre'), ('10606', 'Kimandi Clinic and Laboratory'), ('12316', 'Kimangao Dispensary'), ('15949', 'Kimangeti Dispensary'), ('14869', 'Kimanjo Dispensary'), ('19967', 'Kimathi Dispensary'), ('19330', 'Kimathi Street Medical Centre'), ('18228', 'Kimathi University College Medical Clinic'), ('16671', 'Kimawit-Uswet Dispensary'), ('20439', 'Kimaya Dispensary'), ('10607', 'Kimbimbi Medical Clinic'), ('10608', 'Kimbimbi Medical Laboratory'), ('10609', 'Kimbimbi Sub-District Hospital'), ('20130', 'Kimeeni Dispensary'), ('16196', 'Kinyadu Dispensary'), ('19893', 'Kinyambu Dispensary'), ('20108', 'Kinyambu Kwitu Medical Clinic'), ('10617', 'Kinyangi Health Centre'), ('17307', 'Kinyona Dispensary'), ('10618', 'Kinyona Health Clinic'), ('19917', 'Kiobegi Dispensary (Nyamache)'), ('20113', 'Kioge Disp'), ('13696', 'Kiogoro Health Centre'), ('20292', 'Kiomara (Nyamira North)'), ('16655', 'Kiomo Dispensary'), ('18678', 'Kiongwe Dispensary'), ('12328', 'Kionyo Dispensary (Imenti South)'), ('13697', 'Kionyo Health Centre (Nyamache)'), ('12329', 'Kionyo Medical Clinic'), ('11483', 'Kipao Dispensary'), ('20095', 'Kipawa Medical Centre'), ('14889', 'Kipcherere Dispensary'), ('14890', 'Kipchimchim M Hospital'), ('19251', 'Kipegenda Dispensary'), ('14891', 'Kipeto Dispensary'), ('16269', 'Kipingi Dispensary'), ('11484', 'Kipini Health Centre'), ('19792', 'Kipipiri Medical Centre'), ('14892', 'Kipkabus Forest Dispensary'), ('14893', 'Kipkabus Health Centre'), ('15951', 'Kipkaren Clinic'), ('10628', 'Kirichu Market Medical Clinic'), ('12333', 'Kirie Dispensary'), ('12334', 'Kirie Mission Clinic'), ('10629', 'Kiriita Forest Dispensary'), ('10630', 'Kirima Dispensary'), ('19143', 'Kirimampio Dispensary'), ('10631', 'Kirimara Clinic'), ('16842', 'Kirimara Medical Clinic'), ('19770', 'Kirimara Optical'), ('10632', 'Kirimukuyu Medical Clinic'), ('14515', 'Kirimun GK Dispensary'), ('12335', 'Kirin Agribio (Yoder) Clinic'), ('12336', 'Kirindine Nursing Home'), ('10633', 'Kirinyaga Laboratory Supplies'), ('10634', 'Kiriogo Dispensary'), ('16466', 'Kiritiri Health Centre'), ('12337', 'Kirogine Dispensary'), ('16592', 'Kirogine Medical Clinic'), ('10635', 'Kirogo Dispensary'), ('10636', 'Kirogo Health Centre'), ('14939', 'Kiromwok Dispensary'), ('19391', 'Kirongoi Dispensary'), ('12338', 'Kiroo Clinic'), ('18850', 'Kiroone Dispensary'), ('14906', 'Kiropket Dispensary'), ('12339', 'Kirumi Dispensary'), ('16849', 'Kithaku Medical Clinic'), ('12350', 'Kithatu Medical Clinic'), ('12352', 'Kithayoni Medical Clinic'), ('12353', 'Kithegi Dispensary'), ('12354', 'Kitheo Dispensary'), ('12355', 'Kitheuni Dispensary'), ('12356', 'Kithima (ABC) Dispensary'), ('12357', 'Kithimani Dispensary'), ('12358', 'Kithimani Medical Clinic'), ('12359', 'Kithimu Dispensary'), ('17225', 'Kithithina Dispensary'), ('20021', 'Kithito Medical Centre'), ('17445', 'Kithituni Health Care Clinic'), ('18643', 'Kithoka Chemist'), ('16226', 'Kithoka Outreach Clinic'), ('12360', 'Kithuki Health Centre'), ('12361', 'Kithunguriri Dispensary'), ('16959', 'Kithuni Dispensary'), ('12362', 'Kithyoko Health Centre'), ('12363', 'Kithyoko Mercy Medical Clinic'), ('12364', 'Kithyululu Dispensary'), ('17742', 'Kiti Dispensary'), ('12365', 'Kitise Health Centre'), ('17538', 'Kitise Rural Development VCT'), ('17643', 'Kititu Dispensary'), ('14952', 'Kitoben Dispensary'), ('14975', 'Kokuro Dispensary'), ('14976', 'Kokwa Dispensary'), ('13712', 'Kokwanyo Health Centre'), ('14977', 'Kokwet Dispensary'), ('17633', 'Kokwet Medical Clinic'), ('18204', 'Kokwongoi Dispensary'), ('20316', 'Kokwotendwo Dispensary'), ('14978', 'Kokwototo Dispensary'), ('12381', 'Kola Health Centre'), ('15953', 'Kolanya Salavation Army Dispensary'), ('17172', 'Kolenyo Dispensary'), ('14980', 'Koloch Dispensary'), ('14981', 'Kolongolo M Dispensary'), ('17038', 'Koloo Dispensary'), ('14979', 'Kolowa Health Centre'), ('17344', 'Kolwal Dispensary'), ('13038', 'Komarock Medical Clinic'), ('17717', 'Komarock Morden Medical Care'), ('16270', 'Kombato Dispensary'), ('13713', 'Kombe Dispensary'), ('14982', 'Kombe Dispensary (Nandi Central)'), ('11498', 'Kombeni Dispensary'), ('13714', 'Kombewa District Hospital'), ('20347', 'Kome Dispensary'), ('14983', 'Komolion Dispensary'), ('13727', 'Kusa Health Centre'), ('13389', 'Kutulo Health Centre (Wajir East)'), ('10646', 'Kutus Catholic Dispensary'), ('10647', 'Kutus Dispensary'), ('15959', 'Kuvasali Health Centre'), ('16541', 'Kuze Health Care'), ('12392', 'Kwa Judy Medical Clinic'), ('16933', 'Kwa Kavoo Dispensary'), ('19242', 'Kwa Kilui Dispensary'), ('19417', 'Kwa Kulu Dispensary'), ('17499', 'Kwa Mbekenya Dispensary'), ('12393', 'Kwa Mulungu Dispensary'), ('18449', 'Kwa Mutalia Dispensary'), ('12394', 'Kwa Mutonga Dispenasry'), ('17104', 'Kwa Mwatu Dispensary'), ('11506', 'Kwa Ndomo Medical Clinic'), ('10651', 'Kwa Ng''ang''a Medicare'), ('12395', 'Kwa Nguu Dispensary'), ('12396', 'Kwa Vonza Dispensary'), ('18682', 'Kwa-Amutei Dispensary'), ('12397', 'Kwakala Dispensary'), ('20214', 'Kwakalui dispensary'), ('20197', 'Kwakalusya Dispensary'), ('12398', 'Kwakavisi Dispensary'), ('20446', 'kwakilui Dispensary'), ('12399', 'Kwale Dispensary'), ('15005', 'Laliat Dispensary'), ('15006', 'Lalwet Dispensary'), ('17348', 'Lamaiwe Dispensary'), ('12424', 'Lamba Medical Clinic'), ('13731', 'Lambwe Dispensary'), ('13732', 'Lambwe Forest Dispensary'), ('16376', 'Lamorna Farm Clinic'), ('11511', 'Lamu Clinic'), ('11512', 'Lamu District Hospital'), ('11513', 'Lamu Fort VCT'), ('15007', 'Lamuria Dispensary (Laikipia East)'), ('10653', 'Lamuria Dispensary (Nyeri North)'), ('13040', 'Landmawe Medical Services'), ('15008', 'Lanet Health Centre'), ('19180', 'Lanet Kiondoo Medical Clinic'), ('15009', 'Langa Langa Health Centre'), ('15010', 'Langa Medical Care'), ('15011', 'Langas RCEA'), ('17384', 'Lang''ata Comprehensive Medical Service'), ('18762', 'Lang''ata Dispensary (Ruiru)'), ('15012', 'Langata Enkima Dispensary'), ('13041', 'Langata Health Centre'), ('13042', 'Langata Hospital'), ('13044', 'Langata Women Prison Dispensary'), ('18250', 'Langi Kawino Dispensary'), ('15029', 'Lesirikan Health Centre'), ('15030', 'Lessos Community Dispensary'), ('15031', 'Letea Dispensary'), ('19951', 'Letuaih VCT'), ('18470', 'Levice Medical Clinic'), ('12426', 'Lewa Downs Dispensary'), ('20348', 'Lewa''s Family Nursing Home'), ('19816', 'Lex Medical Clinic'), ('18954', 'Lexa Medical Centre'), ('18235', 'Leysanyu Dispensary'), ('13049', 'Lianas Clinic Health Centre'), ('15032', 'Liavo Medical Clinic (Kwanza)'), ('15033', 'Liavo Medical Clinic (Trans Nzoia West)'), ('16288', 'Libahlow Nomadic Clinic'), ('17895', 'Liban Medical Clinic'), ('13395', 'Liban Pharmacy'), ('13396', 'Libehiya Dispensary'), ('12427', 'Liberty Maternity and Nursing Home'), ('18048', 'Liberty Medical Clinic'), ('13397', 'Liboi Clinic'), ('13398', 'Liboi Health Centre'), ('17525', 'Lidha Dispensary'), ('17439', 'Lieta Health Centre (Rarieda)'), ('10659', 'Life Care Ministry Clinic'), ('18172', 'Life Water Ndege Mobile Clinic'), ('15045', 'Lochwaangikamatak Dispensary'), ('13051', 'Loco Dispensary'), ('15047', 'Lodokejek Dispensary'), ('15048', 'Lodungokwe Health Centre'), ('15049', 'Lodwar District Hospital'), ('16213', 'Logologo AIC Dispensary'), ('18857', 'Logologo Model Health Centre (Marsabit South)'), ('17278', 'Loikumkum Dispensary'), ('15050', 'Loima Medical Clinic'), ('15051', 'Loitokitok District Hospital'), ('15052', 'Loitokitok Medical Clinic'), ('19254', 'Loitokitok Medicare Centre'), ('15053', 'Loiwat Dispensary'), ('12432', 'Loiyangalani Dispensary'), ('12433', 'Loiyangalani Health Centre'), ('17196', 'Lokaburu'), ('15054', 'Lokamarinyang Dispensary'), ('15055', 'Lokangae Health Centre'), ('15056', 'Lokapel Dispensary'), ('15057', 'Lokichar (RCEA) Health Centre'), ('15058', 'Lokichoggio Military Dispensary'), ('15059', 'Lokichogio (AIC) Health Centre'), ('15060', 'Lokipoto Dispensary'), ('15061', 'Lokiriama Dispensary'), ('18042', 'Lukim Medical Clinic'), ('15968', 'Lukolis Model Health Centre'), ('11525', 'Lukore Dispensary'), ('17298', 'Lukoye Health Centre'), ('18125', 'Lukusi Dispensary'), ('16711', 'Lukusi Dispensary'), ('15969', 'Lumakanda District Hospital'), ('15970', 'Lumani Dispensary'), ('18852', 'Lumboka Medical Services'), ('18624', 'Lumino Dispensary'), ('15971', 'Lumino Maternity and Nursing Home'), ('13738', 'Lumumba Health Centre'), ('19481', 'Lumumba Medical Clinic'), ('20156', 'Lunakwe Dispensary'), ('12435', 'Lundi Dispensary'), ('13053', 'Lunga Lunga Health Centre'), ('15973', 'Lungai Dispensary'), ('11526', 'Lungalunga Dispensary'), ('17494', 'Lungalunga Health Centre'), ('15972', 'Lung''anyiro Dispensary'), ('15974', 'Lunyito Dispensary'), ('15102', 'Luoniek Dispensary'), ('15975', 'Lupida Health Centre'), ('15976', 'Lurare Dispensary'), ('13751', 'Magina Health Centre'), ('11537', 'Magodzoni Dispensary'), ('17134', 'Magombo Community Dispensary (Manga)'), ('13752', 'Magombo Health Centre'), ('11538', 'Magongo (MCM) Dispensary'), ('12444', 'Magundu Dispensary'), ('13753', 'Magunga Health Centre'), ('13754', 'Magura Dispensary'), ('10669', 'Magutu (PCEA) Dispensary'), ('12445', 'Magutuni District Hospital'), ('13755', 'Magwagwa (SDA) Dispensary'), ('13756', 'Magwagwa Health Centre'), ('18187', 'Mahandakini Dispensary'), ('15987', 'Mahanga Dispensary'), ('16388', 'Mahanga Dispensary'), ('16144', 'Mahatma Gandi Health Centre'), ('13757', 'Mahaya Health Centre (Rarieda)'), ('16679', 'Mahianyu Dispensary'), ('10670', 'Mahiga (PCEA) Dispensary'), ('15108', 'Mai Mahiu Health Centre'), ('19139', 'Mai Mahiu Maternity and Hospital'), ('19554', 'Maichoma Clinic'), ('15106', 'Maiela Health Centre'), ('12446', 'Maikona Dispensary'), ('20002', 'Maili Saba Dispensary'), ('18831', 'Malabot Dispensary (North Horr)'), ('17150', 'Malaha Dispensary'), ('19622', 'Malaika Health Centre'), ('15994', 'Malakisi Health Centre'), ('12459', 'Malalani Dispensary'), ('11553', 'Malanga (AIC) Dispensary'), ('15995', 'Malanga Dispensary'), ('20342', 'Malanga Dispensary -Vitengeni'), ('13760', 'Malanga Health Centre'), ('15996', 'Malava District Hospital'), ('15997', 'Malekha Dispensary'), ('13761', 'Malela Dispensary'), ('20013', 'Maliera Mission Dispensary'), ('12460', 'Maliku Health Centre'), ('11556', 'Malindi Care Services Limited'), ('11555', 'Malindi District Hospital'), ('11557', 'Malindi Sea Breeze'), ('15998', 'Malinya Clinic'), ('20267', 'Malioni Dispensary'), ('12461', 'Malka Daka Dispensary'), ('12462', 'Malka Galla Dispensary'), ('13400', 'Malkagufu Dispensary'), ('13401', 'Malkamari Health Centre'), ('18487', 'Malkamari Health Centre'), ('10683', 'Maragi Medical Clinic'), ('10684', 'Maragua (African Christian Churches and Schools) C'), ('10685', 'Maragua Clinic'), ('10686', 'Maragua District Hospital'), ('10687', 'Maragua Ridge Health Centre'), ('15124', 'Maraigushu Dispensary'), ('16001', 'Marakusi Dispensary'), ('15125', 'Maralal Catholic Dispensary'), ('15126', 'Maralal District Hospital'), ('14526', 'Maralal GK Prison Dispensary'), ('16322', 'Maralal Medical Clinic'), ('16258', 'Maram Dispensary'), ('15127', 'Maramara Dispensary'), ('19671', 'Marambach Mc'), ('18985', 'Maranatha Medical Services'), ('13772', 'Marani District Hospital'), ('10688', 'Maranjau Dispensary'), ('15128', 'Mararianta Dispensary'), ('16595', 'Marble Clinic'), ('16596', 'Marble Medical Laboratory'), ('18948', 'March Medicare'), ('13773', 'Marenyo Health Centre'), ('11563', 'Marereni Dispensary'), ('11564', 'Marereni Medical Clinic'), ('13061', '<NAME> Dispensary'), ('20409', 'masaani dispensary'), ('16715', 'Masaba Dispensary'), ('13678', 'Masaba District Hospital'), ('13779', 'Masaba Health Centre'), ('18414', 'Masaba Hospital Kisumu'), ('15149', 'Masaita/ Miti-Tatu Dispensary'), ('13780', 'Masala Dispensary'), ('20428', 'Masasini Dispensary'), ('18550', 'Maseki Dispensary'), ('17157', 'Masendebale Dispensary'), ('13781', 'Maseno Mission Hospital'), ('13782', 'Maseno University Medical Clinic'), ('18663', 'Mashaallah Nursing Home-Habaswein'), ('17111', 'Mashambani Dispensary'), ('16325', 'Mashangwa Dispensary'); INSERT INTO `facility_list` (`Facility_Code`, `Facility_Name`) VALUES ('11575', 'Mashauri Medical Centre'), ('15150', 'Mashuru Health Centre'), ('17739', 'Masii Catholic Dispensary'), ('12475', 'Masii Health Centre'), ('17279', 'Masikita Dispensary'), ('18509', 'Masimba'), ('13783', 'Masimba Sub-District Hospital'), ('16764', 'Masinde Muliro University of Science and Technolog'), ('12476', 'Masinga Sub County Hospital'), ('16003', 'Matayos Community Clinic'), ('16004', 'Matayos Health Centre'), ('19838', 'Matches Medical Clinc'), ('19912', 'Matercare Maternity Hospital'), ('12481', 'Materi Girls Dispensary'), ('16005', 'Matete Health Centre'), ('10705', 'Mathakwaini (PCEA) Dispensary'), ('13075', 'Mathare 3A (EDARP)'), ('13077', 'Mathare North Health Centre'), ('13078', 'Mathare Police Depot'), ('13076', 'Mathari Hospital'), ('10706', 'Matharite Dispensary'), ('15154', 'Matharu Dispensary'), ('18106', 'Mathigu Road Medical Clinic'), ('12482', 'Mathima Dispensary'), ('10707', 'Mathingira Medical Clinic'), ('20363', 'Mathow'), ('12483', 'Mathuki Health Centre'), ('16656', 'Mathunzini Dispensary'), ('16927', 'Mathyakani Dispensary'), ('17528', 'Matibabu Nzoia Clinic'), ('17529', 'Matibabu Ukwala Clinic'), ('12484', 'Matiliku Catholic Dispensary'), ('12485', 'Matiliku District Hospital'), ('12486', 'Matinyani Dispensary'), ('20199', 'Mbaka Oromo Dispensary'), ('11588', 'Mbalambala Dispensary'), ('11589', 'Mbale Health Centre'), ('12497', 'Mbale Medical Clinic'), ('16012', 'Mbale Rural Health Training Centre'), ('16013', 'Mbaleway Side Clinic'), ('17622', 'Mbaraki Police VCT'), ('19964', 'Mbari Ya Igi Dispensary'), ('18824', 'Mbaruk Dispensary'), ('17976', 'Mbaruk-Echareria Dispensary'), ('17260', 'Mbau-Ini Dispensary'), ('17839', 'Mbavani Dispensary'), ('16467', 'Mbeere District Hospital'), ('20088', 'Mbeere south DHMT'), ('12498', 'Mbembani Dispensary'), ('12499', 'Mbenuu H Centre'), ('12500', 'Mbeu Sub-District Hospital'), ('10711', 'Mbici Dispensary'), ('19987', 'Mbiini Dispensary'), ('18174', 'Mbiri (ACK) Dispensary'), ('10713', 'Mbiriri Catholic Dispensary'), ('12501', 'Mbita Dispensary'), ('13798', 'Mbita District Hospital'), ('16996', 'Mbitini (ACK) Dispensary'), ('12502', 'Mbitini Catholic Dispensary'), ('12521', 'Mbitini Health Centre'), ('12503', 'Mbiuni Health Centre'), ('13088', 'Mercillin Afya Centre'), ('16746', 'Mercy Afya Clinic'), ('20232', '<NAME>ic'), ('12511', 'Mercy Clinic (Ikutha)'), ('15173', 'Mercy Dispensary'), ('16822', 'Mercy Dispensary (Lare)'), ('17466', 'Mercy Health Centre'), ('15174', 'Mercy Hospital'), ('10563', 'Mercy Medical (Kianugu) Clinic'), ('18135', 'Mercy Medical Clinic'), ('19179', 'Mercy Medical Clinic'), ('12512', 'Mercy Medical Clinic (Embu)'), ('18904', 'Mercy Medical Clinic (Kitui Central)'), ('10721', 'Mercy Medical Clinic (Othaya)'), ('18974', 'Mercy Medical Clinic Engineer'), ('19319', 'Mercy Medical Services'), ('13089', 'Mercy Mission Health Centre'), ('18691', 'Mercy Mission Medical Dispensary'), ('15175', 'Mercy Mobile Clinic (Kipkelion)'), ('15176', 'Mercy Mobile Clinic (Molo)'), ('18597', 'Mercylight Hospital'), ('10722', 'Mere Dispensary'), ('15177', 'Merewet Dispensary'), ('13409', 'Meri Health Centre'), ('13109', 'Meridian Equator Hospital'), ('18351', 'Meridian Medical Centre'), ('19546', 'Meridian Medical Centre'), ('13084', 'Meridian Medical Centre (Buruburu)'), ('18591', 'Meridian Medical Centre (Capital Centre)'), ('19395', 'Meridian Medical Centre (Loita Street)'), ('18916', 'Meridian Medical Centre (Machakos)'), ('18631', 'Meridian Medical Centre (Meru)'), ('19550', 'Meridian Medical Centre (Penson Towers)'), ('19696', 'Meridian Medical Centre Kitengela'), ('18371', 'Meridian Medical Centre Nakuru'), ('19799', 'Meridian Medical Centre Nyeri'), ('18528', 'Meridian Medical Centre- Nyeri Town'), ('18085', 'Meridian Medical Centre Ongata Rongai'), ('20104', 'Meridian Medical centre(Nation Centre Bldg )'), ('17727', 'Meridian Medical Donholm Clinic'), ('15178', 'Merigi Dispensary'), ('16217', 'Merille Dispensary'), ('12513', 'Merti Catholic Dispensary'), ('12514', 'Merti Health Centre'), ('15179', 'Merto Dispensary'), ('16599', 'Meru Clinic'), ('18731', 'Meru Consultant Clinic'), ('16600', 'Meru Consultants'), ('16601', 'Meru Consultants Laboratory'), ('19073', 'Meru Cytology Centre'), ('16602', 'Meru Dental Services'), ('16603', 'Meru Diagnostic Centre'), ('18700', 'Meru Diagnostic Centre'), ('16604', 'Meru Dignostic / Laboratory Services'), ('12516', 'Meru District Hospital'), ('18653', 'Meru Eye Care Services'), ('19113', 'Meru Funeral Home'), ('19102', 'Meru Gynecologist Centre'), ('19135', 'Meru Hospice'), ('20053', 'Meru Kmtc Student/Staff Clinic'), ('18706', 'Meru Lab Services'), ('18648', 'Meru Lab Services'), ('16605', 'Meru Medical /ENT Clinic'), ('16606', 'Meru Medical Diagnostic Imaging Centre Ltd'), ('16607', 'Meru Medical Plaza'), ('16608', 'Meru Medical Plaza Laboratory'), ('17266', 'Meru Technical Training College Clinic'), ('19063', 'Meru X-Ray Services'), ('15180', 'Merueshi Village Community Health Centre'), ('20034', 'Mesedith Medical Clinic'), ('17251', 'Meswo Medical Clinic'), ('13802', 'Metaburo Health Centre'), ('16302', 'Metameta Clinic'), ('15181', 'Meteitei Sub-District Hospital'), ('17079', 'Meti Dispensary'), ('15182', 'Meto Dispensary'), ('10723', 'Metro Optician'), ('19463', 'Metropolitan Dr Plaza'), ('13090', 'Metropolitan Hospital Nairobi'), ('20200', 'Metropolitan Medical Clinic - Kehancha'), ('15183', 'Metta Dispensary'), ('11600', 'Mewa Hospital'), ('20192', 'Meyan Dispensary'), ('19303', 'Mfariji Medical Clinic'), ('11601', 'Mgamboni Dispensary'), ('11602', 'Mgange Dawida Dispensary'), ('11603', 'Mgange Nyika Health Centre'), ('12518', 'Miambani Catholic'), ('12519', 'Miambani Health Centre'), ('16972', 'Miangeni Dispensary (Makueni)'), ('12520', 'Miangeni Dispensary (Mbooni)'), ('11605', 'Miasenyi Dispensary'), ('16234', 'Miathene District Hospital'), ('11606', 'Michaela Denis Medical Clinic'), ('10724', 'Micheus Clinic'), ('12522', 'Micii Mikuru Clinic'), ('13091', 'Mid Hill Medical Clinic'), ('15184', 'Mid Hill Medical Clinic Ngong'), ('13803', 'Midhine Dispensary'), ('17342', 'Midida Dispensary'), ('11609', 'Midoina Dispensary'), ('11615', 'Mikindani Medical Clinic'), ('12524', 'Mikinduri Health Centre'), ('12525', 'Mikinduri Sub-District Hospial'), ('17599', 'Mikongoni Dispensary'), ('12526', 'Mikumbune Sub-District Hospital'), ('17004', 'Mikuyuni Dispensary'), ('19924', 'Mikuyuni Dispensary-Masinga'), ('18247', 'Milaani Dispensary'), ('18552', 'Milcelt Medical Clinic'), ('15185', 'Mile 46 Health Centre'), ('20018', 'Milele Integrated Medical Services'), ('20332', 'Milenye Dispensary'), ('19059', 'M<NAME>ya'), ('15186', 'Milima Tatu Dispensary'), ('19262', 'Milimani Eye Clinic'), ('13808', 'Milimani Hospital'), ('12527', 'Milimani Nursing Home'), ('19212', 'Millenium Clinic'), ('19478', 'Millenium Dental Clinic'), ('16018', 'Milo Health Centre'), ('17792', 'Miloreni Dispensary'), ('16019', 'Miluki Dispensary'), ('16766', 'Miniambo Dispensary'), ('13092', 'Ministry of Education (Moest) VCT Centre'), ('18072', 'Minjira Dispensary'), ('15187', 'Minjore Dispensary'), ('19103', 'Minoptic Eye Clinic'), ('12528', 'Minugu Dispensary'), ('13809', 'Minyenya Dispensary'), ('18075', 'Miorre Dispensary'), ('19030', 'Miraj Medical Centre'), ('11616', 'Miranga Medical Clinic'), ('13810', 'Miranga Sub District Hospital'), ('10732', 'Mirangine Health Centre'), ('11617', 'Mirapera Dispensary'), ('17931', 'Mirere Health Centre'), ('16610', 'Mirigamieru Health Facility'), ('18702', 'Mirigamieru Health Services'), ('11618', 'Mirihini Dispensary'), ('13811', 'Miriri Dispensary'), ('17822', 'Miritini (MCM) Dispensary'), ('11620', 'Miritini CDF Dispensary'), ('13812', 'Miriu Health Centre'), ('13813', 'Mirogi Health Centre'), ('15188', 'Mirugi Kariuki Dispensary'), ('13814', 'Misesi Dispensary (Gucha)'), ('11621', 'Mishoroni Dispensary'), ('19950', 'Misikhu Main Medical Clinic'), ('17679', 'Misikhu Medicalcclinic'), ('15189', 'Miskwony Dispensary'), ('13815', 'Misori Dispensary'), ('12495', 'Mavui Dispensary'), ('16798', 'Mawamu Clinic'), ('13795', 'Mawego Health Centre'), ('12496', 'Maweli Dispensary'), ('17233', 'Maweni CDF Dispensary (Kongowea)'), ('18302', 'Maweni Community Clinic'), ('19253', 'Mawenzi Care Clinics'), ('15161', 'Mawepi Medical and VCT Centre'), ('13796', 'Mawere Dispensary'), ('19403', 'Max Family Health Care'), ('11584', 'Maximillan Clinic'), ('20360', 'Maximum medical centre'), ('15162', 'Maximum Medical Services'), ('16489', 'Mayanja Dispensary'), ('13079', 'Mayflower Clinic'), ('18701', 'Mayo Clinic'), ('16597', 'Mayo Medical Clinic'), ('16598', 'Mayo Medical Laboratory'), ('10709', 'Mayols Medical Clinic'), ('10710', 'Mayos Medical Clinic'), ('11585', 'Mazeras Dispensary'), ('11586', 'Maziwa Dispensary'), ('11587', 'Mazumalume Dispensary'), ('17672', 'Mbaga Dispensary'), ('13797', 'Mbaga Health Centre'), ('16011', 'Mbagara Dispensary'), ('13080', 'Mbagathi District Hospital'), ('11622', 'Mission K Clinic'), ('11623', 'Mission Medical Clinic (Bahari)'), ('16020', 'Mission of Mercy Clinic'), ('12529', 'Misyani Catholic Health Centre'), ('12530', 'Mitaboni Health Centre'), ('12732', 'Mitaboni Mission Dispensary'), ('12531', 'Mitamisyi Dispensary'), ('20032', 'Mithikwani Dispensary'), ('15190', 'Miti-Mingi Dispensary'), ('20207', 'Mitini Miracle Revival Church Clinic'), ('10733', 'Mitubiri Dispensary'), ('12532', 'Mituki Medical Clinic'), ('18752', 'Mitume Dispensary'), ('19260', 'Mitume Dispensary Kitale'), ('17129', 'Mitunguu Catholic Dispensary'), ('12533', 'Mitunguu Ccs Dispensary'), ('12534', 'Mitunguu Dispensary'), ('12535', 'Mitunguu Medical Services'), ('16236', 'Mituntu Cottage Hospital'), ('12536', 'Mituntu Health Centre'), ('17613', 'Miu Dispensary'), ('12537', 'Miu Sub-Health Centre'), ('12538', 'Miumbuni Dispensary'), ('12539', 'Mivukoni Health Centre'), ('11624', 'Mivumoni (Catholic) Dispensary'), ('13816', 'Miwani Dispensary'), ('11625', 'Mizijini Dispensary'), ('11626', 'Mjeni Medical Clinic'), ('13093', '<NAME> Huruma Dispensary'), ('11627', 'Mkang''ombe Community Dispensary'), ('11628', 'Mkokoni Dispensary'), ('11629', 'Mkongani Dispensary'), ('11630', 'Mkundi Dispensary'), ('13094', 'Mkunga Clinic'), ('11631', 'Mkunumbi Dispensary'), ('11633', 'Mkwiro Dispensary'), ('11634', 'Mlaleo Health Centre'), ('18210', 'Mlaleo Health Centre (MOH)'), ('11635', 'Mlanjo Dispensary'), ('18625', 'Mlimani Dispensary'), ('18581', 'Mlolongo Health Centre'), ('18256', 'Mlolongo VCT'), ('17844', 'Mlolongo Wellness Centre'), ('18167', 'Mmak'), ('18275', 'Mmak Embakasi Stand Alone VCT'), ('18639', 'Mmak''s Homecare Pharmacy'), ('20036', 'Mmangani Dispensary'), ('13817', 'Mnara Dispensary'), ('11636', 'Mnarani Dispensary'), ('11637', 'Mnazini Dispensary'), ('11638', 'Mnyenzeni Dispensary'), ('13062', 'Maria Immaculate Health Centre'), ('13063', 'Maria Maternity and Nursing Home'), ('20276', 'Maria Medical Clinic And Diadetic centre(Saika) '), ('18690', 'Maria Salus Infirmorum Dispensary'), ('11565', 'Maria Teressa Nuzzo Health Centre'), ('16970', 'Mariaini Dispensary'), ('16188', 'Mariakani Community Health Care Services'), ('18838', 'Mariakani Cottage Clinic'), ('13064', 'Mariakani Cottage Hospital Ltd'), ('18084', 'Mariakani Cottage Hospital Ongatta Rongai'), ('19432', 'Mariakani Cottage Hospital Utawala Clinic'), ('11566', 'Mariakani District Hospital'), ('15130', 'Marich Dispensary'), ('15131', 'Maridadi RCEA Medical Centre'), ('15132', '<NAME> ( Nakuru)'), ('15133', '<NAME> (Naivasha)'), ('17109', 'Marie Stopes Centre Embu'), ('18615', '<NAME>'), ('16166', '<NAME> (Dagoretti)'), ('12471', '<NAME> (Imenti North)'), ('13065', '<NAME> (Kencom)'), ('13774', '<NAME> (Kisii)'), ('11569', '<NAME> (Kongowea)'), ('18028', '<NAME> (Laikipia East)'), ('16167', '<NAME> (Langata)'), ('13775', '<NAME> (Migori)'), ('16772', '<NAME> (Nyeri South)'), ('13066', '<NAME> (Pangani)'), ('15134', '<NAME> (Trans Nzoia West)'), ('16002', '<NAME> (Vihiga)'), ('13067', '<NAME> (Westlands)'), ('15135', 'Marie Stopes Health Centre (Eldoret West)'), ('15136', 'Marie Stopes Health Centre (Kericho)'), ('18400', '<NAME> Kenya Bungoma Centre'), ('18232', '<NAME> Kenya Bungoma Centre'), ('11567', '<NAME> Kenya Clinic (Malindi)'), ('17967', '<NAME> Kenya Mld Clinic'), ('11570', 'Marie Stopes Mombasa Nursing Home'), ('13068', 'Marie Stopes Nursing Home (Eastleigh)'), ('13776', 'Marie Stopes Nursing Home (Kisumu)'), ('10690', 'Marie Stopes Nursing Home (Muranga)'), ('17484', 'Mariestopes'), ('15137', 'Marigat Catholic Mission'), ('15138', 'Marigat Sub District Hospital'), ('10691', 'Mariine Maternity Home'), ('10692', 'Mariira Catholic Dispensary'), ('11571', 'Marikebuni Dispensary'), ('18431', 'Marimani CDF Dispensary'), ('17658', 'Marimanti Med Clinic'), ('13777', 'Marindi Health Centre'), ('13069', 'Maringo Clinic'), ('15139', 'Marinyin Dispensary'), ('15129', 'Marioshoni Dispensary'), ('20089', 'Marist International University College Medical Clinic'), ('15140', 'Mariwa Dispensary (Kipkelion)'), ('13778', 'Mariwa Health Centre'), ('15141', 'Maron Dispensary'), ('15142', 'Maron-Marichor Dispensary'), ('19882', 'Marps -Chuka Dice Clinic'), ('19879', 'Marps Clinic (Meru)'), ('18767', 'Marps Drop In Medical Centre'), ('15143', 'Mars Associate Medical Centre'), ('18160', 'Mars Medical Clinic'), ('12472', 'Marsabit District Hospital'), ('12473', 'Marsabit Medical Clinic'), ('16207', 'Marsabit Modern Medical Clinic'), ('10694', 'Martha Medical Clinic'), ('15144', 'Marti Dispensary'), ('10695', 'Martmerg Medical Clinic'), ('19705', '<NAME> Medical Clinic'), ('10696', 'Marua Dispensary'), ('20005', 'Mogotio Town Dispensary'), ('16869', 'Mogusii Clinic'), ('15201', 'Mogwa Dispensary'), ('15202', 'MOH Outreach (Trans Nzoia)'), ('13095', 'Moi Air Base Hospital'), ('11640', 'Moi Airport Dispensary'), ('17485', 'Moi Baracks'), ('11641', 'Moi District Hospital Voi'), ('15203', 'Moi Ndabi Dispensary'), ('18363', 'Moi Teachers College - Baringo'), ('15204', 'Moi Teaching Refferal Hospital'), ('15205', 'Moi University Health Centre'), ('20151', 'Moi University Medical Clinic'), ('15206', 'Moiben Health Centre'), ('17115', 'Moigutwo Dispensary'), ('15208', 'Moi''s Bridge Catholic'), ('15209', 'Moi''s Bridge Health Centre'), ('16022', 'Moi''s Bridge Nursing Home'), ('15210', 'Moka Clinic'), ('13819', 'Mokason Clinic'), ('13820', 'Mokomoni Health Centre'), ('15211', 'Mokong Tea Dispensary'), ('11642', 'Mokowe Health Centre'), ('17042', 'Mokoyon Dispensary'), ('15212', 'Molo District Hospital'), ('15213', 'Molo Medical Centre'), ('17652', 'Masingu Health Services'), ('13784', 'Masogo Dispensary'), ('17518', 'Masogo Dispensary (Gem)'), ('13785', 'Masogo Sub District Hospital'), ('20414', 'Masoka Dispensary'), ('19986', 'Masokani Dispensary'), ('17108', 'Masol Dispensary'), ('19365', 'Masombor Community Dispensary'), ('12477', 'Masongaleni Health Centre'), ('13786', 'Masongo Dispensary'), ('18676', 'Mastoo Dispensary'), ('12478', 'Masumba Dispensary'), ('16787', 'Masumbi Dispensary'), ('15151', 'Masurura Dispensary'), ('12479', 'Masyungwa Health Centre'), ('11576', 'Mata Dispensary (Taita)'), ('11577', 'Mata Dispensary (Taveta)'), ('10703', 'Mataara Dispensary'), ('18868', 'Matabitabithi Dispensary'), ('12480', 'Mataka Dispensary'), ('13787', 'Matangwe Community Health Centre'), ('15152', 'Matanya Dispensary'), ('10704', 'Matara ENT Clinic'), ('13788', 'Matare Mission Dispensary'), ('15153', 'Matasia Nursing Home'), ('13789', 'Matata Nursing Hospital'), ('11639', 'Moa Dispensary'), ('15191', 'Mobet Dispensary'), ('13818', 'Mochenwa Dispensary'), ('15192', 'Mochongoi Health Centre'), ('18367', 'Modaan Clinic'), ('17126', 'Modambogho Dispensary'), ('19668', 'Modern Mc'), ('19793', 'Modern Medical Clinic'), ('16021', 'Moding Health Centre'), ('13410', 'Modogashe Clinic'), ('12540', 'Modogashe Dispensary'), ('13411', 'Modogashe District Hospital'), ('15193', 'Mogil Health Centre'), ('15194', 'Mogoget Dispensary'), ('15195', 'Mogogosiek Health Centre'), ('16327', 'Mogoiywet Dispensary'), ('17713', 'Mogonga Maternity and Nursing Home (Kenyenya)'), ('17583', 'Mogonjet Dispensary'), ('15196', 'Mogoon Dispensary'), ('17323', 'Mogor Dispensary'), ('16721', 'Mogori-Komasimo Health Centre'), ('15197', 'Mogorwa Health Centre'), ('15198', 'Mogotio Dispensary'), ('18959', 'Mogotio Medical Clinic'), ('15199', 'Mogotio Plantation Dispensary'), ('15200', 'Mogotio Rhdc'), ('16006', 'Matioli Dispensary'), ('15155', 'Matira Dispensary'), ('17179', 'Matoi Dispensary'), ('11578', 'Matolani Dispensary'), ('11579', 'Matondoni Dispensary'), ('13790', 'Matongo Dispensary'), ('13791', 'Matongo Health Centre'), ('13792', 'Matongo Medical Clinic'), ('13793', 'Matoso Health Clinic'), ('11580', 'Matsangoni Model Health Centre'), ('11581', 'Matuga Dispensary'), ('20257', 'Matulani Dispensary'), ('16389', 'Matulo Dispensary'), ('16410', 'Matumaini Dispensary'), ('18095', 'Matumbi Dispensary'), ('16364', 'Matunda Dispensary'), ('16007', 'Matunda Nursing Home'), ('16008', 'Matunda Sub-District Hospital'), ('20245', 'Matungu Medical Clinic'), ('16037', 'Matungu Sub-District Hospital'), ('16439', 'Matungulu Health Centre'), ('18292', 'Matungulu Medical Centre'), ('10708', 'Matura Medical Care'), ('16009', 'Maturu Dispensary'), ('13794', 'Matutu Dispensary'), ('10697', 'Marua Medical Clinic'), ('11572', 'Marungu Health Centre'), ('15145', 'Marura Dispensary'), ('13070', 'Marura Nursing Home'), ('18553', 'Marura Nursing Home (Ruiru)'), ('19723', 'Marura Nursing Home Kiambu Medical Clinic'), ('13071', 'Marurui Dispensary'), ('15146', 'Mary Finch Dispensary'), ('12474', 'Mary Goretti Health Services'), ('19598', 'Mary Help Mission Medical Centre'), ('10698', 'Mary Help of The Sick Hospital'), ('10699', 'Mary Hill Medical Clinic'), ('12982', 'Mary Immaculate Clinic Mukuru'), ('11573', 'Mary Immaculate Cottage Hospital (Mombasa)'), ('15147', 'Mary Immaculate Dispensary (Eldoret East)'), ('15148', 'Mary Immaculate Dispensary (Laikipia East)'), ('10700', 'Mary Immaculate Hospital (Nyeri North)'), ('13072', 'Mary Immaculate Sisters Dispensary'), ('17514', 'Mary Mission'), ('16179', 'Maryango Medical Clinic'), ('17815', 'Maryland Medical Clinic'), ('11574', 'Marynoll Dispensary'), ('10701', 'Masa Medical Clinic (Kirinyaga)'), ('10702', 'Masa Medical Clinic (Nyeri North)'), ('12504', 'Mbiuni VCT'), ('15164', 'Mbogo Valley Dispensary'), ('15165', 'Mbogoini Dispensary'), ('12505', 'Mbondoni Dispensary'), ('16246', 'Mbondoni Dispensary (Mwingi)'), ('12506', 'Mbonzuki Dispensary'), ('12507', 'Mbooni (AIC) Dispensary'), ('12508', 'Mbooni District Hospital'), ('17287', 'Mboroga Dispensary'), ('13081', 'Mbotela Clinic'), ('17061', 'Mbugiti Dispensary'), ('11590', 'Mbuguni Dispensary'), ('16968', 'Mbuini Dispensary'), ('11591', 'Mbulia Dispensary'), ('18442', 'Mbuni Dispensary'), ('12509', 'Mbusyani Dispensary'), ('11592', 'Mbuta Model Health Centre'), ('10714', 'Mbuti Medical Clinic'), ('20271', 'Mbuvo Health Centre'), ('11593', 'Mbuwani Dispensary'), ('18480', 'Mbuyu Dispensary'), ('11594', 'Mbwajumwali Dispensary'), ('18242', 'Mbwinjeru Methodist Dispensary'), ('19187', 'Mcf Ndalani'), ('19182', 'Mcf Yatta'), ('10715', 'Mchana Estate Dispensary'), ('17927', 'MCK Kiirigu Dispensary'), ('11595', 'Mecca Medical Clinic'), ('13800', 'Mecheo Dispensary'), ('16014', 'Mechimeru Dispensary'), ('16694', 'Med Afric Medical Clinic'), ('19482', 'Medanta Africare'), ('19505', 'Medanta Africare Medical Centre'), ('20451', 'Medecins Du Monde/France (Kangemi Kang''ora)'), ('19099', 'Medical and Dental Clinic'), ('10716', 'Medical Centre Clinic'), ('19496', 'Medical Clinic'), ('19493', 'Medical Link Integrated Health Program'), ('19834', 'Medical Plaza Clinic Banana'), ('13082', 'Medical Reception Dispensary'), ('15166', 'Medical Reception Service - Ist Kr'), ('10719', 'Medical Training College (Nyeri)'), ('11598', 'Medicalitech Clinic'), ('13083', 'Medicare Clinic'), ('13801', 'Medicare Medical Clinic (Manga)'), ('18647', 'Medicare Stores Chemist'), ('15167', 'Mediheal Hospital'), ('18266', 'Mediheal Hospital Nakuru'), ('19525', 'Medimark Health Care'), ('19010', 'Medina Diagnostic'), ('13408', 'Medina Health Centre'), ('19037', 'Medina Hospital'), ('11597', 'Medina Medical Clinic'), ('15062', 'Lokitaung District Hospital'), ('15063', 'Lokore Dispensary'), ('15064', 'Lokori (AIC) Health Centre'), ('16324', 'Lokori Primary Health Care Programme'), ('15065', 'Lokusero Dispensary'), ('15066', 'Lokwamosing Dispensary'), ('16697', 'Lokwatubwa (PAG) Dispensary'), ('15067', 'Lokwii Dispensary'), ('15068', 'Lolgorian Sub District Hosp'), ('15069', 'Lolkeringet Dispensary'), ('15070', 'Lolminingai Dispensary'), ('17189', 'Lolmolog Dispensary'), ('14504', 'Loltulelei Friends Dispensary'), ('20000', 'Lolupe Dispensary'), ('16875', 'Lombi Medical Clinic'), ('18370', 'Lomekwi Dispensary'), ('16698', 'Lomelo Dispensary'), ('15072', 'Lomil Dispensary'), ('20048', 'Lomuke Dispensary'), ('15073', 'Lomut Dispensary'), ('15074', 'Londiani District Hospital'), ('17479', 'Longech Dispensary'), ('15076', 'Longewan Dispensary'), ('15077', 'Longisa Distrioct Hospital'), ('15078', 'Longonot Dispensary'), ('16214', 'Lontolio Dispensary'), ('15046', 'Loodoariak Dispensary'), ('17924', 'Loosho Dispensary'), ('15079', 'Loosuk GK Dispensary'), ('16699', 'Lopedur Dispensary'), ('17246', 'Loperot Dispensary'), ('15081', 'Lopiding Sub-District Hospital'), ('15083', 'Lopur Dispensary (Turkana South)'), ('15082', 'Lopur Dispensary (Turkana West)'), ('16815', 'Lord of Mercy Clinic'), ('17947', 'Loreigns Medical Services (Kasarani)'), ('15084', 'Lorengelup Dispensary'), ('15085', 'Lorengippi Dispensary'), ('15086', 'Lorien Dispensary'), ('15087', 'Lorngoswa Dispensary'), ('15088', 'Lorogon Dispensary'), ('20076', 'Lorugum Medical Services Ltd'), ('15091', 'Loruk Dispensary (East Pokot)'), ('15092', 'Loruth Dispensary'), ('16369', 'Losam Dispensary'), ('18265', 'Losho Dispensary'), ('15093', 'Losogwa Dispensary'), ('15094', 'Loturerei Dispensary'), ('19519', 'Medisafe Medical Labaratoty'), ('18040', 'Meditrust Health Care Services'), ('19820', 'Medkam Pharmacy'), ('19920', 'Medlink Medical Clinic'), ('13085', 'Med-Point Dispensary'), ('19176', 'Meds Pharmaciticals Ongata Rongai'), ('16688', 'Meguara Dispensary'), ('15168', 'Megwara Dispensary'), ('15169', 'Meibeki Dispensary'), ('13086', 'Melchezedek Hospital'), ('20072', 'Melchizedek Hospital Karen'), ('19055', 'Melchizedek Hospital Ngong Clinic'), ('18290', 'Melkasons Clinic'), ('15170', 'Melwa Health Centre'), ('16255', 'Memo Clinic'), ('11205', 'Memon Medical Centre'), ('13087', 'Memorial Hospital'), ('17025', 'Menegai Medical Clinic'), ('19959', 'Menelik Chest Clinic'), ('18688', 'Menengai Crator Dispensary'), ('17021', 'Menengai Health Care Services'), ('20138', 'Menengai Health Centre'), ('15171', 'Menet Dispensary'), ('15172', 'Mentera Dispensary'), ('19019', 'Mephi Medical Clinic'), ('17556', 'Merciful International Guild'), ('15977', 'Lusheya Health Centre'), ('17540', 'Lusop Clinic'), ('10666', 'Lussigetti Health Centre'), ('15978', 'Lutaso Dispensary'), ('11527', 'Lutsangani Dispensary'), ('17608', 'Luucho Dispensary'), ('17116', 'Luuya Dispensary'), ('13740', 'Lwala Dispensary'), ('17174', 'Lwala Kadawa Dispensary'), ('20385', 'Lwala Nyarago Dispensary'), ('16770', 'Lwanda Awiti Dispensary'), ('13741', 'Lwanda Dispensary'), ('15979', 'Lwanda Dispensary (Bungoma West)'), ('13742', 'Lwanda Gwassi Dispensary'), ('20285', 'Lwanda kobita'), ('15980', 'Lwandanyi Dispensary'), ('15981', 'Lwandeti Dispensary'), ('17155', 'Lwanyange Dispensary'), ('15982', 'Lyanaginga Health Centre'), ('16505', 'M K M Clinic'), ('19175', 'M K Medical Clinic Ewuaso'), ('19081', 'Maa Out Patient Centre'), ('12436', 'Maai Dispensary'), ('17339', 'Maalimin Dispensary'), ('11528', 'Maamba Medical Clinic'), ('15103', 'Maasai Medical Centre'), ('15104', 'Maasai Nursing Home'), ('17502', 'Mabanga Medical Clinic'), ('19746', 'Mabariri Medical Clinic (Nyamira North)'), ('15105', 'Mabasi Dispensary'), ('11529', 'Mabati Medical Clinic'), ('13743', 'Mabinju Dispensary'), ('17297', 'Mabole Health Centre'), ('10667', 'Mabroukie Dispensary'), ('19142', 'Mabruk Medical Clinic'), ('15983', 'Mabusi Health Centre'), ('13744', 'Macalder Mission Dispensary'), ('13745', 'Macalder Sub-District Hospital'), ('12437', 'Machaka Mission Dispensary'), ('12439', 'Machakos Health Care Centre'), ('12438', 'Machakos Level 5 Hospital'), ('12440', 'Machakos Medical Clinic'), ('12441', 'Machang''a Dispensary'), ('18970', 'Machengene Dispensary'), ('19892', 'Machinery Health Care Centre'), ('17498', 'Machinery Medical Clinic'), ('19188', 'Machungulu Dispensary'), ('13746', 'Machururiati Dispensary'), ('15984', 'Machwele Dispensary'), ('11530', 'Mackinnon Medical Clinic'), ('11531', 'Mackinon Road Dispensary'), ('19600', 'Madaktari Health Clinic (Njiru)'), ('11532', 'Madamani Dispensary'), ('18735', 'Madaraka Health Services'), ('15985', 'Madende Dispensary'), ('13747', 'Madiany Sub District Hospital'), ('19220', 'Madina Health Care Clinic'), ('13055', 'Madina Nursing Home'), ('17902', 'Madoadi Dispensary (Sololo)'), ('11533', 'Madogo Health Centre'), ('11534', 'Madunguni Dispensary'), ('11535', 'Madunguni Medical Clinic'), ('18890', 'Maendeleo Clinic'), ('19473', 'Maendereo Medical Clinic'), ('15986', 'Maeni Dispensary'), ('11536', 'Mafisini Dispensary'), ('19512', 'Mafra Clinic'), ('20281', 'M-afya Medical Clinic'), ('15107', 'Magadi Hospital'), ('18698', 'Magana Medical Clinic'), ('20453', 'Magaoni Health Centre'), ('13748', 'Magena Dispensary'), ('13749', 'Magenche Dispensary'), ('12443', 'Magenka Dispensary'), ('13750', 'Mageta Dispensary'), ('18430', 'Magina Dispensary'), ('13804', 'Midoti Dispensary'), ('19633', 'Mid-Point Health Services'), ('18605', 'Mid-Town Reoproductive Health and Youth Friendly'), ('10725', 'Midway Clinic'), ('16015', 'Miendo Dispensary'), ('13805', 'Migori District Hospital'), ('17737', 'Migori Health Station Clinic'), ('13806', 'Migori T T C Dispensary'), ('13807', 'Migosi Health Centre'), ('10726', 'Miguta Dispensary'), ('12523', 'Migwani Sub-District Hospital'), ('10727', 'Mihang''o Dispensary'), ('19791', 'Miharate Medical Clinic'), ('10728', 'Mihuti Dispensary (Muranga North)'), ('10729', 'Mihuti Dispensary (Nyeri South)'), ('10730', 'Mihuti Medical Clinic'), ('16016', 'Mihuu Dispensary'), ('16017', 'Mijay Clinic'), ('11610', 'Mijomboni Dispensary'), ('11611', 'Mikanjuni Family Medical Clinic'), ('11612', 'Mikanjuni Medical Clinic'), ('10731', 'Mikaro Dispensary'), ('19050', 'Mikeu PCEA Medical Centre'), ('11613', 'Mikindani (MCM) Dispensary'), ('11614', 'Mikindani Catholic Dispensary'), ('12447', 'Mailiari Dispensary'), ('15109', 'Mailwa Dispensary'), ('10671', 'Maina & Mwangi Health Centre'), ('15110', 'Maina Dispensary'), ('18410', 'Maina Kiganjo Health Clinic'), ('10672', 'Maina Village Dispensary'), ('17862', 'Mainland Health Centre (Changamwe)'), ('11539', 'Mainland Health Centre (Magongo)'), ('11540', 'Mainview Medical Clinic'), ('17303', 'Mairi Dispensary'), ('16506', 'Maisha Bora Clinic'), ('19308', 'Maisha House VCT (Noset)'), ('19542', 'Maisha Poa Dispensary'), ('19414', 'Maiuni Dispensary'), ('12448', 'Majengo (PCEA) Clinic'), ('15988', 'Majengo Dispensary'), ('11541', 'Majengo Dispensary (Mombasa)'), ('11542', 'Majengo Dispensary (Tana River)'), ('15111', 'Maji Mazuri Dispensary'), ('15112', 'Maji Moto Dispensary'), ('15113', 'Maji Moto Dispensary (Narok South)'), ('15114', 'Maji Tamu Health Centre'), ('11543', 'Majimoto Dispensary'), ('17891', 'Majira Dispensary'), ('15115', 'Majoh Medical Clinic'), ('11544', 'Majoreni Dispensary'), ('19341', 'Majve Medical Clinic'), ('13399', 'Maka - Al Mukarama Clinic'), ('12449', 'Makaani Dispensary'), ('12450', 'Makadara Health Care'), ('13056', 'Makadara Health Centre'), ('13057', 'Makadara Mercy Sisters Dispensary'), ('11545', 'Makamini Dispensary'), ('19304', 'Makamu Medical Clinic'), ('17346', 'Makande Healthcare Services'), ('12451', 'Makandune Dispensary'), ('11547', 'Makanzani Dispensary'), ('13758', 'Makararangwe Dispensary'), ('12452', 'Makengi Clinic'), ('12453', 'Makengi Dispensary (Embu)'), ('16645', 'Makengi Dispensary (Maara)'), ('11548', 'Makere Dispensary'), ('15989', 'Makhanga Dispensary'), ('15990', 'Makhonge Health Centre'), ('12454', 'Makima Dispensary'), ('15116', 'Makimeny Dispensary'), ('13058', 'Makina Clinic'), ('11961', 'Makindu Catholic Dispensary'), ('13759', 'Makindu Dispensary'), ('12455', 'Makindu District Hospital'), ('19320', 'Makindu Nursing Home'), ('19222', 'Makkah Medical Clinic and Lab'), ('13059', 'Makkah Nursing Home'), ('13060', 'Makogeni Clinic'), ('18432', 'Makongeni Dispensary'), ('19858', 'Makongeni Health Centre'), ('18681', 'Makongo Dispensary'), ('19107', 'Makongoni Dispensary'), ('17744', 'Makoror Dispensary'), ('11549', 'Maktau Health Centre'), ('12457', 'Makueni District Hospital'), ('18139', 'Makueni Medical Centre'), ('15991', 'Makunga Rhdc'), ('15458', 'Makutano (PCEA) Medical Clinic (Trans Nzoia East)'), ('15992', 'Makutano Dispensary'), ('15117', 'Makutano Health Centre (Turkana West)'), ('16451', 'Makutano Medical Clinic'), ('12458', 'Makutano Medical Clinic (Machakos)'), ('18733', 'Makutano Medical Clinic (Meru)'), ('16594', 'Makutano Medical Clinic/Lab'), ('10674', 'Makuyu Health Centre'), ('10675', 'Makwa Medical Clinic'), ('11552', 'Makwasinyi Dispensary'), ('18397', 'Makyau Dispensary'), ('15118', 'Makyolok Dispensary'), ('15993', 'Malaba Dispensary'), ('19258', 'Malabot Dispensary'), ('17551', 'Matutu Dispensary (Nzaui)'), ('18379', 'Matutu Medical Clinic'), ('12487', 'Matuu Cottage Clinic'), ('12488', 'Matuu District Hospital'), ('12489', 'Matuu Mission Health Centre'), ('12490', 'Matuu Nursing Home'), ('15156', 'Mau Narok Health Centre'), ('15157', 'Mau Summit Medical Clinic'), ('15158', 'Mau Tea Dispensary'), ('12491', 'Maua Cottage'), ('19409', 'Maua Diagnostic Centre'), ('19261', 'Maua East Medical Clinic'), ('19263', 'Maua Medical Clinic'), ('12492', 'Maua Methodist Hospital'), ('15159', 'Mauche Dispensary'), ('15160', 'Mauche Medical Clinic'), ('16412', 'Mau-Narok Health Services'), ('18858', 'Maungu Model Health Centre'), ('11582', 'Maunguja Dispensary'), ('16010', 'Mautuma Sub-District Hospital'), ('12493', 'Mavindini Health Centre'), ('18330', 'Mavindu Dispensary'), ('17256', 'Mavivye Model Health Centre'), ('12494', 'Mavoko Medical Clinic'), ('18482', 'Mavueni Dispensary'), ('18118', 'Malkich Dispensary'), ('17853', 'Maloba Health Clinic'), ('20379', 'Malongo Dispensary'), ('18912', 'Mama Anns Odede Community Health Centre'), ('13762', '<NAME>ic'), ('20012', 'Mama Clinic'), ('13763', '<NAME>linic'), ('13764', 'M<NAME>linic'), ('12463', 'M<NAME> Clinic'), ('17411', 'Mama Lucy Kibaki Hospital - Embakasi'), ('10676', 'Mama Margaret Medical Clinic'), ('13765', 'Mama Maria Clinic'), ('17121', 'Mama Plister Blair Health Centre'), ('12464', 'Mama Vero Clinic'), ('18946', 'Mamakate Medical Clinic'), ('11558', 'Mamba Dispensary'), ('12465', 'Mamba Dispensary (Yatta)'), ('18417', 'Mamboleo Medical Clinic'), ('11559', 'Mambrui Dispensary'), ('17734', 'Mamu Medical Clinic'), ('10677', 'Mamuki Medical Clinic'), ('19659', 'Mana Medical Clinic'), ('12466', 'Mananja Health Centre'), ('19374', 'Manasco Medical Centre (Roysambu)'), ('18529', 'Kivani Dispensary (Kitui West)'), ('12378', 'Kiviu Dispensary'), ('13036', 'Kivuli Dispensary'), ('12379', 'Kivuuni Dispensary'), ('13707', 'Kiwa Island Dispensary'), ('16203', 'Kiwalwa Dispensary'), ('14954', 'Kiwamu Dispensary'), ('11493', 'Kiwandani Dispensary'), ('19712', 'Kiwara Medical Clinic'), ('16374', 'Kiwawa (ACCK) Dispensary'), ('20083', 'Kiwawa GOK Dispensary'), ('11494', 'Kiwayuu Dispensary'), ('11495', 'Kizibe Dispensary'), ('11496', 'Kizingitini Dispensary'), ('11497', 'Kizingo Health Centre'), ('14955', 'Kkit Nursing Home'), ('14956', 'Kkit Nursing Home Annex'), ('12380', 'Kmc Clin<NAME>'), ('17903', 'Kmc Staff Clinic'), ('17554', 'K-Met Corkran'), ('14957', 'Kmq Dispensary'), ('13037', 'Kmtc Dispensary'), ('18347', 'Kmtc Mombasa Students Clinic'), ('14958', 'Kobos Dispensary'), ('14959', 'Kobujoi Forest'), ('17125', 'Kobujoi Forest Dispensary'), ('14960', 'Kobujoi Mission Health Centre'), ('13708', 'Kobuya Dispensary'), ('20134', 'Kochola Dispensary'), ('14961', 'Kocholwo Sub-District Hospital'), ('13709', 'Kodiaga Prison Health Centre'), ('14962', 'Kodich Dispensary'), ('19861', 'Koduogo Dispensary'), ('18268', 'Kogari Dispensary'), ('13710', 'Kogelo Dispensary'), ('13711', 'Kogweno Oriang'' Dispensary'), ('14963', 'Koibatal Medical'), ('17639', 'Koibem Dispensary'), ('14965', 'Koilot Health Centre'), ('10644', 'Koimbi Medical Clinic'), ('18664', 'Koimiret Dispensary'), ('16723', 'Koisagat Dispensary (Kipkelion)'), ('14966', 'Koisagat Tea Dispensary'), ('14967', 'Koitaburot Dispensary'), ('14968', 'Koitebes Dispensary'), ('14969', 'Koitugum Dispensary'), ('14970', 'Koiwa Health Centre'), ('14971', 'Koiwa Medical Clinic'), ('14972', 'Koiwalelach Dispensary'), ('14973', 'Kojonga Dispensary'), ('14974', 'Kokiselei Dispensary'), ('17017', 'Kokotoni Dispensary'), ('13715', 'Komomange Dispensary'), ('13716', 'Komosoko Dispensary'), ('13717', 'Komotobo Mission Health Centre'), ('15954', 'Kona Clinic'), ('14984', 'Kondabilet Dispensary'), ('14985', 'Kondamet Dispensary'), ('20368', 'Kongelai Dispensary'), ('14986', 'Kongoni Dispensary'), ('15955', 'Kongoni Health Centre'), ('14987', 'Kongoro Dispensary'), ('11499', 'Kongowea Health Centre'), ('11501', 'Kongowea Medical Clinic'), ('19150', 'Konton Dispensary'), ('14988', 'Konyao Dispensary'), ('12383', 'Konyu Dispensary'), ('13718', 'Kopanga Dispensary'), ('14989', 'Kopeeto Dispensary'), ('18050', 'Kopiata Beach Dispensary (Rarieda)'), ('16873', 'Kopolo Clinic'), ('15956', 'Kopsiro Health Centre'), ('13382', 'Korakora Health Centre'), ('16391', 'Korao Dispensary'), ('12384', 'Korbesa Dispensary'), ('14990', 'Koriema Dispensary'), ('13383', 'Korisa Dispensary'), ('18895', 'Korogocho Health Centre'), ('14991', 'Korokou Dispensary'), ('13384', 'Korondille Health Centre'), ('14992', 'Korongoi Dispensary'), ('15958', 'Korosiandet Dispensary'), ('14993', 'Koroto Dispensary'), ('12385', 'Korr Dispensary'), ('17110', 'Koru Dispensary'), ('13719', 'Koru Mission Health Centre'), ('13720', 'Korwenje Dispensary'), ('13721', 'Kosele Dispensary'), ('17073', 'Koshok Dispensary'), ('14994', 'Kosikiria Dispensary'), ('14995', 'Kositei Dispensary'), ('13385', 'Kotile Health Centre'), ('13388', 'Kotulo Health Centre (Mandera Central)'), ('13722', 'Kowino Dispensary'), ('14996', 'Koyasa Dispensary'), ('14997', 'Koyo Health Centre'), ('18531', 'Koywech Dispensary'), ('11502', 'Kp&Tc Staff Clinic'), ('12387', 'Kr Memorial Medical Clinic'), ('20456', 'Krezze Dispensary'), ('19699', 'Krisvin Medical Clinic'), ('20340', 'KTTID Dispensary'), ('16488', 'Kubura Dispensary'), ('13723', 'Kugitimo Health Centre'), ('14998', 'Kuikui Dispensary'), ('14999', 'Kuinet Dispensary'), ('20094', 'Kuira District Disability Network Kuria - Isebania HTC Center'), ('13724', 'Kuja Dispensary'), ('12389', 'Kula Mawe Dispensary'), ('17460', 'Kulaaley Health Centre'), ('13386', 'Kulan Health Centre'), ('16195', 'Kulesa Dispensary'), ('16952', 'Kumahumato Dispensary'), ('16271', 'Kumoni Dispensary'), ('15000', 'Kumpa Cmf Dispensary'), ('12390', 'Kunati Health Centre'), ('12391', 'Kunene Dispensary'), ('17010', 'Kuno Dispensary'), ('13725', 'Kunya Dispensary'), ('15001', 'Kunyak Dispensary'), ('17171', 'Kuoyo Kaila Dispensary'), ('15002', 'Kurangurik Dispensary'), ('16326', 'Kuresiet Dispensary'), ('16683', 'Kuresoi Health Centre'), ('13726', 'Kuria District Hospital'), ('13387', 'Kursin Health Centre'), ('20191', 'Kurum Dispensary'), ('18929', 'Kurungu Dispensary (Loiyangalani)'), ('17681', 'Manda Dispensary'), ('13402', 'Mandera District Hospital'), ('16296', 'Mandera Medicare Clinic'), ('13403', 'Mandera Medicare Nursing Home'), ('18851', 'Mandera West Nursing Home'), ('10678', 'Manesh Clinic'), ('13766', 'Manga District Hospital'), ('13767', 'Manga Getobo Clinic'), ('11560', 'Mangai Dispensary'), ('12468', 'Mangala Dispensary'), ('17697', 'Mangani Clinic'), ('13768', 'Mangima SDA Health Centre'), ('19147', 'Mangina Dispensary'), ('12469', 'Mango Dispensary'), ('20120', 'Mango Tree VCT'), ('10019', 'Mangu (Aip) Dispensary'), ('15119', 'Mangu Dispensary (Rongai)'), ('16759', 'Mangu High School Clinic'), ('10679', 'Manguo Medical Clinic'), ('10680', 'Manjo Health Clinic'), ('16310', 'Mankind Medical Clinic'), ('19347', 'Manna Medical Clinic Isinya'), ('17127', 'Manoa Dispensary'), ('16363', 'Manor House Agricultural Health Clinic'), ('13404', 'Mansa Health Centre'), ('16292', 'Mansa Nomadic Clinic'), ('11507', 'Kwale District Hospital'), ('19926', 'Kwamaiko Health Clinic'), ('11508', 'Kwa-Mnegwa Dispensary'), ('13728', 'Kwamo Dispensary'), ('20412', 'Kwa-Mutei Dispensary'), ('12400', 'Kwamwaura Medical Clinic'), ('15003', 'Kwanza Health Centre'), ('18521', 'Kwenik-Ab-Ilet Dispensary'), ('19372', 'Kwetu Medical Clinic'), ('16178', 'Kwetu VCT'), ('18558', 'Kwihota Medical Clinic'), ('12401', 'Kwitu Medical Clinic'), ('18827', 'Kwosp (Korogocho)'), ('13729', 'Kwoyo Kodalo Dispensary'), ('11509', 'KWS Dispensary'), ('18450', 'KWS VCT'), ('17939', 'Kyaango Dispensary'), ('12402', 'Kyaani Dispensary'), ('20033', 'Kyaani Dispensary (Matinyani)'), ('19726', 'Kyaimu Dispensary'), ('17005', 'Kyalilini Dispensary'), ('17842', 'Kyaluma Dispensary'), ('12403', 'Kyamatu Dispensary'), ('12404', 'Kyambeke Dispensary'), ('18083', 'Kyambiti Dispensary'), ('19195', 'Kyandu Medical Clinic'), ('12405', 'Kyandui Dispensary'), ('20196', 'Kyanganda Dispensary'), ('18674', 'Kyango Dispensary'), ('12406', 'Kyangunga Dispensary'), ('12407', 'Kyanika Dispensary'), ('19198', 'Kyanzabe Medical Clinic'), ('12408', 'Kyanzavi Medical Clinic'), ('12409', 'Kyasila (AIC) Dispensary'), ('17161', 'Kyasioni Dispensary'), ('12410', 'Kyatune Health Centre'), ('16965', 'Kyau Dispensary'), ('12411', 'Kyawalia Dispensary'), ('12412', 'Kyawango Dispensary'), ('18168', 'Kyazabe Medical Clinic'), ('16438', 'Kyeleni Health Centre'), ('16967', 'Kyenzenzeni Dispensary'), ('12414', 'Kyethani Health Centre'), ('17611', 'Kyevaluki Dispensary'), ('12415', 'Kyevaluki Medical Clinic'), ('12416', 'Kyoani Dispensary'), ('12417', 'Kyome (AIC) Dispensary'), ('12418', 'Kyondoni Dispensary'), ('16254', 'Kyuasini Health Centre'), ('12419', 'Kyumbe (AIC) Dispensary'), ('20256', 'Kyumbe Dispensary'), ('18607', 'Kyumbi Sasa Centre'), ('12420', 'Kyuso District Hospital'), ('12421', 'Kyusyani Dispensary'), ('12422', 'Laare Health Centre'), ('19192', 'Laare Maternity'), ('17338', 'Labi Sagale'), ('18466', 'Laboret Dispensary'), ('10652', 'Labura/Babito Medical Clinic'), ('19316', 'Lad Nan Hospital'), ('13390', 'Ladnan Medical Clinic'), ('20228', 'Ladopharma Medical Center'), ('18898', 'Ladopharma Medical Centre'), ('11510', 'Lady Grigg Maternity Hospital (CPGH)'), ('16169', 'L<NAME>hey Dispensary'), ('13391', 'Lafaley Dispensary'), ('16293', 'Lafey Nomadic Dispensary'), ('13392', 'Lafey Sub-District Hospital'), ('17463', 'Lagboqol Dispensary'), ('13039', 'Lagos Road Dispensary'), ('18589', 'Laikipia University Medical Centre'), ('12423', 'Lailuba Dispensary'), ('19688', 'Laini Moja Mc & Lab'), ('19993', 'Laini Saba Health Services'), ('18856', 'Laisamis Health Centre (Marsabit South)'), ('13730', 'Lake Basin Development Authority (Lbda) Dispensary'), ('18991', 'Lakeside Medical'), ('15004', 'Lakeview Nursing Home'), ('19850', 'Lakipia Laboratory'), ('17755', 'Lovic Dermacare Clinic'), ('15095', 'Loving Care (MCK) Health Centre'), ('15096', 'Lowarengak Dispensary'), ('13052', 'Lower Kabete Dispensary (Kabete)'), ('15097', 'Lower Solai Dispensary'), ('15098', 'Loyapat Dispensary'), ('20459', 'Loyeya dispensary'), ('17276', 'Lpartuk Dispensary'), ('15962', 'Luanda Mch/Fp Clinic'), ('15963', 'Luanda Town Dispensary'), ('17112', 'Luanda Wayside Clinic'), ('13736', 'Luciel Dispensary'), ('10665', 'Lucimed Clinic'), ('13737', 'Lucky Youth Dispensary'), ('18287', 'Ludomic Clinic'), ('15964', 'Lugari Forest Dispensary'), ('17653', 'Lughpharm Medical Services (Machakos)'), ('18884', 'Lugpharm Medicals Limited'), ('15099', 'Luguget Dispensary'), ('15965', 'Lugulu Friends Mission Hospital'), ('15100', 'Lugumek Dispensary'), ('19650', 'Luisoi Medical Clinic'), ('15966', 'Lukhome Dispensary (Bungoma West)'), ('15101', 'Lukhome Dispensary (Trans Nzoia West)'), ('15967', 'Lukhuna Dispensary'), ('11515', 'Langoni Nursing Home'), ('10654', 'Lankia (PCEA) Dispensary'), ('17644', 'Lanyiru Dispensary'), ('15013', 'Lare Health Centre'), ('10655', 'Lari Health Centre'), ('12425', 'Lasida Clinic'), ('15014', 'Latakweny Dispensary'), ('19503', 'Latema Medical Services (Nairobi)'), ('11516', 'Latulla Medical Centre'), ('13045', '<NAME>'), ('16800', 'Le<NAME> Clinic (Nairobi West)'), ('13047', 'Le<NAME> Clinic Kariobangi South'), ('17720', 'Lea Toto Community Mukuru Reuben'), ('13046', '<NAME>'), ('19914', '<NAME>awangware'), ('13048', '<NAME>'), ('18828', '<NAME>'), ('18964', 'Leah Njoki Ndegwa Dispensary'), ('17361', 'Leberio Dispensary'), ('15016', 'Lebolos Dispensary'), ('15017', 'Ledero Dispensary'), ('18533', 'Legacy Medical Centre'), ('13394', 'Leheley Sub District Hospital'), ('13733', 'Lela (Community) Dispensary'), ('20384', 'LELA Dispensary'), ('18665', 'Lelaitich Dispensary'), ('15018', 'Lelboinet Dispensary (Mosop)'), ('15019', 'Lelboinet Health Centre (Keiyo)'), ('15020', 'Lelechwet Dispensary (Kipkelion)'), ('15021', 'Lelechwet Dispensary (Rongai)'), ('15022', 'Lelmokwo Dispensary'), ('16337', 'Lelmolok Nursing Home'), ('15023', 'Lelu Dispensary'), ('15024', 'Lemook Clinic'), ('15025', 'Lemoru Ngeny Dispensary'), ('19116', 'Lemoru Trinity'), ('15026', 'Lemotit Dispensary'), ('18784', 'Lenana Hills Hospital'), ('11517', 'Lenga Dispensary'), ('15027', 'Lengenet Dispensary'), ('18590', 'Lengo Medical Clinic'), ('17749', 'Lensayu'), ('18538', 'Leo Surgery'), ('16220', 'Leparua Dispensary'), ('16806', 'Lereshwa Dispensary'), ('15028', 'Lerrata Dispensary'), ('10656', 'Leshau Medical Clinic'), ('10657', 'Leshau Pondo Health Centre'), ('17783', 'Leshuta Dispensary'), ('17275', 'Lesidai Dispensary'), ('10610', 'Kimende Orthodox Mission Health Centre'), ('20299', 'Kimeswon Health Centre'), ('15950', 'Kimilili District Hospital'), ('14872', 'Kiminini Cottage Hospital'), ('16362', 'Kiminini Health Centre'), ('19681', 'Kiminini Medical Centre & Laboratory'), ('19680', 'Kiminini Pag VCT'), ('14873', 'Kimintet Dispensary'), ('16436', 'Kimiti Model Health Centre'), ('18885', 'Kimkan Health Services'), ('17198', 'Kimlea Medical Clinic'), ('14874', 'Kimnai Dispensary'), ('20006', 'Kimngorom Dispensary'), ('16720', 'Kimng''oror (ACK) Health Centre'), ('16458', 'Kimogoi Dispensary'), ('16334', 'Kimoloi Dispensary'), ('14875', 'Kimolwet Dispensary'), ('14876', 'Kimondi Forest Dispensary'), ('14877', 'Kimondo Dispensary'), ('10611', 'Kimondo Medical Clinic'), ('14878', 'Kimong Dispensary'), ('13693', 'Kimonge Dispensary'), ('14879', 'Kimoning Dispensary'), ('11477', 'Kimorigho Dispensary'), ('11478', 'Kimorigo Dispensary'), ('20009', 'Kimose Dispenary'), ('14870', 'Kimout Dispensary'), ('16590', 'Kim''s Intergrated Clinic'), ('19644', 'Kims Medical Clinic'), ('14880', 'Kimsaw Medical Clinic'), ('18524', 'Kimuchul Dispensary'), ('18914', 'Kimue Medical Clinic and Laboratory'), ('18129', 'Kimugu Dispensary'), ('16398', 'Kimugul Dispensary'), ('14881', 'Kimugul Dispensary (Baringo North)'), ('14882', 'Kimugul Dispensary (Kipkelion)'), ('17999', 'Kimulot Dispensary'), ('10612', 'Kimunyu (PCEA) Dispensary'), ('14884', 'Kimuren Dispensary'), ('17416', 'Kimuri Disp'), ('17028', 'Kimuri Dispensary'), ('12317', 'Kimutwa Dispensary'), ('12318', 'Kimutwa Medical Clinic'), ('17605', 'Kimweli Dispensary'), ('12319', 'Kina Dispensary'), ('11479', 'Kinagoni Dispensary'), ('12320', 'Kinakoni Dispensary'), ('10613', 'Kinale Forest Dispensary'), ('19790', 'Kinamba Medical Clinic'), ('11480', 'Kinango Hospital'), ('16518', 'Kinango Medical Clinic'), ('12321', 'Kinanie Dispensary'), ('11481', 'Kinarani Dispensary'), ('13694', 'Kinasia Dispensary'), ('13695', 'Kineni Dispensary'), ('19623', 'Kinga Medical Clinic (Dandora)'), ('20003', 'Kingorani Community Clinic'), ('11303', 'King''orani Prison Dispensary'), ('17545', 'Kings Clinic'), ('19436', 'Kings Cross Medical Clinic'), ('14886', 'Kings Medical Centre (Delivarance) Nakuru'), ('11482', 'Kingstone Medical Clinic'), ('14887', 'King''wal Dispensary'), ('12322', 'Kinisa Dispensary'), ('10614', 'Kinja Dispensary'), ('19625', 'Kinmed Medical Clinic (Dandora)'), ('12323', 'Kinna Health Centre'), ('16547', 'Kinondo Kwetu Community Clinic'), ('12324', 'Kinoro Medical Clinic'), ('12325', 'Kinoro Sub-District Hospital'), ('12326', 'Kinoru Dispensary'), ('10615', 'Kinunga Health Centre'), ('10616', 'Kinunga Medical Clinic'), ('16381', 'Kinungi Dispensary'), ('12327', 'Kinyaata Dispensary'), ('14888', 'Kinyach Dispensary'), ('13405', 'Mansabubu Health Centre'), ('16218', 'Mansile Dispensary'), ('10681', 'Manunga Health Centre'), ('15999', 'Manyala Sub-District Hospital'), ('11561', 'Manyani Dispensary'), ('13769', 'Manyatta (SDA) Dispensary'), ('20077', 'Manyatta Clinic'), ('17581', 'Manyatta Dispensary'), ('12470', 'Manyatta Jillo Health Centre'), ('15120', 'Manyatta Medical Clinic'), ('16773', 'Manyatta Medical Clinic (Nyeri South)'), ('18679', 'Manyoeni Dispensary'), ('15121', 'Manyoror Dispensary'), ('13770', 'Manyuanda Health Centre'), ('13771', 'Manyuanda Health Centre (Rarieda)'), ('14126', 'Manyuanda St Teresas CFW Clinic (Rarieda)'), ('20269', 'Manza dispensary'), ('20268', 'Maongoa Dispensary'), ('15122', 'Maparasha Dispensary'), ('16000', 'Mapengo Dispensary'), ('17692', 'Mapenya Dispensary'), ('15123', 'Mara Serena Dispensary'), ('19387', 'Maraa Catholic Dispensary'), ('11562', 'Marafa Health Centre'), ('17015', 'Maragi Dispensary'), ('15214', 'Molo South Dispensary'), ('15215', 'Molok Dispensary'), ('15216', 'Molos Dispensary'), ('15217', 'Molosirwe Dispensary'), ('20280', 'Mombasa Catholic Health Care Services'), ('17625', 'Mombasa HIV Clinic'), ('11643', 'Mombasa Hospital'), ('17621', 'Mombasa Medicare Clinic'), ('17627', 'Mombasa Polytechnic Clinic'), ('18121', 'Mombasa Roadside Wellness Centre'), ('16023', 'Mombasa Royal Clinic'), ('15218', 'Mombwo Dispensary'), ('15219', 'Momoniat Health Centre'), ('18576', 'Mong''oni'), ('16982', 'Mongorisi Health Centre'), ('17601', 'Monguni Dispensary'), ('13821', 'Monianku Health Centre'), ('10734', 'Monica Clinic'), ('15220', 'Monirre Dispensary'), ('18810', 'Montana Hospital'), ('18447', 'Moogi Dispensary'), ('15221', 'Morijo Dispensary'), ('15222', 'Morijo Loita Dispensary'), ('15223', 'Mormorio Dispensary'), ('16024', 'Moru Karisa Dispensary'), ('15225', 'Morulem Dispensary'), ('12541', 'Mosa Dispensary'), ('16261', '<NAME>'), ('15227', 'Mosiro Dispensary'), ('15226', 'Mosiro Dispensary (Kajiado North)'), ('19245', 'Moso Cheptarit Medical Clinic'), ('18580', 'Mosobeti Dispensary'), ('20114', 'Mosocho Market Disp'), ('15228', 'Mosore Dispensary'), ('19250', 'Mosoriot Clinic'), ('15229', 'Mosoriot Rural Health Training Centre'), ('15230', 'Mosoriot Ttc Dispensary'), ('13823', 'Mosque Dispensary'), ('17363', 'Most Precious Blood Sisters Dispensary'), ('13824', 'Motemorabu Dispensary'), ('13096', 'Mother & Child Hospital'), ('19277', 'Mother & Child Meridian & Lab Services'), ('11645', 'Mother Amadea Health Centre'), ('18298', 'Mother and Child Clinic Malindi'), ('15231', 'Mother Franciscan Mission Health Centre'), ('17724', 'Mother Ippolata Mukuru Clinic'), ('15232', 'Mother Kevin Dispensary (Catholic)'), ('12542', 'Mother Land Medical Clinic'), ('17654', 'Mother of Mercy (Machakos)'), ('11646', 'Mother Teresa Medical Clinic'), ('13825', 'Moticho Health Centre'), ('15233', 'Motiret Dispensary'), ('13826', 'Motontera Dispensary'), ('16984', 'Motonto Dispensary (Gucha)'), ('15234', 'Motosiet Dispensary'), ('11647', 'Mount View Nursing & Maternity Home'), ('19782', 'Mountain Med Clinic'), ('16206', 'Mountain Medical Clinic'), ('17754', 'Mountain View Clinic'), ('13097', 'Mow Dispensary'), ('16298', 'Mowlana Medical Clinic'), ('20066', 'Mowlem Diagnostic Medical Centre'), ('18037', 'Moyale Afya Medical Clinic'), ('12543', 'Moyale Catholic Dispensary'), ('12544', 'Moyale District Hospital'), ('12545', 'Moyale Nursing Home'), ('13098', 'Mp Shah Hospital (Westlands)'), ('17192', 'Mpala Mobile Clinic'), ('15236', 'Mpalla Dispensary'), ('18027', 'Mpalla Mobile Clinic'), ('15237', 'Mpata Club Dispensary'), ('18419', 'Mpc Mobile Clinic'), ('11648', 'Mpeketoni Health Services Clinic'), ('17694', 'Mpeketoni Health Sevices (Witu)'), ('11649', 'Mpeketoni Sub-District Hospital'), ('11650', 'Mpinzinyi Health Centre'), ('15328', 'Ndurumo Dispensary'), ('10842', 'Ndururumo Dispensary'), ('16923', 'Nduu Dispensary'), ('17814', 'Nduu Ndune Dispensary'), ('12639', 'Nduva Na Mwene Medical Clinic'), ('16937', 'Nduvani Dispensary'), ('16812', 'Neboi Dispensary'), ('12640', 'Neema (Midus) Medical Clinic'), ('19132', 'Neema Afya Centre'), ('20407', 'Neema Clinic'), ('20147', 'Neema Highway Medical Home'), ('12641', 'Neema Hospital'), ('18061', 'Neema Hospital (Ruiru)'), ('10843', 'Neema Medical'), ('17330', 'Neema Medical Clinic'), ('19161', 'Neema Medical Clinic (Kibera)'), ('18900', 'Neema Medical Clinic (Kitui Central)'), ('11707', 'Neema Medical Clinic (Malindi)'), ('17992', 'Neema Medical Clinic (Muranga North)'), ('15330', 'Neema Medical Clinic (Nakuru North)'), ('15329', 'Neema Medical Clinic (Trans Nzoia West)'), ('18192', 'Neema Medical Clinic Kitengela'), ('10844', 'Neema Medicare Centre'), ('16618', 'Nehema Medical Clinic'), ('16619', 'Nehema Medical Lab'), ('18130', 'Nehemah Clinic'), ('10603', 'Kikuyu (PCEA) Hospital'), ('17612', 'Kikuyuni Dispensary'), ('12309', 'Kilala Health Centre'), ('16648', 'Kilawa Dispensary'), ('12310', 'Kilawani Medical Clinic'), ('16197', 'Kilelengwani Dispensary'), ('12311', 'Kilembwa Dispensary'), ('14864', 'Kilgoris (Cog) Dispensary'), ('14865', 'Kilgoris Medical Centre'), ('11473', 'Kilibasi Dispensary'), ('14866', 'Kilibwoni Health Centre'), ('11474', 'Kilifi District Hospital'), ('11475', 'Kilifi Plantation Dispensary'), ('16921', 'Kiliku Dispensary'), ('12312', 'Kilili Dispensary'), ('17380', 'Kililii Dispensary'), ('11476', 'Kilimangodo Dispensary'), ('18249', 'Kilimanjaro Medical Clinic'), ('13034', 'Kilimanjaro Nursing Home'), ('16210', 'Kilimanjaro Skin & Medical Clinic'), ('20031', 'Kilimu Dispensary'), ('15945', 'Kilingili Health Centre'), ('16428', 'Kilinito Dispensary (CDF)'), ('18004', 'Kilisa Dispensary'), ('13381', 'Kiliweheri Health Centre'), ('13698', 'Kipkebe Health Centre'), ('14894', 'Kipkeibon Tea Dispensary'), ('14895', 'Kipkeikei Dispensary'), ('14896', 'Kipkelion (CHFC) Dispensary'), ('14897', 'Kipkelion Sub District Hospital'), ('14898', 'Kipkenyo Dispensary'), ('14899', 'Kipketer Dispensary'), ('17091', 'Kipkitur Dispensary'), ('14900', 'Kipkoigen Tea Dispensary'), ('14901', 'Kipkoimet Tea Dispensary'), ('19883', 'Kipkonyo Dispensary'), ('17014', 'Kipkoror Dispensary'), ('18186', 'Kipkundul Dispensary'), ('14902', 'Kiplalmat Dispensary'), ('17316', 'Kiplelgutik Dispensary'), ('14903', 'Kiplelji Dispensary'), ('18525', 'Kiplobotwa Dispensary'), ('17299', 'Kiplobotwo Dispensary'), ('14904', 'Kiplombe AIC Dispensary'), ('17154', 'Kiplombe Dispensary (Koibatek)'), ('16733', 'Kipnai Dispensary'), ('14905', 'Kipngchoch Medical Clinic'), ('16473', 'Kiprengwet Dispensary'), ('14907', 'Kipsacho Dispensary'), ('14909', 'Kipsaiya Dispensary'), ('14910', 'Kipsamoite Dispensary'), ('14911', 'Kipsaos Dispensary'), ('14912', 'Kipsaraman Dispensary'), ('14913', 'Kipsegi Dispensary'), ('14914', 'Kipsigak Baibai Dispensary'), ('14916', 'Kipsigak Dispensary (Nandi)'), ('14915', 'Kipsigak Health Centre'), ('15952', 'Kipsigon (FGC) Health Centre'), ('12330', 'Kipsing Dispensary'), ('14918', 'Kipsingei Dispensary'), ('19591', 'Kipsitet Baptist Dispensary'), ('14919', 'Kipsitet Dispensary'), ('17283', 'Kipsoen Dispensary'), ('17099', 'Kipsogon Dispensary'), ('14920', 'Kipsonoi Health Centre'), ('17637', 'Kipsugur Dispensary'), ('14921', 'Kipsuter Dispensary'), ('14922', 'Kipsyenan Dispensary'), ('14923', 'Kiptagich Health Centre'), ('14924', 'Kiptagich Model Health centre'); INSERT INTO `facility_list` (`Facility_Code`, `Facility_Name`) VALUES ('14925', 'Kiptagich Tegat Dispensary'), ('14926', 'Kiptangwanyi Dispensary'), ('13699', 'Kiptenden Dispensary'), ('14927', 'Kiptenden Dispensary (Buret)'), ('19282', 'Kiptenden Dspensary (Nandi Central)'), ('14928', 'Kiptere Dispensary'), ('14929', 'Kiptewit Dispensary'), ('20011', 'Kiptoim Dispensary'), ('14930', 'Kiptome Dispensary'), ('18742', 'Kiptome Dispensary (Belgut)'), ('16404', 'Kiptororo Dispensary'), ('14931', 'Kiptulos Dispensary'), ('14932', 'Kiptulwa Dispensary'), ('14933', 'Kiptuno Dispensary'), ('14934', 'Kipture Dispensary'), ('11485', 'Kipungani Dispensary'), ('14935', 'Kipwastuiyo Health Centre'), ('18526', 'Kipyosit Dispensary'), ('18881', 'Kiracha CFW Clinic'), ('10619', 'Kiracha Medical Clinic'), ('16591', 'Kiramburune Medical Clinic'), ('17003', 'Kiraone Dispensary'), ('17912', 'Kirathe Dispensary'), ('10622', 'Kirathimo Medical Clinic'), ('14936', 'Kiratina Medical Clinic'), ('10624', 'Kiria Health Centre'), ('10625', 'Kiria-Ini Dispensary'), ('10626', 'Kiriaini Medical Clinic'), ('10627', 'Kiria-Ini Mission Hospital'), ('12331', 'Kiriani Dispensary'), ('12332', 'Kiriari (ACK) Dispensary'), ('19224', 'Kiriari Dispensary'), ('14937', 'Kiribwet Dispensary'), ('14938', 'Kiricha Dispensary'), ('20381', 'LIFOG Medical Clinic'), ('19720', 'Lifters Community Medical Clinic'), ('18320', 'Ligala Dispensary'), ('13735', 'Ligega Health Centre'), ('11519', 'Light For Christ Hospital'), ('19334', 'Light Hospital'), ('20132', 'Light Medical and Side Lab Naivasha'), ('17512', 'Lihanda Health Centre'), ('16684', 'Likia Dispensary'), ('15035', 'Likii Dispensary'), ('17539', 'Likii VCT'), ('15960', 'Likindu Dispensary'), ('11520', 'Likoni Catholic Dispensary'), ('11522', 'Likoni District Hospital'), ('18454', 'Likoni HIV Resource Centre'), ('15961', 'Likuyani Sub-District Hospital'), ('15036', 'Likwon Dispensary'), ('10660', 'Lilian Wachuka Clinic'), ('17833', 'Lilian Wacuka Medical Clinic'), ('18460', 'Lilongwe Community Health Care'), ('16593', 'Lily Clinic'), ('19087', 'Lilyon Clinical Services'), ('12428', 'Limauru Dispensay'), ('15037', 'Limo Surgical Hospital'), ('12429', 'Limoro Dispensary'), ('16678', 'Kiruri Dispensary (Laikipia West)'), ('10637', 'Kiruri Dispensary (Muranga North)'), ('10638', 'Kirurumi Dispensary'), ('10640', 'Kirwara Health Clinic'), ('10639', 'Kirwara Sub District'), ('19345', 'Kisaju Health Care Isinya'), ('19346', 'Kisaju Medical Clinic'), ('13700', 'Kisaku Dispensary'), ('14940', 'Kisanana Health Centre'), ('19340', 'Kisangula Medical Clinic'), ('12340', 'Kisasi Dispensary (Kitui)'), ('16744', 'Kisasi Medical Clinic'), ('12341', 'Kisau Sub District Hospital'), ('17911', 'Kisauni Dispensary'), ('17623', 'Kisauni Drop In VCT'), ('11487', 'Kisauni Medical Clinic'), ('12342', 'Kisayani Health Centre'), ('13701', 'Kisegi Sub-District Hospital'), ('20413', 'Kisekini Dispensary '), ('20044', 'Kisembe Dispensary'), ('13035', 'Kisembo Dispensary'), ('14941', 'Kiserian Dispensary'), ('14942', 'Kiserian Medical Clinic'), ('12343', 'Kisesini Dispensary'), ('12345', 'Kiseuni Dispensary '), ('12344', 'Kiseuni Dispensary (Kitui)'), ('12346', 'Kiseveni Dispensary'), ('17160', 'Kishaunet Dispensary'), ('19736', 'Kishon'), ('11488', 'Kishushe Dispensary'), ('13702', 'Kisii Campus Dispensary'), ('13703', 'Kisii Hospital (Level 5)'), ('12347', 'Kisiiki Dispensary'), ('19291', 'Kisima Community Medical Clinic'), ('14943', 'Kisima Health Centre'), ('11489', 'Kisimani Health Services'), ('19628', 'Kisiwani VCT'), ('20128', 'Kisoi Munyao Memorial Dispensary'), ('14944', 'Kisok Dispensary'), ('16672', 'Kisonei Dispensary'), ('14945', 'Kisor Dispensary'), ('19935', 'Kisovo Dispensary'), ('20193', 'Kisukioni Dispensary'), ('12348', 'Kisukioni Medical Clinic'), ('13704', 'Kisumu District Hospital'), ('17553', 'Kisumu International Airport Dispensary'), ('19869', 'Kisumu Police Lines Dispensary'), ('20415', 'Kisyoka Dispensary'), ('18522', 'Kitaima Dispensary'), ('14946', 'Kitalale Dispensary'), ('19743', 'Kitale Cottage Hospital'), ('14947', 'Kitale District Hospital'), ('14817', 'Katibel Dispensary'), ('20125', 'Katilini Dispensary'), ('12241', 'Katilini Health Cetre'), ('14818', 'Katilu District Hospital'), ('20040', 'Katingani Dispensary'), ('16969', 'Katipanga Dispensary'), ('16940', 'Katithini Dispensary'), ('13657', 'Katito Health Centre'), ('18421', 'Katolo-Manyatta Health Centre'), ('17356', 'Katote Dispensary'), ('18246', 'Katothya Dispensary'), ('12242', 'Katse Health Centre'), ('12243', 'Katse Medical Clinic'), ('14819', 'Katuiyo Dispensary'), ('12244', 'Katulani Health Centre'), ('20261', 'Katulani Medical Clinic(kitui)'), ('16991', 'Katulani Sub District Hospital (Kitui)'), ('12246', 'Katulye Dispensary'), ('19888', 'Katulye Dispensary (Kibwezi)'), ('17433', 'Katulye Dispensary-Nzaui'), ('12247', 'Katumani Dispensary'), ('12248', 'Katumbu Dispensary'), ('19235', 'Katune Dispensary'), ('20458', 'Katungura dispensary'), ('12249', 'Katutu Dispensary'), ('12388', 'Katwala Dispensary'), ('12250', 'Katwanyaa Medical Clinic'), ('12251', 'Katyethoka Health Centre'), ('11456', 'Kau Dispensary'), ('12252', 'Kauma Dispensary (Kitui)'), ('13658', 'Kauma Health Centre (Rachuonyo)'), ('12253', 'Kaumu Dispensary'), ('12720', 'Kaune''s Medical Clinic'), ('18316', 'Kaunguni Dispensary'), ('14820', 'Kauriong Dispensary'), ('18230', 'Kauthulini Dispensary'), ('12255', 'Kauwi Sub-District Hospital'), ('12256', 'Kavata Nzou Dispensary'), ('17163', 'Kavatanzou Dispensary'), ('19977', 'Kavete Dispensary (Makindu)'), ('12257', 'Kaviani Health Centre'), ('12258', 'Kavindu Health Centre'), ('12259', 'Kavisuni Dispensary'), ('20275', 'Kavisuni Dispensary(Mwingi)'), ('12260', 'Kavisuni Health Care Clinic'), ('19988', 'Kavuko Dispensary'), ('12261', 'Kavumbu Dispensary'), ('16650', 'Kavumbu Dispensary (Mwala)'), ('12262', 'Kavuta Dispensary'), ('12263', 'Kavuthu H/Centre'), ('12264', 'Kavuvwani Dispensary'), ('19513', 'Kawangware Health Centre'), ('17615', 'Kawauni Dispensary'), ('10511', 'Kaweru Medical Clinic'), ('12265', 'Kawethei Medical Clinic'), ('12266', 'Kawiria Maternity and Nursing Home'), ('17262', 'Kawiru Dispensary'), ('19076', 'Kawongo Medical Centre'), ('20423', 'Kaw''ongo Medical Centre'), ('16340', 'Kayanet Clinic'), ('12267', 'Kayatta Dispensary'), ('16710', 'Kayaya Dispensary'), ('13014', 'Kayole Hospital'), ('13015', 'Kayole I Health Centre'), ('13016', 'Kayole II Sub-District Hospital'), ('12268', 'Kea Dispensary'), ('13659', 'Kebaroti Dispensary'), ('14821', 'Keben Dispensary'), ('14822', 'Kebeneti (SDA) Health Centre'), ('14823', 'Kebeneti Dispensary'), ('13660', 'Kebirigo Mission Health Centre'), ('14824', 'Kedowa Dispensary'), ('16960', 'Kee Dispensary'), ('17958', 'Keega Medical Clinic'), ('17435', 'Keera Dispensary'), ('18729', 'Kefra Clinic'), ('13661', 'Kegati Medical Clinic'), ('13662', 'Kegogi Health Centre'), ('15928', 'Kegondi Health Centre'), ('19670', 'Kitale Eye Care Clinic'), ('19744', 'Kitale Medical Centre - Dr Kamau''s MC'), ('19745', 'Kitale Medical Centre - Dr Kiprop''s MC'), ('19691', 'Kitale Medical Centre - Dr Omunyin'), ('19747', 'Kitale Medical Centre - Dr Onyango''s MC'), ('19847', 'Kitale Medical Centre - Sloam CBO'), ('14948', 'Kitale Mobile Clinic'), ('14949', 'Kitale Nursing Home'), ('19684', 'Kitale Sch Sanatorium'), ('18441', 'Kitambaasye Dispensary'), ('17451', 'Kitamwiki Community Dispensary'), ('12349', 'Kitangani Dispensary'), ('13705', 'Kitare Health Centre'), ('17469', 'Kiteje Dispensary'), ('20324', 'kitende Dispensary'), ('18401', 'Kitengela Centre of Hope Medical Clinic'), ('19698', 'Kitengela Dental Clinic'), ('19677', 'Kitengela ENT and Medical Centre'), ('14950', 'Kitengela Health Centre'), ('14951', 'Kitengela Medical Services'), ('18976', 'Kitengela Medical Services Kajiado'), ('17840', 'Kitengela Pona Services'), ('17341', 'Kitere Dispensary'), ('20026', 'Kitere Minhaj Dispensary'), ('10512', 'Kenol Hospital'), ('17544', 'Kentalya Farm Cilinic'), ('10513', 'Kenton Dispensary'), ('13020', 'Kenwa'), ('17489', '<NAME>'), ('10514', 'Kenwa-Nyeri'), ('13670', 'Kenya Acorn Project (Acorn) Health Centre'), ('13013', 'Kenya AIDS Vaccine Initiative (Kavi)'), ('18261', 'Kenya Airports Employees Association'), ('13021', 'Kenya Airways Medical Centre'), ('18732', 'Kenya Assemblies of God Medical Clinic'), ('18575', 'Kenya Assemblies of God Medical Clinic (Kag Naivas'), ('18385', 'Kenya Association of Pofessional Counsellors (Kapc'), ('10515', 'Kenya Institute of Professional Counsellors'), ('20303', 'kenya institute of special education dispensary'), ('19599', 'Kenya Long Distance Truck Drivers Union VCT'), ('17040', 'Kenya Medical Training College Lodwar'), ('12517', 'Kenya Methodist University Dispensary'), ('11459', 'Kenya Navy (Mir) Hospital'), ('10516', 'Kenya Nut Company Dispensary'), ('10517', 'Kenya Police College Dispensary'), ('20371', 'Kenya Police Staff College Clinic'), ('18212', 'Kenya Ports Authority Staff Clinic'), ('13022', 'Kenya Utalii Dispensary'), ('14828', 'Kenyagoro Dispensary'), ('13671', 'Kenyambi Health Centre'), ('16980', 'Kenyambi Health Centre (Nyamira)'), ('13023', 'Kenyatta National Hospital'), ('19093', 'Kenyatta National Hospital Ongata Rongai'), ('13024', 'Kenyatta University Dispensary'), ('17534', 'Kenyatta University Health Unit Mombasa Campus'), ('18879', 'Kenyatta University Kitui Campus Health Unit'), ('13673', 'Kenyenya District Hospital'), ('20141', 'Kenyenya Health Centre'), ('17712', 'Kenyenya Medical Centre (Kenyenya)'), ('17677', 'Kenyenya Medical Clinic (Kenyenya)'), ('13675', 'Kenyerere Dispensary (Masaba)'), ('13674', 'Kenyerere Dispensary (Sameta)'), ('16280', 'Kenyerere Health Centre (Nyamira)'), ('19996', 'Kenyoro Dispensary'), ('13676', 'Kenyoro Health Centre'), ('14829', 'Kepchomo Tea Dispensary'), ('18336', 'Keragia Dispensary (Gucha)'), ('14830', 'Kerenga Dispensary'), ('19257', 'Kerer Dispensary'), ('19362', 'Kereri Dispensary'), ('14831', 'Kericho District Hospital'), ('14832', 'Kericho Forest Dispensary'), ('14833', 'Kericho Municipal Health Centre'), ('14834', 'Kericho Nursing Home'), ('18163', 'Kericho Youth Centre'), ('17590', 'Kericho Youth Centre'), ('14835', 'Keringani Dispensary'), ('14837', 'Keringet Health Centre'), ('14836', 'Keringet Health Centre (Kuresoi)'), ('18587', 'Keringet Youth Friendly Centre'), ('14838', 'Kerio Health Centre'), ('13677', 'Keritor Dispensary'), ('20389', 'Kernan Medical Clinic'), ('17232', 'Kerobo Health Centre'), ('14839', 'Kerol Health Centre'), ('14840', 'Kerol Health Services'), ('10519', 'Kerugoya Catholic Dispensary'), ('10520', 'Kerugoya District Hospital'), ('10522', 'Kerugoya Medical Centre'), ('10525', 'Kerugoya Medical Laboratory'), ('16502', 'Kerugoya Medical Services and Advisory Centre'), ('16868', 'Kerumbe Dispensary'), ('20212', 'Kerwa Catholic Health Centre'), ('10523', 'Kesma Clinic'), ('19363', 'Kesogon Dispensary'), ('17159', 'Kesot Dispensary'), ('14841', 'Kesses Health Centre'), ('14842', 'Ketepa Dispensary (Kericho)'), ('17210', 'Ketitui Dispensary'), ('10586', 'Kigoro Dispensary'), ('16235', 'Kiguchwa Dispensary'), ('12300', 'Kigumo Dispensary'), ('10587', 'Kigumo Health Centre (Kiambu East)'), ('10588', 'Kigumo Sub District Hospital (Kigumo)'), ('13691', 'Kigwa Dispensary'), ('10590', 'Kihaaro Medical Clinic'), ('10591', 'Kihara Sub-District Hospital'), ('14860', 'Kihato Dispensary'), ('14861', 'Kihia Medical Clinic'), ('10592', 'Kihinga Dispensary'), ('18020', 'Kihinga Medical Clinic'), ('16390', 'Kihingo Dispensary (CDF)'), ('10593', 'Kihora Medical Clinic'), ('10594', 'Kihoya Dispensary'), ('10595', 'Kihoya Medical Centre'), ('10596', 'Kihugiru Maternity Disp'), ('10597', 'Kihumbuini (PCEA) Dispensary'), ('10598', 'Kihumbu-Ini Community Dispensary'), ('17000', 'Kihuri Dispensary'), ('10599', 'Kihuro (ACK) Dispensary'), ('10600', 'Kihuti Orthodox Clinic'), ('10601', 'Kihuyo Dispensary'), ('17214', 'Kiija Dispensary'), ('19233', 'Kiima Kiu Dispensary'), ('17443', 'Kiima Kiu Health Care Services Dispensary'), ('17818', 'Kiimani Medical Clinic'), ('12301', 'Kiini Health Centre'), ('15484', 'Khems Medical Clinic'), ('10524', 'Khilna Medical Clinic'), ('13380', 'Khorof Harar Sub-District Hospital'), ('17041', 'Khulwanda Dispensary'), ('15938', 'Khumsalaba Clinic'), ('15939', 'Khunyangu Sub-District Hospital'), ('15940', 'Khwisero Health Centre'), ('10526', 'Kiaguthu Dispensary'), ('13681', 'Kiagware Dispensary'), ('10527', 'Kiahuria Medical Clinic'), ('17953', 'Kiaibabu Dispensary'), ('10528', 'Kiairathe Dispensary'), ('10529', 'Kiairegi Clinic'), ('12270', 'Kiairugu Dispensary'), ('10530', 'Kiamabara Dispensary'), ('10531', 'Kiamagunyi (ACK) Clinic'), ('10532', 'Kiamanyeki Dispensary'), ('20294', 'Kiamanyomba (Nyamira North)'), ('10533', 'Kiamara Dispensary'), ('10534', 'Kiamara Medical Clinic'), ('10535', 'Kiamariga Medical Clinic'), ('10536', 'Kiamathaga Dispensary'), ('17396', 'Kiambaa Medical Clinic'), ('12271', 'Kiambere Dam Dispensary'), ('16465', 'Kiambere Health Centre'), ('16408', 'Kiamberiria Dispensary (CDF)'), ('14845', 'Kiambogo Dispensary (Naivasha)'), ('10537', 'Kiambogo Dispensary (Nyandarua South)'), ('10538', 'Kiambogo Medical Clinic'), ('17564', 'Kiambogo Medical Clinic (Wanjohi)'), ('10539', 'Kiambu District Hospital'), ('10540', 'Kiambu Institute of Science and Technology Dispens'), ('18032', 'Kiambu Medical Centre'), ('17016', 'Kiambuthia Dispensary'), ('10541', 'Kiambuthia Medical Clinic'), ('17468', 'Kiamiriru MCK Dispensary'), ('13683', 'Kiamokama Health Centre'), ('12272', 'Kiamuchairu Health Centre'), ('12273', 'Kiamuchii Dispensary'), ('10542', 'Kiamuiru Medical Clinic'), ('12274', 'Kiamuringa Dispensary'), ('12275', 'Kiamuriuki Dispensary'), ('19431', 'Kiamuthambi Dispensary'), ('10543', 'Kiamuthambi Medical Clinic'), ('16497', 'Kiamutugu CFW Clinic'), ('10544', 'Kiamutugu Clinic'), ('10545', 'Kiamutugu Health Centre'), ('10546', 'Kiamuya Dispensary'), ('10547', 'Kiamwathi Medical Clinic'), ('17258', 'Kianda Dispensary'), ('10549', 'Kiandai Clinic'), ('10551', 'Kiandegwa (Methodist Church of Kenya) Dispensary'), ('10552', 'Kiandere Dispensary'), ('19430', 'Kianderi Dispensary'), ('17709', 'Kiandiu Dispensary'), ('10553', 'Kiandu Medical Clinic'), ('16814', 'Kiandutu Health Centre'), ('10554', 'Kiane Medical & Eye Clinic'), ('11463', 'Kiangachinyi Dispensary'), ('10556', 'Kiangai Health Centre'), ('16503', 'Kiangai Laboratory'), ('10557', 'Kiangai Medical Clinic'), ('16989', 'Kiang''inda Health Centre'), ('12276', 'Kiangini Dispensary'), ('10558', 'Kiangochi Dispensary'), ('10555', 'Kiang''ombe Dispensary'), ('12277', 'Kiangondu Dispensary'), ('13684', 'Kiangoso Dispensary'), ('18848', 'Kiangua Dispensary'), ('10559', 'Kiangunyi Dispensary'), ('10561', 'Kiangwenyi Clinic'), ('10562', 'Kianjege Dispensary'), ('20155', 'Kianjokoma Muungano SHG Community Dispensary'), ('12278', 'Kianjokoma (ACK) Trinity Clinic'), ('12279', 'Kianjokoma Sub-District Hospital'), ('14846', 'Kianjoya Dispensary'), ('16172', 'Kianjugu Dispensary'), ('12302', 'Kiirua Dispensary'), ('12304', 'Kiitini Dispensary'), ('10602', 'Kijabe (AIC) Hospital'), ('10693', 'Kijabe (AIC) Hospital Marira Medical Clinic'), ('20345', 'Kijana Heri Medical Clinic'), ('17821', 'Kijani (Mirera) Dispensary'), ('13692', 'Kijauri Sub District Hospital'), ('16765', 'Kijawa Dispensary'), ('11470', 'Kikambala Catholic Medical Clinic'), ('11471', 'Kikambala Medical Services'), ('12305', 'Kikesa Dispensary'), ('16932', 'Kikiini Dispensary'), ('19832', 'Kikinga Medical Clinic'), ('12306', 'Kikoko Mission Hospital'), ('11472', 'Kikoneni Health Centre'), ('18944', 'Kikopey Dispensary'), ('13033', 'K<NAME> (Mugumoini)'), ('14863', 'Kikton Medical Clinic'), ('18689', 'Kikule Dispensary'), ('12307', 'Kikumini Dispensary'), ('17147', 'Kikumini Dispensary (Makueni)'), ('12308', 'Kikumini Health Centre'), ('18683', 'Kikuu Dispensary'), ('14680', 'Kamwosor sub-district hospital'), ('14681', 'Kanakurudio Health Centre'), ('11454', 'Kanamai Health Care'), ('14682', 'Kanaodon Dispensary'), ('14683', 'Kanawoi Dispensary'), ('10459', 'Kandara Sub District Hospital'), ('18721', 'Kandaria Medical Centre'), ('18869', 'Kandebene Dispensary'), ('13652', 'Kandege Dispensary'), ('10460', 'Kanderendu Dispensary'), ('13653', 'Kandiege Sub-District Hospital'), ('10461', 'Kandong''u Dispensary'), ('14684', 'Kandutura Dispensary'), ('16860', 'Kandwia Dispensary'), ('14685', 'Kangagetei Dispensary'), ('10462', 'Kangaita Health Centre'), ('10463', 'Kangaita Medical Clinic (Kirinyaga Central)'), ('14686', 'Kangakipur Dispensary'), ('17476', 'Kangalita Dispensary'), ('12171', 'Kangalu Dispensary'), ('15920', 'Kanganga Dispensary'), ('10465', 'Kangari Health Centre'), ('10466', 'Kangari Medical Clinic'), ('12172', 'Kangaru Dispensary (Embu)'), ('10468', 'Kangaru Dispensary (Kirinyaga)'), ('12173', 'Kangaru Hospital'), ('14687', 'Kangatosa Dispensary'), ('10469', 'Kangema Medical Clinic'), ('10470', 'Kangema Sub-District Hospital'), ('19536', 'Kangemi Gichagi Dispensary'), ('13001', 'Kangemi Health Centre'), ('17065', 'Kangeta G K Prison Dispensary'), ('12174', 'Kangeta Health Centre'), ('17475', 'Kangirisae Dispensary'), ('16703', 'Kanglikwan Dispensary'), ('16818', 'Kangocho Dispensary'), ('16373', 'Kangoletiang Dispensary'), ('17106', 'Kangonde Health Centre'), ('20169', 'Kangri Dispensary'), ('10471', 'Kangu Dispensary'), ('19771', 'Kangubiri Girls High School Clinic'), ('12176', 'Kangundo Community Clinic'), ('12177', 'Kangundo District Hospital'), ('12178', 'Kaningo Health Centre'), ('12179', 'Kanja Health Centre'), ('10472', 'Kanjama Dispensary'), ('10436', 'Kanjinji Dispensary'), ('17001', 'Kanjora (PCEA) Dispensary'), ('10473', 'Kanjuiri Dispensary'), ('14688', 'Kanusin Dispensary'), ('12180', 'Kanyaa Dispensary'), ('13654', 'Kanyagwal Dispensary'), ('12181', 'Kanyakine District Hospital'), ('12183', 'Kanyangi Mission Dispensary'), ('12184', 'Kanyangi Sub-District Hospital'), ('14689', 'Kanyarkwat Dispensary'), ('16931', 'Kanyekini Dispensary'), ('17834', 'Kanyenyaini ACK Dispensary'), ('10474', 'Kanyenyaini Health Centre'), ('10475', 'Kanyenyaini Medical Clinic'), ('20084', 'Kanyerus Dispensary'), ('18508', 'Kanyongonyo'), ('20218', 'Kanyoni Community Dispensary'), ('12185', 'Kanyuambora Dispensary'), ('12186', 'Kanyunga Health Centre'), ('12187', 'Kanyungu Dispensary'), ('12188', 'Kanyuru Dispensary'), ('16994', 'Kanzau Dispensary'), ('18687', 'Kanzauwu Dispensary'), ('20416', 'Kanzaw''u Dispensary'), ('12190', 'Kanziku Health Centre'), ('12191', 'Kanzokea Health Centre'), ('18567', 'Kanzui Dispensary'), ('12192', 'Kaongo Health Centre'), ('17105', 'Kaonyweni Dispensary'), ('16335', 'Kaparon Health Centre'), ('20464', 'Kapau dispensary'), ('14849', 'Kibendo Dispensary'), ('20325', 'Kibera CFW Clinic'), ('12894', 'Kibera Chemi Chemi Ya Uzima Clinic'), ('13028', 'Kibera Community Health Centre - Amref'), ('20183', 'Kibera Community Self Help Program - Migori '), ('13029', 'Kibera D O Dispensary'), ('18984', 'Kibera Highway Clinic'), ('13026', 'Kibera Human Development Clinic'), ('13030', 'Kibera South (Msf Belgium) Health Centre'), ('17088', 'Kibias Dispensary'), ('13687', 'Kibigori Dispensary'), ('14850', 'Kibigos Dispensary'), ('15942', 'Kibingei Dispensary'), ('14851', 'Kibingor Dispensary'), ('14852', 'Kibini Hill (PCEA) Dispensary'), ('19134', 'Kibirichia Health & Laboratory Services'), ('16825', 'Kibirichia Medcare'), ('12282', 'Kibirichia Sub-District Hospital'), ('10571', 'Kibirigwi Health Centre'), ('16504', 'Kibirigwi Laboratory'), ('17707', 'Kibiru Dispensary'), ('17102', 'Kibiryokwonin Dispensary'), ('19366', 'Kibisem Dispensary'), ('14854', 'Kibish Dispensary'), ('17656', 'Kapkatet Hospital VCT'), ('14707', 'Kapkeben Dispensary'), ('14708', 'Kapkeburu Dispensary'), ('16354', 'Kapkei Dispensary'), ('14709', 'Kapkein Dispensary'), ('17293', 'Kapkelei'), ('14710', 'Kapkelelwa Dispensary'), ('14711', 'Kapkenyeloi Dispensary'), ('14713', 'Kapkeringoon Dispensary'), ('17808', 'Kapkesembe Dispensary'), ('14714', 'Kapkesosio Dispensary'), ('17284', 'Kapkessum Dispensary'), ('19884', 'Kapket Dispensary'), ('14715', 'Kapkiam Dispensary'), ('14716', 'Kapkiamo Dispensary'), ('17642', 'Kapkibimbir Dispensary'), ('14717', 'Kapkimolwa Dispensary'), ('14718', 'Kapkisiara Dispensary'), ('14719', 'Kapkitony Dispensary'), ('17417', 'Kapkoi Disp'), ('14720', 'Kapkoi Dispensary'), ('14721', 'Kapkoi Health Centre'), ('14722', 'Kapkoi Mission Dispensary'), ('14723', 'Kapkole Dispensary'), ('14724', 'Kapkolei Dispensary'), ('20467', 'Kapkombe Dispensary'), ('17019', 'Kapkomoi Dispensary'), ('17152', 'Kapkoris Dispensary'), ('14726', 'Kapkormom Dispensary'), ('14727', 'Kapkoros Dispensary'), ('17772', 'Kapkoros Dispensary (Tinderet)'), ('14728', 'Kapkoros Health Centre'), ('17076', 'Kapkota Dispensary'), ('19013', 'Kapkres Medical Clinic'), ('14729', 'Kapkuei Dispensary'), ('14731', 'Kapkurer Dispensary'), ('14730', 'Kapkurer Dispensary (Kericho)'), ('14732', 'Kapkures Dispensary (Baringo)'), ('17318', 'Kapkures Dispensary (Kericho)'), ('14733', 'Kapkures Dispensary (Nakuru Central)'), ('16318', 'Kapkures Dispensary (Sotik)'), ('17756', 'Kapkwen Dispensary'), ('17301', 'Kaplamai Dispensary'), ('14734', 'Kaplamai Health Centre'), ('14735', 'Kaplel Dispensary'), ('14736', 'Kaplelach Chepyakwai'), ('19018', 'Kaplelach Clinic'), ('14737', 'Kaplelach Tumoge'), ('14738', 'Kaplelartet Dispensary'), ('14739', 'Kaplenge Dispensary'), ('16674', 'Kapletingi Dispensary'), ('16317', 'Kapletundo Dispensary'), ('14740', 'Kaplomboi Dispensary'), ('14741', 'Kaplong Hospital'), ('14742', 'Kaplong Medical Clinic'), ('14743', 'Kapluk Dispensary'), ('17312', 'Kaplutiet'), ('14744', 'Kapngetuny Dispensary'), ('14745', 'Kapng''ombe Dispensary'), ('14746', 'Kapnyeberai Dispensary'), ('14747', 'Kapoleseroi Dispensary'), ('14748', 'Kaprachoge Tea Dispensary'), ('19294', 'Kaproret Dispensary'), ('14749', 'Kapsabet District Hospital'), ('17632', 'Kapsabet Health Care Centre'), ('19281', 'Kapsabet Medicare Centre'), ('19734', 'Kapsagawat Dispensary'), ('14750', 'Kapsait Dispensary'), ('17043', 'Kapsait Dispensary (Pokot South)'), ('15923', 'Kapsambu Dispensary'), ('14751', 'Kapsamoch Dispensary'), ('18148', 'Kapsang''ar Dispensary'), ('17294', 'Kapsangaru Dispensary'), ('14752', 'Kapsaos Dispensary'), ('14753', 'Kapsara District Hospital'), ('14754', 'Kapsasian Dispensary'), ('14755', 'Kapseger Dispensary'), ('14756', 'Kapsengere Dispensary'), ('14757', 'Kapset Dispensary'), ('10661', 'Limuru Health Centre'), ('18836', 'Limuru Medical Clinic'), ('10662', 'Limuru Nursing Home'), ('18652', 'Limuru Sasa Centre'), ('20406', 'Lina Medical Services'), ('19953', 'Linda Maternity'), ('15038', 'Lingwai Dispensary'), ('15039', 'Litein Dispensary'), ('15040', 'Liter (AIC) Dispensary'), ('18611', 'Lithi Clinic'), ('10663', 'Little Flower Dispensary'), ('17589', 'Live With Hope'), ('13050', 'Liverpool VCT'), ('16662', 'Liverpool VCT (Kisumu East)'), ('17664', 'Liverpool VCT (Machakos)'), ('12430', 'Liverpool VCT Embu'), ('12431', 'Liviero Dispensary'), ('10664', 'Liz Medical Clinic'), ('17145', 'Lkuroto Dispensary'), ('18737', 'Lobei Health Centre'), ('15042', 'Loboi Dispensary'), ('19508', 'Local Aid Organization'), ('17034', 'Location Medical Clinic'), ('15043', 'Locheremoit Dispensary'), ('15044', 'Lochoraikeny Dispensary'), ('17480', 'Lochorekuyen Dispensary'), ('14774', 'Kaptalamwa Health Centre'), ('15924', 'Kaptalelio Dispensary'), ('15925', 'Kaptama (Friends) Health Centre'), ('15926', 'Kaptanai Dispensary'), ('14776', 'Kaptarakwa Sub-District Hospital'), ('14777', 'Kaptebengwo Dispensary'), ('16456', 'Kaptech Dispensary'), ('14778', 'Kaptel Dispensary'), ('19872', 'Kapteldet'), ('14779', 'Kapteldon Health Centre'), ('14780', 'Kaptembwo Dispensary'), ('14781', 'Kapteren Health Centre'), ('18185', 'Kapterit Dispensary'), ('14782', 'Kaptich Dispensary'), ('17130', 'Kaptien Community Dispensary'), ('14783', 'Kaptien Dispensary'), ('17638', 'Kaptildil Dispensary'), ('14784', 'Kaptimbor Dispensary'), ('14785', 'Kaptiony Dispensary'), ('14786', 'Kaptiony Dispensary (Marakwet)'), ('16457', 'Kaptisi Dispensary'), ('14787', 'Kaptoboiti Dispensary'), ('14775', 'Kaptorokwa Dispensary'), ('17254', 'Kaptoror Dispensary'), ('14788', 'Kaptum Dispensary'), ('17758', 'Kaptum Keiyo Dispensary'), ('14789', 'Kaptumek Dispensary'), ('14790', 'Kaptumin Dispensary'), ('14791', 'Kaptumo Dispensary'), ('14792', 'Kaptumo Sub-District Hospital'), ('14793', 'Kapturo Dispensary (Bartabwa)'), ('16725', 'Kaptuya Dispensary'), ('13002', 'Kapu Medical Clinic'), ('14795', 'Kapua Dispensary'), ('17321', 'Kapune Dispensary'), ('16737', 'Kapunyany Dispensary'), ('14796', 'Kaputir Dispensary'), ('14797', 'Kapweria Dispensary'), ('14798', 'Kapyego Health Centre'), ('14799', 'Kapyemit Dispensary'), ('14800', 'Karaba Dispensary (Laikipia West)'), ('12193', 'Karaba Dispensary (Mbeere)'), ('10476', 'Karaba Health Centre (Nyeri South)'), ('12194', 'Karaba Wango Dispensary'), ('14801', 'Karagita Dispensary'), ('10477', 'Karaha Dispensary'), ('19665', 'Karai Medical Clinic'), ('10478', 'Karaini (ACK) Dispensary'), ('12195', 'Karama Dispensary'), ('10479', 'Karandi Health Clinic'), ('12196', 'Karandini Dispensary'), ('17771', 'Karandini Medical Clinic'), ('10480', 'Karangaita Socfinaf Dispensary'), ('10481', 'Karangatha Health Centre'), ('10482', 'Karangi Dispensary'), ('10483', 'Karangia Health Clinic'), ('17377', 'Karanjee Medical Clinic'), ('12197', 'Karare Dispensary'), ('17810', 'Kararia Dispensary'), ('16174', 'Karathe Medical Clinic'), ('14802', 'Karati Dispensary'), ('10484', 'Karatina Catholic Dispensary'), ('10485', 'Karatina District Hospital'), ('10486', 'Karatina Home Based Care Dispensary'), ('18832', 'Karatina Maternity & Nursing Home'), ('10487', 'Karatina Medical Services'), ('19998', 'Karatina Model Health Centre'), ('10488', 'Karatina Nursing Home'), ('19707', 'Karatina University Dispensary'), ('10489', 'Karatu Health Centre'), ('12198', 'Karau Health Centre'), ('18425', 'Karbururi Dispensary'), ('14803', 'Karda Dispensary'), ('10490', 'Karemeno Dispensary'), ('13003', 'Karen Health Centre'), ('19714', 'Karen Hospital (Karatina)'), ('10491', 'Karen Hospital Annex'), ('15481', 'Karen Roses Dispensary'), ('12056', 'Kibwezi Health Care Clinic'), ('12063', 'Kibwezi Huruma Medical Clinic and Laboratory'), ('12291', 'Kibwezi Sub District Hospital'), ('11467', 'Kichaka Simba Dispensary'), ('14859', 'Kichwa Tembo Dispensary'), ('10579', 'Kids Alive Dispensary'), ('13031', 'Kie/Kapc'), ('12292', 'Kiegoi Dispensary'), ('18077', 'Kiembe Dispensary'), ('11468', 'Kiembeni Community'), ('18331', 'Kiembeni Medical Clinic'), ('12294', 'Kiengu Maternity and Nursing Home'), ('10580', 'Kieni Dispensary (Gatundu)'), ('12296', 'Kieni Kia Ndege Dispensary'), ('12295', 'Kieni Model Health Centre'), ('12297', 'Kiereni Dispensary'), ('12298', 'Kigaa Dispensary'), ('10581', 'Kiganjo Dispensary'), ('10582', 'Kiganjo Health Centre'), ('10583', 'Kiganjo Medical Care Clinic'), ('18878', 'Kiganjo Medical Centre'), ('10584', 'Kigetuini Dispensary'), ('11469', 'Kighombo Dispensary'), ('12299', 'Kigogo Dispensary'), ('10585', 'Kigongo Medical Clinic'), ('18570', 'Jordan Medical Clinic (Ruiru)'), ('12113', 'Josan Medical Clinic'), ('14599', '<NAME>'), ('20287', 'Joseph Memorial Medical Centre'), ('10379', 'Joshua Memorial Mbai Dispensary'), ('20450', 'Josiah Community Medical Centre'), ('16586', 'Joska Medical Care'), ('16227', 'Joska Medical Care Clinic'), ('10380', '<NAME>'), ('19814', 'Joskar CFW Clinic (Kibingiti)'), ('20208', '<NAME>'), ('19300', '<NAME>'), ('14600', '<NAME> Clinic'), ('19686', 'Jowabu Modern Med Lab'), ('17981', 'Jowama Medical Clinic'), ('17355', 'Jowhar Dispensary'), ('17329', '<NAME>ells Medical Clinic'), ('16874', '<NAME>'), ('19228', '<NAME>'), ('11440', 'Joy Medical Clinic (Changamwe)'), ('11441', 'Joy Medical Clinic (Mwatate)'), ('10381', 'Joy Medical Clinic (Thunguma)'), ('19952', 'Joy Medical Clinic Chuka'), ('10382', 'Joy Medical Services (Majengo)'), ('18594', 'Joy Nursing Home and Maternity'), ('10383', 'Joy Town Clinic'), ('12114', 'Joykim Nursing Home'), ('10384', 'Joyland Medical Clinic'), ('16760', 'Joytown Special School'), ('19398', 'Jozi Medical Centre'), ('10385', 'Jubilee Medical Clinic'), ('11442', 'Judy Medical Clinic'), ('12992', 'Juhudi Clinic'), ('12115', 'Juhudi Medical Clinic'), ('10386', 'Juja Farm Health Centre'), ('19318', 'Juja Road Hospital (Nairobi)'), ('14601', 'Juluk Dispensary'), ('16360', 'Jumia Medical Clinic'), ('17729', 'Junction Clinic'), ('16450', 'Junction Medical Clinic'), ('14602', 'June Mar Maternity and Medical Centre'), ('11444', 'Junju Dispensary'), ('18407', 'Just Meno Limited'), ('14603', 'Jusus Responds Clinic'), ('16843', 'Juzippos Health Care Clinic'), ('12116', 'K K Chogoria Clinic'), ('12117', 'K K Medical Clinic'), ('18872', 'K K Mwethe Diispensary'), ('13637', 'K- Met Clinic'), ('20184', 'Kaalem Dispensary'), ('14604', 'Kaaleng Dispensary'), ('12118', 'Kaani Dispensary'), ('18882', 'Kaanwa CFW Clinic'), ('18886', 'Kaanwa CFW Clinic'), ('12119', 'Kaanwa Dispensary'), ('20001', 'Kaapus Dispensary'), ('12120', 'Kaare Dispensary'), ('16854', 'Kaathari Dispensary (CDF)'), ('12121', 'Kabaa Dispensary'), ('14605', 'Kabalwat Dispensary'), ('14606', 'Kabarak Health Centre'), ('18823', 'Kabarak University Medical Centre'), ('10388', 'Kabare Health Centre'), ('14607', 'Kabarnet District Hospital'), ('17492', 'Kabarnet Faith Clinic'), ('14608', 'Kabarnet High School Dispensary'), ('17595', 'Kabarnet Womens'' Clinic'), ('14609', 'Kabartonjo District Hospital'), ('10389', 'Kabati Dispensary'), ('16677', 'Kabati Dispensary (Laikipia West)'), ('17449', 'Kabati Maternity Nursing Home'), ('17448', 'Kabati Medical Centre'), ('10391', 'Kabati Medical Clinic'), ('20070', 'Kabati Medicare Health Services Nursing Home'), ('14610', 'Kabatini Health Centre'), ('14611', 'Kabazi Health Centre'), ('18337', 'Kabebero AIPCA Dispensary'), ('17434', 'Kariobangi South Clinic'), ('13007', 'Kariokor Clinic'), ('10499', 'Kariti Dispensary'), ('10500', 'Kariua Dispensary'), ('10501', 'Kariumba Medical Clinic'), ('13008', 'Karma Dispensary'), ('17995', 'Karomo Medical Clinic'), ('16237', 'Karuguaru Dispensary'), ('10504', 'Karumandi Health Centre'), ('14804', 'Karuna Dispensary'), ('10505', 'Karundu Dispensary'), ('19769', 'Karundu Medical Clinic'), ('14805', 'Karunga Dispensary'), ('13656', 'Karungu Sub-District Hospital'), ('17533', 'Karuoth Dispensary'), ('10506', 'Karura (SDA) Dispensary'), ('16939', 'Karura Dispensary'), ('13009', 'Karura Health Centre (Kiambu Rd)'), ('10508', 'Karure Medical Clinic'), ('10507', 'Karuri Health Centre'), ('12203', 'Karurumo Rhtc'), ('15559', 'Karuturi Hospital'), ('12204', 'Kasaala Health Centre'), ('16855', 'Kasafari Dispensary (CDF)'), ('20353', 'Kasaka'), ('18768', 'Kasang''u Dispensary'), ('15910', 'Kaborom Dispensary'), ('14628', 'Kaboson Health Centre'), ('14629', 'Kaboswa Tea Dispensary'), ('15909', 'Kaboywo Dispensary'), ('16164', 'Kabras Action Group (KAG) Clinic'), ('15911', 'Kabuchai Health Centre'), ('12122', 'Kabuguri Dispensary'), ('15912', 'Kabula Dispensary'), ('14631', 'Kabulwo Dispensary'), ('14632', 'Kabunyeria Health Centre'), ('16480', 'Kabuodo Dispensary'), ('17531', 'Kabura Dispensary'), ('17766', 'Kabururu Dispensary'), ('10392', 'Kabuteti (AIC) Medical Clinic'), ('10393', 'Kabuti Clinic'), ('14633', 'Kabutii-Matiret Dispensary'), ('13639', 'Kabuto Dispensary'), ('17626', 'Kabwareng Dispensary'), ('14634', 'Kacheliba District Hospital'), ('14635', 'Kacheliba Mobile Clinic'), ('19070', 'Kacheliba South West Clinic'), ('14636', 'Kachoda Dispensary'), ('18876', 'Kachuth Dispensary'), ('18937', 'Kaciongo Medical Clinic'), ('12123', 'Kadafu Medical Clinic'), ('11445', 'Kadaina Community Dispensary'), ('13640', 'Kadem Tb & Leprosy Dispensary'), ('13641', 'Kadenge Ratuoro Health Centre'), ('11446', 'Kaderboy Medical Clinic (Old Town)'), ('16769', 'Kadhola Dispensary'), ('18696', 'Kadibo Youth Friendly VCT'), ('17648', 'Kadija Dispensary'), ('16283', 'Kadinda Health Centre'), ('16702', 'Kadokong Dispensary'), ('17186', 'Kadokony Dispensary'), ('17848', 'Kadvan Medical Clinic'), ('11447', 'Kadzinuni Dispensary'), ('17381', 'Kaelo Dispensary'), ('14637', 'Kaeris Dispensary'), ('18244', 'Kaewa Dispensary'), ('11448', 'Kafuduni Dispensary'), ('10394', 'Kagaa Dispensary'), ('14638', 'Kagai (PCEA) Dispensary'), ('12124', 'Kageni Med Clinic'), ('13642', 'Kageno Dispensary'), ('13643', 'Kager Dispensary'), ('10396', 'Kagere Dispensary'), ('10397', 'Kagicha Dispensary'), ('10398', 'Kagio Catholic Dispensary (Mary Immucate Catholic '), ('10399', 'Kagio Nursing Home (Kagio)'), ('19937', 'Kagio Nursing Home (Kerugoya)'), ('18227', 'Kagioini Catholic Dispensary'), ('12125', 'Kagoji Dispensary'), ('10400', 'Kagonye Dispensary'), ('11449', 'Kag-Sombo Medical Clinic'), ('19778', 'Kagumo Boys High School Clinic'), ('10401', 'Kagumo College Dispensary'), ('10402', 'Kagumo Health Centre'), ('10403', 'Kagumo Live Giving Dispensary/Laboratory'), ('10404', 'Kagumo Maternity'), ('19775', 'Kagumo Teachers College Dispensary'), ('10405', 'Kagumoini Dispensary (Muranga North)'), ('10406', 'Kagumoini Dispensary (Muranga South)'), ('16971', 'Kagunduini Dispensary'), ('10408', 'Kagunduini Medical Clinic (Nyeri South)'), ('10410', 'Kaguthi Dispensary'), ('13644', 'Kagwa Health Centre'), ('10411', 'Kagwathi (SDA) Dispensary'), ('10412', 'Kagwe Catholic Dispensary'), ('10413', 'Kagwe Dispensary'), ('10415', 'Kagwe Health Services Clinic'), ('18358', 'Kahaaro Dispensary'), ('19774', 'Kahaaro Medical Clinic'), ('11450', 'Kahada Medical Clinic'), ('10416', 'Kahara Medical Clinic'), ('10417', 'Kaharo Dispensary'), ('10418', 'Kahatia Medical Clinic'), ('13645', 'Kahawa Dispensary'), ('12996', 'Kahawa Garrison Health Centre'), ('17948', 'Kasarani Claycity Medical Centre (Kasarani)'), ('19740', 'Kasarani Dispensary'), ('13010', 'Kasarani Health Centre'), ('13011', 'Kasarani Maternity'), ('14806', 'Kasarani Medical Clinic'), ('18545', 'Kasarani Medical Clinic Wote'), ('13012', 'Kasarani Medical Health Centre'), ('20081', 'Kasarani VCT'), ('14807', 'Kasei Dispensary'), ('12206', 'Kaseve Medical Clinic'), ('16928', 'Kasevi Dispensary'), ('20153', 'Kasewe Dispensary'), ('20352', 'Kasha Dispensary'), ('14808', 'Kasheen Dispenasry'), ('14809', 'Kasiela Dispensary'), ('11455', 'Kasigau Rdch'), ('12207', 'Kasikeu Catholic Health Centre'), ('12208', 'Kasikeu Dispensary '), ('20465', 'Kasilangwa dispensary'), ('12209', 'Kasilili Medical Clinic'), ('18158', 'Kasimba Medical Clinic'), ('14810', 'Kasisit Dispensary'), ('14811', 'Kasitet Dispensary'), ('14812', 'Kasok Dispensary'), ('18908', 'Kasolina Medical Clinic'), ('16282', 'Kasongo Dispensary'), ('10430', 'Kairi Medical Clinic'), ('10431', 'Kairini Dispensary'), ('10432', 'Kairo Dispensary'), ('10433', 'Kairo Medical Clinic'), ('12128', 'Kairungu Dispensary (Kyuso)'), ('12129', 'Kairungu Dispensary (Mwingi)'), ('12130', 'Kairuri Health Centre'), ('10434', 'Kairuthi Dispensary'), ('14646', 'Kaisagat Dispensary'), ('14647', 'Kaisugu Dispensary'), ('17477', 'Kaitese Dispensary'), ('16225', 'Kaithe Medical Clinic'), ('16587', 'Kaithe Stage Medcare'), ('16224', 'Kaithe Stage Medcare Clinic'), ('14649', 'Kaitui Dispensary'), ('10435', 'Kaiyaba Dispensary'), ('17695', 'Kajabdar Medical Clinic'), ('14650', 'Kajiado (AIC) Dispensary'), ('14651', 'Kajiado Christian Medical Centre'), ('14652', 'Kajiado District Hospital'), ('12131', 'Kajiampau Dispensary'), ('13646', 'Kajieyi Dispensary'), ('11451', 'Kajire Dispensary'), ('12132', 'Kajuki Health Centre'), ('13647', 'Kajulu/Gita Dispensary'), ('18928', 'Kaka Health Clinic'), ('19541', 'Kaka Medical Centre (Race Course Rd)'), ('15844', 'Kakamega Central Nursing Home'), ('15914', 'Kakamega Forest Dispensary'), ('18101', 'Kakamega Police Line VCT'), ('15915', 'Kakamega Provincial General Hospital (PGH)'), ('18100', 'Kakamega VCT Centre (Stand Alone)'), ('12134', 'Kakeani Dispensary'), ('17961', 'Kaki Family Medical Clinic'), ('14653', 'Kakiptui Dispensary'), ('12135', 'Kako Dispensary'), ('11452', 'Kakoneni Dispensary'), ('20222', 'Kakong Dispensary'), ('12136', 'Kakongo Dispensary'), ('19925', 'Kakuku Dispensary'), ('12137', 'Kakululo Dispensary'), ('14654', 'Kakuma Medical Clinic'), ('14655', 'Kakuma Mission Hospital'), ('12138', 'Kakungu Dispensary'), ('17268', 'Kakutha Dispensary'), ('12139', 'Kakuuni Dispensary'), ('11453', 'Kakuyuni Dispensary (Malindi)'), ('17888', 'Kakuyuni Facility'), ('16433', 'Kakuyuni Health Centre'), ('10437', 'Kakuzi Limited Dispensary'), ('14656', 'Kakwanyang Dispensary'), ('14657', 'Kalaacha Dispensary'), ('17100', 'Kalabata Dispensary'), ('12141', 'Kalacha (AIC) Dispensary'), ('12142', 'Kalacha Dispensary (Chalbi)'), ('18855', 'Kalacha Model Health Centre (Chalbi)'), ('12143', 'Kalala Dispensary'), ('14659', 'Kalalu Dispensary'), ('12144', 'Kalama Dispensary'), ('17602', 'Kalambani Dispensary'), ('17089', 'Kalamene Dispensary'), ('12146', 'Kalandini Health Centre'), ('16654', 'Kalanga Dispensary'), ('16726', 'Kalapata Dispensary'), ('16862', 'Kalatine Dispensary'), ('12147', 'Kalawa Health Centre'), ('20365', 'Kalemrekai Dispensary'), ('14660', 'Kalemungorok Dispensary'), ('20356', 'Kalemung''orok Dispensary'), ('12148', 'Kalewa Dispensary'), ('12149', 'Kali Dispensary'), ('18079', 'Kaliakakya Dispensary'), ('12150', 'Kaliani Health Centre'), ('17030', 'Kalicha Dispensary'), ('16643', 'Kalii Dispensary'), ('12151', 'Kaliku Dispensary'), ('17219', 'Kasphat Dispensary'), ('10509', 'Kasuku Health Centre'), ('12210', 'Kasunguni Dispensary'), ('14813', 'Kasuroi Dispensary'), ('12211', 'Kasyala Dispensary'), ('14814', 'Kataboi Dispensary'), ('12212', 'Katagini Dispensary'), ('12213', 'Katakani Dispensary'), ('12214', 'Katalwa Dispensary'), ('12215', 'Katangi Health Centre'), ('19196', 'Katangi Medical Clinic'), ('12216', 'Katangi Mission Health Centre'), ('12217', 'Katani Dispensary'), ('14815', 'Kataret Dispensary'), ('17668', 'Kate Dispensary'), ('14816', 'Katee Dispensary'), ('12218', 'Katethya Medical Clinic'), ('17616', 'Kathaana Dispensary'), ('12220', 'Kathama Dispensary'), ('12221', 'Kathande Medical Clinic'), ('12222', 'Kathangacini Dispensary'), ('19227', 'Kathangari CFW Clinic'), ('12223', 'Kathangari Dispensary'), ('12224', 'Kathangariri (ACK) Clinic'), ('12225', 'Kathangariri Dispensary'), ('12226', 'Kathanje Dispensary'), ('12227', 'Kathanjuri Dispensary'), ('10325', 'Hope Medical Clinic (Kirinyaga)'), ('18994', 'Hope Medical Clinic (Loitokitok)'), ('17869', 'Hope Medical Clinic (Mariakani)'), ('16686', 'Hope Medical Clinic (Nakuru)'), ('10327', 'Hope Medical Clinic (Nyeri North)'), ('19649', 'Hope Medical Clinic Yatta'), ('19128', 'Hope Medical Laboratory'), ('16724', 'Hope Nursing Home'), ('19114', 'Hope World Wide'), ('19890', 'Hope World Wide (Makindu)'), ('17684', 'Hope World Wide Kenya Mukuru Clinic'), ('18875', 'Hope World Wide Nakuru'), ('18493', 'Hope Worldwide Htc Centre'), ('18543', 'Hope Worldwide Kenya VCT (Makadara)'), ('19373', 'Horeb Medical Clinic ( Hunters)'), ('11415', 'Horesha Medicalicare'), ('19643', 'Horseet Medical Clinic'), ('16517', 'Hosana Medical Clinic'), ('16352', 'Hospice Dispensary'), ('18720', 'House of Hope Medical Centre'), ('17897', 'Howdil Aday Clinic'), ('20063', 'Hoymas VCT (Nairobi)'), ('13610', 'Huduma Clinic'), ('17393', 'Huduma Health Centre'), ('16575', 'Huduma Medical Clinic'), ('18675', 'Huhoini Dispensary'), ('16205', 'Hulahula Dispensary'), ('13365', 'Hulugho Sub-District Hospital'), ('19823', 'Humanity Medical Clinic (Kir South)'), ('19845', 'Humanity Medical Clinic (Kir West)'), ('16793', 'Hungai Dispensary'), ('19302', 'Hunters Medical Clinic'), ('12061', 'Hurri-Hills Dispensary'), ('12973', 'Huruma (EDARP)'), ('12972', 'Huruma (NCCK) Dispensary'), ('12062', 'Huruma Clinic (Embu)'), ('14552', 'Huruma Dispensary'), ('14555', 'Huruma District Hospital'), ('14553', 'Huruma Health Centre (Laikipia East)'), ('12974', 'Huruma Lions Dispensary'), ('12975', 'Huruma Maternity Hospital'), ('16576', 'Huruma Medical Centre'), ('18736', 'Huruma Medical Clinc'), ('17580', 'Huruma Medical Clinic'), ('18297', 'Huruma Medical Clinic (Bamba)'), ('19255', 'Huruma Medical Clinic (Changamwe)'), ('10329', 'Huruma Medical Clinic (Gatundu)'), ('12065', 'Huruma Medical Clinic (Kangundo)'), ('17879', 'Huruma Medical Clinic (Kanja)'), ('17898', 'Huruma Medical Clinic (Moyale)'), ('14554', 'Huruma Mobile Clinic'), ('12976', 'Huruma Nursing Home & Maternity'), ('19310', 'Huruma St Jude''s Community Health Services'), ('19983', 'Hylax Clinic (Masaba North)'), ('18201', 'I Choose Life Africa'), ('12979', 'I R Iran Medical Clinic'), ('13611', 'Ibacho Sub-District Hospital'), ('13612', 'Ibeno Sub-District Hospital'), ('11417', 'Ibnusina Clinic'), ('13366', 'Ibnu-Sina Medical Clinic'), ('18808', 'Ibrahim Ure Dispensary'), ('10331', 'Ichagachiru Dispensary'), ('10332', 'Ichagaki (Mission) Health Centre'), ('10333', 'Ichamara Dispensary'), ('10334', 'Ichamara Medical Clinic'), ('10335', 'Ichichi Dispensary'), ('12067', 'Ichomba Clinic'), ('18023', 'Ichuga Medical Clinic'), ('20376', 'ICRH-DROP-IN-CENTRE Ukunda'), ('14556', 'Icross Dispensary'), ('16577', 'Ideal Health Laboratory'), ('16578', 'Ideal Medical /Fp Clinic'), ('20211', 'Ideal Medical Clinic'), ('12068', 'Ideal Medical Clinic (Kangundo)'), ('10336', 'Ideal Medical Clinic (Nyeri North)'), ('20145', 'IDEWES'), ('12980', 'IDF Mathare Dispensary'), ('11418', 'Idsowe Dispensary'), ('15896', 'Iduku Dispensary'), ('19312', 'Kam ENT Services'), ('19313', 'Kam Health Services'), ('17660', 'Kama Medical Clinic'), ('12158', 'Kamacabi Dispensary'), ('10439', 'Kamacharia Clinic'), ('19727', 'Kamacharia Dispensary'), ('10440', 'Kamae Forest Dispensary'), ('17407', 'Kamae Medical Clinic'), ('20419', 'Kamaembe Dispensary'), ('13649', 'Kamagambo Dispenasry'), ('14666', 'Kamaget Dispensary'), ('14667', 'Kamaget Dispensary (Trans Mara)'), ('16239', 'Kamaguna Dispensary'), ('17212', 'Kamahindu (AIC) Medical Centre'), ('10441', 'Kamahuha Dispensary'), ('12159', 'Kamaindi Dispensary'), ('10442', 'Kamakwa Medical Clinic'), ('12160', 'Kamandio Dispensary'), ('16331', 'Kamangunet VCT'), ('12161', 'Kamanyaki Dispensary'), ('18513', 'Kamanyi Dispensary'), ('17098', 'Kamar Dispensary'), ('14668', 'Kamara Dispensary'), ('18775', 'Kamarandi Dispensary'), ('14669', 'Kamasai Dispensary'), ('17209', 'Kamasega Dispensary'), ('10342', 'Ihwa Medical Clinic'), ('10343', 'Ihwagi Medical Clinic'), ('12073', 'Iiani Catholic Dispensary'), ('12072', 'Iiani Dispensary'), ('17918', 'Iiani Dispensary (Kibwezi)'), ('12074', 'Iiani/Kiatineni Dispensary'), ('13406', 'Ijara District Hospital - Masalani'), ('13370', 'Ijara Health Centre'), ('12075', 'Ikaatini Dispensary'), ('16649', 'Ikalaasa Dispensary'), ('16958', 'Ikalyoni Dispensary'), ('12077', 'Ikanga Sub-District Hospital'), ('13615', 'Ikerege Clinic'), ('13616', 'Ikobe Health Centre(Manga)'), ('12078', 'Ikombe Disp'), ('13617', 'Ikonge Dispensary'), ('17165', 'Ikonzo Dispensary'), ('10344', 'Ikumbi Clinic'), ('14559', 'Ikumbi Health Centre'), ('12079', 'Ikumbo Dispensary'), ('12080', 'Ikutha Health Centre'), ('17610', 'Ikutha Medical Clinic'), ('18883', 'Ikuu CFW Clinic'), ('12081', 'Ikuu Dispensary'), ('12082', 'Ikuyuni Dispensary'), ('16717', 'Ikuywa Dispensary'), ('14562', 'Ilaiser Dispensary'), ('12083', 'Ilalambyu Dispensary'), ('17337', 'Ilan Dispensary'), ('19976', 'Ilatu Dispensary (Makindu)'), ('19269', 'Ilbissil Medical Clinic'), ('20161', 'Ilbrah Counseling Centre'), ('17053', 'Ilchalai Dispensary'), ('15900', 'Ileho Health Centre'), ('12084', 'Ilengi Dispensary'), ('12085', 'Ilika Dispensary'), ('14563', 'Ilkerin Dispensary (Narok South)'), ('14564', 'Ilkerin Dispensary (Trans Mara)'), ('14565', 'Ilkilinyet Dispensary'), ('19676', 'Ilkilorit Dispeensary'), ('17750', 'Ilkiremisho Dispensary'), ('20372', 'Illasit Dispensary'), ('14567', 'Illasit Medical Clinic'), ('12086', 'Illaut Dispensary'), ('12087', 'Illeret Health Centre (North Horr)'), ('18251', 'Illikeek Oodupa Clinic'), ('14568', 'Illinga''rua Dispensary'), ('19724', 'Ilparakuo Dispensary'), ('14561', 'Ilpolei Dispensary'), ('15041', 'Ilpolosat Dispensary'), ('14569', 'Iltilal Health Centre'), ('14570', 'Ilula Dispensary'), ('18586', 'Iluvya'), ('16484', 'Imalaba Dispensary'), ('18941', 'Imanga Health Centre'), ('16142', 'Imani Clinic'), ('16357', 'Imani Dispensary'), ('12088', 'Imani Health Care (Machakos)'), ('19469', 'Imani Health Servises'), ('18177', 'Imani Hospital'), ('19402', 'Imani Medical Centre'), ('17669', 'Imani Medical Centre (Athi River)'), ('16579', 'Imani Medical Clinic'), ('19286', 'Imani Medical Clinic ( Mathare A 4)'), ('10345', 'Imani Medical Clinic (Kiambu West)'), ('10347', 'Imani Medical Clinic (Muranga North)'), ('19808', 'Imani Medical Clinic (Nyandarua)'), ('10348', 'Imani Medical Clinic (Nyeri South)'), ('16752', 'Imani Medical Clinic (Ruiru)'), ('19193', 'Imani Medical Clinic Yatta'), ('17885', 'Imani Medical Services'), ('12089', 'Imani Yako Medical Clinic'), ('18294', 'Imani Yako Medical Clinic (Joska)'), ('17685', 'Imara Health Centre'), ('12981', 'Imara Medical Clinic'), ('19327', 'Imarba Dispensary'), ('15901', 'Imbiakalo Dispensary'), ('19108', 'Imbirikani Dispensary'), ('13650', 'Kamasengere Dispensary'), ('18802', 'Kamashia'), ('14670', 'Kamasia Health Centre'), ('20223', 'Kamasielo Dispensary'), ('14671', 'Kamawoi Dispensary'), ('13651', 'Kambajo Dispensary'), ('12162', 'Kambandi Dispensary'), ('17527', 'Kambare Dispensary'), ('16192', 'Kambe Dispensary'), ('17026', 'Kambe Kikomani Medical Clinic'), ('16745', 'Kambi Garba Dispensary'), ('16219', 'Kambi Ya Juu Catholic Dispensary (Isiolo)'), ('16962', 'Kambimawe Dispensary'), ('20392', 'Kambini Dispensary'), ('15916', 'Kambiri Health Centre'), ('10443', 'Kambirwa Health Centre'), ('10445', 'Kambiti Health Centre'), ('16216', 'Kamboe Dispensary'), ('17290', 'Kamboo Dispensary'), ('11962', 'Kambu Catholic Dispensary'), ('12090', 'Kambu Integrated Health Clinic'), ('18596', 'Kambu Model Health Centre'), ('10446', 'Kambui (PCEA) Dispensary'), ('10447', 'Kamburaini Dispensary'), ('10448', 'Kamburu (PCEA) Dispensary'), ('18002', 'Innoculation Centre'), ('17585', 'Integrated Development Fund (IDF) VCT'), ('17846', 'International Medical Corps Mobile VCT (Mbita)'), ('20408', 'International Medical Corps Tekelza DiCE Kisii'), ('14576', 'Intrepids Dispensary'), ('13618', 'Inuka Hospital & Maternity Home'), ('20097', 'Inuka Nursing Home'), ('15903', 'Inyali Dispensary'), ('12091', 'Inyuu Dispensary'), ('20158', 'IOM International Organization for migration(girigiri)'), ('19471', 'Iom Wellness Clinic'), ('15904', 'Ipali Health Centre'), ('14577', 'Ipcc Kaimosi Dispensary'), ('19459', 'Iqlas Medical Clinic'), ('19408', 'Iqra Medical Centre'), ('19915', 'Iqra Medical Centre and Nursing Home'), ('14578', 'Iraa Dispensary'), ('13619', 'Iraha Dispensary'), ('20227', 'Iran Medical Clinic'), ('19421', 'Iran Medical Clinic (Ngara)'), ('13620', 'Iranda Health Centre'), ('14579', 'Irc Kakuma Hospital'), ('11953', 'Iresaboru Dispensary'), ('13372', 'Iresteno Dispensary'), ('10352', 'Iriaini Medical Clinic'), ('12092', 'Iriga Dispensary'), ('10353', 'Irigiro Dispensary'), ('13621', 'Irondi Dispensary'), ('10354', 'Iruri Dispensary'), ('14580', 'Irwaga Health Centre'), ('16425', 'Isamwera Dispensary'), ('13622', 'Isana Maternity and Nursing'), ('13623', 'Isecha Health Centre'), ('16464', 'Ishiara Sub-District Hospital'), ('13624', 'Isibania Mission Health Centre'), ('13625', 'Isibania Sub-District Hospital'), ('14581', 'Isinet Dispensary'), ('18993', 'Isinet Medical Clinic'), ('14582', 'Isinya Health Centre'), ('14583', 'Isinya Medical Care'), ('19348', 'Isinya Medical Clinic'), ('19293', 'Isiolo Central Medical Clinic'), ('12094', 'Isiolo District Hospital'), ('19410', 'Isiolo Medical Centre'), ('13373', 'Islamic Relief Agency'), ('10355', 'Island Farms Dispensary'), ('12066', 'Ismc Clinic'), ('13626', 'Isoge Health Centre'), ('18953', 'Isra Walmiraj Medical Clinic'), ('19991', 'Isumba Dispensary'), ('12095', 'Itabua Police Dispensary'), ('18512', 'Itando Mission of Hope and Health Centre'), ('18680', 'Itangani Dispensary'), ('10356', 'Itara Medical Clinic'), ('14584', 'Itare Dispensary'), ('14585', 'Itembe Dispensary'), ('16879', 'Itembu Dispensary'), ('14586', 'Iten District Hospital'), ('19936', 'Itendeu Dispensary'), ('20092', 'Itetani Dispensary'), ('12096', 'Ithaeni Dispensary'), ('10357', 'Ithanga Dispensary'), ('16747', 'Ithanga Medical Clinic'), ('17059', 'Ithangarari Dispensary'), ('10358', 'Ithare Medical Clinic'), ('10359', 'Ithe-Kahuno Medical Clinic'), ('16653', 'Itheng''eli Dispensary'), ('12097', 'Ithimbari Dispensary'), ('19934', 'Ithumbi Dispensary'), ('19762', 'Ithuthi Healthcare Unit'), ('10360', 'Itiati Dispensary'), ('19830', 'Itiati University Campus Dispensary'), ('13627', 'Itibo Eramani Dispensary'), ('13628', 'Itibo Mission Health Centre'), ('13629', 'Itierio Nursing Home'), ('14587', 'Itigo Dispensary'), ('18684', 'Itiko Dispensary'), ('16957', 'Itithini Dispensary'), ('12098', 'Itoleka Dispenasry'), ('12163', 'Kambusu Dispensary'), ('14672', 'Kamelil Dispensary (Tinderet)'), ('19209', 'Kamelilo Dispensary'), ('15917', 'Kamenjo Dispensary'), ('10449', 'Kamfas Clinic'), ('19488', 'Kamili Organization'), ('17201', 'Kamirithu Medical Clinic'), ('18942', 'Kamiti Maximum Clinic'), ('13000', 'Kamiti Prison Hospital'), ('16375', 'Kamketo Dispensary'), ('19189', 'Kamkomani Dispensary'), ('14673', 'Kamkong Tea Dispensary'), ('16372', 'Kamla Bamako Initiative Dispensary'), ('16371', 'Kamla Community Dispensary'), ('14674', 'Kamogo Health Centre'), ('14675', 'Kamoi Dispensary'), ('10450', 'Kamoko Health Centre'), ('17242', 'Kamolo Dispensary'), ('14676', 'Kamongil Dispensary'), ('17234', 'Kamorow Dispensary'), ('14677', 'Kampi Samaki Health Centre'), ('17261', 'Kamuchege Dispensary'), ('20219', 'Kamuge Dispensary'), ('18577', 'Kamujohn Medical Clinic'), ('19654', 'Kamukunji District Health Management Team Offices'), ('15918', 'Kamukuywa (ACK) Dispensary'), ('18346', 'Kamukuywa Dispensary'), ('13568', 'Geteri Dispensary'), ('20102', 'Gethsemane Garden Mission Hospital'), ('16281', 'Getiesi Health Centre'), ('13569', 'Getongoroma Dispensary'), ('13570', 'Getongoroma Health Centre'), ('13571', 'Getontira Clinic'), ('12035', 'Getrude Dispensary'), ('12952', '<NAME> Clinic'), ('18395', 'Getrude Embakasi Clinic'), ('12953', 'Getrudes Hospital (Nairobi West Clinic)'), ('18969', 'Geva Family Health Services'), ('11390', 'Ghazi Dispensary'), ('10246', 'Giachuki Medical Clinic'), ('10247', 'Giakaibei Catholic Dispensary'), ('16223', 'Giaki Clinic'), ('12036', 'Giaki Sub-District Hospital'), ('13572', 'Gianchore Health Centre'), ('12037', 'Gianchuku Dispensary'), ('10248', 'Giathanini Dispensary'), ('13573', 'Giatunda Dispensary'), ('17421', 'Giatutu Dispensary'), ('20259', 'Gibea Medical Centre'), ('17365', 'Gichagini Dispensary'), ('16799', 'Gichago Dispensary'), ('12038', 'Gichiche Dispensary'), ('10249', 'Gichiche Health Centre'), ('10250', 'Gichiche Medical Clinic'), ('10251', 'Gichira Health Centre'), ('16400', 'Gichobo Dispensary'), ('10252', 'Gichuru Dispensary'), ('13574', 'Gietai (AIC) Dispensary'), ('11391', 'Gift Medical Clinic'), ('17645', 'Giithu Dispensary'), ('10253', 'Gikoe Dispensary'), ('10254', 'Gikoe Medical Clinic'), ('16171', 'Gikono Dispensary'), ('10256', 'Gikui Health Centre'), ('16853', 'Gikuuri Dispensary (CDF)'), ('17960', 'Gil Medical Clinic'), ('14508', 'Gilgil Astu Dispensary'), ('14509', 'Gilgil Community Medical Clinic'), ('14511', 'Gilgil Military Regional Hospital'), ('14510', 'Gilgil Sub-District Hospital'), ('19916', 'Gionsaria Health Centre (Nyamache)'), ('12955', 'Giovanna Dispensary'), ('13575', 'Girango Dispensary'), ('11392', 'Giriama Mission Dispensary'), ('13576', 'Giribe Dispensary'), ('16665', 'Girigiri Dispensary'), ('13348', 'Girissa Dispensary'), ('13577', 'Gisage Dispensary'), ('19538', 'Gitanga Medical Centre'), ('17843', 'Gitaraka Dispensary'), ('12039', 'Gitare Dispensary (Embu)'), ('10257', 'Gitare Health Centre (Gatundu)'), ('10258', 'Gitaro Dispensary'), ('12040', 'Gitaru Clinic'), ('10259', 'Gitata Medical Clinic'), ('17659', 'Gitathi Dispensary'), ('10260', 'Gitaus Medical Clinic'), ('19804', 'Githabai Medical Clinic'), ('10261', 'Githagara Health Centre'), ('17253', 'Githambo Dispensary'), ('10262', 'Githanga (ACK) Dispensary'), ('13349', 'Gither Dispensary'), ('10263', 'Githiga Health Centre'), ('10264', 'Githiga Midways Clinic'), ('17401', 'Githiga Private Medical Clinic'); INSERT INTO `facility_list` (`Facility_Code`, `Facility_Name`) VALUES ('19968', 'Githima Dispensary'), ('17424', 'Githima Medical Clinic'), ('16394', 'Githiriga Dispensary'), ('10265', 'Githirioni Dispensary'), ('18887', 'Githogoro Runda Baptist Clinic (Getrudes Nairobi)'), ('12041', 'Githongo District Hospital'), ('10266', 'Githuani (ACK) Dispensary'), ('10267', 'Githumu Hospital'), ('10268', 'Githunguri Dispensary'), ('14588', 'Jagoror Dispensary'), ('10364', 'Jaima Clinic'), ('13632', 'Jalaram Nursing Home'), ('13374', 'Jalish Dispensary'), ('18758', 'Jalsonga Medical Clinic'), ('10366', 'Jamaica Medical Clinic'), ('11424', 'Jambo Clinic'), ('11425', 'Jambo Medical Clinic'), ('12106', 'Jambu Medical Clinic'), ('10367', 'James Clinic and Lab Services'), ('11426', 'Jamhuri Medical Clinic'), ('18475', 'Jamia Islamic Intergrated'), ('17366', 'Jamia Med Clinic'), ('15906', 'Jamia Medical Centre'), ('17618', 'Jamia Mosque Dispensary'), ('12107', 'Jamii Afya Clinic'), ('11427', 'Jamii Clinic (Lamu)'), ('12985', 'Jamii Clinic (Westlands)'), ('14590', 'Jamii Clinical Services'), ('14115', 'Jamii Clinical Services Clinic'), ('11429', 'Jamii Health Care Clinic (Kisauni)'), ('15907', 'Jamii Health Services Medical Clinic'), ('10368', 'Jamii Hospital'), ('17265', 'Jamii Med Clinic'), ('19786', 'Jamii Medical Clinic'), ('19818', 'Jamii Medical Clinic'), ('17408', 'Gitura Dispensary'), ('17423', 'Gitura Dispensary-Kenol'), ('18962', 'Gituuru Dispensary'), ('14512', 'Gitwamba Health Centre'), ('10284', 'Gitwe Medical Clinic'), ('17182', 'Givole Dispensary'), ('15889', 'Givudimbuli Health Centre'), ('19593', 'Giwa Health Services'), ('14514', 'GK Farm Prisons Dispensary (Trans Nzoia)'), ('14516', 'GK Prison Annex Dispensary (Naivasha)'), ('18308', 'GK Prison Clinic'), ('10189', 'GK Prison Dispensary'), ('15890', 'GK Prison Dispensary ( Bungoma South)'), ('14517', 'GK Prison Dispensary (Athi River)'), ('12045', 'GK Prison Dispensary (Embu)'), ('13350', 'GK Prison Dispensary (Garissa)'), ('10285', 'GK Prison Dispensary (Gathigiriri )'), ('13578', 'GK Prison Dispensary (Homa Bay)'), ('12046', 'GK Prison Dispensary (Isiolo)'), ('10286', 'GK Prison Dispensary (Kingongo)'), ('12047', 'GK Prison Dispensary (Kitui)'), ('12048', 'GK Prison Dispensary (Machakos)'), ('11394', 'GK Prison Dispensary (Malindi)'), ('12049', 'GK Prison Dispensary (Meru)'), ('17728', 'GK Prison Dispensary (Migori)'), ('10287', 'GK Prison Dispensary (Murang''a)'), ('14518', 'GK Prison Dispensary (Nandi Central)'), ('10288', 'GK Prison Dispensary (Ruiru)'), ('20255', 'GK Prison Mbale'), ('11396', 'GK Prisons Clinic (Malindi)'), ('14523', 'GK Prisons Dispensary'), ('15891', 'GK Prisons Dispensary (Busia)'), ('14519', 'GK Prisons Dispensary (Eldoret East)'), ('15892', 'GK Prisons Dispensary (Kakamega Central)'), ('14520', 'GK Prisons Dispensary (Kapenguria)'), ('14521', 'GK Prisons Dispensary (Kericho)'), ('10290', 'GK Prisons Dispensary (Kiambu)'), ('13579', 'GK Prisons Dispensary (Kibos)'), ('13580', 'GK Prisons Dispensary (Kisii)'), ('14522', 'GK Prisons Dispensary (Laikipia East)'), ('14524', 'GK Prisons Dispensary (Ngeria)'), ('11398', 'GK Prisons Dispensary (Tana River)'), ('14527', 'GK Prisons Dispensary (Turkana Central)'), ('18616', 'GK Prisons Medium Dispensary'), ('14528', 'GK Remand Prisons Dispensary (Trans Nzoia West)'), ('17972', 'Glaisa Medical Clinic'), ('19927', 'Global Providers International Clinic'), ('14529', 'Gloria Health Services'), ('18613', 'Glory Health Clinic'), ('10291', 'Glory Medical Clinic'), ('10370', 'Jamii Medical Clinic (Gatundu)'), ('19819', 'Jamii Medical Clinic (Kirinyaga North)'), ('16193', 'Jamii Medical Clinic (Malindi)'), ('16585', 'Jamii Medical Clinic (Meru)'), ('10371', 'Jamii Medical Clinic (Muranga North)'), ('12108', 'Jamii Medical Clinic (Mwala)'), ('14591', 'Jamii Medical Clinic (Namanga)'), ('19232', 'Jamii Medical Clinic Masimba'), ('19446', 'Jamii Medical Clinic Mukuru'), ('18926', 'Jamii Medical Clinic Vihiga'), ('12986', 'Jamii Medical Hospital'), ('13375', 'Jamii Nursing Home'), ('19433', 'Jamii Yadah Medical Centre'), ('14592', 'Jamji Dispensary'), ('10372', 'Jamwa Medical Clinic'), ('13376', 'Jarajara Dispensary'), ('13377', 'Jaribu Medical Clinic'), ('11430', 'Jaribuni Dispensary'), ('16448', 'Jasho Medical Clinic '), ('13633', 'Jawabu (Community) Medical Clinic'), ('14593', 'Jawabu Medical Clinic'), ('19156', 'Jeddah Nursing Home and Medical Centre'), ('19170', 'Jeddah Pharmacy'), ('20064', 'Jeffrey Medical & Diagnostic Centre'), ('10373', 'Jehova Jireh Clinic'), ('18825', 'Jehova Rapha Clinic'), ('16546', 'Gombato Dispensary (CDF)'), ('13587', 'Gongo Dispensary'), ('17516', 'Gongo Health Centre'), ('11401', 'Gongoni Health Centre'), ('11402', 'Gongoni Medical Clinic'), ('14530', 'Good Health Clinic Ngong'), ('10293', 'Good Health Medical Clinic'), ('16847', 'Good Hope Clinic'), ('10294', 'Good Hope Hospital'), ('10295', 'Good Hope Medical Clinic'), ('19619', 'Good Neighbours Medical Clinic (Dandora)'), ('10296', 'Good Samaritan (ACK) Medical Clinic'), ('12959', 'Good Samaritan Dispensary'), ('10297', 'Good Samaritan Health Services (Kirinyaga)'), ('19913', 'Good Samaritan Medical Centre'), ('17747', 'Good Shepherd Ang''iya'), ('12960', 'Good Shepherd Dispensary'), ('10298', 'Good Shepherd Medical Clinic (Nyeri North)'), ('10299', 'Good Shepherd Medical Clinic (Nyeri South)'), ('18975', 'Good Shephered Medical Clinic'), ('12052', 'Good Will Medical Clinic'), ('10300', 'Goodwill Clinic'), ('17836', 'Goodwill Medical Clinic'), ('14531', 'Gorgor Dispensary'), ('12053', 'Goro Rukesa Dispensary'), ('11403', 'Gorofani Medical Clinic'), ('14532', 'Goseta Dispensary'), ('14533', 'Gosheni Medical Clinic'), ('13588', 'Got Agulu Sub-District Hospital'), ('19928', 'Got Kachola Dispensary'), ('18874', 'Got Kamondi Dispensary'), ('13589', 'Got Kojowi Health Centre'), ('13590', 'Got Matar Dispensary'), ('13591', 'Got Nyabondo Dispensary'), ('18321', 'Got Osimbo Dispensary'), ('13592', 'Got Oyaro Dispensary'), ('17520', 'Got Regea Dispensary'), ('11404', 'Gotani Dispensary'), ('13593', 'Gotichaki Dispensary'), ('10717', 'Grace Baricho Clinic'), ('17070', 'Grace Medical Care Centre'), ('14534', 'Grace Medical Centre'), ('18489', 'Grace Medical Clinic'), ('18288', 'Grace Medical Clinic (Imenti South)'), ('18317', 'Gracious Day Medical Clinic'), ('10301', 'Gracious M Clinic'), ('14535', 'Grand Avens Clinic'), ('14536', 'Grassland Dispensary'), ('20305', 'Grazia Medical Clinic'), ('14537', 'Great Comm Medical Clinic'), ('19528', 'Green Croos Medical and Dental Clinic'), ('19895', 'Green Cross Medical Clinic'), ('10303', 'Green Hill Medical Clinic'), ('14594', 'Jehova Rapha Medical Clinic'), ('19969', 'Jehovah Shalom Medical Clinic Lodwar'), ('18560', 'Jeikei Medical Clinic'), ('10374', 'Jekam Medical Clinic'), ('19490', 'Jellin Medical Clinic'), ('20274', 'Jeluto Medical Clinic'), ('14595', 'Jemunada Dispensary'), ('18765', 'Jena Medical Clinic'), ('16453', 'Jepkoyai Dispensary'), ('13634', 'Jera Dispensary'), ('12987', 'Jerapha Maternity'), ('12988', 'Jericho Health Centre'), ('11431', 'Jericho Medical Clinic'), ('12989', '<NAME>'), ('17295', 'Jesmah CFW Clinic'), ('10375', 'Jesmond (ACK) Dispensary (Mburi)'), ('19669', '<NAME>'), ('19548', 'Jesus Is Alive Dental Clinic (Nairobi)'), ('15908', 'Jesus The Healer Clinic'), ('12109', '<NAME>'), ('13635', '<NAME>'), ('18672', 'Jeytee'), ('14596', 'JFK Engineering Disp'), ('14597', 'JFK Ii Dispensary'), ('11432', 'Jibana Sub District Hospital'), ('20121', 'Jilango Dispensary'), ('17354', 'Hargal Dispensary'), ('19908', 'Harmony Medical Clinic'), ('17078', 'Haroresa'), ('19755', '<NAME>'), ('20178', 'Havillan Medical Center'), ('13600', 'Hawinga Health Centre'), ('19566', 'Hazina Medical Clinic'), ('17008', 'Health Bridge Medical Clinic'), ('19497', 'Health Care Services'), ('14543', 'Health For All (ACK) Clinic'), ('19582', 'Health Matters Medical Centre'), ('13601', 'Health Mountain Hospital'), ('19597', 'Health Source Medical Centre'), ('10310', 'Healthscope Clinic (Muranga North)'), ('14544', 'Healthway Medical Clinic'), ('18278', 'Healthways Medical Centre'), ('19824', 'Hebron CFW Clinic'), ('19813', 'Hebron CFW Clinic (Kutus)'), ('12057', 'Heillu Dispensary'), ('14545', 'Hekima Dispensary'), ('20093', 'Hekima HTC Center'), ('11408', 'Hekima Medical Clinic'), ('14546', 'Helmon Clinic'), ('20229', 'Helna Medical Clinic'), ('18373', 'Helpers of Mary Dispensary'), ('13602', 'Hema Clinic'), ('13603', 'Hema Hospital'), ('17674', 'Hema Medical Clinic'), ('10312', 'Heni Health Centre'), ('16884', 'Henzoro Medical Clinic'), ('16180', 'Heri Medical Centre'), ('19605', 'Heri Medical Cilinic Bombolulu'), ('19955', 'Heri Tana Medical Clinic'), ('17364', 'Heritage Medical Clinic'), ('10313', 'Heshima Clinic'), ('10314', 'Heshima Medical Clinic'), ('12058', 'Heshima Medical Clinic (Kangundo)'), ('14547', 'Heshima Medical Clinic (Nakuru North)'), ('19112', 'Heshima Medical Clinic-Masinga'), ('18445', 'Hessed Clinic Masiro'), ('10316', '<NAME>ora'), ('16522', 'Hidaya Medical Clinic'), ('19787', 'High Way Medical Clinic'), ('18844', 'Highrise Medical Services'), ('13363', 'Highway Clinic (Wajir East)'), ('15895', 'Highway Maternity and Nursing Home'), ('18022', 'Highway Mediacl Clinic (Nyeri North)'), ('12060', 'Highway Medical Clinic'), ('16708', 'Highway Medical Clinic (Bungoma East)'), ('10318', 'Highway Medical Clinic (Kirinyaga)'), ('16349', 'Emc Kimumu Dispensary'), ('17272', 'Emeroka Dispensary'), ('17184', 'Emesc Medical Clinic'), ('14446', 'Emining Health Centre'), ('19005', 'Emirates Medical Clinic'), ('14447', 'Emitik Dispensary'), ('18987', 'Emko Clinic'), ('17425', 'Emmah Medial Clinic'), ('17574', 'Emmanuel Community Health Clinic'), ('12005', '<NAME> (ACK) Dispensary'), ('10167', 'Emmanuel M/C VCT Centre'), ('18893', 'Emmanuel Medical Centre'), ('16707', 'Emmanuel Medical Clinic (Bungoma East)'), ('16743', 'Emmanuel Medical Clinic (Kangundo)'), ('10168', 'Emmanuel Medical Clinic (Nyeri North)'), ('14443', 'Emmaus Clinic'), ('10169', 'Emmaus Medical Clinic'), ('12936', 'Emmaus Nursing Home'), ('14448', 'Emotoroki Dispensary'), ('14444', 'Empough Dispensary'), ('14449', 'Emsea Dispensary'), ('20010', 'Emsos Dispensary'), ('15876', 'Emuhaya Sub District Hospital'), ('20039', 'Emukaba Dispensary'), ('15877', 'Emukaya Clinic'), ('14450', 'Emumwenyi Dispensary'), ('14451', 'Emurua Dikir Dispensary'), ('14452', 'Emurua Dikirr Dispensary'), ('16762', 'Emusanda Dispensary'), ('15878', 'Emusenjeli Dispensary'), ('16979', 'Emusire Health Centre'), ('12007', 'Ena Dispensary'), ('14453', 'Enabelbel Health Centre'), ('14454', 'Enaibor Ajijik Dispensary'), ('17519', 'Enanga Clinic'), ('19730', 'Endarasha Medical Clinic'), ('10170', 'Endarasha Rural Health Centre'), ('12008', 'Endau Dispensary'), ('14455', 'Endebess District Hospital'), ('12009', 'Endei Dispensary'), ('13544', 'Endiba Health Centre'), ('14456', 'Endo Health Centre'), ('14457', 'Endoinyo Erinka Dispensary'), ('17746', 'Endoinyo Narasha'), ('19360', 'Enego Dispensary'), ('17221', 'Enesampulai Dispensary'), ('14458', 'Engashura Health Centre'), ('10171', 'Engineer District Hospital'), ('17557', 'Engineer Medical Clinic'), ('17910', 'Engos Health Cente'), ('10172', 'Enkasiti Roses Farm Clinic'), ('14460', 'Enkirgir Dispensary'), ('14461', 'Enkirotet Medical Clinic'), ('15600', 'Enkitok Joy Nursing Home'), ('14462', 'Enkitoria Dispensary'), ('17813', 'Enkongu Narok Dispensary'), ('14463', 'Enkorika Health Centre'), ('17784', 'Enkutoto Dispensary'), ('14465', 'Enoosaen Health Centre'), ('14466', 'Enoosaen Zh Clinic'), ('14464', 'Enoosupukia Dispensary'), ('17730', 'Ensakia Dispensary'), ('13545', 'Entanda Dispensary'), ('16424', 'Entanke Dispensary'), ('14467', 'Entarara Health Centre'), ('17320', 'Entargeti Dispensary'), ('14479', 'Entasekera Health Centre'), ('14469', 'Entasopia Health Centre'), ('14470', 'Entiyani Dispensary'), ('14471', 'Entontol Dispensary'), ('17430', 'Enzai Afya Medical Clinic'), ('15879', 'Enzaro Health Centre'), ('12011', 'Enziu Dispensary'), ('17281', 'Epkee Dispensary'), ('20443', 'Equator Clinic'), ('19015', 'Highway Medical Clinic (Pokot Central)'), ('14548', 'Highway Medical Clinic (Trans Nzoia East)'), ('18134', 'Highway Medical Clinic (Wote)'), ('19876', 'Highway Medical Clinic Iten'), ('10718', 'Highway Medical Clinic Kibingoti'), ('18924', 'Highway Medical Clinic Maua'), ('19197', 'Highway Medical Clinic Yatta'), ('10319', 'Highway Medical Enterprises'), ('19949', 'Hilac Medical Clinic-Habaswein'), ('19877', 'Hillday Medical Clinic'), ('19383', 'Hillview Park Medical Clinic'), ('19008', 'Hilwa Pharmacy and Clinic'), ('11409', 'Hindi Magogoni Dispensary'), ('11410', 'Hindi Prison Dispensary'), ('13364', 'Hodhan Dispensary'), ('11411', 'Hola District Hospital'), ('18035', 'Holale Medical Clinic ( Moyale)'), ('18950', 'Holiday Medical Clinic'), ('17118', 'Holo Dispensary'), ('10321', 'Holy Cross Dispensary'), ('10320', 'Holy Family Dispensary'), ('19963', 'Holy Family Mission Hospital Githunguri'), ('16073', 'Holy Family Nangina Hospital'), ('13604', 'Holy Family Oriang Mission Dispensary'), ('15884', 'Eshisiru Maternity and Nursing Home'), ('11368', 'Eshu Dispensary'), ('13549', 'Esianyi Dispensary'), ('15885', 'Esiarambatsi Health Centre'), ('20171', 'Esikulu Dispensary'), ('15886', 'Esirulo Imani Medical Clinic'), ('15887', 'Esitsaba Dispensary'), ('16427', 'Esonorua Dispensary'), ('14478', 'Esther Memorial Nursing Home'), ('13550', 'Etago Sub-District Hospital'), ('14480', 'Ethi Dispensary'), ('13551', 'Etono Health Centre'), ('10173', 'Eunice Medical Clinic'), ('14481', 'Eureka Medical Clinic'), ('14482', 'Euvan Medical Clinic'), ('18046', 'Everest Dental Group Karatina Clinic'), ('20220', 'Everest Health Care(Mwingi Central)'), ('18719', 'Everest Medical/Dental Clinic'), ('19995', 'Evesben Foundation Medical Clinic'), ('20109', 'Ewang''ane Suswa '), ('14483', 'Ewaso Dispensary'), ('14484', 'Ewaso Ngiro Dispensary'), ('14485', 'Ewaso Ngiro Health Centre'), ('14486', 'Ewuaso Kedong Dispensary'), ('12006', 'Ex Lewa Dispensary'), ('13336', 'Excel Health Services'), ('19443', 'Exodus Community Health Care'), ('18054', 'Exodus Medical Clinic'), ('19632', 'Express Medical Clinic'), ('18632', 'Eye Care Centre'), ('10174', 'Eye Sight Clinic'), ('19572', 'Eyeclinic (Nairobi)'), ('18458', 'Eymole Health Centre'), ('13337', 'Eymole Health Centre'), ('13338', 'Fafi Dispensary'), ('17592', 'Faith Clinic'), ('19078', 'Faith Health Clinic'), ('10176', 'Faith Health Services Medical Clinic'), ('17453', 'Faith Medical Centre'), ('18469', 'Faith Medical Clinic'), ('18840', 'Faith Medical Clinic'), ('10177', 'Faith Medical Clinic (Nyeri North)'), ('16774', 'Faith Medical Clinic (Nyeri South)'), ('14490', 'Faith Medical Clinic Karate'), ('12013', 'Faith Nursing Home (Ikutha)'), ('12937', 'Family Care Clinic Kasarani'), ('19137', 'Family Care Doctor''s Plaza'), ('12942', 'Family Care Medical Centre & Maternity'), ('12015', 'Family Care Medical Centre (Meru)'), ('13140', 'Family Care Medical Centre (Phoenix)'), ('19328', 'Family Care Medical Centre Eye Clinic'), ('10178', 'Family Care Medical Clinic'), ('18755', 'Family Dental Care (Ayany)'), ('10179', 'Family Dental Clinic'), ('15888', 'Family Health Care Clinic'), ('18239', 'Family Health Centre (Embu)'), ('10180', 'Family Health Clinic'), ('10181', 'Family Health Clinic (Nyeri South)'), ('14492', 'Family Health Opition Kenya Clinic (Buret)'), ('18217', 'Family Health Option of Kenya'), ('16348', 'Family Health Options Kenya (Eldoret)'), ('11375', 'Family Health Options Kenya (FHOK) Mombasa'), ('13552', 'Family Health Options Kenya (FHOPK) Dispensary'), ('16756', 'Family Health Options Kenya Clinic'), ('12939', 'Family Health Options Phoenix'), ('12940', 'Family Health Options Ribeiro'), ('14177', 'Family Healthoptions Kenya (Nakuru)'), ('12941', 'Family Life Promotions and Services'), ('11370', 'Family Medical Centre (Kisauni)'), ('11371', 'Family Medical Centre (Malindi)'), ('11372', 'Family Medical Centre (Mombasa)'), ('18390', 'Family Medical Centre (Ruai)'), ('20115', 'Family Medical Clinic'), ('11490', 'Kitobo Dispensary (Taita)'), ('11491', 'Kitobo Dispensary (Taveta)'), ('16472', 'Kitoi Dispensary'), ('16253', 'Kitonyoni Dispensary'), ('18905', 'Kitui Afya Medical'), ('12366', 'Kitui District Hospital'), ('12367', 'Kitui Quality Care'), ('13706', 'Kituka Dispensary'), ('16437', 'Kituluni Dispensary'), ('18216', 'Kitum Dispensary'), ('12369', 'Kitundu (GOK) Dispensary'), ('12368', 'Kitundu (SDA) Dispensary'), ('19145', 'Kitundu Dispensary (Katulani District)'), ('12370', 'Kitunduni Dispensary'), ('12371', 'Kituneni Medical Clinic'), ('12372', 'Kitungati Dispensary'), ('14953', 'Kituro Health Centre'), ('12373', 'Kituruni Dispensary'), ('12374', 'Kiu (AIC) Dispensary'), ('10641', 'Kiumbu Health Centre'), ('11492', 'Kiunga Health Centre'), ('10642', 'Kiunyu Dispensary'), ('10643', 'Kiuu Dispensary'), ('12375', 'Kivaa Health Centre'), ('12376', 'Kivaani Health Centre'), ('12377', 'Kivani Dispensary'), ('12943', 'Flack Clinic'), ('14499', 'Flax Dispensary'), ('18472', 'Flomed Med Clinic'), ('20399', 'Florensis Kenya LTD Medical Clinic(Naivasha)'), ('18659', 'Florex Medical Clinic'), ('14500', 'Flourspar Health Centre'), ('19807', 'Fly Over Health Clinic'), ('19806', 'Fly Over Medical Clinic'), ('19274', 'Fmily Acces Medical Centre'), ('10184', 'Focus Medical Clinic and Counselling Centre'), ('19539', 'Focus Outreach Medical Mission'), ('20035', 'Fofcom VCT'), ('12019', 'Forolle Dispensary'), ('14501', 'Forttenan Sub District Hospital'), ('19173', 'Fountain Healthcare'), ('14502', 'Fountain Medical Centre'), ('17787', 'Fountain Medical Clinic'), ('18780', 'Fountain of Hope Medical Clinic'), ('14503', 'Fr andrian Heath Centre'), ('10185', '<NAME> Cath Disp'), ('13555', 'Framo Medical Clinic'), ('10187', 'Franjane Medical Clinic'), ('17721', 'Frankstar Medical Clinic (Manga)'), ('10188', 'Frayjoy Clinic (Dr Tumbo)'), ('11376', 'Freedom Medical Clinic'), ('18612', 'Fremo Medical Centre'), ('12944', 'Frepals Community Nursing Home'), ('18645', 'Friends Chemist'), ('19835', 'Front Line Medical Clinic'), ('12021', 'Frontier Clinic'), ('19219', 'Frontier Health Services'), ('19898', 'Frontier Health Services Malaba'), ('19886', 'Frontier Health Services- Malaba'), ('17901', 'Frontier Medical Clinic (Moyale)'), ('19058', 'Frontier Medicare'), ('11378', 'Frontline Clinic'), ('11379', 'Fundi Issa Dispensary'), ('16659', 'Furqan Dispensary'), ('12945', 'Future Age Medical Services'), ('17522', 'Future Life Dispensary'), ('17877', 'G K Prisons (Thika)'), ('17716', 'G S U Kinisa Dispensary'), ('16852', 'Gaatia Dispensary'), ('18630', 'Gababa Dispensary'), ('12022', 'Gacabari Dispensary'), ('10190', 'Gacharage Dispensary'), ('10191', 'Gacharageini Dispensary'), ('10192', 'Gachatha Medical Clinic (Nyeri South)'), ('10194', 'Gachege Dispensary'), ('10195', 'Gachika Dispensary'), ('10196', 'Gachika Orthodox Medical Clinic'), ('18608', 'Gachororo Health Centre'), ('18339', 'Gachua Catholic Dispensary'), ('12023', 'Gachuriri Dispensary'), ('12024', 'Gaciongo Dispensary'), ('10197', 'Gaciongo Dispensary (Kirinyaga)'), ('10198', 'Gadi Medical Clinic'), ('12025', 'Gafarsa Health Centre'), ('11380', 'Gahaleni Dispensary'), ('19918', 'Gaichanjiru Hospita (Satelite)'), ('10199', 'Gaichanjiru Hospital'), ('12946', 'Gaimu Clinic'), ('13556', 'Gairoro Dispensary'), ('12026', 'Gaitu Dispensary'), ('10200', 'Gakawa Dispensary'), ('20355', 'Gaketha Dispensary'), ('10201', 'Gakira Medical Clinic'), ('10202', 'Gakoe Health Centre'), ('12027', 'Gakoromone Dispensary'), ('18703', 'Gakoromone Health Care Clinic'), ('16570', 'Gakoromone Medical Clinic'), ('16738', 'Gakurungu Dispensary'), ('10203', 'Gakurwe Dispensary'), ('10204', 'Gakuyuini Medical Clinic'), ('11381', 'Galana Hospital'), ('16244', 'Galilee Medical Clinic'), ('12898', 'Clinitec Medical Services'), ('17388', 'Clinix Health Care'), ('18754', 'Clinix Health Care (Kibera)'), ('19071', 'Clinix Health Care Limited (Meru)'), ('19407', 'Clinix Medical Centre Isiolo'), ('18917', 'Clinix Medical Clinic (Machakos)'), ('14394', 'Cmf Aitong Health Centre'), ('20369', 'CMIA Grace Children''s Centre Dispensary'), ('20326', 'CMM Clinic'), ('11289', 'Coast Province General Hospital'), ('10101', 'Coffee Research Staff Dispensary'), ('18745', 'Comboni Missionary Sisters Health Programm'), ('19200', 'Comet Medical Clinic'), ('18748', 'Comfort The Chidren International (Ctc) Naivasha'), ('19455', 'Communal Oriented Service International Centre'), ('20079', 'Community Action for Rural Developement VCT'), ('18384', 'Community Counselling Resource Centre'), ('19697', 'Community Diagnostic Medical Centre'), ('20230', 'Community Evolution Network VCT'), ('12901', 'Community Health Foundation'), ('14395', 'Community Medical and Lab Services Clinic'), ('16536', 'Community Medical Centre (Kongowea)'), ('12902', 'Compassionate Hospital'), ('18740', 'Green Valley Clinic'), ('14538', 'Greenview Hospital'), ('20217', 'Greenview Medical Clinic'), ('13352', 'Griftu District Hospital'), ('16413', 'Gsu Dispensary'), ('14539', 'Gsu Dispensary (Kabarak)'), ('14540', 'Gsu Dispensary (Kibish)'), ('12961', 'Gsu Dispensary (Nairobi West)'), ('10304', 'Gsu Dispensary (Ruiru)'), ('14541', 'Gsu Field Dispensary (Kajiado)'), ('12963', 'Gsu Hq Dispensary (Ruaraka)'), ('12962', 'Gsu Training School'), ('13353', 'Guba Dispensary'), ('13594', 'Gucha District Hospital'), ('13595', 'Gucha Maternity and Nursing Home'), ('19007', 'Gule Medical Clinic'), ('10305', 'Gumba Health Centre'), ('19122', 'Gundua Health Centre'), ('18715', 'Gunduwa Health Centre'), ('13355', 'Gurar Health Centre'), ('13596', 'Guru Nanak Dispensary'), ('12965', 'Guru Nanak Hospital'), ('13356', 'Gurufa Dispensary'), ('18213', 'Gurunanak Medical Clinic'), ('12054', 'Gus Dispensary'), ('17007', 'Guticha Dispensary'), ('18842', 'Darajani Medical Clinic'), ('18276', 'Darushif Medical Clinic'), ('13325', 'Dasheq Dispensary'), ('16498', 'Dave Laboratory'), ('11632', 'David Kariuki Medical Centre'), ('11457', '<NAME> Dispensary'), ('19596', 'Dawa Jema Medical Cl'), ('19240', 'Dawa Mart Clinic'), ('10104', 'Dawa Medical Clinic (Nyeri South)'), ('11299', 'Dawida Maternity Nursing Home'), ('11300', 'Dawson Mwanyumba Dispensary'), ('15863', 'Day Light Clinic'), ('20195', 'Debomart Med Clinic'), ('13532', 'Dede Dispensary'), ('10105', 'Del Monte Dispensary'), ('14401', 'Delamere Clinic'), ('19377', 'Delight Chemist & Lab'), ('10106', 'Delina Health Care'), ('12915', 'Delta Medical Clinic Dandora'), ('11302', 'Dembwa Dispensary'), ('19105', 'Dental Clinic Dr <NAME>'), ('19343', 'Dental Surgery Kitengela'), ('20452', 'Denticheck Clinical Services'), ('19694', 'Dentmind Dental Clinic Kitengela'), ('14402', 'Dentomed Clinic'), ('18457', 'Derkale Dispensary'), ('13327', 'Dertu Health Centre'), ('13326', 'Dertu Medical Clinic'), ('17949', 'Destiny Medical Centre (Ruaraka)'), ('18839', 'Destiny Medical Clinic'), ('19717', 'Destiny Medical Clinic (Kinoro-Imenti South)'), ('17537', 'Deteni Medical Clinic'), ('17904', 'Devki Staff Clinic'), ('19265', 'Devki Staff Clinic (Ruiru)'), ('20143', 'Devlink Africa VCT, Mbita'), ('19004', 'Dhanun Clinic'), ('19874', 'Dhmt'), ('19516', 'Dhs Ghataura'), ('10108', 'Diana Medical Clinic'), ('18499', 'Diani Beach Hospital'), ('12916', 'Diani Dispensary'), ('11304', 'Diani Health Centre'), ('18897', 'Dice Clinic Migori'), ('11305', 'Dida Dispensary'), ('11306', 'Didewaride Dispensary'), ('13533', 'Dienya Health Centre'), ('10109', 'Difathas Catholic Dispensary'), ('10110', 'Difathas Health Centre'), ('13328', 'Diff Health Centre'), ('19210', 'Digfer Nursing Home'), ('14403', 'Diguna Dispensary'), ('13329', 'Dilmanyaley Health Centre'), ('16561', 'Diplomat Clinic'), ('18723', 'Diplomatic Medical Clinic'), ('11986', 'Dirib Gombo Dispensary'), ('16268', 'Diruma Dispensary'), ('13534', 'Disciples of Mercy Clinic'), ('17663', 'Discordant Couples of Kenya VCT'), ('19074', 'District Public Health Office (Meru)'), ('19109', 'Divine Mercy Catholic Dispensary'), ('11308', 'Divine Mercy Dispensary'), ('11365', 'Divine Mercy Eldoro (Catholic) Dispensary'), ('18388', 'Divine Mercy Kariobangi'), ('12351', 'Divine Mercy Kithatu Dispensary'), ('12917', 'Diwopa Health Centre'), ('12918', 'Dod Mrs Dispensary'), ('12919', 'Dog Unit Dispensary (O P Kenya Police)'), ('14404', 'Doldol Sub District Hospital'), ('13535', 'Dolphil Nursing & Maternity Home'), ('19136', '<NAME>'), ('10111', 'Dommy Medical Clinic'), ('10112', '<NAME> Catholic Dispensary'), ('11987', '<NAME>linic'), ('10113', 'Dona Medical Clinical'), ('16432', 'Donyo Sabuk Dispensary'), ('11385', 'Garsen Health Centre'), ('16444', 'Garsesala Dispensary'), ('17289', 'Garseyqoftu Dispensary'), ('12030', 'Gatab Health Centre'), ('16378', 'Gatamaiyo Dispensary'), ('10206', 'Gatamu Medical Clinic'), ('10207', 'Gatanga Dispensary'), ('10208', 'Gatangara Dispensary'), ('16230', 'Gatankene Dispensary'), ('10209', 'Gatara Health Centre'), ('16463', 'Gategi Health Centre'), ('10210', 'Gatei Dispensary'), ('10211', 'Gateways Medical Clinic'), ('10212', 'Gathaithi Dispensary'), ('10213', 'Gathambi Health Centre'), ('10214', 'Gathanga Dispensary'), ('19965', 'Gathangari Dispensary'), ('20023', '<NAME>'), ('17058', 'Gathanji Dispensary'), ('10215', 'Gathara Dispensary'), ('10216', 'Gatheru Dispensary'), ('10217', 'Gathigiriri Health Centre'), ('10219', 'Gathiruini (PCEA) Dispensary'), ('17305', 'Gatiaini Dispensary'), ('12031', 'Gatimbi Health Centre'), ('11318', 'Dr <NAME>'), ('11319', 'Dr <NAME>'), ('11320', 'Dr <NAME>'), ('11321', 'Dr <NAME>'), ('10119', 'Dr <NAME>'), ('10120', 'Dr <NAME>'), ('19565', 'Dr <NAME> (Parklands)'), ('18003', 'Dr <NAME>ic'), ('19851', 'Dr <NAME> Medical Clinic'), ('19588', 'Dr Fatema'), ('18778', 'Dr <NAME> (Ngong Road)'), ('17235', 'Dr <NAME>'), ('12922', 'Dr Gachare Medical Clinic'), ('14408', 'Dr <NAME>'), ('10121', 'Dr Gachiri'), ('11324', 'Dr <NAME>'), ('19425', 'Dr <NAME> Medical Clinic'), ('19567', 'Dr <NAME>'), ('19586', 'Dr Giddie'), ('11325', 'Dr <NAME>'), ('11326', 'Dr <NAME>'), ('11327', 'Dr <NAME>'), ('11328', 'Dr <NAME>'), ('19563', 'Dr <NAME>'), ('19783', 'Dr <NAME>'), ('18807', 'Dr Irimu'), ('10122', 'Dr <NAME> Dermatology Clinic'), ('19961', 'Dr <NAME>'), ('11329', 'Dr <NAME>'), ('17292', 'Dr <NAME>'), ('19522', 'Dr <NAME> Clinic (Nairobi)'), ('19687', 'Dr <NAME>'), ('19468', 'Dr Jemmah & Nyawange Med Clinic'), ('10124', 'Dr <NAME>'), ('11331', 'Dr <NAME>'), ('11332', 'Dr <NAME>'), ('14409', 'Dr <NAME>ic'), ('11333', 'Dr Kamande Clinic'), ('11334', 'Dr Kandwalla Clinic'), ('10125', 'Dr <NAME> K Urology Clinic'), ('14410', 'Dr Kanyiri Dental Clinic'), ('14411', 'Dr Karania Medical Clinic'), ('11335', 'Dr Karima Clinic'), ('10126', 'Dr Kariuki'), ('10127', 'Dr <NAME> M Psychiatric Clinic'), ('11336', 'Dr <NAME> Clinic'), ('19690', 'Dr <NAME>'), ('19661', 'Dr <NAME>'), ('18724', 'Dr Kiara Medical Clinic'), ('18716', 'Dr Kiara Medical Clinic'), ('14412', 'Dr Kibe Medical Clinic'), ('19780', 'Dr Kibec Clinic'), ('10128', 'Dr <NAME>'), ('19982', 'Dr Kingondu Clinic (Westlands)'), ('18633', 'Dr <NAME>linic'), ('16564', 'Dr <NAME>linic'), ('19666', 'Dr Kiptum Medical Clinic'), ('11337', 'Dr <NAME>linic'), ('11338', 'Dr <NAME>'), ('19568', 'Dr <NAME> D Medical Centre'), ('10129', 'Dr L G Mburu Radiological Clinic'), ('10130', 'Dr L L M Muturi Medical Clinic'), ('17768', 'Dr L M Macharia Dental Clinic'), ('19797', 'Dr L N Wagana Clinic'), ('19587', 'Dr <NAME>'), ('10131', 'Dr M H Shah Medical Clinic'), ('10132', 'Dr <NAME> Opthamological Clinic'), ('10133', 'Dr <NAME> / Obstretric Clinic'), ('19420', 'Dr M S Saroya Medical Clinic (Nairobi)'), ('10134', 'Dr Macharia'), ('11339', 'Dr <NAME>'), ('10135', 'Dr Maina'), ('20106', 'Dr Maina Ruga Medical Clinic'), ('19419', 'Dr Maina Skin Clinic (Ngara)'), ('14413', 'Dr <NAME>'), ('11341', 'Dr <NAME>'), ('19573', 'Dr Maroo'), ('10136', 'Dr <NAME>/Obstetic Clinic'), ('19646', 'Dr <NAME>'), ('14414', 'Dr <NAME>'), ('19501', 'Dr <NAME> Dental Surgeon'), ('11343', 'Dr <NAME>'), ('12925', 'Dr <NAME>'), ('12926', 'Dr Montet Medical Clinic'), ('12927', 'Dr Muasya Medical Clinic'), ('16838', 'Gatimbi Medical Clinic'), ('16397', 'Gatimu Dispensary'), ('18781', 'Gatimu Health Centre'), ('10220', 'Gatina Dispensary'), ('16803', 'Gatina United Clinic'), ('18453', 'Gatiruri Dispensary'), ('10221', 'Gatithi Dispensary'), ('10222', 'Gatitu Dispensary'), ('10223', 'Gatondo Dispensary (Kipipiri)'), ('10224', 'Gatondo Dispensary (Nyeri North)'), ('10226', 'Gatuamba Medical Clinic'), ('10227', 'Gatuanyaga Dispensary'), ('10228', 'Gatugi Mission Dispensary'), ('10229', 'Gatugura Dispensary'), ('10231', 'Gatukuyu Medical Clinic'), ('10232', 'Gatumbi (SDA) Dispensary'), ('12032', 'Gatumbi Dispensary'), ('10233', 'Gatundu District Hospital'), ('12033', 'Gatunduri Dispensary'), ('12034', 'Gatunga Health Centre'), ('18080', 'Gatunga Model Health Centre'), ('10234', 'Gatunyu Dispensary'), ('10235', 'Gatura (PCEA) Dispensary'), ('10236', 'Gatura Healh Centre'), ('16976', 'Gaturi Catholic Parish Dispensary'), ('10149', 'Dr <NAME> Pathological Clinic'), ('10150', 'Dr <NAME>ynae/ Obstetic Clinic'), ('16355', 'Dr <NAME>'), ('19423', 'Dr <NAME> Clinic'), ('18182', 'Dr Ogaro Medical Clinic'), ('20122', 'Dr Ogindo''s Clinic'), ('11348', 'Dr <NAME> O'), ('16781', 'Dr P K Kapombe Dental Clinic'), ('10151', 'Dr <NAME>'), ('19426', 'Dr <NAME>'), ('19480', 'Dr Parmar Medical Clinic (Nairobi)'), ('20105', 'Dr <NAME>'), ('19534', 'Dr <NAME>'), ('19570', 'Dr <NAME>'), ('19062', 'Dr <NAME>'), ('16539', 'Dr <NAME>'), ('19576', 'Dr <NAME>'), ('11352', 'Dr <NAME>'), ('19583', 'Dr Sajay'), ('19675', 'Dr <NAME> (Kitale Medical Centre)'), ('19579', 'Dr <NAME>'), ('11353', 'Dr <NAME>'), ('18183', 'Dr Sharma Medical Clinic'), ('11354', 'Dr <NAME>'), ('11355', 'Dr <NAME>'), ('14422', 'Dr <NAME>'), ('19571', 'Dr <NAME>linic'), ('19781', 'Dr <NAME>'), ('19177', 'Dr Thuo''<NAME>'), ('19721', 'Crestwood Medical Clinic'), ('11979', 'Crossroad Nursing Home'), ('19301', 'Crow Medical Centre'), ('14399', 'Crystal Medical And Cottage Hospital'), ('16538', 'Crystal Medical Centre'), ('10102', 'Cura (ACK) Medical Clinic'), ('17402', 'Cura Medical Clinic'), ('17397', 'Cure (AIC) International Children''s Hospital'), ('11980', 'Curran Dispensary'), ('19238', 'Current Medical Ciinic'), ('11981', 'D Comboni Mission'), ('11296', 'Daba (AIC) Dispensary'), ('11982', 'Dabel Health Centre (Moyale)'), ('12908', 'Dabliu Clinic'), ('13315', 'Dadaab Clinic'), ('13316', 'Dadaab Sub-District Hospital'), ('13317', 'Dadajabula Sub District Hospital'), ('13318', 'Dagahaley Hospital'), ('17006', 'Dagahley Dispensary'), ('11297', 'Dagamra Dispensary'), ('16186', 'Dagamra Medical Clinic'), ('20377', '<NAME> Dispensary'), ('12909', 'Dagoretti Approved Dispensary'), ('20189', 'Dagoretti Community Dispesary'), ('10115', 'Dr <NAME> Dental Clinic'), ('10153', 'Dr <NAME>linic'), ('11356', 'Dr <NAME>linic'), ('10154', 'Dr Wachira'), ('10155', 'Dr Waihenya'), ('10156', 'Dr Wanjohi'), ('16797', 'Dr Waris'), ('14423', 'Dr <NAME>'), ('12928', 'Dr Were Medical Clinic'), ('11357', 'Dr <NAME>'), ('11358', 'Dr <NAME>'), ('18981', 'Dr <NAME>ic'), ('18429', 'Dr <NAME>'), ('20393', 'Dr.Charles.J.R.Opondo (landmark plaza)'), ('20394', 'Dr.<NAME> (landmark plaza)'), ('20397', 'Dr.K.Gicheru(Upper Hill Centre)'), ('20396', 'Dr.P.W.Kamau&Associates(Upper Hill Medical Centre)'), ('15864', 'Dreamland Mc Health Centre'), ('18389', 'Dreamline Medical Clinic Kamulu'), ('12929', 'Dreams Centre Dispensary (Langata)'), ('18481', 'DRIC (Naivasha)'), ('20059', 'Drop In Service Centre'), ('16668', 'Drop Inn Ray Clinic'), ('16307', 'Drugmart Medical Clinic'), ('13520', 'Central Clinic (Kisumu East)'), ('15843', 'Central Clinic (Lugari)'), ('11965', 'Central Medical Clinic'), ('18903', 'Central Medical Clinic (Kitui Central)'), ('19578', 'Central Medical Clinic (Nairobi)'), ('17696', 'Central Medical Clinic and Labaratory (Changamwe)'), ('10083', 'Central Memorial Hospital'), ('19531', 'Central Park Clinic'), ('20154', 'Centre medical clinic'), ('19985', 'CFW Clinic'), ('19938', 'CFW Kiamugumo Glory'), ('11966', 'CFW Kimangaru Clinic'), ('19225', 'CFW Mbuvori Clinic'), ('19841', 'CFW Mwea Clinic'), ('11274', 'Chaani (MCM) Dispensary'), ('17223', 'Chabuene Dispensary'), ('16475', 'Chagaik Dispensary'), ('14284', 'Chagaiya Dispensary'), ('17573', 'Chaka Health Services Clinic'), ('11276', 'Chakama Dispensary'), ('11277', 'Chala Dispensary (Taita Taveta)'), ('16191', 'Chalani Dispensary'), ('11278', 'Challa Dispensary'), ('10086', 'Chalo Medical Clinic'), ('15845', 'Chamakanga Mission'), ('14285', 'Chamalal Dispensary'), ('19339', 'Chamamo Medical Clinic'), ('11279', 'Chamari CDF Dispensary'), ('20308', 'Chamari Dispensary'), ('18782', 'Chamuka (CDF) Dispensary'), ('12893', 'Chandaria Health Centre'), ('12621', 'Chandaria Mwania Dispensary'), ('14286', 'Changach Barak Dispensary'), ('11280', 'Changamwe Maternity'), ('16421', 'Changara (GOK) Dispensary'), ('15846', 'Changara Calvary Dispensary'), ('14287', 'Changoi Dispensary'), ('10087', 'Chania Clinic'), ('10088', 'Chania Obstetrics Gyno Clinic'), ('19772', 'Chania Optical'), ('11281', 'Charidende Dispensary (CDF)'), ('10089', 'Charity Medical Centre'), ('10090', 'Charity Medical Clinic'), ('11967', 'Charuru Dispensary'), ('11282', 'Chasimba Health Centre'), ('15847', 'Chavogere Mission'), ('14288', 'Chebaiwa Dispensary'), ('14289', 'Chebangang Health Centre'), ('14290', 'Chebango Dispensary'), ('14291', 'Chebaraa Dispensary'), ('14292', 'Cheberen Dispensary'), ('14293', 'Chebewor Dispensary'), ('14294', 'Chebiemit District Hospital'), ('14295', 'Chebilat Dispensary'), ('17131', 'Chebilat Dispensary (Nandi South)'), ('14296', 'Chebirbei Dspensary'), ('14297', 'Chebirbelek Dispensary'), ('14298', 'Chebitet Dispensary'), ('19849', 'Cheboet Dispensary'), ('20060', 'Cheboin Dispensary'), ('18236', 'Cheboin Dispensary (Bureti)'), ('19155', 'Chebon Medical Clinic'), ('14300', 'Cheborgei Health Centre'), ('14301', 'Chebororwa Health Centre'), ('14302', 'Cheboyo Dispensary'), ('15848', 'Chebukaka Dispensary'), ('20159', 'Chebukwabi Dispensary'), ('14303', 'Chebulbai Dispensary'), ('14304', 'Chebunyo Dispensary'), ('15849', 'Chebwai Mission Dispensary'), ('14305', 'Chechan Dispensary'), ('11968', 'Cheera Dispensary'), ('14306', 'Chegilet Dispensary'), ('15850', 'Chegulo Dispensary'), ('14307', 'Cheindoi Dispensary'), ('15851', 'Chekalini Dispensary'), ('14308', 'Chelelach Dispensary'), ('15852', 'Chelelemuk (St.Boniface Mwanda B) Dispensary'), ('20234', 'Drugnet Medical centre'), ('17063', 'Dry''s Dispensary'), ('13099', 'Dsc Karen Dispensary (Armed Forces)'), ('17046', 'Dubai Medical Clinic'), ('13330', 'Dugo Health Centre'), ('13331', 'Dujis Health Centre'), ('11990', 'Dukana Health Centre (North Horr)'), ('14424', 'Dundori Health Centre'), ('16661', 'Dunga Nursing Home'), ('19024', 'Dungicha Dispensary'), ('17353', 'Dunto Dispensary'), ('19218', 'Durdur Medical Clinic and Lab'), ('11991', 'Dwa Health Centre'), ('18263', 'Dzanikeni Medical Clinic'), ('11359', 'Dzikunze Dispensary'), ('11360', 'Dzitsoni Medical Clinic'), ('18739', 'Eagle Wings Medical Centre'), ('11992', 'EAPC Kigumo Clinic'), ('18152', 'East Africa Portland Cement Company Clinic'), ('18638', 'East End Chemist'), ('19618', 'East Medical Clinic'), ('11993', 'East Way Medical Clinic'), ('10521', 'Eastend Clinic'), ('16567', 'Eastern Consultans Laboratory'), ('19452', 'Eastern Medical Clinic'), ('16568', 'Eastern Medical Consultants'), ('12930', 'Eastleigh Health Centre'), ('14321', 'Chemolingot District Hospital'), ('14322', 'Chemomi Tea Dispensary'), ('20461', 'Chemoril dispensary'), ('14323', 'Chemosot Health Centre'), ('20328', 'Chemotong Dispensary'), ('18584', 'Chemses Dispensary'), ('16731', 'Chemsik Dispensary'), ('14324', 'Chemundu Dispensary (Nandi Central)'), ('14325', 'Chemursoi Dispensary'), ('14326', 'Chemuswo Dispensary'), ('18563', 'Chemwa Bridge Dispensary'), ('17782', 'Chemwokter Dispensary'), ('18583', 'Chemworemwo Dispensary'), ('14327', 'Chemworor Health Centre'), ('14328', 'Chepakundi Dispensary'), ('14329', 'Chepareria (SDA) Dispensary'), ('14330', 'Chepareria Sub District Hospital'), ('14331', 'Chepchabas Dispensary'), ('14332', 'Chepchoina Dispensary'), ('14333', 'Chepcholiet Dispensary'), ('14334', 'Chepgoiben Dispensary'), ('16727', 'Chepkalacha Dispensary'), ('14335', 'Chepkanga Health Centre'), ('14336', 'Chepkechir Dispensary'), ('14337', 'Chepkemel Dispensary'), ('14338', 'Chepkemel Health Centre (Kericho)'), ('14339', 'Chepkemel Health Centre (Mosop)'), ('14340', 'Chepkero Dispensary'), ('14341', 'Chepkigen Dispensary'), ('14343', 'Chepkoilel Campus Dispensary'), ('18188', 'Chepkoiyo'), ('14344', 'Chepkoiyo Dispensary'), ('14345', 'Chepkongony Dispensary'), ('20330', 'Chepkono Dispensary'), ('19011', 'Chepkono Medical Clinic'), ('14342', 'Chepkopegh Dipensary'), ('14346', 'Chepkorio Health Centre'), ('14347', 'Chepkoton Dispensary'), ('15854', 'Chepkube Dispensary'), ('14348', 'Chepkumia Dispensary'), ('14349', 'Chepkunan Clinic'), ('14351', 'Chepkunyuk Dispensary'), ('14350', 'Chepkunyuk Dispensary (Kipkelion)'), ('20149', 'Chepkurngung Dispensary'), ('14352', 'Cheplambus Dispensary'), ('14353', 'Cheplanget Dispensary'), ('14354', 'Cheplaskei Dispensary'), ('17239', 'Cheplelabei Dispensary'), ('17629', 'Cheplengu Dispensary'), ('13523', 'Chepngombe Health Centre'), ('14355', 'Chepngoror Dispensary'), ('19246', 'Chepnoet Clinic'), ('19244', 'Chepnoet Private Clinic'), ('14356', 'Chepnyal Dispensary'), ('20366', 'Chepnyal GOK Dispensary'), ('14357', 'Cheppemma (AIC) Dispensary'), ('14358', 'Chepsaita Dispensary'), ('14359', 'Chepseon Dispensary'), ('14360', 'Chepseon Health Care Clinic'), ('14361', 'Chepseon Medical Clinic'), ('16469', 'Chepseon-VCT Site'), ('14362', 'Chepsir Dispensary'), ('18497', 'Chepsire Dispensary'), ('14363', 'Chepsiro Dispensary'), ('17310', 'Chepsoo'), ('14364', 'Cheptabach Dispensary'), ('14365', 'Cheptabes Dispensary'), ('18891', 'Cheptais Clinic'), ('15855', 'Cheptais Sub District Hospital'), ('14366', 'Cheptalal Sub-District Hospital'), ('17334', 'Cheptangulgei Dispensary'), ('19750', 'Cheptantan Dispensary'), ('18467', 'Cheptarit Dispensary'), ('19248', 'Cheptarit Med Clinic'), ('14367', 'Cheptebo Dispensary'), ('20210', 'Complete Care Health Services'), ('10098', 'Complex Medical Centre'), ('10099', 'Comrade Nurising Home'), ('12903', 'Conerstone Clinic'), ('12958', 'Coni Health Centre'), ('19450', 'Connections Medical Clinic'), ('14396', 'Consolata Clinic'), ('11976', 'Consolata Hospital (Nkubu)'), ('12413', 'Consolata Kyeni Hospital'), ('14397', 'Consolata Medical Clinic (Eldoret South)'), ('10100', 'Consolata Mission Hospital (Mathari)'), ('18888', 'Consolata Shrine Dispensary (Deep Sea Nairobi)'), ('20148', 'Copeman Health Care Centre'), ('18579', 'Coping Centre'), ('12905', 'Coptic Hospital (Ngong Road)'), ('12904', 'Coptic Medical Clinic'), ('15862', 'Coptic Nursing Home'), ('19439', 'Corban Health Care'), ('19722', '<NAME> Dispensary'), ('11291', 'Corner Chaani Medical Clinic'), ('18313', 'Corner Clinic'), ('19470', 'Corner Hse Med Laboratory'), ('16537', 'Corner Medical Clinic'), ('15856', 'Chesikaki Dispensary'), ('14382', 'Chesinende (Elck) Dispensary'), ('18582', 'Chesinende Dispensary'), ('20107', 'Chesinende Health Services'), ('16728', 'Chesirimion Dispensary'), ('14383', 'Chesiyo Dispensary'), ('14384', 'Chesoen Dispensary'), ('19249', 'Chesogor Medical Clinic/Chemist'), ('14385', 'Chesoi Health Centre'), ('16336', 'Chesoi Medical Clinic'), ('17018', 'Chesongo Dispensary'), ('14386', 'Chesongoch Health Centre'), ('14387', 'Chesta Dispensary'), ('14388', 'Chesubet Dispensary'), ('17358', 'Chesunet Dispensary'), ('17047', 'Chesupet Dispensary'), ('15857', 'Chevoso Dispensary'), ('11283', 'Chewani Dispensary'), ('11284', 'Chewele Dispensary'), ('11969', 'Chiakariga H/C'), ('18564', 'Chianda Dispensary (Rarieda)'), ('11285', 'Chifiri Dispensary (LATIF)'), ('13524', 'Chiga Dispensary'), ('19504', 'Child Doctor Kenya'), ('18443', 'Child Welfare Society of Kenya Medical Clinic'), ('17951', 'Children Medical Clinic (Kasarani)'), ('18329', 'Children''s Support Centre Emurembe'), ('11286', 'Chimbiriro Clinic'), ('15858', 'Chimoi Health Centre'), ('13525', 'China Dispensary'), ('13526', 'Chinato Health Centre'), ('19589', 'Chiromo Medical Centre'), ('15584', 'Chitugul Medical Clinic'), ('11287', 'Chizi Medical Clinic'), ('11970', 'Chogoria (PCEA) Hospital'), ('19169', 'Choice Health Care'), ('15859', 'Chombeli Health Centre'), ('17418', 'Chomei Medical Clinic'), ('19035', 'Chonesus Clinic'), ('17282', 'Chororget Dispensary'), ('19812', '<NAME>'), ('17824', 'Christ The Healer'), ('18483', 'Christamarianne Medical Clinic (Suneka)'), ('13527', 'Christamarianne Mission Hospital'), ('12895', 'Christian Aid Dispensary'), ('10092', 'Christian Community Services Clinic Base Kerugoya'), ('10093', 'Christian Community Services Wang''uru Dispensary'), ('18270', 'Christian Partners Development Agency VCT'), ('11971', 'Chugu Dispensary'), ('14389', 'Chuiyat Dispensary'), ('16232', 'Gaturi Dispensary'), ('10237', 'Gaturi Medical Clinic'), ('16386', 'Gatuto Dispensary'), ('10239', 'Gatwe Health Centre'), ('19006', 'Gatwell/Lab Medical Clinic'), ('10240', 'Gawa Medical Clinic'), ('19862', 'Gazi Bay Medical Clinic'), ('11386', 'Geca Medical Clinic'), ('17314', 'Gechiriet Dispensary'), ('18650', 'Gecy Chemist'), ('11387', 'Gede Health Centre'), ('11388', 'Gede Medical Clinic'), ('19611', 'Gedmed Medical Clinic'), ('13557', 'Gekano Health Centre (Manga)'), ('14505', 'Gelegele Dispensary'), ('16571', 'General Medical Clinic'), ('18705', 'General Medical Clinic and Lab'), ('16572', 'General Medical Laboratory'), ('16573', 'Generation Medical Clinic/Lab'), ('10241', 'Generations Medical Clinic'), ('16574', 'Genesis Clinic (Imenti North)'), ('10242', 'Genesis Clinic (Kirinyaga)'), ('16500', 'Genesis Community Bamako Initiative'), ('17236', 'Genesis Medical Clinic'), ('19702', 'Genesis Medical Clinic Kitengela'), ('16442', 'Genesis Medicare'), ('12949', 'Genessaret Clinic'), ('13191', 'EDARP Soweto Health Centre'), ('10162', 'Eddiana Hospital'), ('12931', 'Eden Dispensary'), ('12932', 'Ediana Nursing Home'), ('18197', 'Edkar Health Services'), ('12933', 'Edna Clinic'), ('12934', 'Edna Maternity'), ('18359', 'Educational Assessment and Resource Centre'), ('11364', 'Egah Medical Clinic'), ('14426', 'Egerton University'), ('13538', 'Egetonto Dispensary (Gucha)'), ('19984', 'Egetuki GOK Dispensary'), ('13539', 'Egetuki Medical Clinic (Gucha)'), ('11995', 'Ekalakala Health Centre'), ('11996', 'Ekalakala Medical Clinic'), ('15868', 'Ekamanji Dispensary'), ('17600', 'Ekani Dispenasry'), ('13540', 'Ekerenyo Sub-District Hospital'), ('16422', 'Ekerubo Dispensary (Kisii South)'), ('13541', 'Ekerubo Dispensary (Masaba)'), ('19971', 'Ekialo Kiano VCT'), ('15869', 'Ekitale Dispensary'), ('19900', 'Ekomero Health Centre'), ('15870', 'Ekwanda Health Centre'), ('11997', 'El Hadi Dispensary'), ('17733', 'Bahati Medical Clinic Migori'), ('16532', 'Bakarani Community Clinic'), ('11235', 'Bakarani Maternity and Nursing Home'), ('11236', 'Bakhita Dispensary'), ('13298', 'Balambala Sub-District Hospital'), ('19259', 'Bales Saru Dispensary'), ('11941', 'Balesa Dispensary'), ('13299', 'Balich Dispensary'), ('11776', 'Ballore Africa Logistic Staff Clinic'), ('13493', 'Bama Hospital'), ('11238', 'Bamba Medical Clinic'), ('11237', 'Bamba Sub-District Hospital'), ('10044', 'Bamboo Health Centre'), ('11239', 'Bamburi Dispensary'), ('11240', 'Bamburi Medicare'), ('16297', 'Banadir Clinic'), ('13494', 'Bande Dispensary'), ('11242', 'Bangali Dispensary'), ('17074', 'Bangali Nomadic'), ('14225', 'Bangii Medical Clinic'), ('13300', 'Banisa Health Centre'), ('14226', 'Banita Dispensary'), ('15805', 'Banja Health Centre'), ('19428', 'Bans Optical (Nairobi)'), ('11243', 'Baobab Clinic - Bamburi Cement'), ('17871', 'Baobab Medical Clinic'), ('11244', 'Baolala Dispensary'), ('13495', 'Bar Achuth Dispensary'), ('13496', 'Bar Agulu Dispensary'), ('13497', 'Bar Aluru Dispensary (Rarieda)'), ('20206', 'Bar Hostess Empowerment and Support Programme (Makadara)'), ('18468', 'Bar Hostess Empowerment Support Program VCT'), ('13498', 'Bar Korwa Dispensary'), ('16784', 'Bar Ndege Dispensary'), ('13499', 'Bar Olengo Dispensary'), ('14227', 'Baragoi Catholic Dispensary'), ('14228', 'Baragoi Sub-District Hospital'), ('11942', 'Baragu Health Centre'), ('10046', 'Baragwi Maternity Home'), ('11943', 'Baraka Afya Clinic'), ('18841', 'Baraka Clinic (Lugari)'), ('18915', 'Baraka Dental Clinic (Maara)'), ('12881', 'Baraka Dispensary (Nairobi)'), ('17757', 'Baraka Health Centre'), ('14230', 'Baraka Maternity Home'), ('19529', 'Baraka Medical Cenre'), ('17934', 'Baraka Medical Centre'), ('17426', 'Baraka Medical Clinic'), ('19840', 'Baraka Medical Clinic (Kirinyaga)'), ('16202', 'Baraka Medical Clinic (Lamu)'), ('19306', 'Baraka Medical Clinic (Makindu)'), ('20260', 'Baraka Medical Clinic (Mbitini)'), ('10047', 'Baraka Medical Clinic (Muranga North)'), ('14229', 'Baraka Medical Clinic (Pokot Central)'), ('17882', 'Baraka Medical Clinic (Runyenjes)'), ('16670', 'Baraka Medical Clinic (Samburu East)'), ('16693', 'Baraka Medical Clinic (Trans Nzoia East)'), ('14231', 'Baraka Medical Clinic (Turkana Central)'), ('11245', 'Baraka Medical Clinic (Vikwatani)'), ('18224', 'Baraka Medical Clinic Kitengela'), ('11944', 'Baraka Nursing Home'), ('19601', 'Baraka Yetu Medical Clinic'), ('17360', 'Barakeiywo Dispensary'), ('16289', 'Baraki Dispensary'), ('11945', 'Barambate Dispensary'), ('17302', 'Bararget Dispensary'), ('17218', 'Baraton'), ('14232', 'Baraton Mch'), ('11946', 'Barazani Medical Clinic'), ('18396', 'Barding Dispensary'), ('18381', 'Bargain Medical Clinic'), ('11247', 'Bargoni Nys Dispensary'), ('10048', 'Baricho Catholic Health Centre'), ('12906', 'Corner Stone'), ('11292', 'Cornerstone Medical Clinic'), ('18474', 'Cornerstone Medical Clinic (Nyeri Central)'), ('18119', 'Cornestone Baptist Clinic'), ('12907', 'Cotolengo Centre'), ('11977', 'Cottolengo Mission Hospital'), ('18546', 'County Medical Centre - Embu Ltd'), ('19843', 'County Medical Clinic (Kangai)'), ('19217', 'County Medical Clinic and Lab Services'), ('19153', 'County Medical Clinic and Lab Sevices'), ('19842', 'County Medical Health Clinic (Wanguru)'), ('18812', 'County Medicare Ltd (Maralal Nursing Home)'), ('18794', 'Couple Counselling Centre'), ('11978', 'Courtesy Community Based Health Services'), ('11293', 'Cowdray Dispensary'), ('14398', 'Crater Medical Centre'), ('18549', 'Creadis Htc Centre'), ('19486', 'Credible Health Centre'), ('19392', 'Crescent Medical Aid (Jamia Towers)'), ('12900', 'Crescent Medical Aid (Pangani)'), ('19634', 'Crescent Medical Aid Kenya Korogocho Clinic'), ('12899', 'Crescent Medical Aid Murang''a Road'), ('19685', 'Crescent-Davina Med Clinic'), ('10051', 'Batian Eye Clinic'), ('19125', 'Batian Flowers Clinic'), ('10052', 'Batian Laboratory Services'), ('14245', 'Batian Medical Centre'), ('19695', 'Batian Medical Centre Annex'), ('10053', 'Batian Medical Services Medical Clinic'), ('20382', 'Bay Leaf Health Center'), ('15806', 'Bay Way Medical Clinic'), ('10054', 'Bcj Medical Centre'), ('16667', 'Beacon of Hope Clinic (Kajiado)'), ('15807', 'Beberion Clinic'), ('18626', 'Beggs Clinic'), ('13500', 'Bekam Clinic'), ('14246', 'Bekibon Dispensary'), ('17085', 'Belgut Dispensary'), ('10055', 'Bellevue Health Centre'), ('13305', 'Benane Health Centre'), ('16786', 'Benga Bi Dispensary'), ('16185', 'Bengo Medical Clinic'), ('14247', '<NAME>'), ('10056', 'Bennedict XVI Dispensary'), ('16695', 'Benon Dispensary'), ('13501', '<NAME>linic'), ('10057', 'Bens Labs'), ('17270', 'Bensu Health Care Medical Clinic'), ('19873', 'Best Healthlife Clinic'), ('10058', 'Beta Care Nursing Home'), ('16533', 'Beta Medical & Skin Clinic'), ('17542', 'Bethania Clinic'), ('10059', 'Bethany Clinic'), ('10060', 'Bethany Family Clinic'), ('17432', 'Bethany Health Services Clinic'), ('12882', '<NAME>'), ('14249', 'Bethel Faith Dispensary'), ('10061', 'Bethel Medical Clinic'), ('14250', '<NAME>'), ('18935', 'Bethezda Medical Clinic'), ('14251', 'Bethsaida (AIC) Clinic (Nakuru)'), ('10063', 'Bethsaida (PCEA) Dispensary (Nyeri)'), ('19921', 'Bethsaida Catholic Dispensary'), ('17777', 'Bethsaida CFW Bamako'), ('10064', 'Bethsaida Clinic (Kirinyaga-Gathiga)'), ('10065', 'Bethsaida Clinic (Kirinyaga-Thiba)'), ('19051', 'Bethsaida Grandcure Medical Clinic'), ('10067', 'Bethsaida Medical Clinic (Gatundu)'), ('11948', 'Bethsaida Medical Clinic (Kangundo)'), ('11949', 'Bethwell Clinic'), ('19411', 'Betta Health Care'), ('14253', 'Better Health Services'), ('19166', 'Better Medical Clinic'), ('11251', 'Better off Knowing Stand Alone VCT Centre (Liverpo'), ('19053', 'Beula''s Clinic'), ('19709', 'Bevans Medical Clinic'), ('20374', 'Beyond the Bridge Vision VCT'), ('18813', 'Bgp Block 10Ba Base Camp Clinic'), ('12883', 'Biafra Lions Clinic'), ('12884', 'Biafra Medical Clinic'), ('19602', 'Bibirioni Health Centre'), ('14221', 'Bible Faith Church Medical Services Dispensary'), ('18532', 'Bidii Health Centre'), ('17900', 'Biftu Medical Clinic (Moyale)'), ('10070', 'Bigem Clinic'), ('14255', 'Bigot Medical Clinic'), ('16361', 'Bikeke Helth Centre'), ('16338', 'Bindura Dispensary'), ('18666', 'Bingwa Dispensary'), ('15163', 'Binyo Medical Clinic'), ('19788', 'Biotisho Ang'' Medical Clinic'), ('14256', 'Biretwa health centre'), ('14257', 'Biribiriet Dispensary'), ('14258', 'Birunda (Lyavo Project) Clinic'), ('11950', 'Bisan Biliqo Dispensary'), ('11955', 'Bishop Kioko Catholic Hospital'), ('14259', 'Bisil Health Centre'), ('16311', 'Bismillahi Medical Clinic'), ('19167', 'Bismillahi Medical Clinic (Garissa)'), ('13502', 'Bitare Dispensary'), ('18170', 'El Kambere Nomadic Clinic'), ('14427', 'Elangata Enterit Dispensary'), ('19329', 'Elatiai Health Ccare Services Medical Clinic'), ('13332', 'Elben Dispensary'), ('14428', 'Elburgon (PCEA) Dispensary'), ('14430', 'Elburgon Nursing Home'), ('14431', 'Elburgon Sub-District Hospital'), ('14964', 'Eldama Ravine (AIC) Health Centre'), ('14432', 'Eldama Ravine District Hospital'), ('19324', 'Eldama Ravine Medical Centre'), ('19322', 'Eldama Ravine Nursing Home'), ('13333', 'Eldas Health Centre'), ('11998', 'Eldera Dispensary'), ('16290', 'Eldere Dispensary'), ('14433', 'Eldo-Kit Clinic'), ('14434', 'Eldoret Airport Dispensary'), ('14435', 'Eldoret Hospital'), ('18978', 'Eldoret Medical Services'), ('17874', 'Eldoret MTC Clinic'), ('18669', 'Eldoret Rapha Medical Centre'), ('18861', 'Eldoret Regional Blood Bank'), ('17351', 'Eldume Dispensary'), ('19032', 'Elele Dispensary'), ('16443', 'Elele Nomadic Clinic'), ('14436', 'Elelea Health Centre'), ('11254', 'Bokole CDF Dispensary'), ('16706', 'Bokoli Base Clinic'), ('15808', 'Bokoli Hospital'), ('14260', 'Boma La Tumaini VCT'), ('11255', 'Bomani Dispensary'), ('12886', 'Bomas of Kenya Dispensary'), ('11256', 'Bombi Dispensary'), ('16534', 'Bombolulu Staff Clinic'), ('16184', 'Bombululu Medical Clinic'), ('14261', 'Bomet Health Centre'), ('19939', 'Bomet Youth Ffriendly Centre'), ('11259', 'Bomu Medical Centre (Likoni)'), ('18267', 'Bomu Medical Centre (Mariakani)'), ('11258', 'Bomu Medical Hospital (Changamwe)'), ('16441', 'Bona Medical Clinic'), ('14262', 'Bonchoge Dispensary'), ('13506', 'Bonde Dispensary'), ('14263', 'Bondeni Dispensary (Nakuru Central)'), ('14264', 'Bondeni Dispensary (Trans Nzoia West)'), ('14265', 'Bondeni Maternity'), ('13507', 'Bondo District Hospital'), ('13508', 'Bondo Medical Clinic'), ('18053', 'Bondo Nyironge Medical Clinic'), ('18096', 'Bondo Town VCT'), ('17582', 'AIC Ebenezer'), ('10283', 'AIC Gituru Dispensary'), ('17431', 'AIC Kalamba Dispensary'); INSERT INTO `facility_list` (`Facility_Code`, `Facility_Name`) VALUES ('14178', 'AIC Litein Mission Hospital'), ('17655', 'AIC Liten VCT'), ('12558', 'AIC Mukaa Dispensary'), ('20071', 'AIC Mununga Dispensary'), ('18439', 'AIC Parkview Dispensary'), ('20388', 'AIC Zion Medical Clinic'), ('12860', 'AIC Zombe Dispensary'), ('20030', 'Aina Onlus'), ('16350', 'Ainabkoi (RCEA) Health Centre'), ('19885', 'Ainamoi Dispensary'), ('14192', 'Ainamoi Health Centre'), ('11922', 'Air Port Medical Centre'), ('19817', 'Airborne No Twist Huduma Bora Clinic'), ('13469', 'Airport Dispensary (Kisumu)'), ('11204', 'Airport View Medical Clinic'), ('18038', 'Airstrip Medical Clinic (Moyale)'), ('20370', 'Airtech Medical Clinic'), ('14193', 'Aiyebo Dispensary'), ('18398', 'Ajam VCT'), ('13272', 'Ajawa Health Centre'), ('20430', 'Aka Khan Medical Clinic'), ('11923', 'Akachiu Health Centre'), ('13470', 'Akado Dispensary'), ('18097', 'Bondo University Clinic'), ('17481', 'Bonjoge Dispensary'), ('14266', 'Bonzina Medical Clinic'), ('10074', 'Boore Clinic'), ('13509', 'Bora Bora Clinic'), ('19962', 'Bora Imani Medical Clinic'), ('11260', 'Borabu Medical Clinic'), ('13510', 'Borabu Nursing Home'), ('14267', 'Borana Dispensary'), ('13511', 'Borangi Health Centre'), ('13512', 'Border Clinic'), ('14268', 'Border Medical Care'), ('13310', 'Bore Hole 11 Health Centre'), ('20309', 'Bore Singwaya Dispensary'), ('17762', 'Borehole Five Dispensary'), ('11952', 'Bori Dispensary'), ('13513', 'Boro Dispensary'), ('14269', 'Borrowonin Dispensary'), ('18853', 'Boru Haro Model Health Centre'), ('13514', 'Bosiango Health Centre'), ('13515', 'Bosongo Hospital'), ('14270', 'Bossei Dispensary'), ('18074', 'Bosto Dispensary'), ('13311', 'Bour-Algy Dispensary'), ('20112', 'Bouti Dispensary'), ('13516', 'Boya Nursing Home'), ('15809', 'Boyani Dispensary'), ('16811', 'Bp1 Dispensary'), ('17731', 'Brase Clinic and Eye Centre'), ('16208', 'Bravo Medical Clinic (Marsabit)'), ('10075', 'Breeze Hospital'), ('19537', 'Bridgeway Clinic'), ('19405', 'Bridging Out-Patient'), ('11954', 'Bright Clinic'), ('18271', 'Bristal Park Hospital'), ('18277', 'British American Tobacco Kenya Clinic'), ('19922', 'Brooks Health Care Medical Clinic'), ('12887', 'Brother andre Clinic'), ('18750', 'Brown''s Memorial Medical Centre'), ('11956', 'Bubisa Dispensary'), ('18120', 'Buburi Community Clinic'), ('15810', 'Buchangu Dispensary'), ('14271', 'Buchenge Dispensary'), ('15811', 'Budalangi Dispensary'), ('15812', 'Budonga Dispensary'), ('15813', 'Buduta Dispensary'), ('15814', 'Bugamangi Dispensary'), ('11262', 'Bughuta Health Centre'), ('15815', 'Bugina Health Centre'), ('13517', 'Bugumbe Health Centre'), ('19645', 'Afya Medicare Clinic'), ('13271', 'Afya Medicare Clinic (Wajir East)'), ('11921', 'Afya Njema Clinic'), ('14188', 'Afya Njema Medical Clinic'), ('18021', 'Afya Njema Medical Clinic (Nyeri North)'), ('18428', 'Afya Nursing Home (Moyale)'), ('20244', 'Afya Royal Clinics'), ('19764', 'Afya Yako Medical Clinic'), ('19082', 'Afya Yetu Medical Centre'), ('19397', 'Afyamax Medical & Centre Dental'), ('20065', 'Aga Khan Clinic'), ('20236', 'Aga Khan Clinic (Eastleigh)'), ('18223', 'Aga Khan Clinic Kitengela'), ('19457', 'Aga Khan Greenspam Medical Centre'), ('12867', 'Aga Khan Hospital'), ('20390', 'Aga Khan Hospital (Juja)'), ('13465', 'Aga Khan Hospital (Kisumu)'), ('11203', 'Aga Khan Hospital (Mombasa)'), ('20176', 'Aga Khan Medical Centre Kericho'), ('19464', 'Aga Khan Reinsurance Plaza Lab'), ('19223', 'Aga Khan University Hospital - Embu '), ('12868', 'Aga Khan University Hospital (Buruburu)'), ('20404', 'Aga Khan University Hospital (Capital Centre)'), ('19335', 'Aga Khan University Hospital Clinic (Naivasha)'), ('18535', 'Adventist Centre For Care and Support (Westlands)'), ('18382', 'Afraha Maternity and Nursing Home'), ('13268', 'Africa Inland Church Dispensary'), ('20090', 'African Divine Church-Org'), ('20320', 'African Muslim Agency- Matsangoni'), ('12865', 'Afwan Medical Centre'), ('17335', 'Afwein Dispensary'), ('19162', 'Afwene Clinic'), ('17577', 'Afya Bora Clinic'), ('11919', 'Afya Bora Clinic (Meru South)'), ('17819', 'Afya Bora Clinic (Mutomo)'), ('10011', 'Afya Bora Clinic (Mwea)'), ('19966', 'Afya Bora Clinic Karia'), ('19515', 'Afya Bora Health Care'), ('19794', 'Afya Bora Health Clinic'), ('19662', 'Afya Bora Mc'), ('16411', 'Afya Bora Medical Clinic'), ('16491', 'Afya Bora Medical Clinic (CFW Clinic Gichugu)'), ('11200', 'Afya Bora Medical Clinic (Malindi)'), ('10007', 'Afya Bora Medical Clinic (Muchagara)'), ('10008', 'Afya Bora Medical Clinic (Nyeri South)'), ('14186', 'Afya Bora Medical Clinic (Turkana Central)'), ('19551', 'Afya Bora Medical Clinic (Westlands)'), ('11201', 'Afya Clinic'), ('20205', 'Aga Khan University Hospital Kiambu Clinic'), ('18738', 'Aga Khan University Hospital -New Machakos Medical'), ('17857', 'Aga Khan University Hospital- Nyeri Medical Centre'), ('14189', 'Aga Khan University Hospital O/R Clinic'), ('20226', 'Agakhan Medical Centre'), ('10016', 'Agape Medical Services'), ('13466', 'Agawo Dispensary'), ('14190', 'Agc Baby Health Centre'), ('13467', 'Agenga Dispensary'), ('15790', 'Agenga Dispensary (Samia)'), ('20254', 'Agha Khan University Hospital (Kikuyu Medical Centre)'), ('16452', 'Agma Clinic'), ('19815', 'Agro Chemical Dispensary'), ('10017', 'Aguthi Dispensary'), ('10018', 'Ahadi Maternity Services'), ('16516', 'Ahadi Medical Clinic'), ('18291', 'Ahero Medical Centre'), ('14191', 'Ahero Medical Clinic'), ('13468', 'Ahero Sub-District Hospital'), ('18804', 'AHF Soko Clinic'), ('15791', 'Ahmadiya Hospital'), ('18835', 'AIC Biribiriet Dispensary'), ('12093', 'AIC Dispensary (Isiolo)'), ('16379', 'Elementeita Dispensary'), ('11999', 'Elgade Dispensary'), ('14437', 'Elgeyo Boader Dispensary'), ('17229', 'El-Golicha Dispensary'), ('14438', 'Elgon View Hospital'), ('15871', 'Elgon View Medical Cottage'), ('19064', 'Elim Dental Clinic'), ('16883', 'Elim Family Community Care'), ('19517', 'Elimu Medical Clinic'), ('18146', 'Elis Medicare'), ('19836', 'Elite Clinic'), ('14439', 'Elite Medical Clinic'), ('18031', 'Elite Medical Clinic (Bungoma East)'), ('19708', 'Elite Medical Clinic (Mathira West)'), ('14440', 'Eliye Springs (AIC) Dispensary'), ('18846', 'Eliye Springs Community Dispensary'), ('12001', 'El-Molo Bay Dispensary'), ('13334', 'Elnoor Dispensary'), ('17230', 'El-Ram Dispensary'), ('18361', 'Eluche'), ('15872', 'Elukhambi Dispensary'), ('13335', 'Elwak District Hospital'), ('19272', 'Elwak Health Centre'), ('16714', 'Elwangale Health Centre'), ('15873', 'Elwasambi Dispensary'), ('15874', 'Elwesero Dispensary'), ('15828', 'Bungoma District Hospital'), ('15829', 'Bungoma Medical Centre'), ('20323', 'Bungoma west Medical Services'), ('14272', 'Bungwet Dispensary'), ('13339', 'Bura District Hospital'), ('11264', 'Bura Health Centre'), ('11263', 'Bura Health Centre (Taita Taveta)'), ('18312', 'Bura Health Centre Taita'), ('11265', 'Bura Mission Clinic'), ('17075', 'Bura Nomadic'), ('17870', 'Burabor Dispensary'), ('13313', 'Burder Health Centre'), ('17035', 'Burduras Health Centre'), ('18830', 'Burgabo Dispensary (Chalbi)'), ('14273', 'Burgei Dispensary'), ('10076', 'Burguret Dispensary'), ('15830', 'Burinda Dispensary'), ('19243', 'Burjon Dispensary'), ('17228', 'Burmayo Dispensary'), ('14274', 'Burnt Forest Catholic Dispensary'), ('16342', 'Burnt Forest Medical Clinic'), ('16347', 'Burnt Forest Rhdc (Eldoret East)'), ('18033', 'Burqa Medical Clinic (Moyale)'), ('16313', 'Buruburu Dispensary'), ('18273', 'Buruburu Friends Clinic'), ('17886', 'Al-Amin Medical Clinic'), ('16299', 'Al-Ansar Medical Clinic'), ('13274', 'Al-Aqsa Medical Clinic'), ('17899', 'Albilal Medical Clinic (Moyale)'), ('16530', 'Al-Bir Medical Centre'), ('11210', 'Al-Bir Medical Centre (Kilindini)'), ('19344', 'Aldai Medical Services'), ('16256', 'Alfa Clinic'), ('11924', 'Alfalah Nursing Home'), ('19608', 'Al-Fallah Medical Clinic'), ('13275', 'Al-Faruq Dispensary'), ('18998', 'Al-Faruq Medical Clinic'), ('19629', 'Al-Firdaus Health Care'), ('13276', 'Al-Furaqan Clinic'), ('16801', 'Al-Gadhir Clinic'), ('18009', 'Algadir Medical Clinic'), ('18982', 'Alhamdu Medical Clinic'), ('13277', 'Al-Hamdu Medical Clinic'), ('13278', 'Al-Haqq Medical Clinic'), ('18956', 'Al-Hidaya Clinic'), ('19031', 'Alhidaya Medical Clinic'), ('12869', 'Alice Nursing Home'), ('20249', 'Aliki Medical Centre'), ('17012', 'Alikune Dispensary'), ('13281', 'Alimaow Health Centre'), ('13282', 'Alinjugur Health Centre'), ('10021', 'All Day Medical Clinic'), ('17794', 'All Nation Medical Clinic'), ('15793', 'All Saints Musaa'), ('15794', 'Alliance Clinic'), ('17847', 'Alliance Medical Centre'), ('18999', 'Alliance Medical Clinic'), ('19822', 'Alliance Medical Clinic (Kirinyaga)'), ('13283', 'Al-Maaruf Clinic'), ('13284', 'Al-Maqdis ENT Clinic'), ('16557', 'Almed Health Products'), ('19653', 'Alms House Dispensary'), ('18404', 'Al-Mumtaz Medical Clinic'), ('13285', 'Al-Mustaqim Clinic'), ('16294', 'Alnas Medical Clinic'), ('19000', 'Alnasar Medical Clinic'), ('18067', 'Alpha Community Health Clinic (Migori)'), ('19748', 'Alpha Dental Services'), ('10022', 'Alpha Family Health Care'), ('19880', 'Alpha Medical Agency'), ('16321', 'Alpha Medical Clinic'), ('19321', 'Alpha Medical Clinic (Koibatek)'), ('19040', 'Alpha Medical Clinic Mile Tisa'), ('19356', 'Alphine Dental Centre (Kencom Hse)'), ('19461', 'Al-Ramah Healthcare'), ('13287', 'Al-Siha Nursing Home'), ('13472', 'Alum Beach Dispensary'), ('13473', 'Aluor Mission Health Centre'), ('15795', 'Alupe Sub-District Hospital'), ('10023', 'Ama (Africa Muslim Agency) Clinic'), ('19215', 'Amaal Annex Nursing'), ('15796', 'Amagoro Nursing Home'), ('14198', 'Amakuriat Dispensary'), ('16308', 'Amal Medical Clinic'), ('20213', 'Amalya Medical Centre'), ('10024', 'Amani Clinic'), ('19001', 'Amani Clinic (Garissa)'), ('19846', 'Amani MC'), ('13474', 'Amani Medical Centre (Suneka)'), ('20119', 'Amani Medical Clinic'), ('11216', 'Amani Medical Clinic (Changamwe)'), ('11925', 'Amani Medical Clinic (Kambu)'), ('11217', 'Amani Medical Clinic (Kilifi)'), ('11218', 'Amani Medical Clinic (Likoni)'), ('11219', 'Amani Medical Clinic (Malindi)'), ('19075', 'Amani Medical Clinic (Meru)'), ('18718', 'Amani Medical Clinic (Meru)'), ('17561', 'Amani Medical Clinic (Murungaru)'), ('17559', 'Amani Medical Clinic Magumu'), ('18921', 'Amani Medical Clinic Yatta'), ('17624', 'Amani VCT'), ('15797', 'Amase Dispensary'), ('13475', 'Amatierio Dispensary'), ('17797', 'Amaya/Plesian Dispensary'), ('19656', 'Amazing Grace M C'), ('12888', 'Buruburu Medical Clinic'), ('16722', 'Burutu Dspensary'), ('15831', 'Busembe Dispensary'), ('15832', 'Bushiangala Health Centre'), ('15833', 'Bushiri Health Centre'), ('15834', 'Busia District Hospital'), ('18126', 'Busia Trailer Park Clinic'), ('15835', 'Busibwabo Dispensary'), ('18208', 'Busieso Dispensary'), ('13314', 'Bute District Hospital'), ('19870', 'Bute Medical Clinic'), ('15836', 'Butere District Hospital'), ('18939', 'Butere Iranda Health Centre'), ('14276', 'Butiik Dispensary'), ('20043', 'Butingo Dispensary'), ('11958', 'Butiye Dispensary'), ('15837', 'Butonge Dispensary'), ('15838', 'Butula Mission Health Centre'), ('16559', 'Buuri Chemist / Laboratory'), ('17081', 'Buwa'), ('15839', 'Buyangu Health Centre'), ('20188', 'Buyemi Dispensary'), ('11266', 'Bwagamoyo Dispensary'), ('15840', 'Bwaliro Dispensary'), ('13519', 'Bware Dispensary'), ('14205', 'Angata Health Centre'), ('17274', 'Angata Nanyokie Dispensary'), ('18272', 'Angaza VCT'), ('18627', 'Angelic Medical Centre'), ('18923', 'Angels Health Services'), ('13479', 'Ang''iya Dispensary'), ('15800', 'Angurai Health Centre'), ('14206', 'Anin Dispensary'), ('13480', 'Anjego Dispensary'), ('18871', 'Ankamia Dispensary'), ('10029', 'Anmer Dispensary'), ('16323', 'Annet Dispensary'), ('13481', 'Annex Clinic (Kenyenya)'), ('19404', 'Annex Health Care'), ('14207', 'Annex Hospital (Nakuru)'), ('10031', 'Annex Laboratory'), ('19904', 'Annex Medical Clinic'), ('10032', 'Annex Medical Clinic (Muranga North)'), ('14208', 'Annex Medical Clinic (Trans Nzoia West)'), ('18816', 'Annointed Medical Clinic'), ('10033', 'Annunciation Catholic Dispensary'), ('11930', 'Anona Dispensary'), ('11222', 'Ansar Medical Clinic'), ('18618', 'Antodevi Medical Clinic'), ('10034', '<NAME> Clinic'), ('17718', 'Antubangai Catholic Dispensary'), ('17068', 'Antubetwe Njoune Dispensary'), ('17067', 'Antubochiu Dispensary'), ('13482', 'Anyuongi Dispensary'), ('17649', 'Ap Buru Buru Disp'), ('15801', 'Ap Line Dispensary'), ('11931', 'Apdk Dispensary (Machakos)'), ('16872', 'Apex Clinic'), ('16492', 'Apha Laboratory'), ('18671', 'Aphia Disc 1 Nanyuki Transport'), ('20022', 'Aphia Plus Marps Dic Nanyuki'), ('18790', 'Aphiaplus Drop-In Centre (Naivasha)'), ('15802', 'Apokor Dispensary'), ('14209', 'Aposta Dispensary'), ('15803', 'Apostles Clinic'), ('18934', 'Appex Medical Clinic'), ('15804', 'Approved Dispensary'), ('11932', 'Approved School Dispensary (Machakos)'), ('12871', 'Aptc Health Centre'), ('11933', 'Apu Dispensary'), ('17572', 'Aqua Medical Clinic'), ('14210', 'Aquilla Farm Medical Clinic'), ('13290', 'Arabia Health Centre'), ('14211', 'Arama Dispensary'), ('19660', 'Arara ENT Clinic'), ('19761', 'Arara ENT Clinic'), ('13291', 'Arbajahan Health Centre'), ('16286', 'Arbajahan Nomadic Mobile Clinic'), ('13292', 'Arbaqueranso Dispensary'), ('10037', 'Arcade Medical Clinic'), ('10036', 'Arcade Medical Clinic (Ruiru)'), ('14212', 'Archers Post Health Centre'), ('17202', 'Aren Medical Clinic'), ('17977', 'Aren Medical Clinic'), ('16810', 'Aresa Dispensary'), ('13293', 'Argane Dispensary'), ('18319', 'Arimi Clinic and Laboratory'), ('14213', 'Arimi Dispensary'), ('13484', 'Arito Langi Dispensary'), ('14197', 'Arjijo Dispensary'), ('18814', 'Armstrong'), ('13485', 'Aro (SDA) Dispensary'), ('13486', 'Arombe Dispensary'), ('17705', 'Arosa Dispensary'), ('14214', 'Arpollo Dispensary'), ('14215', 'Arroket Dispensary'), ('14216', 'Arror Health Centre'), ('19756', 'Bwayi Dispensary'), ('14277', 'Bwena Dipensary'), ('17894', 'Bwiti (Tiomin) Dispensary'), ('10077', 'By Faith Clinic (Kirinyaga)'), ('10078', 'By Faith Clinic (Thika)'), ('19229', 'By Faith Medical Centre'), ('11959', 'By Faith Medical Clinic'), ('10079', 'By Grace Medical (Kutus) Clinic'), ('20014', 'Bygrace Medical Clinic'), ('17763', 'California Medical Clinic'), ('17978', 'Calvary Family Health Care Centre'), ('17812', 'Calvary Medical Clinic'), ('14278', 'Camp Brethren Medical Clinic'), ('11269', 'Camp David Medical Clinic'), ('12889', 'Cana Family Life Clinic'), ('14279', 'Canaan (ACK) Medical Clinic'), ('15841', 'Canaan Clinic (Matete)'), ('12890', 'Canaan Health Providers (Nairobi)'), ('11270', 'Canaan Medical Clinic'), ('10080', 'Canan Medical Clinic'), ('16176', 'Care Medical Clinic'), ('17563', 'Care Medical Clinic (Geta Bush)'), ('17562', 'Care Medical Clinic (Munyaka)'), ('20016', 'Careplus Medical Services'), ('18006', 'Cargo Human Care Clinic'), ('10041', 'Athi Dispensary'), ('11934', 'Athi Kamunyuni Dispensary'), ('11935', 'Athi River Community Hospital'), ('11936', 'Athi River Health Centre'), ('11937', 'Athi River Medical Services'), ('13295', 'Athibohol Dispensary'), ('19185', 'Athirunjine Runjine Dispensary'), ('14220', 'Atiar Dispensary'), ('10042', 'Atlas Medical Clinic'), ('16866', 'Avarende Medical Clinic'), ('16531', 'Avenue Health Care'), ('19462', 'Avenue Health Care (Makadara)'), ('13490', 'Avenue Health Care Clinic'), ('18817', 'Avenue Health Care Nakuru'), ('19083', 'Avenue Health Care Ongata Rongai'), ('12874', 'Avenue Hospital'), ('20123', 'Avenue Hospital Kisumu'), ('13491', 'Awasi Mission Dispensary'), ('18081', 'Awendo Jiwdendi'), ('13492', 'Awendo Sub-District Hospital'), ('18783', 'Axis Nursing Home'), ('13296', 'Ayan Clinic'), ('20475', 'Ayatya Dispensary'), ('11232', 'Azimio Medical Centre'), ('19413', 'Acacia Medical Centre (Nairobi)'), ('14184', 'Acacia Medicare Centre'), ('18965', 'Acc&S Kariua Dispensary'), ('19467', 'Access Afya'), ('12791', 'Acef Ena Health Centre'), ('11918', 'ACK Dispensary (Isiolo)'), ('17980', 'ACK Kanunga Dispensary'), ('19651', 'ACK Mwingi CHBC Clinic'), ('19704', 'ACK Nyandarua Medical Clinic'), ('17473', 'ACK Tumaini Medical Clinic'), ('11195', 'Acode Medical Clinic Maungu'), ('19520', 'Aculaser Institute'), ('13266', 'Adadijolle Dispensary'), ('11196', 'ADC Danisa Dispensary'), ('13267', 'Ademasajida Dispensary'), ('20357', 'Adenawale Dispensaty'), ('13463', 'Adiedo Dispensary'), ('13464', 'Administration Police Dispensary (Kisumu East)'), ('18171', 'Administration Police Senior Staff College Dispens'), ('20479', 'Adoma Medical Clinic'), ('18793', 'Adora Children Clinic'), ('11198', 'Adu Dispensary'), ('14185', 'Adurkoit Dispensary'), ('18372', 'Advent Med & Dentist Care Centre'), ('14187', 'Afya Frank Medical Clinic'), ('12546', 'Mpukoni Health Centre'), ('11651', 'Mrima (Catholic) Dispensary'), ('19606', 'Mrima CDF Health Cenre'), ('11225', 'Mrs - 77 Artillery Battallion (Mariakani)'), ('11652', 'Mrughua Dispensary'), ('11655', 'Msambweni District Hospital'), ('13828', 'Msare Health Centre'), ('11656', 'Msau Dispensary'), ('15238', 'Msekekwa Health Centre'), ('20049', 'Msf- Green House Clinic'), ('20050', 'Msf- Lavender House Clinic'), ('17651', 'Msf Olympic Centre'), ('20300', 'Mshongoleni Community Dispensary'), ('11657', 'Msikiti Noor Medical Clinic'), ('18055', 'Msomi Complex Medical Clinic'), ('11658', 'Msulwa Dispensary'), ('11659', 'Msumarini Dispensary'), ('19742', 'Mt Elgon Annex Clinics'), ('19857', 'Mt Elgon Annex Clinics -Dr Manuthu'), ('19385', 'Mt Elgon Clinic'), ('16025', 'Mt Elgon District Hospital'), ('15239', 'Mt Elgon Hospital'), ('15240', 'Mt Elgon National Park Dispensary'), ('19715', 'Mt Everest Medical Clinic'), ('17277', 'Muruangai Dispensary'), ('16048', 'Murudef Clinic'), ('16613', 'Murugu Herbal Clinic'), ('16999', 'Muruguru Dispensary'), ('10783', 'Muruguru Medical Clinic (Nyeri North)'), ('10784', 'Muruguru Medical Clinic (Nyeri South)'), ('10785', 'Muruka Dispensary'), ('17033', 'Muruku Dispensary'), ('10786', 'Murungaru Health Centre'), ('11653', 'Muryachakwe Dispensary'), ('12582', 'Musalala Dispensary'), ('16049', 'Musanda (ACK) Clinic'), ('17507', 'Musau Medical Clinic'), ('20042', 'Musavani Dispensary'), ('17501', 'Musco Clinic'), ('18507', 'Muselele'), ('16865', 'Musembe Dispensary'), ('16051', 'Musembe Dispensary (Lugari)'), ('17447', 'Musengo Medical Clinic'), ('20433', 'Muserechi Dispensary'), ('12583', 'Museve Dispensary'), ('16486', 'Musibiriri Dispensary'), ('17162', 'Musingini Dispensary'), ('16052', 'Musitinyi Dispensary'), ('18434', 'Muska Medical Centre'), ('15275', 'Nadoto Dispensary'), ('18099', 'Nadung''a Dispensary'), ('10818', 'Nahashon Mwangi Medical Clinic'), ('10819', 'Naidu Hospital'), ('15276', 'Naikara Dispensary'), ('17383', 'Naikuriu Dispensary'), ('13107', 'Naioth Medical Clinic'), ('15277', 'Nairagie-Enkare Health Centre'), ('15278', 'Nairasirasa Dispensary'), ('17280', 'Nairimirimo Dispensary'), ('13108', 'Nairobi Deaf (Liverpool)'), ('18394', 'Nairobi Earc St Anne Medical Clinic'), ('20264', 'Nairobi East Hospital Ltd'), ('19580', 'Nairobi Eye Associates'), ('17619', 'Nairobi Homes Clinic'), ('13110', 'Nairobi Hospital'), ('13111', 'Nairobi Outpatient Centre'), ('19477', 'Nairobi Outreach Services Trust'), ('12632', 'Nairobi Pathologist Clinic'), ('13161', 'Nairobi Remand Prison Health Centre'), ('13113', 'Nairobi South Clinic'), ('13112', 'Nairobi South Hospital'), ('13114', 'Nairobi West Chidren Clinic'), ('11661', 'Mt Harmony Clinic'), ('10738', 'Mt Kenya (ACK) Hospital'), ('16611', 'Mt Kenya Herbal Centre'), ('19766', 'Mt Kenya Junior Academy'), ('18015', 'Mt Kenya Kabiruini Medical Clinic'), ('10741', 'Mt Kenya Narumoru Medical Clinic'), ('19765', 'Mt Kenya Senior Academy'), ('10739', 'Mt Kenya Sub-District Hospital'), ('15241', 'Mt Longonot Hospital'), ('10740', 'Mt Sinai Nursing Home'), ('17269', 'Mt Zion Community Health Clinic'), ('17568', 'Mt Zion Mission Medical Clinic'), ('20373', 'Mt. Pleasant Medical Clinic'), ('11662', 'Mtaa Dispensary'), ('11663', 'Mtaani Clinic'), ('17455', 'Mtaani VCT'), ('11664', 'Mtangani Medical Clinic'), ('15242', 'Mtaragon Health Centre'), ('19594', 'Mtaro Estate Dispensary and Family Planning'), ('13829', 'MTC Clinic (Kisumu)'), ('11665', 'MTC Mombasa'), ('11666', 'Mtepeni Dispensary'), ('17500', 'Mteremuko Medical Clinic'), ('12547', 'Mtito andei Sub District'), ('11667', 'Mtondia Dispensary'), ('11668', 'Mtondia Medical Clinic'), ('11669', 'Mtongwe (MCM) Dispensary'), ('18945', 'Mtoni Medical Clinic'), ('11670', 'Mtopanga Clinic'), ('18309', 'Mtoroni Dispensary'), ('11672', 'Mtwapa Health Centre'), ('11673', 'Mtwapa Nursing Home'), ('12548', 'Mua Hills Dispensary'), ('17603', 'Muamba Dispensary'), ('17816', 'Muangeni Dispensary'), ('20284', 'Muangeni Dispensary (Mwingi)'), ('18066', 'Mubachi Dispensary'), ('18127', 'Mubwekas Medical Clinic'), ('12549', 'Muchagori Dispensary'), ('18753', 'Mucharage Mlc'), ('17333', 'Muchatha Dispensary'), ('19831', 'Muchatha Medical Clinic'), ('13830', 'Muchebe Dispensary'), ('18269', 'Muchonoke Dispensary'), ('15243', 'Muchukwo Dispensary'), ('16476', 'Muchuro Dispensary'), ('11674', 'Mudzo Medical Clinic'), ('12550', 'Mufu Dispensary'), ('18444', 'Mufutu Medical Clinic'), ('17510', 'Muga Medical Clinic'), ('16272', 'Mugabo Dispensary'), ('18779', 'Mugai Dispensary'), ('15244', 'Mugango Dispensary'), ('12552', 'Mugas Clinic'), ('10744', 'Mugeka Dispensary'), ('19648', 'Mugi Medical Clinic'), ('10745', 'Mugoiri Dispensary'), ('17597', 'Mugomari Dispensary'), ('11675', 'Mugos Clinic'), ('12551', 'Mugui Consolata Clinic'), ('12553', 'Mugui Dispensary'), ('16507', 'Mugumo Clinic/Laboratory'), ('19288', 'Mugumo Medical'), ('15245', 'Mugumoini Dispensary (Kipkelion)'), ('10748', 'Mugumoini Dispensary (Muranga South)'), ('10747', 'Mugumo-Ini Medical Clinic'), ('16612', 'Muguna West Clinic'), ('10749', 'Mugunda Dispensary'), ('10750', 'Mugunda Mission Dispensary'), ('10751', 'Muguo Clinic'), ('15246', 'Mugurin Dispensary'), ('18391', 'Mugutha (CDF) Dispensary'), ('12555', 'Mugwee Clinic'), ('16026', 'Muhabini Medical Clinic'), ('16027', 'Muhaka Disensary'), ('11676', 'Muhaka Dispensary'), ('18788', 'Muhamarani Dispensary'), ('13831', 'Muhoroni Sub-District Hospital'), ('13832', 'Muhoroni Sugar Company (Musco) Dispensary'), ('15247', 'Muhotetu Dispensary'), ('10752', 'Muhoya Medical Clinic'), ('13833', 'Muhuru Health Centre'), ('12556', 'Mui Dispensary'), ('19848', 'Muiywek Dispensary'), ('12557', 'Mujwa Dispensary'), ('20306', 'Mukameni Dispensary'), ('18536', 'Mukanga Dispensary (Muranga North)'), ('12559', 'Mukangu (ACK) Dispensary'), ('16387', 'Mukangu Health Centre'), ('10753', 'Mukarara Community Dispensary'), ('17057', 'Mukarara Dispensary'), ('10754', 'Mukarara Medical Clinic'), ('18963', 'Mukerenju Dispensary'), ('10755', 'Mukeu (AIC) Dispensary'), ('16028', 'Mukhe Dispensary'), ('16029', 'Mukhobola Health Centre'), ('20046', 'Mukhweso Clinic'), ('10756', 'Mukindu Dispensary'), ('10757', 'Mukoe Dispensary'), ('16863', 'Mukong''a Dispensary'), ('16399', 'Mukorombosi Dispensary'), ('12560', 'Mukothima Health Centre'), ('13407', 'Muktar Dada Medical Clinic'), ('12561', 'Mukui Health Centre'), ('16030', 'Mukumu Hospital'), ('10758', 'Mukungi Dispensary'), ('16435', 'Mukunike Dispensary'), ('10759', 'Mukuria Dispensary'), ('13100', 'Mukuru Crescent Clinic'), ('18463', 'Mukuru Health Centre'), ('13101', 'Mukuru Mmm Clinic'), ('10760', 'Mukurwe (PCEA) Medical Clinic'), ('10761', 'Mukurwe Dispensary'), ('10763', 'Mukurweini District Hospital'), ('10762', 'Mukurweini Medical Clinic'), ('12562', 'Mukusu Dispensary'), ('15249', 'Mukutani Dispensary (East Pokot)'), ('12563', 'Mukuuni Dispensary'), ('12564', 'Mukuuri Dispensary'), ('16031', 'Mukuyu Dispensary'), ('10764', 'Mukuyu Medical Clinic'), ('12565', 'Mukuyuni Health Centre'), ('13834', 'Mulaha Dispensary'), ('12566', 'Mulango (AIC) Health Centre'), ('12567', 'Mulangoni Dispensary'), ('16032', 'Mulele Dispensary'), ('16482', 'Mulembe Clinic'), ('18815', 'Mulembe Medical Clinic'), ('15250', 'Mulemi Maternity Home'), ('18863', 'Mulika Dispensary'), ('16924', 'Muliluni Dispensary'), ('18451', 'Mulimani Medical Clinic'), ('16936', 'Mulinde Dispensary'), ('15251', 'Mulot Catholic Dispensary'), ('18519', 'Mulot Dispensary'), ('17740', 'Mulot Health Centre'), ('19737', 'Mulot VCT'), ('13018', 'Multi Media University Dispensary'), ('18377', 'Multipurpose Village Health Care Centre'), ('16416', 'Mulukaka Clinic'), ('12568', 'Mulundi Dispensary'), ('12569', 'Mulutu Mission Dispensary'), ('16033', 'Mulwanda Dispensary'), ('10766', 'Mumbuini Dispensary'), ('16034', 'Mumbule Dispensary'), ('12570', 'Mumbuni Dispensary (Maara)'), ('12571', 'Mumbuni Dispensary (Makueni)'), ('12572', 'Mumbuni Dispensary (Mwala)'), ('12573', 'Mumbuni Dispensary (Mwingi)'), ('12574', 'Mumbuni Nursing Home'), ('16036', 'Mumias Maternity'), ('16035', 'Mumias Model Health Centre'), ('16038', 'Mumias Sugar Clinic'), ('18714', 'Mummy Medical Clinic'), ('16039', 'Mummy''s Medical Clinic'), ('12575', 'Mumo (AIC) Health Centre'), ('12576', 'Mumoni Dispensary'), ('18951', 'Mumui Dispensary'), ('20062', 'Mundika Maternity & Nursing Home'), ('16040', 'Mundoli Health Centre'), ('17823', 'Mundoro Community'), ('18658', 'Mundoro Community Dispensary'), ('10767', 'Mundoro Medical Clinic'), ('13102', 'Mundoro Medical Clinic Dandora'), ('12577', 'Mundu Ta Mundu Clinic'), ('10768', 'Mung''ang''a (ACK) Dispensary'), ('16041', 'Mung''ang''a Dispensary'), ('17309', 'Mungaria Dispensary'), ('10769', 'Mungu Aponya Medical Clinic'), ('16042', 'Mung''ung''u Dispensary'), ('15252', 'Mungwa Dispensary'), ('11677', 'Municipal Health Centre'), ('16043', 'Munongo Dispensary'), ('16044', 'Munoywa Dispensary'), ('10770', 'Mununga Dispensary'), ('10771', 'Mununga Health Clinic'), ('16807', 'Munyaka Dispensary'), ('10772', 'Munyaka Medical Clinic'), ('10773', 'Munyange (AIPCA) Dispensary'), ('17883', 'Munyange Gikoe Dispensary'), ('16045', 'Munyanza Nursing Home'), ('10774', 'Munyu Health Centre'), ('10775', 'Munyu Medical Clinic'), ('10776', 'Munyu-Ini Dispensary'), ('16046', 'Munyuki Dispensary'), ('12578', 'Muono Dispensary'), ('17523', 'Mur Malanga Dispensary'), ('15253', 'Muramati Dispensary'), ('12579', 'Murambani Dispensary'), ('10777', 'Murang''a District Hospital'), ('16431', 'Murantawa Dispensary'), ('10778', 'Murarandia Dispensary'), ('10779', 'Murarandia Medical Centre'), ('19732', 'Murarandia Medical Clinic'), ('10780', 'Mureru Dispensary'), ('15254', 'Murgor Hills Dispensary'), ('15255', 'Murgusi Dispensary'), ('16047', 'Murhanda Medical Clinic'), ('15256', 'Muricho Dispensary'), ('17191', 'Murindoku Dispensary'), ('10781', 'Murinduko Health Centre'), ('12580', 'Muringombugi Clinic'), ('10782', 'Muriranjas Sub-District Hospital'), ('12581', 'Muriri Clinic'), ('15257', 'Murkwijit Dipensary'), ('20055', 'Murkwijit Dispensary'), ('19012', 'Murpus Medical Clinic'), ('15260', 'Muskut Health Centre'), ('18660', 'Musoa SDA Dispensary'), ('16053', 'Musoli Health Clinic'), ('16938', 'Musovo Dispensary'), ('16247', 'Musukini Dispensary'), ('18365', 'Mutanda Community Dispensary'), ('18565', 'Mutanda Dispensary'), ('15261', 'Mutara Dispensary'), ('15262', 'Mutarakwa Dispensary (Molo)'), ('10788', 'Mutarakwa Dispensary (Nyandarua South)'), ('19500', 'Mutathamia Medical Clinic'), ('20401', 'Mutati Community Dispensary'), ('13103', 'Muteithania Medical Clinic'), ('19881', 'Mutelai Dispensary'), ('12584', 'Mutembuku Dispensary'), ('16222', 'Mutethia Clinic'), ('18931', 'Mutethia Clinic Magutuni'), ('17661', 'Mutethia Medical Clinic'), ('10789', 'Mutethia Medical Clinic (Nyeri South)'), ('12585', 'Mutethya Medical Clnic'), ('12586', 'Mutha Health Centre'), ('10790', 'Muthaara Dispensary'), ('17450', 'Muthale East Medical Clinic'), ('12587', 'Muthale Mission Hospital'), ('18899', 'Muthale Mission Hospital Satelite Clinic'), ('12588', 'Muthambi Dispensary'), ('12589', 'Muthambi Health Centre'), ('12590', 'Muthanthara Dispensary'), ('12591', 'Muthara Sub-District Hospital'), ('15263', 'Muthegera Dispensary'), ('10791', 'Mutheru Dispensary'), ('12592', 'Muthesya Dispensary'), ('12593', 'Muthetheni Health Centre'), ('12594', 'Muthetheni Mission Health Centre'), ('10792', 'Muthinga Medical Clinic'), ('16175', 'Muthithi (PCEA) Dispensary'), ('10793', 'Muthithi Dispensary'), ('18628', 'Muthua Dispensary'), ('17606', 'Muthue Dispenary'), ('18673', 'Muthungue Dispensary'), ('13104', 'Muthurwa Clinic'), ('10794', 'Muthuthiini Dispensary'), ('10795', 'Muthuthiini Medical Clinic'), ('12595', 'Muthwani (AIC) Dispensary'), ('12596', 'Mutiluni Dispensary'), ('18707', 'Mutindwa Clinic and Lab'), ('12597', 'Mutindwa Dispensary'), ('16615', 'Mutindwa Laboratory'), ('16616', 'Mutindwa Med Clinic'), ('16054', 'Muting''ong''o Dispensary'), ('18132', 'Mutini Dispensary'), ('17379', 'Mutiokiama Health Centre'), ('12598', 'Mutionjuri Health Centre'), ('10796', 'Mutira (ACK) Dispensary'), ('10797', 'Mutira Laboratory'), ('18349', 'Mutithi Dispensary'), ('10798', 'Mutithi Health Centre'), ('12599', 'Mutito Catholic Dispensary'), ('10799', 'Mutitu Community Dispensary'), ('12600', 'Mutitu Dispensary'), ('10800', 'Mutitu Gikondi Medical Clinic'), ('12601', 'Mutitu Sub-District Hospital'), ('12602', 'Mutituni Dispensary'), ('12603', 'Mutomo Health Centre'), ('18911', 'Mutomo Health Clinic'), ('20341', 'Mutomo Medical Services'), ('12604', 'Mutomo Mission Hospital'), ('19932', 'Mutonya CDF Dispensary'), ('16055', 'Mutsetsa Dispensary'), ('19237', 'Mutuati Catholic Hospital'), ('12606', 'Mutuati Nursing Home'), ('12605', 'Mutuati Sub-District Hospital'), ('13105', 'Mutuini Sub-District Hospital'), ('18102', 'Mutukanio ACK Dispensary'), ('12607', 'Mutukya Dispensary'), ('18008', 'Mutulani Dispensary'), ('12608', 'Mutulu (AIC) Dispensary'), ('12609', 'Mutune Dispensary'), ('18289', 'Mutunguru PCEA Dispensary'), ('10802', 'Mutungus Medical Clinic'), ('19933', 'Mutwangombe Dispensary'), ('12610', 'Mutyambua Dispensary'), ('12611', 'Mutyangome Dispensary'), ('19903', 'Muua Dispensary'), ('17872', 'Muuani Rural Health Dispensary'), ('12612', 'Muumandu Dispensary'), ('19751', 'Muungano Dispensary'), ('12613', 'Muusini Dispensary'), ('18413', 'Muusini Dispensary (Makueni)'), ('12614', 'Muutine Med Clinic'), ('12615', 'Muutiokiama Health Centre'), ('17779', 'Muvuko Dispensary'), ('12616', 'Muvuti Dispensary'), ('10803', 'Muwa M Clinic'), ('15264', 'Muyengwet Dispensary'), ('11678', 'Muyeye Medical Clinic'), ('12617', 'Muyuni Dispensary'), ('13412', 'Muzadilifa Clinic'), ('13835', 'Mv Patel Clinic'), ('11679', 'Mvita Dispensary'), ('11680', 'Mvono Clinic'), ('16956', 'Mwaani Dispensary'), ('11681', 'Mwabila Dispensary'), ('16548', 'Mwachande Medical Clinic'), ('11682', 'Mwachinga Medical Clinic'), ('18279', 'Mwafrika Institute of Development'), ('20201', 'Mwaki Healthcare'), ('11683', 'Mwakirunge Dispensary'), ('12618', 'Mwala District Hospital'), ('18262', 'Mwala Medical Clinic'), ('11684', 'Mwaluphamba Dispensary'), ('11685', 'Mwaluvanga Dispensary'), ('11686', 'Mwambirwa Dispensary'), ('12619', 'Mwambiu Dispensary'), ('20266', 'Mwambui dispensary'), ('19190', 'Mwanainchi Medical Clinic'), ('19038', 'Mwananchi Clinic'), ('16549', 'Mwananyamala (CDF) Dispensary'), ('11687', 'Mwanda Dispensary'), ('11688', 'Mwanda Health Centre (Taita Taveta)'), ('16395', 'Mwangate Dispensary'), ('11689', 'Mwangatini Dispensary'), ('16356', 'Mwangaza Medical Clinic'), ('18350', 'Mwangaza Medical Clinic (Bakarani)'), ('11690', 'Mwangaza Medical Clinic (Mombasa)'), ('10804', 'Mwangaza Medical Clinic (Thika)'), ('20015', 'Mwangaza Tana Medical Clinic'), ('20091', 'Mwangaza ulio Na Tumaini clinic'), ('20335', 'Mwanguda Dispensary'), ('11691', 'Mwangulu Dispensary'), ('20336', 'Mwangwei Dispensary'), ('17941', 'Mwanianga Dispensary'), ('12622', 'Mwanyani Dispensary'), ('19944', 'Mwanyani Dispensary (Kitui Central)'), ('11692', 'Mwanzo Medical Clinic'), ('11693', 'Mwapala Dispensary'), ('18938', 'Mwarimba Medical Clinic'), ('16554', 'Mwashuma Dispensary (CDF)'), ('16056', 'Mwasi Med Clinc'), ('13106', 'Mwatate Clinic'), ('19454', 'Mwatate Healthcare Centre'), ('11694', 'Mwatate Sisal Estate Clinic'), ('11695', 'Mwatate Sub-District Hospital'), ('18961', 'Mwathene Dispensary'), ('16523', 'Mwavizi Medical Clinic'), ('11696', 'Mwawesa Medical Clinic'), ('17427', 'Mwea Dental Clinic'), ('17132', 'Mwea Diabetes / Hypertension Community Clinic'), ('18833', 'Mwea Drop Inn Centre'), ('10806', 'Mwea Medical Centre'), ('16508', 'Mwea Medical Clinic'), ('10805', 'Mwea Medical Clinic Kagio'), ('10807', 'Mwea Medical Laboratory'), ('10808', 'Mwea Mission (Our Lady of Lourdes) Hospital'), ('10809', 'Mweiga Health Centre'), ('10810', 'Mweiga Medical Care'), ('10811', 'Mweiga Rural Health Clinic'), ('12623', 'Mweini Dispensary'), ('19239', 'Mwema Health Care Clinic'), ('11697', 'Mwembe Tayari Staff Clinic'), ('19803', 'Mwenda andu Medical Clinic'), ('18989', 'Mwendantu Amani Clinic'), ('18947', 'Mwendantu Baraka Clinic'), ('12624', 'Mwendwa Clinic'), ('10812', 'Mwendwa Medical Clinic'), ('17604', 'Mwengea Dispensary'), ('15266', 'Mwenje Dispensary'), ('16788', 'Mwer Dispensary'), ('19442', 'Mwera Medical Clinic'), ('12625', 'Mweronkaga Dispensary'), ('16229', 'Mweru Dispensary (Imenti South)'), ('10814', 'Mweru Dispensary (Nyeri South)'), ('11698', 'Mwichens Medical Clinic'), ('16057', 'Mwichio Amua Medical Clinic'), ('16396', 'Mwigito Dispensary'), ('16058', 'Mwihila Mission Hospital'), ('17410', 'Mwikalikha Dispensary'), ('16646', 'Mwikia Clinic'), ('16194', 'Mwina Dispensary'), ('16201', 'Mwina Methodist Dispensary'), ('12626', 'Mwingi District Hospital'), ('17055', 'Mwingi Medicare Centre'), ('12627', 'Mwingi Nursing Home'), ('10815', 'Mwireri Sunrise Medical Clinic'), ('18104', 'M<NAME> Lami Medical Clinic'), ('12628', 'Mwitika Dispensary'), ('15267', 'Mwituria Dispensary'), ('12629', 'Mwonge Clinic'), ('12630', 'Mwonge Dispensary'), ('13836', 'Mwongori Dispensary'), ('19386', 'Mworoga Catholic Dispensary'), ('19350', 'Mworoga Dispensary'), ('16617', 'Myopic Eye Clinic'), ('20096', 'MYSA VCT'), ('20237', 'Mzee Paurana Community Medical Clinic'), ('17893', 'Mzizima (CDF) Dispensary'), ('12631', 'Naari Health Centre'), ('10817', 'Naaro Dispensary'), ('15268', 'Nabkoi Dispensary'), ('16059', 'Nabongo Dispensary'), ('16478', 'Nabuganda Dispensary'), ('15269', 'Nachecheyet Dispensary'), ('15270', 'Nachola Dispensary'), ('15271', 'Nachukui Dispensary'), ('15272', 'Nacoharg Medical Centre'), ('16060', 'Nadanya Dispensary'), ('15273', 'Nadapal Dispensary'), ('15274', 'Nadapal Primary Health Care Programme'), ('13115', 'Nairobi West Hospital'), ('13116', 'Nairobi West Men''s Prison Dispensary'), ('19609', 'Nairobi Women Hospital Eastleigh'), ('19178', 'Nairobi Women Hospital Kitengela'), ('18195', 'Nairobi Women Hospital Ongata Rongai'), ('20061', 'Nairobi Women''s Hospital'), ('13117', 'Nairobi Womens Hospital (Hurlingham)'), ('16795', 'Nairobi Womens Hospital Adams'), ('16402', 'Naishi Game Dispensary'), ('15279', 'Naisoya Dispensary'), ('18979', 'Naisula Medical Clinic'), ('12633', 'Naisura Medical Clinic'), ('16061', 'Naitiri Sub-District Hospital'), ('15282', 'Naivasha (AIC) Medical Centre'), ('15280', 'Naivasha District Hospital'), ('15281', 'Naivasha Max Prison Health Centre'), ('13280', 'Najah Medical Clinic'), ('15283', 'Najile Dispensary'), ('15284', 'Nakaalei Dispensary'), ('18354', 'Nakechichok Dispensary'), ('19511', 'Nakhayo Medical Clinic'), ('16729', 'Nakoko Dispensary'), ('16700', 'Nakukulas Dispensary'), ('15285', 'Nakurio Dispensary'), ('17084', 'Nakurtakwei Dispensary'), ('15286', 'Nakuru Clinical Unit'), ('20343', 'Nakuru Heart Centre'), ('15287', 'Nakuru Nursing Home'), ('15288', 'Nakuru Provincial General Hospital (PGH)'), ('15289', 'Nakuru War Memorial Hospital'), ('15290', 'Nakuru West (PCEA) Health Centre'), ('15291', 'Nakururum Dispensary'), ('15292', 'Nakwamoru Health Centre'), ('16366', 'Nakwijit Dispensary'), ('17153', 'Nakwijit Dispensary'), ('16062', 'Nala Maternity and Nursing Home'), ('18971', 'Nalala Initiative Community Clinic'), ('15293', 'Nalepo Medical Clinic'), ('18412', 'Nalis Medical Centre'), ('16063', 'Nalondo Cbm Dispensary'), ('17117', 'Nalondo Health Centre (Model)'), ('16064', 'Namagara Dispensary'), ('15294', 'Namanga Health Centre'), ('18491', 'Namanga Wellness Centre'), ('17994', 'Namanjalala Dispensary'), ('18930', 'Namarei Dispensary (Marsabit South)'), ('16065', 'Namasoli Health Centre'), ('15295', 'Namayiana Clinic'), ('16273', 'Namba Kodero Dispensary'), ('16066', 'Nambale Health Centre'), ('16067', 'Namboboto Dispensary'), ('16068', 'Nambuku Model Health Centre'), ('15296', 'Namelok Health Centre'), ('15297', 'Namelok Medical Clinic'), ('18091', 'Namenya CFW Clinic'), ('15298', 'Nameyana Dispensary'), ('17178', 'Namirama Dispensary'), ('16380', 'Namocha Dispensary'), ('15299', 'Namoruputh (PAG) Health Centre'), ('16069', 'Namuduru Dispensary'), ('15301', 'Namukuse Dispensary'), ('16070', 'Namulungu Dispensary'), ('15300', 'Namuncha Dispensary'), ('17541', 'Namunyak Clinic'), ('17773', 'Namunyak Dispensary'), ('16071', 'Namwaya Clinic'), ('12634', 'Nana Dispensary'), ('15303', 'Nanam Dispensary'), ('10820', 'Nandarasi Dispensary'), ('14179', 'Nandi Hills District Hospital'), ('17211', 'Nandi Hills Doctors Scheme Association Dispensary '), ('19358', 'Nandi Hills Medicare Clinic'), ('16072', 'Nangina Dispensary'), ('11699', 'Nanighi Dispensary (Tana River)'), ('13413', 'Nanighi Health Centre'), ('10821', 'Nanyuki Cottage'), ('15304', 'Nanyuki Cottage Hospital'), ('15305', 'Nanyuki District Hospital'), ('15307', 'Naoros Dispensary'), ('17478', 'Naotin Dispensary'), ('18070', 'Napeikar Dispensary'), ('15308', 'Napeililim Dispensary'), ('17249', 'Napeitom Dispensary'), ('15309', 'Napusimoru Dispensary'), ('17300', 'Naramam Dispensary'), ('19208', 'Naretisho Dispensary'), ('15310', 'Nariokotome Dispensary'), ('15311', 'Narok District Hospital'), ('18299', 'Narok University College Clinic'), ('17326', 'Narolong Dispensary'), ('16689', 'Narolong Dispensary (Trans Mara West)'), ('10822', 'Naromoru Health Centre'), ('15312', 'Naroosura Health Centre'), ('16221', 'Narrapu Dispensary'), ('16816', 'Narumoru Catholic Dispensary'), ('19279', 'Narzareth Medical Services'), ('15313', 'Nasaroni Medical Clinic'), ('19338', 'Nasaruni Medical Clinic'), ('13119', 'Nascop VCT'), ('16074', 'Nasewa Health Centre'), ('20056', 'Nasha Lengot Medical Centre'), ('16075', 'Nasianda Dispensary'), ('18355', 'Nasiger Dispensary'), ('19887', 'Nasira Dispensary'), ('15314', 'Nasolot Dispensary'), ('16076', 'Nasusi Dispensary'), ('10824', 'National Hospital Insurance Fund Central'), ('13194', 'National Spinal Injury Hospital'), ('16077', 'National Youth Service Dispensary'), ('13130', 'National Youth Service Hq Dispensary (Ruaraka)'), ('15315', 'Natira Dispensary'), ('20045', 'Natunyi Dispensary'), ('15316', 'Nauyapong Dispensary'), ('16078', 'Navakholo Sub-District Hospital'), ('11514', 'Nawaco Clinic'), ('13837', 'Naya Health Centre'), ('18025', 'Nayrus Medical Clinic'), ('18554', 'Nazarene Medical Clinic'), ('19118', 'Nazarene Medical Clinic (Kitui West)'), ('18712', 'Nazarene Sister''s Dispensary Rwarera'), ('10825', 'Nazareth Hospital'), ('17490', 'Nazareth Hospital (Ruiru)'), ('19323', 'Nazareth Medical Clinic'), ('16341', 'Nazareth Medical Clinic (Wareng)'), ('17708', 'Ncooro Dispensary'), ('18504', 'Ncunga Catholic Dispensary'), ('15317', 'Ndabarnach Clinic'), ('15318', 'Ndabibi Dispensary'), ('10827', 'Ndakaini Clinic'), ('10828', 'Ndakaini Dispensary'), ('17817', 'Ndakani Dispensary'), ('12635', 'Ndalani Dispensary'), ('19978', 'Ndalani Dispensary (Makindu)'), ('15319', 'Ndalat (PCEA) Health Centre'), ('15320', 'Ndalat Gaa Dispensary'), ('16079', 'Ndalu Health Centre'), ('17325', 'Ndamama Dispensary'), ('15321', 'Ndamichonik Dispensary'), ('15322', 'Ndanai'), ('10829', 'Ndaragwa Health Centre'), ('15323', 'Ndarawetta Dispensary'), ('15324', 'Ndarugu (PCEA) Dispensary'), ('12636', 'Ndatani Dispensary'), ('10830', 'Ndathi Dispensary'), ('11700', 'Ndau Dispensary'), ('20127', 'Ndauni Dispensary'), ('11701', 'Ndavaya Dispensary'), ('13839', 'Ndeda Dispensary'), ('19029', 'Ndege Medical Clinic'), ('17345', 'Ndege Oriedo Dispensary'), ('10831', 'Ndeiya Health Centre'), ('18245', 'Ndela Dispensary'), ('19923', 'Ndelekeni Dispensary'), ('10832', 'Ndemi Health Centre'), ('20025', 'Ndenderu Dispensary'), ('19833', 'Ndenderu Medical Services'), ('20173', 'Ndere Community Dispensary'), ('13840', 'Ndere Health Centre'), ('16660', 'Nderema Dispensary'), ('13841', 'Ndhiwa Sub-District Hospital'), ('13842', 'Ndhuru Dispensary'), ('19844', 'Ndia Chemist Clinic'), ('11702', 'Ndilidau Dispensary (Jipe)'), ('10833', 'Ndimaini Dispensary'), ('15325', 'Ndindika Health Centre'), ('13843', 'Ndiru Health Centre'), ('16771', 'Ndisi Dispensary'), ('12637', 'Ndithini Health Centre'), ('12638', 'Ndiuni Dispensary'), ('10834', 'Ndivai Dispensary'), ('13844', 'Ndiwa Dispensary'), ('15326', 'Ndoinet Dispensary'), ('17715', 'Ndoleli MCK Dispensay'), ('11704', 'Ndome Dispensary (Taita)'), ('11745', 'Ndongo Purple Clinic'), ('10835', 'Ndonyero Medical Clinic'), ('15511', 'Ndonyo Medical Clinic'), ('19336', 'Ndonyo Medical Clinic (Naivasha Kwa Muya)'), ('19946', 'Ndonyo Nasipa Dispensary'), ('15327', 'Ndonyo Wasin Dispensary'), ('20411', 'Ndooni Dispensary'), ('13845', 'Ndori Health Centre'), ('11705', 'Ndovu Health Centre'), ('17465', 'Ndubeneti Dispensary'), ('16669', 'Ndubusat Bethel Dispensary'), ('19868', 'Nduga Dispensary'), ('10836', 'Ndugamano Dispensary'), ('10837', 'Ndula Dispensary'), ('20129', 'Nduluku Dispensary'), ('19902', 'Nduluni Dispensary'), ('20111', 'Ndumbi Dispensary'), ('20349', 'Ndumbini Dispensary'), ('18462', 'Ndumoni Dispensary'), ('16922', 'Ndunduni Dispensary'), ('18958', 'Ndunguni Dispensary'), ('10839', 'Ndunyu Chege Dispensary'), ('10840', 'Ndunyu Njeru Dispensary'), ('10841', 'Nduriri (AIC) Dispensary'), ('19326', 'Nduri-Sarma Dispensary'), ('13847', 'Nduru District Hospital'), ('13848', 'Nduru Kadero Dispensary'), ('18338', 'Nehemiah International Dispensary'), ('15331', 'Neissuit Dispensary'), ('15332', 'Nekeki Clinic (Hbc)'), ('17745', 'Nembu Med'), ('16804', 'Nembu Medical Clinic'), ('12642', 'Nembure Health Centre'), ('10847', 'Neno Clinic'), ('19776', 'Neno Optical'), ('18403', 'Nep Medical Centre'), ('20354', 'NEP Technical Training Institute Dispensary'), ('15333', 'Nerkwo Dispensary'), ('18919', 'Network Integrated Communication Empowerment Medic'), ('19077', 'New Age VCT'), ('16620', 'New Avenue Medical Clinic'), ('16080', 'New Busia Maternity & Nursing Home'), ('19592', 'New Canaan Idp Dispensary'), ('17698', 'New Chaani Healthcare Clinic & Laboratory'), ('18734', 'New Generation Clinic'), ('18792', 'New Hope Clinic (Nyamira)'), ('18254', 'New Hope Community Centre'), ('16751', 'New Hope Medical Clinic'), ('17952', 'New Hope VCT'), ('11428', 'New Jamin Medical Clinic'), ('10849', 'New Kihoya Clinic'), ('14871', 'New Kimilili Medical Clinic'), ('13120', 'New Life Home Childrens Home (Westlands)'), ('15334', 'New Life Mission Rotary Clinic'), ('10850', 'New Line Laboratory'), ('10851', 'New Mawingu Health Centre'), ('17691', 'New Mbita Clinic'), ('16209', 'New Moon Medical Clinic'), ('18311', 'New Mtongwe Medical Clinic'), ('18325', 'New Mwema Medical Clinic'), ('12643', 'New Ngei Road Nursing Home'), ('11709', 'New Nyali Paeds Hospital'), ('18218', 'New Partner Initiative (Npi) Sasa Centre'), ('18007', 'New Partners Initiative Scaling Up HIV and AIDS Pr'), ('19509', 'New Riruta Medical Clinic'), ('11710', 'New Road Medical Care'), ('16621', 'New Southlands Laboratory'), ('16622', 'New Southlands Med Clinic'), ('19158', 'New Southlands X-Ray Services'), ('10852', 'New Tumaini Health Centre'), ('12644', 'Ngai Dispensary'), ('15335', 'Ngai Murunya Health Service'), ('16861', 'Ngaie Dispensary'), ('20455', 'Ngaina dispensary'), ('13121', 'Ngaira Rhodes Dispensary'), ('16081', 'Ngalasia Dispensary'), ('10853', 'Ngamba Dispensary'), ('15336', 'Ngambo Dispensary'), ('18473', 'Ngamwa Dispensary'), ('10854', 'Ngamwa Medical Laboratory'), ('15337', 'Nganayio Dispensary'), ('10855', 'Ngandu Catholic Dispensary'), ('12645', 'Nganduri Dispensary'), ('12646', 'Ngangani Dispensary'), ('10856', 'Ngano Health Centre'), ('11711', 'Ngao District Hospital'), ('13122', 'Ngara Health Centre (City Council of Nairobi)'), ('10857', 'Ngararia Dispensary'), ('10859', 'Ngarariga Health Centre'), ('12647', 'Ngaremara Dispensary'), ('17226', 'Ngarendare Dispensary'), ('15338', 'Ngarua Catholic Dispensary'), ('15339', 'Ngarua Health Centre'), ('15340', 'Ngatataek Dispensary'), ('15341', '<NAME>'), ('11712', 'Ngathini Dispensary'), ('18284', 'Ngatu CDF'), ('17454', 'Ngecha (PCEA) Health Centre'), ('17244', 'Ngecha Health Centre'), ('10862', 'Ngecha Orthodox Dispensary'), ('15342', 'Ngechek Dispensary'), ('13849', 'Ngegu Dispensary'), ('12648', 'Ngelani (AIC) Dispensary'), ('18686', 'Ngelani Dispensary'), ('20181', 'Ngelechom Community Dispensary'), ('17829', 'Ngelel Tarit Dispensary'), ('10863', 'Ngelelya Dispensary'), ('10864', 'Ngenda Health Centre'), ('15343', 'Ngendalel Dispensary'), ('17097', 'Ng''endalel Dispensary'), ('18604', 'Ngenia Dispensary'), ('17641', 'Ngenybogurio Dispensary'), ('15344', 'Ngenyilel Dispensary'), ('13850', 'Ngere Dispensary'), ('11713', 'Ngerenya Dispensary'), ('17711', 'Ngeri Dispensary'), ('15345', 'Ngeria South Dispensary'), ('12649', 'Ngeru Dispensary'), ('20168', 'Ngeta Dispensary'), ('12650', 'Ngetani Dispensary'), ('17122', 'Ngeteti Community Health Dispensary'), ('15346', 'Ngetmoi Dispensary'), ('10865', 'Ngewa Health Centre'), ('18500', 'Ngieni Community Dispensary'), ('18252', 'Ngiini Dispensary'), ('20166', 'Ngiini Dispensary Kathiani'), ('18360', 'Ngiitakito Dispensary'), ('14459', 'Ngilai Dispensary'), ('12651', 'Ngiluni Dispensary'), ('20215', 'Ngiluni Dispensary (Kaiti)'), ('12652', 'Ngiluni Dispensary (Kitui)'), ('16935', 'Ngiluni Dispensary (Mwingi)'), ('16274', 'Ng''imalo Dispensary'), ('15347', 'Nginyang Health Centre'), ('10868', 'Ngiriambu (ACK) Dispensary'), ('13851', 'Ngisiru Dispensary'), ('15348', 'Ngito Dispensary'), ('13852', 'Ng''iya Health Centre'), ('15349', 'Ngobit Dispensary'), ('13853', 'Ngodhe Dispensary'), ('18076', 'Ng''odhe Dispensary (Main Land)'), ('13854', 'Ng''odhe Island Dispensary'), ('12653', 'Ngoleni Dispensary'), ('10869', 'Ngoliba Health Centre'), ('11714', 'Ng''ombeni Dispensary'), ('11715', 'Ngomeni Dispensary (Malindi)'), ('12654', 'Ngomeni Health Centre'), ('18510', 'Ngomoni Dispensary'), ('16382', 'Ngondi Dispensary'), ('18131', 'Ngondu Medical Clinic'), ('15350', 'Ngong Hills Hospital'), ('19060', 'Ngong Medicare Clinic'), ('18238', 'Ngong Rapha Hospital'), ('13123', 'Ngong Road Health Centre'), ('15351', 'Ngong Sub-District Hospital'), ('17052', 'Ngo''nga Dispensary'), ('18849', 'Ngongo Dispensary'), ('16864', 'Ngongoni Dispensary (Kyuso)'), ('12655', 'Ngongoni Dispensary (Mwingi)'), ('10870', 'Ngorano Health Centre'), ('10871', 'Ngorika Dispensary'), ('15352', 'Ngoron Dispensary'), ('10872', 'Ngorongo Health Centre'), ('17752', 'Ngosuani Dispensary'), ('17558', 'Ngothi Mc'), ('15353', 'Ngubereti Health Centre'), ('17526', 'Nguge Dispensary'), ('10873', 'Nguka Dispensary'), ('13855', 'Nguku Dispensary'), ('12656', 'Ngulini Dispensary'), ('12657', 'Nguluni Health Centre'), ('19236', 'Ngumba Medical Centre'), ('19415', 'Ngumbulu Dispensary'), ('20429', 'Ngungi Dispensary'), ('12658', 'Nguni Health Centre'), ('20297', 'Ngura Medical Clinic'), ('19829', 'Ngurubani Medical Services'), ('12659', 'Nguruki-Iruma Dispensary'), ('16819', 'Ngurumo Dispensary'), ('19658', 'Ngurumo Medical Clinic'), ('15354', 'Ngurunga Dispensary'), ('12660', 'Ngurunit Dispensary'), ('10874', 'Ngurweini Dispensary'), ('10875', 'Nguthuru Dispensary'), ('15355', 'Ngutuk-Engiron Dispensary'), ('12661', 'Nguuku Dispensary'), ('12662', 'Nguungani Dispensary'), ('16858', 'Nguuni Dispensary'), ('11716', 'Nguuni Health Centre'), ('19226', 'Nguviu Boys High School Clinic'), ('12663', 'Ngwata Health Centre'), ('16712', 'Ngwelo Dispensary'), ('10876', 'Nhera Clinic'), ('16623', 'Nica Kaunjira Dispensary'), ('13856', 'Nightingale Medical Centre'), ('19479', 'Nile Medical Care'), ('17804', 'Nile Medical Clinic'), ('13125', 'Nimoli Medical Centre'), ('19759', 'Ninami Medical Clinic'), ('17357', 'Ningaini Dispensary'), ('18798', 'Nist Dispensary'), ('10878', 'Njabini Health Centre'), ('10877', 'Njabini Maternity and Nursing Home'), ('10879', 'Njambi Nursing Home'), ('17560', 'Njambini Catholic Dispensary'), ('18966', 'Njambu Clinic'), ('10880', 'Njegas Health Centre'), ('10881', 'Njemuka Clinic'), ('17458', 'Njemuka Medical Clinic'), ('17367', 'Njeruri Dispensary'), ('17513', 'Njete Medical Clinic'), ('10882', 'Njika Wega Medical Clinic'), ('15356', 'Njipiship Dispensary'), ('13126', 'Njiru Dispensary'), ('10883', 'Njoguini Dispensary'), ('10884', 'Njoki Dispensary'), ('15357', 'Njoro (PCEA) Dispensary'), ('15358', 'Njoro Health Centre'), ('10885', 'Njukini Clinic'), ('15359', 'Njukini Dispensary'), ('11718', 'Njukini Health Centre'), ('18306', 'Njuruta Dispensary'), ('16835', 'Njuthine Dispensary'), ('12664', 'Nkabune Dispensary'), ('15361', 'Nkama Dispensary'), ('18972', 'Nkama Medical Clinic'), ('17227', 'Nkando Dispensary'), ('15362', 'Nkararo Health Centre'), ('15363', 'Nkareta Dispensary'), ('19942', 'Nkaroni Dispensary'), ('12231', 'Nkathiari Dispensary'), ('19186', 'Nkirina Medical Clinic'), ('12665', 'Nkondi Dispensary'), ('15364', 'Nkorinkori Dispensary'), ('15365', 'Nku West Health Centre'), ('12666', 'Nkubu Dispensary'), ('12667', 'Nkubu Medical Clinic'), ('16231', 'Nkunjumu Dispensary'), ('18030', 'Nkutuk Elmuget Dispensary'), ('17785', 'Nkutuk Elmuget Dispensary (Duplicate)'), ('10886', 'No 4 Community Health Clinic'), ('18156', 'Noble Medical Clinic'), ('18960', 'Nogoi Medical Clinic'), ('15366', 'Nolasit Dispensary'), ('17467', 'Nopri Medical Centre'), ('19749', 'Norident Dental Clinic Kitale'), ('12668', 'North Horr Health Centre'), ('10887', 'North Kinangop Catholic Hospital'), ('17511', 'North Star Alliance Clinic'), ('18599', 'North Star Alliance VCT'), ('19206', 'North Star Alliance Wellness Centre'), ('16301', 'Northern Medical Clinic'), ('20319', 'NorthShore Medical Centre'), ('19123', 'Northstar Alliance Wellness Centre (Mai Mahiu)'), ('13127', 'Nsis Health Centre (Ruaraka)'), ('12670', 'Ntemwene Dispensary'), ('12671', 'Ntemwene Medical Clinic'), ('12672', 'Ntha Clinic'), ('12673', 'Nthagaiya Catholic Dispensary'), ('12674', 'Nthambiro Catholic Dispensary'), ('12675', 'Nthambiro Dispensary'), ('16954', 'Nthangu Dispensary'), ('12669', 'Ntharene Medical Clinic'), ('16955', 'Nthimbani Dispensary'), ('12676', 'Nthongoni Dispensary (Kibwezi)'), ('12677', 'Nthongoni Dispensary (Kitui)'), ('17213', 'Nthungululu Dispensary'), ('12678', 'Nthwanguu Dispensary'), ('16624', 'Ntima Medical Clinic'), ('13857', 'Ntimaru Clinic'), ('13858', 'Ntimaru Sub-District Hospital'), ('12679', 'Ntonyiri Health Services'), ('15367', 'Ntulele Dispensary'), ('20198', 'Ntunyigi Medical Clinic'), ('15368', 'Nturukuma Dispensary'), ('15369', 'Nturumeti Dispensary'), ('13128', 'Nuffield Nursing Home'), ('18159', 'Nunguni Medical Clinic'), ('19172', 'Nureyn Medical and Lab Services'), ('11719', 'Nuru Health Care Centre'), ('17955', 'Nuru Lutheran Media Ministry'), ('12680', 'Nuu Catholic Dispensary'), ('20277', 'Nuu Medical Clinic'), ('12681', 'Nuu Sub-District Hospital'), ('12682', 'Nyaani Dispensary'), ('17137', 'Nyabangi Dispensary'), ('13859', 'Nyabikaye Dispensary'), ('13860', 'Nyabikomu Dispensary'), ('16880', 'Nyabiosi Dispensary'), ('16423', 'Nyabioto Dispensary'), ('13861', 'Nyabite Clinic'), ('13862', 'Nyabokarange Dispensary'), ('18865', 'Nyabola CDF Dispensary'), ('13863', 'Nyabola Dispensary'), ('13864', 'Nyabondo Mission Hospital'), ('18867', 'Nyabondo Rehabilitation Centre'), ('20290', 'Nyabonge (Nyamira North)'), ('13865', 'Nyaburi Clinic'), ('13866', 'Nyabururu Dispensary'), ('20289', 'Nyabweri (Nyamira North)'), ('11720', 'Nyache Health Centre'), ('13867', 'Nyacheki Sub-District Hospital'), ('13868', 'Nyachenge Dispensary'), ('13869', 'Nyachogochogo Dispensary'), ('13870', 'Nyadenda Health Centre'), ('17535', 'Nyadhi Dispensary'), ('16266', 'Nyagancha Dispensary'), ('12683', 'Nyagani Dispensary'), ('16856', 'Nyagari Dispensary (CDF)'), ('17536', 'Nyagem Dispensary'), ('13871', 'Nyagesenda Dispensary'), ('16881', 'Nyagichenche (SDA) Dispensary'), ('13872', 'Nyagiki Dispensary'), ('10888', 'Nyagiti Dispensary'), ('13874', 'Nyagoko Dispensary'), ('13875', 'Nyagoro Health Centre'); INSERT INTO `facility_list` (`Facility_Code`, `Facility_Name`) VALUES ('13876', 'Nyagoto Dispensary'), ('13873', 'Nyagowa Elck Dispensary'), ('13877', 'Nyaguda Dispensary'), ('13878', 'Nyaguta Dispensary'), ('13879', 'Nyagwethe Dispensary'), ('13880', 'Nyahera Sub District Hospital'), ('10889', 'Nyahururu Catholic Dispensary'), ('10890', 'Nyahururu District Hospital'), ('10891', 'Nyahururu Private Hospital'), ('20142', 'Nyaiguta Dispensary'), ('16666', 'Nyaitara Dispensary'), ('13881', 'Nyakach (AIC) Dispensary'), ('10892', 'Nyakahuho Dispensary'), ('13882', 'Nyakegogi Dispensary'), ('15370', 'Nyakiambi Dispensary'), ('10893', 'Nyakianga Health Centre'), ('13884', 'Nyakongo Dispensary'), ('13885', 'Nyakuru Dispensary'), ('16275', 'Nyakurungoto Dispensary'), ('16732', 'Nyakwala Dispensary'), ('13886', 'Nyakwana Dispensary'), ('18420', 'Nyakweri Dispensary'), ('19499', 'Nyalego Medical Clinic'), ('13887', 'Nyalenda Health Centre'), ('13888', 'Nyalenda Nursing Home'), ('13889', 'Nyalgosi Dispensary'), ('11722', 'Nyali Barracks Dispensary'), ('16543', 'Nyali Children Hospital'), ('19065', 'Nyali Childrens Hospital'), ('15371', 'Nyalilbuch Dispensary'), ('16986', 'Nyalkinyi (Jersey) Dispensary'), ('13890', 'Nyalunya Dispensary'), ('13891', 'Nyamache District Hospital'), ('16265', 'Nyamagesa Dispensary'), ('16878', 'Nyamagiri Dispensary'), ('13892', 'Nyamagundo Health Centre'), ('13893', 'Nyamagwa Health Centre'), ('13894', 'Nyamaiya Health Centre'), ('13895', 'Nyamakoroto Dispensary'), ('15372', 'Nyamamithi Dispensary'), ('13896', 'Nyamanga Dispensary'), ('13897', 'Nyamaraga Health Centre'), ('13898', 'Nyamaranya Dispensary'), ('13899', 'Nyamarimba Dispensary'), ('13900', 'Nyamasare Dispensary'), ('13901', 'Nyamasege Dispensary'), ('13902', 'Nyamasi Dispensary'), ('13903', 'Nyamasibi Health Centre'), ('15373', 'Nyamathi Dispensary'), ('18295', 'Nyamatwoni Dispensary'), ('19867', 'Nyambare Dispensary'), ('13904', 'Nyambare Health Centre'), ('13905', 'Nyambari Geke Dispensary'), ('12684', 'Nyambene District Hospital'), ('18925', 'Nyambene Medical & Surgical Centre'), ('12685', 'Nyambene Nursing Home'), ('13906', 'Nyambunwa Medical Clinic'), ('13907', 'Nyamekongoroto Health Centre'), ('13908', 'Nyamemiso Dispensary'), ('13909', 'Nyametaburo Health Centre'), ('13910', 'Nyametembe Dispensary'), ('13911', 'Nyamira Adventist Health Centre'), ('13912', 'Nyamira District Hospital'), ('13913', 'Nyamira Maternity and Nursing Home'), ('18342', 'Nyamira Royal Clinic'), ('13983', 'Nyamogonchoro Dispensary'), ('20133', 'Nyamokenye Health Centre(Sameta)'), ('13914', 'Nyamonye Mission Dispensary'), ('13915', 'Nyamrisra Health Centre'), ('13916', 'Nyamusi Sub-District Hospital'), ('20333', 'Nyamwetureko'), ('13917', 'Nyanchonori Dispensary'), ('13918', 'Nyanchwa Dispensary'), ('13919', 'Nyandago Koweru Dispensary'), ('16877', 'Nyandiwa Baptist Dispensary'), ('13920', 'Nyandiwa Dispensary'), ('13921', 'Nyando District Hospital'), ('13922', 'Nyandoche Ibere Dispensary'), ('17264', 'Nyanduma Dispensary'), ('18786', 'Nyandusi'), ('20339', 'Nyandwela Medical Clinic'), ('20315', 'Nyang''aita Dispensary'), ('20172', 'Nyangajo Dispensary'), ('13923', 'Nyangande Dispensary'), ('13925', 'Nyangena Hospital'), ('13924', 'Nyangena Sub District Hospital (Manga)'), ('13926', 'Nyangiela Dispensary'), ('17832', 'Nyangiti Health Centre'), ('17646', 'Nyango Medical Clinic'), ('13927', 'Nyangoge Health Centre'), ('13928', 'Nyang''oma Health Centre'), ('13929', 'Nyang''oma Mission Health Centre'), ('16082', 'Nyang''ori Health Centre'), ('13930', 'Nyangu Dispensary'), ('16988', 'Nyangweta Health Centre'), ('13931', 'Nyanko Dispensary'), ('13932', 'Nyankono Dispensary'), ('16990', 'Nyansabakwa Health Centre'), ('13933', 'Nyansakia Health Centre'), ('13934', 'Nyansancha Dispensary'), ('13935', 'Nyansangio Dispensary'), ('13937', 'Nyansiongo Nursing Home'), ('13938', 'Nyansira Dispensary'), ('18446', 'Nyanturago Health Centre'), ('13939', 'Nyanza Provincial General Hospital (PGH)'), ('16876', 'Nyaoga Community Dispensary'), ('17714', 'Nyaore Dispensary'), ('17082', 'Nyaporo Dispensary'), ('18862', 'Nyara Tea Estate Dispensary'), ('17738', 'Nyarami VCT'), ('10894', 'Nyaribo Dispensary'), ('13940', 'Nyarongi Dispensary'), ('16083', 'Nyarotis Clinic'), ('15374', 'Nyaru Dispensary'), ('19860', 'Nyarut Health Centre'), ('13941', 'Nyasese Dispensary'), ('13942', 'Nyasike Dispensary'), ('20075', 'Nyasoko Dispensary'), ('13943', 'Nyasore Dispensary'), ('13944', 'Nyathengo Dispensary'), ('10895', 'Nyathuna Sub District Hospital'), ('13945', 'Nyatike Health Centre'), ('13946', 'Nyatoto Health Centre'), ('16735', 'Nyaunyau Dispensary'), ('18051', 'Nyawango Dispensary'), ('13947', 'Nyawara Health Centre'), ('19863', 'Nyawawa Dispensary'), ('18225', 'Nyaweri Deaf VCT'), ('19864', 'Nyawita Dispensary'), ('20038', 'Nyayiera Dispensary'), ('13948', 'Nyenye Misori Dispensary'), ('10896', 'Nyeri (Islamic Foundation) Clinic'), ('10897', 'Nyeri Dental Clinic'), ('19773', 'Nyeri Endoscopy & Surgicare Centre'), ('19768', 'Nyeri Good Shepherd Primary Clinic'), ('10898', 'Nyeri Health Care X Ray Clinic'), ('10899', 'Nyeri High School Clinic'), ('19767', 'Nyeri High School Dispensary'), ('17002', 'Nyeri Hill (PCEA) Dispensary'), ('10900', 'Nyeri Hospice'), ('10901', 'Nyeri Medical Clinic'), ('19784', 'Nyeri Primary School Dispensary'), ('10903', 'Nyeri Provincial General Hospital (PGH)'), ('10904', 'Nyeri Surgical Care Centre'), ('19763', 'Nyeri Technical Dispensary'), ('10905', 'Nyeri Town Health Centre'), ('10906', 'Nyeri Youth Heath Centre (Family Health Options Ke'), ('18052', 'Nyikendo Medical Clinic'), ('17349', 'Nyimbei Dispensary'), ('13129', 'Nyina Wa Mumbi Dispensary'), ('18523', 'Nyongores Dispensary'), ('15375', 'Nyonjoro Maternity Home'), ('15376', 'Nyonjoro Medical Clinic (Nakuru)'), ('19191', 'Nyota Njema Medical Clinic'), ('10816', 'Nys (National Youth Service) Dispensary Yatta'), ('15377', 'Nys Dispensary (Gilgil)'), ('15378', 'Nys Dispensary (Keiyo)'), ('11723', 'Nys Dispensary (Kilindini)'), ('15379', 'Nys Dispensary (Kirimun)'), ('12686', 'Nys Dispensary (Mavoloni)'), ('13949', 'Nys Dispensary (Suba)'), ('15380', 'Nys Karate Dispensary'), ('13131', 'Nyumbani Diagnostic Laboratory and Medical Clinic'), ('18199', 'Nyumbani Village Catholic Dispensary'), ('12687', 'Nzaini Dispensary'), ('20410', 'Nzambia Dispensary'), ('16992', 'Nzangathi health centre'), ('12689', 'Nzatani Dispensary (Mwingi)'), ('16929', 'Nzauni Dispensary'), ('12690', 'Nzawa Health Centre'), ('12691', 'Nzeluni Health Centre'), ('12692', 'Nzeveni Dispensary'), ('20298', 'Nzikani community centre'), ('18566', 'Nzinia Dispensary'), ('12693', 'Nziu Health Centre'), ('16084', 'Nzoia (ACK) Dispensary'), ('15381', 'Nzoia Dispensary (Trans Nzoia East)'), ('16086', 'Nzoia Matete Dispensary'), ('18111', 'Nzoia Medical Centre'), ('16085', 'Nzoia Sugar Dispensary'), ('12694', 'Nzoila Dispensary'), ('20258', 'Nzouni Dispensary'), ('19626', 'Nzukini Dispensary'), ('12695', 'Nzunguni Dispensary'), ('10907', 'Oaklands Estate Dispensary'), ('16212', 'Oasis Diagnostic Laboratory'), ('20051', 'Oasis Doctors Plaza Medical Centre'), ('11912', 'Oasis Medical Center'), ('18436', 'Oasis Medical Clinic'), ('17991', 'Oasis Mission Hospital'), ('13950', 'Obalwanda Dispensary'), ('13951', 'Obanga Health Centre'), ('16087', 'Obekai Dispensary'), ('13953', 'Ober Health Centre'), ('13952', 'Ober Kabuoch Dispensary'), ('13954', 'Ober Kamoth Health Centre'), ('10908', 'Obeys Medical Clinic'), ('13955', 'Oboch Dispensary'), ('13956', 'Obumba Dispensary'), ('13957', 'Obunga Dispensary'), ('19866', 'Obuya Dispensary'), ('13958', 'Obwanda Dispensary'), ('20085', 'Ocean Breeze Medical Facilty'), ('15382', 'Ochii Dispensary'), ('16420', 'Ochude Dispensary'), ('13959', 'Ochuna Dispensary'), ('11725', 'Oda Dispensary'), ('12698', 'Odda Dispensary (Moyale)'), ('19492', 'Odeon Medical Centre (Nairobi)'), ('17515', 'Oding Dispensary'), ('13132', 'of<NAME>'), ('13960', 'Ogada Dispensary'), ('13961', 'Ogam Dispensary'), ('13962', 'Ogande Dispensary'), ('18078', 'Ogando Dispensary'), ('13963', 'Ogango Dispensary'), ('13964', 'Ogango Health Centre'), ('16257', 'Ogembo Medical Clinic'), ('13965', 'Ogen Dispensary'), ('13966', 'Ogero Dispensary'), ('15383', 'Ogirgir Tea Dispensary'), ('13967', 'Ogongo Sub-District Hospital'), ('13416', 'Ogorji Dispensary'), ('13968', 'Ogra Health Centre'), ('13133', 'Ogwedhi Dispensary (Nairobi North)'), ('13969', 'Ogwedhi Health Centre'), ('16276', 'Ogwedhi Sigawa Dispensary'), ('13970', 'Ojele Memorial Hospital'), ('16088', 'Ojm Medical Clinic'), ('13971', 'Ojola Dispensary'), ('20152', 'Ojwando Dispensary'), ('13972', 'Okiki Amayo Health Centre'), ('15385', 'Okilgei Dispensary'), ('13973', 'Okitta Maternity Nursing Home'), ('16259', 'Okok Dispensary'), ('17245', 'Okook Dispensary'), ('10909', 'Ol Jabet Medical Clinic'), ('10910', 'Ol Jororok Medical Clinic'), ('13974', 'Olando Dispensary'), ('15386', 'Ol-Arabel Dispensary'), ('13975', 'Olasi Dispensary'), ('13976', 'Olasi Dispensary (Nyando)'), ('15387', 'Olasiti (AIC) Dispensary'), ('10911', 'Olborosat Dispensary'), ('15388', 'Olbutyo Health Centre'), ('17802', 'Olchekut Community Based Clinic'), ('16328', 'Olchobosei Clinic'), ('17811', 'Olchorro Dispensary (Loitokitok)'), ('15389', 'Olchorro Health Centre'), ('10912', 'Old Mawingu Health Centre'), ('15390', 'Oldanyati Health Centre'), ('17090', 'Oldebes Dispensary'), ('15391', 'Oldepesi Dispensary'), ('15392', 'Olderkesi Dispensary'), ('17671', 'Oldoinyo Oibor Dispensary'), ('12697', 'Oldonyiro Dispensary (Isiolo)'), ('15393', 'Oldonyo Nyokie Dispensary'), ('15394', 'Oldonyorok (Cog) Dispensary'), ('15395', 'Oldorko Dispensary'), ('16383', 'Olemila Stand Alone VCT'), ('15396', 'Olemila VCT Centre'), ('15397', 'Olendeem Dispensary'), ('15398', 'Olenguruone Sub-District Hospital'), ('16330', 'Olenkasurai Dispensary'), ('15399', 'Olepolos Dispensary'), ('19268', 'Olepolos Medical Clinic'), ('15400', 'Olereko Dispensary'), ('19738', 'Olesere Dispensary'), ('15401', 'Oletukat Dispensary'), ('15402', 'Olgulului Health Centre'), ('15403', 'Olgumi Dispensary'), ('19811', 'Olifras Medical Clinic'), ('17675', 'Olive Health Care International'), ('16509', 'Olive Health Care/Laboratory'), ('18797', 'Olive Link Health Care'), ('18196', 'Olive Medical Clinic Kitengela'), ('15404', 'Oljabet Health Centre'), ('17428', 'Oljabet Medical Clinic'), ('15405', 'Oljogi Dispensary'), ('15406', 'Ol-Jorai Dispensary'), ('10914', 'Oljororok Catholic Dispensary'), ('17786', 'Oljorre Dispensary'), ('10915', 'Olkalou (ACK) Dispensary'), ('10916', 'Olkalou Sub-District Hospital'), ('15408', 'Olkinyei Dispensary'), ('15409', 'Olkiramatian Dispensary'), ('15410', 'Olkokwe Health Centre'), ('15411', 'Olkoroi Dispensary'), ('12696', 'Oll Mwea Hospital Clinic Embu (Satelite)'), ('15412', 'Ollessos Holy Family Dispensary'), ('13414', 'Ollo Health Centre'), ('15413', 'Ol-Malaika Health Centre'), ('15414', 'Olmekenyu Dispensary'), ('15415', 'Olmesutie Dispensary'), ('15416', 'Olmoran Catholic Dispensary'), ('15417', 'Olmoran Health Centre'), ('16429', 'Olnarau Dispensary (CDF)'), ('15407', 'Ol-Njorowa Flower Farm Medical Clinic'), ('18257', 'Oloibon Medical Centre'), ('15418', 'Oloika Dispensary'), ('19267', 'Oloimirmir Dispensary'), ('15419', 'Oloiyangalani Dispensary'), ('15420', 'Olokurto Health Centre'), ('15421', 'Olokyin Health Centre'), ('16690', 'Ololchani Dispensary'), ('15422', 'Ololpironito Health Centre'), ('15423', 'Ololulunga District Hospital'), ('19910', 'Ololulunga VCT'), ('15424', 'Olooltepes Dispensary'), ('17805', 'Olooltoto Dispensary'), ('18087', 'Oloolua Dispensary'), ('15425', 'Olooseos Dispensary'), ('17867', 'Oloosirkon Disp'), ('18088', 'Oloosirkon Dispensary'), ('15426', 'Olorika Dispensary'), ('17552', 'Oloropil Dispensary'), ('15428', 'Olorte Dispensary'), ('17798', 'Oloshoibor Dispensary'), ('15429', 'Olosho-Oibor Dispensary'), ('15430', 'Olpajeta Dispensary'), ('15431', 'Olposimoru Dispensary'), ('13977', 'Olps Clinic'), ('15432', 'Ol-Rongai Dispensary (Rongai)'), ('15434', 'Oltepesi Dispensary'), ('15433', 'Oltepesi Health Clinic'), ('15435', 'Oltiasika Dispensary'), ('12699', 'Ol-Torot Dispensary'), ('15436', 'Oltukai Lodge Clinic'), ('19080', 'Oltukai Medical Clinic'), ('18511', 'Olturoto Dispensary'), ('11727', 'Om Dental Centre'), ('13978', 'Ombek Dispensary'), ('17607', 'Ombo Bita Dispensary'), ('13979', 'Ombo Kachieng'' Dispensary'), ('17039', 'Ombo Kowiti Dispensary'), ('13980', 'Omboga Dispensary'), ('13981', 'Omiro Dispensary'), ('13982', 'Omobera Dispensary'), ('13984', 'Omogwa Dispensary'), ('13985', 'Omorembe Health Centre (Gucha)'), ('13986', 'Omosaria Dispensary'), ('18772', 'Omosocho Medical Clinic (Manga)'), ('16264', 'Omwabo Medical Clinic'), ('17735', 'Ondong Dispensary'), ('16277', 'Ondong Dispensary'), ('16985', 'Oneno Dispensary'), ('18892', 'Ong''amo Dispensary'), ('19094', 'Ongata Comprehensive Medical Centre'), ('15437', 'Ongata Dispensary'), ('15438', 'Ongata Medical Clinic'), ('15439', 'Ongata Naado Dispensary'), ('15440', 'Ongata Rongai Health Centre'), ('19091', 'Ongata Rongai X-Ray Services'), ('15441', 'Ongatta Cottage Medical Clinic'), ('13987', 'Ong''ielo Health Centre'), ('13988', 'Ongito Dispensary'), ('13989', 'Ongo Health Centre'), ('20317', 'Onoch Dispensary'), ('12700', 'Ontulili Dispensary'), ('17173', 'Onyinjo Dispensary'), ('20209', 'Onyuongo Dispensary'), ('13990', 'Opapla Dispensary'), ('16973', 'Openda Dispensary'), ('15442', 'Opiroi Dispensary'), ('19785', 'Optica Clinic Nyeri'), ('16626', 'Optician Clinic'), ('18870', 'Optimum Care Medical'), ('13415', 'Orahey Medical Clinic'), ('18800', 'Oren Health Centre'), ('13991', 'Oresi Health Centre'), ('16284', 'Oriang (SDA) Health Centre'), ('18086', 'Oriang'' Alwala Dispensary'), ('18422', 'Oriang Kanyadwera Dispensary'), ('17587', 'Oriang VCT'), ('16767', 'Oridi Dispensary'), ('19465', 'Orient Medical Care'), ('15443', 'Orinie (AIC) Clinic'), ('17800', 'Orinie (AIC) Dispensary'), ('13992', 'Oroche Dispensary'), ('16370', 'Orolwo Dispensary'), ('15444', 'Oromodei Dispensary'), ('15445', 'Oropoi Dispensary'), ('13135', 'Orthodox Dispensary'), ('17395', 'Orthodox Maternity and Health Centre'), ('19014', 'Ortum Central Clinic'), ('15446', 'Ortum Hospital'), ('13993', 'Oruba Nursing and Maternity Home'), ('19638', 'Orwa Clinic'), ('20318', 'Orwa dispnsary'), ('13994', 'Orwaki Dispensary'), ('17726', 'Osani Community Dispensary'), ('13995', 'Osano Nursing Home'), ('17776', 'Osarara Dispensary'), ('15447', 'Oserian Health Centre'), ('20069', 'Osewre Dispensary'), ('17680', 'Osieko Dispensary'), ('13996', 'Osingo Dispensary'), ('15448', 'Osinoni Dispensary'), ('13997', 'Osogo Dispensary'), ('15449', 'Osorongai Dispensary'), ('15450', 'Osotua Medical Clinic'), ('15451', 'Osupuko Dispensary'), ('13998', 'Otacho Dispensary'), ('18877', 'Otange Dispensary'), ('13999', 'Otati Dispensary'), ('14000', 'Othach Dispensary'), ('10918', 'Othaya Approved Dispensary'), ('10919', 'Othaya Catholic Dispensary'), ('16777', 'Othaya Dental Clinic'), ('10920', 'Othaya Medical Clinic'), ('10921', 'Othaya Medical Services Clinic'), ('10922', 'Othaya Sub-District Hospital'), ('14001', 'Othoch Rakuom Dispensary'), ('14002', 'Othoro Health Centre (Rachuonyo)'), ('14003', 'Othoro Sub District Hospital'), ('20024', 'Otieno Owala Dispensary'), ('10923', 'Our Choice Medical Clinic'), ('15452', 'Our Lady of Lords Dispensary'), ('14004', 'Our Lady of Lourdes Dispensary (Gucha)'), ('16384', 'Our Lady of Mercy (Magumu)'), ('18093', 'Our Lady of Perpetual Sisters VCT (Bondo)'), ('17296', 'Our Lady''s Hospice'), ('10924', 'Outspan Hospital'), ('14005', 'Ouya Dispensary'), ('14006', 'Owens Nursing Home'), ('14007', 'Oyamo Dispensary'), ('14008', 'Oyani (SDA) Dispensary'), ('14009', 'Oyani Health Centre'), ('17852', 'Oyuma Dispensary (Rachuonyo)'), ('11728', 'Ozi Dispensary'), ('13136', 'P & T Clinic'), ('15454', 'P O M Dipensary'), ('11729', 'Pablo Hortsman Health Centre'), ('10925', 'Pacco Ebenezer Medical Clinic'), ('18318', 'Pacific Medical Clinic'), ('13137', 'Padens Medicare Centre'), ('10926', 'Paed Afya Clinic'), ('17795', 'Pakase Dispensary'), ('15455', 'Pakase Medical Clinic'), ('16430', 'Pakasse Dispensary'), ('17136', 'Pakeza Medical Clinic (Manga)'), ('14011', 'Pala Health Centre'), ('19859', 'Pala Masogo Health Centre'), ('11730', 'Palakumi Dispensary'), ('11731', 'Palani Health Care Clinic'), ('18498', 'Palm Beach Hospital'), ('20165', 'Pamar Medical Clinic'), ('16089', 'Pan M Medical Clinic'), ('16090', 'Pan Paper Dispensary'), ('14012', 'Pand Pieri Community Health Centre'), ('15456', 'Panda Flowers Medical Clinic'), ('11733', 'Pandanguo Dispensary'), ('11734', 'Pandya Memorial Hospital'), ('13138', 'Pangani Dispensary'), ('16339', 'Panpaper Dispensary'), ('14013', 'Pap Kodero Health Centre'), ('18387', 'Paradise Medical Centre'), ('18889', 'Paradise Medical Centre'), ('13417', 'Paramount Clinic'), ('16303', 'Paramount Medical Clinic'), ('18162', 'Parayon Dispensary'), ('20367', 'Paraywa Dispensary'), ('19424', 'Parkroad Dental Clinic (Ngara)'), ('13139', 'Parkroad Nursing Home (Nairobi)'), ('16749', 'Partners In Prevention'), ('18322', 'Partners In Prevention VCT Centre'), ('17048', 'Parua Dispensary'), ('10927', 'Passenga Dispensary'), ('14014', 'Pastor Machage Memorial Hospital'), ('12977', 'Patanisho Maternity and Nursing Home'), ('18637', 'Path Care Kenya'), ('18708', 'Path Care Kenya'), ('10928', 'Patmas Medical Clinic'), ('16343', 'Patrician Dispensary'), ('19025', 'Patrona Medical Services'), ('11735', 'Patte Dispensary'), ('16419', 'Paula Nursing Home'), ('13124', 'PCEA Clinic (Ngundo)'), ('12910', 'PCEA Dandora Clinic'), ('16446', 'PCEA Gateway'), ('19827', 'PCEA Honi Dispensary'), ('17803', 'PCEA Kaigai Memorial'), ('19337', 'PCEA Karero Dispensary'), ('17444', 'PCEA Karungaru Dispensary'), ('12205', 'PCEA Kasasule Dispensary'), ('19435', 'PCEA Kayole Parish Health Centre'), ('17921', 'PCEA Kibwezi Dispensary'), ('12293', 'PCEA Kiengu Disp/Mat'), ('18763', 'PCEA Kuwinda Health Clinic'), ('17878', 'PCEA Mau-Summit Health Centre'), ('18598', 'PCEA Mwangaza Dispensary'), ('19700', 'PCEA Pipeline Clinic'), ('18494', 'PCEA Silanga Church VCT'), ('18116', 'PCEA Smyrna'), ('18376', 'PCEA Upendo Health Centre'), ('17547', 'PCEA VCT'), ('19289', 'Peace Medical Clinic'), ('19853', 'Peace Medical Clinic-Tetu'), ('18380', 'Peak Health Medical Centre'), ('18725', 'Pedo Dispensary'), ('17124', 'Pefa Mercy Medical Centre'), ('15460', 'Peka Maga Clinic'), ('10929', 'Pekaru Medical Centre'), ('16426', 'Pelewa Dispensary (CDF)'), ('18402', 'Penda Health Medical Clinic'), ('18496', 'Pendo Medical Clinic'), ('11736', 'Pendo Medical Clinic (Kilindini)'), ('16519', 'Pendo Medical Clinic (Kinango)'), ('16757', 'Penta Flowers Clinic'), ('20449', 'Penta Medical Centre Umoja'), ('19975', 'Pentapharm Limited'), ('19241', 'Peoples Medical Clinic'), ('12701', 'Pepo La Tumaini Dispensary'), ('17928', 'Perani Private Clinic'), ('19753', 'Perazim Diagnostic Centre'), ('10931', 'Pesi Dispensary'), ('15461', 'Pesi Dispensary (Laikipia West)'), ('20167', 'Pesi Medical Centre'), ('10933', 'Pharma Point Clinic'), ('19540', 'Pharmat Health Care'), ('10934', 'Phase 7 Clinic'), ('10935', 'Phase Ten Clinic'), ('10936', 'Phatholab Laboratory'), ('18711', 'Philia Medical Clinic'), ('18655', 'Philips Medical Clinic'), ('19483', 'Philis Medical Laboratory'), ('10937', 'Physiotherapy Clinic (Kirinyaga)'), ('15462', 'Piave Dispensary'), ('10938', 'Piemu Medical Clinic'), ('13141', 'Piemu Medical Health Centre'), ('18667', 'Pillar of Development'), ('18785', 'Pillar of Development'), ('10939', 'Pilot Medical Clinic'), ('16320', 'Pims Medical Clinic'), ('13142', 'Pine Medical Clinic'), ('11738', 'Pingilikani Dispensary'), ('18534', 'Pinnacle Health Services'), ('17343', 'Piny Owacho Dispensary'), ('15463', 'Pioneer Health Centre'), ('16309', 'Pioneer Medical Clinic (Mandera East)'), ('13418', 'Pioneer Medical Clinic (Wajir East)'), ('13143', 'Pipeline Medical Health Services'), ('12978', 'Pipeline Nursing Home'), ('20302', 'PJ Dave Company Clinic'), ('10940', 'Plainsview Nursing Home'), ('15464', 'Plateau Hospital'), ('16740', 'Plateau Medical Clinic'), ('10941', 'Plaza Medical Laboratory'), ('13419', 'Plaza Nursing Home'), ('19353', 'Plaza X-Ray Services (Re-Insurance Plaza-Nairobi)'), ('15465', 'Poi Dispensary'), ('12702', 'Pole Medical Clinic'), ('19878', 'Police Central Workshop Dispensary'), ('13420', 'Police Line Dispensary (Garissa)'), ('10942', 'Police Line Dispensary (Nyeri South)'), ('10917', 'Pollen Medical Clinic'), ('10943', 'Polly Jam Medical Clinic'), ('15466', 'Polyclinic Hospital'), ('12704', 'Pona Dispensary'), ('12703', 'Pona Haraka Clinic'), ('13145', 'Pona Mat Dispensary'), ('18573', 'Pona Medical and Eye Care Centre'), ('17851', 'Pona Medical Clinic'), ('10944', 'Pona Medical Clinic (Nyeri North)'), ('17854', 'Pona Services Opd'), ('18943', 'Pona VCT'), ('12705', 'Pondeni Medical Clinic'), ('14015', 'Ponge Dispensary'), ('14016', 'Ponge Dispensary (Mbita)'), ('16647', 'Ponya Clinic'), ('18143', 'Ponya Medical Clinic'), ('18140', 'Ponya Surgicals Nursing Home'), ('15467', 'Poole Dispensary'), ('15468', 'Porro Dispensary'), ('20243', 'Port Florence (Ndhiwa)'), ('18774', 'Port Florence Clinic'), ('19875', 'Port Florence Community Hospital Homa Bay Clinic'), ('20225', 'Port Florence Community Hospital, Mbita'), ('14017', 'Port Florence Hospital'), ('13146', 'Port Health Dispensary (Langata)'), ('16291', 'Port Health Dispensary (Wajir East)'), ('18098', 'Port Health Dispensary Lokichoggio'), ('11740', 'Port Reitz District Hospital'), ('11741', 'Port Reitz MTC Dispensary'), ('16091', 'Port Victoria Hospital'), ('19901', 'Positive Partner Network VCT'), ('16629', 'Posland Medical Clinic'), ('20067', 'Post Bank Staff Clinic'), ('18713', 'Pr Health Services'), ('16630', 'Pr Medical Clinic (Buuri)'), ('16631', 'Pr Medical Clinic (Ngushishi)'), ('19266', 'Precious Care Medical Centre'), ('19111', 'Precious Life Health Services'), ('17996', 'Precious Life Medical Clinic Ruai'), ('10945', 'Premier Bag and Cordage Dispensary'), ('19498', 'Premier Laboratory (Nairobi)'), ('18623', 'Premier Medical Clinic'), ('12706', 'Premier Medical Clinic (Kangundo)'), ('12707', 'Premier Medical Clinic (Kitui)'), ('18744', 'Premium Health Services'), ('16233', 'Presbyterian Ttc Rubate Health Centre'), ('18556', 'Prescort Dispensary'), ('19171', 'Prestige Clinic'), ('19275', 'Prestige Health Centre (Zimerman)'), ('18110', 'Primarosa Flower Ltd'), ('17372', 'Primary Health Services'), ('16775', 'Prime Care Health Clinic'), ('19104', 'Prime Dental Clinic'), ('13147', 'Prime Healthservices Dispensary'), ('15469', 'Prime Medical Care'), ('10947', 'Prime Medical Clinic'), ('19440', 'Primed Medical Centre'), ('19451', 'Primed Medical Services Komarock'), ('18829', 'Primo Medical Clinic'), ('16977', 'Prisca Wakarima (ACK) Dispensary'), ('15470', 'Prison Dispensary'), ('15471', 'Pro Esamai Clinic'), ('20163', 'Proact services'), ('19506', 'Professional Diagnostic Centre (Nairobi)'), ('19290', 'Promise Medical Services'), ('13149', 'Provide Inter Math Dispensary'), ('13148', 'Provide Internatinal Clinic (Dandora)'), ('13151', 'Provide International Clinic (Kayole)'), ('17971', 'Provide International Health Care (Mathare)'), ('19447', 'Provide International Hospital Mukuru'), ('13150', 'Provide International Korogocho'), ('12971', 'Provide International Mutindwa Umoja Clinic'), ('18059', 'Provide Medical Clinic'), ('20263', 'Providence Medical Centre'), ('19521', 'Providence Whole Care'), ('19056', 'Providenve Health Clinic'), ('17474', 'Provincial Police Hq VCT'), ('18001', 'Prudent Medical Clinic Kariobangi'), ('16704', 'Pserum Dispensary'), ('16705', 'Psigirio Dispensary'), ('15472', 'Psigor Dispensary'), ('13153', 'Pstc Health Centre'), ('19523', 'Psychological Health Services'), ('20135', 'Psyco Africa Consultancy'), ('16734', 'Ptigchi Dispensary'), ('15473', 'Ptoyo Dipensary'), ('13154', 'Pumwani Clinic'), ('11744', 'Pumwani Dispensary'), ('13155', 'Pumwani Majengo Dispensary'), ('13156', 'Pumwani Maternity Hospital'), ('13157', 'Pumwani Maternity VCT Centre'), ('18324', 'Pumzika Medical Clinic'), ('10949', 'Purity Medical Clinic'), ('15474', 'Pwani (GOK) Dispensary'), ('16092', 'Pwani Dispensary'), ('11746', 'Pwani Maternity and Nursing Home'), ('17662', 'Pwani University College Clinic'), ('19098', 'Qarsadamu Dispensary'), ('15475', 'Quadalupe Sisters Roret'), ('19406', 'Quality Health Care Clinic (Naivasha)'), ('18527', 'Quarry VCT Ongata Rongai'), ('13421', 'Qudama Dispensary'), ('20068', 'Quebee Health Care'), ('11747', 'Queen Kadede Medical Clinic'), ('16758', 'Queen of Peace Clinic'), ('19906', 'Queens & Kings Health Centre'), ('18757', 'R - Care Health Clinic'), ('11748', 'Rabai Rural Health Demonstration Centre'), ('14018', 'Rabar Dispensary'), ('14019', 'Rabondo Dispensary'), ('14020', 'Rabuor Health Centre'), ('15476', 'Racecourse Clinic'), ('19990', 'Racecourse Hospital'), ('14021', 'Rachar Sugar Belt Hospital'), ('14022', 'Rachuonyo District Hospital'), ('15477', 'Radat Dispensary'), ('20383', 'Radiant Group of Hospital (Kiambu)'), ('19370', 'Radiant Hosp Kasarani'), ('13158', 'Radiant Pangani Hospital'), ('18722', 'Radienya Dispensary'), ('14023', 'Radier Dispensary'), ('14024', 'Rae Dispensary'), ('18326', 'Rafiki Clinic'), ('17932', 'Rafiki Kenia (Private) Clinic'), ('16779', 'Rafiki Medical Clinic'), ('10950', 'Rafiki Medical Clinic (Muranga North)'), ('19487', 'Rafiki Medical Clinic (Westlands)'), ('11749', 'Rafiki Miracle Clinic (Hindi )'), ('14025', 'Raganga Health Centre'), ('14026', 'Rageng''ni Dispensary'), ('10951', 'Ragia Forest Dispensary'), ('18530', 'Ragwe Dispensary'), ('18211', 'Railway Dispensary'), ('13168', 'Railway Training Institute Dispensary South B'), ('15478', 'Railways Dispensary'), ('14027', 'Railways Dispensary (Kisumu)'), ('19213', 'Rainbow Clinic'), ('11751', 'Rainbow Community Care'), ('11752', 'Rainbow Medical Burangi'), ('16295', 'Rainbow Medical Clinic'), ('14028', 'Ram Hospital'), ('11753', 'Ramada Dispensary'), ('19295', 'Ramah Medical Clinic'), ('14029', 'Ramasha Dispensary'), ('12708', 'Ramata Health Centre'), ('17437', 'Rambugu Dispensary (Rarieda)'), ('16789', 'Rambula Dispensary'), ('10952', 'Ramos Medical Clinic'), ('20331', 'Ramula Dispensary'), ('14030', 'Ramula Health Centre'), ('17521', 'Randago Dispensary'), ('14031', 'Randung'' Dispensary'), ('14032', 'Ranen (SDA) Dispensary'), ('14033', 'Rangala Health Centre'), ('14034', 'Rangenyo Health Centre'), ('14035', 'Rangwe (SDA) Dispensary'), ('14036', 'Rangwe Sub-District Hospital'), ('18082', 'Rapando VCT'), ('14037', 'Rapcom Nursing and Maternity Home'), ('10953', 'Rapha Afya Medical Clinic (Kirinyaga)'), ('15480', 'Rapha Maternity (Nakuru Central)'), ('15479', 'Rapha Medical Centre'), ('19535', 'Rapha Medical Clinic'), ('19474', 'Rapha Mission Clinic'), ('20202', 'Raphica Medical Clinic'), ('12709', 'Rapsu Dispensary'), ('14038', 'Rariw Dispensary'), ('14039', 'Raruowa Health Centre'), ('14040', 'Ratta Health Centre'), ('19731', 'Rau Dispensary'), ('18592', 'Ravine Glory Health Care Services'), ('19384', 'Ravine Medical and ENT Clinic'), ('18424', 'Rawana Dispensary'), ('18255', 'Ray Comprehensive Youth Centre (Kanco)'), ('13159', 'Ray of Hope Health Centre'), ('17905', 'Ray Youth Consortium VCT'), ('13422', 'Raya Dispensary'), ('17806', 'Reliance Medical Clinic'), ('17998', 'Rays International Clinic Kariobangi'), ('11755', 'Rea Vipingo Dispensary'), ('20375', 'Reachout Centre Trust'), ('18406', 'Real Healthcare Medical Clinic'), ('20177', 'Real I P M Company Clinic'), ('18983', 'Reale Medical Clinic'), ('10954', 'Reality Medical Clinic'), ('20474', 'Rebeko Dispensary'), ('19616', 'Recovery Medical Clinic (Kariobangi South)'), ('19357', 'Reddys Medical Clinic'), ('18822', 'Redeemed Gospel Church VCT'), ('12710', 'Redeemed Medical Clinic'), ('13160', 'Redemeed Health Centre'), ('10955', 'Redland Roses Ltd Clinic'), ('16857', 'Regional Blood Transfusion Centre (Embu)'), ('17180', 'Rehema Children Medical Clinic Lodwar'), ('15482', 'Rehema Dental Health'), ('19673', 'Rehema MC (Top Station-Kitale)'), ('10956', 'Rehema Medical Centre'), ('16461', 'Rehema VCT Centre'), ('20278', 'Rehoboth Maternity and Nursing Home'), ('17071', 'Rei Dispensary'), ('18668', 'Reinha Rosary Medical Clinic (Githunguri)'), ('18927', 'Rejoice Medical Clinic Lusiola'), ('17114', 'Rekeke Model Health Centre'), ('20426', 'Relief Medical Clinic'), ('17593', 'Remba Dispensary'), ('19805', 'Remedy Laboratory Services'), ('19466', 'Remer Medical Clinic'), ('19620', 'Remla Medical Clinic (Dandora)'), ('17373', 'Renguti (PCEA) Women''s Guild Clinic'), ('14042', 'Rera Dispensary'), ('10035', 'Rescue Centre (Thika)'), ('18375', 'Restore Life Medical Centre'), ('13173', 'Reuben Mukuru Health Centre'), ('14043', 'Reusse Troyer Health Centre'), ('20273', 'Review Medical Clinic'), ('16377', 'Revival Baptist VCT Centre'), ('16168', 'Revival Home Based Care Clinic'), ('13423', 'Rhamu Sub-District Hospital'), ('13424', 'Rhamudimtu Health Centre'), ('15483', 'Rhein Valley Hospital'), ('18547', 'Rheno Medicare Clinic'), ('17963', 'Rhodes Ches Clinic (Ccn)'), ('13163', 'Rhodes Chest Clinic'), ('20137', 'Rhonda Dispensary and Maternity'), ('10957', 'Riabai Dispensary'), ('12711', 'Riachina Dispensary'), ('12712', 'Riakanau Dispensary'), ('16981', 'Riakinaro Health Centre'), ('19894', 'Riakithiga Dispensary'), ('14044', 'Riakworo Dispensary'), ('14045', 'Riana Health Centre'), ('16468', 'Riandu Dispensary'), ('20291', 'Rianyambweke (Nyamira North)'), ('14046', 'Riat Dispensary'), ('14047', 'Riat Dispensary (Migori)'), ('13425', 'Riba Dispensary'), ('11756', 'Ribe Dispensary'), ('13164', 'Ribeiro Clinic'), ('14048', 'Riechieri Health Centre'), ('14049', 'Rietago Dispensary'), ('11757', 'Riflot Medical Centre'), ('18955', 'Riflot Medical Clinic'), ('16826', 'Right Choice Clinic'), ('14050', 'Rigoko Dispensary'), ('14051', 'Rigoma Dispensary'), ('17347', 'Rikendo Dispensary'), ('17678', 'Rikenye Dispensary (Masaba)'), ('19544', 'Rimaal Medical Laboratory'), ('15485', 'Rimoi Dispensary'), ('19475', 'Rinah Health Consultants'), ('20364', 'Ringa Dispensary'), ('17710', 'Ringiti Dispensary'), ('14052', 'Riokindo Health Centre'), ('14053', 'Riongige Dispensry'), ('15486', 'Riongo Dispensary'), ('14054', 'Riotanchi Health Centre'), ('12713', 'Ripples International Dispensary'), ('17962', 'Riria Medical Clinic'), ('17248', 'Rironi Dispensary'), ('13165', 'Riruta Health Centre'), ('18806', 'Rithika Medical and Counseling Centre'), ('14055', 'Ritumbe Health Centre'), ('10958', 'Riverside Clinic'), ('19495', 'Riverside Medical Centre'), ('15487', 'Riwo Dispensary'), ('18259', 'Riyadh Medical Clinic'), ('14056', 'Roadblock Clinic'), ('10959', 'Roadside Clinic (Kagunduini)'), ('10960', 'Roadside Medical Clinic Kiangai'), ('20238', 'Roadway Medical Clinic'), ('15488', 'Robana Medical Clinic'), ('18936', 'Robins Health Care Clinic'), ('17135', 'Robinson Medical Clinic (Manga)'), ('20441', 'Roborwo Dispensary'), ('15489', 'Rocco Dispensary'), ('14057', 'Rodi Dispensary'), ('17077', 'Roka'), ('11758', 'R<NAME>aweni Dispensary'), ('18175', 'Rokimwi Clinic'), ('12714', 'Rolex Medical Clinic'), ('19642', 'Roma Medical Clinic'), ('15490', 'Rombo Health Centre'), ('17861', 'Romieva Medical Centre'), ('19456', 'Romieva Medical Centre Tassia'), ('15491', 'Romosha Dispensary'), ('17101', 'Rondonin Dispensary'), ('15493', 'Rongai Diagnstic Laboratory'), ('15494', 'Rongai First Medical Centre'), ('15495', 'Rongai Health Centre'), ('18314', 'Rongai Orthopaedics Medical Services'), ('15496', 'Rongai Uzima Medical Clinic'), ('15497', 'Rongena Dispensary'), ('17781', 'Rongena Dispensary (Narok South)'), ('14058', 'Rongo District Hospital'), ('13166', 'Ronil Medical Clinic (Githurai)'), ('16093', 'Rophy Clinic'), ('15499', 'Roret Medical Clinic'), ('15498', 'Roret Sub-District Hospital'), ('12715', 'Ros Megg Clinic'), ('10961', 'Rosa Medical Clinic'), ('18992', 'Rosade Medical Clinic'), ('19401', 'Rosadett Medical Clinic'), ('10963', 'Rose Medical Clinic'), ('18307', 'Rosewo VCT Centre'), ('18068', 'Rosewood Nursing Home'), ('20008', 'Rosoga Dispensary'), ('10964', 'Rospa Glory Clinic'), ('14060', 'Rota Dispensary'), ('16094', 'Rotary Doctors Clinic'), ('15500', 'Rotary Doctors General Outreach'), ('19940', 'Rotu Dispensary'), ('17938', 'Round About Medical Centre'), ('13167', 'Round About Medical Dispensary'), ('16300', 'Rowla Medical Clinic'), ('17732', 'Royal Clinic'), ('16836', 'Royal Clinic & Laboratory'), ('18988', 'Royal Clinic-Kibera'), ('19821', 'Royal Dental Clinic'), ('11759', 'Royal Health Care'), ('10965', 'Royal Medical Centre'), ('19956', 'Royal Medical Clinic'), ('19106', 'Royal Medical Clinic (Meru)'), ('10966', 'Royal Medical Clinic (Thika)'), ('14061', 'Royal Nursing Home'), ('18572', 'Royal Run Medical Clinic'), ('19382', 'Royolk Medical Clinic'), ('18221', 'Ruai (SDA) Clinic'), ('13170', 'Ruai Community Clinic'), ('13171', 'Ruai Health Centre'), ('16487', 'Ruanda Dispensary'), ('13172', 'Ruaraka Clinic'), ('18485', 'Ruaraka Uhai Neema Hospital'), ('10969', 'Ruchu Dispensary'), ('10967', 'Ruera Estate Dispensary'), ('18013', 'Ruguru Community Health Centre'), ('17791', 'Ruguru Dispensary'), ('12716', 'Ruiri Catholic Health Centre'), ('19129', 'Ruiri MCK Medical Centre'), ('18709', 'Ruiri Medical Centre'), ('16632', 'Ruiri Medical Clinic'), ('12717', 'Ruiri Rural Health Demonstration Centre'), ('10971', 'Ruiru Diagnostic Centre'), ('10972', 'Ruiru East Medical Clinic'), ('18184', 'Ruiru Health Clinic'), ('10974', 'Ruiru Hospital Limited'), ('10973', 'Ruiru Sub-District Hospital'), ('16095', 'Rukala Dispensary'), ('10975', 'Rukanga Health Centre'), ('16241', 'Rukenya Dispensary'), ('12718', 'Rukira Dispensary'), ('18416', 'Ruma Youth Friendly VCT (Rarieda)'), ('11760', 'Rumangao Dispensary'), ('16096', 'Rumbiye Dispensary'), ('15501', 'Rumuruti Catholic Dispensary'), ('15502', 'Rumuruti District Hospital'), ('15503', 'Rumuruti Medical Clinic'), ('12719', 'Runyenjes District Hospital'), ('17304', 'Ruona Dispensary'), ('13426', 'Ruqa Dispensary'), ('13174', 'Rural Aid VCT'), ('20425', 'Rural Border Patrol'), ('18128', 'Rural Education and Environmental Program'), ('10976', 'Rural Medical Clinic (Muranga South)'), ('10977', 'Rural Medical Clinic (Nyeri South)'), ('10978', 'Rural Personal Care Centre'), ('10979', 'Rurii (ACK) Dispensary'), ('10980', 'Rurii Kiandegwa Dispensary'), ('10981', 'Ruringu Medical Clinic'), ('10982', 'Ruruguti Afya Clinic'), ('10983', 'Ruruguti Dispensary'), ('15504', 'Rusana Medical Clinic'), ('14062', 'Rusinga Dispensary'), ('17594', 'Rusinga Island of Hope Humanist Health Centre'), ('17250', 'Rwamburi Dispensary'), ('14063', 'Rwambwa Health Centre'), ('10984', 'Rwanyambo Dispensary'), ('12721', 'Rwanyange Dispensary'), ('10985', 'Rware Clinic'), ('16512', 'Rwathe Dispensary'), ('10986', 'Rwathia Dispensary'), ('12722', 'Rwika Dispensary'), ('17549', 'Sa/Ahf Kithituni Health Clinic'), ('11761', 'Sabaki Dispensary'), ('16170', 'Sabasaba Catholic Dispensary'), ('10987', 'Sabasaba Health Centre'), ('15505', 'Sabatia Dispensary'), ('16097', 'Sabatia Eye Hospital Mission'), ('16098', 'Sabatia Health Centre'), ('13427', 'Sabir Medical Clinic'), ('15506', 'Sabor Dispensary'), ('17890', 'Sabor Forest Dispensary'), ('15508', 'Saboti Sub-District Hospital'), ('13428', 'Sabuli Health Centre'), ('13429', 'Sabuli Nomadic Dispensary'), ('16099', 'Sacha Health Centre'), ('15509', 'Sachang''wan Dispensary'), ('15510', 'Sacho School Dispensary'), ('17092', 'Sachora Dispensary'), ('20231', 'SACODEN VCT Center'), ('10988', 'Sacred Heart Dispensary'), ('16252', 'Sacred Heart Dispensary (Nzaikoni)'), ('10989', 'Sacred Heart Kangaita Catholic Dispensary'), ('16524', 'Sacred Heart Medical Clinic'), ('10990', 'Sacred Heart Mission Dispensary'), ('19039', 'Safa Medical Centre'), ('16447', 'Safi Medical Clinic'), ('11763', 'Sagaighu Dispensary'), ('11764', 'Sagala Health Centre'), ('17271', 'Sagala Medical Clinic'), ('14064', 'Sagam Community Hospital'), ('20057', 'Sagam Hospital'), ('10991', 'Sagana Catholic Dispensary'), ('10992', 'Sagana Medical Care'), ('10993', 'Sagana Medical Clinic'), ('20391', 'Sagana State Lodge Dispensary'), ('10994', 'Sagana Sub-District Hospital'), ('12723', 'Sagante Dispensary'), ('15512', 'Sagat Dispensary'), ('19640', 'Sahal Medical Clinic'), ('18044', 'Sahla Medical Clinic'), ('11765', 'Saifee Foundation Medical Centre'), ('18386', 'Saika Medical Centre'), ('15513', 'Saikeri Dispensary'), ('15515', 'Sajiloni Dispensary'), ('13430', 'Saka Health Centre'), ('19960', 'Sakali Dispensary'), ('15516', 'Sakutiek Health Centre'), ('19115', 'Sala Dispensary'), ('15517', 'Salabani Dispensary'), ('17780', 'Salabwek Dispensary'), ('15518', 'Salala Medical Clinic'), ('12724', 'Salama (Baptist) Nursing Home'), ('15519', 'Salama Clinic'), ('12725', 'Salama Dawa Health Services'), ('15520', 'Salama Health Centre (Laikipia West)'), ('17896', 'Salama Lab Services'), ('10995', 'Salama Medical Clinic'), ('18237', 'Salama Medical Clinic (Embu)'), ('11766', 'Salama Medical Clinic (Mombasa)'), ('13175', 'Salama Nursing Home'), ('15521', 'Salawa Catholic Mission Dispensary PHC'), ('15522', 'Salawa Health Centre'), ('18600', 'Salgaa Intergrated VCT'), ('18392', 'Salivin Medical Clinic'), ('19026', 'Salvage Medical Clinic'), ('19613', 'Sam Medical Clinic'), ('19203', 'Samaad Hospital'), ('15523', 'Samaria (AIC) Mission Dispensary'), ('10996', 'Samaria Maternity Home'), ('12726', 'Samaritan Health Services'), ('10997', 'Samaritan Medical Clinic'), ('13176', 'Samaritan Medical Services (Dandora)'), ('19054', 'Samaritan Soul Hospital'), ('11767', 'Samba Medical Clinic'), ('12727', 'Samburu Complex'), ('11768', 'Samburu Health Centre'), ('15524', 'Samburu Lodge Dispensary'), ('16520', 'Samburu Medical Centre'), ('19352', 'Samburu Medical Centre (Outreach Services)'), ('15525', 'Sambut Dispensary'), ('20251', 'Sam-Evan Medical Clinic'), ('19728', 'Samilo Medical Clinic'), ('10998', 'Samkim Medical Clinic'), ('20235', 'Sam-link medical centre'), ('17944', 'Samoei Medical Clinic'), ('14065', 'Samora Clinic'), ('17143', 'Samutet Dispensary'), ('16525', 'San Marco Project Clinic'), ('15526', 'Sancta Maria Clinic'), ('15527', 'Sandai Dispensary'), ('15528', 'Sanga Dispensary'), ('13431', 'Sangailu Health Centre'), ('15529', 'Sang''alo Dispensary'), ('11769', 'Sangekoro Dispensary'), ('16100', 'Sango Dispensary'), ('20186', 'Sango Kabuyefwe Dispensary'), ('17986', 'Sango Natiri Dispensary'), ('14066', 'Sango Rota Dispensary'), ('13432', 'Sangole Dispensary'), ('15530', 'Sangurur Dispensary'), ('17957', 'Sani Medical Clinic'), ('19379', 'Sanitas Lotus Medical Centre'), ('13433', 'Sankuri Health Centre'), ('19733', 'Santa Lucia Medical Clinic'), ('11770', 'Santa Maria Medical Clinic'), ('17828', 'Santa Maria Medical Clinic (Kwale)'), ('19445', 'Santi Meridian Health Care'), ('14067', 'Saokon Clinic'), ('13178', 'Saola Maternity and Nursing Home'), ('20434', 'Saos Dispensary'), ('14068', 'Saradidi Dispensary'), ('19757', 'Sarara Chemistry'), ('13434', 'Saretho Health Centre'), ('13435', 'Sarif Health Centre'), ('19256', 'Sarimo Medical Centre'), ('13436', 'Sarman Dispensary'), ('14069', 'Saro Dispensary'), ('19706', 'Sarova Hotels'), ('15532', 'Saruchat Dispensary'), ('18766', 'Sasa Centre'), ('18796', 'Sasa Centre (Makadara)'), ('18773', 'Sasa Centre (Westlands)'), ('18571', 'Sasa Centre Naivasha (Drop In Service Centre-Disc)'), ('19311', 'Sasa Centre-Ngara'), ('15533', 'Satiet Dispensary'), ('11771', 'Sau Health Services'), ('11772', 'Savana Medical Clinic'), ('16101', 'Savane Dispensary'), ('11773', 'Savani Medical Centre'), ('15534', 'Savani Tea Dispensary'), ('18459', 'Savannah Likoni Medical Centre'), ('15535', 'Savannah Medical Clinic'), ('16691', 'Savimbi Medical Clinic'), ('19201', 'Sawa Ikombe Medical Clinic'), ('19202', 'Sawa Makutano Medical Clinic'), ('11000', 'Sawa Medical Consultants'), ('14070', 'Sayyid Aysha Dispensary'), ('11774', 'Sayyida Fatimah Hospital'), ('12728', 'School For The Deaf (Machakos)'), ('19449', 'Scion Healthcare Ltd Clinic'), ('18593', 'SDA Health Services Likoni Road Clinic'), ('11777', 'Sea Breeze Medical Clinic'), ('17630', 'Seaside Nursing Home'), ('15536', 'Seed of Hope Medical Clinic'), ('14071', 'Sega Cottage Hospital'), ('14072', 'Sega Dispensary'), ('14073', 'Sega Health Centre'), ('17029', 'Segera Mission Dispensary'), ('16790', 'Segere Dispensary'), ('15537', 'Segero Dispensary'), ('16470', 'Segetet Dispensary'), ('15538', 'Sego Dispensary'), ('15539', 'Segut Dispensary'), ('15540', 'Segutiet Dispensary'), ('17086', 'Seguton Dispensary'), ('14074', 'Seka Health Centre'), ('15541', 'Sekenani Health Centre'), ('15542', 'Sekerr Dispensary'), ('15543', 'Seketet Dispensary'), ('20304', 'Selma medical clinic'), ('11778', 'Semikaro Dispensary'), ('14075', 'Sena Health Centre'), ('18662', 'Senate Health Services'), ('16440', 'Sengani Dispensary'), ('14076', 'Sengera Health Centre (Gucha)'), ('11779', 'Senior Staff Medical Clinic (MCM)'), ('20301', 'Seniors Medical Services'), ('13179', 'Senye Medical Clinic'), ('11780', 'Sera Dispensary'), ('14077', 'Serawongo Dispensary'), ('19085', 'Sere Clinic'), ('16102', 'Seregeya Dispensary'), ('16103', 'Serem Health Centre'), ('15545', 'Serem Health Centre (Nandi South)'), ('18749', 'Serena Beach Hotel & Spa Staff Clinic'), ('17884', 'Serena Medical Clinic'), ('15546', 'Sereng Dispensary'), ('15547', 'Sereolipi Health Centre'), ('15548', 'Sererit Catholic Dispensary'), ('16730', 'Seretion Dispensary'), ('15549', 'Seretunin Health Centre'), ('15550', 'Seretut Dispensary'), ('17591', 'Seretut Medical Clinic'), ('15551', 'Serewo Health Centre'), ('15552', 'Sergoit Clinic'), ('15553', 'Sergoit Dispensary (Eldoret East)'), ('15554', 'Sergoit Dispensary (Keiyo)'), ('12729', 'Sericho Health Centre'), ('19325', 'Serotec Medical Clinic'), ('15555', 'Setano Dispensary'), ('15556', 'Setek Dispensary'), ('17267', 'Seth Medical Clinic'), ('13180', 'Sex Workers Operation Project (Swop)'), ('18176', 'Sex Workers Outreach Program (Lang''ata)'), ('13181', 'SGRR Medical Clinic'), ('13182', 'Shaam Nursing Home'), ('17647', 'Shafshafey Health Centre'), ('18595', 'Shallom Dispensary'), ('18952', 'Shalom Community Health Centre'), ('17979', 'Shalom Community Hospital (Athi River)'), ('12730', 'Shalom Community Hospital (Machakos)'), ('11781', 'Shalom Health Services'), ('15557', 'Shalom Medical Centre'), ('20028', 'Shalom Medical Clinic'), ('12731', 'Shalom Medical Clinic (Embu)'), ('11002', 'Shalom Medical Clinic (Thika)'), ('19315', 'Shalom Medical Clinical'), ('19412', 'Shalom Satelite Clinic'), ('18555', 'Shalome Medical Clinic'), ('16104', 'Shamakhubu Health Centre'), ('11004', 'Shamata Health Centre'), ('16105', 'Shamberere Dispensary'), ('11005', 'Shammah Clinic'), ('18094', 'Shammah Medical Clinic'), ('16189', 'Shangia Dispensary'), ('11006', 'Shanka Medical'), ('15558', 'Shankoe Dispensary'), ('13437', 'Shanta Abaq Dispensary (Wajir West)'), ('13438', 'Shantaabaq Health Centre (Lagdera)'), ('11783', 'Shanzu Teachers College Clinic'), ('19400', 'Sharifik Medical Clinic'), ('17375', 'Sharom Dispensary'), ('17324', 'Shartuka Dispensary'), ('17374', 'Shauri Dispensary'), ('13183', 'Shauri Moyo Baptist VCT Centre'), ('13184', '<NAME> Clinic'), ('19636', 'Shauri Moyo Health Services'), ('18019', 'Sheikh Nurein Medical Centre'), ('18471', 'Shekina Medical Clinic'), ('17569', 'Shekinah Medical Clinic'), ('17120', 'Shelemba'), ('11784', 'Shella Dispensary'), ('13185', 'Shepherds Medical Clinic Maringo'), ('16106', 'Shianda Baptist Clinic'), ('20194', 'Shianda Dispensary'), ('18759', 'Shibanga Medical Clinic'), ('16123', 'Shibanze Dispensary'), ('16107', 'Shibwe Sub-District Hospital'), ('18034', 'Shifa Medical Clinic (Moyale)'), ('13439', 'Shifaa Nursing Home'), ('16108', 'Shihalia Dispensary'), ('16109', 'Shihome Dispensary'), ('11785', 'Shika Adabu (MCM) Dispensary'), ('11007', 'Shikamoo Medical Clinic'), ('16110', 'Shikokho Dispensary'), ('16483', 'Shikumu Dispensary'), ('16111', 'Shikunga Health Centre'), ('16112', 'Shikusa Health Centre'), ('16113', 'Shikusi Dispensary'), ('11786', 'Shiloh Nursing Clinic'), ('11787', 'Shimba Hills Health Centre'), ('13440', 'Shimbir Fatuma Health Centre'), ('13443', 'Shimbrey Dispensary'), ('11397', 'Shimo Borstal Dispensary (GK Prison)'), ('11393', 'Shimo La Tewa Annex Dispensary (GK Prison)'), ('11788', 'Shimo La Tewa High School Dispensary'), ('11395', 'Shimo-La Tewa Health Centre (GK Prison)'), ('11789', 'Shimoni Dispensary'), ('16718', 'Shimuli Medical Clinic'), ('16115', 'Shinutsa Dispensary'), ('16719', 'Shinyalu Central Clinic'), ('17596', 'Shinyalu Health Centre'), ('19371', 'Shiply Medical Centre & Lab'), ('16116', 'Shiraha Health Centre'), ('14078', 'Shirikisho Dispensary'), ('16200', 'Shirikisho Medical Dispensary'), ('16198', 'Shirikisho Methodist Dispensary'), ('16117', 'Shiru Health Centre'), ('16118', 'Shisaba Dispensary'), ('16119', 'Shiseso Health Centre'), ('16120', 'Shitoto Medical Clinic'), ('16121', 'Shitsitswi Health Centre'), ('16122', 'Shivanga Health Centre'), ('20307', 'Shomella Dispensary'), ('15560', 'Shompole Dispensary'), ('17389', '<NAME> Medical Clinic'), ('11791', '<NAME>'), ('11792', 'Shuffa Clinic'), ('18490', 'Shujaa Project Namanga'), ('20052', 'Shujaa Satellite Clinic'), ('11793', 'Shukrani Medical Clinic'), ('18820', 'Shura Dispensary (Chalbi)'), ('11008', 'Shwak Medical Clinic'), ('14079', 'Siabai Makonge Dispensary'), ('19905', 'Siakago Boys High School Dispensary'), ('12733', 'Siakago Clinic'), ('18426', 'Siala Kaduol'), ('15561', 'Siana Springs Dispensary'), ('14080', 'Siaya District Hospital'), ('14081', 'Siaya Medical Centre'), ('18520', 'Sibayan Dispensary'), ('15562', 'Sibilo Dispensary'), ('16124', 'Siboti Health Centre'), ('14082', 'Sibuoche Dispensary'), ('14083', 'Sieka Dispensary'), ('14084', 'Sifuyo Dispensary'), ('15563', 'Sigilai (Cmc) Clinic'), ('14085', 'Sigomere Health Centre'), ('15564', 'Sigor Sub District Hospital'), ('15565', 'Sigor Sub-District Hospital'), ('15566', 'Sigoro Dispensary'), ('15567', 'Sigot Dispensary'), ('14086', 'Sigoti Health Centre'), ('15568', 'Sigowet Sub-District Hospital'), ('14087', 'Sikalame Dispensary'), ('16485', 'Sikarira Dispensary'), ('12734', 'Sikh Temple Hospital'), ('20432', 'sikhendu'), ('20162', 'Sikhendu Disp'), ('15569', 'Sikhendu Medical Clinic'), ('19368', 'Siksik Dispensary'), ('16125', 'Sikulu Dispensary'), ('18145', 'Sikusi Dispensary'), ('11794', 'Silaloni Dispensary'), ('13186', 'Silanga (MSF Belgium) Dispensary'), ('17860', 'Silibwet Dispensary'), ('15570', 'Silibwet Dispensary (Bomet)'), ('11009', 'Silibwet Health Centre (Nyandaruawest)'), ('15571', 'Siloam Hospital'), ('12735', 'Siloam Mediacl Clinic'), ('11010', 'Siloam Medical Centre'), ('17825', 'Siloam Medical Clinic'), ('19635', 'Siloam Medical Clinic ( Pokot Central)'), ('15572', 'Siloam Medical Clinic (Kajiado)'), ('19713', 'Siloam Medical Clinic (Kieni East)'), ('11796', 'Siloam Medical Clinic (Malindi)'), ('15573', 'Siloam Medicalclinic'), ('11011', 'Silver Line Medical Clinic'), ('20400', 'Silverdine Medical Centre(lancet hse)'), ('15574', 'Simba Health Centre'), ('14088', 'Simba Opepo Dispensary'), ('15575', 'Simbi Dispensary'), ('14089', 'Simbi Kogembo Dispensary'), ('11012', 'Simbi Roses Clinic'), ('14090', 'Simbiri Nanbell Health Centre'), ('17988', 'Simboiyon Dispensary'), ('14091', 'Simenya Dispensary'), ('17970', 'Similani Medical Clinic'), ('15576', 'Simotwet Dispensary'), ('17151', 'Simotwet Dispensary ( Koibatek)'), ('15577', 'Simotwo Dispensary (Eldoret East)'), ('15578', 'Simotwo Dispensary (Keiyo)'), ('15579', 'Simrose Medical Clinic'), ('15580', 'Sina Dispensary'), ('20279', 'Sinai clinic'), ('11013', 'Sinai Maternity and Medical Clinic'), ('17123', 'Sinai Medical Services'), ('15581', 'Sinai Mount Hospital'), ('20029', 'Sindo Drop In Centre'), ('17765', 'Singawa Medical Centre'), ('15582', 'Singiraine Dispensary'), ('13187', 'Single Mothers Association of Kenya (Smak)'), ('15583', 'Singorwet Dispensary'), ('14092', 'Sino Dispensary'), ('16126', 'Sinoko Dispensary (Bungoma East)'), ('16127', 'Sinoko Dispensary (Likuyani)'), ('17240', 'Sinonin Dispensary'), ('20435', 'Sinonin Dispensary (Koibatek)'), ('16128', 'Sio Port District Hospital'), ('15585', 'Siomo Dispensary'), ('15586', 'Siongi Dispensary'), ('15587', 'Siongiroi Health Centre'), ('15588', 'Sipili Catholic Dispensary'), ('15589', 'Sipili Health Centre'), ('17148', 'Sipili Maternity and Nursing Home'), ('18777', 'Sir John and Mbatia Community Medical Centre'), ('17990', 'Sirakaru Dispensary'), ('17350', 'Sirata Dispensary'), ('15590', 'Sirata Oirobi Dispensary'), ('17140', 'Sirate Dispensary (Manga)'), ('14093', 'Sirembe Dispensary'), ('20431', 'Sirende Friends Dispensary'), ('15591', 'Siret Tea Dispensary'), ('14094', 'Siriba Dispensary'), ('17858', 'Sirikwa Peace Dispensary'), ('16129', 'Sirimba Dispensary'), ('16130', 'Sirisia Hospital'), ('17177', 'Sironoi GOK Dispensary'), ('17247', 'Sironoi SDA Dispensary'), ('17051', 'Siruti Dispensary'), ('15594', 'Sirwa Dispensary'), ('15593', 'Sirwa Dispensary (Mogotio)'), ('16131', 'Sisenye Dispensary'), ('12736', 'Sisi Kwa Sisi Medical Clinic'), ('15595', 'Sisiya Dispensary'), ('20041', 'Sisokhe Dispensary'), ('15596', 'Sispar Medical Clinic'), ('19957', 'Sister Medical Clinic'), ('13442', 'Sisters Maternity Home (Simaho)'), ('18011', 'Sisto Mazoldi Dispensary (Rongai)'), ('17027', 'Sitatunga Dispensary'), ('15597', 'Sitoi Tea Dispensary'), ('17322', 'Sitoka Dispensary'), ('11799', 'Siu Dispensary'), ('16147', 'Sivilie Dispensary'), ('15598', 'Siwo Dispensary'), ('15599', 'Siyiapei (AIC) Dispensary'), ('11775', 'Skans Health Care Centre'), ('17959', 'Sky Way Medical Clinic'), ('18622', 'Skyhill Medical Centre'), ('19639', 'Skylit Medical Clinic'), ('18000', 'Skymed Medical Clinic Githunguri'), ('11800', 'Sloam Medical Clinic'), ('11014', 'Slope Optician'), ('18717', 'Slopes Medical Clinic'), ('19994', 'Slum Medical Clinic'), ('19552', 'Smiles Medical Centre'), ('19342', 'Snocx Medical Clinic'), ('16633', 'Snowview Medical Clinic'), ('15601', 'Soba River Health Centre'), ('18634', 'Soceno Pharmacy'), ('15602', 'Sochoi (AIC) Dispensary'), ('15603', 'Sochoi Dispensary'), ('19393', 'Social Service League (Nairobi )'), ('18045', 'Soget Dispensary'), ('15604', 'Sogon Dispensary'), ('15605', 'Sogoo Health Centre'), ('19331', 'Soin Health Care - Mfangano Street)'), ('14095', 'Soklo Dispensary'), ('17187', 'Soko Medical Clinic'), ('11802', 'Sokoke Dispensary'), ('11803', 'Sokoke Medical Clinic'), ('13188', 'Sokoni Arcade VCT'), ('18049', 'Soldier'), ('11015', 'Soldier Medical Clinic'), ('11016', 'Solea Medical Clinic'), ('15606', 'Solian Dispensary'), ('15607', 'Soliat Dispensary'), ('17575', 'Solio Dispensary'), ('17666', 'Sololo Makutano Dispensary'), ('12739', 'Sololo Mission Hospital'), ('19041', 'Solution Medical Clinic'), ('15608', 'Solyot Dispensary'), ('12740', 'Somare Dispensary'), ('11804', 'Sombo Dispensary'), ('11017', 'Somo Medical Clinic'), ('16132', 'Sonak Clinic'), ('15609', 'Sondany Dispensary'), ('14096', 'Sondu Health Centre'), ('12741', 'Songa Health Centre'), ('15610', 'Songeto Dispensary'), ('15611', 'Songonyet Dispensary'), ('14097', 'Sony Medical Centre'), ('20420', 'Sooma Dispensary'), ('17809', 'Sopa Lodge Dispensary'), ('15613', 'Sore Dispensary'), ('14098', 'Sori Lakeside Nursing and Maternity Home'), ('16673', 'Sorok Dispensary'), ('20386', 'SOS Children Medical Clinic'), ('13189', 'Sos Dispensary'), ('17945', 'Sos Medical Clinic (Eldoret East)'), ('14099', 'Sosera Dispensary'), ('15614', 'Sosian Dispensary'), ('15615', 'Sosiana Dispensary'), ('15616', 'Sosiani Health Centre'), ('19389', 'Sosio Medical Clinic'), ('15617', 'Sosiot Health Centre'), ('15618', 'Sosit Dispensary'), ('11805', 'Sosoni Dispensary'), ('17993', 'Soteni Dispensary'), ('15619', 'Sotik Health Centre'), ('14100', 'Sotik Highlands Dispensary'), ('17880', 'Sotik Town VCT'), ('15620', 'Sotit Dispensary'), ('13190', 'South B Clinic'), ('18005', 'South B Hospital Ltd'), ('13144', 'South B Police Band Dispensary'), ('18880', 'South Eastern Kenya University (Seku) Health Unit'), ('15622', 'South Horr Catholic Health Centre'), ('15621', 'South Horr Dispensary'), ('20395', 'South Ngariama Dispensary'), ('17390', 'Southern Health Care'), ('17693', 'Sowa Medcal Clinic'), ('13017', 'Soweto Kayole PHC Health Centre'), ('17470', 'Soweto Medical Clinic'), ('15623', 'Soy Health Centre'), ('16133', 'Soy Resource Centre'); INSERT INTO `facility_list` (`Facility_Code`, `Facility_Name`) VALUES ('16134', 'Soy Sambu Dispensary'), ('15624', 'Soymet Dispensary'), ('16135', 'Soysambu (ACK) Dispensary'), ('18761', 'Spa Nursing Home'), ('11807', 'Sparki Health Services'), ('17483', 'Speak and Act'), ('13192', 'Special Provision Clinic'), ('13193', 'Special Treatment Clinic'), ('18791', 'Sportlight Empowerment Group'), ('11018', 'Sports View CFW Medical Clinic'), ('18922', 'Springs Health Care Clinic'), ('20054', 'Springs of Life Lutheran Dispensary'), ('19973', 'Springs of Patmos Health Services'), ('19130', 'Sr Rhoda Medical Clinic'), ('19547', 'Srisathya Sai Medical Clinic'), ('11019', 'Ssema Medical Clinic'), ('16260', 'St Agnes Clinic'), ('12742', 'St Agnes Kiaganari'), ('14101', 'St Akidiva Memorial Hospital'), ('20020', 'St Akidiva Mindira Hospital - Mabera'), ('18219', 'St Alice (EDARP) Dandora'), ('18495', 'St Aloysius Gonzaga School Dispensary'), ('11020', 'St Andrew Umoja Medical Clinic'), ('17973', 'St Andrews Cc Rironi Dispensary'), ('11021', 'St <NAME> (ACK) Dispensary'), ('11808', 'St Andrews Medical Clinic'), ('18980', 'St Andrews Medical Clinic - Eldoret'), ('16136', 'St Andrews Othodox Clinic'), ('11022', 'St Angela Kingeero Clinic'), ('17362', 'St Angela Melici Health Centre'), ('17876', 'St Angela Merici Health Centre (Kingeero)'), ('19034', 'St Angelas Clinic'), ('12743', 'St Ann Hospital'), ('11023', 'St Ann Lioki Dispensary'), ('16805', 'St Ann Medical Clinic'), ('19716', 'St Ann Medical Clinic'), ('15625', 'St Ann Medical Clinic (Naivasha)'), ('11024', 'St Anne (ACK) Dispensary'), ('19825', 'St Anne CFW Clinic'), ('12744', 'St Anne Kariene Dispensary'), ('16544', 'St Anne Medical Centre (Mombasa)'), ('11607', 'St Anne Mida Catholic Dispensary'), ('16496', 'St Anne''s Cry For The World Clinic (Raimu)'), ('17142', 'St Annes Health Clinic'), ('19096', 'St Annes Medical Clinic Ongata Rongai'), ('13196', 'St Annes Medical Health Centre'), ('13197', 'St Ann''s Clinic'), ('18756', 'St Anns Medical Centre'), ('17989', 'St Anns Medical Centre'), ('19057', 'St Anns Medical Clinic'), ('11809', 'St Ann''s Medical Clinic'), ('20080', 'St Anselmo Medical Clinic'), ('15626', 'St Anthony Lemek Dispensary'), ('17203', 'St Anthony Medical Clinic'), ('15628', 'St Antony Health Centre'), ('18113', 'St Antony Medical Clinic'), ('15627', 'St Antony''s Abossi Health Centre'), ('12745', 'St Assisi Sisters of Mary Immaculate Nursing Home'), ('11027', 'St Augastine'), ('15629', 'St Augustine Youth Friendly Centre'), ('11028', 'St Austine Medical Clinic'), ('13822', 'St Barbara Mosocho Health Centre'), ('17723', 'St Barkita Dispensary Utawala'), ('14102', 'St Barnabas Dispensary'), ('18115', 'St Basil''s Catholic Dispensary'), ('13198', 'St Begson Clinic'), ('16526', 'St Bennedticto Health Centre'), ('15630', 'St Boniface Dispensary'), ('13199', 'St Bridget''s Mother & Child'), ('14661', 'St Bridgit Kalemunyang Dispensary'), ('15631', 'St Brigids Girls High School Dispensary'), ('15632', 'St Brigitas Health Centre'), ('15633', 'St Camellus Medical Clinic'), ('19615', 'St Camillus Health Centres'), ('14103', 'St Camillus Mission Hospital'), ('13200', 'St Catherine''s Health Centre'), ('15634', 'St Catherine''s Napetet Dispensary'), ('11029', 'St Cecilia Nursing Home'), ('11030', 'St Charles Lwanga Dispensary'), ('15957', 'St Charles Lwanga Health Centre'), ('18405', 'St Christopher Dispensary'), ('16137', 'St Claire Dispensary'), ('14104', 'St Clare Bolo Health Centre'), ('15635', 'St Clare Dispensary'), ('18465', 'St Clare Medical Clinic'), ('14105', 'St Consolata Clinic'), ('16138', 'St Damiano Nursing Home'), ('11031', 'St David Medical Clinic'), ('12746', 'St David''s Health Care'), ('19896', 'St Eliza Medical Clinic'), ('14106', 'St Elizabeth Chiga Health Centre'), ('15636', 'St Elizabeth Health Centre'), ('15089', 'St Elizabeth Lorugum Health Centre'), ('13739', 'St Elizabeth Lwak Mission Health Centre'), ('11813', 'St Elizabeth Medical Clinic Bakarani'), ('15637', 'St Elizabeth Nursing Home'), ('14489', 'St Faith Medical Clinic (Kimana)'), ('13201', 'St Florence Medical Care Health Centre'), ('13202', 'St Francis Com Hospital'), ('17943', 'St Francis Community Hospital (Kasarani)'), ('20262', 'ST Francis dispensary'), ('12748', 'St Francis Health Centre'), ('13203', 'St Francis Health Centre (Nairobi North)'), ('15639', 'St Francis Health Centre (Nakuru Central)'), ('19828', 'St Francis Health Clinic'), ('12749', 'St Francis Medical Clinic (Machakos)'), ('11032', 'St Francis Medical Clinic (Thika)'), ('18542', 'St Francis of Assisi Dispensary'), ('15640', 'St Francis Tinga Health Centre (Kipkelion)'), ('11033', 'St Frank Dispensing Centre'), ('15641', 'St Freda''s Cottage Hospital'), ('11034', 'St Gabriel Health Centre'), ('16344', 'St Getrude Dispensary'), ('15642', 'St Gladys Njoga Clinic'), ('11815', 'St Grace Medical Clinic'), ('14108', 'St Hellens Clinic'), ('11816', 'St Hillarias Medical Clinic'), ('12750', 'St Immaculate Clinic'), ('11035', 'St James Angilcan Church of Kenya Kiaritha Dispens'), ('11036', 'St James Clinic'), ('19121', 'St James Clinic'), ('19299', 'St James Medical Centre'), ('19033', 'St James Medical Clinic'), ('16685', 'St James Medical Clinic'), ('16870', 'St Jane Nursing Home'), ('19729', 'St John Afya Bora Medical Clinic'), ('12076', 'St John Baptist Ikalaasa Mission Dispensary'), ('16817', 'St John Catholic Dispensary (Nyeri North)'), ('15643', 'St John Cottage Health Centre'), ('13205', 'St John Hospital'), ('17936', 'St John Hospital Limited'), ('12510', 'St John Marieni Dispensary'), ('19448', 'St John Medical Centre'), ('20117', 'St John Medical Clinic'), ('15644', 'St John Medical Clinic (Kajiado)'), ('11038', 'St John Medical Clinic (Nyeri North)'), ('18411', 'St John Medical Surgical Centre'), ('11039', 'St John Ndururumo Medical Clinic'), ('17369', 'St John Orthodox Dispensary Kahuho'), ('13206', 'St Johns Ambulance'), ('19741', 'St John''s Clinic'), ('18408', 'St John''s Community Centre'), ('18222', 'St John''s Community Clinic Njiru'), ('17570', 'St John''s Dispensary (Kithoka)'), ('15645', 'St Johns Health Care'), ('14109', 'St John''s Karabach Dispensary'), ('17036', 'St John''s Nyabite'), ('11040', 'St Johns Thaita (ACK) Dispensary'), ('16882', 'St Jones &Ring Road Health Clinic'), ('11043', 'St Josef Medical Clinic'), ('17368', 'St Joseph (ACK) Kanyariri Dispensary'), ('13207', 'St Joseph (EDARP) Clinic'), ('17576', 'St Joseph Brothers'), ('12751', 'St Joseph Catholic Dispensary (Igembe)'), ('15646', 'St Joseph Catholic Dispensary (Laikipia East)'), ('11041', 'St Joseph Catholic Dispensary (Ruiru)'), ('11042', 'St Joseph Clinic (Muranga)'), ('12752', 'St Joseph Dispensary (Kabaa)'), ('15647', 'St Joseph Hospital'), ('16995', 'St Joseph Kavisuni Dispensary'), ('16550', 'St Joseph Maledi Clinic'), ('12753', 'St Joseph Medical Clinic (Kangundo)'), ('11044', 'St Joseph Medical Clinic (Thika)'), ('12754', 'St Joseph Medical Clinic (Yathui)'), ('19119', 'St Joseph Medical Clinic Kathiani'), ('18601', 'St Joseph Mission Dispensary Chumvini'), ('14110', 'St Joseph Mission Hospital'), ('13208', 'St Joseph Mukasa Dispensary'), ('16409', 'St Joseph Nursing Home'), ('17933', 'St Joseph Nursing Home'), ('12755', 'St Joseph School (Kabaa)'), ('13209', 'St Joseph W Dispensary (Westlands)'), ('19683', 'St Joseph''s Boys National School Disp'), ('13210', 'St Joseph''s Dispensary (Dagoretti)'), ('16248', 'St Joseph''s Dispensary (Machakos)'), ('19682', 'St Joseph''s Girls High School Disp'), ('13936', 'St Joseph''s Nyansiongo Health Centre'), ('14111', 'St Joseph''s Obaga Dispensary'), ('11817', 'St Joseph''s Shelter of Hope'), ('17807', 'St Joseph''s The Worker'), ('12756', 'St Joy Afya Clinic'), ('17252', 'St Jude Catholic Dispensary'), ('11046', 'St Jude Clinic'), ('14112', 'St Jude Health Centre (Icipe)'), ('17835', 'St Jude Medical Clinic'), ('17974', 'St Jude Medical Clinic'), ('16513', 'St Jude Medical Clinic (Maragua)'), ('19672', 'St Jude Theddeus Mc'), ('14113', 'St Jude''s Clinic'), ('13212', 'St Jude''s Health Centre'), ('13211', 'St Jude''s Medical Centre'), ('18198', 'St Judes Medical Clinic'), ('19603', 'St Judes Nursing Hospital'), ('15648', 'St Kevina Dispensary'), ('14114', 'St Kizito Health Centre'), ('12757', 'St Kizito Mission'), ('16345', 'St Ladislaus Dispensary'), ('17517', 'St Lawrence Dispensary'), ('15649', 'St Leonard Hospital'), ('19280', 'St Louis Community Hospital'), ('17370', 'St Lucy Medical Clinic'), ('12758', 'St Lucy''s Hospital'), ('20139', 'St Luke Clinic'), ('17238', 'St Luke Kihuro (ACK) Dispensary'), ('11047', 'St Luke Medical Care Clinic'), ('17169', 'St Luke Medical Centre'), ('11818', 'St Luke''s (ACK) Hospital Kaloleni'), ('13213', 'St Lukes (Kona) Health Centre'), ('16821', 'St Lukes (Molo)'), ('12759', 'St Lukes Cottage Hospital'), ('14116', 'St Luke''s Health Centre (Mbita)'), ('14117', 'St Luke''s Hospital'), ('18776', 'St Lukes Orthopaedic and Trauma Hospital'), ('18303', 'St Luke''s The Physician Medical Centre'), ('17391', 'St Mac''s Hospital'), ('11049', 'St Margret Family Care Clinic'), ('16742', 'St Mark Maternity'), ('18606', 'St Mark Medical Clinic'), ('19657', 'St Mark Medical Clinic'), ('12760', 'St Mark Medical Clinic (Kangundo)'), ('13214', 'St Mark Medical Clinic (Nairobi East)'), ('18047', 'St Marks'), ('12761', 'St Marks Dispensary (Kariene)'), ('19655', 'St Marks Hospital'), ('19231', 'St Marks Kigari Teachers College Dispensary'), ('14118', 'St Mark''s Lela Dispensary'), ('17340', 'St Marks Medical Clinic'), ('11050', 'St Mark''s Medical Clinic'), ('17567', 'St Martin Catholic Social Apostolate'), ('15650', 'St Martin De Porres (Mobile)'), ('15651', 'St Martin De Porres (Static)'), ('16644', 'St Martin Medical Clinic'), ('11048', 'St Mary (ACK) Dispensary (Ngariama)'), ('10746', 'St Mary (ACK) Mugumo Dispensary'), ('15652', 'St Mary Health Centre (Kiserian)'), ('11052', 'St Mary Health Clinic'), ('11053', 'St Mary Health Services'), ('11054', 'St Mary Laboratory (Mwea)'), ('18173', 'St Mary Magdalene Kanjuu Dispensary'), ('16778', 'St Mary Medical Clinic'), ('15653', 'St Mary Medical Clinic (Nakuru North)'), ('17748', 'St Mary Medical Clinic Gatundu'), ('11057', 'St Marys Clinic (Kangema)'), ('18248', 'St Mary''s Dispensary'), ('16139', 'St Mary''s Dispensary (Lugari)'), ('12762', 'St Marys Dispensary (Mwala)'), ('13217', 'St Mary''s Health Centre'), ('14119', 'St Mary''s Health Centre (Mbita)'), ('17940', 'St Mary''s Health Services'), ('16140', 'St Mary''s Health Unit Chelelemuk'), ('15654', 'St Mary''s Hospital (Gilgil)'), ('16141', 'St Mary''s Hospital (Mumias)'), ('15656', 'St Mary''s Kalokol Primary Health Care Programme'), ('15655', 'St Mary''s Kapsoya Dispensary'), ('13216', 'St Mary''s Medical Clinic'), ('13215', 'St Mary''s Medical Clinic'), ('12763', 'St Marys Medical Clinic (Kiaragana)'), ('11820', 'St Mary''s Medical Clinic (Malindi)'), ('11058', 'St Mary''s Medical Clinic (Muranga South)'), ('11055', 'St Mary''s Medical Clinic (Ruiru)'), ('12764', 'St Marys Medical Clinic (Runyenjes)'), ('13218', 'St Mary''s Mission Hospital'), ('18603', 'St Mary''s Mother & Child Medical Services'), ('11654', 'St Marys Msabaha Catholic Dispensary'), ('12765', 'St Marys Nguviu Dispensary'), ('16418', 'St Mary''s Yala Dispensary'), ('11059', 'St Mathews and Sarah Dispensary'), ('20037', 'St Mathews Kandaria Dispensary'), ('15657', 'St Mathews Maternity and Lab Services'), ('19438', 'St Maurice Medical Services'), ('14059', 'St Mercelline Roo Dispensary (Suba)'), ('12766', 'St Michael (Miaani) Mission Dispensary'), ('13219', 'St Michael Clinic'), ('19332', 'St Michael Community Nursing Home'), ('15658', 'St Michael Dispensary'), ('11060', 'St Michael Dispensary (Kangaita)'), ('18179', 'St Michael Goodwill Medical Clinic'), ('17741', 'St Michael Medical Clinic'), ('11061', 'St Michael Medical Clinic (Nyeri South)'), ('19194', 'St Michael Medical Clinic -Kangundo'), ('16250', 'St Michael Medical Services'), ('12768', 'St Michael Nursing Home'), ('16657', 'St Monica Catholic Dispensary (Nguutani)'), ('11062', 'St Monica Dispensary'), ('14120', 'St Monica Hospital'), ('17044', 'St Monica Medical Clinic'), ('15659', 'St Monica Medical Clinic (Dundori)'), ('15660', 'St Monica Medical Clinic (Nakuru)'), ('14121', 'St Monica Rapogi Health Centre'), ('15661', 'St Monica''s Nakwamekwi Dispensary'), ('10765', 'St Mulumba Mission Hospital'), ('18114', 'St Nicholas Medical Clinic'), ('14122', 'St Norah''s Clinc'), ('12769', 'St Orsola Mission Hospital'), ('13222', 'St Patrick Health Care Centre'), ('19297', 'St Patrick Medical Centre'), ('18305', 'St Patricks Dispensary'), ('15662', 'St Patrick''s Kanamkemer Dispensary'), ('14123', 'St Paul Dispensary'), ('18537', 'St Paul Ithiki (ACK ) Dispensary'), ('18548', 'St Paul Kiamuri (ACK) Dispensary'), ('12770', 'St Paul Medical Clinic (Makutano)'), ('18477', 'St Pauline Medical Clinic'), ('16143', 'St Pauline Nursing Home and Marternity'), ('17930', 'St Pauls Ejinja Dispensary'), ('14124', 'St Paul''s Health Centre'), ('18190', 'St Paul''s Hospital'), ('11823', 'St Paul''s Medical Clinic (Malindi)'), ('20224', 'St Pauls Ndumbuli Community Health Centre'), ('17392', 'St Pery''s Medical Clinic'), ('15663', 'St <NAME>'), ('13223', 'St Peter Dispensary'), ('15664', 'St Peter Kware Medical Clinic'), ('17462', 'St Peter Orthodox Church Dispenasary'), ('17982', 'St Peter Orthodox Kanjeru Dispensary'), ('17983', 'St Peters (ACK) Dispensary'), ('11066', 'St Peter''s (ACK) Medical Clinic'), ('18017', 'St Peter''s Catholic Dispensary (Ng''onyi)'), ('16978', 'St <NAME> (ACK) Dispensary'), ('11824', 'St Peter''s Hospital'), ('17141', 'St Peters Medical Clinic'), ('15665', 'St Peter''s Medical Clinic'), ('16050', 'St Philiphs Mukomari'), ('11067', 'St Philips (ACK) Dispensary Ndiriti'), ('13224', 'St Philips Health Centre'), ('12771', 'St Philomena Medical Clinic'), ('16145', 'St Pius Musoli Health Centre'), ('17488', 'St Raphael Arch Medical'), ('18515', 'St Raphael Dispensary'), ('11366', 'St Raphael Health Centre'), ('17683', 'St Raphael''s Clinic'), ('18843', 'St Richard Medical Clinic'), ('14125', 'St Ruth Clinic'), ('17406', 'St Stephen (ACK) Cura Dispensary'), ('17440', 'St Stephen''s Children Clinic Gatondo'), ('17429', 'St Stephen''s Kiandagae (ACK) Dispensary'), ('16146', 'St Susan Clinic'), ('11069', 'St Teresa Catholic Dispensary'), ('12772', 'St Teresa Medical Clinic'), ('19380', 'St Teresa Medical Clinic ( Zimmerman)'), ('11071', 'St Teresa Nursing Home'), ('15666', 'St Teresa Olokirikirai Dispensary'), ('13227', 'St Teresa''s Health Centre'), ('13226', 'St Teresa''s Health Centre (Nairobi North)'), ('13225', 'St Teresa''s Parish Dispensary'), ('11072', 'St Teresia Medical Clinic'), ('11825', 'St Terezia Medical Clinic'), ('17503', 'St Thadeus Medical Clinic'), ('11826', 'St Theresa Dispensary'), ('12303', 'St Theresa Kiirua Hospital (Kiirua)'), ('12774', 'St Theresa Thatha Mission Dispensary'), ('12775', 'St Theresas Riiji Health Centre'), ('15667', 'St Therese Dispensary'), ('15668', 'St Theresia of Jesus'), ('18435', 'St Thomas Maternity'), ('18501', 'St Thomas The Apostle Athi Catholic Dispensary'), ('11073', 'St Triza Medical Clinic'), ('19021', 'St Trizah Medical Clinic'), ('15669', 'St Ursula Dispensary'), ('11828', 'St Valeria Medical Clinic'), ('17413', 'St Veronica'), ('11074', 'St Veronica Dispensary Mukurweini'), ('18409', 'St Veronica EDARP Clinic'), ('15670', 'St Victors Medical Clinic'), ('13230', 'St Vincent Catholic Clinic'), ('14127', 'St Vincent Clinic (Kisumu East)'), ('13229', 'St Vincent Clinic (Nairobi East)'), ('14128', 'St Vincents De Paul Health Centre'), ('20445', 'St. Charle''s Medical Services'), ('13221', 'St. Odilia''s Dispensary'), ('20288', 'St. Tresa''s Medical Clinic'), ('20216', 'St.Catherine Catholic Church VCT'), ('20310', 'St.Charle''s Medical Services'), ('20468', 'ST.James Memorial Medical Clinic'), ('20248', 'St.Paul Clinic'), ('20378', 'St.Teresa Hospital Kiambu'), ('18909', 'Stadia Medical Clinic'), ('19028', 'Stage View Medical Clinic'), ('16527', 'Stanbridge Care Centre'), ('11829', 'Star Hospital'), ('14129', 'Star Maternity & Nursing Home'), ('15671', 'Star Medical Clinic'), ('11830', 'Star of Good Hope Medical Clinic'), ('20314', 'Star of the Sea Health Clinic'), ('19422', 'Starehe Boys Centre School Clinic'), ('20180', 'Star-Heal Medical Clinic'), ('16358', 'Starlight Mti Moja'), ('15672', 'Starlite Medical Clinic'), ('19276', 'Stars General Medical Clinic'), ('13231', 'State House Clinic'), ('11831', 'State House Dispensary (Mombasa)'), ('13232', 'State House Dispensary (Nairobi)'), ('15673', 'State House Dispensary (Nakuru)'), ('15674', 'State Lodge Dispensary'), ('18018', 'Station Side Makupa Clinic'), ('11832', 'Stella Maris Medical Clinic'), ('15675', 'Stgetrude Dispensary'), ('12776', 'Stone Athi Medical Clinic'), ('17700', 'Stops Medical Clinic Kenya Ltd'), ('18973', 'Stralight Medical Clinic'), ('18574', 'Strathmore University Medical Centre'), ('15676', 'Stream of Life Clinic'), ('14130', 'Suba District Hospital'), ('17790', 'Subati Medical Clinic'), ('16528', 'Subira Medical Clinic'), ('15677', 'Subukia Dispensary (Kipkelion)'), ('15678', 'Subukia Health Centre'), ('15679', 'Subuku Dispensary (Molo)'), ('11076', 'Subuku Dispensary (Nyandarua North)'), ('11077', 'Subuku Medical Clinic'), ('19381', 'Success Medical Services'), ('14204', 'Sucos Hospital'), ('16776', 'Sugarbaker Memorial Clinic'), ('17331', 'Sugoi A Dispensary'), ('15680', 'Sugoi B Dispensary'), ('17093', 'Sugumerga Dispensary'), ('14131', 'Suguta Health Centre'), ('15681', 'Suguta Marmar Catholic Dispensary'), ('15682', 'Suguta Marmar Health Centre'), ('12018', 'Suleman Farooq Memorial Centre'), ('12777', 'Sultan Hamud Sub District Hospital'), ('14132', 'Sulwe Clinic'), ('20246', 'Sulwe Dispensary'), ('14133', 'Sumba Community Dispensary'), ('18614', 'Sumba Medical Clinic'), ('15683', 'Sumbeiywet Dispensary'), ('15684', 'Sumeiyon Dispensary'), ('15685', 'Sumek Dispensary'), ('11078', 'Summit Medical Clinic'), ('16316', 'Sumoiyot Dispensary'), ('11833', 'Sun N'' Sand Medical Clinic'), ('14134', 'Suna Nursing and Maternity Home'), ('14135', 'Suna Rabuor Dispensary'), ('14136', 'Suna Ragana Dispensary'), ('18281', 'Sunbeam Medical Centre'), ('17175', 'Sunga Dispensary'), ('11079', 'Sunny Medical Clinic (Nyeri North)'), ('11080', 'Sunny Medical Clinic (Nyeri South)'), ('14137', 'Sunrise Clinic'), ('15686', 'Sunrise Evans Hospital'), ('16304', 'Sunrise Medical Clinic (Mandera East)'), ('19826', 'Sunset Medical Clinic'), ('18138', 'Sunshine Family Health Medicare Centre'), ('19351', 'Sunshine Medical & Diagnostic Centre (Nairobi)'), ('19530', 'Sunshine Medical Centre'), ('19052', 'Sunshine Medical Clinic'), ('15687', 'Sun-Shine Medical Clinic'), ('17827', 'Sunshine Medical Clinic (Kwale)'), ('15688', 'Sun-Shine Medical Clinic Annex'), ('18438', 'Sunton CFW Clinic'), ('19739', 'Sunview Maternity & Nursing Home'), ('15689', 'Supat Med Clinic'), ('19941', 'Super Drug Nursing Home'), ('11835', 'Super Medical Clinic'), ('13233', 'Supkem (Liverpool)'), ('20402', 'Support For Addiction Prevention & Treatment In Africa'), ('19355', 'Supreme Health Care (Ktda House-Nairobi)'), ('19852', 'Supreme Medical Clinic'), ('19637', 'Sure Drug Medical Clinic'), ('11347', 'Surgery Clinic'), ('11081', 'Surgical Consultant (Muranga South)'), ('17964', 'Surgury Clinic'), ('16407', 'Sururu Health Centre (CDF)'), ('15690', 'Survey Dispensary'), ('17686', 'Susamed Medical Clinic'), ('17103', 'Sutyechun Dispensary'), ('15692', 'Suwerwa Health Centre'), ('15693', 'Swari Model Health Centre'), ('15694', 'Sweet Waters Dispensary'), ('14138', 'Swindon Clinic'), ('19023', 'Swiss Cottage Hospital'), ('19394', 'Swop Clinic'), ('19719', 'Swop Kawangware'), ('19271', 'Swop Korogocho'), ('19429', 'Swop Outreach Project Clinic'), ('18896', 'Swop Thika Road'), ('16993', 'Syathani (Kyathani) Dispensary'), ('20118', 'Syokimau Medical Centre'), ('18819', 'Syokimau Medical Services'), ('18551', 'Syokithumbi Dispensary'), ('20421', 'Syomakanda Dispensary'), ('20447', 'Syomunyu Dispensary'), ('12780', 'Syongila (ACK) Dispensary'), ('12781', 'Syongila Dispensary'), ('12782', 'Syumile Dispensary'), ('14139', 'Tabaka Mission Hospital'), ('20322', 'Tabani Dispensary'), ('15695', 'Tabare Dispensary'), ('12783', 'Tabasamu Medical Clinic'), ('19779', 'Tabby Plaza ENT & Orthopaedic Clinic'), ('13234', 'Tabitha Medical Clinic'), ('15696', 'Tabolwa Dispensary'), ('15697', 'Tabuga (PCEA) Dispensary'), ('18010', 'Tachasis Dispensary'), ('15698', 'Tachasis Mission Dispensary'), ('19027', 'Tahidi Nursing Home'), ('17969', 'Taiba Medical Centre'), ('17020', 'Taito Community Dispensary'), ('15699', 'Taito Tea Dispensary'), ('13445', 'Takaba District Hospital'), ('16314', 'Takaba Nomadic Mobile'), ('11836', 'Takaungu Dispensary'), ('14140', 'Takawiri Dispensary'), ('20362', 'Takaywa Dispensary'), ('15700', 'Takitech Dispensary'), ('17170', 'Tala Dispensary'), ('12784', 'Tala Medical Services'), ('15701', 'Talai Dispensary'), ('20058', 'Talau Dispensary'), ('15702', 'Talek Health Centre'), ('19199', 'Tamam Medical Clinic'), ('15703', 'Tambach Sub-District Hospital'), ('16332', 'Tambach T T College Dispensary'), ('11083', 'Tambaya Dispensary'), ('11084', 'Tambaya Medical Clinic'), ('15704', 'Tamkal Dispensary'), ('16148', 'Tamlega Dispensary'), ('15705', 'Tamough Health Centre'), ('14141', 'Tamu Health Centre'), ('11085', 'Tana Clinic'), ('12785', 'Tana Medical Clinic (Machakos)'), ('12786', 'Tana Medical Clinic (Yatta)'), ('16149', 'Tanaka Nursing Home'), ('18112', 'Tanganyika Medical Clinic'), ('15706', 'Tangasir Dispensary'), ('15707', 'Tangulbei Health Centre'), ('15708', 'Tapach Dispensary'), ('17706', 'Taqwa Nursing Home'), ('14142', 'Taracha Dispensary'), ('14143', 'Taragai Dispensary'), ('15710', 'Tarakwa Dispensary'), ('17255', 'Tarakwa Dispensary (Eldoret West)'), ('14144', 'Taranganya Dispensary'), ('11837', 'Tarasaa Catholic Dispensary'), ('13446', 'Tarbaj Health Centre'), ('11838', 'Taru Dispensary'), ('18258', 'Tasia Family Medical Centre'), ('19152', 'Tasneem Pharmacy'), ('11086', '<NAME> (African Christian Churches and School'), ('11087', 'Tatu Dispensary'), ('17801', 'Taunet Dispensary'), ('11839', 'Tausa Health Centre'), ('11840', 'Taveta District Hospital'), ('11841', 'Taveta Meditech Centre'), ('12787', 'Tawa Sub-Distrct Hospial'), ('19044', 'Tawaheed Community Medical Clinic'), ('19043', 'Tawaheed Community Nursing Home'), ('19042', 'Tawakal Medical Clinic'), ('16305', 'Tawakal Medical Clinic (Mandera East)'), ('16551', 'Tawakal Medical Clinic (Msambweni)'), ('19061', 'Tawakal Medical Clinic and Laboratory Services'), ('11843', 'Tawfiq Muslim Hospital'), ('11844', 'Tawheed Dispensary'), ('17975', 'Tayabi Medical and Dental Centre'), ('19283', 'Tazama Dentel Clinic'), ('11845', 'Tchamalo Medical Clinic'), ('11846', 'Tchundwa Dispensary'), ('14473', 'Tdmp Tangulbei Dispensary'), ('15711', 'Tea Resaerch Dispensary'), ('16471', 'Tea Research Foundation Dispensary'), ('13235', 'Teachers Service Commission'), ('15712', 'Tebei Dispensary'), ('15713', 'Tebesonik Dispensary'), ('12788', 'Tefran Community Clinic'), ('15714', 'Tegat Health Centre'), ('15715', 'Tegego Dispensary'), ('12789', 'Tei Wa Yesu Health Centre'), ('17315', 'Telanet'), ('13236', 'Tena (PCEA) Clinic'), ('15716', 'Tenden Dispensary'), ('19230', 'Tender Loving Care CFW Clinic'), ('15717', 'Tenduet Dispensary'), ('17859', 'Tendwet Dispensary'), ('15718', 'Tenges Health Centre'), ('15719', 'Tenwek Mission Hospital'), ('15720', 'Tenwek Mobile'), ('15721', 'Teret Dispensary'), ('12773', '<NAME>''Lima Dispensary'), ('16417', 'Terige Dispensary (CDF)'), ('19624', 'Terminus Medical Clinic (Dandora)'), ('20185', 'Terry G Medical Clinic'), ('19184', 'Tesco Pharmacy Limited'), ('16150', 'Teso District Hospital'), ('18418', 'Tesorie Dispensary'), ('11095', 'Tevica Medical Clinic'), ('18058', 'Tewa Medical Clinic'), ('11088', 'Tewas Medical Clinic'), ('11848', 'Tezo Community Health Care'), ('12792', 'Thaana Nzau Dispensary'), ('11089', 'Thaara Medical Clinic'), ('18569', 'Thaene Medical Clinic'), ('19146', 'Thamare Dispensary'), ('12793', 'Thanantu Faith Clinic Dispensary'), ('11090', 'Thangathi Health Centre'), ('11091', 'Thangathi Health Clinic'), ('12795', 'Tharaka District Hospital'), ('12794', 'Tharaka Health Centre'), ('18328', 'The Aga Khan University Hospital (Meru)'), ('19376', 'The Arcade Medical Centre'), ('18304', 'The Co-Operative University College of Kenya Dispe'), ('20295', 'The Great Lakes Medical Centre'), ('19247', 'The Hanna Medicare Centre'), ('18041', 'The Haven Medical Clinic'), ('18415', 'The Hope Medical Centre-Awasi'), ('13004', 'The Karen Hospital'), ('18327', 'The Karen Hospital (Meru)'), ('18461', 'The Kitui Marternity and Nursing Home'), ('19434', 'The Mater Embakasi Clinic'), ('19543', 'The Mater Hospital (Westlands)'), ('17657', 'The Mater Hospital Buruburu'), ('13074', 'The Mater Hospital Mukuru'), ('18476', 'The Mater Hospital Thika Satellite'), ('19101', 'The Nairobi Hospital Out-Patient Centre Galeria'), ('19066', 'The Nyali Childrens Hospital (Mikindani)'), ('17966', 'The Omari Project'), ('20103', 'The Savannah Health Services Ltd'), ('16555', 'Theere Health Centre'), ('18636', 'Theluji Pharmacy Ltd'), ('15722', 'Thessalia Health Centre'), ('11092', 'Thiba Health Centre'), ('11093', 'Thigio Dispensary (Kiambu West)'), ('15723', 'Thigio Dispensary (Laikipia West)'), ('18578', '<NAME>'), ('10138', 'Thika Arcade Health Services'), ('16754', 'Thika High School For The Blind'), ('11094', 'Thika Level 5 Hospital'), ('11096', 'Thika Medical Clinic ENT'), ('11097', 'Thika Nursing Home'), ('16755', 'Thika Primary School For The Blind Clinic'), ('17950', 'Thika Road Health Services Ltd (Kasarani)'), ('17968', 'Thika Sasa Centre'), ('16278', 'Thim Lich Dispensary'), ('16228', 'Thimangiri Medical Clinic'), ('20073', 'Thimjope Dispensary'), ('12796', 'Thinu Health Centre'), ('12797', 'Thitani Health Centre'), ('12798', 'Thitha Dispensary'), ('20253', 'Thogoto Medical clinic'), ('17909', 'Thome Catholic Dispensary'), ('18029', 'Thome Clinic'), ('16859', 'Thonzweni Dispensary'), ('11098', 'Three In One Clinic'), ('11099', 'Thuita Clinic'), ('11100', 'Thumaita (ACK) Dispensary'), ('17066', 'Thumberera Dispensary'), ('11101', 'Thunguma Medical Clinic'), ('11102', 'Thunguri Medical Clinic'), ('11849', 'Thureya Medical Clinic'), ('11103', 'Thuthi Medical Clinic'), ('19795', 'Thuti Medical Clinic'), ('18699', 'Thuura Health Care'), ('18646', 'Thuura Health Care'), ('19141', 'Thuuru Dispensary'), ('20126', 'Thwake Community Dispensary'), ('20004', 'Tian Dispensary'), ('19298', 'Tibaland Chemistry & Lab'), ('16177', 'Tico - Bao VCT'), ('12799', 'Tigania Hospital'), ('16151', 'Tigoi Health Centre'), ('11104', 'Tigoni District Hospital'), ('12800', 'Tii Dispensary'), ('16368', 'Tiinei Dispensary'), ('20438', 'Tilangok Dispensary'), ('20460', 'Tilingwo dispensary'), ('20470', 'Tiloi Dispensary'), ('12801', 'Timau Catholic Dispensary'), ('19127', 'Timau Dental Clinic'), ('16634', 'Timau Integrated Medical Centre'), ('12802', 'Timau Sub-District Hospital'), ('15724', 'Timboiywo Dispensary'), ('11851', 'Timboni Community Dispensary'), ('15725', 'Timboroa Health Centre'), ('17759', 'Timbwani Medical Clinic'), ('11105', 'Time Health Care'), ('11106', 'Times Clinic'), ('16319', 'Times Medical Clinic'), ('15726', 'Tinderet Tea Dispensary'), ('14145', 'Tindereti Dispensary'), ('15728', 'Tinet Dispensary'), ('15727', 'Tinet Dispensary (Koibatek)'), ('14146', 'Tinga Health Centre'), ('11107', 'Tinganga (PCEA) Dispensary'), ('17094', 'Tinganga Catholic Dispensary'), ('14147', 'Tingare Dispensary'), ('14148', 'Ting''wangi Health Centre'), ('18746', 'Tionybei Medical Clinic'), ('15729', 'Tirimionin Dispensary'), ('15730', 'Tirriondonin Dispensary'), ('17176', 'Tiryo Dispensary (Nandi Central)'), ('14149', 'Tisinye Dispensary'), ('11852', 'Titila (AIC) Dispensary'), ('12803', 'Tiva Dispensary'), ('11853', 'Tiwi Rhtc'), ('15731', 'Todonyang Dispensary'), ('16315', 'Tolilet Dispensary'), ('11108', 'Tom King''s Laboratory'), ('15732', 'Tom Mboya Dispensary'), ('14150', 'Tom Mboya Memorial Health Centre'), ('18286', 'Tom Mboyaschool Cp Clinic'), ('14151', 'Tombe Health Centre (Manga)'), ('14152', 'Tonga Health Centre'), ('16152', 'Tongaren Health Centre'), ('15733', 'Toniok Dispensary'), ('11854', 'Tononoka Administration Police Dispensary & VCT'), ('18343', 'Tononoka CPC'), ('16682', 'Tonymed Medical Clinic'), ('11109', 'Tonys Medical Clinic'), ('15306', 'Top Choice Maternity and Nursing Home'), ('17946', 'Top Hill Medical Centre'), ('15734', 'Top Station Dispensary'), ('18189', 'Topcare Nursing Home'), ('20462', 'Topulen dispensary'), ('17022', 'Toretmoi Dispensary'), ('19612', 'Toric''s Nursing Home'), ('15735', 'Torongo Health Centre'), ('16675', 'Toror Medical Clinic'), ('15736', 'Tororek Dispensary'), ('15737', 'Torosei Dispensary'), ('15738', 'Tot Sub-District Hospital'), ('16403', 'Total Dispensary'), ('18356', 'Totoo Medical Clinic'), ('18544', 'Touch of Health - Well-Being Centre'), ('18957', 'Towba Clinic'), ('19045', 'Towfiq Medical Clinic'), ('11855', 'Town Centre Medical Clinic'), ('16635', 'Town Clinic Laboratory'), ('16636', 'Town Medical Clinic'), ('12804', 'Township Dispensary (Kitui)'), ('13237', 'Transcom Medical Services'), ('18105', 'Transcon Wendo Medical Services'), ('15739', 'Transmara District Hospital'), ('15740', 'Transmara Medicare'), ('11110', 'Trans-Saharan Medical Clinic'), ('11856', 'Travellers Medical Clinic'), ('11111', 'Trinity Afya Centre'), ('16750', 'Trinity Clinic (Ruiru)'), ('17237', 'Trinity Githiga (ACK) Dispensary'), ('13238', 'Trinity Medical Care Health Centre'), ('11858', 'Trinity Medical Clinic (Kilindini)'), ('20164', 'Trinity Mission Hospital'), ('19444', 'Trocare Medical Clinic'), ('19126', 'Tropical Medical Centre'), ('17767', 'Tropical Medical Clinic'), ('18335', 'True Light Medical Clinic'), ('11859', 'Tsangatsini Dispensary'), ('12805', 'Tseikuru Sub-District Hospital'), ('11861', 'Tudor District Hospital (Mombasa)'), ('11862', 'Tudor Health Care'), ('19069', 'Tudor Healthcare Services (Mikindani)'), ('18016', 'Tudor Nursing Home'), ('15741', 'Tugen Estate Dispensary'), ('16333', 'Tugumoi Dispensary'), ('15742', 'Tugumoi Dispensary'), ('16153', 'Tuikut Dispensary'), ('15743', 'Tuina Dipensary'), ('15744', 'Tuiyobei Dispensary'), ('17873', 'Tuiyoluk Dispensary'), ('15745', 'Tuiyotich Dispensary'), ('19046', 'Tulah Medical Services'), ('13447', 'Tulatula Dispensary'), ('12806', 'Tulia Dispensary'), ('12807', 'Tulila Dispensary'), ('12808', 'Tulimani Dispensary'), ('17403', 'Tulwet Dispensary'), ('15746', 'Tulwet Dispensary (Buret)'), ('16393', 'Tulwet Dispensary (Kuresoi)'), ('15747', 'Tulwet Health Centre'), ('20190', 'Tumaini Africa'), ('19647', 'Tumaini Baraka Medical Clinic'), ('18285', 'Tumaini Childrens Home Out Patient Clinic'), ('15748', 'Tumaini Clinic'), ('17371', 'Tumaini Clinic (Kiambu West)'), ('11115', 'Tumaini Clinic (Kigumo)'), ('11116', 'Tumaini Clinic (Mwea)'), ('19092', 'Tumaini Clinic Voi'), ('16511', 'Tumaini Clinic/Laboratory'), ('18557', 'Tumaini DiSC - Asembo Bay'), ('17914', 'Tumaini Health Services (Makindu)'), ('17917', 'Tumaini Maternity and Nursing Home (Kibwezi)'), ('16637', 'Tumaini Medial Clinic (Miriga Mieru West)'), ('16651', 'Tumaini Medical Centre'), ('17385', 'Tumaini Medical Centre'), ('18296', 'Tumaini Medical Centre (Tezo)'), ('19972', 'Tumaini Medical Centre-Komothai'), ('11863', 'Tumaini Medical Cl Dzitsoni'), ('11865', 'Tumaini Medical Clinic'), ('16638', 'Tumaini Medical Clinic (Buuri)'), ('18478', 'Tumaini Medical Clinic (Kabaa)'), ('11864', 'Tumaini Medical Clinic (Kilindini)'), ('12810', 'Tumaini Medical Clinic (Kitui)'), ('11117', 'Tumaini Medical Clinic (Makuyu)'), ('16529', 'Tumaini Medical Clinic (Malindi)'), ('16204', 'Tumaini Medical Clinic (Marsabit)'), ('18704', 'Tumaini Medical Clinic (Meru)'), ('11118', 'Tumaini Medical Clinic (Nyandarua North)'), ('11119', 'Tumaini Medical Clinic (Nyeri North)'), ('11120', 'Tumaini Medical Clinic (Nyeri South)'), ('19138', 'Tumaini Medical Clinic (Tezo)'), ('17866', 'Tumaini Medical Clinic (Thika West)'), ('15749', 'Tumaini Medical Clinic (Turkana Central)'), ('15750', 'Tumaini Medical Clinic (Wareng)'), ('18710', 'Tumaini Medical Clinic (Yatta)'), ('16639', 'Tumaini Medical Clinic Laboratory'), ('19183', 'Tumaini Medical Clinic Yatta'), ('11121', 'Tumaini Medicare (Kandara)'), ('18771', 'Tumaini Multi - Counselling Centre'), ('19396', 'Tumaini Mwangaza ( Korogocho)'), ('11122', 'Tumaini National Youth Service Dispensary'), ('12809', 'Tumaini Rh Clinic'), ('20437', 'Tumaini Wellness Centre'), ('15751', 'Tumoi Dispensary'), ('11124', 'Tumutumu (PCEA) Hospital'), ('11123', 'Tumutumu Community Medical Centre'), ('12811', 'Tunawanjali Clinic'), ('12812', 'Tungutu Dispensary'), ('20469', 'Tunoiwo Dispensary'), ('11125', 'Tunuku Medical Clinic'), ('12813', 'Tunyai Dispensary'), ('15752', 'Tunyo Dispensary'), ('17620', 'Tuonane VCT'), ('12814', 'Tupendane Dispensary'), ('11126', 'Turasha Dispensary'), ('12815', 'Turbi Dispensary (Marsabit North)'), ('16154', 'Turbo Forest Dispensary'), ('15753', 'Turbo Health Centre'), ('16820', 'Turi (PCEA) Dispensary'), ('18103', 'Turi AIC Health Centre'), ('16406', 'Turi Dispensary (CDF)'), ('15754', 'Turkwel Dispensary (Loima)'), ('15755', 'Turkwel Health Centre'), ('11127', 'Turuturu Dispensary'), ('19553', 'Tusker Dental Laboratory Services & Laboratory'), ('19555', 'Tusker House Medical Centre'), ('11129', 'Tuthu Dispensary'), ('18809', 'Tutini Dispensary'), ('15756', 'Tuturung Dispensary'), ('15757', 'Tuum Dispensary'), ('18109', 'Tuungane'), ('18503', 'Tuungane Centre Awendo'), ('18502', 'Tuungane Centre Rongo'), ('16663', 'Tuungane Youth Centre (Kisumu East)'), ('14154', 'Tuungane Youth Centre (Mbita)'), ('17166', 'Tuungane Youth Transition Centre'), ('12816', 'Tuuru Catholic Health Centre'), ('12817', 'Tuvaani Dispensary'), ('16351', 'Twiga Dispensary'), ('12818', 'Twimyua Dispensary'), ('19133', 'Twins Bell'), ('12819', 'Tyaa Kamuthale Dispensary'), ('19652', 'Tyaa Medical Clinic'), ('17614', 'Uamani Dispensary'), ('15758', 'Uasin Gishu District Hospital'), ('11130', 'Ucheru Community Health Centre'), ('20350', 'Ufalme Medical Centre'), ('14155', 'Ugina Health Centre'), ('20444', 'Ugua Pole Clinic'), ('12820', 'Ugweri Disp'), ('17532', 'Uhembo Dispensary'), ('13239', 'Uhuru Camp Dispensary (O P Admin Police)'), ('15759', 'Uhuru Dispensary'), ('17404', 'Uhuru Presitige Health Care'), ('14107', 'Uhuyi Dispensary'), ('12821', 'Ukasi Dispensary'), ('18090', 'Ukasi Model Health Centre'), ('12822', 'Ukia Dispensary'), ('11867', 'Ukunda Diani Catholic Dispensary'), ('16552', 'Ukunda Medical Clinic'), ('16553', 'Ukunda Primary Health Care Dispensary'), ('18215', 'Ukuu MCK Dispensary'), ('14156', 'Ukwala Health Centre'), ('11131', 'Ukweli Medical Clinic'), ('14157', 'Ulanda Dispensary'), ('11132', 'Ultra Sound & X-Ray Clinic'), ('14158', 'Ulungo Dispensary'), ('13799', 'Uluthe Dispensary'), ('16791', 'Umala Dispensary'), ('20398', 'Umbrella Health Clinic'), ('17530', 'Umer Dispensary'), ('19607', 'Umma CBO'), ('13240', 'Umoja Health Centre'), ('13241', 'Umoja Hospital'), ('20187', 'Umoja III Medical Centre'), ('11133', 'Umoja Medical Clinic'), ('15760', 'Umoja Medical Clinic (Eldoret West)'), ('18727', 'Umoja Medical Clinic (Imenti North)'), ('11134', 'Umoja Medical Clinic (Muranga North)'), ('19627', 'Umoja Medical Clinic- Bombolulu'), ('18233', 'Umoja VCT Centre Stand Alone'), ('20242', 'Unga Dispensary'), ('12823', 'Ung''atu Dispensary'), ('15761', 'Unilever Central Hospital'), ('16181', 'Union Medical Dispensary'), ('18036', 'Unique Medical Clinic (Moyale)'), ('11135', 'Unique Tambaya Medical Clinic'), ('17032', 'Unison Medical Clinic'), ('19948', 'United States International University VCT'), ('19399', 'Unity Health Care'), ('18334', 'Unity Nursing Home'), ('18907', 'Universal M Clinic'), ('12824', 'Universal Medical Clinic'), ('19710', 'Universal Medical Clinic (Nyeri North)'), ('19292', 'Universal Medical Clinic (Samburu)'), ('17634', 'University of East Africa-Baraton VCT'), ('18352', 'University of Nairobi Centre of HIV Prevention and'), ('13242', 'University of Nairobi Dispensary'), ('19527', 'University of Nairobi Health Services'), ('20098', 'University of Nairobi Institute of Tropical and Infections Disease (UNITID)'), ('20448', 'University Of Nairobi Kitui Drop In Centre'), ('18518', 'University of Nairobi Marps Project Clinic'), ('20203', 'University of Nairobi Marps Project Mwingi'), ('18427', 'University of Nairobi Staff Students Clinic'), ('11136', 'Unjiru Health Centre'), ('19285', 'Unmet Health Foundation'), ('18345', 'Uon Thika Drop In Centre Ii (Chivpr)'), ('17243', 'Upec Chebaiywa Dispensary'), ('18726', 'Upendo Clinic'), ('12825', 'Upendo Clinic (Imenti North)'), ('16155', 'Upendo Clinic (Navakholo)'), ('19476', 'Upendo Clinic Makadara'), ('13243', 'Upendo Dispensary'), ('11870', 'Upendo Health Care Clinic'), ('19367', 'Upendo Medica Clinic'), ('11137', 'Upendo Medical Care'), ('19375', 'Upendo Medical Centre (Githurai 44)'), ('19507', 'Upendo Medical Clinic'), ('12826', 'Upendo Medical Clinic (Kitui)'), ('16640', 'Upendo Medical Laboratory'), ('18062', 'Upendo VCT Centre'), ('11138', 'Uplands Forest Dispensary'), ('15763', 'Upper Solai Health Centre'), ('17183', 'Uradi Health Centre'), ('18142', 'Urafiki Medical Clinic'), ('12828', 'Uran Health Centre'), ('14159', 'Urenga Dispensary'), ('12829', 'Uringu Health Centre'), ('14160', 'Uriri Dispensary'), ('14161', 'Uriri Health Centre'), ('11139', 'Uruku Dispensary'), ('12830', 'Uruku GK Dispensary'), ('12831', 'Uruku Health Centre'), ('14162', 'Usao Health Centre'), ('14163', 'Usenge Dispensary'), ('13245', 'Ushirika Medical Clinic'), ('18949', 'Ushirika Medical Clinic Maara'), ('18364', 'Usiani Dispensary'), ('14164', 'Usigu Dispensary'), ('16664', 'Usoma Dispensary'), ('12832', 'Usueni Dispensary'), ('11873', 'Utange Dispensary'), ('17838', 'Utangwa Dispensary'), ('13448', 'Utawala Dispensary'), ('18464', 'Utawala Estate Health Centre'), ('11141', 'Uthiru Dispensary'), ('19796', 'Utugi (Olk) Medical Clinic'), ('12833', 'Utugi Medical Clinic'), ('18193', 'Utugi Medical Clinic Kitengela'), ('12834', 'Utulivu Clinic'), ('20110', 'Utuneni Dispensary'), ('20338', 'Uturini Community Dispensary'), ('17441', 'Uvete Dispensary'), ('17845', 'Uviluni Dispensary'), ('16741', 'Uvoosyo Medical Clinic'), ('14165', 'Uyawi Dispensary'), ('13846', 'Uzima Clinic'), ('13246', 'Uzima Dispensary'), ('19614', 'Uzima Medical Cliinic'), ('17436', 'Uzima Medical Clinic'), ('19159', 'Uzima Medical Clinic (Chuka)'), ('17565', 'Uzima Medical Clinic (Githamba)'), ('12835', 'Uzima Medical Clinic (Imenti South)'), ('11876', 'Uzima Medical Clinic (Kilifi)'), ('11877', 'Uzima Medical Clinic (Lamu)'), ('11878', 'Uzima Medical Clinic (Malindi)'), ('19140', 'Uzima Medical Clinic (Meru)'), ('18243', 'Uzima Medical Clinic (Nandi Central)'), ('11144', 'Uzima Medical Clinic (Nyeri North)'), ('11145', 'Uzima Medical Clinic (Thika)'), ('19049', 'Uzima Medical Clinic Namanga'), ('18635', 'Uzima Medical Services'), ('18621', 'Uzima Medicare Clinic'), ('17956', 'Uzima VCT Centre'), ('15764', 'Valley Hospital'), ('17546', 'Van Den Berg Clinic'), ('11879', 'Vanga Health Centre'), ('18747', 'Vegpro Delamere Pivot Medical Clinic (Naivasha)'), ('18202', 'Vegpro In House Clinic'), ('17887', 'Venoma Medical Clinic'), ('14166', 'Verna Health Centre'), ('14167', 'Viagenco Medical Centre'), ('18619', 'Vichabem Medical Clinic'), ('18141', 'Vicodec Medical Clinic'), ('16262', 'Victoria Clinic'), ('18136', 'Victoria Medical Centre'), ('18108', 'Victoria Medical Clinic'), ('17376', 'Victoria Sub District Hospital'), ('16156', 'Victorious Living Ministries (Vlm) Dispensary'), ('11146', 'Victors Medical Clinic'), ('19911', 'Victory &Hope Medical Clinic Services'), ('13247', 'Victory Hospital'), ('11147', 'Victory Medical Clinic'), ('19491', 'Victory Medicare'), ('17491', 'Victory Revival Medical Clinic'), ('19667', 'Viebe MC'), ('11148', 'Viewpoint Clinic'), ('20157', 'Vigarace Health services'), ('19086', 'Vigombonyi SDA Clinic'), ('11880', 'Vigurungani Dispensary'), ('16157', 'Vihiga District Hosptial'), ('16158', 'Vihiga Health Centre'), ('20160', 'Vijana Against Aids and drug Abuse (juja)'), ('20174', 'Vikunga Dispensary'), ('16545', 'Vikwatani Community Medical Clinic'), ('18657', 'Village Hope Core International'), ('18092', 'Vines Kenya Htc Centre'), ('15765', 'Vinet Medical Clinic'), ('18741', 'Vipawa Medical Services'), ('11881', 'Vipingo Rural Demonstration Health Centre'), ('19485', 'Vips Health Servises'), ('17689', 'Viragoni Dispensary'), ('20175', 'Virhembe Medical Clinic'), ('11149', 'Virmo Clinic'), ('11882', 'Visa Oshwol Dispensary'), ('16190', 'Vishakani Dispensary'), ('19758', 'Vision Dental Clinic'), ('19810', 'Vision Medical Clinic'), ('11150', 'Vision Medical Clinic'), ('17849', 'Vision Medical Clinic Butere'), ('13248', 'Vision Peoples Inter Health Centre'), ('11883', 'Vitengeni Health Centre'), ('11884', 'Vitsangalaweni Dispensary'), ('17687', '<NAME>'), ('19630', 'Viva Afya Medical Clinic'), ('18368', 'Viva Afya Medical Clinic (Matopeni)'), ('19089', 'Voi Dental'), ('17704', 'Voi Medical Centre'), ('19090', 'Voi Medical Clinix'), ('17703', 'Voi Roadside Clinic'), ('17442', 'Vololo Dispensary'), ('17778', 'Voo Health Centre'), ('18826', 'Vorhca Stand Alone'), ('18323', 'Vostrum Clinic'), ('17937', 'Vote Dispensary'), ('15766', 'Vuma VCT'), ('17915', 'Vumilia Medical Clinic'), ('11886', 'Vutakaka Medical Clinic'), ('11887', 'Vyongwani Dispensary'), ('12837', 'Vyulya Dispensary'), ('18967', 'Wa Tonny Clinic'), ('11888', 'Waa Health Centre'), ('11151', 'Wa-Anne Medical Clinic'), ('12838', 'Wachoro Dispensary'), ('16808', 'Wachoro Medical Clinic'), ('16792', 'Wagai Dispensary'), ('13449', 'Wagalla Health Centre'), ('17820', 'Wagalla Health Centre'), ('13450', 'Wagberi Dispensary'), ('17438', 'Wagoro Dispensary (Rarieda)'), ('14168', 'Wagwe Health Centre'), ('18123', 'Wahome Health Clinic'), ('11152', 'Wahundura Dispensary'), ('17841', 'Waia Dispensary'), ('11153', 'Waiganjo Clinic'), ('11154', 'Waihara Medical Clinic'), ('11155', 'Wairungu Clinic'), ('12839', 'Waita Health Centre'), ('13249', 'Waithaka Health Centre'), ('13451', 'Wajir Bor Health Centre'), ('13452', 'Wajir District Hospital'), ('17743', 'Wajir Girls Dispensary'), ('19181', 'Wajir Medical City Clinic'), ('13453', 'Wajir Medical Clinic'), ('18166', 'Wajir North Nomadic Clinic'), ('18651', 'Wajir Tb Manyatta Sub - District Hospital'), ('11156', 'Waka Maternity Home'), ('11157', 'Wakagori Medicalclinic'), ('11158', 'Wakamata Dispensary'), ('16479', 'Wakhungu Dispensary'), ('13250', 'Wakibe Clinic'), ('17045', 'Wakor Dispensary'), ('14169', 'Wakula Health Centre'), ('12840', 'Walda Health Centre'), ('11889', 'Waldena Dispensary'), ('17923', 'Walking With Maasai Community Health Clinic (Olort'), ('18164', 'Walmer Eye Clinic'), ('19943', 'Waluku Dispensary'), ('11159', 'Wama Medical Clinic (Kiganjo)'), ('11160', 'Wama Medical Clinic (Mukaro)'), ('15767', 'Wama Nursing Home'), ('11161', 'Wamagana Health Centre'), ('11162', 'Wamagana Medical Clinic'), ('15768', 'Wamba Health Centre'), ('18229', 'Wamboo Dispensary'), ('11164', 'Wamumu Dispensary'), ('13251', 'Wamunga Health Clinic'), ('12841', 'Wamunyu Health Centre'), ('15770', 'Wanainchi Jamii Materinty and Nursing Home'), ('19692', 'Wanainchi Medical Clinic'), ('15265', 'Wanainchi Medical Clinic'), ('11165', 'Wananchi Clinic'), ('20082', 'Wananchi Clinic Githunguri- Kiambu'), ('16641', 'Wananchi Health Services'), ('16642', 'Wananchi Health Services Laboratory'), ('11166', 'Wananchi Medical Centre'), ('17414', 'Wananchi Medical Clinic'), ('15771', 'Wananchi Medical Clinic (Kajiado)'), ('11890', 'Wananchi Medical Clinic (Kilindini)'), ('18117', 'Wananchi Medical Clinic (Mwingi)'), ('20101', 'Wananchi Medical Clinic (Nyambari)'), ('19789', 'Wananchi Medical Clinic (Nyandarua)'), ('18933', 'Wananchi Medical Clinic Maara'), ('11891', 'Wananchi Nursing Home'), ('11167', 'Wandumbi Dispensary'), ('11168', 'Wanduta Medical Clinic'), ('20252', 'Wanemed Medical Clinic'), ('18283', 'Wanganga Health Centre'), ('11169', 'Wangema (African Christian Churches and Schools) C'), ('11170', 'Wangige Health Centre'), ('20074', 'Wangiya Dispensary'), ('15772', 'Wangu Maternity Home'), ('13252', 'Wangu Medical Clinic'), ('11171', 'Wanjengi Dispensary'), ('11172', 'Wanjerere Dispensary'), ('11173', 'Wanjohi Health Centre'), ('20387', 'Wankam Medical clinic'), ('17420', 'Wanyaga Community Dispensary'), ('12842', 'Wanzoa Dispensary'), ('20427', 'Wara'), ('16813', 'Warankara Health Centre'), ('13253', 'Warazo Clinic'), ('19711', 'Warazo Jet Catholic Dispensary'), ('11175', 'Warazo Medical Clinic (Ruiru)'), ('11176', 'Warazo Rural Health Centre'), ('20358', 'Wargadud Dispensary'), ('13455', 'Wargadud Health Centre'), ('19047', 'Warsan Health Services'), ('11177', 'Warui Medical Clinic'), ('17031', 'Wasammy Medical Clinic'), ('15773', 'Wa-Sammy Medical Clinic'), ('17096', 'Waseges Dispensary'), ('11892', 'Wasini Dispensary'), ('17774', 'Waso AIPCA Dispensary (Isiolo)'), ('16953', 'Waso Rongai Dispensary'), ('16159', 'Wasundi Clinic'), ('11893', 'Watamu (SDA) Dispensary'), ('11894', 'Watamu Community Health Care'), ('11895', 'Watamu Dispensary'), ('11897', 'Watamu Hospital'), ('11896', 'Watamu Maternity and Nursing Home'), ('18012', 'Watanu SDA Dispensary'), ('14170', 'Wath Onger Dispensary'), ('12843', 'Watoto Clinic'), ('11178', 'Watuka Dispensary'), ('14171', 'Waware Dispensary'), ('11898', 'Wayani Medical Clinic (Changamwe)'), ('17667', 'Waye Godha Dispensary'), ('15775', 'Wayside Clinic'), ('19284', 'Wayside Medical & Dental Clinic'), ('17080', 'Wayu Boru'), ('11900', 'Wayu Dispensary'), ('16160', 'Webuye Health Centre'), ('16161', 'Webuye Hospital'), ('16162', 'Webuye Nursing Home'), ('16163', 'Webuye Surgical'), ('11179', 'Wega Medical Clinic'), ('15776', 'Wei Dispensary'), ('11180', 'Weithaga (ACK) Dispensary'), ('20100', 'Wekoye Medical Clinic'), ('16780', 'Welfare Medical Clinic'), ('11181', 'Wellness Medical Clinic'), ('18860', 'Wellness Program KWS Hq'), ('11901', 'Wema Catholic Dispensary'), ('11902', 'Wema Centre Medical Clinic'), ('13255', 'Wema CFW Clinic'), ('19855', 'Wema Laboratory'), ('17394', 'Wema Medical Clinic'), ('19036', 'Wema Medical Clinic B'), ('18383', 'Wema Medical Clinic-Mshomoroni'), ('13256', 'Wema Nursing Home'), ('19997', 'Wema Private Clinic'), ('18234', 'Wendani Medical Services'), ('11182', 'Wendiga Dispensary'), ('11903', 'Wenje Dispensary'), ('13257', 'Wentworth Hospital'), ('15777', 'Weonia Dispensary'), ('12845', 'Weru Dispensary'), ('11183', 'Weru Health Centre (Nyandarua South)'), ('11904', 'Werugha Health Centre'), ('15778', 'Wesley Health Centre'), ('18918', 'West End Medical Solutions'), ('15780', 'West Gate Dispensary'), ('15779', 'West Health Centre'), ('19211', 'West Wing Diagnostic and Laboratory'), ('20027', 'Westgates Medical Centre'), ('19663', 'Westlands District Health Management Team'), ('11905', 'Westlands Health Care Services'), ('13258', 'Westlands Health Centre'), ('19494', 'Westlands Medical Centre'), ('18455', 'Westwood Medical Centre'), ('11906', 'Wesu District Hospital'), ('18448', 'What Matters Mission Dispensary'), ('18834', 'Wheel Kenya Medical Clinic'), ('17487', 'Whemis'), ('19524', 'Wide Medical Services'), ('14172', 'Wiga Dispensary'), ('12846', 'Wii Dispensary'), ('16925', 'Wikithuki Dispensary'), ('19909', 'Wikondiek Dispensary'), ('17543', 'Wildfire Clinic'), ('20017', 'Wilwinns Nursing Home'), ('19947', 'Wima Medical Clinic (Samburu East)'), ('15781', 'Winas Medical Clinic'), ('12848', 'Wingemi Health Centre'), ('14173', 'Winjo Dispensary'), ('15782', 'Winners Medical Clinic'), ('12849', 'Winzyeei Health Centre'), ('14174', 'Wire Dispensary'), ('17889', 'Withare Dispensary'), ('11186', 'Witima Health Centre'), ('11907', 'Witu Health Centre'), ('15783', 'Wiyeta Dispensary'), ('15784', 'Wiyumiririe Dispensary'), ('19048', 'Women Initiative Health Services'), ('18873', 'Wondeni Dispensary'), ('12850', 'Woodlands Hospital'), ('13259', 'Woodley Clinic'), ('16514', 'Woodpark Med Clinic'), ('18214', 'Woodshaven Medical Centre'), ('13260', 'Woodstreet Nursing Home'), ('19067', 'Word of Faith Church Dispensary'), ('18253', 'World Provision Centre VCT (Athi River)'), ('17906', 'World Provision VCT'), ('19889', 'World Provision Wellness Centre'), ('11188', 'Wote Clinic'), ('18133', 'Wote Health Clinic'), ('18144', 'Wote Medical Clinic'), ('18203', 'Wumiisyo Medical Clinic'), ('19735', 'Wundanyi GK Prisons'), ('11908', 'Wundanyi Sub-District Hospital'), ('11909', 'Wusi-Wutesia (ACK) Dispensary'), ('19502', 'X Press Medical Clinic'), ('14487', 'X-Cellent Medical Centre'), ('18492', 'Xposha VCT Centre'), ('19854', 'X-Ray Screening Centre'), ('17598', 'Yaathi Dispensary'), ('17579', 'Yaballo Dispensary'), ('13456', 'Yabicho Health Centre'), ('20334', 'Yago Community Dispensary'), ('16279', 'Yago Dispensary'), ('12851', 'Yakalia Dispensary'), ('17069', 'Yala Dispensary'), ('14175', 'Yala Sub-District Hospital'), ('17505', 'Yanja Medical Clinic'), ('12852', 'Yanzuu Health Centre'), ('13457', 'Yassin Clinic'), ('16652', 'Yathui Dispensary'), ('18206', 'Yatoi'), ('12853', 'Yatta Health Centre'), ('12854', 'Yatwa Dispensary'), ('15785', 'Yatya Dispensary'), ('16963', 'Yekanga Dispensary'), ('11911', 'Yeshua Medical'), ('17550', 'Yikivumbu Dispensary'), ('12855', 'Yimwaa Dispensary'), ('20270', 'Yinthungu Dispensary'), ('20221', 'Yoef Mediacl Clinic'), ('17584', 'Yofak VCT'), ('14176', 'Yokia Dispensary'), ('12856', 'Yongela Dispensary'), ('18677', 'Yoonye Dispensary'), ('17690', 'Young Generation Centre Dispensary (Med 25)'), ('13458', 'Young Muslim Dispensary'), ('16165', 'Your Family Clinic'), ('20124', 'Youth Empowerment Center Ngong'), ('13459', 'Yumbis Dispensary'), ('12857', 'Yumbu Dispensary'), ('20087', 'Yunasi'), ('12858', 'Yururu Medical Clinic'), ('15786', 'Ywalateke Dispensary'), ('19020', 'Zahri Medical Clinic'), ('11189', 'Zaina Dispensary'), ('11190', '<NAME> Laboratory'), ('13460', 'Zakma Medical Clinic'), ('15787', 'Zam Zam Medical Services'), ('17863', 'Zaro Nursing Clinic (Likoni)'), ('11192', 'Zawadi Clinic'), ('11193', '<NAME>'), ('18517', 'Zennith Community Project'), ('18374', 'Ziani Dispensary'), ('17892', 'Zigira (Community) Dispensary'), ('19273', 'Zimerbreeze Medical Centre'), ('19378', 'Zimma Health Care'), ('13261', 'Zimmerman Medical Dispensary'), ('13262', 'Zinduka Clinic'), ('12859', 'Zion Medical Clinic'), ('20283', 'Zioni II Medical Centre'), ('11913', 'Ziwa La Ng''ombe Medical Clinic'), ('17220', 'Ziwa SDA'), ('15788', 'Ziwa Sub-District Hospital'), ('11915', 'Ziwani Dispensary'), ('16997', 'Zombe Catholic Dispensary'), ('20313', 'Zombe medical clinic'); -- -------------------------------------------------------- -- -- Table structure for table `global_measures` -- CREATE TABLE IF NOT EXISTS `global_measures` ( `user_id` int(11) NOT NULL DEFAULT '0', `name` varchar(128) COLLATE latin1_general_ci DEFAULT NULL, `range` varchar(1024) COLLATE latin1_general_ci DEFAULT NULL, `test_id` int(10) NOT NULL DEFAULT '0', `measure_id` int(10) NOT NULL DEFAULT '0', `unit` varchar(64) COLLATE latin1_general_ci DEFAULT NULL, PRIMARY KEY (`user_id`,`test_id`,`measure_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci; -- -------------------------------------------------------- -- -- Table structure for table `import_log` -- CREATE TABLE IF NOT EXISTS `import_log` ( `id` int(11) NOT NULL AUTO_INCREMENT, `lab_config_id` int(10) NOT NULL, `successful` int(1) DEFAULT NULL, `flag` int(1) DEFAULT NULL, `user_id` int(11) DEFAULT NULL, `country` varchar(100) COLLATE latin1_general_ci DEFAULT NULL, `lab_name` varchar(100) COLLATE latin1_general_ci DEFAULT NULL, `db_name` varchar(100) COLLATE latin1_general_ci DEFAULT NULL, `remarks` varchar(250) COLLATE latin1_general_ci DEFAULT NULL, `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=4 ; -- -------------------------------------------------------- -- -- Table structure for table `infection_report_settings` -- CREATE TABLE IF NOT EXISTS `infection_report_settings` ( `id` int(10) unsigned NOT NULL DEFAULT '0', `group_by_age` int(10) unsigned DEFAULT NULL, `group_by_gender` int(10) unsigned DEFAULT NULL, `age_groups` varchar(512) COLLATE latin1_general_ci DEFAULT NULL, `measure_groups` varchar(512) COLLATE latin1_general_ci DEFAULT NULL, `measure_id` int(10) DEFAULT NULL, `user_id` int(11) NOT NULL DEFAULT '0', `test_id` int(10) DEFAULT NULL, PRIMARY KEY (`user_id`,`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci; -- -------------------------------------------------------- -- -- Table structure for table `inv_reagent` -- CREATE TABLE IF NOT EXISTS `inv_reagent` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(100) COLLATE latin1_general_ci NOT NULL, `unit` varchar(45) COLLATE latin1_general_ci NOT NULL DEFAULT 'units', `remarks` varchar(245) COLLATE latin1_general_ci DEFAULT NULL, `created_by` varchar(10) COLLATE latin1_general_ci NOT NULL DEFAULT '0', `assocation` varchar(10) COLLATE latin1_general_ci DEFAULT '0', `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=17 ; -- -------------------------------------------------------- -- -- Table structure for table `inv_supply` -- CREATE TABLE IF NOT EXISTS `inv_supply` ( `id` int(11) NOT NULL AUTO_INCREMENT, `reagent_id` int(11) NOT NULL, `lot` varchar(100) COLLATE latin1_general_ci NOT NULL, `expiry_date` date DEFAULT NULL, `manufacturer` varchar(100) COLLATE latin1_general_ci DEFAULT NULL, `supplier` varchar(100) COLLATE latin1_general_ci DEFAULT NULL, `quantity_ordered` int(11) NOT NULL DEFAULT '0', `quantity_supplied` int(11) NOT NULL DEFAULT '0', `cost_per_unit` decimal(10,0) DEFAULT NULL, `user_id` int(11) NOT NULL DEFAULT '0', `date_of_order` date DEFAULT NULL, `date_of_supply` date DEFAULT NULL, `date_of_reception` date DEFAULT NULL, `remarks` varchar(250) COLLATE latin1_general_ci DEFAULT NULL, `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`), KEY `reagent_id` (`reagent_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=29 ; -- -------------------------------------------------------- -- -- Table structure for table `inv_usage` -- CREATE TABLE IF NOT EXISTS `inv_usage` ( `id` int(11) NOT NULL AUTO_INCREMENT, `reagent_id` int(11) NOT NULL, `lot` varchar(100) COLLATE latin1_general_ci NOT NULL, `quantity_used` int(11) NOT NULL DEFAULT '0', `date_of_use` date NOT NULL, `user_id` int(11) NOT NULL, `remarks` varchar(250) COLLATE latin1_general_ci DEFAULT NULL, `ts` timestamp NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`), KEY `reagent_id` (`reagent_id`), KEY `reagent_id2` (`reagent_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=21 ; -- -------------------------------------------------------- -- -- Table structure for table `labtitle_custom_field` -- CREATE TABLE IF NOT EXISTS `labtitle_custom_field` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `field_name` varchar(45) NOT NULL, `field_options` varchar(200) NOT NULL, `field_type_id` int(11) unsigned NOT NULL DEFAULT '0', `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`), KEY `field_type_id` (`field_type_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `lab_config` -- CREATE TABLE IF NOT EXISTS `lab_config` ( `lab_config_id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` char(45) NOT NULL DEFAULT '', `location` char(45) NOT NULL DEFAULT '', `admin_user_id` int(10) unsigned NOT NULL DEFAULT '0', `db_name` char(45) NOT NULL DEFAULT '', `id_mode` int(10) unsigned NOT NULL DEFAULT '2', `p_addl` int(10) unsigned NOT NULL DEFAULT '0', `s_addl` int(10) unsigned NOT NULL DEFAULT '0', `daily_num` int(10) unsigned NOT NULL DEFAULT '1', `pid` int(10) unsigned NOT NULL DEFAULT '2', `pname` int(10) unsigned NOT NULL DEFAULT '1', `sex` int(10) unsigned NOT NULL DEFAULT '2', `age` int(10) unsigned NOT NULL DEFAULT '1', `dob` int(10) unsigned NOT NULL DEFAULT '1', `sid` int(10) unsigned NOT NULL DEFAULT '2', `refout` int(10) unsigned NOT NULL DEFAULT '1', `rdate` int(10) unsigned NOT NULL DEFAULT '2', `comm` int(10) unsigned NOT NULL DEFAULT '1', `dformat` varchar(45) NOT NULL DEFAULT 'd-m-Y', `dnum_reset` int(10) unsigned NOT NULL DEFAULT '1', `doctor` int(10) unsigned NOT NULL DEFAULT '1', `country` varchar(512) DEFAULT NULL, `Facility_Code` varchar(20) NOT NULL, PRIMARY KEY (`lab_config_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 ROW_FORMAT=FIXED AUTO_INCREMENT=1006 ; -- -- Dumping data for table `lab_config` -- INSERT INTO `lab_config` (`lab_config_id`, `name`, `location`, `admin_user_id`, `db_name`, `id_mode`, `p_addl`, `s_addl`, `daily_num`, `pid`, `pname`, `sex`, `age`, `dob`, `sid`, `refout`, `rdate`, `comm`, `dformat`, `dnum_reset`, `doctor`, `country`, `Facility_Code`) VALUES (127, 'Testlab1', 'GT', 53, 'blis_127', 1, 0, 0, 10, 0, 1, 2, 11, 0, 2, 1, 2, 0, 'd-m-Y', 1, 1, 'USA', ''), (128, 'Bamenda Regional Hospital Lab', 'Bamenda, Cameroon', 115, 'blis_128', 2, 0, 0, 1, 2, 1, 2, 1, 1, 2, 1, 2, 1, 'm-d-Y', 1, 1, 'Cameroon', ''), (129, 'Buea Regional Hospital Lab', 'Buea, Cameroon', 116, 'blis_129', 2, 0, 0, 1, 1, 1, 2, 1, 1, 2, 1, 2, 1, 'd-m-Y', 1, 1, 'Cameroon', ''), (130, 'Hopital Centrel Laboratoire', 'Messa-Yaounde, Cameroon', 113, 'blis_130', 2, 0, 0, 1, 2, 1, 2, 1, 1, 2, 1, 2, 1, 'd-m-Y', 1, 1, 'Cameroon', ''), (131, 'Hopital Laquintinie Laboratoire', 'Douala, Cameroon', 114, 'blis_131', 2, 0, 1, 1, 1, 1, 2, 1, 1, 2, 1, 2, 1, 'd-m-Y', 1, 1, 'Cameroon', ''), (151, 'Tema Polyclinic Laboratory', 'Ghana', 340, 'blis_151', 1, 0, 0, 2, 2, 1, 2, 1, 1, 2, 1, 2, 0, 'd-m-Y', 1, 0, 'Ghana', ''), (152, 'Saltpond Municipal Hospital', 'Ghana', 339, 'blis_152', 1, 0, 0, 1, 2, 1, 2, 1, 1, 2, 1, 2, 1, 'd-m-Y', 1, 1, 'Ghana', ''), (153, 'Kaneshie Polyclinic', 'Ghana', 338, 'blis_153', 1, 0, 0, 1, 2, 1, 2, 1, 1, 2, 1, 2, 1, 'd-m-Y', 1, 1, 'Ghana', ''), (203, 'Limbe Hospital Laboratory', 'Limbe, Cameroon', 174, 'blis_203', 1, 0, 0, 1, 2, 1, 2, 1, 1, 2, 1, 2, 1, 'd-m-Y', 1, 1, 'Cameroon', ''), (222, 'Nkonsamba Regional Hospital', 'Nkonsamba', 209, 'blis_222', 1, 0, 0, 1, 2, 1, 2, 1, 1, 2, 1, 2, 1, 'd-m-Y', 3, 1, 'Cameroon', ''), (223, 'Kisarawe District Laboratory', 'Coast Region', 264, 'blis_223', 1, 0, 0, 1, 2, 1, 2, 1, 1, 2, 1, 2, 1, 'd-m-Y', 1, 1, 'Tanzania', ''), (225, 'Mafinga Laboratory', 'Mafinga District. Iringa Region', 262, 'blis_225', 1, 0, 0, 1, 2, 1, 2, 1, 1, 2, 1, 2, 1, 'd-m-Y', 1, 1, 'Tanzania', ''), (226, 'Lushoto Laboratory', 'Lushoto District, Tanga Region', 260, 'blis_226', 1, 0, 0, 1, 2, 1, 2, 1, 1, 2, 1, 2, 1, 'd-m-Y', 1, 1, 'Tanzania', ''), (232, 'Kiwoko Health Facility', 'Uganda', 220, 'blis_232', 1, 0, 0, 1, 2, 1, 2, 1, 1, 2, 1, 2, 1, 'd-m-Y', 1, 1, 'Uganda', ''), (233, 'JOY Medical Center-Ndeeba', 'Kampala, Uganda', 224, 'blis_233', 1, 0, 0, 1, 2, 1, 2, 1, 1, 2, 1, 2, 1, 'd-m-Y', 1, 1, 'Uganda', ''), (234, 'St. Stephens Health Centre', 'Kampala , Uganda', 227, 'blis_234', 1, 0, 0, 2, 0, 1, 2, 1, 1, 2, 2, 0, 2, 'd-m-Y', 1, 2, 'Uganda', ''), (235, 'Alive Medical Services', 'Kampala, Uganda', 226, 'blis_235', 1, 0, 0, 1, 2, 1, 2, 1, 1, 2, 1, 2, 1, 'd-m-Y', 1, 1, 'Uganda', ''), (236, 'Kawempe Health Centre', 'Uganda', 233, 'blis_236', 1, 0, 0, 1, 2, 1, 2, 1, 1, 2, 1, 2, 1, 'd-m-Y', 1, 1, 'Uganda', ''), (237, 'Ndejje Health Centre', 'Uganda', 234, 'blis_237', 1, 0, 0, 1, 2, 1, 2, 1, 1, 2, 1, 2, 1, 'd-m-Y', 1, 1, 'Uganda', ''), (238, 'Jinja Hospital', 'Uganda', 200, 'blis_238', 1, 0, 0, 1, 2, 1, 2, 1, 1, 2, 1, 2, 1, 'd-m-Y', 1, 1, 'Uganda', ''), (1005, 'GhanaTest', 'Atl', 404, 'blis_1005', 1, 0, 0, 1, 2, 1, 2, 1, 1, 2, 1, 2, 1, 'd-m-Y', 1, 1, 'Ghana', ''); -- -------------------------------------------------------- -- -- Table structure for table `lab_config_access` -- CREATE TABLE IF NOT EXISTS `lab_config_access` ( `user_id` int(10) unsigned NOT NULL DEFAULT '0', `lab_config_id` int(10) unsigned NOT NULL DEFAULT '0', PRIMARY KEY (`user_id`,`lab_config_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; -- -- Dumping data for table `lab_config_access` -- INSERT INTO `lab_config_access` (`user_id`, `lab_config_id`) VALUES (505, 1); -- -------------------------------------------------------- -- -- Table structure for table `lab_config_settings` -- CREATE TABLE IF NOT EXISTS `lab_config_settings` ( `id` int(11) NOT NULL, `flag1` int(11) DEFAULT NULL, `flag2` int(11) DEFAULT NULL, `flag3` int(11) DEFAULT NULL, `flag4` int(11) DEFAULT NULL, `setting1` varchar(200) COLLATE latin1_general_ci DEFAULT NULL, `setting2` varchar(200) COLLATE latin1_general_ci DEFAULT NULL, `setting3` varchar(200) COLLATE latin1_general_ci DEFAULT NULL, `setting4` varchar(200) COLLATE latin1_general_ci DEFAULT NULL, `misc` varchar(500) COLLATE latin1_general_ci DEFAULT NULL, `remarks` varchar(500) COLLATE latin1_general_ci DEFAULT NULL, `ts` timestamp NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci; -- -- Dumping data for table `lab_config_settings` -- INSERT INTO `lab_config_settings` (`id`, `flag1`, `flag2`, `flag3`, `flag4`, `setting1`, `setting2`, `setting3`, `setting4`, `misc`, `remarks`, `ts`) VALUES (1, 0, 2, 30, 11, 'code39', NULL, NULL, NULL, NULL, 'Barcode Settings', '2014-02-21 11:01:05'), (2, 10, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 'Search Settings', '2014-02-17 11:34:55'), (3, 1, NULL, NULL, NULL, 'KSHS', '.', NULL, NULL, NULL, 'Billing Settings', '2014-02-17 19:12:35'); -- -------------------------------------------------------- -- -- Table structure for table `lab_config_specimen_type` -- CREATE TABLE IF NOT EXISTS `lab_config_specimen_type` ( `lab_config_id` int(10) unsigned NOT NULL DEFAULT '0', `specimen_type_id` int(10) unsigned NOT NULL DEFAULT '0' ) ENGINE=MyISAM DEFAULT CHARSET=latin1; -- -- Dumping data for table `lab_config_specimen_type` -- INSERT INTO `lab_config_specimen_type` (`lab_config_id`, `specimen_type_id`) VALUES (132, 16), (132, 17), (134, 17), (141, 16), (179, 16), (180, 16), (131, 16), (191, 16), (192, 16), (193, 16), (194, 16), (131, 17), (128, 21), (129, 21), (130, 21), (131, 21), (203, 21), (214, 16), (222, 16), (223, 16); -- -------------------------------------------------------- -- -- Table structure for table `lab_config_test_type` -- CREATE TABLE IF NOT EXISTS `lab_config_test_type` ( `lab_config_id` int(10) unsigned NOT NULL DEFAULT '0', `test_type_id` int(10) unsigned NOT NULL DEFAULT '0' ) ENGINE=MyISAM DEFAULT CHARSET=latin1; -- -- Dumping data for table `lab_config_test_type` -- INSERT INTO `lab_config_test_type` (`lab_config_id`, `test_type_id`) VALUES (127, 204), (127, 203), (127, 202), (127, 201), (127, 200), (127, 126), (127, 199), (127, 125), (127, 198), (127, 124), (127, 197), (127, 123), (127, 133), (127, 196), (127, 122), (127, 195), (127, 121), (127, 194), (127, 120), (127, 193), (127, 192), (127, 191), (127, 132), (127, 190), (127, 189), (127, 188), (127, 131), (127, 119), (127, 187), (127, 186), (127, 185), (127, 184), (127, 183), (127, 182), (127, 181), (127, 180), (127, 179), (127, 118), (127, 178), (127, 177), (127, 176), (127, 117), (127, 175), (127, 174), (127, 173), (127, 172), (127, 171), (127, 170), (127, 169), (127, 168), (127, 167), (127, 166), (127, 165), (127, 164), (127, 163), (127, 162), (127, 116), (127, 161), (127, 160), (127, 159), (127, 158), (127, 157), (127, 156), (127, 155), (127, 154), (127, 153), (127, 152), (127, 151), (127, 150), (127, 149), (127, 213), (127, 148), (127, 212), (127, 211), (127, 147), (127, 210), (127, 146), (127, 209), (127, 145), (127, 144), (127, 143), (127, 142), (127, 141), (127, 140), (127, 139), (127, 138), (127, 115), (127, 130), (127, 114), (127, 129), (127, 137), (127, 208), (127, 136), (127, 207), (127, 135), (127, 134), (127, 206), (127, 128), (127, 113), (127, 127), (127, 205); -- -------------------------------------------------------- -- -- Table structure for table `map_coordinates` -- CREATE TABLE IF NOT EXISTS `map_coordinates` ( `id` int(11) NOT NULL AUTO_INCREMENT, `lab_id` int(11) NOT NULL, `coordinates` varchar(100) COLLATE latin1_general_ci DEFAULT NULL, `user_id` int(11) DEFAULT NULL, `flag` int(11) DEFAULT '1', `country` varchar(110) COLLATE latin1_general_ci DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=4 ; -- -- Dumping data for table `map_coordinates` -- INSERT INTO `map_coordinates` (`id`, `lab_id`, `coordinates`, `user_id`, `flag`, `country`) VALUES (2, 126, '220,291', 504, 1, NULL), (3, 127, '303,330', 504, 1, NULL); -- -------------------------------------------------------- -- -- Table structure for table `measure` -- CREATE TABLE IF NOT EXISTS `measure` ( `measure_id` int(11) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(45) NOT NULL DEFAULT '', `unit_id` int(10) unsigned DEFAULT NULL, `measure_range` varchar(500) DEFAULT NULL, `description` varchar(500) DEFAULT NULL, `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `unit` varchar(30) DEFAULT NULL, PRIMARY KEY (`measure_id`), KEY `unit_id` (`unit_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=46 ; -- -- Dumping data for table `measure` -- INSERT INTO `measure` (`measure_id`, `name`, `unit_id`, `measure_range`, `description`, `ts`, `unit`) VALUES (1, 'Cell Count', NULL, ':', NULL, '2014-04-01 21:41:31', ''), (2, 'CD4 Count', NULL, ':', NULL, '2014-04-02 05:49:30', 'cell/ul'), (3, '12', NULL, ':', NULL, '2014-03-07 14:09:36', ''), (4, 'Nominal Result', NULL, '$freetext$$', NULL, '2014-03-17 22:16:50', ''), (5, 'CD8 Count', NULL, ':', NULL, '2014-04-02 05:49:30', 'cell/ul'), (6, 'Cell Percentage', NULL, ':', NULL, '2014-04-22 13:09:45', ''), (7, 'cells/L', NULL, ':', NULL, '2014-04-22 13:52:18', ''), (8, 'cells/L ', NULL, ':', NULL, '2014-04-23 05:10:25', ''), (9, 'g/dL', NULL, ':', NULL, '2014-04-23 05:13:59', ''), (10, 'Glucose', NULL, ':', NULL, '2014-06-18 12:47:27', 'mmol/L'), (11, 'mm/Hr', NULL, ':', NULL, '2014-06-18 08:26:54', ''), (12, 'units/g', NULL, ':', NULL, '2014-04-28 07:34:22', ''), (13, '+/++/+++', NULL, '$freetext$$', NULL, '2014-04-29 07:22:38', ''), (14, 'mmol/L', NULL, ':', NULL, '2014-04-29 07:44:34', ''), (15, 'mmol/d', NULL, ':', NULL, '2014-06-18 12:27:04', ''), (16, 'mu/l', NULL, ':', NULL, '2014-04-29 11:15:06', ''), (17, 'pvf', NULL, ':', NULL, '2014-06-18 13:17:36', ''), (18, 'Present/Absent', NULL, '$freetext$$', NULL, '2014-04-29 13:00:06', ''), (19, 'Noticed/Not-Noticed', NULL, '$freetext$$', NULL, '2014-04-29 13:03:49', ''), (20, 'Count', NULL, '$freetext$$', NULL, '2014-04-29 13:04:37', ''), (21, '(Units)', NULL, '$freetext$$', NULL, '2014-05-06 08:44:23', ''), (22, 'Units', NULL, ':', NULL, '2014-05-29 13:45:42', ''), (23, 'Test Units', NULL, ':', NULL, '2014-06-17 16:07:43', ''), (24, 'U/L', NULL, ':', NULL, '2014-06-18 12:06:00', ''), (25, 'umol/L', NULL, ':', NULL, '2014-06-18 12:21:26', ''), (26, 'mmol/d', NULL, ':', NULL, '2014-06-18 12:26:01', ''), (27, 'mg/dL', NULL, ':', NULL, '2014-06-18 12:29:10', ''), (28, 'µg/I ', NULL, ':', NULL, '2014-07-15 11:32:13', ''), (29, 'Glucose', NULL, ':', NULL, '2014-07-25 20:15:51', ''), (30, 'Positive/Negative', NULL, '$freetext$$', NULL, '2014-08-06 12:32:17', ''), (31, 'mg/dl', NULL, ':', NULL, '2014-07-30 10:39:43', ''), (32, 'mg/dl', NULL, ':', NULL, '2014-07-30 12:28:24', ''), (33, 'mgN/dl', NULL, ':', NULL, '2014-07-30 11:54:43', ''), (34, 'mEq/L', NULL, ':', NULL, '2014-07-30 11:56:07', ''), (35, 'U/L', NULL, 'N/P', NULL, '2014-08-21 08:43:52', ''), (36, 'ng/ml', NULL, ':', NULL, '2014-07-30 13:24:47', ''), (37, 'ng/dL', NULL, ':', NULL, '2014-07-30 13:41:56', ''), (38, 'mcg/dL', NULL, ':', NULL, '2014-07-30 13:47:54', ''), (39, 'mIU/L', NULL, ':', NULL, '2014-07-30 13:51:06', ''), (40, 'mcL', NULL, ':', NULL, '2014-07-31 04:31:44', ''), (41, '%', NULL, ':', NULL, '2014-07-31 04:51:22', ''), (42, 'u/g', NULL, ':', NULL, '2014-07-31 04:54:23', ''), (43, 'Minutes', NULL, ':', NULL, '2014-07-31 05:05:43', ''), (44, 'Seconds', NULL, ':', NULL, '2014-07-31 05:07:06', ''), (45, 'Copies/mL', NULL, ':', NULL, '2014-07-31 09:12:09', ''); -- -------------------------------------------------------- -- -- Table structure for table `measure_mapping` -- CREATE TABLE IF NOT EXISTS `measure_mapping` ( `user_id` int(11) NOT NULL DEFAULT '0', `measure_name` varchar(256) COLLATE latin1_general_ci DEFAULT NULL, `lab_id_measure_id` varchar(256) COLLATE latin1_general_ci DEFAULT NULL, `measure_id` int(10) NOT NULL DEFAULT '0', PRIMARY KEY (`user_id`,`measure_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci; -- -------------------------------------------------------- -- -- Table structure for table `misc` -- CREATE TABLE IF NOT EXISTS `misc` ( `id` int(11) NOT NULL AUTO_INCREMENT, `r_id` int(11) NOT NULL DEFAULT '0', `vr_id` varchar(45) COLLATE latin1_general_ci NOT NULL DEFAULT '0', `i1` int(11) NOT NULL DEFAULT '0', `i2` int(11) NOT NULL DEFAULT '0', `i3` int(11) NOT NULL DEFAULT '0', `i4` int(11) NOT NULL DEFAULT '0', `i5` int(11) NOT NULL DEFAULT '0', `v1` varchar(500) COLLATE latin1_general_ci NOT NULL DEFAULT '0', `v2` varchar(500) COLLATE latin1_general_ci NOT NULL DEFAULT '0', `v3` varchar(500) COLLATE latin1_general_ci NOT NULL DEFAULT '0', `v4` varchar(500) COLLATE latin1_general_ci NOT NULL DEFAULT '0', `v5` varchar(500) COLLATE latin1_general_ci NOT NULL DEFAULT '0', `dt1` datetime DEFAULT NULL, `dt2` datetime DEFAULT NULL, `dt3` datetime DEFAULT NULL, `d1` date DEFAULT NULL, `d2` date DEFAULT NULL, `d3` date DEFAULT NULL, `ts` timestamp NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `numeric_interpretation` -- CREATE TABLE IF NOT EXISTS `numeric_interpretation` ( `range_u` int(10) DEFAULT NULL, `range_l` int(10) DEFAULT NULL, `age_u` int(10) DEFAULT NULL, `age_l` int(10) DEFAULT NULL, `gender` varchar(40) DEFAULT NULL, `description` varchar(40) DEFAULT NULL, `measure_id` int(10) unsigned NOT NULL, `id` int(10) NOT NULL AUTO_INCREMENT, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `patient` -- CREATE TABLE IF NOT EXISTS `patient` ( `patient_id` int(11) unsigned NOT NULL DEFAULT '0', `addl_id` varchar(40) DEFAULT NULL, `name` varchar(45) DEFAULT NULL, `sex` char(1) NOT NULL DEFAULT '', `age` decimal(10,0) DEFAULT NULL, `dob` date DEFAULT NULL, `created_by` int(11) unsigned DEFAULT NULL, `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `partial_dob` varchar(45) DEFAULT NULL, `surr_id` varchar(45) DEFAULT NULL, `hash_value` varchar(100) DEFAULT NULL, PRIMARY KEY (`patient_id`), KEY `created_by` (`created_by`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `patient_custom_data` -- CREATE TABLE IF NOT EXISTS `patient_custom_data` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `field_id` int(11) unsigned NOT NULL DEFAULT '0', `patient_id` int(11) unsigned NOT NULL DEFAULT '0', `field_value` varchar(45) NOT NULL DEFAULT '', `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`), KEY `field_id` (`field_id`), KEY `patient_id` (`patient_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `patient_custom_field` -- CREATE TABLE IF NOT EXISTS `patient_custom_field` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `field_name` varchar(45) NOT NULL DEFAULT '', `field_options` varchar(45) NOT NULL DEFAULT '', `field_type_id` int(11) unsigned NOT NULL DEFAULT '0', `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`), KEY `field_type_id` (`field_type_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `patient_daily` -- CREATE TABLE IF NOT EXISTS `patient_daily` ( `datestring` varchar(45) NOT NULL, `count` int(10) unsigned NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `payments` -- CREATE TABLE IF NOT EXISTS `payments` ( `id` int(11) NOT NULL AUTO_INCREMENT, `amount` decimal(10,2) NOT NULL DEFAULT '0.00', `bill_id` int(11) unsigned NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `quality_controls` -- CREATE TABLE IF NOT EXISTS `quality_controls` ( `qc_id` int(11) NOT NULL AUTO_INCREMENT, `qcc_id` int(11) NOT NULL, `irl_id` int(11) NOT NULL, `name` varchar(200) COLLATE latin1_general_ci NOT NULL, `description` varchar(250) COLLATE latin1_general_ci NOT NULL, `created_by` int(11) NOT NULL, `ts` datetime NOT NULL, PRIMARY KEY (`qc_id`), KEY `qc_1` (`qcc_id`), KEY `qc_2` (`created_by`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `quality_control_category` -- CREATE TABLE IF NOT EXISTS `quality_control_category` ( `qcc_id` int(11) NOT NULL AUTO_INCREMENT, `description` varchar(200) COLLATE latin1_general_ci NOT NULL, `created_by` int(11) NOT NULL, `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`qcc_id`), KEY `qcc_user_fk` (`created_by`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=8 ; -- -- Dumping data for table `quality_control_category` -- INSERT INTO `quality_control_category` (`qcc_id`, `description`, `created_by`, `ts`) VALUES (1, 'Test', 0, '2014-04-30 23:25:32'), (2, 'Test', 0, '2014-05-08 08:01:11'), (3, 'Test', 0, '2014-05-08 08:01:23'), (4, 'Standard QC', 0, '2014-05-12 07:16:21'), (5, 'Accuracy', 0, '2014-06-05 10:33:14'), (6, 'Reliability', 0, '2014-06-05 10:35:14'), (7, 'Testing QC Category', 0, '2014-06-17 00:45:42'); -- -------------------------------------------------------- -- -- Table structure for table `quality_control_fields` -- CREATE TABLE IF NOT EXISTS `quality_control_fields` ( `field_id` int(11) NOT NULL AUTO_INCREMENT, `qc_id` int(11) NOT NULL, `field_name` varchar(200) COLLATE latin1_general_ci NOT NULL, `field_type` varchar(25) COLLATE latin1_general_ci NOT NULL, `field_size` int(11) NOT NULL, `required` int(11) NOT NULL, `options` varchar(250) COLLATE latin1_general_ci NOT NULL, `created_by` int(11) NOT NULL, `ts` datetime NOT NULL, PRIMARY KEY (`field_id`), KEY `qcf_1` (`qc_id`), KEY `qcf_3` (`created_by`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `quality_control_field_responses` -- CREATE TABLE IF NOT EXISTS `quality_control_field_responses` ( `response_id` int(11) NOT NULL AUTO_INCREMENT, `created_by` int(11) NOT NULL, `qc_id` int(11) NOT NULL, `ts` datetime NOT NULL, PRIMARY KEY (`response_id`), KEY `qcfrs_1` (`created_by`), KEY `qcfrs_2` (`qc_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `quality_control_field_results` -- CREATE TABLE IF NOT EXISTS `quality_control_field_results` ( `result_id` int(11) NOT NULL AUTO_INCREMENT, `response_id` int(11) NOT NULL, `field_id` int(11) NOT NULL, `value` varchar(250) COLLATE latin1_general_ci NOT NULL, `ts` datetime NOT NULL, PRIMARY KEY (`result_id`), KEY `qcfr_1` (`response_id`), KEY `qcfr_2` (`field_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `reference_range` -- CREATE TABLE IF NOT EXISTS `reference_range` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `measure_id` int(10) unsigned NOT NULL, `age_min` varchar(45) DEFAULT NULL, `age_max` varchar(45) DEFAULT NULL, `sex` varchar(10) DEFAULT NULL, `range_lower` varchar(45) NOT NULL, `range_upper` varchar(45) NOT NULL, PRIMARY KEY (`id`), KEY `measure_id` (`measure_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=70 ; -- -- Dumping data for table `reference_range` -- INSERT INTO `reference_range` (`id`, `measure_id`, `age_min`, `age_max`, `sex`, `range_lower`, `range_upper`) VALUES (1, 3, '0', '100', 'B', '12', '24'), (2, 1, '0', '0', '', '0', '2200'), (5, 5, '0', '100', 'B', '1', '5000'), (6, 6, '0', '100', 'B', '10', '500'), (8, 7, '0', '100', 'B', '1', '100'), (9, 8, '0', '100', 'B', '1', '1000'), (10, 9, '0', '100', 'B', '1', '100'), (14, 12, '0', '100', 'B', '1', '100'), (25, 16, '0', '100', 'B', '1', '1000'), (26, 16, 'Array', 'Array', 'Array', '-13', '13'), (27, 16, 'Array', 'Array', 'Array', '14', '999'), (28, 22, '0', '100', 'B', '0', '12'), (30, 23, '0', '100', 'B', '1', '25'), (31, 11, '0', '100', 'B', '0', '29'), (32, 24, '0', '100', 'B', '0', '0.8'), (33, 25, '0', '100', 'B', '1', '10'), (35, 26, '0', '100', 'B', '2', '250'), (36, 15, '0', '100', 'B', '7', '17.6'), (38, 14, '0', '100', 'B', '4', '7'), (39, 10, '0', '100', 'B', '3.9', '6.1'), (40, 17, '0', '100', 'B', '0', '4'), (41, 28, '0', '100', 'B', '30', '140'), (42, 2, '0', '100', '', '600', '1500'), (43, 29, '0', '100', '', '70', '126'), (44, 31, '0', '100', 'B', '0', '8'), (46, 33, '0', '100', 'B', '12', '20'), (47, 34, '0', '100', 'B', '135', '145'), (50, 32, '0', '100', 'B', '0.7', '1.4'), (52, 35, '0', '100', 'B', '5', '40'), (53, 36, '0', '100', 'B', '4.0', '10.0'), (54, 37, '0', '100', 'B', '100', '200'), (55, 38, '0', '100', 'B', '4.5', '11.2'), (56, 39, '0', '100', 'B', '0.4', '4.0'), (60, 40, '0', '100', 'B', '4500', '10000'), (61, 41, '0', '100', 'B', '0', '100'), (62, 42, '0', '100', 'B', '5', '14'), (63, 43, '0', '100', 'B', '1', '9'), (64, 44, '0', '100', 'B', '11', '13.5'), (65, 45, '0', '100', 'B', '40', '10000'), (66, 27, '0', '100', 'B', '70', '125'), (67, 27, 'Array', 'Array', 'Array', '126', '180'), (68, 27, 'Array', 'Array', 'Array', '181', '500'), (69, 30, '0', '0', '', '4', '10'); -- -------------------------------------------------------- -- -- Table structure for table `reference_range_global` -- CREATE TABLE IF NOT EXISTS `reference_range_global` ( `measure_id` int(10) NOT NULL DEFAULT '0', `age_min` varchar(64) COLLATE latin1_general_ci DEFAULT NULL, `age_max` varchar(64) COLLATE latin1_general_ci DEFAULT NULL, `sex` varchar(64) COLLATE latin1_general_ci DEFAULT NULL, `range_lower` varchar(64) COLLATE latin1_general_ci DEFAULT NULL, `range_upper` varchar(64) COLLATE latin1_general_ci DEFAULT NULL, `user_id` int(11) NOT NULL DEFAULT '0', PRIMARY KEY (`user_id`,`measure_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci; -- -------------------------------------------------------- -- -- Table structure for table `rejected_specimen` -- CREATE TABLE IF NOT EXISTS `rejected_specimen` ( `specimen_id` int(11) unsigned NOT NULL DEFAULT '0', `reason_id` int(11) unsigned NOT NULL DEFAULT '0', `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, KEY `specimen_id` (`specimen_id`), KEY `reason_id` (`reason_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `rejection_phases` -- CREATE TABLE IF NOT EXISTS `rejection_phases` ( `rejection_phase_id` int(11) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(45) COLLATE latin1_general_ci NOT NULL DEFAULT '', `description` varchar(100) COLLATE latin1_general_ci DEFAULT NULL, `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`rejection_phase_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=8 ; -- -------------------------------------------------------- -- -- Table structure for table `rejection_reasons` -- CREATE TABLE IF NOT EXISTS `rejection_reasons` ( `rejection_reason_id` int(11) unsigned NOT NULL AUTO_INCREMENT, `rejection_phase` int(11) NOT NULL, `description` varchar(100) COLLATE latin1_general_ci DEFAULT NULL, `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`rejection_reason_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=8 ; -- -------------------------------------------------------- -- -- Table structure for table `removal_record` -- CREATE TABLE IF NOT EXISTS `removal_record` ( `id` int(11) NOT NULL AUTO_INCREMENT, `r_id` int(11) NOT NULL DEFAULT '0', `vr_id` varchar(45) COLLATE latin1_general_ci NOT NULL DEFAULT '0', `type` int(11) DEFAULT NULL, `user_id` int(11) DEFAULT '0', `remarks` varchar(500) COLLATE latin1_general_ci DEFAULT NULL, `status` int(11) NOT NULL DEFAULT '1', `ts` timestamp NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `report_config` -- CREATE TABLE IF NOT EXISTS `report_config` ( `report_id` int(10) unsigned NOT NULL AUTO_INCREMENT, `header` varchar(500) NOT NULL DEFAULT '', `footer` varchar(500) NOT NULL DEFAULT '-End-', `margins` varchar(45) NOT NULL DEFAULT '2,0,10,0', `p_fields` varchar(45) NOT NULL DEFAULT '1,1,1,1,1,1,1', `s_fields` varchar(45) NOT NULL DEFAULT '1,1,1,1,1,1', `t_fields` varchar(45) NOT NULL DEFAULT '1,0,1,1,1,0,1,1', `p_custom_fields` varchar(45) NOT NULL DEFAULT '', `s_custom_fields` varchar(45) NOT NULL DEFAULT '', `test_type_id` varchar(45) NOT NULL DEFAULT '0', `title` varchar(500) NOT NULL DEFAULT '', `landscape` int(10) unsigned NOT NULL DEFAULT '0', PRIMARY KEY (`report_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=159 ; -- -- Dumping data for table `report_config` -- INSERT INTO `report_config` (`report_id`, `header`, `footer`, `margins`, `p_fields`, `s_fields`, `t_fields`, `p_custom_fields`, `s_custom_fields`, `test_type_id`, `title`, `landscape`) VALUES (1, 'Patient Report??center', '#', '2,0,10,0', '1,1,1,1,1,1,1,1,1', '1,1,1,1,1,1,1', '1,1,1,1,1,1,1,1,1,1', '', '', '0', '<br>Laboratory Patient Report', 1), (2, 'Specimen Report', '', '2,0,10,0', '1,1,1,1,1,1,1', '1,1,1,1,1,1', '1,0,1,1,1,0,1,1', '', '', '0', '', 0), (3, 'Test Records', '', '2,0,10,0', '1,1,1,1,1,1,1', '1,1,1,1,1,1', '1,0,1,1,1,0,1,1', '', '', '0', '', 0), (4, 'Daily Log - Tests??left', '#', '2,0,10,0', '1,1,1,1,1,1,1,0,0', '1,1,1,1,1,1,0', '1,0,1,1,1,0,1,1,0,0', '', '', '0', '', 0), (5, 'Worksheet', '', '2,0,10,0', '1,1,1,1,1,1,1', '1,1,1,1,1,1', '1,0,1,1,1,0,1,1', '', '', '0', '', 0), (6, 'Daily Log - Patients??left', '#', '2,0,10,0', '1,1,1,1,1,1,1,1,0', '1,1,1,1,1,1,0', '1,0,1,1,1,0,1,1,0,0', '', '', '0', '', 1), (9, 'Worksheet - FHG', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '2', '', 0), (10, 'Worksheet - CD4', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '3', '', 0), (11, 'Worksheet - New Test Type', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '4', '', 0), (12, 'Worksheet - My Test', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '5', '', 0), (13, 'Worksheet - HGC', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '22', '', 0), (14, 'Worksheet - UPA', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '21', '', 0), (15, 'Chemistry Worksheet??left', 'Chemistry Unit #Nandi Hills', '5,0,5,0', '1,1,1,1,1,1,1,1,0', '1,0,1,1,0,1,1', '1,0,1,1,1,1,0,1,0,0', '', '', '20', 'Patient Information and Test Orders', 0), (16, 'Worksheet - Blood??left', '#', '5,0,5,0', '1,1,0,1,1,0,1,0,0', '1,0,1,1,0,0,0', '1,0,1,0,0,0,1,1,0,0', '', '', '19', '', 0), (17, 'Worksheet - Proteins', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '18', '', 0), (18, 'Worksheet - Ketones', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '17', '', 0), (19, 'Worksheet - G6PD', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '16', '', 0), (20, 'Worksheet - Glucose', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '10', '', 0), (21, 'Worksheet - HbE', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '15', '', 0), (22, 'Worksheet - Sickling', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '13', '', 0), (23, 'Worksheet - ESR', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '12', '', 0), (24, 'Worksheet - FBC??left', '#', '5,0,5,0', '0,1,0,1,1,0,0,0,0', '1,0,1,1,0,0,0', '1,0,1,0,0,0,0,1,0,0', '', '', '7', '', 0), (25, 'Worksheet - PBF', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '9', '', 0), (26, 'Worksheet - WBC', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '8', '', 0), (27, 'Worksheet - FBS', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '23', '', 0), (28, 'Worksheet - RBS', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '24', '', 0), (29, 'Worksheet - OGTT', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '25', '', 0), (30, 'Worksheet - Creatinine', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '26', '', 0), (31, 'Worksheet - Urea', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '27', '', 0), (32, 'Worksheet - Sodium', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '28', '', 0), (33, 'Worksheet - Potassium', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '29', '', 0), (34, 'Worksheet - Chloride', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '30', '', 0), (35, 'Worksheet - Direct bilirubin', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '31', '', 0), (36, 'Worksheet - Total bilirubin', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '32', '', 0), (37, 'Worksheet - ASAT (SGOT)', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '33', '', 0), (38, 'Worksheet - ALAT (SGPT)', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '34', '', 0), (39, 'Worksheet - Serum Protein', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '35', '', 0), (40, 'Worksheet - Albumin', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '36', '', 0), (41, 'Worksheet - Alkaline Phodphate', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '37', '', 0), (42, 'Worksheet - Gamma GT', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '38', '', 0), (43, 'Worksheet - Amylase', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '39', '', 0), (44, 'Worksheet - Total Cholestrol', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '40', '', 0), (45, 'Worksheet - Trigycerides', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '41', '', 0), (46, 'Worksheet - HDL', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '42', '', 0), (47, 'Worksheet - LDE', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '43', '', 0), (48, 'Worksheet - PSA', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '44', '', 0), (49, 'Worksheet - Acid Phosphatase??left', '#', '5,0,5,0', '0,1,0,1,1,0,0,0,0', '1,0,1,1,0,0,0', '1,0,1,0,0,0,0,1,0,1', '', '', '45', '', 0), (50, 'Worksheet - Bence jones protein', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '46', '', 0), (51, 'Worksheet - T3', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '47', '', 0), (52, 'Worksheet - T4', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '48', '', 0), (53, 'Worksheet - TSH', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '49', '', 0), (54, 'Worksheet - Pus cells', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '50', '', 0), (55, 'Worksheet - S. haematobium', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '51', '', 0), (56, 'Worksheet - T. vaginalis', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '52', '', 0), (57, 'Worksheet - Yeast Cells', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '53', '', 0), (58, 'Worksheet - Red blood cells', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '54', '', 0), (59, 'Worksheet - Bacteria', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '55', '', 0), (60, 'Worksheet - Spermatozoa', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '56', '', 0), (61, 'Worksheet - Taenia spp.', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '57', '', 0), (62, 'Worksheet - <NAME>', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '58', '', 0), (63, 'Worksheet - <NAME>', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '59', '', 0), (64, 'Worksheet - Hookworm', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '60', '', 0), (65, 'Worksheet - Roundworms', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '61', '', 0), (66, 'Worksheet - <NAME>', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '62', '', 0), (67, 'Worksheet - Trichuris trichiura', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '63', '', 0), (68, 'Worksheet - Strongyloides stercoralis', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '64', '', 0), (69, 'Worksheet - Isospora belli', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '65', '', 0), (70, 'Worksheet - E hystolytica', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '66', '', 0), (71, 'Worksheet - <NAME>', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '67', '', 0), (72, 'Worksheet - Cryptosporidium', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '68', '', 0), (73, 'Worksheet - Cyclospora', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '69', '', 0), (74, 'Worksheet - Onchocerca volvulus', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '70', '', 0), (75, 'Worksheet - Leishmania', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '71', '', 0), (76, 'Worksheet - <NAME>', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '72', '', 0), (77, 'Worksheet - <NAME>', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '73', '', 0), (78, 'Worksheet - <NAME>', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '74', '', 0), (79, 'Worksheet - Yeast Cells', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '75', '', 0), (80, 'Worksheet - Falciparum', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '76', '', 0), (81, 'Worksheet - Ovale', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '77', '', 0), (82, 'Worksheet - Ovale', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '78', '', 0), (83, 'Worksheet - Malariae', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '79', '', 0), (84, 'Worksheet - Vivax', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '80', '', 0), (85, 'Worksheet - Borrelia', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '81', '', 0), (86, 'Worksheet - Microfilariae', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '82', '', 0), (87, 'Worksheet - Trypanosomes', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '83', '', 0), (88, 'Worksheet - Testing New Test Type', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '84', '', 0), (131, 'Grouped Test Count Report Configuration', '0:4,4:9,9:14,14:19,19:24,24:29,29:34,34:39,39:44,44:49,49:54,54:59,59:64,64:68,68:+', '0', '1', '1', '1', '1', '0', '9999009', '0', 9999009), (132, 'Grouped Specimen Count Report Configuration', '0:4,4:9,9:14,14:19,19:24,24:29,29:34,34:39,39:44,44:49,49:54,54:59,59:64,64:68,68:+', '0', '1', '1', '0', '1', '0', '9999019', '0', 9999019), (133, 'Worksheet - Billirubin', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '94', '', 0), (134, 'Worksheet - HE', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '103', '', 0), (135, 'Worksheet - HbE', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '101', '', 0), (136, 'Worksheet - Proteins', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '110', '', 0), (137, 'Worksheet - FBC', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '99', '', 0), (138, 'Worksheet - OGTT', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '107', '', 0), (139, 'Worksheet - Potassium', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '109', '', 0), (140, 'Worksheet - Chloride', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '96', '', 0), (141, 'Worksheet - Direct bilirubin', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '97', '', 0), (142, 'Worksheet - ASAT (SGOT)', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '92', '', 0), (143, 'Worksheet - ALAT (SGPT)', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '88', '', 0), (144, 'Worksheet - Albumin', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '89', '', 0), (145, 'Worksheet - Alkaline Phodphate', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '90', '', 0), (146, 'Worksheet - Gamma GT', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '100', '', 0), (147, 'Worksheet - Amylase', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '91', '', 0), (148, 'Worksheet - HDL', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '102', '', 0), (149, 'Worksheet - Acid Phosphatase', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '87', '', 0), (150, 'Worksheet - Bence jones protein', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '93', '', 0), (151, 'Worksheet - <NAME>', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '104', '', 0), (152, 'Worksheet - Falciparum', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '98', '', 0), (153, 'Worksheet - Ovale', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '108', '', 0), (154, 'Worksheet - Malariae', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '105', '', 0), (155, 'Worksheet - Borrelia', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '95', '', 0), (156, 'Worksheet - Microfilariae', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '106', '', 0), (157, 'Worksheet - Iodine', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '112', '', 0), (158, 'Worksheet - Testing Add New Test Type', '', '5,0,5,0', '0,1,0,1,1,0,0', '0,0,1,1,0,0', '1,0,1,0,0,0,0,1', '', '', '86', '', 0); -- -------------------------------------------------------- -- -- Table structure for table `report_disease` -- CREATE TABLE IF NOT EXISTS `report_disease` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `group_by_age` int(10) unsigned NOT NULL, `group_by_gender` int(10) unsigned NOT NULL, `age_groups` varchar(500) DEFAULT NULL, `measure_groups` varchar(500) DEFAULT NULL, `measure_id` int(10) unsigned NOT NULL, `lab_config_id` int(10) unsigned NOT NULL, `test_type_id` int(10) unsigned NOT NULL, PRIMARY KEY (`id`) USING BTREE, KEY `measure_id` (`measure_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2780 ; -- -- Dumping data for table `report_disease` -- INSERT INTO `report_disease` (`id`, `group_by_age`, `group_by_gender`, `age_groups`, `measure_groups`, `measure_id`, `lab_config_id`, `test_type_id`) VALUES (504, 1, 1, '', 'Straw/Pale Yellow/Deep Yellow/Amber', 51, 127, 56), (505, 1, 1, '', 'Clear/Cloudy', 52, 127, 56), (506, 1, 1, '', 'P/N', 53, 127, 56), (507, 1, 1, '', 'Formed(solid)/Semi-formed(not solid)/Watery', 54, 127, 71), (508, 1, 1, '', 'P/N', 55, 127, 71), (511, 1, 1, '0:10,10:20,20:50,50:100', '0:1500,1500:3000,', 4, 127, 7), (512, 1, 1, '0:10,10:20,20:50,50:100', '0:90,', 5, 127, 7), (513, 1, 1, '0:10,10:20,20:50,50:100', '0:1000,1001:2000,', 6, 127, 8), (514, 1, 1, '0:10,10:20,20:50,50:100', '0:1000,', 17, 127, 19), (515, 1, 1, '0:10,10:20,20:50,50:100', '0:1000,', 30, 127, 32), (516, 1, 1, '0:10,10:20,20:50,50:100', '0:1000,', 16, 127, 18), (517, 1, 1, '0:10,10:20,20:50,50:100', '0.5:25,', 34, 127, 40), (558, 1, 1, '', 'R/NR', 45, 128, 48), (566, 1, 1, '', 'AA/AF/AS/SS', 46, 128, 49), (571, 1, 1, '', 'A/B/AB/O', 64, 128, 63), (572, 1, 1, '', 'P/N', 65, 128, 63), (584, 1, 1, '', 'P/N', 42, 128, 43), (585, 1, 1, '', 'N/P', 3, 128, 44), (586, 1, 1, '', 'P/N', 68, 128, 58), (587, 1, 1, '', 'N/P', 62, 128, 61), (678, 1, 1, '', 'Formed(solid)/Semi-formed(not solid)/Watery', 54, 203, 71), (679, 1, 1, '', 'P/N', 55, 203, 71), (681, 1, 1, '', 'R/NR', 45, 203, 48), (683, 1, 1, '', 'P/N', 42, 203, 43), (684, 1, 1, '', 'N/P', 3, 203, 44), (693, 1, 1, '', 'P/N', 68, 203, 58), (697, 1, 1, '', 'R/NR', 45, 129, 48), (716, 1, 1, '', 'A/B/AB/O', 64, 129, 63), (717, 1, 1, '', 'P/N', 65, 129, 63), (730, 1, 1, '', 'N/P', 3, 129, 44), (731, 1, 1, '', 'P/N', 58, 129, 59), (732, 1, 1, '', 'P/N', 69, 129, 67), (733, 1, 1, '', 'P/N', 68, 129, 66), (734, 1, 1, '', 'P/N', 68, 129, 58), (736, 1, 1, '', 'Formed(solid)/Semi-formed(not solid)/Watery', 54, 129, 71), (737, 1, 1, '', 'P/N', 55, 129, 71), (738, 1, 1, '', 'AAFB seen/AAFB not seen', 72, 129, 69), (740, 1, 1, '', '', 0, 130, 0), (741, 1, 1, '', '0:1000', 6, 130, 8), (742, 1, 1, '', 'R/NR', 45, 130, 48), (743, 1, 1, '', '0:1000', 18, 130, 20), (744, 1, 1, '', '0:1000', 19, 130, 21), (745, 1, 1, '', '0.56:1.13', 13, 130, 22), (746, 1, 1, '', '0:100', 22, 130, 24), (747, 1, 1, '', '0:100', 23, 130, 25), (748, 1, 1, '', '0:1000', 27, 130, 29), (749, 1, 1, '', '0:1000', 28, 130, 30), (750, 1, 1, '', '0:1000', 30, 130, 32), (751, 1, 1, '', '0:1000', 50, 130, 55), (752, 1, 1, '', '0:1000', 14, 130, 16), (753, 1, 1, '', '4.0:10.0', 2, 130, 39), (754, 1, 1, '', '3.5:5.5', 33, 130, 39), (755, 1, 1, '', '11.0 0.5:15.0', 34, 130, 39), (756, 1, 1, '', '80.0:99.0', 36, 130, 39), (757, 1, 1, '', '26.0:32.0', 37, 130, 39), (758, 1, 1, '', '32.0:36.0', 38, 130, 39), (759, 1, 1, '', '100:300', 39, 130, 39), (760, 1, 1, '', 'AA/AF/AS/SS', 46, 130, 49), (761, 1, 1, '', '0:1000', 47, 130, 51), (762, 1, 1, '', '11.0 0.5:15.0', 34, 130, 40), (763, 1, 1, '', '4.0:10.0', 2, 130, 52), (764, 1, 1, '', '0:100', 49, 130, 54), (765, 1, 1, '', 'A/B/AB/O', 64, 130, 63), (766, 1, 1, '', 'P/N', 65, 130, 63), (767, 1, 1, '', '0:100', 21, 130, 23), (768, 1, 1, '', 'P/N', 42, 130, 43), (769, 1, 1, '', 'N/P', 3, 130, 44), (770, 1, 1, '', 'P/N', 68, 130, 58), (771, 1, 1, '', 'Formed(solid)/Semi-formed(not solid)/Watery', 54, 130, 71), (772, 1, 1, '', 'P/N', 55, 130, 71), (773, 1, 1, '', '0:1000', 75, 130, 72), (774, 1, 1, '', '0:100', 59, 130, 60), (775, 1, 1, '', '0:10000', 60, 130, 60), (776, 1, 1, '', '0:1000', 61, 130, 60), (777, 1, 1, '', '0:1000', 67, 130, 65), (778, 1, 1, '', '0:100', 73, 130, 70), (781, 1, 1, '', 'R/NR', 45, 131, 48), (803, 1, 1, '', 'A/B/AB/O', 64, 131, 63), (804, 1, 1, '', 'P/N', 65, 131, 63), (805, 1, 1, '', 'P/N', 42, 131, 43), (806, 1, 1, '', 'N/P', 3, 131, 44), (807, 1, 1, '', 'P/N', 68, 131, 58), (808, 1, 1, '', 'Formed(solid)/Semi-formed(not solid)/Watery', 54, 131, 71), (809, 1, 1, '', 'P/N', 55, 131, 71), (812, 1, 1, '', 'P/N', 48, 131, 53), (813, 1, 1, '', 'P/N', 40, 131, 41), (814, 1, 1, '', 'P/N', 58, 131, 59), (819, 1, 1, '', 'AAFB seen/AAFB not seen', 72, 131, 69), (1203, 1, 1, '0:4,4:9,9:14,14:19,19:24,24:29,29:34,34:39,39:44,44:49,49:54,54:59,59:64,64:+', '', 0, 129, 0), (1204, 1, 1, '0:4,4:9,9:14,14:19,19:24,24:29,29:34,34:39,39:44,44:49,49:54,54:59,59:64,64:+', '0:1000,', 6, 129, 8), (1205, 1, 1, '0:4,4:9,9:14,14:19,19:24,24:29,29:34,34:39,39:44,44:49,49:54,54:59,59:64,64:+', '0:1000,', 19, 129, 21), (1206, 1, 1, '0:4,4:9,9:14,14:19,19:24,24:29,29:34,34:39,39:44,44:49,49:54,54:59,59:64,64:+', '0:1000,', 16, 129, 18), (1207, 1, 1, '0:4,4:9,9:14,14:19,19:24,24:29,29:34,34:39,39:44,44:49,49:54,54:59,59:64,64:+', '0:100,', 23, 129, 25), (1208, 1, 1, '0:4,4:9,9:14,14:19,19:24,24:29,29:34,34:39,39:44,44:49,49:54,54:59,59:64,64:+', '0:1000,', 25, 129, 27), (1209, 1, 1, '0:4,4:9,9:14,14:19,19:24,24:29,29:34,34:39,39:44,44:49,49:54,54:59,59:64,64:+', '0.56:1.13,', 13, 129, 22), (1210, 1, 1, '0:4,4:9,9:14,14:19,19:24,24:29,29:34,34:39,39:44,44:49,49:54,54:59,59:64,64:+', '0:100,', 59, 129, 60), (1211, 1, 1, '0:4,4:9,9:14,14:19,19:24,24:29,29:34,34:39,39:44,44:49,49:54,54:59,59:64,64:+', '0:10000,', 60, 129, 60), (1212, 1, 1, '0:4,4:9,9:14,14:19,19:24,24:29,29:34,34:39,39:44,44:49,49:54,54:59,59:64,64:+', '0:1000,', 61, 129, 60), (1213, 1, 1, '0:4,4:9,9:14,14:19,19:24,24:29,29:34,34:39,39:44,44:49,49:54,54:59,59:64,64:+', '0:1000,', 50, 129, 55), (1214, 1, 1, '0:4,4:9,9:14,14:19,19:24,24:29,29:34,34:39,39:44,44:49,49:54,54:59,59:64,64:+', '60:110,', 7, 129, 9), (1215, 1, 1, '0:4,4:9,9:14,14:19,19:24,24:29,29:34,34:39,39:44,44:49,49:54,54:59,59:64,64:+', '0:1000,', 27, 129, 29), (1216, 1, 1, '0:4,4:9,9:14,14:19,19:24,24:29,29:34,34:39,39:44,44:49,49:54,54:59,59:64,64:+', '0:1000,', 28, 129, 30), (1217, 1, 1, '0:4,4:9,9:14,14:19,19:24,24:29,29:34,34:39,39:44,44:49,49:54,54:59,59:64,64:+', '0:10,', 12, 129, 14), (1218, 1, 1, '0:4,4:9,9:14,14:19,19:24,24:29,29:34,34:39,39:44,44:49,49:54,54:59,59:64,64:+', '0:100,', 22, 129, 24), (1219, 1, 1, '0:4,4:9,9:14,14:19,19:24,24:29,29:34,34:39,39:44,44:49,49:54,54:59,59:64,64:+', '0:100,', 21, 129, 23), (1220, 1, 1, '0:4,4:9,9:14,14:19,19:24,24:29,29:34,34:39,39:44,44:49,49:54,54:59,59:64,64:+', '0:1000,', 18, 129, 20), (1221, 1, 1, '0:4,4:9,9:14,14:19,19:24,24:29,29:34,34:39,39:44,44:49,49:54,54:59,59:64,64:+', '0:1000,', 26, 129, 28), (1222, 1, 1, '0:4,4:9,9:14,14:19,19:24,24:29,29:34,34:39,39:44,44:49,49:54,54:59,59:64,64:+', '0:100,', 73, 129, 70), (1223, 1, 1, '0:4,4:9,9:14,14:19,19:24,24:29,29:34,34:39,39:44,44:49,49:54,54:59,59:64,64:+', '0:100,', 49, 129, 54), (1224, 1, 1, '0:4,4:9,9:14,14:19,19:24,24:29,29:34,34:39,39:44,44:49,49:54,54:59,59:64,64:+', '4.0:10.0,', 2, 129, 39), (1225, 1, 1, '0:4,4:9,9:14,14:19,19:24,24:29,29:34,34:39,39:44,44:49,49:54,54:59,59:64,64:+', '3.5:5.5,', 33, 129, 39), (1226, 1, 1, '0:4,4:9,9:14,14:19,19:24,24:29,29:34,34:39,39:44,44:49,49:54,54:59,59:64,64:+', '11.0 0.5:15.0,', 34, 129, 39), (1227, 1, 1, '0:4,4:9,9:14,14:19,19:24,24:29,29:34,34:39,39:44,44:49,49:54,54:59,59:64,64:+', '80.0:99.0,', 36, 129, 39), (1228, 1, 1, '0:4,4:9,9:14,14:19,19:24,24:29,29:34,34:39,39:44,44:49,49:54,54:59,59:64,64:+', '26.0:32.0,', 37, 129, 39), (1229, 1, 1, '0:4,4:9,9:14,14:19,19:24,24:29,29:34,34:39,39:44,44:49,49:54,54:59,59:64,64:+', '32.0:36.0,', 38, 129, 39), (1230, 1, 1, '0:4,4:9,9:14,14:19,19:24,24:29,29:34,34:39,39:44,44:49,49:54,54:59,59:64,64:+', '100:300,', 39, 129, 39), (1231, 1, 1, '0:4,4:9,9:14,14:19,19:24,24:29,29:34,34:39,39:44,44:49,49:54,54:59,59:64,64:+', '0:1000,', 47, 129, 51), (1232, 1, 1, '0:4,4:9,9:14,14:19,19:24,24:29,29:34,34:39,39:44,44:49,49:54,54:59,59:64,64:+', '11.0 0.5:15.0,', 34, 129, 40), (1233, 1, 1, '0:4,4:9,9:14,14:19,19:24,24:29,29:34,34:39,39:44,44:49,49:54,54:59,59:64,64:+', '4.0:10.0,', 2, 129, 52), (1234, 1, 1, '0:4,4:9,9:14,14:19,19:24,24:29,29:34,34:39,39:44,44:49,49:54,54:59,59:64,64:+', '0:1000,', 70, 129, 68), (1235, 1, 1, '0:4,4:9,9:14,14:19,19:24,24:29,29:34,34:39,39:44,44:49,49:54,54:59,59:64,64:+', '0:1000,', 67, 129, 65), (1271, 1, 1, '0:14,14:+', '', 0, 203, 0), (1272, 1, 1, '0:14,14:+', '0:1000,', 6, 203, 8), (1273, 1, 1, '0:14,14:+', '0:1000,', 16, 203, 18), (1274, 1, 1, '0:14,14:+', '0:100,', 73, 203, 70), (1275, 1, 1, '0:14,14:+', '0:3000,', 4, 203, 7), (1276, 1, 1, '0:14,14:+', '0:90,', 5, 203, 7), (1277, 1, 1, '0:14,14:+', '0:100,', 23, 203, 25), (1278, 1, 1, '0:14,14:+', '4.0:10.0,', 2, 203, 39), (1279, 1, 1, '0:14,14:+', '3.5:5.5,', 33, 203, 39), (1280, 1, 1, '0:14,14:+', '11.0 0.5:15.0,', 34, 203, 39), (1281, 1, 1, '0:14,14:+', '80.0:99.0,', 36, 203, 39), (1282, 1, 1, '0:14,14:+', '26.0:32.0,', 37, 203, 39), (1283, 1, 1, '0:14,14:+', '32.0:36.0,', 38, 203, 39), (1284, 1, 1, '0:14,14:+', '100:300,', 39, 203, 39), (1285, 1, 1, '0:14,14:+', '60:110,', 7, 203, 9), (1286, 1, 1, '0:14,14:+', '0:10,', 12, 203, 14), (1287, 1, 1, '0:14,14:+', '0:100,', 22, 203, 24), (1288, 1, 1, '0:14,14:+', '0:100,', 21, 203, 23), (1289, 1, 1, '0:14,14:+', '0:1000,', 27, 203, 29), (1290, 1, 1, '0:14,14:+', '11.0 0.5:15.0,', 34, 203, 40), (1291, 1, 1, '0:14,14:+', '400:1000000,', 41, 203, 42), (1292, 1, 1, '0:14,14:+', '0:1000,', 28, 203, 30), (1293, 1, 1, '0:14,14:+', '0:1000,', 67, 203, 65), (1294, 1, 1, '0:14,14:+', ':,', 93, 203, 86), (1295, 1, 1, '0:14,14:+', '190:1955,', 92, 203, 86), (1296, 1, 1, '0:14,14:+', '130:1118,', 91, 203, 86), (1297, 1, 1, '0:14,14:+', '350:1610,', 90, 203, 86), (1298, 1, 1, '0:14,14:+', '0:1000,', 77, 203, 74), (1299, 1, 1, '0:14,14:+', '4.0:10.0,', 2, 203, 52), (1336, 1, 1, '', 'P/N', 57, 129, 58), (1337, 1, 1, '', 'P/N', 40, 129, 41), (1338, 1, 1, '', 'N/P', 3, 129, 87), (1360, 1, 1, '', 'Straw/Pale Yellow/Deep Yellow/Amber', 51, 129, 56), (1361, 1, 1, '', 'Clear/Cloudy', 52, 129, 56), (1362, 1, 1, '', 'P/N', 53, 129, 56), (1365, 1, 1, '', 'Clear/Cloudy', 52, 128, 56), (1366, 1, 1, '', 'P/N', 53, 128, 56), (1367, 1, 1, '', 'P/N', 57, 130, 58), (1368, 1, 1, '', 'Straw/Pale Yellow/Deep Yellow/Amber', 51, 130, 56), (1369, 1, 1, '', 'Clear/Cloudy', 52, 130, 56), (1370, 1, 1, '', 'P/N', 53, 130, 56), (1371, 1, 1, '', 'P/N', 57, 131, 58), (1372, 1, 1, '', 'Straw/Pale Yellow/Deep Yellow/Amber', 51, 131, 56), (1373, 1, 1, '', 'Clear/Cloudy', 52, 131, 56), (1374, 1, 1, '', 'P/N', 53, 131, 56), (1422, 1, 1, '', 'P/N', 57, 203, 58), (1423, 1, 1, '', 'Straw/Pale Yellow/Deep Yellow/Amber', 51, 203, 56), (1424, 1, 1, '', 'Clear/Cloudy', 52, 203, 56), (1425, 1, 1, '', 'P/N', 53, 203, 56), (1432, 1, 1, '', 'N/P', 89, 131, 85), (1433, 1, 1, '', 'P/N', 66, 131, 64), (1442, 1, 1, '', 'P/N', 56, 131, 57), (1443, 1, 1, '', 'AA/AF/AS/SS', 46, 131, 49), (1458, 1, 1, '', 'N/1+/2+/3+/4+', 32, 131, 38), (1461, 1, 1, '', 'N/P', 62, 131, 61), (1466, 1, 1, '', 'N/P', 44, 131, 47), (1472, 1, 1, '', 'NR/1+/2+/3+/4+', 87, 131, 83), (1475, 1, 1, '', 'P/N', 69, 131, 67), (1476, 1, 1, '', 'P/N', 68, 131, 66), (1479, 1, 1, '', '', 0, 131, 0), (1480, 1, 1, '', '0:1000,', 6, 131, 8), (1481, 1, 1, '', '0:1000,', 18, 131, 20), (1482, 1, 1, '', '0:1000,', 19, 131, 21), (1483, 1, 1, '', '0.56:1.13,', 13, 131, 22), (1484, 1, 1, '', '0:100,', 21, 131, 23), (1485, 1, 1, '', '0:100,', 22, 131, 24), (1486, 1, 1, '', '0:100,', 23, 131, 25), (1487, 1, 1, '', '0:1000,', 27, 131, 29), (1488, 1, 1, '', '0:1000,', 28, 131, 30), (1489, 1, 1, '', '0:1000,', 50, 131, 55), (1490, 1, 1, '', '0:1000,', 14, 131, 16), (1491, 1, 1, '', '4.0:10.0,', 2, 131, 39), (1492, 1, 1, '', '3.5:5.5,', 33, 131, 39), (1493, 1, 1, '', '11.0 0.5:15.0,', 34, 131, 39), (1494, 1, 1, '', '80.0:99.0,', 36, 131, 39), (1495, 1, 1, '', '26.0:32.0,', 37, 131, 39), (1496, 1, 1, '', '32.0:36.0,', 38, 131, 39), (1497, 1, 1, '', '100:300,', 39, 131, 39), (1498, 1, 1, '', '0:1000,', 47, 131, 51), (1499, 1, 1, '', '11.0 0.5:15.0,', 34, 131, 40), (1500, 1, 1, '', '4.0:10.0,', 2, 131, 52), (1501, 1, 1, '', '0:100,', 49, 131, 54), (1502, 1, 1, '', '0:1000,', 25, 131, 27), (1503, 1, 1, '', '0:1000,', 30, 131, 32), (1504, 1, 1, '', '0:100,', 73, 131, 70), (1505, 1, 1, '', '0:100,', 59, 131, 60), (1506, 1, 1, '', '0:10000,', 60, 131, 60), (1507, 1, 1, '', '0:1000,', 61, 131, 60), (1508, 1, 1, '', '0:1000,', 16, 131, 18), (1509, 1, 1, '', '0:1000,', 70, 131, 68), (1510, 1, 1, '', '0:10,', 10, 131, 12), (1511, 1, 1, '', '0:3000,', 4, 131, 7), (1512, 1, 1, '', '0:90,', 5, 131, 7), (1513, 1, 1, '', '0.56:1.13,', 13, 131, 15), (1514, 1, 1, '', '0:1000,', 76, 131, 73), (1515, 1, 1, '', '0:1000,', 29, 131, 31), (1516, 1, 1, '', '0:1000,', 6, 131, 37), (1517, 1, 1, '', '0:1000,', 16, 131, 37), (1518, 1, 1, '', '0.56:1.13,', 13, 131, 37), (1519, 1, 1, '', '0:1000,', 29, 131, 37), (1520, 1, 1, '', '0:1000,', 31, 131, 33), (1521, 1, 1, '', '0:1000,', 25, 131, 35), (1522, 1, 1, '', '0:1000,', 26, 131, 35), (1523, 1, 1, '', '0:1000,', 27, 131, 35), (1524, 1, 1, '', '0:1000,', 28, 131, 35), (1525, 1, 1, '', '0:1000,', 6, 131, 36), (1526, 1, 1, '', '0:1000,', 16, 131, 36), (1527, 1, 1, '', '0:1000,', 17, 131, 36), (1528, 1, 1, '', '0:1000,', 18, 131, 36), (1529, 1, 1, '', '0:10,', 12, 131, 14), (1530, 1, 1, '', '1:10,', 11, 131, 13), (1531, 1, 1, '', '100:300,', 39, 131, 50), (1532, 1, 1, '', '0:1000,', 63, 131, 62), (1533, 1, 1, '', '0:1000,', 75, 131, 72), (1534, 1, 1, '', '5:1000,', 8, 131, 10), (1535, 1, 1, '', '3.6:12,', 88, 131, 84), (1536, 1, 1, '', '0:1000,', 67, 131, 65), (1537, 1, 1, '', ':,', 93, 131, 86), (1538, 1, 1, '', '190:1955,', 92, 131, 86), (1539, 1, 1, '', '130:1118,', 91, 131, 86), (1540, 1, 1, '', '350:1610,', 90, 131, 86), (1541, 1, 1, '', '0:1000,', 77, 131, 74), (1542, 1, 1, '', '0:1000,', 15, 131, 17), (1543, 1, 1, '', '0:1000,', 26, 131, 28), (1544, 1, 1, '', '0:100,', 9, 131, 11), (1545, 1, 1, '', 'oui/non', 94, 131, 88), (1547, 1, 1, '', 'YES/NO', 95, 129, 89), (1548, 1, 1, '', 'YES/NO', 95, 130, 89), (1549, 1, 1, '', 'YES/NO', 95, 131, 89), (1550, 1, 1, '', 'YES/NO', 95, 203, 89), (1554, 1, 1, '', 'P/N', 66, 128, 64), (1564, 1, 1, '', 'positif/negatif', 94, 128, 88), (1568, 1, 1, '', 'P/N', 56, 128, 57), (1580, 1, 1, '', 'N/1+/2+/3+/4+', 32, 128, 38), (1585, 1, 1, '', 'P/N', 58, 128, 59), (1586, 1, 1, '', 'N/P', 44, 128, 47), (1588, 1, 1, '', 'NR/1+/2+/3+/4+', 87, 128, 83), (1591, 1, 1, '', 'P/N', 69, 128, 67), (1592, 1, 1, '', 'P/N', 68, 128, 66), (1601, 1, 1, '', '1/5', 97, 128, 91), (1603, 1, 1, '', 'Present/Absent', 99, 128, 93), (1606, 1, 1, '', 'P/A', 104, 128, 98), (1808, 1, 1, '0:1,1:4,4:14,14:45,45:+', '0:1000,', 70, 128, 68), (1848, 1, 1, '0:1,1:4,4:14,14:45,45:+', '0:4.0,', 105, 128, 99), (1856, 1, 1, '', 'leucocytes - upto 10cells/HPF_leucocytes - 11 - 40cells/HPF_leucocytes - >40cells/HPF_epithelial cells +_epithelial cells ++_epithelial cellsb +++_red blood cells +_red blood cells ++_red blood cells +++_yeast cells +_yeast cells ++_yeast cells +++_motile bacteria +_motile bacteria ++_motile bacteria +++_eggs of Schitosoma haematobium +_eggs of Schitosoma haematobium ++_eggs of Schitosoma haematobium +++_Trichomonas vaginalis +_Trichomonas vaginalis ++_Trichomonas vaginalis +++_Microfilarial', 139, 128, 56), (1860, 1, 1, '', 'leucocytes+_leucocytes++_leucocytes++_epith cells+_epith cells++_epith cells+++_pus cells+_yeast cells+_pus cells++_pus cells+++_yeast cells++_yeast cells+++_gram positive cocci iso/pairs+_gram positive cocci in clusters +_gram positive cocci in clusters ++_gram positive cocci in clusters +++_gram positive cocci iso/pairs++_gram positive cocci iso/pairs+++_gram negative intra/extracellular cocci +_gram negative intra/extracellular cocci ++_gram negative intra/extracellular cocci +++_gram negativ', 132, 128, 93), (1862, 1, 1, '', '1/80_1/160_1/320_positive_negative', 133, 128, 96), (1863, 1, 1, '', '1/80_1/160_1/320_positive_negative', 134, 128, 96), (1864, 1, 1, '', '1/80_1/160_1/320_positive_negative', 135, 128, 96), (1865, 1, 1, '', '1/80_1/160_1/320_positive_negative', 136, 128, 96), (1866, 1, 1, '', '1/80_1/160_1/320_positive_negative', 152, 128, 96), (1867, 1, 1, '', '1/80_1/160_1/320_positive_negative', 153, 128, 96), (1868, 1, 1, '', '1/80_1/160_1/320_positive_negative', 154, 128, 96), (1869, 1, 1, '', '1/80_1/160_1/320_positive_negative', 155, 128, 96), (1870, 1, 1, '', 'presence/absence_M hominis and M ureaplasma', 112, 128, 106), (1872, 1, 1, '', 'epith cells +_yeast cells +_pus cells +_Gram positive cocci iso/pairs_Gram positive rods isolated_Gram negative cocci isolated/pairs_Gram negative bacilli_Gram positive bacilli_Clue cells_epith cells ++_epith cells +++_yeast cells ++_yeast cells +++_pus cells ++_pus cels +++', 118, 128, 107), (1873, 1, 1, '', 'epith cells+_epith cells++_epith cells+++_pus cells+_pus cells++_pus cells+++_yeast cells +_yeast cells ++_yeast cells +++_absence of normal flora_presence of normal flora_gram positive bacilli +_gram positive bacilli ++_gram positive bacilli +++_gram positive cocci isolated/pairs +_gram positive cocci isolated/pairs ++_gram positive cocci isolated/pairs +++_gram negative bacilli +_gram negative bacilli ++_gram negative bacilli +++_gram negative intra/extracellular cocci +_gram negative intra/ex', 130, 128, 92), (1889, 1, 1, '', 'epithelial cells +_epithelial cells ++_epithelial cells +++_pus cells +_pus cells ++_pus cells +++_Gram positive bacilli +_Gram positive bacilli ++_Gram positive bacilli +++_Gram positive cocci clusters +_Gram positive cocci clusters ++_Gram positive cocci clusters +++_Gram positive cocci: iso/pairs +_Gram positive cocci: iso/pairs ++_Gram positive cocci: iso/pairs +++_Gram positive cocci in chains +_Gram positive cocci in chains ++_Gram positive cocci in chains +++_Gram negative bacilli +_Gram ', 151, 128, 118), (1894, 1, 1, '', 'epith cells_yeast cells_pus cells_Gram positive cocci iso/pairs +_Gram positive cocci in pairs/clustre/chains+_Gram negative rods+_Gram negative bacilli, intracellular/extracellular+_gram positive rods+_T. vagina_Gram positive cocci iso/pairs ++_Gram positive cocci iso/pairs +++_Gram positive cocci in pairs/clustre/chains++_Gram negative rods++_Gram negative rods+++_Gram negative bacilli, intracellular/extracellular++_Gram negative bacilli, intracellular/extracellular+++_gram positive rods++_gra', 119, 128, 89), (1896, 1, 1, '0:1,1:4,4:14,14:45,45:+', '', 0, 128, 0), (1897, 1, 1, '0:1,1:4,4:14,14:45,45:+', '0:31F,0:41M,', 6, 128, 8), (1898, 1, 1, '0:1,1:4,4:14,14:45,45:+', '4.0:10.0,', 2, 128, 39), (1899, 1, 1, '0:1,1:4,4:14,14:45,45:+', '3.5:5.5,', 33, 128, 39), (1900, 1, 1, '0:1,1:4,4:14,14:45,45:+', '11.0 0.5:15.0,', 34, 128, 39), (1901, 1, 1, '0:1,1:4,4:14,14:45,45:+', '80.0:99.0,', 36, 128, 39), (1902, 1, 1, '0:1,1:4,4:14,14:45,45:+', '26.0:32.0,', 37, 128, 39), (1903, 1, 1, '0:1,1:4,4:14,14:45,45:+', '32.0:36.0,', 38, 128, 39), (1904, 1, 1, '0:1,1:4,4:14,14:45,45:+', '100:300,', 39, 128, 39), (1905, 1, 1, '0:1,1:4,4:14,14:45,45:+', '100:300,', 39, 128, 50), (1906, 1, 1, '0:1,1:4,4:14,14:45,45:+', '0:1000,', 47, 128, 51), (1907, 1, 1, '0:1,1:4,4:14,14:45,45:+', '11.0 0.5:15.0,', 34, 128, 40), (1908, 1, 1, '0:1,1:4,4:14,14:45,45:+', '4.0:10.0,', 2, 128, 52), (1909, 1, 1, '0:1,1:4,4:14,14:45,45:+', '5:8,:,', 49, 128, 54), (1910, 1, 1, '0:1,1:4,4:14,14:45,45:+', 'Formed(solid)/Semi-formed(not solid)/Watery:,', 54, 128, 71), (1911, 1, 1, '0:1,1:4,4:14,14:45,45:+', 'P/N:,', 55, 128, 71), (1912, 1, 1, '0:1,1:4,4:14,14:45,45:+', '0:30 for female,0:36 for male,', 16, 128, 18), (1913, 1, 1, '0:1,1:4,4:14,14:45,45:+', '0:1000,', 18, 128, 20), (1914, 1, 1, '0:1,1:4,4:14,14:45,45:+', '0.5:0.9F,0.6:1.1M,', 13, 128, 22), (1915, 1, 1, '0:1,1:4,4:14,14:45,45:+', '135:155,', 21, 128, 23), (1916, 1, 1, '0:1,1:4,4:14,14:45,45:+', ':,', 120, 128, 23), (1917, 1, 1, '0:1,1:4,4:14,14:45,45:+', '3.6:5.5,', 22, 128, 24), (1918, 1, 1, '0:1,1:4,4:14,14:45,45:+', '98:105,', 23, 128, 25), (1919, 1, 1, '0:1,1:4,4:14,14:45,45:+', '9:39F,11:61M,', 50, 128, 55), (1920, 1, 1, '0:1,1:4,4:14,14:45,45:+', '1.9:2.5,', 12, 128, 14), (1921, 1, 1, '0:1,1:4,4:14,14:45,45:+', 'P/N:,', 57, 128, 58), (1922, 1, 1, '0:1,1:4,4:14,14:45,45:+', '1.2:19.5,', 75, 128, 72), (1923, 1, 1, '0:1,1:4,4:14,14:45,45:+', '0:1000,', 77, 128, 74), (1924, 1, 1, '0:1,1:4,4:14,14:45,45:+', '2:2.5,', 73, 128, 70), (1925, 1, 1, '0:1,1:4,4:14,14:45,45:+', 'Straw/Pale Yellow/Deep Yellow/Amber:,', 51, 128, 56), (1926, 1, 1, '0:1,1:4,4:14,14:45,45:+', ':,', 93, 128, 86), (1927, 1, 1, '0:1,1:4,4:14,14:45,45:+', '190:1955,', 92, 128, 86), (1928, 1, 1, '0:1,1:4,4:14,14:45,45:+', '130:1118,', 91, 128, 86), (1929, 1, 1, '0:1,1:4,4:14,14:45,45:+', '350:1610,', 90, 128, 86), (1930, 1, 1, '0:1,1:4,4:14,14:45,45:+', '0:3000,', 4, 128, 7), (1931, 1, 1, '0:1,1:4,4:14,14:45,45:+', '0:90,', 5, 128, 7), (1932, 1, 1, '0:1,1:4,4:14,14:45,45:+', '76:110,', 7, 128, 9), (1933, 1, 1, '0:1,1:4,4:14,14:45,45:+', 'YES/NO:,', 95, 128, 89), (1934, 1, 1, '0:1,1:4,4:14,14:45,45:+', 'bloody_sticky discharge:,', 113, 128, 89), (1935, 1, 1, '0:1,1:4,4:14,14:45,45:+', 'Staph aureus_stahp spp_E. coli_Escherichia spp_serratia spp_klebsiella spp_Proteus spp_Streptococcuc spp_Salmonella spp_Shigella spp:,', 114, 128, 89), (1936, 1, 1, '0:1,1:4,4:14,14:45,45:+', 'sensitive to_intermediate to_resistant to_doxycyclin_erythromycin_penicillin_ceftriazone_nyststin_ketoconazole_netilmicin_cotrimoxazole_trimetoprime_ampicillin:,', 115, 128, 89), (1937, 1, 1, '0:1,1:4,4:14,14:45,45:+', 'significant > 1000000_intermediate 1000 to 1000000_insignificant >1000000:,', 116, 128, 89), (1938, 1, 1, '0:1,1:4,4:14,14:45,45:+', 'N/P:,', 89, 128, 85), (1939, 1, 1, '0:1,1:4,4:14,14:45,45:+', '0:1000,', 17, 128, 19), (1940, 1, 1, '0:1,1:4,4:14,14:45,45:+', ':,', 126, 128, 19), (1941, 1, 1, '0:1,1:4,4:14,14:45,45:+', ':,', 127, 128, 19), (1942, 1, 1, '0:1,1:4,4:14,14:45,45:+', '0:1000,', 30, 128, 32), (1943, 1, 1, '0:1,1:4,4:14,14:45,45:+', '4.7:23.4,', 19, 128, 21), (1944, 1, 1, '0:1,1:4,4:14,14:45,45:+', '0:10,', 10, 128, 12), (1945, 1, 1, '0:1,1:4,4:14,14:45,45:+', '0:1000,', 25, 128, 27), (1946, 1, 1, '0:1,1:4,4:14,14:45,45:+', '0:100,', 24, 128, 26), (1947, 1, 1, '0:1,1:4,4:14,14:45,45:+', '0.56:1.13,', 13, 128, 15), (1948, 1, 1, '0:1,1:4,4:14,14:45,45:+', '0:100,', 59, 128, 60), (1949, 1, 1, '0:1,1:4,4:14,14:45,45:+', '0:10000,', 60, 128, 60), (1950, 1, 1, '0:1,1:4,4:14,14:45,45:+', '0:1000,', 61, 128, 60), (1951, 1, 1, '0:1,1:4,4:14,14:45,45:+', '0:1000,', 76, 128, 73), (1952, 1, 1, '0:1,1:4,4:14,14:45,45:+', '0:1000,', 29, 128, 31), (1953, 1, 1, '0:1,1:4,4:14,14:45,45:+', '0:1000,', 27, 128, 29), (1954, 1, 1, '0:1,1:4,4:14,14:45,45:+', '0:1000,', 6, 128, 37), (1955, 1, 1, '0:1,1:4,4:14,14:45,45:+', '0:1000,', 16, 128, 37), (1956, 1, 1, '0:1,1:4,4:14,14:45,45:+', '0.56:1.13,', 13, 128, 37), (1957, 1, 1, '0:1,1:4,4:14,14:45,45:+', '0:1000,', 29, 128, 37), (1958, 1, 1, '0:1,1:4,4:14,14:45,45:+', '0:1000,', 19, 128, 34), (1959, 1, 1, '0:1,1:4,4:14,14:45,45:+', '0.56:1.13,', 13, 128, 34), (1960, 1, 1, '0:1,1:4,4:14,14:45,45:+', '0:1000,', 28, 128, 30), (1961, 1, 1, '0:1,1:4,4:14,14:45,45:+', '0:1000,', 6, 128, 36), (1962, 1, 1, '0:1,1:4,4:14,14:45,45:+', '0:1000,', 16, 128, 36), (1963, 1, 1, '0:1,1:4,4:14,14:45,45:+', '0:1000,', 17, 128, 36), (1964, 1, 1, '0:1,1:4,4:14,14:45,45:+', '0:1000,', 18, 128, 36), (1965, 1, 1, '0:1,1:4,4:14,14:45,45:+', '0:4.1F,0:4.9M,', 11, 128, 13), (1966, 1, 1, '0:1,1:4,4:14,14:45,45:+', '0:1000,', 63, 128, 62), (1967, 1, 1, '0:1,1:4,4:14,14:45,45:+', '5:1000,', 8, 128, 10), (1968, 1, 1, '0:1,1:4,4:14,14:45,45:+', '3.6:12,', 88, 128, 84), (1969, 1, 1, '0:1,1:4,4:14,14:45,45:+', '0:1000,', 67, 128, 65), (1970, 1, 1, '0:1,1:4,4:14,14:45,45:+', '0:1000,', 14, 128, 16), (1971, 1, 1, '0:1,1:4,4:14,14:45,45:+', '0:1000,', 15, 128, 17), (1972, 1, 1, '0:1,1:4,4:14,14:45,45:+', '0:1000,', 26, 128, 28), (1973, 1, 1, '0:1,1:4,4:14,14:45,45:+', '0:100,', 9, 128, 11), (1974, 1, 1, '0:1,1:4,4:14,14:45,45:+', '0:1000,', 96, 128, 90), (1975, 1, 1, '0:1,1:4,4:14,14:45,45:+', '0:1000,', 31, 128, 33), (1976, 1, 1, '0:1,1:4,4:14,14:45,45:+', '0:199,', 25, 128, 35), (1977, 1, 1, '0:1,1:4,4:14,14:45,45:+', '0:200,', 26, 128, 35), (1978, 1, 1, '0:1,1:4,4:14,14:45,45:+', '45:165F,35:55M,', 27, 128, 35), (1979, 1, 1, '0:1,1:4,4:14,14:45,45:+', '255:450,', 28, 128, 35), (1980, 1, 1, '0:1,1:4,4:14,14:45,45:+', ':,', 128, 128, 108), (1981, 1, 1, '0:1,1:4,4:14,14:45,45:+', 'epith cells+_yeast cells+_leucocytes+_absence of T. vaginalis_presence of T. vaginalis_epith cells++_epith cells+++_yeast cells++_yeast cells+++_leucocytes++_leucocytes+++:,', 131, 128, 93), (1982, 1, 1, '0:1,1:4,4:14,14:45,45:+', '160:320,', 102, 128, 96), (1983, 1, 1, '0:1,1:4,4:14,14:45,45:+', '60:1000,', 103, 128, 97), (1984, 1, 1, '0:1,1:4,4:14,14:45,45:+', '8.5:10.5,', 106, 128, 100), (1985, 1, 1, '0:1,1:4,4:14,14:45,45:+', '10:50,', 107, 128, 101), (1986, 1, 1, '0:1,1:4,4:14,14:45,45:+', '0:0.24,', 109, 128, 103), (1987, 1, 1, '0:1,1:4,4:14,14:45,45:+', '1:1000,', 108, 128, 102), (1988, 1, 1, '0:1,1:4,4:14,14:45,45:+', '0:0.10,', 110, 128, 104), (1989, 1, 1, '0:1,1:4,4:14,14:45,45:+', '0:500,', 111, 128, 105), (1990, 1, 1, '0:1,1:4,4:14,14:45,45:+', 'whitish discharge_purulent discharge_clear fluid_no discharge_Foamy discharge:,', 117, 128, 107), (1991, 1, 1, '0:1,1:4,4:14,14:45,45:+', ':,', 98, 128, 92), (1992, 1, 1, '0:1,1:4,4:14,14:45,45:+', 'epith cells +_epith cells ++_epith cells +++_leucocytes +_leucocytes ++_leucocytes +++_yeast cells +_yeast cells ++_yeast cells +++_absence of T. vaginalis_T. vaginalis present:,', 129, 128, 92), (1993, 1, 1, '0:1,1:4,4:14,14:45,45:+', 'Present_Absent_Loa loa_Wuchereria bancrofti_Onchocerca vulvolis:,', 137, 128, 109), (1994, 1, 1, '0:1,1:4,4:14,14:45,45:+', ':,', 138, 128, 110), (1995, 1, 1, '0:1,1:4,4:14,14:45,45:+', '1:10,', 100, 128, 94), (1996, 1, 1, '0:1,1:4,4:14,14:45,45:+', ':,', 140, 128, 111), (1997, 1, 1, '0:1,1:4,4:14,14:45,45:+', 'Positive_Negative:,', 145, 128, 116), (1998, 1, 1, '0:1,1:4,4:14,14:45,45:+', 'Positive_negative:,', 146, 128, 116), (1999, 1, 1, '0:1,1:4,4:14,14:45,45:+', 'Positive_negative:,', 147, 128, 116), (2000, 1, 1, '0:1,1:4,4:14,14:45,45:+', 'Positive_Negative:,', 148, 128, 116), (2001, 1, 1, '0:1,1:4,4:14,14:45,45:+', 'Positive_Nagative:,', 149, 128, 116), (2002, 1, 1, '0:1,1:4,4:14,14:45,45:+', ':,', 141, 128, 112), (2003, 1, 1, '0:1,1:4,4:14,14:45,45:+', ':,', 143, 128, 114), (2004, 1, 1, '0:1,1:4,4:14,14:45,45:+', ':,', 142, 128, 113), (2005, 1, 1, '0:1,1:4,4:14,14:45,45:+', ':,', 144, 128, 115), (2006, 1, 1, '0:1,1:4,4:14,14:45,45:+', ':,', 150, 128, 117), (2007, 1, 1, '0:1,1:4,4:14,14:45,45:+', 'NEGATIVE_POSITIVE:,', 156, 128, 119), (2008, 1, 1, '', ':', 161, 128, 124), (2009, 1, 1, '', ':', 162, 128, 125), (2010, 1, 1, '', ':', 163, 128, 126), (2028, 1, 0, '', '$freetext$$:,', 13, 127, 21), (2066, 1, 0, '', '$freetext$$:,', 18, 127, 93), (2071, 1, 0, '', '$freetext$$:,', 18, 127, 51), (2072, 1, 0, '', '$freetext$$:,', 18, 127, 52), (2073, 1, 0, '', '$freetext$$:,', 18, 127, 53), (2074, 1, 0, '', '$freetext$$:,', 13, 127, 54), (2075, 1, 0, '', '$freetext$$:,', 19, 127, 55), (2076, 1, 0, '', '$freetext$$:,', 20, 127, 56), (2077, 1, 0, '', '$freetext$$:,', 18, 127, 57), (2078, 1, 0, '', '$freetext$$:,', 18, 127, 58), (2079, 1, 0, '', '$freetext$$:,', 18, 127, 59), (2080, 1, 0, '', '$freetext$$:,', 18, 127, 60), (2081, 1, 0, '', '$freetext$$:,', 18, 127, 61), (2082, 1, 0, '', '$freetext$$:,', 18, 127, 62), (2083, 1, 0, '', '$freetext$$:,', 18, 127, 63), (2084, 1, 0, '', '$freetext$$:,', 18, 127, 64), (2085, 1, 0, '', '$freetext$$:,', 18, 127, 65), (2086, 1, 0, '', '$freetext$$:,', 18, 127, 66), (2087, 1, 0, '', '$freetext$$:,', 18, 127, 67), (2088, 1, 0, '', '$freetext$$:,', 18, 127, 68), (2089, 1, 0, '', '$freetext$$:,', 18, 127, 69), (2090, 1, 0, '', '$freetext$$:,', 18, 127, 70), (2091, 1, 0, '', '$freetext$$:,', 18, 127, 71), (2092, 1, 0, '', '$freetext$$:,', 18, 127, 104), (2093, 1, 0, '', '$freetext$$:,', 21, 127, 73), (2094, 1, 0, '', '$freetext$$:,', 21, 127, 74), (2095, 1, 0, '', '$freetext$$:,', 21, 127, 75), (2096, 1, 0, '', '$freetext$$:,', 18, 127, 98), (2097, 1, 0, '', '$freetext$$:,', 18, 127, 108), (2098, 1, 0, '', '$freetext$$:,', 18, 127, 105), (2099, 1, 0, '', '$freetext$$:,', 21, 127, 80), (2100, 1, 0, '', '$freetext$$:,', 13, 127, 95), (2101, 1, 0, '', '$freetext$$:,', 18, 127, 106), (2102, 1, 0, '', '$freetext$$:,', 21, 127, 83), (2105, 1, 0, '', '$freetext$$:,', 20, 127, 85), (2732, 1, 1, '0:10,11:20,21:30,31:40,41:50,51:60,61:100', ':,', 12, 127, 85), (2734, 1, 1, '0:10,11:20,21:30,31:40,41:50,51:60,61:100', '', 0, 127, 0), (2735, 1, 1, '0:10,11:20,21:30,31:40,41:50,51:60,61:100', '4:5,', 13, 127, 22), (2736, 1, 1, '0:10,11:20,21:30,31:40,41:50,51:60,61:100', '47:258,', 25, 127, 94), (2737, 1, 1, '0:10,11:20,21:30,31:40,41:50,51:60,61:100', '45:244,', 13, 127, 19), (2738, 1, 1, '0:10,11:20,21:30,31:40,41:50,51:60,61:100', '472:500,', 13, 127, 17), (2739, 1, 1, '0:10,11:20,21:30,31:40,41:50,51:60,61:100', '4:10,', 12, 127, 16), (2740, 1, 1, '0:10,11:20,21:30,31:40,41:50,51:60,61:100', '0:5,6:10,', 10, 127, 10), (2741, 1, 1, '0:10,11:20,21:30,31:40,41:50,51:60,61:100', '45:789,', 27, 127, 103), (2742, 1, 1, '0:10,11:20,21:30,31:40,41:50,51:60,61:100', '4:10,', 18, 127, 101), (2743, 1, 1, '0:10,11:20,21:30,31:40,41:50,51:60,61:100', '1:2,', 8, 127, 13), (2744, 1, 1, '0:10,11:20,21:30,31:40,41:50,51:60,61:100', '1:5,', 11, 127, 12), (2745, 1, 1, '0:10,11:20,21:30,31:40,41:50,51:60,61:100', '11:99,', 15, 127, 110), (2746, 1, 1, '0:10,11:20,21:30,31:40,41:50,51:60,61:100', '0:100,', 9, 127, 99), (2747, 1, 1, '0:10,11:20,21:30,31:40,41:50,51:60,61:100', '0:150,151:350,351:500,501:10000,', 2, 127, 3), (2748, 1, 1, '0:10,11:20,21:30,31:40,41:50,51:60,61:100', ':,', 9, 127, 9), (2749, 1, 1, '0:10,11:20,21:30,31:40,41:50,51:60,61:100', '0:400,401:800,801:1000,', 8, 127, 8), (2750, 1, 1, '0:10,11:20,21:30,31:40,41:50,51:60,61:100', ':,', 14, 127, 23), (2751, 1, 1, '0:10,11:20,21:30,31:40,41:50,51:60,61:100', ':,', 14, 127, 24), (2752, 1, 1, '0:10,11:20,21:30,31:40,41:50,51:60,61:100', '7:8,', 14, 127, 107), (2753, 1, 1, '0:10,11:20,21:30,31:40,41:50,51:60,61:100', '7:25,', 15, 127, 26), (2754, 1, 1, '0:10,11:20,21:30,31:40,41:50,51:60,61:100', '4:47,', 14, 127, 27), (2755, 1, 1, '0:10,11:20,21:30,31:40,41:50,51:60,61:100', '7:10,', 14, 127, 28), (2756, 1, 1, '0:10,11:20,21:30,31:40,41:50,51:60,61:100', ':,', 15, 127, 109), (2757, 1, 1, '0:10,11:20,21:30,31:40,41:50,51:60,61:100', ':,', 26, 127, 96), (2758, 1, 1, '0:10,11:20,21:30,31:40,41:50,51:60,61:100', ':,', 27, 127, 97), (2759, 1, 1, '0:10,11:20,21:30,31:40,41:50,51:60,61:100', ':,', 9, 127, 32), (2760, 1, 1, '0:10,11:20,21:30,31:40,41:50,51:60,61:100', ':,', 24, 127, 92), (2761, 1, 1, '0:10,11:20,21:30,31:40,41:50,51:60,61:100', ':,', 9, 127, 88), (2762, 1, 1, '0:10,11:20,21:30,31:40,41:50,51:60,61:100', ':,', 9, 127, 35), (2763, 1, 1, '0:10,11:20,21:30,31:40,41:50,51:60,61:100', ':,', 9, 127, 89), (2764, 1, 1, '0:10,11:20,21:30,31:40,41:50,51:60,61:100', ':,', 24, 127, 90), (2765, 1, 1, '0:10,11:20,21:30,31:40,41:50,51:60,61:100', ':,', 24, 127, 100), (2766, 1, 1, '0:10,11:20,21:30,31:40,41:50,51:60,61:100', ':,', 24, 127, 91), (2767, 1, 1, '0:10,11:20,21:30,31:40,41:50,51:60,61:100', '4:50,', 14, 127, 40), (2768, 1, 1, '0:10,11:20,21:30,31:40,41:50,51:60,61:100', ':,', 14, 127, 41), (2769, 1, 1, '0:10,11:20,21:30,31:40,41:50,51:60,61:100', ':,', 27, 127, 102), (2770, 1, 1, '0:10,11:20,21:30,31:40,41:50,51:60,61:100', ':,', 14, 127, 43), (2771, 1, 1, '0:10,11:20,21:30,31:40,41:50,51:60,61:100', ':,', 14, 127, 44), (2772, 1, 1, '0:10,11:20,21:30,31:40,41:50,51:60,61:100', ':,', 24, 127, 87), (2773, 1, 1, '0:10,11:20,21:30,31:40,41:50,51:60,61:100', ':,', 14, 127, 47), (2774, 1, 1, '0:10,11:20,21:30,31:40,41:50,51:60,61:100', ':,', 14, 127, 48), (2775, 1, 1, '0:10,11:20,21:30,31:40,41:50,51:60,61:100', ':,', 16, 127, 49), (2776, 1, 1, '0:10,11:20,21:30,31:40,41:50,51:60,61:100', ':,', 17, 127, 50), (2777, 1, 1, '0:10,11:20,21:30,31:40,41:50,51:60,61:100', ':,', 22, 127, 84), (2778, 1, 1, '0:10,11:20,21:30,31:40,41:50,51:60,61:100', ':,', 28, 127, 112), (2779, 1, 1, '0:10,11:20,21:30,31:40,41:50,51:60,61:100', ':,', 23, 127, 86); -- -------------------------------------------------------- -- -- Table structure for table `specimen` -- CREATE TABLE IF NOT EXISTS `specimen` ( `specimen_id` int(10) unsigned NOT NULL DEFAULT '0', `patient_id` int(11) unsigned NOT NULL DEFAULT '0', `specimen_type_id` int(11) unsigned NOT NULL DEFAULT '0', `user_id` int(11) unsigned DEFAULT NULL, `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `status_code_id` int(11) unsigned DEFAULT NULL, `referred_to` int(11) unsigned DEFAULT NULL, `comments` text, `aux_id` varchar(45) DEFAULT NULL, `date_collected` date NOT NULL DEFAULT '0000-00-00', `date_recvd` date DEFAULT NULL, `session_num` varchar(45) DEFAULT NULL, `time_collected` varchar(45) DEFAULT NULL, `report_to` int(10) unsigned DEFAULT NULL, `doctor` varchar(45) DEFAULT NULL, `date_reported` datetime DEFAULT NULL, `referred_to_name` varchar(70) DEFAULT NULL, `daily_num` varchar(45) NOT NULL DEFAULT '', `external_lab_no` varchar(45) DEFAULT NULL, `ts_collected` datetime DEFAULT NULL, `referral_facility_code` int(11) DEFAULT NULL, `ts_accept_reject` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `accept_rejected_by` varchar(20) DEFAULT NULL, PRIMARY KEY (`specimen_id`), KEY `patient_id` (`patient_id`), KEY `specimen_type_id` (`specimen_type_id`), KEY `user_id` (`user_id`), KEY `IDX_DATE` (`date_collected`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `specimen_custom_data` -- CREATE TABLE IF NOT EXISTS `specimen_custom_data` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `field_id` int(11) unsigned NOT NULL DEFAULT '0', `specimen_id` int(10) unsigned NOT NULL DEFAULT '0', `field_value` varchar(45) NOT NULL DEFAULT '', `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`), KEY `field_id` (`field_id`), KEY `specimen_id` (`specimen_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `specimen_custom_field` -- CREATE TABLE IF NOT EXISTS `specimen_custom_field` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `field_name` varchar(45) NOT NULL DEFAULT '', `field_options` varchar(45) NOT NULL DEFAULT '', `field_type_id` int(11) unsigned NOT NULL DEFAULT '0', `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`), KEY `field_type_id` (`field_type_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `specimen_mapping` -- CREATE TABLE IF NOT EXISTS `specimen_mapping` ( `user_id` int(11) NOT NULL DEFAULT '0', `specimen_name` varchar(256) COLLATE latin1_general_ci DEFAULT NULL, `lab_id_specimen_id` varchar(256) COLLATE latin1_general_ci DEFAULT NULL, `specimen_id` int(10) NOT NULL DEFAULT '0', PRIMARY KEY (`user_id`,`specimen_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci; -- -------------------------------------------------------- -- -- Table structure for table `specimen_session` -- CREATE TABLE IF NOT EXISTS `specimen_session` ( `session_num` varchar(45) NOT NULL DEFAULT '', `count` int(10) unsigned NOT NULL DEFAULT '0', PRIMARY KEY (`session_num`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `specimen_session` -- INSERT INTO `specimen_session` (`session_num`, `count`) VALUES ('20140225', 3), ('20140226', 4), ('20140228', 9), ('20140307', 7), ('20140308', 1), ('20140317', 3), ('20140318', 10), ('20140320', 1), ('20140322', 2), ('20140325', 1), ('20140327', 1), ('20140331', 7), ('20140402', 4), ('20140405', 6), ('20140407', 2), ('20140408', 15), ('20140409', 4), ('20140421', 24), ('20140422', 1), ('20140423', 2), ('20140424', 13), ('20140429', 4), ('20140430', 17), ('20140505', 6), ('20140506', 4), ('20140507', 1), ('20140508', 2), ('20140509', 1), ('20140510', 10), ('20140512', 39), ('20140513', 6), ('20140514', 3), ('20140516', 2), ('20140519', 4), ('20140520', 5), ('20140521', 35), ('20140522', 15), ('20140525', 2), ('20140526', 1), ('20140529', 2), ('20140530', 10), ('20140601', 1), ('20140602', 5), ('20140603', 9), ('20140604', 7), ('20140605', 1), ('20140606', 1), ('20140609', 11), ('20140611', 1), ('20140612', 16), ('20140613', 8), ('20140616', 5), ('20140617', 9), ('20140618', 1), ('20140623', 2), ('20140625', 6), ('20140626', 6), ('20140629', 2), ('20140630', 22), ('20140701', 5), ('20140702', 21), ('20140703', 13), ('20140704', 4), ('20140708', 13), ('20140709', 8), ('20140710', 2), ('20140711', 16), ('20140713', 1), ('20140714', 11), ('20140715', 13), ('20140716', 14), ('20140717', 10), ('20140718', 6), ('20140721', 9), ('20140722', 10), ('20140723', 4), ('20140724', 6), ('20140725', 38), ('20140728', 9), ('20140730', 9), ('20140731', 9), ('20140804', 30), ('20140805', 35), ('20140806', 15), ('20140807', 26), ('20140808', 20), ('20140811', 29), ('20140813', 5), ('20140814', 33), ('20140815', 48), ('20140817', 2), ('20140821', 4), ('20140826', 9), ('20140828', 1), ('20140901', 3), ('20140902', 1), ('20140903', 88), ('20140904', 152), ('20140906', 10), ('20140909', 2); -- -------------------------------------------------------- -- -- Table structure for table `specimen_test` -- CREATE TABLE IF NOT EXISTS `specimen_test` ( `test_type_id` int(11) unsigned NOT NULL DEFAULT '0', `specimen_type_id` int(11) unsigned NOT NULL DEFAULT '0', `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, KEY `test_type_id` (`test_type_id`), KEY `specimen_type_id` (`specimen_type_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='Relates tests to the specimens that are compatible with thos'; -- -- Dumping data for table `specimen_test` -- INSERT INTO `specimen_test` (`test_type_id`, `specimen_type_id`, `ts`) VALUES (113, 16, '2014-07-30 08:44:43'), (114, 16, '2014-07-30 08:53:10'), (115, 16, '2014-07-30 08:58:28'), (116, 16, '2014-07-30 10:33:25'), (117, 16, '2014-07-30 10:36:50'), (118, 16, '2014-07-30 10:39:43'), (119, 16, '2014-07-30 10:41:11'), (120, 16, '2014-07-30 10:43:06'), (121, 16, '2014-07-30 10:48:49'), (122, 16, '2014-07-30 10:50:12'), (123, 16, '2014-07-30 10:52:40'), (124, 16, '2014-07-30 10:53:42'), (125, 16, '2014-07-30 10:54:19'), (126, 16, '2014-07-30 10:58:05'), (127, 17, '2014-07-30 11:33:01'), (128, 17, '2014-07-30 11:38:14'), (129, 17, '2014-07-30 11:41:41'), (130, 17, '2014-07-30 11:46:40'), (131, 17, '2014-07-30 11:54:43'), (132, 17, '2014-07-30 11:56:07'), (133, 17, '2014-07-30 11:58:04'), (134, 17, '2014-07-30 12:00:51'), (135, 17, '2014-07-30 12:22:12'), (136, 17, '2014-07-30 12:23:11'), (137, 17, '2014-07-30 12:33:04'), (138, 17, '2014-07-30 12:34:21'), (139, 17, '2014-07-30 12:39:38'), (140, 17, '2014-07-30 12:40:44'), (141, 17, '2014-07-30 12:41:43'), (142, 17, '2014-07-30 12:44:51'), (143, 17, '2014-07-30 12:49:48'), (144, 17, '2014-07-30 12:52:55'), (145, 17, '2014-07-30 13:00:29'), (146, 17, '2014-07-30 13:19:36'), (147, 17, '2014-07-30 13:24:47'), (148, 17, '2014-07-30 13:29:10'), (149, 17, '2014-07-30 13:32:10'), (150, 17, '2014-07-30 13:35:46'), (151, 16, '2014-07-30 13:38:30'), (152, 17, '2014-07-30 13:41:56'), (153, 17, '2014-07-30 13:47:54'), (154, 17, '2014-07-30 13:51:06'), (155, 17, '2014-07-31 04:31:44'), (156, 17, '2014-07-31 04:45:10'), (157, 17, '2014-07-31 04:48:04'), (158, 17, '2014-07-31 04:51:22'), (159, 17, '2014-07-31 04:54:23'), (160, 17, '2014-07-31 05:05:43'), (161, 17, '2014-07-31 05:07:06'), (162, 17, '2014-07-31 05:11:15'), (163, 17, '2014-07-31 05:23:29'), (164, 19, '2014-07-31 05:30:53'), (165, 19, '2014-07-31 05:31:37'), (166, 19, '2014-07-31 05:32:15'), (167, 19, '2014-07-31 05:32:46'), (168, 19, '2014-07-31 05:33:26'), (169, 19, '2014-07-31 05:34:02'), (171, 21, '2014-07-31 05:45:01'), (172, 21, '2014-07-31 05:49:44'), (173, 21, '2014-07-31 05:50:37'), (174, 21, '2014-07-31 05:53:06'), (175, 21, '2014-07-31 05:56:41'), (176, 21, '2014-07-31 05:58:07'), (177, 22, '2014-07-31 06:03:39'), (178, 22, '2014-07-31 06:04:56'), (179, 23, '2014-07-31 06:08:02'), (180, 22, '2014-07-31 06:10:13'), (181, 22, '2014-07-31 06:11:22'), (182, 22, '2014-07-31 06:12:33'), (183, 22, '2014-07-31 06:13:30'), (184, 22, '2014-07-31 06:14:29'), (185, 22, '2014-07-31 06:15:19'), (186, 22, '2014-07-31 06:16:13'), (187, 22, '2014-07-31 06:17:10'), (188, 22, '2014-07-31 06:17:58'), (189, 22, '2014-07-31 06:19:52'), (190, 22, '2014-07-31 06:20:42'), (191, 24, '2014-07-31 06:22:38'), (192, 24, '2014-07-31 06:23:44'), (170, 19, '2014-07-31 07:05:52'), (193, 21, '2014-07-31 07:09:05'), (194, 21, '2014-07-31 08:44:07'), (195, 25, '2014-07-31 08:49:39'), (196, 25, '2014-07-31 08:50:35'), (197, 25, '2014-07-31 08:51:06'), (198, 25, '2014-07-31 08:51:40'), (199, 25, '2014-07-31 08:52:09'), (200, 25, '2014-07-31 08:52:43'), (201, 17, '2014-07-31 08:54:03'), (202, 17, '2014-07-31 08:56:09'), (203, 17, '2014-07-31 08:57:10'), (204, 17, '2014-07-31 08:57:36'), (205, 17, '2014-07-31 08:58:05'), (206, 17, '2014-07-31 08:59:39'), (207, 17, '2014-07-31 09:00:29'), (208, 17, '2014-07-31 09:04:11'), (209, 17, '2014-07-31 09:05:49'), (210, 17, '2014-07-31 09:07:32'), (211, 17, '2014-07-31 09:08:08'), (212, 17, '2014-07-31 09:08:44'), (213, 17, '2014-07-31 09:12:09'); -- -------------------------------------------------------- -- -- Table structure for table `specimen_type` -- CREATE TABLE IF NOT EXISTS `specimen_type` ( `specimen_type_id` int(11) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(45) NOT NULL DEFAULT '', `description` varchar(100) DEFAULT NULL, `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `disabled` int(10) unsigned NOT NULL DEFAULT '0', PRIMARY KEY (`specimen_type_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=26 ; -- -- Dumping data for table `specimen_type` -- INSERT INTO `specimen_type` (`specimen_type_id`, `name`, `description`, `ts`, `disabled`) VALUES (1, 'Blood', '', '2014-07-30 05:47:03', 1), (2, 'Plasma', '', '2014-04-22 07:33:53', 1), (3, 'Urinal', '', '2014-04-07 08:42:00', 1), (4, 'Sputum', '', '2014-07-30 05:47:10', 1), (5, 'willy nilly', '', '2014-04-22 07:30:51', 1), (6, 'Urine', '', '2014-07-30 05:47:13', 1), (7, 'Stool', '', '2014-07-30 05:47:12', 1), (8, 'Skin', '', '2014-07-30 05:46:04', 1), (9, 'Bone Marrow', '', '2014-07-30 05:47:07', 1), (10, 'Genital Smear', '', '2014-07-30 05:45:12', 1), (11, 'Blood Smears', '', '2014-07-30 05:45:09', 1), (12, 'feacal matter', '', '2014-07-16 11:56:56', 1), (13, 'Test Specimen Type', 'Testing Add New Specimen Type', '2014-05-29 14:26:03', 1), (14, 'Test Specimen Type', 'Testing Add New Specimen Function', '2014-05-29 19:34:10', 1), (15, 'Stool II', '', '2014-07-25 22:17:56', 1), (16, 'Urine', '', '2014-07-30 08:42:55', 0), (17, 'Blood', '', '2014-07-30 11:28:20', 0), (18, 'Bone Marrow', '', '2014-07-31 05:21:24', 1), (19, 'Swab', '', '2014-07-31 07:05:52', 0), (20, 'Throat Swab', '', '2014-07-31 07:06:56', 1), (21, 'Smear', '', '2014-07-31 07:03:19', 0), (22, 'Stool', '', '2014-07-31 06:01:02', 0), (23, '<NAME>', '', '2014-07-31 06:07:27', 0), (24, 'Skin', '', '2014-07-31 06:22:03', 0), (25, 'Tissue', '', '2014-07-31 08:47:12', 0); -- -------------------------------------------------------- -- -- Table structure for table `stock_content` -- CREATE TABLE IF NOT EXISTS `stock_content` ( `name` varchar(40) DEFAULT NULL, `current_quantity` int(11) DEFAULT NULL, `date_of_use` date NOT NULL, `receiver` varchar(40) DEFAULT NULL, `remarks` text, `lot_number` varchar(40) DEFAULT NULL, `new_balance` int(11) DEFAULT NULL, `user_name` varchar(40) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `stock_details` -- CREATE TABLE IF NOT EXISTS `stock_details` ( `name` varchar(40) DEFAULT NULL, `lot_number` varchar(40) DEFAULT NULL, `expiry_date` varchar(40) DEFAULT NULL, `manufacturer` varchar(40) DEFAULT NULL, `quantity_ordered` int(11) DEFAULT NULL, `supplier` varchar(40) DEFAULT NULL, `date_of_reception` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `current_quantity` int(11) DEFAULT NULL, `date_of_supply` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `quantity_supplied` int(11) DEFAULT NULL, `unit` varchar(10) DEFAULT NULL, `entry_id` int(11) DEFAULT NULL, `cost_per_unit` decimal(10,0) DEFAULT '0', `quantity_used` int(10) DEFAULT '0', UNIQUE KEY `entry_id` (`entry_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `test` -- CREATE TABLE IF NOT EXISTS `test` ( `test_id` int(10) unsigned NOT NULL AUTO_INCREMENT, `test_type_id` int(11) unsigned NOT NULL DEFAULT '0', `result` varchar(201) DEFAULT NULL, `ts_started` datetime DEFAULT NULL, `comments` varchar(200) DEFAULT NULL, `user_id` int(11) unsigned DEFAULT NULL, `verified_by` int(11) unsigned DEFAULT NULL, `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `specimen_id` int(11) unsigned DEFAULT NULL, `date_verified` datetime DEFAULT NULL, `status_code_id` int(10) unsigned DEFAULT '0', `external_lab_no` varchar(100) DEFAULT NULL, `external_parent_lab_no` varchar(100) DEFAULT '0', `ts_result_entered` datetime DEFAULT NULL, PRIMARY KEY (`test_id`), KEY `test_type_id` (`test_type_id`), KEY `user_id` (`user_id`), KEY `specimen_id` (`specimen_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=110 ; -- -------------------------------------------------------- -- -- Table structure for table `test_category` -- CREATE TABLE IF NOT EXISTS `test_category` ( `test_category_id` int(11) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(45) NOT NULL DEFAULT '', `description` varchar(100) DEFAULT NULL, `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`test_category_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=32 ; -- -- Dumping data for table `test_category` -- INSERT INTO `test_category` (`test_category_id`, `name`, `description`, `ts`) VALUES (24, 'Urinalysis', '', '2014-07-30 08:08:17'), (25, 'Chemistry', '', '2014-07-30 08:13:29'), (26, 'Parasitology', '', '2014-07-30 08:25:06'), (27, 'Bacteriology', '', '2014-07-30 08:32:35'), (28, 'Hematology', '', '2014-07-30 08:33:27'), (29, 'Histology', '', '2014-07-30 08:37:15'), (30, 'Serology', '', '2014-07-30 08:37:36'), (31, 'Cytology', '', '2014-07-31 07:11:07'); -- -------------------------------------------------------- -- -- Table structure for table `test_category_mapping` -- CREATE TABLE IF NOT EXISTS `test_category_mapping` ( `user_id` int(11) NOT NULL DEFAULT '0', `test_category_name` varchar(256) COLLATE latin1_general_ci DEFAULT NULL, `lab_id_test_category_id` varchar(256) COLLATE latin1_general_ci DEFAULT NULL, `test_category_id` int(10) NOT NULL DEFAULT '0', PRIMARY KEY (`user_id`,`test_category_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci; -- -------------------------------------------------------- -- -- Table structure for table `test_mapping` -- CREATE TABLE IF NOT EXISTS `test_mapping` ( `user_id` int(11) NOT NULL DEFAULT '0', `test_name` varchar(256) COLLATE latin1_general_ci DEFAULT NULL, `lab_id_test_id` varchar(256) COLLATE latin1_general_ci DEFAULT NULL, `test_id` int(10) unsigned NOT NULL DEFAULT '0', `test_category_id` int(10) unsigned DEFAULT NULL, PRIMARY KEY (`user_id`,`test_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci; -- -- Dumping data for table `test_mapping` -- INSERT INTO `test_mapping` (`user_id`, `test_name`, `lab_id_test_id`, `test_id`, `test_category_id`) VALUES (125, 'Widal', '126:96;127:93', 1, NULL), (123, 'Widal', '126:96;127:93', 4, NULL), (502, 'Widal', '126:96;127:93', 1, NULL), (503, 'Widal', '126:96;127:93', 1, NULL), (501, 'Widal', '126:96;127:93', 1, NULL), (504, 'Widal', '126:96;127:93', 1, NULL); -- -------------------------------------------------------- -- -- Table structure for table `test_type` -- CREATE TABLE IF NOT EXISTS `test_type` ( `test_type_id` int(11) unsigned NOT NULL AUTO_INCREMENT, `parent_test_type_id` int(10) DEFAULT '0', `name` varchar(45) NOT NULL DEFAULT '', `description` varchar(100) DEFAULT NULL, `test_category_id` int(11) unsigned NOT NULL DEFAULT '0', `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `is_panel` int(10) unsigned DEFAULT NULL, `disabled` int(10) unsigned NOT NULL DEFAULT '0', `clinical_data` longtext, `hide_patient_name` int(1) DEFAULT NULL, `prevalence_threshold` int(3) DEFAULT '70', `target_tat` int(3) unsigned DEFAULT NULL, PRIMARY KEY (`test_type_id`), KEY `test_category_id` (`test_category_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=214 ; -- -- Dumping data for table `test_type` -- INSERT INTO `test_type` (`test_type_id`, `parent_test_type_id`, `name`, `description`, `test_category_id`, `ts`, `is_panel`, `disabled`, `clinical_data`, `hide_patient_name`, `prevalence_threshold`, `target_tat`) VALUES (113, 0, 'Glucose', '', 24, '2014-07-30 10:03:24', 1, 0, '!#!-%%%###', 0, 70, 24), (114, 0, 'Ketones', '', 24, '2014-07-30 08:53:10', 1, 0, NULL, 0, 70, 24), (115, 0, 'Proteins', '', 24, '2014-07-30 08:58:28', 1, 0, NULL, 0, 70, 24), (116, 0, 'Bilirubin', '', 24, '2014-07-30 10:33:25', 1, 0, NULL, 0, 70, 24), (117, 0, 'Blood', '', 24, '2014-07-30 10:36:50', 1, 0, NULL, 0, 70, 24), (118, 0, 'Urobilinogen', '', 24, '2014-07-30 10:39:43', 1, 0, NULL, 0, 70, 24), (119, 0, 'HGC', '', 24, '2014-07-30 12:26:07', 1, 0, '%%%###', 0, 70, 24), (120, 0, 'Pus Cells', '', 24, '2014-07-30 10:43:06', 1, 0, NULL, 0, 70, 24), (121, 0, '<NAME>', '', 24, '2014-07-30 10:48:49', 1, 0, NULL, 0, 70, 24), (122, 0, '<NAME>', '', 24, '2014-07-30 10:50:12', 1, 0, NULL, 0, 70, 24), (123, 0, 'Yeast Cells', '', 24, '2014-07-30 10:52:40', 1, 0, NULL, 0, 70, 24), (124, 0, 'Red Blood Cells', '', 24, '2014-07-30 10:53:42', 1, 0, NULL, 0, 70, 24), (125, 0, 'Bacteria', '', 24, '2014-07-30 10:54:19', 1, 0, NULL, 0, 70, 24), (126, 0, 'Spermatozoa', '', 24, '2014-07-30 10:58:05', 1, 0, NULL, 0, 70, 24), (127, 0, 'Fasting Blood Sugar', '', 28, '2014-07-30 11:33:01', 1, 0, NULL, 0, 70, 24), (128, 0, 'Random Blood Sugar', '', 28, '2014-07-30 11:42:15', 1, 0, '%%%###', 0, 70, 24), (129, 0, 'OGTT', '', 28, '2014-07-30 11:41:41', 1, 0, NULL, 0, 70, 24), (130, 0, 'Creatinine', '', 28, '2014-07-30 12:28:24', 1, 0, '!#!-%%%###', 0, 70, 24), (131, 0, 'Urea', '', 28, '2014-07-30 11:54:43', 1, 0, NULL, 0, 70, 24), (132, 0, 'Sodium', '', 28, '2014-07-30 11:56:07', 1, 0, NULL, 0, 70, 24), (133, 0, 'Potassium', '', 28, '2014-07-30 11:58:04', 1, 0, NULL, 0, 70, 24), (134, 0, 'Chloride', '', 28, '2014-07-30 12:00:51', 1, 0, NULL, 0, 70, 24), (135, 0, 'ASAT(SGOT)', '', 28, '2014-07-30 12:22:12', 1, 0, NULL, 0, 70, 24), (136, 0, 'ALAT(SGPT)', '', 28, '2014-07-30 12:45:25', 1, 0, '%%%###', 0, 70, 24), (137, 0, 'Albumin', '', 28, '2014-07-30 12:33:04', 1, 0, NULL, 0, 70, 24), (138, 0, 'Alpha-1 globulin', '', 28, '2014-07-30 12:34:21', 1, 0, NULL, 0, 70, 24), (139, 0, 'Alpha-2 globulin', '', 28, '2014-07-30 12:39:38', 1, 0, NULL, 0, 70, 24), (140, 0, 'Beta globulin', '', 28, '2014-07-30 12:40:44', 1, 0, NULL, 0, 70, 24), (141, 0, 'Gamma globulin ', '', 28, '2014-07-30 12:41:43', 1, 0, NULL, 0, 70, 24), (142, 0, 'Amylase', '', 28, '2014-07-30 12:44:51', 1, 0, NULL, 0, 70, 24), (143, 0, 'Cholesterol', '', 28, '2014-07-30 12:49:48', 1, 0, NULL, 0, 70, 24), (144, 0, 'Triglyceride', '', 28, '2014-07-30 12:52:55', 1, 0, NULL, 0, 70, 24), (145, 0, 'HDL', '', 28, '2014-07-30 13:00:29', 1, 0, NULL, 0, 70, 24), (146, 0, 'LDL', '', 28, '2014-07-30 13:19:36', 1, 0, NULL, 0, 70, 24), (147, 0, 'PSA', '', 28, '2014-07-30 13:24:47', 1, 0, NULL, 0, 70, 24), (148, 0, 'CSF Protein', '', 28, '2014-07-30 13:29:10', 1, 0, NULL, 0, 70, 24), (149, 0, 'CSF Glucose', '', 28, '2014-07-30 13:32:10', 1, 0, NULL, 0, 70, 24), (150, 0, 'Acid phosphatase', '', 28, '2014-08-21 05:52:16', 1, 0, '!#!-%%%###', 0, 70, 24), (151, 0, 'Bence-Jones protein', '', 24, '2014-07-30 13:38:30', 1, 0, NULL, 0, 70, 24), (152, 0, 'Triiodothyronine (T3)', '', 28, '2014-07-30 13:41:56', 1, 0, NULL, 0, 70, 24), (153, 0, 'Thyroxine (T4)', '', 28, '2014-07-30 13:47:54', 1, 0, NULL, 0, 70, 24), (154, 0, 'Thyroid-stimulating Hormone', '', 28, '2014-07-30 13:51:06', 1, 0, NULL, 0, 70, 24), (155, 0, 'WBC Counts', '', 28, '2014-07-31 04:31:44', 1, 0, NULL, 0, 70, 24), (156, 0, 'Erythrocyte Sedimentation Rate ', '', 28, '2014-07-31 04:45:10', 1, 0, NULL, 0, 70, 24), (157, 0, 'Sickling Test', '', 28, '2014-07-31 04:48:04', 1, 0, NULL, 0, 70, 24), (158, 0, 'Hb Electrophoresis', '', 28, '2014-07-31 04:51:22', 1, 0, NULL, 0, 70, 24), (159, 0, 'G6PD', '', 28, '2014-07-31 04:54:23', 1, 0, NULL, 0, 70, 24), (160, 0, 'Bleeding Time', '', 28, '2014-07-31 05:05:43', 1, 0, NULL, 0, 70, 24), (161, 0, 'Clotting time', '', 28, '2014-07-31 05:07:06', 1, 0, NULL, 0, 70, 24), (162, 0, 'Partial thromboplastin time', '', 28, '2014-07-31 05:11:15', 1, 0, NULL, 0, 70, 24), (163, 0, 'Reticulocyte count', '', 28, '2014-07-31 05:23:29', 1, 0, NULL, 0, 70, 24), (164, 0, 'Trichomonas vaginalis', '', 27, '2014-07-31 05:30:53', 1, 0, NULL, 0, 70, 24), (165, 0, 'Epithelial cells ', '', 27, '2014-07-31 05:31:37', 1, 0, NULL, 0, 70, 24), (166, 0, 'WBCs', '', 27, '2014-07-31 05:32:15', 1, 0, NULL, 0, 70, 24), (167, 0, 'RBCs ', '', 27, '2014-07-31 05:32:46', 1, 0, NULL, 0, 70, 24), (168, 0, 'Yeasts', '', 27, '2014-07-31 05:33:26', 1, 0, NULL, 0, 70, 24), (169, 0, 'HVS Culture', '', 27, '2014-07-31 05:34:02', 1, 0, NULL, 0, 70, 24), (170, 0, 'Throat Swab Culture', '', 27, '2014-07-31 05:36:27', 1, 0, NULL, 0, 70, 24), (171, 0, 'Falciparum', '', 26, '2014-07-31 05:45:01', 1, 0, NULL, 0, 70, 24), (172, 0, 'Ovale', '', 26, '2014-07-31 05:49:44', 1, 0, NULL, 0, 70, 24), (173, 0, 'Malariae', '', 26, '2014-07-31 05:50:37', 1, 0, NULL, 0, 70, 24), (174, 0, 'Vivax', '', 26, '2014-07-31 05:53:06', 1, 0, NULL, 0, 70, 24), (175, 0, 'Borrelia', '', 26, '2014-07-31 05:56:41', 1, 0, NULL, 0, 70, 24), (176, 0, 'Microfilariae', '', 26, '2014-07-31 05:58:07', 1, 0, NULL, 0, 70, 24), (177, 0, 'Taenia', '', 26, '2014-07-31 06:03:39', 1, 0, NULL, 0, 70, 24), (178, 0, '<NAME>', '', 26, '2014-07-31 06:04:56', 1, 0, NULL, 0, 70, 24), (179, 0, '<NAME> ', '', 26, '2014-08-06 12:29:31', 1, 0, '!#!-%%%###', 0, 70, 24), (180, 0, '<NAME>', '', 26, '2014-07-31 06:10:13', 1, 0, NULL, 0, 70, 24), (181, 0, 'Hookworm', '', 26, '2014-07-31 06:11:22', 1, 0, NULL, 0, 70, 24), (182, 0, 'Roundworms', '', 26, '2014-07-31 06:12:33', 1, 0, NULL, 0, 70, 24), (183, 0, '<NAME>', '', 26, '2014-07-31 06:13:30', 1, 0, NULL, 0, 70, 24), (184, 0, '<NAME>', '', 26, '2014-07-31 06:14:29', 1, 0, NULL, 0, 70, 24), (185, 0, '<NAME>', '', 26, '2014-07-31 06:15:19', 1, 0, NULL, 0, 70, 24), (186, 0, '<NAME>', '', 26, '2014-07-31 06:16:12', 1, 0, NULL, 0, 70, 24), (187, 0, '<NAME>', '', 26, '2014-07-31 06:17:10', 1, 0, NULL, 0, 70, 24), (188, 0, '<NAME>', '', 26, '2014-07-31 06:17:58', 1, 0, NULL, 0, 70, 24), (189, 0, 'Cryptosporidium', '', 26, '2014-07-31 06:19:52', 1, 0, NULL, 0, 70, 24), (190, 0, 'Cyclospora', '', 26, '2014-07-31 06:20:42', 1, 0, NULL, 0, 70, 24), (191, 0, '<NAME>', '', 26, '2014-07-31 06:22:38', 1, 0, NULL, 0, 70, 24), (192, 0, 'Leishmania', '', 26, '2014-07-31 06:23:44', 1, 0, NULL, 0, 70, 24), (193, 0, '<NAME>', '', 29, '2014-07-31 07:09:05', 1, 0, NULL, 0, 70, 24), (194, 0, 'Tissue Impression', '', 31, '2014-07-31 08:44:07', 1, 0, NULL, 0, 70, 24), (195, 0, 'Cervix', '', 29, '2014-07-31 08:49:39', 1, 0, NULL, 0, 70, 24), (196, 0, 'Prostrate', '', 29, '2014-07-31 08:50:35', 1, 0, NULL, 0, 70, 24), (197, 0, 'Breast', '', 29, '2014-07-31 08:51:06', 1, 0, NULL, 0, 70, 24), (198, 0, '<NAME>', '', 29, '2014-07-31 08:51:40', 1, 0, NULL, 0, 70, 24), (199, 0, 'Fibroids', '', 29, '2014-07-31 08:52:09', 1, 0, NULL, 0, 70, 24), (200, 0, 'Lymph Nodes', '', 29, '2014-07-31 08:52:43', 1, 0, NULL, 0, 70, 24), (201, 0, 'Rapid Plasma', '', 30, '2014-07-31 08:54:03', 1, 0, NULL, 0, 70, 24), (202, 0, 'TPHA', '', 30, '2014-07-31 08:56:09', 1, 0, NULL, 0, 70, 24), (203, 0, 'ASO', '', 30, '2014-07-31 08:57:10', 1, 0, NULL, 0, 70, 24), (204, 0, 'HIV', '', 30, '2014-07-31 08:57:36', 1, 0, NULL, 0, 70, 24), (205, 0, 'Widal', '', 30, '2014-07-31 08:58:05', 1, 0, NULL, 0, 70, 24), (206, 0, 'Brucella', '', 30, '2014-07-31 08:59:39', 1, 0, NULL, 0, 70, 24), (207, 0, 'Rheumatoid Factor', '', 30, '2014-07-31 09:00:29', 1, 0, NULL, 0, 70, 24), (208, 0, 'Cryptococcal Antigen', '', 30, '2014-07-31 09:04:11', 1, 0, NULL, 0, 70, 24), (209, 0, '<NAME>', '', 30, '2014-07-31 09:05:49', 1, 0, NULL, 0, 70, 24), (210, 0, 'Hepatitis A', '', 30, '2014-07-31 09:07:32', 1, 0, NULL, 0, 70, 24), (211, 0, 'Hepatitis B', '', 30, '2014-07-31 09:08:08', 1, 0, NULL, 0, 70, 24), (212, 0, 'Hepatitis C', '', 30, '2014-07-31 09:08:44', 1, 0, NULL, 0, 70, 24), (213, 0, 'HIV Viral Load', '', 30, '2014-07-31 09:12:09', 1, 0, NULL, 0, 70, 24); -- -------------------------------------------------------- -- -- Table structure for table `test_type_costs` -- CREATE TABLE IF NOT EXISTS `test_type_costs` ( `earliest_date_valid` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `test_type_id` int(11) NOT NULL, `amount` decimal(10,2) NOT NULL DEFAULT '0.00' ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci; -- -- Dumping data for table `test_type_costs` -- INSERT INTO `test_type_costs` (`earliest_date_valid`, `test_type_id`, `amount`) VALUES ('2014-02-28 19:13:01', 2, 0.00), ('2014-02-28 19:14:18', 3, 0.00), ('2014-03-07 14:09:37', 4, 0.00), ('2014-03-17 22:16:51', 5, 0.00), ('2014-04-22 13:09:46', 6, 0.00), ('2014-04-22 13:51:33', 7, 0.00), ('2014-04-23 05:10:25', 8, 0.00), ('2014-04-23 05:14:00', 9, 0.00), ('2014-04-24 14:34:33', 10, 0.00), ('2014-04-24 21:54:42', 11, 0.00), ('2014-04-25 11:24:07', 12, 0.00), ('2014-04-25 11:35:04', 13, 0.00), ('2014-04-28 07:24:11', 14, 0.00), ('2014-04-28 07:25:53', 15, 0.00), ('2014-04-28 07:34:23', 16, 0.00), ('2014-04-29 07:22:39', 17, 0.00), ('2014-04-29 07:23:24', 18, 0.00), ('2014-07-16 12:00:08', 19, 50.00), ('2014-04-29 07:26:06', 20, 0.00), ('2014-04-29 07:26:59', 21, 0.00), ('2014-04-29 07:28:02', 22, 0.00), ('2014-04-29 07:44:35', 23, 0.00), ('2014-04-29 07:47:45', 24, 0.00), ('2014-04-29 07:49:43', 25, 0.00), ('2014-04-29 07:50:48', 26, 0.00), ('2014-04-29 07:51:25', 27, 0.00), ('2014-04-29 07:51:54', 28, 0.00), ('2014-04-29 07:52:29', 29, 0.00), ('2014-04-29 07:53:09', 30, 0.00), ('2014-04-29 09:07:27', 31, 0.00), ('2014-04-29 09:10:03', 32, 0.00), ('2014-04-29 09:10:56', 33, 0.00), ('2014-04-29 09:12:11', 34, 0.00), ('2014-04-29 09:13:17', 35, 0.00), ('2014-04-29 09:14:21', 36, 0.00), ('2014-04-29 09:15:09', 37, 0.00), ('2014-04-29 09:15:53', 38, 0.00), ('2014-04-29 10:51:04', 39, 0.00), ('2014-04-29 10:52:36', 40, 0.00), ('2014-04-29 10:53:27', 41, 0.00), ('2014-04-29 10:54:03', 42, 0.00), ('2014-04-29 10:54:26', 43, 0.00), ('2014-04-29 10:55:05', 44, 0.00), ('2014-04-29 11:11:45', 45, 0.00), ('2014-04-29 11:12:27', 46, 0.00), ('2014-04-29 11:13:27', 47, 0.00), ('2014-04-29 11:14:04', 48, 0.00), ('2014-04-29 11:15:06', 49, 0.00), ('2014-04-29 12:57:43', 50, 0.00), ('2014-04-29 13:00:06', 51, 0.00), ('2014-04-29 13:01:04', 52, 0.00), ('2014-04-29 13:01:54', 53, 0.00), ('2014-04-29 13:02:40', 54, 0.00), ('2014-04-29 13:03:50', 55, 0.00), ('2014-04-29 13:04:37', 56, 0.00), ('2014-05-06 08:13:13', 57, 50.00), ('2014-05-06 08:18:02', 58, 0.00), ('2014-05-06 08:18:44', 59, 0.00), ('2014-05-06 08:19:24', 60, 0.00), ('2014-05-06 08:20:01', 61, 0.00), ('2014-05-06 08:21:05', 62, 0.00), ('2014-05-06 08:21:55', 63, 0.00), ('2014-05-06 08:24:44', 64, 0.00), ('2014-05-06 08:26:29', 65, 0.00), ('2014-05-06 08:29:56', 66, 0.00), ('2014-05-06 08:30:44', 67, 0.00), ('2014-05-06 08:31:45', 68, 0.00), ('2014-05-06 08:32:55', 69, 0.00), ('2014-05-06 08:35:37', 70, 0.00), ('2014-05-06 08:37:13', 71, 0.00), ('2014-05-06 08:44:24', 72, 0.00), ('2014-05-06 08:58:00', 76, 0.00), ('2014-05-06 08:58:38', 77, 0.00), ('2014-05-06 09:04:40', 79, 0.00), ('2014-05-06 09:05:25', 80, 0.00), ('2014-05-06 09:06:13', 81, 0.00), ('2014-05-06 09:06:46', 82, 0.00), ('2014-05-06 09:07:17', 83, 0.00), ('2014-05-12 06:01:42', 78, 0.00), ('2014-05-13 08:13:16', 19, 50.00), ('2014-05-29 14:36:05', 84, 50.00), ('2014-06-17 07:51:02', 85, 0.00), ('2014-06-17 16:07:43', 86, 0.00), ('2014-06-18 09:51:01', 74, 0.00), ('2014-06-18 09:54:07', 73, 0.00), ('2014-06-18 12:06:00', 87, 0.00), ('2014-06-18 12:09:09', 88, 0.00), ('2014-06-18 12:10:43', 89, 0.00), ('2014-06-18 12:12:09', 90, 0.00), ('2014-06-18 12:15:00', 91, 0.00), ('2014-06-18 12:16:30', 92, 0.00), ('2014-06-18 12:19:10', 93, 0.00), ('2014-06-18 12:21:26', 94, 0.00), ('2014-06-18 12:23:20', 95, 0.00), ('2014-06-18 12:26:02', 96, 0.00), ('2014-06-18 12:29:11', 97, 0.00), ('2014-06-18 12:31:35', 98, 0.00), ('2014-06-18 12:33:41', 99, 0.00), ('2014-06-18 12:45:52', 100, 0.00), ('2014-06-18 12:53:44', 101, 0.00), ('2014-06-18 12:55:41', 102, 0.00), ('2014-06-18 12:58:27', 103, 0.00), ('2014-06-18 13:01:47', 104, 0.00), ('2014-06-18 13:05:00', 105, 0.00), ('2014-06-18 13:06:37', 106, 0.00), ('2014-06-18 13:10:44', 107, 0.00), ('2014-06-18 13:12:37', 108, 0.00), ('2014-06-18 13:14:53', 109, 0.00), ('2014-06-18 13:16:37', 110, 0.00), ('2014-07-15 11:32:13', 111, 0.00), ('2014-07-15 11:38:09', 112, 50.00), ('2014-07-16 11:56:26', 19, 50.00), ('2014-07-24 09:36:40', 3, 50.00), ('2014-07-30 08:44:43', 113, 0.00), ('2014-07-30 08:53:10', 114, 0.00), ('2014-07-30 08:58:28', 115, 0.00), ('2014-07-30 10:33:26', 116, 0.00), ('2014-07-30 10:36:51', 117, 0.00), ('2014-07-30 10:39:44', 118, 0.00), ('2014-07-30 10:41:12', 119, 0.00), ('2014-07-30 10:43:06', 120, 0.00), ('2014-07-30 10:48:49', 121, 0.00), ('2014-07-30 10:50:12', 122, 0.00), ('2014-07-30 10:52:41', 123, 0.00), ('2014-07-30 10:53:43', 124, 0.00), ('2014-07-30 10:54:20', 125, 0.00), ('2014-07-30 10:58:06', 126, 0.00), ('2014-07-30 11:33:01', 127, 0.00), ('2014-07-30 11:38:14', 128, 0.00), ('2014-07-30 11:41:41', 129, 0.00), ('2014-07-30 11:46:41', 130, 0.00), ('2014-07-30 11:54:44', 131, 0.00), ('2014-07-30 11:56:08', 132, 0.00), ('2014-07-30 11:58:05', 133, 0.00), ('2014-07-30 12:00:52', 134, 0.00), ('2014-07-30 12:22:13', 135, 0.00), ('2014-07-30 12:23:11', 136, 0.00), ('2014-07-30 12:33:04', 137, 0.00), ('2014-07-30 12:34:21', 138, 0.00), ('2014-07-30 12:39:39', 139, 0.00), ('2014-07-30 12:40:44', 140, 0.00), ('2014-07-30 12:41:44', 141, 0.00), ('2014-07-30 12:44:52', 142, 0.00), ('2014-07-30 12:49:49', 143, 0.00), ('2014-07-30 12:52:55', 144, 0.00), ('2014-07-30 13:00:29', 145, 0.00), ('2014-07-30 13:19:36', 146, 0.00), ('2014-07-30 13:24:48', 147, 0.00), ('2014-07-30 13:29:10', 148, 0.00), ('2014-07-30 13:32:11', 149, 0.00), ('2014-08-21 05:55:23', 150, 50.00), ('2014-07-30 13:38:30', 151, 0.00), ('2014-07-30 13:41:56', 152, 0.00), ('2014-07-30 13:47:55', 153, 0.00), ('2014-07-30 13:51:06', 154, 0.00), ('2014-07-31 04:31:44', 155, 0.00), ('2014-07-31 04:45:10', 156, 0.00), ('2014-07-31 04:48:05', 157, 0.00), ('2014-07-31 04:51:22', 158, 0.00), ('2014-07-31 04:54:24', 159, 0.00), ('2014-07-31 05:05:43', 160, 0.00), ('2014-07-31 05:07:07', 161, 0.00), ('2014-07-31 05:11:15', 162, 0.00), ('2014-07-31 05:23:29', 163, 0.00), ('2014-07-31 05:30:53', 164, 0.00), ('2014-07-31 05:31:38', 165, 0.00), ('2014-07-31 05:32:16', 166, 0.00), ('2014-07-31 05:32:46', 167, 0.00), ('2014-07-31 05:33:27', 168, 0.00), ('2014-07-31 05:34:03', 169, 0.00), ('2014-07-31 05:36:27', 170, 0.00), ('2014-07-31 05:45:01', 171, 0.00), ('2014-07-31 05:49:44', 172, 0.00), ('2014-07-31 05:50:37', 173, 0.00), ('2014-07-31 05:53:07', 174, 0.00), ('2014-07-31 05:56:42', 175, 0.00), ('2014-07-31 05:58:08', 176, 0.00), ('2014-07-31 06:03:40', 177, 0.00), ('2014-07-31 06:04:56', 178, 0.00), ('2014-07-31 06:08:02', 179, 0.00), ('2014-07-31 06:10:14', 180, 0.00), ('2014-07-31 06:11:22', 181, 0.00), ('2014-07-31 06:12:33', 182, 0.00), ('2014-07-31 06:13:30', 183, 0.00), ('2014-07-31 06:14:29', 184, 0.00), ('2014-07-31 06:15:20', 185, 0.00), ('2014-07-31 06:16:13', 186, 0.00), ('2014-07-31 06:17:10', 187, 0.00), ('2014-07-31 06:17:59', 188, 0.00), ('2014-07-31 06:19:53', 189, 0.00), ('2014-07-31 06:20:43', 190, 0.00), ('2014-07-31 06:22:39', 191, 0.00), ('2014-07-31 06:23:44', 192, 0.00), ('2014-07-31 07:09:06', 193, 0.00), ('2014-07-31 08:44:08', 194, 0.00), ('2014-07-31 08:49:40', 195, 0.00), ('2014-07-31 08:50:36', 196, 0.00), ('2014-07-31 08:51:06', 197, 0.00), ('2014-07-31 08:51:41', 198, 0.00), ('2014-07-31 08:52:09', 199, 0.00), ('2014-07-31 08:52:43', 200, 0.00), ('2014-07-31 08:54:03', 201, 0.00), ('2014-07-31 08:56:10', 202, 0.00), ('2014-07-31 08:57:10', 203, 0.00), ('2014-07-31 08:57:37', 204, 0.00), ('2014-07-31 08:58:05', 205, 0.00), ('2014-07-31 08:59:40', 206, 0.00), ('2014-07-31 09:00:29', 207, 0.00), ('2014-07-31 09:04:11', 208, 0.00), ('2014-07-31 09:05:49', 209, 0.00), ('2014-07-31 09:07:33', 210, 0.00), ('2014-07-31 09:08:08', 211, 0.00), ('2014-07-31 09:08:45', 212, 0.00), ('2014-07-31 09:12:10', 213, 0.00), ('2014-08-21 05:55:23', 150, 50.00); -- -------------------------------------------------------- -- -- Table structure for table `test_type_measure` -- CREATE TABLE IF NOT EXISTS `test_type_measure` ( `test_type_id` int(11) unsigned NOT NULL DEFAULT '0', `measure_id` int(11) unsigned NOT NULL DEFAULT '0', `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, KEY `test_type_id` (`test_type_id`), KEY `measure_id` (`measure_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `test_type_measure` -- INSERT INTO `test_type_measure` (`test_type_id`, `measure_id`, `ts`) VALUES (113, 27, '2014-07-30 08:44:43'), (114, 30, '2014-07-30 08:53:10'), (115, 27, '2014-07-30 08:58:28'), (116, 18, '2014-07-30 10:33:25'), (117, 18, '2014-07-30 10:36:50'), (118, 31, '2014-07-30 10:39:43'), (119, 30, '2014-07-30 10:41:11'), (120, 18, '2014-07-30 10:43:06'), (121, 18, '2014-07-30 10:48:49'), (122, 30, '2014-07-30 10:50:12'), (123, 18, '2014-07-30 10:52:40'), (124, 18, '2014-07-30 10:53:42'), (125, 18, '2014-07-30 10:54:19'), (126, 18, '2014-07-30 10:58:05'), (127, 31, '2014-07-30 11:33:01'), (128, 31, '2014-07-30 11:38:14'), (129, 27, '2014-07-30 11:41:41'), (130, 32, '2014-07-30 11:46:40'), (131, 33, '2014-07-30 11:54:43'), (132, 34, '2014-07-30 11:56:07'), (133, 34, '2014-07-30 11:58:04'), (134, 34, '2014-07-30 12:00:51'), (135, 35, '2014-07-30 12:22:12'), (136, 35, '2014-07-30 12:23:11'), (137, 31, '2014-07-30 12:33:04'), (138, 31, '2014-07-30 12:34:21'), (139, 31, '2014-07-30 12:39:38'), (140, 31, '2014-07-30 12:40:44'), (141, 31, '2014-07-30 12:41:43'), (142, 24, '2014-07-30 12:44:51'), (143, 27, '2014-07-30 12:49:48'), (144, 27, '2014-07-30 12:52:55'), (145, 27, '2014-07-30 13:00:29'), (146, 27, '2014-07-30 13:19:36'), (147, 36, '2014-07-30 13:24:47'), (148, 27, '2014-07-30 13:29:10'), (149, 32, '2014-07-30 13:32:10'), (150, 35, '2014-07-30 13:35:46'), (151, 18, '2014-07-30 13:38:30'), (152, 37, '2014-07-30 13:41:56'), (153, 38, '2014-07-30 13:47:54'), (154, 39, '2014-07-30 13:51:06'), (155, 40, '2014-07-31 04:31:44'), (156, 11, '2014-07-31 04:45:10'), (157, 30, '2014-07-31 04:48:04'), (158, 41, '2014-07-31 04:51:22'), (159, 42, '2014-07-31 04:54:23'), (160, 43, '2014-07-31 05:05:43'), (161, 44, '2014-07-31 05:07:06'), (162, 44, '2014-07-31 05:11:15'), (163, 41, '2014-07-31 05:23:29'), (164, 18, '2014-07-31 05:30:53'), (165, 13, '2014-07-31 05:31:37'), (166, 18, '2014-07-31 05:32:15'), (167, 13, '2014-07-31 05:32:46'), (168, 18, '2014-07-31 05:33:26'), (169, 13, '2014-07-31 05:34:02'), (170, 30, '2014-07-31 05:36:27'), (171, 18, '2014-07-31 05:45:01'), (172, 18, '2014-07-31 05:49:44'), (173, 18, '2014-07-31 05:50:37'), (174, 18, '2014-07-31 05:53:06'), (175, 30, '2014-07-31 05:56:41'), (176, 30, '2014-07-31 05:58:07'), (177, 30, '2014-07-31 06:03:39'), (178, 30, '2014-07-31 06:04:56'), (179, 30, '2014-07-31 06:08:02'), (180, 30, '2014-07-31 06:10:13'), (181, 30, '2014-07-31 06:11:22'), (182, 30, '2014-07-31 06:12:33'), (183, 30, '2014-07-31 06:13:30'), (184, 30, '2014-07-31 06:14:29'), (185, 30, '2014-07-31 06:15:19'), (186, 30, '2014-07-31 06:16:13'), (187, 30, '2014-07-31 06:17:10'), (188, 30, '2014-07-31 06:17:58'), (189, 30, '2014-07-31 06:19:52'), (190, 30, '2014-07-31 06:20:42'), (191, 30, '2014-07-31 06:22:38'), (192, 30, '2014-07-31 06:23:44'), (193, 30, '2014-07-31 07:09:05'), (194, 30, '2014-07-31 08:44:07'), (195, 30, '2014-07-31 08:49:39'), (196, 30, '2014-07-31 08:50:35'), (197, 30, '2014-07-31 08:51:06'), (198, 30, '2014-07-31 08:51:40'), (199, 30, '2014-07-31 08:52:09'), (200, 30, '2014-07-31 08:52:43'), (201, 30, '2014-07-31 08:54:03'), (202, 30, '2014-07-31 08:56:09'), (203, 30, '2014-07-31 08:57:10'), (204, 30, '2014-07-31 08:57:36'), (205, 30, '2014-07-31 08:58:05'), (206, 30, '2014-07-31 08:59:39'), (207, 30, '2014-07-31 09:00:29'), (208, 30, '2014-07-31 09:04:11'), (209, 30, '2014-07-31 09:05:49'), (210, 30, '2014-07-31 09:07:32'), (211, 30, '2014-07-31 09:08:08'), (212, 30, '2014-07-31 09:08:44'), (213, 45, '2014-07-31 09:12:09'); -- -------------------------------------------------------- -- -- Table structure for table `unit` -- CREATE TABLE IF NOT EXISTS `unit` ( `unit_id` int(11) unsigned NOT NULL AUTO_INCREMENT, `unit` varchar(45) NOT NULL DEFAULT '', `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`unit_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `user` -- CREATE TABLE IF NOT EXISTS `user` ( `user_id` int(10) unsigned NOT NULL AUTO_INCREMENT, `username` varchar(45) NOT NULL, `password` varchar(45) NOT NULL, `actualname` varchar(45) DEFAULT NULL, `email` varchar(45) DEFAULT NULL, `created_by` int(11) unsigned DEFAULT NULL, `ts` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `lab_config_id` int(11) unsigned DEFAULT NULL, `level` int(11) unsigned DEFAULT NULL, `phone` varchar(45) DEFAULT NULL, `lang_id` varchar(45) NOT NULL, `img` varchar(200) DEFAULT NULL, `emr_user_id` varchar(45) DEFAULT NULL, `verify` int(11) NOT NULL DEFAULT '0', `active_status` int(11) DEFAULT '1', UNIQUE KEY `user_id` (`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=568 ; -- -- Dumping data for table `user` -- INSERT INTO `user` (`user_id`, `username`, `password`, `actualname`, `email`, `created_by`, `ts`, `lab_config_id`, `level`, `phone`, `lang_id`, `img`, `emr_user_id`, `verify`, `active_status`) VALUES (53, 'testlab1_admin', '<PASSWORD>', 'Testlab1 admin', '', 26, '2010-01-14 17:05:44', 0, 2, '', 'default', '', NULL, 1, 1); -- -------------------------------------------------------- -- -- Table structure for table `user_feedback` -- CREATE TABLE IF NOT EXISTS `user_feedback` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_id` int(11) DEFAULT NULL, `rating` int(3) DEFAULT NULL, `comments` varchar(500) COLLATE latin1_general_ci DEFAULT NULL, `ts` timestamp NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `user_props` -- CREATE TABLE IF NOT EXISTS `user_props` ( `User_Id` varchar(50) NOT NULL DEFAULT '', `AppCodeName` varchar(25) NOT NULL DEFAULT '', `AppName` varchar(25) NOT NULL DEFAULT '', `AppVersion` varchar(25) NOT NULL DEFAULT '', `CookieEnabled` tinyint(1) NOT NULL DEFAULT '0', `Platform` varchar(20) NOT NULL DEFAULT '', `UserAgent` varchar(200) NOT NULL DEFAULT '', `SystemLanguage` varchar(15) NOT NULL DEFAULT '', `UserLanguage` varchar(15) NOT NULL DEFAULT '', `Language` varchar(15) NOT NULL DEFAULT '', `ScreenAvailHeight` int(11) NOT NULL DEFAULT '0', `ScreenAvailWidth` int(11) NOT NULL DEFAULT '0', `ScreenColorDepth` int(11) NOT NULL DEFAULT '0', `ScreenHeight` int(11) NOT NULL DEFAULT '0', `ScreenWidth` int(11) NOT NULL DEFAULT '0', `Recorded_At` datetime NOT NULL DEFAULT '0000-00-00 00:00:00' ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `user_rating` -- CREATE TABLE IF NOT EXISTS `user_rating` ( `user_id` int(10) unsigned NOT NULL, `rating` int(10) unsigned NOT NULL, `ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`user_id`,`ts`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `version_data` -- CREATE TABLE IF NOT EXISTS `version_data` ( `id` int(11) NOT NULL AUTO_INCREMENT, `version` varchar(45) COLLATE latin1_general_ci NOT NULL, `status` int(11) DEFAULT NULL, `user_id` int(11) DEFAULT NULL, `remarks` varchar(250) COLLATE latin1_general_ci DEFAULT NULL, `i_ts` timestamp NULL DEFAULT NULL, `u_ts` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=4 ; -- -------------------------------------------------------- -- -- Table structure for table `worksheet_custom` -- CREATE TABLE IF NOT EXISTS `worksheet_custom` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(100) NOT NULL, `header` varchar(500) NOT NULL, `footer` varchar(500) NOT NULL, `title` varchar(500) NOT NULL, `p_fields` varchar(100) NOT NULL, `s_fields` varchar(100) NOT NULL, `t_fields` varchar(100) NOT NULL, `p_custom` varchar(100) NOT NULL, `s_custom` varchar(100) NOT NULL, `margins` varchar(50) NOT NULL, `id_fields` varchar(45) NOT NULL DEFAULT '0,0,0', `landscape` int(10) unsigned NOT NULL DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ; -- -------------------------------------------------------- -- -- Table structure for table `worksheet_custom_test` -- CREATE TABLE IF NOT EXISTS `worksheet_custom_test` ( `worksheet_id` int(10) unsigned NOT NULL, `test_type_id` int(10) unsigned NOT NULL, `measure_id` int(10) unsigned NOT NULL, `width` varchar(45) NOT NULL, KEY `worksheet_id` (`worksheet_id`), KEY `test_type_id` (`test_type_id`), KEY `measure_id` (`measure_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `worksheet_custom_userfield` -- CREATE TABLE IF NOT EXISTS `worksheet_custom_userfield` ( `worksheet_id` int(10) unsigned NOT NULL, `name` varchar(70) NOT NULL DEFAULT '', `width` int(10) unsigned NOT NULL DEFAULT '10', `field_id` int(10) unsigned NOT NULL AUTO_INCREMENT, KEY `Primary Key` (`field_id`), KEY `worksheet_id` (`worksheet_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -- Constraints for dumped tables -- -- -- Constraints for table `inv_supply` -- ALTER TABLE `inv_supply` ADD CONSTRAINT `reagent_id` FOREIGN KEY (`reagent_id`) REFERENCES `inv_reagent` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION; -- -- Constraints for table `inv_usage` -- ALTER TABLE `inv_usage` ADD CONSTRAINT `reagent_id2` FOREIGN KEY (`reagent_id`) REFERENCES `inv_reagent` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION; -- -- Constraints for table `patient_custom_data` -- ALTER TABLE `patient_custom_data` ADD CONSTRAINT `patient_custom_data_ibfk_1` FOREIGN KEY (`patient_id`) REFERENCES `patient` (`patient_id`) ON UPDATE CASCADE; -- -- Constraints for table `reference_range` -- ALTER TABLE `reference_range` ADD CONSTRAINT `reference_range_ibfk_1` FOREIGN KEY (`measure_id`) REFERENCES `measure` (`measure_id`) ON UPDATE CASCADE; -- -- Constraints for table `report_disease` -- ALTER TABLE `report_disease` ADD CONSTRAINT `report_disease_ibfk_1` FOREIGN KEY (`measure_id`) REFERENCES `measure` (`measure_id`) ON UPDATE CASCADE; -- -- Constraints for table `specimen` -- ALTER TABLE `specimen` ADD CONSTRAINT `specimen_ibfk_1` FOREIGN KEY (`patient_id`) REFERENCES `patient` (`patient_id`) ON UPDATE CASCADE, ADD CONSTRAINT `specimen_ibfk_2` FOREIGN KEY (`specimen_type_id`) REFERENCES `specimen_type` (`specimen_type_id`) ON UPDATE CASCADE, ADD CONSTRAINT `specimen_ibfk_3` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`) ON UPDATE CASCADE; -- -- Constraints for table `specimen_custom_data` -- ALTER TABLE `specimen_custom_data` ADD CONSTRAINT `specimen_custom_data_ibfk_1` FOREIGN KEY (`specimen_id`) REFERENCES `specimen` (`specimen_id`) ON UPDATE CASCADE; -- -- Constraints for table `specimen_test` -- ALTER TABLE `specimen_test` ADD CONSTRAINT `specimen_test_ibfk_1` FOREIGN KEY (`specimen_type_id`) REFERENCES `specimen_type` (`specimen_type_id`) ON UPDATE CASCADE, ADD CONSTRAINT `specimen_test_ibfk_2` FOREIGN KEY (`test_type_id`) REFERENCES `test_type` (`test_type_id`) ON UPDATE CASCADE; -- -- Constraints for table `test` -- ALTER TABLE `test` ADD CONSTRAINT `test_ibfk_1` FOREIGN KEY (`test_type_id`) REFERENCES `test_type` (`test_type_id`) ON UPDATE CASCADE, ADD CONSTRAINT `test_ibfk_2` FOREIGN KEY (`specimen_id`) REFERENCES `specimen` (`specimen_id`) ON UPDATE CASCADE, ADD CONSTRAINT `test_ibfk_3` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`) ON UPDATE CASCADE; -- -- Constraints for table `test_type` -- ALTER TABLE `test_type` ADD CONSTRAINT `test_type_ibfk_1` FOREIGN KEY (`test_category_id`) REFERENCES `test_category` (`test_category_id`) ON UPDATE CASCADE; -- -- Constraints for table `test_type_measure` -- ALTER TABLE `test_type_measure` ADD CONSTRAINT `test_type_measure_ibfk_1` FOREIGN KEY (`test_type_id`) REFERENCES `test_type` (`test_type_id`) ON UPDATE CASCADE, ADD CONSTRAINT `test_type_measure_ibfk_2` FOREIGN KEY (`measure_id`) REFERENCES `measure` (`measure_id`) ON UPDATE CASCADE; -- -- Constraints for table `user_rating` -- ALTER TABLE `user_rating` ADD CONSTRAINT `user_rating_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`); -- -- Constraints for table `worksheet_custom_test` -- ALTER TABLE `worksheet_custom_test` ADD CONSTRAINT `worksheet_custom_test_ibfk_1` FOREIGN KEY (`worksheet_id`) REFERENCES `worksheet` (`worksheet_id`) ON UPDATE CASCADE, ADD CONSTRAINT `worksheet_custom_test_ibfk_2` FOREIGN KEY (`test_type_id`) REFERENCES `test_type` (`test_type_id`) ON UPDATE CASCADE, ADD CONSTRAINT `worksheet_custom_test_ibfk_3` FOREIGN KEY (`measure_id`) REFERENCES `measure` (`measure_id`) ON UPDATE CASCADE; -- -- Constraints for table `worksheet_custom_userfield` -- ALTER TABLE `worksheet_custom_userfield` ADD CONSTRAINT `worksheet_custom_userfield_ibfk_1` FOREIGN KEY (`worksheet_id`) REFERENCES `worksheet` (`worksheet_id`) ON UPDATE CASCADE; /*!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>/htdocs/api/user_create_or_edit.php <?php require_once "authenticate.php"; $rcd = array(); $rcd['userId'] = $_REQUEST['userId']; $rcd['username'] = $_REQUEST['username']; $rcd['actualName'] = $_REQUEST['actualName']; $rcd['level'] = $_REQUEST['level']; $rcd['labSection'] = $_REQUEST['labSection']; $rcd['email'] = $_REQUEST['email']; $rcd['phone'] = $_REQUEST['phone']; $rcd['canverify'] = $_REQUEST['canverify']; $rcd['activeStatus'] = $_REQUEST['activeStatus']; if($_REQUEST['password']){ $rcd['password'] = $_REQUEST['password']; } $result = API::user_create_or_edit($rcd); if($result < 1) echo $result; else echo json_encode($result); ?> <file_sep>/htdocs/api/get_patient_specimen_details.php <?php require_once "authenticate.php"; $debug = false; $patient_id = $_REQUEST["npid"]; $patient = get_patient_by_npid($patient_id); $result = false; if ($patient && $patient != NULL && $patient->patientId != ""){ $result = API::get_patient_specimen_details($patient->patientId); } echo json_encode($result); ?> <file_sep>/htdocs/catalog/test_panel_new.php <?php # # Main page for adding new test panel # include("redirect.php"); include("../includes/page_elems.php"); require_once("includes/script_elems.php"); $script_elems = new ScriptElems(); $page_elems = new PageElems(); LangUtil::setPageId("catalog"); ?> <script type='text/javascript'> function check_input() { // Validate var panel_name = $('#panel_name').val(); if(panel_name == "") { alert("<?php echo LangUtil::$pageTerms['TIPS_MISSING_CATNAME']; ?>"); return; } // All OK $('#new_test_panel_form').submit(); } </script> <br> <b style="margin-left:50px;"><?php echo "New Test Panel"; ?></b> | <a href='catalog.php?show_tp=1'><?php echo LangUtil::$generalTerms['CMD_CANCEL']; ?></a> <br><br> <div class='pretty_box' style='margin-left:50px;' > <form name='new_test_panel_form' id='new_test_panel_form' action='test_panel_add.php' method='post'> <table class='smaller_font' style="width:100%;"> <tr> <td style='width:150px;'><?php echo "Select Parent Test Type"; ?><?php $page_elems->getAsterisk(); ?></td> <td> </td> </tr> <tr> <td colspan="2"><?php $page_elems->getTestPanelCheckBoxes($_SESSION['lab_config_id'], false); ?> </td> </tr> </table> <br><br> <div class="form-actions"> <button type="submit" onclick='check_input();' class="btn blue"><?php echo LangUtil::$generalTerms['CMD_SUBMIT']; ?></button> <a href='catalog.php?show_tp=1' class='btn'> <?php echo LangUtil::$generalTerms['CMD_CANCEL']; ?></a> </div> </form> </div> <div id='test_panel_help' style='display:none'> <small> Use Ctrl+F to search easily through the list. Ctrl+F will prompt a box where you can enter the test panel you are looking for. </small> </div> <?php //include("includes/footer.php"); ?> <file_sep>/htdocs/ajax/reject_result.php~ <?php include("redirect.php"); include('../includes/db_lib.php'); include('../includes/page_elems.php'); $reason = stripslashes($_REQUEST['rej_reason']); $specimen_id = $_REQUEST['spec']; $test = $_REQUEST['tname']; $test_type_id = $_REQUEST['ttype']; //echo $specimen_id." ".$reasons." ".$test; reject_test($specimen_id, $test_type_id, $reason); header('location:../'); // header('location:../results/results_entry.php?prompt#tests'); ?><file_sep>/htdocs/api/Net.old/HL7/Messages/ORU_R01.php <?php require_once "Net/HL7/Message.php"; /** * Class Net_HL7_Messages_ORU_R01 * * Construct a blank ORU_R01 message */ class Net_HL7_Messages_ORU_R01 { /** * @return Net_HL7_Message * */ public static function template() { return new Net_HL7_Message("MSH||||||||ORU^R01^ORU_R01|\rPID|1|\rPV1|1|\rORC|1|\rOBR|1|\rTQ1|1|\rOBX|1|\rSPM|1|\r"); } } ?> <file_sep>/metadata_table_list.sh #!/usr/bin/env bash unset username # clear STR=$'Enter username:\r' echo "$STR" read username # clear unset password prompt="Enter Password:" while IFS= read -p "$prompt" -r -s -n 1 char do if [[ $char == $'\0' ]] then break fi prompt='*' password+="$char" done mysqldump -u $username -p$password blis_revamp --tables specimen_activity test_type measure test_type_measure test_panel test_type_container_type specimen_type specimen_test measure_mapping specimen_custom_data test_category unit > metadata.sql clear echo "Done!" <file_sep>/htdocs/api/authenticate.php <?php include "../includes/db_lib.php"; $username = null; $password = <PASSWORD>; // mod_php if (isset($_SERVER['PHP_AUTH_USER'])) { $username = $_SERVER['PHP_AUTH_USER']; $password = $_SERVER['PHP_AUTH_PW']; // most other servers } elseif (isset($_SERVER['HTTP_AUTHORIZATION'])) { if (strpos(strtolower($_SERVER['HTTP_AUTHORIZATION']),'basic')===0) list($username,$password) = explode(':',base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6))); } $error_msg = array("ERROR"=>"Authentication failed!"); if (is_null($username)) { header('WWW-Authenticate: Basic realm="My Realm"'); header('HTTP/1.0 401 Unauthorized'); echo json_encode($error_msg); die(); } else { $tok = API::login($username, $password); if($tok < 0){ echo json_encode($error_msg); die(); }else{ $token = session_id(); $update_query = "UPDATE user SET cur_token = '$token' WHERE username = '$username'"; query_update($update_query); } } ?> <file_sep>/htdocs/api/get_users.php <?php require_once "authenticate.php"; $result = API::get_users(); if($result < 1) echo $result; else echo json_encode($result); ?> <file_sep>/htdocs/api/test_type_create_or_edit.php <?php require_once "authenticate.php"; $rcd = array(); $rcd['tid'] = $_REQUEST['tid']; $rcd['t_name'] = $_REQUEST['t_name']; $rcd['cat_code'] = $_REQUEST['cat_code']; $rcd['loinc_code'] = $_REQUEST['loinc_code']; $rcd['qty'] = $_REQUEST['qty']; $rcd['s_unit'] = $_REQUEST['s_unit']; $rcd['desc'] = $_REQUEST['desc']; $rcd['hide_name'] = $_REQUEST['hide_name']; $rcd['specimen_types'] = $_REQUEST['specimen_types']; $rcd['measures'] = $_REQUEST['measures']; $result = API::test_type_create_or_edit($rcd); if($result < 1) echo $result; else echo json_encode($result); ?> <file_sep>/htdocs/api/processHL7Order.php <?php require_once "authenticate.php"; require_once "Net/HL7/Segments/MSH.php"; require_once "Net/HL7/Message.php"; $debug = false; $debugPrint = false; if(!isset($_REQUEST['hl7']) && !$debug) { echo -2; return; } if(!$debug){ $request=$_REQUEST['hl7']; } else { $request = "MSH|^~&||KCH^2.16.840.1.113883.3.5986.2.15^ISO||KCH^2.16.840.1.113883.3.5986.2.15^ISO|20150222200401||OML^O21^OML_O21|20150222200401|T|2.5\nPID|1||P170000000031||Patient^Test^N/A||19930701|F\nORC||||||||||1^Super^User|||^^^^^^^^MEDICINE||||||||KCH\nTQ1|1||||||||S\nOBR|1|||5909-7^Blood films^LOINC|||20150222200401||||||Rule out diagnosis|||439234^Moyo^Chris\nOBR|2|||65758-5^CD4^LOINC|||20150222200401||||||Rule out diagnosis|||439234^Moyo^Chris\nOBR|3|||4537-7^Erythrocyte sedimentation rate^LOINC|||20150222200401||||||Rule out diagnosis|||439234^Moyo^Chris\nOBR|4|||57021-8^Full blood count^LOINC|||20150222200401||||||Rule out diagnosis|||439234^Moyo^Chris\nSPM|1|||Whole blood^Whole blood"; } $msg = new Net_HL7_Message($request); $msh = $msg->getSegmentsByName("MSH"); $pid = $msg->getSegmentsByName("PID"); $orc = $msg->getSegmentsByName("ORC"); $tq1 = $msg->getSegmentsByName("TQ1"); $obr = $msg->getSegmentsByName("OBR"); $spm = $msg->getSegmentsByName("SPM"); $nte = $msg->getSegmentsByName("NTE"); $sendingFacility = $msh[0]->getField(4)[0]; // MSH.04 $receivingFacility = $msh[0]->getField(6)[0]; // MSH.06 $messageDatetime = $msh[0]->getField(7); // MSH.07 $messageType = $msh[0]->getField(9)[2]; // MSH.09 $messageControlID = $msh[0]->getField(10); // MSH.10 $processingID = $msh[0]->getField(11); // MSH.11 $hl7VersionID = $msh[0]->getField(12); // MSH.12 $obrSetID = $obr[0]->getField(1); // OBR.01 $testCode = $obr[0]->getField(4)[0]; // OBR.04 $testName = $obr[0]->getField(4)[1]; // OBR.04 $timestampForSpecimenCollection = $obr[0]->getField(7); // OBR.07 $reasonTestPerformed = $obr[0]->getField(13); // OBR.13 $whoOrderedTest = $obr[0]->getField(16)[2] . " " . $obr[0]->getField(16)[1] . " (" . $obr[0]->getField(1)[0] . ")"; // OBR.16 $healthFacilitySiteCodeAndName = $orc[0]->getField(21); // ORC.21 $pidSetID = $pid[0]->getField(1); // PID.01 $nationalID = $pid[0]->getField(3); // PID.03 $patientName = $pid[0]->getField(5)[1] . " " . $pid[0]->getField(5)[2] . " " . $pid[0]->getField(5)[0] . " " . $pid[0]->getField(5)[3]; // PID.05 $dateOfBirth = $pid[0]->getField(7); // PID.07 $gender = $pid[0]->getField(8); // PID.08 $spmSetID = $spm[0]->getField(1); // SPM.01 $accessionNumber = $spm[0]->getField(2); // SPM.02 $typeOfSample = $spm[0]->getField(4)[1]; // SPM.04 $tq1SetID = $tq1[0]->getField(1); // TQ1.01 $priority = $tq1[0]->getField(9); // TQ1.09 $enteredBy = $orc[0]->getField(10)[2] . " " . $orc[0]->getField(10)[1] . " (" . $orc[0]->getField(10)[0] . ")"; // ORC.10 $enterersLocation = $orc[0]->getField(13); // ORC.13 $status = (gettype($nte[0]->getField(3)) == "array" && count($nte[0]->getField(3)) > 1 ? $nte[0]->getField(3)[0] : $nte[0]->getField(3)); $parent = (count($nte) > 0 && gettype($nte[0]->getField(3)) == "array" && count($nte[0]->getField(3)) > 1 ? ($nte[0]->getField(3)[1] == "parent" ? true : false) : false); $panel_loinc_code = (count($nte) > 0 && gettype($nte[0]->getField(3)) == "array" && count($nte[0]->getField(3)) > 2 ? $nte[0]->getField(3)[2] : ($parent ? null : $testCode)); if($debugPrint && false){ echo "sendingFacility: $sendingFacility<br />"; echo "receivingFacility: $receivingFacility<br />"; echo "messageDatetime: $messageDatetime<br />"; echo "messageType: $messageType<br />"; echo "messageControlID: $messageControlID<br />"; echo "processingID: $processingID<br />"; echo "hl7VersionID: $hl7VersionID<br />"; echo"obrSetID: $obrSetID<br />"; echo "testCode: $testCode<br />"; echo "timestampForSpecimenCollection: $timestampForSpecimenCollection<br />"; echo "reasonTestPerformed: $reasonTestPerformed<br />"; echo "whoOrderedTest: $whoOrderedTest<br />"; echo "healthFacilitySiteCodeAndName: $healthFacilitySiteCodeAndName<br />"; echo "pidSetID: $pidSetID<br />"; echo "nationalID: $nationalID<br />"; echo "patientName: $patientName<br />"; echo "dateOfBirth: $dateOfBirth<br />"; echo "gender: $gender<br />"; echo "spmSetID: $spmSetID<br />"; echo "accessionNumber: $accessionNumber<br />"; echo "typeOfSample: $typeOfSample<br />"; echo "tq1SetID: $tq1SetID<br />"; echo "priority: $priority<br />"; echo "enteredBy: $enteredBy<br />"; echo "enterersLocation: $enterersLocation<br />"; } $accessionNumber = null; if ($debug){ $accessionNumber = rand(); } $result = array( "sendingFacility" => $sendingFacility, "receivingFacility" => $receivingFacility, "messageDatetime" => $messageDatetime, "messageType" => $messageType, "messageControlID" => $messageControlID, "processingID" => $processingID, "hl7VersionID" => $hl7VersionID, "obrSetID" => $obrSetID, "testCode" => $testCode, "timestampForSpecimenCollection" => $timestampForSpecimenCollection, "reasonTestPerformed" => $reasonTestPerformed, "whoOrderedTest" => $whoOrderedTest, "healthFacilitySiteCodeAndName" => $healthFacilitySiteCodeAndName, "pidSetID" => $pidSetID, "nationalID" => $nationalID, "patientName" => $patientName, "dateOfBirth" => $dateOfBirth, "gender" => $gender, "spmSetID" => $spmSetID, "accessionNumber" => $accessionNumber, "typeOfSample" => $typeOfSample, "tq1SetID" => $tq1SetID, "priority" => $priority, "enteredBy" => $enteredBy, "enterersLocation" => $enterersLocation, "status" => $status, "panel_loinc_code" => $panel_loinc_code ); if (!$debug){ $response = API::create_order($result); } else { $response = $result; } $accessionNumber = $response["accessionNumber"]; $finalResult = array( "sendingFacility" => $sendingFacility, "receivingFacility" => $receivingFacility, "messageDatetime" => $messageDatetime, "messageType" => $messageType, "messageControlID" => $messageControlID, "processingID" => $processingID, "hl7VersionID" => $hl7VersionID, "tests" => array( array( "obrSetID" => $response["obrSetID"], "testCode" => $response["testCode"], "testName" => $testName, "timestampForSpecimenCollection" => $response["timestampForSpecimenCollection"], "reasonTestPerformed" => $response["reasonTestPerformed"], "enteredBy" => $enteredBy, "enterersLocation" => $enterersLocation, "panel_loinc_code" => $panel_loinc_code ) ), "healthFacilitySiteCodeAndName" => $healthFacilitySiteCodeAndName, "pidSetID" => $pidSetID, "nationalID" => $nationalID, "patientName" => $patientName, "dateOfBirth" => $dateOfBirth, "gender" => $gender, "spmSetID" => $spmSetID, "accessionNumber" => $accessionNumber, "typeOfSample" => $typeOfSample, "tq1SetID" => $tq1SetID, "priority" => $priority, "whoOrderedTest" => $response["whoOrderedTest"], "status" => $status ); for($i = 1; $i < sizeof($obr); $i++){ $obrSetID = $obr[$i]->getField(1); // OBR.01 $testCode = $obr[$i]->getField(4)[0]; // OBR.04 $testName = $obr[$i]->getField(4)[1]; // OBR.04 $timestampForSpecimenCollection = $obr[$i]->getField(7); // OBR.07 $reasonTestPerformed = $obr[$i]->getField(13); // OBR.13 $whoOrderedTest = $obr[$i]->getField(16)[2] . " " . $obr[$i]->getField(16)[1] . " (" . $obr[$i]->getField(1)[0] . ")"; // OBR.16 $priority = $tq1[$i]->getField(9); // TQ1.09 $parent = (count($nte) > $i && gettype($nte[$i]->getField(3)) == "array" && count($nte[$i]->getField(3)) > 1 ? ($nte[$i]->getField(3)[1] == "parent" ? true : false) : false); $panel_loinc_code = (count($nte) > $i && gettype($nte[$i]->getField(3)) == "array" && count($nte[$i]->getField(3)) > 2 ? $nte[$i]->getField(3)[2] : ($parent ? null : $testCode)); $result = array( "sendingFacility" => $sendingFacility, "receivingFacility" => $receivingFacility, "messageDatetime" => $messageDatetime, "messageType" => $messageType, "messageControlID" => $messageControlID, "processingID" => $processingID, "hl7VersionID" => $hl7VersionID, "obrSetID" => $obrSetID, "testCode" => $testCode, "timestampForSpecimenCollection" => $timestampForSpecimenCollection, "reasonTestPerformed" => $reasonTestPerformed, "whoOrderedTest" => $whoOrderedTest, "healthFacilitySiteCodeAndName" => $healthFacilitySiteCodeAndName, "pidSetID" => $pidSetID, "nationalID" => $nationalID, "patientName" => $patientName, "dateOfBirth" => $dateOfBirth, "gender" => $gender, "spmSetID" => $spmSetID, "accessionNumber" => $accessionNumber, "typeOfSample" => $typeOfSample, "tq1SetID" => $tq1SetID, "priority" => $priority, "enteredBy" => $enteredBy, "enterersLocation" => $enterersLocation, "status" => $status, "panel_loinc_code" => $panel_loinc_code ); if (!$debug){ $response = API::create_order($result); } else { $response = $result; } $set = array( "obrSetID" => $response["obrSetID"], "testCode" => $response["testCode"], "testName" => $testName, "timestampForSpecimenCollection" => $response["timestampForSpecimenCollection"], "reasonTestPerformed" => $response["reasonTestPerformed"], "enteredBy" => $enteredBy, "enterersLocation" => $enterersLocation, "panel_loinc_code" => $panel_loinc_code ); array_push($finalResult["tests"], $set); } echo json_encode($finalResult); ?> <file_sep>/htdocs/api/Net.old/HL7/Types/PRL.php <?php class Net_HL7_Types_PRL { private $parentObservationIdentifier; private $parentObservationSubIdentifier; private $parentObservationValueDescriptor; public function __construct($components) { $this->parentObservationIdentifier = (empty($components[0])) ? "" : $components[0]; $this->parentObservationSubIdentifier = (empty($components[1])) ? "" : $components[1]; $this->parentObservationValueDescriptor = (empty($components[2])) ? "" : $components[2]; } /** * @return Net_HL7_Types_PRL */ public static function template() { return new Net_HL7_Types_PRL(array()); } /** * @return array */ public function toArray() { $components = array(); $components[0] = $this->parentObservationIdentifier; $components[1] = $this->parentObservationSubIdentifier; $components[2] = $this->parentObservationValueDescriptor; return $components; } /** * @param $parentObservationIdentifier string */ public function setParentObservationIdentifier($parentObservationIdentifier) { $this->parentObservationIdentifier = $parentObservationIdentifier; } /** * @return string */ public function getParentObservationIdentifier() { return $this->parentObservationIdentifier; } /** * @param $parentObservationSubIdentifier string */ public function setParentObservationSubIdentifier($parentObservationSubIdentifier) { $this->parentObservationSubIdentifier = $parentObservationSubIdentifier; } /** * @return string */ public function getParentObservationSubIdentifier() { return $this->parentObservationSubIdentifier; } /** * @param $parentObservationValueDescriptor string */ public function setParentObservationValueDescriptor($parentObservationValueDescriptor) { $this->parentObservationValueDescriptor = $parentObservationValueDescriptor; } /** * @return string */ public function getParentObservationValueDescriptor() { return $this->parentObservationValueDescriptor; } } ?> <file_sep>/htdocs/catalog/test_panel_delete.php <?php # # Deletes a test category from DB //# Sets disabled flag to true instead of deleting the record //# This maintains info for samples that were linked to this test type previously # include("../includes/db_lib.php"); $saved_session = SessionUtil::save(); $saved_db = DbUtil::switchToGlobal(); $test_panel_id = $_REQUEST['tpid']; $query_delete_nodes = "DELETE FROM test_panel WHERE parent_test_type_id = $test_panel_id"; $query_update_panel = "UPDATE test_type SET is_panel = 0 WHERE test_type_id = $test_panel_id"; query_delete($query_delete_nodes); query_update($query_update_panel); DbUtil::switchRestore($saved_db); SessionUtil::restore($saved_session); header("Location: catalog.php?show_tp=1"); ?> <file_sep>/htdocs/ajax/test_panels_update.php <?php # # Main page for updating specimen type info # Called via Ajax from specimen_type_edit.php # include("../includes/db_lib.php"); $tid = $_REQUEST['tid']; $query_delete = "DELETE FROM test_panel WHERE parent_test_type_id = $tid"; query_delete($query_delete); foreach ($_REQUEST AS $key=>$value){ if(preg_match("/tp_type/", $key)){ $child_test_type_id = explode('_', $key)[2]; if($value == 'on'){ $query_insert = "INSERT INTO test_panel(parent_test_type_id, child_test_type_id) VALUES($tid, $child_test_type_id)"; query_insert_one($query_insert); } } } ?> <file_sep>/htdocs/api/get_specimen_details.php <?php require_once "authenticate.php"; $rcd = array(); $rcd['department'] = $_REQUEST['department']; $rcd['status'] = $_REQUEST['status']; $rcd['dashboard_type'] = $_REQUEST['dashboard_type']; $rcd['ward'] = $_REQUEST['ward']; if ($_REQUEST['date']) $rcd['date'] = $_REQUEST['date']; else $rcd['date'] = date('Y-m-d H:i:s'); $result = API::get_specimen_details($rcd); if($result < 1) echo $result; else echo json_encode($result); ?> <file_sep>/install.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <link href="htdocs/assets/bootstrap/css/bootstrap.min.css" rel="stylesheet" /> <!--link href="assets/css/metro.css" rel="stylesheet" /> <link href="assets/bootstrap/css/bootstrap-responsive.min.css" rel="stylesheet" /--> <link href="htdocs/assets/font-awesome/css/font-awesome.css" rel="stylesheet" /> <?php # # (c) C4G, <NAME> # BLIS Installation Page # if (session_id()!=''){ session_start(); $_SESSION = array(); session_destroy(); } if ($_REQUEST){ extract($_REQUEST); $con = mysql_connect($DB_Host, $DB_User, $DB_Pwd); if (!$con) die('Unable to connect to host: '.mysql_error()); $query = 'SHOW DATABASES LIKE \''.$DB_Name.'\''; $result = mysql_query($query); if ($result){ if (!mysql_num_rows($result)){ $query = 'CREATE DATABASE '.$DB_Name; if (!mysql_query($query)) die('Unable to create database: '.mysql_error()); } else $db_exists = true; } else die('MySQL Error: '.mysql_error()); if (!mysql_select_db($DB_Name, $con)){ die('Unable to select database: '.mysql_error()); } if ($db_exists && ($DB_Overwrite!='on')) die('<p align="center">The database \''.$DB_Name.'\' already exists!<br><br>Please select the \'Overwrite existing data\' option on the <a href="javascript:window.back()">previous page</a> if you wish to replace the existing data</p>'); //Run db script $handle = @fopen("blis_def.sql", "r"); if ($handle){ $currline = ''; while (($buffer = fgets($handle)) !== false) { //echo 'Buf='.$buffer.'<br>'; $currline .= $buffer; //echo 'Sub='.substr($buffer, -3, 1); if (substr($buffer, -2, 1)==';'){ mysql_query($currline); $currline = ''; } //echo $buffer; } if (!feof($handle)) { die("Error: unexpected fgets() failure\n"); } fclose($handle); if ($MFL_Code!=''){ $query = 'SELECT Facility_Name FROM facility_list WHERE Facility_Code='.$MFL_Code; $result = mysql_query($query); if ($result){ $row = mysql_fetch_assoc($result); $query = 'UPDATE lab_config SET `name`=\''.$row['Facility_Name'].'\', Facility_Code=\''.$MFL_Code.'\' LIMIT 1'; mysql_query($query); } } //Update db_constants.php $currfolder = str_replace('\\', '/', dirname(__FILE__)); $constfile = $currfolder.'/htdocs/includes/db_constants.php'; $constfileold = str_replace('db_constants.php', 'db_constants.old.php', $constfile); //if (rename($currfolder."/htdocs/includes/db_constants.php", $currfolder."/htdocs/includes/db_constants.php.old")){ if (copy($constfile, $constfileold)){ if (unlink($constfile)){ $infile = @fopen($constfileold, "r"); $outfile = @fopen($constfile, "w"); if ($infile && $outfile){ $currline = ''; while (($buffer = fgets($infile)) !== false) { if ((strtolower($DB_Host)!=='localhost') && (strpos($buffer, 'DB_HOST =')!==false)){ $buffer = '$DB_HOST = "'.$DB_Host.'";'.chr(13); } else if ((strtolower($DB_User)!=='root') && (strpos($buffer, 'DB_USER =')!==false)){ $buffer = '$DB_USER = "'.$DB_User.'";'.chr(13); } else if ((strtolower($DB_Name)!=='blis_revamp') && (strpos($buffer, 'GLOBAL_DB_NAME=')!==false)){ $buffer = '$GLOBAL_DB_NAME="'.$DB_Name.'";'.chr(13); } else if ((strtolower($DB_Pwd)!=='') && (strpos($buffer, 'DB_PASS =')!==false)){ $buffer = '$DB_PASS = "'.$DB_Pwd.'";'.chr(13); } //echo $buffer.'<br>'; fwrite($outfile, $buffer); } if (!feof($infile)) { die('Error: unexpected fgets() infile failure\n'); } fclose($infile); fclose($outfile); header('location:htdocs/login.php'); } else error_log(chr(13).date('Y-m-d H:i:s').':Unable to open constants file for reading/writing', 3, 'install.log'); } else error_log(chr(13).date('Y-m-d H:i:s').':Unable to delete constants file', 3, 'install.log'); } else error_log(chr(13).date('Y-m-d H:i:s').':Unable to copy constants file', 3, 'install.log'); } else error_log(chr(13).date('Y-m-d H:i:s').':Unable to open database file', 3, 'install.log'); } ?> </head> <body> <!-- BEGIN ROW-FLUID--> <div class="row-fluid" align="center"> <div class="span12 sortable"> <div class='content_div'> <div class="portlet box green"> <div class="portlet-title"> <h2><i class="icon-reorder"></i>BLIS INSTALLATION PAGE</h2> </div> </div> <p> <form method="post"> <table> <tr><td>Database Host</td><td><input type="text" name="DB_Host" value="localhost" /></td></tr> <tr><td>Database User</td><td><input type="text" name="DB_User" value="root" /></td></tr> <tr><td>Database Password</td><td><input type="password" name="DB_Pwd" /></td></tr> <tr><td>Database Name</td><td><input type="text" name="DB_Name" value="blis" /><br>&nbsp;&nbsp;&nbsp;<input type="checkbox" name="DB_Overwrite" />&nbsp;Overwrite existing data</td></tr> <tr><td>Facility</td><td> <select name="MFL_Code"> <option value="14180">10 Engineer VCT</option> <option value="17486">12 Engineers</option> <option value="18393">3Kl Maternity & Nursing Home</option> <option value="14181">3Kr Health Centre</option> <option value="11917">78 Tank Battalion Dispensary</option> <option value="13043">7Kr Mrs Health Centre</option> <option value="14182">8Th Street Clinic</option> <option value="18137">A To Z Quality Health Family Health Services</option> <option value="12861">AAR City Centre Clinic</option> <option value="16796">AAR Clinic Sarit Centre (Westlands)</option> <option value="18178">AAR Eldoret</option> <option value="19958">AAR Gwh Health Care Ltd</option> <option value="18859">AAR Healthcare Limited (Karen)</option> <option value="12862">AAR Kariobangi Clinic</option> <option value="11194">AAR Medical Services (Docks)</option> <option value="20140">AAR Mountain mall</option> <option value="14183">AAR Nakuru Clinic</option> <option value="11721">AAR Nyali Health Care</option> <option value="12863">AAR Thika Road Clinic</option> <option value="18821">Abakaile Dispensary</option> <option value="13265">Abakore Sub District Hospital</option> <option value="12864">Abandoned Child Care</option> <option value="19856">Abba Medical Clinic</option> <option value="19484">Abby Clinic</option> <option value="19117">Abby Health Services</option> <option value="12126">ABC Thange Dispensary</option> <option value="19354">Abdallah Dental Clinic (Barclays Plaza-Nairobi)</option> <option value="17009">Abdisamad Dispensary</option> <option value="10001">Abel Migwi Johana Laboratory</option> <option value="10003">Aberdare Health Services</option> <option value="10002">Aberdare Medical & Surgical Clinic</option> <option value="13461">Abidha Health Centre</option> <option value="16716">Able Medical Clinic</option> <option value="15789">Aboloi Dispensary</option> <option value="19441">Abra Health Services</option> <option value="19562">Abraham Memorial Nursing Home (Westlands)</option> <option value="10004">Abrahams Clinic</option> <option value="19897">Abundant Life Clinic</option> <option value="19980">Acacia Clinic (Westlands)</option> <option value="19413">Acacia Medical Centre (Nairobi)</option> <option value="14184">Acacia Medicare Centre</option> <option value="18965">Acc&S Kariua Dispensary</option> <option value="19467">Access Afya</option> <option value="12791">Acef Ena Health Centre</option> <option value="11918">ACK Dispensary (Isiolo)</option> <option value="17980">ACK Kanunga Dispensary</option> <option value="19651">ACK Mwingi CHBC Clinic</option> <option value="19704">ACK Nyandarua Medical Clinic</option> <option value="17473">ACK Tumaini Medical Clinic</option> <option value="11195">Acode Medical Clinic Maungu</option> <option value="19520">Aculaser Institute</option> <option value="13266">Adadijolle Dispensary</option> <option value="11196">ADC Danisa Dispensary</option> <option value="13267">Ademasajida Dispensary</option> <option value="13463">Adiedo Dispensary</option> <option value="13464">Administration Police Dispensary (Kisumu East)</option> <option value="18171">Administration Police Senior Staff College Dispens</option> <option value="18793">Adora Children Clinic</option> <option value="11198">Adu Dispensary</option> <option value="14185">Adurkoit Dispensary</option> <option value="18372">Advent Med & Dentist Care Centre</option> <option value="18535">Adventist Centre For Care and Support (Westlands)</option> <option value="18382">Afraha Maternity and Nursing Home</option> <option value="13268">Africa Inland Church Dispensary</option> <option value="20090">African Divine Church-Org</option> <option value="12865">Afwan Medical Centre</option> <option value="17335">Afwein Dispensary</option> <option value="19162">Afwene Clinic</option> <option value="17577">Afya Bora Clinic</option> <option value="11919">Afya Bora Clinic (Meru South)</option> <option value="17819">Afya Bora Clinic (Mutomo)</option> <option value="10011">Afya Bora Clinic (Mwea)</option> <option value="19966">Afya Bora Clinic Karia</option> <option value="19515">Afya Bora Health Care</option> <option value="19794">Afya Bora Health Clinic</option> <option value="19662">Afya Bora Mc</option> <option value="16411">Afya Bora Medical Clinic</option> <option value="16491">Afya Bora Medical Clinic (CFW Clinic Gichugu)</option> <option value="11200">Afya Bora Medical Clinic (Malindi)</option> <option value="10007">Afya Bora Medical Clinic (Muchagara)</option> <option value="10008">Afya Bora Medical Clinic (Nyeri South)</option> <option value="14186">Afya Bora Medical Clinic (Turkana Central)</option> <option value="19551">Afya Bora Medical Clinic (Westlands)</option> <option value="11201">Afya Clinic</option> <option value="14187">Afya Frank Medical Clinic</option> <option value="18486">Afya Health Care</option> <option value="10009">Afya Health Services</option> <option value="18344">Afya House Dispensary</option> <option value="10006">Afya Link Ngurubani Clinic</option> <option value="18845">Afya Medical Centre</option> <option value="10015">Afya Medical Clinic</option> <option value="16556">Afya Medical Clinic</option> <option value="19621">Afya Medical Clinic (Dandora)</option> <option value="13269">Afya Medical Clinic (Garissa)</option> <option value="19802">Afya Medical Clinic (Gwakungu)</option> <option value="11920">Afya Medical Clinic (Kangundo)</option> <option value="18730">Afya Medical Clinic (Meru)</option> <option value="17566">Afya Medical Clinic (Munyaka)</option> <option value="10010">Afya Medical Clinic (Muranga North)</option> <option value="18440">Afya Medical Clinic (Nakuru)</option> <option value="10013">Afya Medical Clinic (Nyeri North)</option> <option value="10014">Afya Medical Clinic (Nyeri South)</option> <option value="13270">Afya Medical Clinic (Wajir East)</option> <option value="19131">Afya Medical Laboratory</option> <option value="19453">Afya Medical Services</option> <option value="19645">Afya Medicare Clinic</option> <option value="13271">Afya Medicare Clinic (Wajir East)</option> <option value="11921">Afya Njema Clinic</option> <option value="14188">Afya Njema Medical Clinic</option> <option value="18021">Afya Njema Medical Clinic (Nyeri North)</option> <option value="18428">Afya Nursing Home (Moyale)</option> <option value="19764">Afya Yako Medical Clinic</option> <option value="19082">Afya Yetu Medical Centre</option> <option value="19397">Afyamax Medical & Centre Dental</option> <option value="20065">Aga Khan Clinic</option> <option value="18223">Aga Khan Clinic Kitengela</option> <option value="19457">Aga Khan Greenspam Medical Centre</option> <option value="12867">Aga Khan Hospital</option> <option value="13465">Aga Khan Hospital (Kisumu)</option> <option value="11203">Aga Khan Hospital (Mombasa)</option> <option value="20176">Aga Khan Medical Centre Kericho</option> <option value="19464">Aga Khan Reinsurance Plaza Lab</option> <option value="12868">Aga Khan University Hospital (Buruburu)</option> <option value="19223">Aga Khan University Hospital - Embu </option> <option value="18738">Aga Khan University Hospital -New Machakos Medical</option> <option value="19335">Aga Khan University Hospital Clinic (Naivasha)</option> <option value="20205">Aga Khan University Hospital Kiambu Clinic</option> <option value="14189">Aga Khan University Hospital O/R Clinic</option> <option value="17857">Aga Khan University Hospital- Nyeri Medical Centre</option> <option value="10016">Agape Medical Services</option> <option value="13466">Agawo Dispensary</option> <option value="14190">Agc Baby Health Centre</option> <option value="13467">Agenga Dispensary</option> <option value="15790">Agenga Dispensary (Samia)</option> <option value="16452">Agma Clinic</option> <option value="19815">Agro Chemical Dispensary</option> <option value="10017">Aguthi Dispensary</option> <option value="10018">Ahadi Maternity Services</option> <option value="16516">Ahadi Medical Clinic</option> <option value="18291">Ahero Medical Centre</option> <option value="14191">Ahero Medical Clinic</option> <option value="13468">Ahero Sub-District Hospital</option> <option value="18804">AHF Soko Clinic</option> <option value="15791">Ahmadiya Hospital</option> <option value="18835">AIC Biribiriet Dispensary</option> <option value="12093">AIC Dispensary (Isiolo)</option> <option value="17582">AIC Ebenezer</option> <option value="10283">AIC Gituru Dispensary</option> <option value="17431">AIC Kalamba Dispensary</option> <option value="14178">AIC Litein Mission Hospital</option> <option value="17655">AIC Liten VCT</option> <option value="12558">AIC Mukaa Dispensary</option> <option value="20071">AIC Mununga Dispensary</option> <option value="18439">AIC Parkview Dispensary</option> <option value="20030">Aina Onlus</option> <option value="16350">Ainabkoi (RCEA) Health Centre</option> <option value="19885">Ainamoi Dispensary</option> <option value="14192">Ainamoi Health Centre</option> <option value="11922">Air Port Medical Centre</option> <option value="19817">Airborne No Twist Huduma Bora Clinic</option> <option value="13469">Airport Dispensary (Kisumu)</option> <option value="11204">Airport View Medical Clinic</option> <option value="18038">Airstrip Medical Clinic (Moyale)</option> <option value="14193">Aiyebo Dispensary</option> <option value="18398">Ajam VCT</option> <option value="13272">Ajawa Health Centre</option> <option value="11923">Akachiu Health Centre</option> <option value="13470">Akado Dispensary</option> <option value="13471">Akala Health Centre</option> <option value="17770">Akemo Medical Clinic</option> <option value="14194">Akemo Nursing Home</option> <option value="18764">Akicha Medical Services</option> <option value="15792">Akichelesit Dispensary</option> <option value="13462">Akidiva Clinic</option> <option value="10604">Akshar Nursing Home</option> <option value="19154">Al - Azhar Medical Clinic Centre</option> <option value="19149">Al - Bushra Medical Centre</option> <option value="19174">Al - Hayat Medicare</option> <option value="19204">Al - Nasri Medical Care</option> <option value="17185">Al -Arbrar Medical Clinic</option> <option value="18996">Al Amin Medical Clinic</option> <option value="18769">Al Amin Nursing Home</option> <option value="17628">Al Azhar Medical Clinic</option> <option value="11208">Al Farooq Hospital</option> <option value="18997">Al Iklas Medical Clinic</option> <option value="19165">Al Qudus Clinic</option> <option value="11209">Al Riyadh Medical Clinic</option> <option value="11207">Al-Agsa Medical Clinic</option> <option value="17886">Al-Amin Medical Clinic</option> <option value="16299">Al-Ansar Medical Clinic</option> <option value="13274">Al-Aqsa Medical Clinic</option> <option value="16530">Al-Bir Medical Centre</option> <option value="11210">Al-Bir Medical Centre (Kilindini)</option> <option value="19608">Al-Fallah Medical Clinic</option> <option value="13275">Al-Faruq Dispensary</option> <option value="18998">Al-Faruq Medical Clinic</option> <option value="19629">Al-Firdaus Health Care</option> <option value="13276">Al-Furaqan Clinic</option> <option value="16801">Al-Gadhir Clinic</option> <option value="13277">Al-Hamdu Medical Clinic</option> <option value="13278">Al-Haqq Medical Clinic</option> <option value="18956">Al-Hidaya Clinic</option> <option value="13283">Al-Maaruf Clinic</option> <option value="13284">Al-Maqdis ENT Clinic</option> <option value="18404">Al-Mumtaz Medical Clinic</option> <option value="13285">Al-Mustaqim Clinic</option> <option value="19461">Al-Ramah Healthcare</option> <option value="13287">Al-Siha Nursing Home</option> <option value="14195">Alakara Medical Clinic</option> <option value="14196">Alale (AIC) Health Centre</option> <option value="16367">Alale Health Centre</option> <option value="17899">Albilal Medical Clinic (Moyale)</option> <option value="19344">Aldai Medical Services</option> <option value="16256">Alfa Clinic</option> <option value="11924">Alfalah Nursing Home</option> <option value="18009">Algadir Medical Clinic</option> <option value="18982">Alhamdu Medical Clinic</option> <option value="19031">Alhidaya Medical Clinic</option> <option value="12869">Alice Nursing Home</option> <option value="17012">Alikune Dispensary</option> <option value="13281">Alimaow Health Centre</option> <option value="13282">Alinjugur Health Centre</option> <option value="10021">All Day Medical Clinic</option> <option value="17794">All Nation Medical Clinic</option> <option value="15793">All Saints Musaa</option> <option value="15794">Alliance Clinic</option> <option value="17847">Alliance Medical Centre</option> <option value="18999">Alliance Medical Clinic</option> <option value="19822">Alliance Medical Clinic (Kirinyaga)</option> <option value="16557">Almed Health Products</option> <option value="19653">Alms House Dispensary</option> <option value="16294">Alnas Medical Clinic</option> <option value="19000">Alnasar Medical Clinic</option> <option value="18067">Alpha Community Health Clinic (Migori)</option> <option value="19748">Alpha Dental Services</option> <option value="10022">Alpha Family Health Care</option> <option value="19880">Alpha Medical Agency</option> <option value="16321">Alpha Medical Clinic</option> <option value="19321">Alpha Medical Clinic (Koibatek)</option> <option value="19040">Alpha Medical Clinic Mile Tisa</option> <option value="19356">Alphine Dental Centre (Kencom Hse)</option> <option value="13472">Alum Beach Dispensary</option> <option value="13473">Aluor Mission Health Centre</option> <option value="15795">Alupe Sub-District Hospital</option> <option value="10023">Ama (Africa Muslim Agency) Clinic</option> <option value="19215">Amaal Annex Nursing</option> <option value="15796">Amagoro Nursing Home</option> <option value="14198">Amakuriat Dispensary</option> <option value="16308">Amal Medical Clinic</option> <option value="10024">Amani Clinic</option> <option value="19001">Amani Clinic (Garissa)</option> <option value="19846">Amani MC</option> <option value="13474">Amani Medical Centre (Suneka)</option> <option value="20119">Amani Medical Clinic</option> <option value="11216">Amani Medical Clinic (Changamwe)</option> <option value="11925">Amani Medical Clinic (Kambu)</option> <option value="11217">Amani Medical Clinic (Kilifi)</option> <option value="11218">Amani Medical Clinic (Likoni)</option> <option value="11219">Amani Medical Clinic (Malindi)</option> <option value="19075">Amani Medical Clinic (Meru)</option> <option value="18718">Amani Medical Clinic (Meru)</option> <option value="17561">Amani Medical Clinic (Murungaru)</option> <option value="10026">Amani Medical Clinic (Nyeri North)</option> <option value="17559">Amani Medical Clinic Magumu</option> <option value="18921">Amani Medical Clinic Yatta</option> <option value="17624">Amani VCT</option> <option value="15797">Amase Dispensary</option> <option value="13475">Amatierio Dispensary</option> <option value="17797">Amaya/Plesian Dispensary</option> <option value="19656">Amazing Grace M C</option> <option value="11927">Ambalo Dispensary</option> <option value="13476">Ambira Sub-District Hospital</option> <option value="10027">Amboni Dispensary</option> <option value="14200">Amboseli Dispensary</option> <option value="14201">Amboseli Serena Lodge Clinic</option> <option value="20136">AMEC Laboratories</option> <option value="19022">Amina Medical Clinic</option> <option value="20170">Among'ura Community Dispensary</option> <option value="16768">Amoyo Dispensary</option> <option value="11928">Amugaa Health Centre</option> <option value="15798">Amukura Health Centre</option> <option value="15799">Amukura Mission Health Centre</option> <option value="13288">Amuma Dispensary</option> <option value="13289">Amuma Mobile Dispensary</option> <option value="11929">Amungeti Catholic Dispensary</option> <option value="20116">Amurt Health care Centre (Malindi)</option> <option value="12870">Amurt Health Centre</option> <option value="11221">Amurt Health Centre (Likoni)</option> <option value="17062">Amwamba Dispensary</option> <option value="16359">Ancilla Catholic Dispensary</option> <option value="14203">Andersen Medical Centre</option> <option value="13477">Anding'o Opanga Dispensary</option> <option value="18770">Andulus Medical Clinic</option> <option value="13478">Aneko Dispensary</option> <option value="13479">Ang'iya Dispensary</option> <option value="17050">Angaga Dispensary</option> <option value="14205">Angata Health Centre</option> <option value="17274">Angata Nanyokie Dispensary</option> <option value="18272">Angaza VCT</option> <option value="18627">Angelic Medical Centre</option> <option value="18923">Angels Health Services</option> <option value="15800">Angurai Health Centre</option> <option value="14206">Anin Dispensary</option> <option value="13480">Anjego Dispensary</option> <option value="18871">Ankamia Dispensary</option> <option value="10029">Anmer Dispensary</option> <option value="16323">Annet Dispensary</option> <option value="13481">Annex Clinic (Kenyenya)</option> <option value="19404">Annex Health Care</option> <option value="14207">Annex Hospital (Nakuru)</option> <option value="10031">Annex Laboratory</option> <option value="19904">Annex Medical Clinic</option> <option value="10032">Annex Medical Clinic (Muranga North)</option> <option value="14208">Annex Medical Clinic (Trans Nzoia West)</option> <option value="18816">Annointed Medical Clinic</option> <option value="10033">Annunciation Catholic Dispensary</option> <option value="11930">Anona Dispensary</option> <option value="11222">Ansar Medical Clinic</option> <option value="18618">Antodevi Medical Clinic</option> <option value="10034">Antony Njogu Clinic</option> <option value="17718">Antubangai Catholic Dispensary</option> <option value="17068">Antubetwe Njoune Dispensary</option> <option value="17067">Antubochiu Dispensary</option> <option value="13482">Anyuongi Dispensary</option> <option value="17649">Ap Buru Buru Disp</option> <option value="15801">Ap Line Dispensary</option> <option value="11931">Apdk Dispensary (Machakos)</option> <option value="16872">Apex Clinic</option> <option value="16492">Apha Laboratory</option> <option value="18671">Aphia Disc 1 Nanyuki Transport</option> <option value="20022">Aphia Plus Marps Dic Nanyuki</option> <option value="18790">Aphiaplus Drop-In Centre (Naivasha)</option> <option value="15802">Apokor Dispensary</option> <option value="14209">Aposta Dispensary</option> <option value="15803">Apostles Clinic</option> <option value="18934">Appex Medical Clinic</option> <option value="15804">Approved Dispensary</option> <option value="11932">Approved School Dispensary (Machakos)</option> <option value="12871">Aptc Health Centre</option> <option value="11933">Apu Dispensary</option> <option value="17572">Aqua Medical Clinic</option> <option value="14210">Aquilla Farm Medical Clinic</option> <option value="13290">Arabia Health Centre</option> <option value="14211">Arama Dispensary</option> <option value="19660">Arara ENT Clinic</option> <option value="19761">Arara ENT Clinic</option> <option value="13291">Arbajahan Health Centre</option> <option value="16286">Arbajahan Nomadic Mobile Clinic</option> <option value="13292">Arbaqueranso Dispensary</option> <option value="10037">Arcade Medical Clinic</option> <option value="10036">Arcade Medical Clinic (Ruiru)</option> <option value="14212">Archers Post Health Centre</option> <option value="17202">Aren Medical Clinic</option> <option value="17977">Aren Medical Clinic</option> <option value="16810">Aresa Dispensary</option> <option value="13293">Argane Dispensary</option> <option value="18319">Arimi Clinic and Laboratory</option> <option value="14213">Arimi Dispensary</option> <option value="13484">Arito Langi Dispensary</option> <option value="14197">Arjijo Dispensary</option> <option value="18814">Armstrong</option> <option value="13485">Aro (SDA) Dispensary</option> <option value="13486">Arombe Dispensary</option> <option value="17705">Arosa Dispensary</option> <option value="14214">Arpollo Dispensary</option> <option value="14215">Arroket Dispensary</option> <option value="14216">Arror Health Centre</option> <option value="12872">Arrow Web Maternity and Nursing Home</option> <option value="14217">Arsim Lutheran Dispensary</option> <option value="19560">Artisan Dental Laboratory (Nairobi)</option> <option value="10038">Asantey Clinic</option> <option value="13487">Asat Beach Dispensary</option> <option value="16783">Asayi Dispensary</option> <option value="18039">Asembo Bay Health Clinic (Rarieda)</option> <option value="18751">Ash Community Health Centre</option> <option value="13294">Ashabito Health Centre</option> <option value="17524">Ashburn Ohuru Clinic</option> <option value="11226">Ashraf Medical Clinic</option> <option value="12873">Aski Medical Clinic</option> <option value="15762">ASN Upendo Village Dispensary</option> <option value="10039">ASPE Medical Clinic</option> <option value="11229">Assa Dispensary</option> <option value="18348">Association of Physically Disabled of Kenya</option> <option value="10040">Assumption of Mary Dispensary</option> <option value="14218">Assumption Sisters Dispensary</option> <option value="18661">Assumption Sisters Mbooni Clinic</option> <option value="14219">Assururiet (SDA) Dispensary</option> <option value="16987">Asumbi Annex Dispensary</option> <option value="13488">Asumbi Health Centre</option> <option value="18610">Atela Dispensary</option> <option value="13489">Atemo Health Centre</option> <option value="18169">Athi Complex Community Centre</option> <option value="10041">Athi Dispensary</option> <option value="11934">Athi Kamunyuni Dispensary</option> <option value="11935">Athi River Community Hospital</option> <option value="11936">Athi River Health Centre</option> <option value="11937">Athi River Medical Services</option> <option value="13295">Athibohol Dispensary</option> <option value="19185">Athirunjine Runjine Dispensary</option> <option value="14220">Atiar Dispensary</option> <option value="10042">Atlas Medical Clinic</option> <option value="16866">Avarende Medical Clinic</option> <option value="16531">Avenue Health Care</option> <option value="19462">Avenue Health Care (Makadara)</option> <option value="13490">Avenue Health Care Clinic</option> <option value="18817">Avenue Health Care Nakuru</option> <option value="19083">Avenue Health Care Ongata Rongai</option> <option value="12874">Avenue Hospital</option> <option value="20123">Avenue Hospital Kisumu</option> <option value="13491">Awasi Mission Dispensary</option> <option value="18081">Awendo Jiwdendi</option> <option value="13492">Awendo Sub-District Hospital</option> <option value="18783">Axis Nursing Home</option> <option value="13296">Ayan Clinic</option> <option value="11232">Azimio Medical Centre</option> <option value="11938">Azimio Medical Clinic (Meru South)</option> <option value="11939">B/Valley (PCEA) Clinic</option> <option value="10043">Baari Health Centre</option> <option value="17273">Baawa Community Dispensary</option> <option value="12875">Babadogo (EDARP)</option> <option value="12876">Babadogo Health Centre</option> <option value="12877">Babadogo Medical Health Centre</option> <option value="19296">Babito Medical Centre</option> <option value="18423">Badan-Rero Dispensary</option> <option value="16477">Badana Dispensary</option> <option value="11940">Badassa Dispensary</option> <option value="17586">Badilika VCT</option> <option value="19604">Badri Medical Clinic</option> <option value="11233">Badria Medical Clinic</option> <option value="19557">Bafana Medical Centre</option> <option value="14222">Bagaria Dispensary</option> <option value="17190">Bahai Dispensary</option> <option value="11234">Bahari Medical Clinic</option> <option value="18588">Bahari Medical Clinic Diani Beach</option> <option value="12878">Bahati Clinic</option> <option value="14223">Bahati Dispensary</option> <option value="14224">Bahati District Hospital</option> <option value="12879">Bahati Health Centre</option> <option value="12880">Bahati Medical Clinic</option> <option value="18161">Bahati Medical Clinic (Lugari)</option> <option value="19088">Bahati Medical Clinic (West Pokot)</option> <option value="17733">Bahati Medical Clinic Migori</option> <option value="16532">Bakarani Community Clinic</option> <option value="11235">Bakarani Maternity and Nursing Home</option> <option value="11236">Bakhita Dispensary</option> <option value="13298">Balambala Sub-District Hospital</option> <option value="19259">Bales Saru Dispensary</option> <option value="11941">Balesa Dispensary</option> <option value="13299">Balich Dispensary</option> <option value="11776">Ballore Africa Logistic Staff Clinic</option> <option value="13493">Bama Hospital</option> <option value="11238">Bamba Medical Clinic</option> <option value="11237">Bamba Sub-District Hospital</option> <option value="10044">Bamboo Health Centre</option> <option value="11239">Bamburi Dispensary</option> <option value="11240">Bamburi Medicare</option> <option value="16297">Banadir Clinic</option> <option value="13494">Bande Dispensary</option> <option value="11242">Bangali Dispensary</option> <option value="17074">Bangali Nomadic</option> <option value="14225">Bangii Medical Clinic</option> <option value="13300">Banisa Health Centre</option> <option value="14226">Banita Dispensary</option> <option value="15805">Banja Health Centre</option> <option value="19428">Bans Optical (Nairobi)</option> <option value="11243">Baobab Clinic - Bamburi Cement</option> <option value="17871">Baobab Medical Clinic</option> <option value="11244">Baolala Dispensary</option> <option value="13495">Bar Achuth Dispensary</option> <option value="13496">Bar Agulu Dispensary</option> <option value="13497">Bar Aluru Dispensary (Rarieda)</option> <option value="20206">Bar Hostess Empowerment And Support programme (Makadara)</option> <option value="18468">Bar Hostess Empowerment Support Program VCT</option> <option value="13498">Bar Korwa Dispensary</option> <option value="16784">Bar Ndege Dispensary</option> <option value="13499">Bar Olengo Dispensary</option> <option value="16785">Bar-Sauri Dispensry</option> <option value="14227">Baragoi Catholic Dispensary</option> <option value="14228">Baragoi Sub-District Hospital</option> <option value="11942">Baragu Health Centre</option> <option value="10046">Baragwi Maternity Home</option> <option value="11943">Baraka Afya Clinic</option> <option value="18841">Baraka Clinic (Lugari)</option> <option value="18915">Baraka Dental Clinic (Maara)</option> <option value="12881">Baraka Dispensary (Nairobi)</option> <option value="17757">Baraka Health Centre</option> <option value="14230">Baraka Maternity Home</option> <option value="19529">Baraka Medical Cenre</option> <option value="17934">Baraka Medical Centre</option> <option value="17426">Baraka Medical Clinic</option> <option value="19840">Baraka Medical Clinic (Kirinyaga)</option> <option value="16202">Baraka Medical Clinic (Lamu)</option> <option value="19306">Baraka Medical Clinic (Makindu)</option> <option value="10047">Baraka Medical Clinic (Muranga North)</option> <option value="14229">Baraka Medical Clinic (Pokot Central)</option> <option value="17882">Baraka Medical Clinic (Runyenjes)</option> <option value="16670">Baraka Medical Clinic (Samburu East)</option> <option value="16693">Baraka Medical Clinic (Trans Nzoia East)</option> <option value="14231">Baraka Medical Clinic (Turkana Central)</option> <option value="11245">Baraka Medical Clinic (Vikwatani)</option> <option value="18224">Baraka Medical Clinic Kitengela</option> <option value="11944">Baraka Nursing Home</option> <option value="19601">Baraka Yetu Medical Clinic</option> <option value="17360">Barakeiywo Dispensary</option> <option value="16289">Baraki Dispensary</option> <option value="11945">Barambate Dispensary</option> <option value="17302">Bararget Dispensary</option> <option value="17218">Baraton</option> <option value="14232">Baraton Mch</option> <option value="11946">Barazani Medical Clinic</option> <option value="18396">Barding Dispensary</option> <option value="18381">Bargain Medical Clinic</option> <option value="11247">Bargoni Nys Dispensary</option> <option value="10048">Baricho Catholic Health Centre</option> <option value="11248">Baricho Dispensary (Malindi)</option> <option value="10049">Baricho Health Centre</option> <option value="17352">Barnet Memorial Hospital</option> <option value="14234">Barotion (AIC) Dispensary</option> <option value="14235">Barpello Dispensary</option> <option value="14236">Barsaloi Catholic Dispensary</option> <option value="14237">Barsaloi GK Dispensary</option> <option value="17056">Barsemoi Dispensary</option> <option value="18071">Barsheba Medical Clinic</option> <option value="14238">Barsiele Dispensary</option> <option value="14239">Barsombe Dispensary</option> <option value="14240">Barsombe Dispensary (Turbo)</option> <option value="14241">Bartabwa Dispensary</option> <option value="14242">Bartolimo Dispensary</option> <option value="17793">Barut Dispensary</option> <option value="13301">Barwaqo Clinic</option> <option value="13302">Barwaqo Dispensary</option> <option value="14243">Barwessa Healthcentre</option> <option value="11947">Basa Dispensary</option> <option value="14244">Base Medical Centre</option> <option value="17855">Bashal Islamic Community Health Initiative</option> <option value="13303">Basir Dispensary</option> <option value="13304">Batalu Dispensary</option> <option value="19701">Batian Clinical Services</option> <option value="10051">Batian Eye Clinic</option> <option value="19125">Batian Flowers Clinic</option> <option value="10052">Batian Laboratory Services</option> <option value="14245">Batian Medical Centre</option> <option value="19695">Batian Medical Centre Annex</option> <option value="10053">Batian Medical Services Medical Clinic</option> <option value="15806">Bay Way Medical Clinic</option> <option value="10054">Bcj Medical Centre</option> <option value="16667">Beacon of Hope Clinic (Kajiado)</option> <option value="15807">Beberion Clinic</option> <option value="18626">Beggs Clinic</option> <option value="13500">Bekam Clinic</option> <option value="14246">Bekibon Dispensary</option> <option value="17085">Belgut Dispensary</option> <option value="10055">Bellevue Health Centre</option> <option value="13305">Benane Health Centre</option> <option value="16786">Benga Bi Dispensary</option> <option value="16185">Bengo Medical Clinic</option> <option value="14247">Benmac Clinic</option> <option value="10056">Bennedict XVI Dispensary</option> <option value="16695">Benon Dispensary</option> <option value="13501">Benrose Clinic</option> <option value="10057">Bens Labs</option> <option value="17270">Bensu Health Care Medical Clinic</option> <option value="19873">Best Healthlife Clinic</option> <option value="10058">Beta Care Nursing Home</option> <option value="16533">Beta Medical & Skin Clinic</option> <option value="17542">Bethania Clinic</option> <option value="10059">Bethany Clinic</option> <option value="10060">Bethany Family Clinic</option> <option value="17432">Bethany Health Services Clinic</option> <option value="12882">Bethel Clinic</option> <option value="14249">Bethel Faith Dispensary</option> <option value="10061">Bethel Medical Clinic</option> <option value="14250">Bethelm Clinic</option> <option value="18935">Bethezda Medical Clinic</option> <option value="14251">Bethsaida (AIC) Clinic (Nakuru)</option> <option value="10063">Bethsaida (PCEA) Dispensary (Nyeri)</option> <option value="19921">Bethsaida Catholic Dispensary</option> <option value="17777">Bethsaida CFW Bamako</option> <option value="10064">Bethsaida Clinic (Kirinyaga-Gathiga)</option> <option value="10065">Bethsaida Clinic (Kirinyaga-Thiba)</option> <option value="18932">Bethsaida Grand Cure Clinic</option> <option value="19051">Bethsaida Grandcure Medical Clinic</option> <option value="10067">Bethsaida Medical Clinic (Gatundu)</option> <option value="11948">Bethsaida Medical Clinic (Kangundo)</option> <option value="11949">Bethwell Clinic</option> <option value="19411">Betta Health Care</option> <option value="14253">Better Health Services</option> <option value="19166">Better Medical Clinic</option> <option value="11251">Better off Knowing Stand Alone VCT Centre (Liverpo</option> <option value="19053">Beula's Clinic</option> <option value="19709">Bevans Medical Clinic</option> <option value="18813">Bgp Block 10Ba Base Camp Clinic</option> <option value="12883">Biafra Lions Clinic</option> <option value="12884">Biafra Medical Clinic</option> <option value="19602">Bibirioni Health Centre</option> <option value="14221">Bible Faith Church Medical Services Dispensary</option> <option value="18532">Bidii Health Centre</option> <option value="17900">Biftu Medical Clinic (Moyale)</option> <option value="10070">Bigem Clinic</option> <option value="14255">Bigot Medical Clinic</option> <option value="16361">Bikeke Helth Centre</option> <option value="16338">Bindura Dispensary</option> <option value="18666">Bingwa Dispensary</option> <option value="15163">Binyo Medical Clinic</option> <option value="19788">Biotisho Ang' Medical Clinic</option> <option value="14256">Biretwa Dispensary</option> <option value="14257">Biribiriet Dispensary</option> <option value="14258">Birunda (Lyavo Project) Clinic</option> <option value="11950">Bisan Biliqo Dispensary</option> <option value="11955">Bishop Kioko Catholic Hospital</option> <option value="14259">Bisil Health Centre</option> <option value="16311">Bismillahi Medical Clinic</option> <option value="19167">Bismillahi Medical Clinic (Garissa)</option> <option value="13502">Bitare Dispensary</option> <option value="17193">Bituyu Dispensary</option> <option value="13306">Biyamadhow Health Centre</option> <option value="10072">Blessed Louis Palazzolo Health Centre</option> <option value="19514">Blessed Medical Clinic</option> <option value="18180">Blue Haven Medical Clinic</option> <option value="12885">Blue House Dispensary</option> <option value="13307">Blue Light Nursing Home</option> <option value="10073">Blue Line Clinic</option> <option value="19016">Blue Nile Medical Clinic</option> <option value="18837">Bluebells Medical Clinic</option> <option value="17609">Blueturtle</option> <option value="19144">Boarder Medical Clinic Namanga</option> <option value="19561">Bodaki Health Centre</option> <option value="18805">Bodaki Medical Clinic</option> <option value="16558">Boddu Pharmacy Ltd</option> <option value="13308">Bodhai Dispensary</option> <option value="13503">Bodi Health Centre</option> <option value="11253">Bofu Dispensary</option> <option value="13504">Bogwendo Health Centre(Manga)</option> <option value="19359">Boi Dispensary</option> <option value="13505">Boige Health Centre</option> <option value="18280">Boito Dispensary</option> <option value="11951">Boji Dispensary</option> <option value="17072">Boka</option> <option value="16974">Bokimai Dispensary</option> <option value="11254">Bokole CDF Dispensary</option> <option value="16706">Bokoli Base Clinic</option> <option value="15808">Bokoli Hospital</option> <option value="14260">Boma La Tumaini VCT</option> <option value="11255">Bomani Dispensary</option> <option value="12886">Bomas of Kenya Dispensary</option> <option value="11256">Bombi Dispensary</option> <option value="16534">Bombolulu Staff Clinic</option> <option value="16184">Bombululu Medical Clinic</option> <option value="14261">Bomet Health Centre</option> <option value="19939">Bomet Youth Ffriendly Centre</option> <option value="11259">Bomu Medical Centre (Likoni)</option> <option value="18267">Bomu Medical Centre (Mariakani)</option> <option value="11258">Bomu Medical Hospital (Changamwe)</option> <option value="16441">Bona Medical Clinic</option> <option value="14262">Bonchoge Dispensary</option> <option value="13506">Bonde Dispensary</option> <option value="14263">Bondeni Dispensary (Nakuru Central)</option> <option value="14264">Bondeni Dispensary (Trans Nzoia West)</option> <option value="14265">Bondeni Maternity</option> <option value="13507">Bondo District Hospital</option> <option value="13508">Bondo Medical Clinic</option> <option value="18053">Bondo Nyironge Medical Clinic</option> <option value="18096">Bondo Town VCT</option> <option value="18097">Bondo University Clinic</option> <option value="18787">Bonjoge Disabled Group</option> <option value="17481">Bonjoge Dispensary</option> <option value="14266">Bonzina Medical Clinic</option> <option value="10074">Boore Clinic</option> <option value="13509">Bora Bora Clinic</option> <option value="19962">Bora Imani Medical Clinic</option> <option value="11260">Borabu Medical Clinic</option> <option value="13510">Borabu Nursing Home</option> <option value="14267">Borana Dispensary</option> <option value="13511">Borangi Health Centre</option> <option value="13512">Border Clinic</option> <option value="14268">Border Medical Care</option> <option value="13310">Bore Hole 11 Health Centre</option> <option value="17762">Borehole Five Dispensary</option> <option value="11952">Bori Dispensary</option> <option value="13513">Boro Dispensary</option> <option value="14269">Borrowonin Dispensary</option> <option value="18853">Boru Haro Model Health Centre</option> <option value="13514">Bosiango Health Centre</option> <option value="13515">Bosongo Hospital</option> <option value="14270">Bossei Dispensary</option> <option value="18074">Bosto Dispensary</option> <option value="13311">Bour-Algy Dispensary</option> <option value="20112">Bouti Dispensary</option> <option value="13516">Boya Nursing Home</option> <option value="15809">Boyani Dispensary</option> <option value="16811">Bp1 Dispensary</option> <option value="17731">Brase Clinic and Eye Centre</option> <option value="16208">Bravo Medical Clinic (Marsabit)</option> <option value="10075">Breeze Hospital</option> <option value="19537">Bridgeway Clinic</option> <option value="19405">Bridging Out-Patient</option> <option value="11954">Bright Clinic</option> <option value="18271">Bristal Park Hospital</option> <option value="18277">British American Tobacco Kenya Clinic</option> <option value="19922">Brooks Health Care Medical Clinic</option> <option value="12887">Brother andre Clinic</option> <option value="18750">Brown's Memorial Medical Centre</option> <option value="11956">Bubisa Dispensary</option> <option value="18120">Buburi Community Clinic</option> <option value="15810">Buchangu Dispensary</option> <option value="14271">Buchenge Dispensary</option> <option value="15811">Budalangi Dispensary</option> <option value="15812">Budonga Dispensary</option> <option value="15813">Buduta Dispensary</option> <option value="15814">Bugamangi Dispensary</option> <option value="11262">Bughuta Health Centre</option> <option value="15815">Bugina Health Centre</option> <option value="13517">Bugumbe Health Centre</option> <option value="15816">Bujumba Dispensary</option> <option value="17156">Bukalama Dispensary</option> <option value="15817">Bukaya Health Centre</option> <option value="15818">Bukaya Medical Centre</option> <option value="15819">Bukembe Dispensary</option> <option value="17158">Bukhalalire Dispensary</option> <option value="15820">Bukura Health Centre</option> <option value="17850">Bukura Medical Clinic</option> <option value="18315">Bukwala SDA Dispensary</option> <option value="11957">Bulesa Dispensary</option> <option value="19002">Bulla Game Medical Clinic and Laboratory</option> <option value="19003">Bulla Hagar Clinic</option> <option value="19168">Bulla Medina Clinic</option> <option value="19214">Bulla Mpya Nursing Home</option> <option value="17011">Bulla Mzuri Dispensary</option> <option value="19216">Bulla Tawakal Medical Clinic</option> <option value="16306">Bullampya Medical Clinic</option> <option value="15821">Bulondo Dispensary</option> <option value="16285">Bultohama Dispensary</option> <option value="15822">Bulwani Dispensary</option> <option value="15823">Bumala A Health Centre</option> <option value="15824">Bumala B Health Centre</option> <option value="15825">Bumula Health Centre</option> <option value="15826">Bumutiru Dispensary</option> <option value="13312">Buna Sub-District Hospital</option> <option value="13518">Bunde Dispensary</option> <option value="15827">Bungasi Health Centre</option> <option value="15828">Bungoma District Hospital</option> <option value="15829">Bungoma Medical Centre</option> <option value="14272">Bungwet Dispensary</option> <option value="13339">Bura District Hospital</option> <option value="11264">Bura Health Centre</option> <option value="11263">Bura Health Centre (Taita Taveta)</option> <option value="18312">Bura Health Centre Taita</option> <option value="11265">Bura Mission Clinic</option> <option value="17075">Bura Nomadic</option> <option value="17870">Burabor Dispensary</option> <option value="13313">Burder Health Centre</option> <option value="17035">Burduras Health Centre</option> <option value="18910">Burgabo Dispensary</option> <option value="18830">Burgabo Dispensary (Chalbi)</option> <option value="14273">Burgei Dispensary</option> <option value="10076">Burguret Dispensary</option> <option value="15830">Burinda Dispensary</option> <option value="19243">Burjon Dispensary</option> <option value="17228">Burmayo Dispensary</option> <option value="14274">Burnt Forest Catholic Dispensary</option> <option value="16342">Burnt Forest Medical Clinic</option> <option value="16347">Burnt Forest Rhdc (Eldoret East)</option> <option value="18033">Burqa Medical Clinic (Moyale)</option> <option value="16313">Buruburu Dispensary</option> <option value="18273">Buruburu Friends Clinic</option> <option value="12888">Buruburu Medical Clinic</option> <option value="16722">Burutu Dspensary</option> <option value="15831">Busembe Dispensary</option> <option value="15832">Bushiangala Health Centre</option> <option value="15833">Bushiri Health Centre</option> <option value="15834">Busia District Hospital</option> <option value="18126">Busia Trailer Park Clinic</option> <option value="15835">Busibwabo Dispensary</option> <option value="18208">Busieso Dispensary</option> <option value="13314">Bute District Hospital</option> <option value="19870">Bute Medical Clinic</option> <option value="15836">Butere District Hospital</option> <option value="18939">Butere Iranda Health Centre</option> <option value="14276">Butiik Dispensary</option> <option value="20043">Butingo Dispensary</option> <option value="11958">Butiye Dispensary</option> <option value="15837">Butonge Dispensary</option> <option value="15838">Butula Mission Health Centre</option> <option value="16559">Buuri Chemist / Laboratory</option> <option value="17081">Buwa</option> <option value="15839">Buyangu Health Centre</option> <option value="20188">Buyemi Dispensary</option> <option value="11266">Bwagamoyo Dispensary</option> <option value="15840">Bwaliro Dispensary</option> <option value="13519">Bware Dispensary</option> <option value="19756">Bwayi Dispensary</option> <option value="14277">Bwena Dipensary</option> <option value="17894">Bwiti (Tiomin) Dispensary</option> <option value="10077">By Faith Clinic (Kirinyaga)</option> <option value="10078">By Faith Clinic (Thika)</option> <option value="19229">By Faith Medical Centre</option> <option value="11959">By Faith Medical Clinic</option> <option value="10079">By Grace Medical (Kutus) Clinic</option> <option value="20014">Bygrace Medical Clinic</option> <option value="17763">California Medical Clinic</option> <option value="17978">Calvary Family Health Care Centre</option> <option value="17812">Calvary Medical Clinic</option> <option value="14278">Camp Brethren Medical Clinic</option> <option value="11269">Camp David Medical Clinic</option> <option value="12889">Cana Family Life Clinic</option> <option value="14279">Canaan (ACK) Medical Clinic</option> <option value="15841">Canaan Clinic (Matete)</option> <option value="12890">Canaan Health Providers (Nairobi)</option> <option value="11270">Canaan Medical Clinic</option> <option value="10080">Canan Medical Clinic</option> <option value="16176">Care Medical Clinic</option> <option value="17563">Care Medical Clinic (Geta Bush)</option> <option value="17562">Care Medical Clinic (Munyaka)</option> <option value="20016">Careplus Medical Services</option> <option value="18006">Cargo Human Care Clinic</option> <option value="10081"><NAME></option> <option value="15842"><NAME> Clinic</option> <option value="12891">Carolina For Kibera VCT</option> <option value="18043">Catholic Archdiocese of Mombasa CHBC & AIDS Relief</option> <option value="11960">Catholic Dispensary (Isiolo)</option> <option value="18484">Catholic Dispensary Kariobangi</option> <option value="15769">Catholic Hospital Wamba</option> <option value="17922">Catholic Mission Dispensary</option> <option value="12456">Catholic Mission Dispensary Makueni</option> <option value="12892">Catholic University Dispensary</option> <option value="19919">Catmag Medical Centre</option> <option value="19689">Causqurow Medical Clinic</option> <option value="11272">Cbk Staff Clinic (Mombasa)</option> <option value="19072">Ccm Kaare</option> <option value="11963">Ccs (ACK) Dispensary</option> <option value="11964">Ccs Kiritiri Clinic</option> <option value="16242">Ccs Macumo Clinic</option> <option value="18378">Cdn VCT</option> <option value="14280">Cedar Associate Clinic</option> <option value="14281">Cedar Medical Clinic (Kimana)</option> <option value="14283">Cengalo Dispensary</option> <option value="19974">Central Bank Staff Clinic</option> <option value="13520">Central Clinic (Kisumu East)</option> <option value="15843">Central Clinic (Lugari)</option> <option value="10082">Central Health Clinic</option> <option value="11965">Central Medical Clinic</option> <option value="18903">Central Medical Clinic (Kitui Central)</option> <option value="19578">Central Medical Clinic (Nairobi)</option> <option value="17696">Central Medical Clinic and Labaratory (Changamwe)</option> <option value="10083">Central Memorial Hospital</option> <option value="19531">Central Park Clinic</option> <option value="20154">Centre medical clinic</option> <option value="19985">CFW Clinic</option> <option value="19938">CFW Kiamugumo Glory</option> <option value="11966">CFW Kimangaru Clinic</option> <option value="19225">CFW Mbuvori Clinic</option> <option value="19841">CFW Mwea Clinic</option> <option value="11274">Chaani (MCM) Dispensary</option> <option value="17223">Chabuene Dispensary</option> <option value="16475">Chagaik Dispensary</option> <option value="14284">Chagaiya Dispensary</option> <option value="17573">Chaka Health Services Clinic</option> <option value="11276">Chakama Dispensary</option> <option value="11277">Chala Dispensary (Taita Taveta)</option> <option value="16191">Chalani Dispensary</option> <option value="11278">Challa Dispensary</option> <option value="10086">Chalo Medical Clinic</option> <option value="15845">Chamakanga Mission</option> <option value="14285">Chamalal Dispensary</option> <option value="19339">Chamamo Medical Clinic</option> <option value="11279">Chamari CDF Dispensary</option> <option value="18782">Chamuka (CDF) Dispensary</option> <option value="12893">Chandaria Health Centre</option> <option value="12621">Chandaria Mwania Dispensary</option> <option value="14286">Changach Barak Dispensary</option> <option value="11280">Changamwe Maternity</option> <option value="16421">Changara (GOK) Dispensary</option> <option value="15846">Changara Calvary Dispensary</option> <option value="14287">Changoi Dispensary</option> <option value="10087">Chania Clinic</option> <option value="10088">Chania Obstetrics Gyno Clinic</option> <option value="19772">Chania Optical</option> <option value="11281">Charidende Dispensary (CDF)</option> <option value="10089">Charity Medical Centre</option> <option value="10090">Charity Medical Clinic</option> <option value="11967">Charuru Dispensary</option> <option value="11282">Chasimba Health Centre</option> <option value="15847">Chavogere Mission</option> <option value="14288">Chebaiwa Dispensary</option> <option value="14289">Chebangang Health Centre</option> <option value="14290">Chebango Dispensary</option> <option value="14291">Chebaraa Dispensary</option> <option value="14292">Cheberen Dispensary</option> <option value="14293">Chebewor Dispensary</option> <option value="14294">Chebiemit District Hospital</option> <option value="14295">Chebilat Dispensary</option> <option value="17131">Chebilat Dispensary (Nandi South)</option> <option value="14296">Chebirbei Dspensary</option> <option value="14297">Chebirbelek Dispensary</option> <option value="14298">Chebitet Dispensary</option> <option value="19849">Cheboet Dispensary</option> <option value="20060">Cheboin Dispensary</option> <option value="18236">Cheboin Dispensary (Bureti)</option> <option value="19155">Chebon Medical Clinic</option> <option value="14300">Cheborgei Health Centre</option> <option value="14301">Chebororwa Health Centre</option> <option value="14302">Cheboyo Dispensary</option> <option value="15848">Chebukaka Dispensary</option> <option value="20159">Chebukwabi Dispensary</option> <option value="14303">Chebulbai Dispensary</option> <option value="14304">Chebunyo Dispensary</option> <option value="15849">Chebwai Mission Dispensary</option> <option value="14305">Chechan Dispensary</option> <option value="11968">Cheera Dispensary</option> <option value="14306">Chegilet Dispensary</option> <option value="15850">Chegulo Dispensary</option> <option value="14307">Cheindoi Dispensary</option> <option value="15851">Chekalini Dispensary</option> <option value="14308">Chelelach Dispensary</option> <option value="15852">Chelelemuk (St.Boniface Mwanda B) Dispensary</option> <option value="14309">Chelilis Dispensary</option> <option value="17328">Chemamit Dispensary</option> <option value="14310">Chemamul Dispensary</option> <option value="19207">Chemamul Dispensary (Tinderet)</option> <option value="14311">Chemaner Dispensary (Bomet)</option> <option value="14312">Chemaner Dispensary (Kuresoi)</option> <option value="14313">Chemartin Tea Dispensary</option> <option value="14314">Chemase Dispensary</option> <option value="14315">Chemase Health Centre</option> <option value="15853">Chemasiri (ACK) Dispensary</option> <option value="14316">Chemasis Maternity Home</option> <option value="10091">Chemat For Health Solutions Kamweti</option> <option value="14317">Chembulet Health Centre</option> <option value="17319">Chemegong</option> <option value="14318">Chemelil Dispensary</option> <option value="13521">Chemelil GOK Dispensary</option> <option value="13522">Chemelil Sugar Health Centre</option> <option value="16521">Chemichemi Medical Clinic</option> <option value="19837">Chemichemi Medical Clinic (Nyandarua)</option> <option value="16267">Chemin Clinic</option> <option value="20150">Chemobo dispensary</option> <option value="14319">Chemogondany Hospital</option> <option value="14320">Chemoiben Dispensary</option> <option value="17095">Chemoinoi Dispensary</option> <option value="14321">Chemolingot District Hospital</option> <option value="14322">Chemomi Tea Dispensary</option> <option value="14323">Chemosot Health Centre</option> <option value="18584">Chemses Dispensary</option> <option value="16731">Chemsik Dispensary</option> <option value="14324">Chemundu Dispensary (Nandi Central)</option> <option value="14325">Chemursoi Dispensary</option> <option value="14326">Chemuswo Dispensary</option> <option value="18563">Chemwa Bridge Dispensary</option> <option value="17782">Chemwokter Dispensary</option> <option value="18583">Chemworemwo Dispensary</option> <option value="14327">Chemworor Health Centre</option> <option value="14328">Chepakundi Dispensary</option> <option value="14329">Chepareria (SDA) Dispensary</option> <option value="14330">Chepareria Sub District Hospital</option> <option value="14331">Chepchabas Dispensary</option> <option value="14332">Chepchoina Dispensary</option> <option value="14333">Chepcholiet Dispensary</option> <option value="14334">Chepgoiben Dispensary</option> <option value="16727">Chepkalacha Dispensary</option> <option value="14335">Chepkanga Health Centre</option> <option value="14336">Chepkechir Dispensary</option> <option value="14337">Chepkemel Dispensary</option> <option value="14338">Chepkemel Health Centre (Kericho)</option> <option value="14339">Chepkemel Health Centre (Mosop)</option> <option value="14340">Chepkero Dispensary</option> <option value="14341">Chepkigen Dispensary</option> <option value="14343">Chepkoilel Campus Dispensary</option> <option value="18188">Chepkoiyo</option> <option value="14344">Chepkoiyo Dispensary</option> <option value="14345">Chepkongony Dispensary</option> <option value="19011">Chepkono Medical Clinic</option> <option value="14342">Chepkopegh Dipensary</option> <option value="14346">Chepkorio Health Centre</option> <option value="14347">Chepkoton Dispensary</option> <option value="15854">Chepkube Dispensary</option> <option value="14348">Chepkumia Dispensary</option> <option value="14349">Chepkunan Clinic</option> <option value="14351">Chepkunyuk Dispensary</option> <option value="14350">Chepkunyuk Dispensary (Kipkelion)</option> <option value="20149">Chepkurngung Dispensary</option> <option value="14352">Cheplambus Dispensary</option> <option value="14353">Cheplanget Dispensary</option> <option value="14354">Cheplaskei Dispensary</option> <option value="17239">Cheplelabei Dispensary</option> <option value="17629">Cheplengu Dispensary</option> <option value="13523">Chepngombe Health Centre</option> <option value="14355">Chepngoror Dispensary</option> <option value="19246">Chepnoet Clinic</option> <option value="19244">Chepnoet Private Clinic</option> <option value="14356">Chepnyal Dispensary</option> <option value="14357">Cheppemma (AIC) Dispensary</option> <option value="14358">Chepsaita Dispensary</option> <option value="14359">Chepseon Dispensary</option> <option value="14360">Chepseon Health Care Clinic</option> <option value="14361">Chepseon Medical Clinic</option> <option value="16469">Chepseon-VCT Site</option> <option value="14362">Chepsir Dispensary</option> <option value="18497">Chepsire Dispensary</option> <option value="14363">Chepsiro Dispensary</option> <option value="17310">Chepsoo</option> <option value="14364">Cheptabach Dispensary</option> <option value="14365">Cheptabes Dispensary</option> <option value="18891">Cheptais Clinic</option> <option value="15855">Cheptais Sub District Hospital</option> <option value="14366">Cheptalal Sub-District Hospital</option> <option value="17334">Cheptangulgei Dispensary</option> <option value="19750">Cheptantan Dispensary</option> <option value="18467">Cheptarit Dispensary</option> <option value="19248">Cheptarit Med Clinic</option> <option value="14367">Cheptebo Dispensary</option> <option value="14368">Chepterit Mission Health Centre</option> <option value="14369">Chepterwai Sub-District Hospital</option> <option value="14370">Chepterwo Dispensary</option> <option value="17830">Cheptigit Dispensary</option> <option value="14371">Cheptil Dispensary</option> <option value="17013">Cheptilil Dispensary</option> <option value="17024">Cheptingwich Dispensary</option> <option value="14372">Cheptobot Dispensary</option> <option value="14373">Cheptongei Dispensary</option> <option value="14374">Cheptuech Dispensary</option> <option value="14375">Cheptuiyet Dispensary</option> <option value="16701">Chepturnguny Dispensary</option> <option value="16736">Chepturu Dispensary</option> <option value="14376">Chepwostuiyet Dispensary</option> <option value="14377">Cheramei Dispensary</option> <option value="14378">Cherangan Dispensary</option> <option value="14379">Cherangany Health Centre</option> <option value="14380">Cherangany Nursing Home</option> <option value="19760">Cherangany Nursing Home Outpatient Clinic</option> <option value="14381">Cherara Dispensary</option> <option value="17144">Cheronget</option> <option value="16680">Chesetan Dispensary</option> <option value="15856">Chesikaki Dispensary</option> <option value="14382">Chesinende (Elck) Dispensary</option> <option value="18582">Chesinende Dispensary</option> <option value="20107">Chesinende Health Services</option> <option value="16728">Chesirimion Dispensary</option> <option value="14383">Chesiyo Dispensary</option> <option value="14384">Chesoen Dispensary</option> <option value="19249">Chesogor Medical Clinic/Chemist</option> <option value="14385">Chesoi Health Centre</option> <option value="16336">Chesoi Medical Clinic</option> <option value="17018">Chesongo Dispensary</option> <option value="14386">Chesongoch Health Centre</option> <option value="14387">Chesta Dispensary</option> <option value="14388">Chesubet Dispensary</option> <option value="17358">Chesunet Dispensary</option> <option value="17047">Chesupet Dispensary</option> <option value="15857">Chevoso Dispensary</option> <option value="11283">Chewani Dispensary</option> <option value="11284">Chewele Dispensary</option> <option value="11969">Chiakariga H/C</option> <option value="18564">Chianda Dispensary (Rarieda)</option> <option value="11285">Chifiri Dispensary (LATIF)</option> <option value="13524">Chiga Dispensary</option> <option value="19504">Child Doctor Kenya</option> <option value="18443">Child Welfare Society of Kenya Medical Clinic</option> <option value="17951">Children Medical Clinic (Kasarani)</option> <option value="18329">Children's Support Centre Emurembe</option> <option value="11286">Chimbiriro Clinic</option> <option value="15858">Chimoi Health Centre</option> <option value="13525">China Dispensary</option> <option value="13526">Chinato Dispensary</option> <option value="19589">Chiromo Medical Centre</option> <option value="15584">Chitugul Medical Clinic</option> <option value="11287">Chizi Medical Clinic</option> <option value="11970">Chogoria (PCEA) Hospital</option> <option value="19169">Choice Health Care</option> <option value="15859">Chombeli Health Centre</option> <option value="17418">Chomei Medical Clinic</option> <option value="19035">Chonesus Clinic</option> <option value="17282">Chororget Dispensary</option> <option value="19812"><NAME> Clinic</option> <option value="17824">Christ The Healer</option> <option value="18483">Christamarianne Medical Clinic (Suneka)</option> <option value="13527">Christamarianne Mission Hospital</option> <option value="12895">Christian Aid Dispensary</option> <option value="10092">Christian Community Services Clinic Base Kerugoya</option> <option value="10093">Christian Community Services Wang'uru Dispensary</option> <option value="18270">Christian Partners Development Agency VCT</option> <option value="11971">Chugu Dispensary</option> <option value="14389">Chuiyat Dispensary</option> <option value="11972">Chuka Cottage Hospital</option> <option value="11973">Chuka District Hospital</option> <option value="18789">Chuka University Dispensary</option> <option value="17769">Chuka Unversity Dispensary</option> <option value="14390">Chukura Dispensary</option> <option value="13528">Chulaimbo Sub-District Hospital</option> <option value="11974">Chuluni Dispensary</option> <option value="11288">Chumani Medical Clinic</option> <option value="14391">Chumvi Dispensary</option> <option value="13529">Chuowe Dispensary</option> <option value="18795">Church Army Medical Clinic</option> <option value="14392">Churo Dispensary</option> <option value="20047">Churo GOK Dispensary</option> <option value="13530">Chuthber Dispensary</option> <option value="15861">Chwele Friends Dispensary</option> <option value="15860">Chwele Health Centre</option> <option value="10096">Ciagini Dispensary</option> <option value="11975">Ciama Medical Clinic</option> <option value="10097">Cianda Dispensary</option> <option value="18629">Cid Hqs Dispensary</option> <option value="12897">Cidi Mukuru Clinic</option> <option value="19641">City Point Medical Clinic</option> <option value="14393">Civil Servant Dc Headquarter Dispensary</option> <option value="17985">Civil Servants Clinic (Nakuru)</option> <option value="18901">Clay Hill Hospital</option> <option value="12898">Clinitec Medical Services</option> <option value="17388">Clinix Health Care</option> <option value="18754">Clinix Health Care (Kibera)</option> <option value="19071">Clinix Health Care Limited (Meru)</option> <option value="19407">Clinix Medical Centre Isiolo</option> <option value="18917">Clinix Medical Clinic (Machakos)</option> <option value="14394">Cmf Aitong Health Centre</option> <option value="11289">Coast Province General Hospital</option> <option value="10101">Coffee Research Staff Dispensary</option> <option value="18745">Comboni Missionary Sisters Health Programm</option> <option value="19200">Comet Medical Clinic</option> <option value="18748">Comfort The Chidren International (Ctc) Naivasha</option> <option value="19455">Communal Oriented Service International Centre</option> <option value="20079">Community Action for Rural Developement VCT</option> <option value="18384">Community Counselling Resource Centre</option> <option value="19697">Community Diagnostic Medical Centre</option> <option value="12901">Community Health Foundation</option> <option value="14395">Community Medical and Lab Services Clinic</option> <option value="16536">Community Medical Centre (Kongowea)</option> <option value="12902">Compassionate Hospital</option> <option value="10098">Complex Medical Centre</option> <option value="10099">Comrade Nurising Home</option> <option value="12903">Conerstone Clinic</option> <option value="12958">Coni Health Centre</option> <option value="19450">Connections Medical Clinic</option> <option value="14396">Consolata Clinic</option> <option value="11976">Consolata Hospital (Nkubu)</option> <option value="12413">Consolata Kyeni Hospital</option> <option value="14397">Consolata Medical Clinic (Eldoret South)</option> <option value="10100">Consolata Mission Hospital (Mathari)</option> <option value="18888">Consolata Shrine Dispensary (Deep Sea Nairobi)</option> <option value="20148">Copeman Health Care Centre</option> <option value="18579">Coping Centre</option> <option value="12905">Coptic Hospital (Ngong Road)</option> <option value="12904">Coptic Medical Clinic</option> <option value="15862">Coptic Nursing Home</option> <option value="19439">Corban Health Care</option> <option value="19722">Cordis Maria Dispensary</option> <option value="11291">Corner Chaani Medical Clinic</option> <option value="18313">Corner Clinic</option> <option value="19470">Corner Hse Med Laboratory</option> <option value="16537">Corner Medical Clinic</option> <option value="12906">Corner Stone</option> <option value="11292">Cornerstone Medical Clinic</option> <option value="18474">Cornerstone Medical Clinic (Nyeri Central)</option> <option value="18119">Cornestone Baptist Clinic</option> <option value="12907">Cotolengo Centre</option> <option value="11977">Cottolengo Mission Hospital</option> <option value="18546">County Medical Centre - Embu Ltd</option> <option value="19843">County Medical Clinic (Kangai)</option> <option value="19217">County Medical Clinic and Lab Services</option> <option value="19153">County Medical Clinic and Lab Sevices</option> <option value="19842">County Medical Health Clinic (Wanguru)</option> <option value="18812">County Medicare Ltd (Maralal Nursing Home)</option> <option value="18794">Couple Counselling Centre</option> <option value="11978">Courtesy Community Based Health Services</option> <option value="11293">Cowdray Dispensary</option> <option value="14398">Crater Medical Centre</option> <option value="18549">Creadis Htc Centre</option> <option value="19486">Credible Health Centre</option> <option value="19392">Crescent Medical Aid (Jamia Towers)</option> <option value="12900">Crescent Medical Aid (Pangani)</option> <option value="19634">Crescent Medical Aid Kenya Korogocho Clinic</option> <option value="12899">Crescent Medical Aid Murang'a Road</option> <option value="19685">Crescent-Davina Med Clinic</option> <option value="19721">Crestwood Medical Clinic</option> <option value="11979">Crossroad Nursing Home</option> <option value="19301">Crow Medical Centre</option> <option value="16538">Crystal Medical Centre</option> <option value="14399">Crystal Medical Clinic</option> <option value="10102">Cura (ACK) Medical Clinic</option> <option value="17402">Cura Medical Clinic</option> <option value="17397">Cure (AIC) International Children's Hospital</option> <option value="11980">Curran Dispensary</option> <option value="19238">Current Medical Ciinic</option> <option value="11981">D Comboni Mission</option> <option value="11296">Daba (AIC) Dispensary</option> <option value="11982">Dabel Health Centre (Moyale)</option> <option value="12908">Dabliu Clinic</option> <option value="13315">Dadaab Clinic</option> <option value="13316">Dadaab Sub-District Hospital</option> <option value="13317">Dadajabula Sub District Hospital</option> <option value="13318">Dagahaley Hospital</option> <option value="17006">Dagahley Dispensary</option> <option value="11297">Dagamra Dispensary</option> <option value="16186">Dagamra Medical Clinic</option> <option value="12909">Dagoretti Approved Dispensary</option> <option value="20189">Dagoretti Community Dispesary</option> <option value="11983">Dakabaricha Dispensary</option> <option value="17472">Dakarh Medical Services</option> <option value="16809">Dal-Lahelay Nomadic Clinic</option> <option value="13319">Daley Dispensary</option> <option value="11984">Dallas Dispensary</option> <option value="19068">Dalsan Medical Clinic</option> <option value="18995">Dam Pharmacy and Clinic</option> <option value="13320">Damajale Dispensary</option> <option value="11985">Dambalafachana Health Centre</option> <option value="13321">Dambas Health Centre</option> <option value="19545">Damic Dental X-Ray Services</option> <option value="13322">Danaba Health Centre</option> <option value="19798">Danama Medical Clinic</option> <option value="12911">Dandora (EDARP) Clinic</option> <option value="17997">Dandora Health Service</option> <option value="12913">Dandora I Health Centre</option> <option value="12912">Dandora II Health Centre</option> <option value="19617">Dandora Medical and Laboratory Services (Kojwang)</option> <option value="18220">Dandora Medical Centre</option> <option value="13323">Dandu Health Centre</option> <option value="11298">Danrose Clinic</option> <option value="13324">Danyere Health Centre</option> <option value="19703">Dap Health Clinic</option> <option value="13531">Daraja Medical Clinic</option> <option value="18842">Darajani Medical Clinic</option> <option value="18276">Darushif Medical Clinic</option> <option value="13325">Dasheq Dispensary</option> <option value="16498">Dave Laboratory</option> <option value="11632">David Kariuki Medical Centre</option> <option value="11457">David Kayanda Dispensary</option> <option value="19596">Dawa Jema Medical Cl</option> <option value="19240">Dawa Mart Clinic</option> <option value="10104">Dawa Medical Clinic (Nyeri South)</option> <option value="11299">Dawida Maternity Nursing Home</option> <option value="11300">Dawson Mwanyumba Dispensary</option> <option value="15863">Day Light Clinic</option> <option value="20195">DEBOMART MED CLINIC</option> <option value="13532">Dede Dispensary</option> <option value="10105">Del Monte Dispensary</option> <option value="14401">Delamere Clinic</option> <option value="19377">Delight Chemist & Lab</option> <option value="10106">Delina Health Care</option> <option value="12915">Delta Medical Clinic Dandora</option> <option value="11302">Dembwa Dispensary</option> <option value="19105">Dental Clinic Dr Mwiti Jm</option> <option value="19343">Dental Surgery Kitengela</option> <option value="19694">Dentmind Dental Clinic Kitengela</option> <option value="14402">Dentomed Clinic</option> <option value="18457">Derkale Dispensary</option> <option value="13327">Dertu Health Centre</option> <option value="13326">Dertu Medical Clinic</option> <option value="17949">Destiny Medical Centre (Ruaraka)</option> <option value="18839">Destiny Medical Clinic</option> <option value="19717">Destiny Medical Clinic (Kinoro-Imenti South)</option> <option value="17537">Deteni Medical Clinic</option> <option value="17904">Devki Staff Clinic</option> <option value="19265">Devki Staff Clinic (Ruiru)</option> <option value="20143">Devlink Africa VCT, Mbita</option> <option value="19004">Dhanun Clinic</option> <option value="19874">Dhmt</option> <option value="19516">Dhs Ghataura</option> <option value="10108">Diana Medical Clinic</option> <option value="18499">Diani Beach Hospital</option> <option value="12916">Diani Dispensary</option> <option value="11304">Diani Health Centre</option> <option value="18897">Dice Clinic Migori</option> <option value="11305">Dida Dispensary</option> <option value="11306">Didewaride Dispensary</option> <option value="13533">Dienya Health Centre</option> <option value="10109">Difathas Catholic Dispensary</option> <option value="10110">Difathas Health Centre</option> <option value="13328">Diff Health Centre</option> <option value="19210">Digfer Nursing Home</option> <option value="14403">Diguna Dispensary</option> <option value="13329">Dilmanyaley Health Centre</option> <option value="16561">Diplomat Clinic</option> <option value="18723">Diplomatic Medical Clinic</option> <option value="11986">Dirib Gombo Dispensary</option> <option value="16268">Diruma Dispensary</option> <option value="13534">Disciples of Mercy Clinic</option> <option value="17663">Discordant Couples of Kenya VCT</option> <option value="19074">District Public Health Office (Meru)</option> <option value="19109">Divine Mercy Catholic Dispensary</option> <option value="11308">Divine Mercy Dispensary</option> <option value="11365">Divine Mercy Eldoro (Catholic) Dispensary</option> <option value="18388">Divine Mercy Kariobangi</option> <option value="12351">Divine Mercy Kithatu Dispensary</option> <option value="12917">Diwopa Health Centre</option> <option value="12918">Dod Mrs Dispensary</option> <option value="12919">Dog Unit Dispensary (O P Kenya Police)</option> <option value="14404">Doldol Sub District Hospital</option> <option value="13535">Dolphil Nursing & Maternity Home</option> <option value="19136">Dom Spark</option> <option value="10111">Dommy Medical Clinic</option> <option value="10112">Don Bosco Catholic Dispensary</option> <option value="11987">Don Bosco Clinic</option> <option value="10113">Dona Medical Clinical</option> <option value="16432">Donyo Sabuk Dispensary</option> <option value="11988">Donyo Sabuk Nursing Home</option> <option value="16562">Dorjos Health Services</option> <option value="16563">Dorjos Laboratory</option> <option value="12921">Dorkcare Nursing Home</option> <option value="10116">Dr <NAME> Radiological Clinic</option> <option value="11310">Dr <NAME>ana Clinic</option> <option value="19549">Dr <NAME></option> <option value="19581">Dr <NAME></option> <option value="10117">Dr <NAME> Medical Clinic</option> <option value="19674">Dr <NAME></option> <option value="14405">Dr Aluvaala Medical Clinic</option> <option value="16243">Dr <NAME> Clinic</option> <option value="11312">Dr <NAME>linic</option> <option value="14406">Dr Arthur (PCEA) Dispensary</option> <option value="19559">Dr Ashwin Clinic</option> <option value="19584">Dr <NAME>atel</option> <option value="11313">Dr Awimbo E Clinic</option> <option value="12924">Dr Aziz MOHamed Medical Clinic</option> <option value="11140">Dr <NAME></option> <option value="19532">Dr Barads Clinic</option> <option value="20086">Dr Barnados House clinic</option> <option value="11314">Dr <NAME> Clinic</option> <option value="19585">Dr <NAME></option> <option value="11316">Dr <NAME>ic</option> <option value="19418">Dr Chaundry Dental Services (Nairobi)</option> <option value="19577">Dr <NAME></option> <option value="19558">Dr <NAME></option> <option value="19575">Dr <NAME></option> <option value="19564">Dr <NAME> Clinic</option> <option value="11318">Dr Dhanji Clinic</option> <option value="11319">Dr <NAME>linic</option> <option value="11320">Dr Dosajee Medical Clinic</option> <option value="11321">Dr <NAME>linic</option> <option value="10119">Dr <NAME>ediatric Clinic</option> <option value="10120">Dr <NAME> Dental Clinic</option> <option value="19565">Dr <NAME> (Parklands)</option> <option value="18003">Dr Eshtera Clinic</option> <option value="19851">Dr <NAME>i Medical Clinic</option> <option value="19588">Dr Fatema</option> <option value="18778">Dr <NAME> (Ngong Road)</option> <option value="17235">Dr <NAME> Clinic</option> <option value="12922">Dr Gachare Medical Clinic</option> <option value="14408">Dr Gacheru Clinic</option> <option value="10121">Dr Gachiri</option> <option value="11324">Dr Gathuo Clinic</option> <option value="19425">Dr <NAME> Medical Clinic</option> <option value="19567">Dr <NAME></option> <option value="19586">Dr Giddie</option> <option value="11325">Dr Gikandi Clinic</option> <option value="11326">Dr <NAME> Clinic</option> <option value="11327">Dr Gupta Clinic</option> <option value="11328">Dr Hassannali Clinic</option> <option value="19563">Dr <NAME></option> <option value="19783">Dr <NAME> Clinic</option> <option value="18807">Dr Irimu</option> <option value="10122">Dr <NAME> Dermatology Clinic</option> <option value="19961">Dr <NAME></option> <option value="11329">Dr <NAME></option> <option value="17292">Dr <NAME></option> <option value="19522">Dr <NAME> Clinic (Nairobi)</option> <option value="19687">Dr <NAME> Mc</option> <option value="19468">Dr Jemmah & Nyawange Med Clinic</option> <option value="10124">Dr Juma Clinic</option> <option value="11331">Dr <NAME>ora Clinic</option> <option value="11332">Dr Kaguta Clinic</option> <option value="14409">Dr Kalyas Clinic</option> <option value="11333">Dr Kamande Clinic</option> <option value="11334">Dr Kandwalla Clinic</option> <option value="10125">Dr <NAME> K Urology Clinic</option> <option value="14410">Dr Kanyiri Dental Clinic</option> <option value="14411">Dr Karania Medical Clinic</option> <option value="11335">Dr Karima Clinic</option> <option value="10126">Dr Kariuki</option> <option value="10127">Dr Kariuki N M Psychiatric Clinic</option> <option value="11336">Dr Kariuki R F Clinic</option> <option value="19690">Dr <NAME></option> <option value="19661">Dr <NAME></option> <option value="18724">Dr Kiara Medical Clinic</option> <option value="18716">Dr Kiara Medical Clinic</option> <option value="14412">Dr Kibe Medical Clinic</option> <option value="19780">Dr Kibec Clinic</option> <option value="10128">Dr <NAME> Clinic</option> <option value="19982">Dr Kingondu Clinic (Westlands)</option> <option value="18633">Dr Kiome Clinic</option> <option value="16564">Dr Kiomes Clinic</option> <option value="19666">Dr Kiptum Medical Clinic</option> <option value="11337">Dr Kirash Shah Clinic</option> <option value="11338">Dr Kirima Clinic</option> <option value="19568">Dr Kishor J D Medical Centre</option> <option value="10129">Dr L G Mburu Radiological Clinic</option> <option value="10130">Dr L L M Muturi Medical Clinic</option> <option value="17768">Dr <NAME>aria Dental Clinic</option> <option value="19797">Dr L N Wagana Clinic</option> <option value="19587">Dr <NAME>oli</option> <option value="10131">Dr M H Shah Medical Clinic</option> <option value="10132">Dr <NAME>i Opthamological Clinic</option> <option value="10133">Dr <NAME>ae / Obstretric Clinic</option> <option value="19420">Dr <NAME>ya Medical Clinic (Nairobi)</option> <option value="10134">Dr Macharia</option> <option value="11339">Dr Mahero Clinic</option> <option value="10135">Dr Maina</option> <option value="20106">Dr Maina Ruga Medical Clinic</option> <option value="19419">Dr Maina Skin Clinic (Ngara)</option> <option value="14413">Dr Manyara Clinic</option> <option value="11341">Dr Marami Clinic</option> <option value="19573">Dr Maroo</option> <option value="10136">Dr Mate Gynae/Obstetic Clinic</option> <option value="19646">Dr Mboloi Clinic</option> <option value="14414">Dr Mbuthia Clinic</option> <option value="19501">Dr Minesh Shah Dental Surgeon</option> <option value="11343">Dr Miyalla Clinic</option> <option value="12925">Dr MOHamed Clinic</option> <option value="12926">Dr Montet Medical Clinic</option> <option value="12927">Dr Muasya Medical Clinic</option> <option value="14415">Dr Mugo Medical Clinic</option> <option value="19981">Dr Muhindi Clinic (Westlands)</option> <option value="10137">Dr Muhiu Medical Clinic</option> <option value="10139">Dr Mukui</option> <option value="10141">Dr Mukui F K Psychiatric Clinic</option> <option value="10142">Dr Mulingwa</option> <option value="10143">Dr Muraya Clinic</option> <option value="19979">Dr Mureithi Clinic (Westlands)</option> <option value="19221">Dr Mushtaq Muhammad</option> <option value="19416">Dr Musili Clinic (Afya Centre-Nairobi)</option> <option value="11344">Dr <NAME> Clinic</option> <option value="14416">Dr Muthiora Clinic</option> <option value="18728">Dr <NAME> Clinic</option> <option value="11989">Dr Mutuma Medical Clinic</option> <option value="10144">Dr Mwangi Medical Clinic</option> <option value="11345">Dr N Mwangome Clinic</option> <option value="10145">Dr N N Ngugi Dental Clinic</option> <option value="16353">Dr Nabakwe Clinic</option> <option value="11346">Dr Nahif Maamry Clinic</option> <option value="10146">Dr Ndambuki Clinic</option> <option value="19809">Dr Ndambuki Clinic</option> <option value="19095">Dr Ndanya Medical Clinic</option> <option value="10147">Dr Ndungu Wamburu Clinic</option> <option value="19569">Dr Ngathia Dental Clinic</option> <option value="16565">Dr Ngatia's Clinic</option> <option value="14418">Dr Ngotho Medical Clinic</option> <option value="10148">Dr Nguhiu</option> <option value="14419">Dr Njoroge Clinic</option> <option value="10149">Dr Njue M G Pathological Clinic</option> <option value="10150">Dr Njuguna Thuo Gynae/ Obstetic Clinic</option> <option value="16355">Dr Nyandiko Clinic</option> <option value="19423">Dr Nzuki Hildapaed Clinic</option> <option value="18182">Dr Ogaro Medical Clinic</option> <option value="20122">Dr Ogindo's Clinic</option> <option value="11348">Dr Okanga J B O</option> <option value="16781">Dr P K Kapombe Dental Clinic</option> <option value="10151">Dr P M Mbugua</option> <option value="19426">Dr Parmar Clinic</option> <option value="19480">Dr Parmar Medical Clinic (Nairobi)</option> <option value="20105">Dr <NAME> Clinic</option> <option value="19534">Dr <NAME></option> <option value="19570">Dr Prayerful Patel</option> <option value="19062">Dr <NAME></option> <option value="16539">Dr <NAME></option> <option value="19576">Dr <NAME> Dental Clinic</option> <option value="11352">Dr <NAME></option> <option value="19583">Dr Sajay</option> <option value="19675">Dr <NAME> (Kitale Medical Centre)</option> <option value="19579">Dr <NAME></option> <option value="11353">Dr <NAME>linic</option> <option value="18183">Dr Sharma Medical Clinic</option> <option value="11354">Dr <NAME></option> <option value="11355">Dr <NAME></option> <option value="14422">Dr <NAME>ic</option> <option value="19571">Dr <NAME> Medical Clinic</option> <option value="19781">Dr Thuo Clinic</option> <option value="19177">Dr Thuo's Clinic Kitengela</option> <option value="10115">Dr U N Kanani Dental Clinic</option> <option value="10153">Dr <NAME> Orthopaedic Clinic</option> <option value="11356">Dr <NAME> Sur Clinic</option> <option value="10154">Dr Wachira</option> <option value="10155">Dr Waihenya</option> <option value="10156">Dr Wanjohi</option> <option value="16797">Dr Waris</option> <option value="14423">Dr <NAME>linic</option> <option value="12928">Dr Were Medical Clinic</option> <option value="11357">Dr Yossa Clinic</option> <option value="11358">Dr Yunus Clinic</option> <option value="18981">Dr <NAME> Clinic</option> <option value="18429">Dr <NAME></option> <option value="15864">Dreamland Mc Health Centre</option> <option value="18389">Dreamline Medical Clinic Kamulu</option> <option value="12929">Dreams Centre Dispensary (Langata)</option> <option value="18481">DRIC (Naivasha)</option> <option value="20059">Drop In Service Centre</option> <option value="16668">Drop Inn Ray Clinic</option> <option value="16307">Drugmart Medical Clinic</option> <option value="17063">Dry's Dispensary</option> <option value="13099">Dsc Karen Dispensary (Armed Forces)</option> <option value="17046">Dubai Medical Clinic</option> <option value="13330">Dugo Health Centre</option> <option value="13331">Dujis Health Centre</option> <option value="11990">Dukana Health Centre (North Horr)</option> <option value="14424">Dundori Health Centre</option> <option value="16661">Dunga Nursing Home</option> <option value="19024">Dungicha Dispensary</option> <option value="17353">Dunto Dispensary</option> <option value="19218">Durdur Medical Clinic and Lab</option> <option value="11991">Dwa Health Centre</option> <option value="18263">Dzanikeni Medical Clinic</option> <option value="11359">Dzikunze Dispensary</option> <option value="11360">Dzitsoni Medical Clinic</option> <option value="18739">Eagle Wings Medical Centre</option> <option value="11992">EAPC Kigumo Clinic</option> <option value="18152">East Africa Portland Cement Company Clinic</option> <option value="18638">East End Chemist</option> <option value="19618">East Medical Clinic</option> <option value="11993">East Way Medical Clinic</option> <option value="10521">Eastend Clinic</option> <option value="16567">Eastern Consultans Laboratory</option> <option value="19452">Eastern Medical Clinic</option> <option value="16568">Eastern Medical Consultants</option> <option value="12930">Eastleigh Health Centre</option> <option value="19526">Eastway Medical Centre</option> <option value="10157">Ebenezar Medical Clinic (Muranga North)</option> <option value="11994">Ebenezer Dispensary</option> <option value="17496">Ebenezer Medical Clinic</option> <option value="20179">Ebenezer Medical Clinic </option> <option value="10158">Ebenezer Medical Clinic (Lari)</option> <option value="11362">Ebenezer Medical Clinic (Malindi)</option> <option value="10159">Ebenezer Medical Clinic (Nyeri North)</option> <option value="10160">Ebenezer Medical Clinic (Nyeri South)</option> <option value="10161">Ebenezer Medical Clinic (Thika)</option> <option value="18990">Ebenezer Medical Services</option> <option value="16761">Ebenezer Nursing Home</option> <option value="13536">Eberege Dispensary</option> <option value="13537">Ebiosi Dispensary</option> <option value="15865">Ebukanga Dispensary</option> <option value="17113">Ebukoolo Dispensary</option> <option value="16975">Eburi Dispensary</option> <option value="14425">Eburru Dispensary</option> <option value="15866">Ebusiratsi Health Centre</option> <option value="15867">Ebusyubi Dispensary</option> <option value="16499">Ecclesiates Gathuthuma Bamako</option> <option value="13220">EDARP Donholm Clinic</option> <option value="17719">EDARP Komarock Health Centre</option> <option value="17548">EDARP Njiru Clinic</option> <option value="13169">EDARP Ruai Clinic</option> <option value="13191">EDARP Soweto Health Centre</option> <option value="10162">Eddiana Hospital</option> <option value="12931">Eden Dispensary</option> <option value="12932">Ediana Nursing Home</option> <option value="18197">Edkar Health Services</option> <option value="12933">Edna Clinic</option> <option value="12934">Edna Maternity</option> <option value="18359">Educational Assessment and Resource Centre</option> <option value="11364">Egah Medical Clinic</option> <option value="14426">Egerton University</option> <option value="13538">Egetonto Dispensary (Gucha)</option> <option value="19984">Egetuki GOK Dispensary</option> <option value="13539">Egetuki Medical Clinic (Gucha)</option> <option value="11995">Ekalakala Health Centre</option> <option value="11996">Ekalakala Medical Clinic</option> <option value="15868">Ekamanji Dispensary</option> <option value="17600">Ekani Dispenasry</option> <option value="13540">Ekerenyo Sub-District Hospital</option> <option value="16422">Ekerubo Dispensary (Kisii South)</option> <option value="13541">Ekerubo Dispensary (Masaba)</option> <option value="19971">Ekialo Kiano VCT</option> <option value="15869">Ekitale Dispensary</option> <option value="19900">Ekomero Health Centre</option> <option value="15870">Ekwanda Health Centre</option> <option value="11997">El Hadi Dispensary</option> <option value="18170">El Kambere Nomadic Clinic</option> <option value="17229">El-Golicha Dispensary</option> <option value="12001">El-Molo Bay Dispensary</option> <option value="17230">El-Ram Dispensary</option> <option value="14427">Elangata Enterit Dispensary</option> <option value="19329">Elatiai Health Ccare Services Medical Clinic</option> <option value="13332">Elben Dispensary</option> <option value="14428">Elburgon (PCEA) Dispensary</option> <option value="14430">Elburgon Nursing Home</option> <option value="14431">Elburgon Sub-District Hospital</option> <option value="14964">Eldama Ravine (AIC) Health Centre</option> <option value="14432">Eldama Ravine District Hospital</option> <option value="19324">Eldama Ravine Medical Centre</option> <option value="19322">Eldama Ravine Nursing Home</option> <option value="13333">Eldas Health Centre</option> <option value="11998">Eldera Dispensary</option> <option value="16290">Eldere Dispensary</option> <option value="14433">Eldo-Kit Clinic</option> <option value="14434">Eldoret Airport Dispensary</option> <option value="14435">Eldoret Hospital</option> <option value="18978">Eldoret Medical Services</option> <option value="17874">Eldoret MTC Clinic</option> <option value="18669">Eldoret Rapha Medical Centre</option> <option value="18861">Eldoret Regional Blood Bank</option> <option value="17351">Eldume Dispensary</option> <option value="19032">Elele Dispensary</option> <option value="16443">Elele Nomadic Clinic</option> <option value="14436">Elelea Health Centre</option> <option value="16379">Elementeita Dispensary</option> <option value="11999">Elgade Dispensary</option> <option value="14437">Elgeyo Boader Dispensary</option> <option value="14438">Elgon View Hospital</option> <option value="15871">Elgon View Medical Cottage</option> <option value="19064">Elim Dental Clinic</option> <option value="16883">Elim Family Community Care</option> <option value="19517">Elimu Medical Clinic</option> <option value="18146">Elis Medicare</option> <option value="19836">Elite Clinic</option> <option value="14439">Elite Medical Clinic</option> <option value="18031">Elite Medical Clinic (Bungoma East)</option> <option value="19708">Elite Medical Clinic (Mathira West)</option> <option value="14440">Eliye Springs (AIC) Dispensary</option> <option value="18846">Eliye Springs Community Dispensary</option> <option value="13334">Elnoor Dispensary</option> <option value="18361">Eluche</option> <option value="15872">Elukhambi Dispensary</option> <option value="13335">Elwak District Hospital</option> <option value="19272">Elwak Health Centre</option> <option value="16714">Elwangale Health Centre</option> <option value="15873">Elwasambi Dispensary</option> <option value="15874">Elwesero Dispensary</option> <option value="18165">Emahene Medical Clinic</option> <option value="12467">Emali Manchester Medical Clinic</option> <option value="18260">Emali Model Health Centre</option> <option value="12002">Emali Nursing Home</option> <option value="17409">Emalindi Health Centre</option> <option value="19270">Emanuel Medical Clinic</option> <option value="14441">Emaroro Dispensary</option> <option value="14442">Emarti Health Centre</option> <option value="16867">Ematiha Dispensary</option> <option value="15875">Ematsuli Dispensary</option> <option value="19252">Embakasi District Medical Office</option> <option value="12935">Embakasi Health Centre</option> <option value="19437">Embakasi Medical Centre</option> <option value="18894">Embakasi Medical Centre (Aun)</option> <option value="10166">Embaringo Dispensary</option> <option value="18073">Embomos Dispensary</option> <option value="13543">Embonga Health Centre</option> <option value="12003">Embori Farm Clinic</option> <option value="12790">Embu Children Clinic</option> <option value="16238">Embu Kmtc Dispensary</option> <option value="12004">Embu Provincial General Hospital</option> <option value="20204">EMBU UNIVERSITY COLLEGE HEALTH UNIT</option> <option value="17164">Embu-Mbeere Hospice</option> <option value="14445">Embul - Bul Catholic Dispensary</option> <option value="16349">Emc Kimumu Dispensary</option> <option value="17272">Emeroka Dispensary</option> <option value="17184">Emesc Medical Clinic</option> <option value="14446">Emining Health Centre</option> <option value="19005">Emirates Medical Clinic</option> <option value="14447">Emitik Dispensary</option> <option value="18987">Emko Clinic</option> <option value="17425">Emmah Medial Clinic</option> <option value="17574">Emmanuel Community Health Clinic</option> <option value="12005"><NAME> (ACK) Dispensary</option> <option value="10167">Emmanuel M/C VCT Centre</option> <option value="18893">Emmanuel Medical Centre</option> <option value="16707">Emmanuel Medical Clinic (Bungoma East)</option> <option value="16743">Emmanuel Medical Clinic (Kangundo)</option> <option value="10168">Emmanuel Medical Clinic (Nyeri North)</option> <option value="14443">Emmaus Clinic</option> <option value="10169">Emmaus Medical Clinic</option> <option value="12936">Emmaus Nursing Home</option> <option value="14448">Emotoroki Dispensary</option> <option value="14444">Empough Dispensary</option> <option value="14449">Emsea Dispensary</option> <option value="20010">Emsos Dispensary</option> <option value="15876">Emuhaya Sub District Hospital</option> <option value="20039">Emukaba Dispensary</option> <option value="15877">Emukaya Clinic</option> <option value="14450">Emumwenyi Dispensary</option> <option value="14451">Emurua Dikir Dispensary</option> <option value="14452">Emurua Dikirr Dispensary</option> <option value="16762">Emusanda Dispensary</option> <option value="15878">Emusenjeli Dispensary</option> <option value="16979">Emusire Health Centre</option> <option value="12007">Ena Dispensary</option> <option value="14453">Enabelbel Health Centre</option> <option value="14454">Enaibor Ajijik Dispensary</option> <option value="17519">Enanga Clinic</option> <option value="19730">Endarasha Medical Clinic</option> <option value="10170">Endarasha Rural Health Centre</option> <option value="12008">Endau Dispensary</option> <option value="14455">Endebess District Hospital</option> <option value="12009">Endei Dispensary</option> <option value="13544">Endiba Health Centre</option> <option value="14456">Endo Health Centre</option> <option value="14457">Endoinyo Erinka Dispensary</option> <option value="17746">Endoinyo Narasha</option> <option value="19360">Enego Dispensary</option> <option value="17221">Enesampulai Dispensary</option> <option value="14458">Engashura Health Centre</option> <option value="10171">Engineer District Hospital</option> <option value="17557">Engineer Medical Clinic</option> <option value="17910">Engos Health Cente</option> <option value="10172">Enkasiti Roses Farm Clinic</option> <option value="14460">Enkirgir Dispensary</option> <option value="14461">Enkirotet Medical Clinic</option> <option value="15600">Enkitok Joy Nursing Home</option> <option value="14462">Enkitoria Dispensary</option> <option value="17813">Enkongu Narok Dispensary</option> <option value="14463">Enkorika Health Centre</option> <option value="17784">Enkutoto Dispensary</option> <option value="14465">Enoosaen Health Centre</option> <option value="14466">Enoosaen Zh Clinic</option> <option value="14464">Enoosupukia Dispensary</option> <option value="17730">Ensakia Dispensary</option> <option value="13545">Entanda Dispensary</option> <option value="16424">Entanke Dispensary</option> <option value="14467">Entarara Health Centre</option> <option value="17320">Entargeti Dispensary</option> <option value="14479">Entasekera Health Centre</option> <option value="14469">Entasopia Health Centre</option> <option value="14470">Entiyani Dispensary</option> <option value="14471">Entontol Dispensary</option> <option value="17430">Enzai Afya Medical Clinic</option> <option value="15879">Enzaro Health Centre</option> <option value="12011">Enziu Dispensary</option> <option value="17281">Epkee Dispensary</option> <option value="14474">Equator Health Centre</option> <option value="15880">Equator Nursing and Maternity Home</option> <option value="17916">Equity Medical Clinic</option> <option value="13546">Eramba Dispensary</option> <option value="15881">Eregi Mission Health Centre</option> <option value="12012">Eremet Dispensary</option> <option value="18089">Eremit Dispensary</option> <option value="14475">Ereteti Dispensary</option> <option value="14476">Ereto Health Centre</option> <option value="13547">Eronge Health Centre</option> <option value="17925">Erreteti Dispensary</option> <option value="14477">Esageri Health Centre</option> <option value="13548">Esani Sub-District Hospital</option> <option value="17263">Escarpment Dispensary</option> <option value="19725">Escutar Health Partners Medical Clinic</option> <option value="19899">Eshiabwali Health Centre</option> <option value="18940">Eshibimbi Health Centre</option> <option value="15882">Eshikhuyu Dispensary</option> <option value="17217">Eshikulu Dispensary</option> <option value="16114">Eshimukoko Health Centre</option> <option value="15883">Eshiongo Dispensary</option> <option value="17133">Eshirembe Dispensary</option> <option value="16763">Eshisiru Catholic Dispensary</option> <option value="15884">Eshisiru Maternity and Nursing Home</option> <option value="11368">Eshu Dispensary</option> <option value="13549">Esianyi Dispensary</option> <option value="15885">Esiarambatsi Health Centre</option> <option value="20171">Esikulu Dispensary</option> <option value="15886">Esirulo Imani Medical Clinic</option> <option value="15887">Esitsaba Dispensary</option> <option value="16427">Esonorua Dispensary</option> <option value="14478">Esther Memorial Nursing Home</option> <option value="13550">Etago Sub-District Hospital</option> <option value="14480">Ethi Dispensary</option> <option value="13551">Etono Health Centre</option> <option value="10173">Eunice Medical Clinic</option> <option value="14481">Eureka Medical Clinic</option> <option value="14482">Euvan Medical Clinic</option> <option value="18046">Everest Dental Group Karatina Clinic</option> <option value="18719">Everest Medical/Dental Clinic</option> <option value="19995">Evesben Foundation Medical Clinic</option> <option value="20109">Ewang'ane Suswa </option> <option value="14483">Ewaso Dispensary</option> <option value="14484">Ewaso Ngiro Dispensary</option> <option value="14485">Ewaso Ngiro Health Centre</option> <option value="14486">Ewuaso Kedong Dispensary</option> <option value="12006">Ex Lewa Dispensary</option> <option value="13336">Excel Health Services</option> <option value="19443">Exodus Community Health Care</option> <option value="18054">Exodus Medical Clinic</option> <option value="19632">Express Medical Clinic</option> <option value="18632">Eye Care Centre</option> <option value="10174">Eye Sight Clinic</option> <option value="19572">Eyeclinic (Nairobi)</option> <option value="18458">Eymole Health Centre</option> <option value="13337">Eymole Health Centre</option> <option value="13338">Fafi Dispensary</option> <option value="17592">Faith Clinic</option> <option value="19078">Faith Health Clinic</option> <option value="10176">Faith Health Services Medical Clinic</option> <option value="17453">Faith Medical Centre</option> <option value="18469">Faith Medical Clinic</option> <option value="18840">Faith Medical Clinic</option> <option value="10177">Faith Medical Clinic (Nyeri North)</option> <option value="16774">Faith Medical Clinic (Nyeri South)</option> <option value="14490">Faith Medical Clinic Karate</option> <option value="12013">Faith Nursing Home (Ikutha)</option> <option value="18568">Family ( Mwingi Central)</option> <option value="12937">Family Care Clinic Kasarani</option> <option value="19137">Family Care Doctor's Plaza</option> <option value="12942">Family Care Medical Centre & Maternity</option> <option value="12015">Family Care Medical Centre (Meru)</option> <option value="13140">Family Care Medical Centre (Phoenix)</option> <option value="19328">Family Care Medical Centre Eye Clinic</option> <option value="10178">Family Care Medical Clinic</option> <option value="18755">Family Dental Care (Ayany)</option> <option value="10179">Family Dental Clinic</option> <option value="15888">Family Health Care Clinic</option> <option value="18239">Family Health Centre (Embu)</option> <option value="10180">Family Health Clinic</option> <option value="10181">Family Health Clinic (Nyeri South)</option> <option value="14492">Family Health Opition Kenya Clinic (Buret)</option> <option value="18217">Family Health Option of Kenya</option> <option value="16348">Family Health Options Kenya (Eldoret)</option> <option value="11375">Family Health Options Kenya (FHOK) Mombasa</option> <option value="13552">Family Health Options Kenya (FHOPK) Dispensary</option> <option value="16756">Family Health Options Kenya Clinic</option> <option value="12939">Family Health Options Phoenix</option> <option value="12940">Family Health Options Ribeiro</option> <option value="14177">Family Healthoptions Kenya (Nakuru)</option> <option value="12941">Family Life Promotions and Services</option> <option value="11370">Family Medical Centre (Kisauni)</option> <option value="11371">Family Medical Centre (Malindi)</option> <option value="11372">Family Medical Centre (Mombasa)</option> <option value="18390">Family Medical Centre (Ruai)</option> <option value="20115">Family Medical Clinic</option> <option value="12017">Family Medical Clinic (Machakos)</option> <option value="10182">Family Planning Association of Kenya Clinic (Nyeri</option> <option value="13553">Family Saver Clinic</option> <option value="10183">Family Smiles Dental Clinic</option> <option value="16829">Fanaka Clinic</option> <option value="18155">Fanaka Medical Centre</option> <option value="20078">Farmers choice wellness centre clinic</option> <option value="18617">Fathers Maternity and Health Services</option> <option value="14493">Fatima Health Centre (Lenkism)</option> <option value="14494">Fatima Maternity Hospital</option> <option value="17908">Favour Primary Health Care</option> <option value="16211">Fayaa Medical Clinic</option> <option value="11373">Faza Hospital</option> <option value="16392">FGC of Kenya Medical Centre</option> <option value="14496">Fig Tree Clinic</option> <option value="16569">Filhia Medical Clinic</option> <option value="13341">Fincharo Dispensary</option> <option value="14497">Finlay Flowers Dispensary</option> <option value="14551">Finlays Hospital</option> <option value="13340">Fino Health Centre</option> <option value="13554">Firmview Medical Clinic</option> <option value="18226">First Baptist Dispensary</option> <option value="14498">Fitc Dispensary</option> <option value="12943">Flack Clinic</option> <option value="14499">Flax Dispensary</option> <option value="18472">Flomed Med Clinic</option> <option value="18659">Florex Medical Clinic</option> <option value="14500">Flourspar Health Centre</option> <option value="19807">Fly Over Health Clinic</option> <option value="19806">Fly Over Medical Clinic</option> <option value="19274">Fmily Acces Medical Centre</option> <option value="10184">Focus Medical Clinic and Counselling Centre</option> <option value="19539">Focus Outreach Medical Mission</option> <option value="20035">Fofcom VCT</option> <option value="12019">Forolle Dispensary</option> <option value="14501">Forttenan Sub District Hospital</option> <option value="19173">Fountain Healthcare</option> <option value="14502">Fountain Medical Centre</option> <option value="17787">Fountain Medical Clinic</option> <option value="18780">Fountain of Hope Medical Clinic</option> <option value="14503">Fr andrian Heath Centre</option> <option value="10185">Fr Baldo Cath Disp</option> <option value="12020">Fr Meru Dispensary</option> <option value="13555">Framo Medical Clinic</option> <option value="10187">Franjane Medical Clinic</option> <option value="17721">Frankstar Medical Clinic (Manga)</option> <option value="10188">Frayjoy Clinic (Dr Tumbo)</option> <option value="11376">Freedom Medical Clinic</option> <option value="18612">Fremo Medical Centre</option> <option value="12944">Frepals Community Nursing Home</option> <option value="18645">Friends Chemist</option> <option value="19835">Front Line Medical Clinic</option> <option value="12021">Frontier Clinic</option> <option value="19219">Frontier Health Services</option> <option value="19898">Frontier Health Services Malaba</option> <option value="19886">Frontier Health Services- Malaba</option> <option value="17901">Frontier Medical Clinic (Moyale)</option> <option value="19058">Frontier Medicare</option> <option value="11378">Frontline Clinic</option> <option value="11379">Fundi Issa Dispensary</option> <option value="16659">Furqan Dispensary</option> <option value="12945">Future Age Medical Services</option> <option value="17522">Future Life Dispensary</option> <option value="17877">G K Prisons (Thika)</option> <option value="17716">G S U Kinisa Dispensary</option> <option value="16852">Gaatia Dispensary</option> <option value="18630">Gababa Dispensary</option> <option value="12022">Gacabari Dispensary</option> <option value="10190">Gacharage Dispensary</option> <option value="10191">Gacharageini Dispensary</option> <option value="10192">Gachatha Medical Clinic (Nyeri South)</option> <option value="10194">Gachege Dispensary</option> <option value="10195">Gachika Dispensary</option> <option value="10196">Gachika Orthodox Medical Clinic</option> <option value="18608">Gachororo Health Centre</option> <option value="18339">Gachua Catholic Dispensary</option> <option value="12023">Gachuriri Dispensary</option> <option value="12024">Gaciongo Dispensary</option> <option value="10197">Gaciongo Dispensary (Kirinyaga)</option> <option value="10198">Gadi Medical Clinic</option> <option value="12025">Gafarsa Health Centre</option> <option value="11380">Gahaleni Dispensary</option> <option value="19918">Gaichanjiru Hospita (Satelite)</option> <option value="10199">Gaichanjiru Hospital</option> <option value="12946">Gaimu Clinic</option> <option value="13556">Gairoro Dispensary</option> <option value="12026">Gaitu Dispensary</option> <option value="16833">Gaitu Medical Clinic</option> <option value="10200">Gakawa Dispensary</option> <option value="10201">Gakira Medical Clinic</option> <option value="10202">Gakoe Health Centre</option> <option value="12027">Gakoromone Dispensary</option> <option value="18703">Gakoromone Health Care Clinic</option> <option value="16570">Gakoromone Medical Clinic</option> <option value="16738">Gakurungu Dispensary</option> <option value="10203">Gakurwe Dispensary</option> <option value="10204">Gakuyuini Medical Clinic</option> <option value="11381">Galana Hospital</option> <option value="16244">Galilee Medical Clinic</option> <option value="16199">Galili Dispensary</option> <option value="13342">Galmagalla Health Centre</option> <option value="18332">Galmagalla Nomadic Clinic</option> <option value="16540">Gama Medical Clinic</option> <option value="19954">Gamba Medical Clinic</option> <option value="11382">Ganda Dispensary</option> <option value="18300">Gandini Dispensary</option> <option value="12028">Gangara Dispensary</option> <option value="17224">Gankere Dispensary</option> <option value="13343">Ganyure Dispensary</option> <option value="11383">Ganze Health Centre</option> <option value="11384">Garashi Dispensary</option> <option value="12029">Garbatulla District Hospital</option> <option value="19718">Garden Park Medical Centre</option> <option value="18866">Gari Dispensary</option> <option value="13344">Garissa Medical Clinic</option> <option value="17670">Garissa Mother and Child Care Nursing Home</option> <option value="13345">Garissa Nursing Home</option> <option value="19460">Garissa Pride Healthcare</option> <option value="13346">Garissa Provincial General Hospital (PGH)</option> <option value="16287">Garissa Teacher Training College Dispensary</option> <option value="19079">Garlands Medical Centree</option> <option value="12947">Garrison Health Centre</option> <option value="10205">Garrissa Highway Medical Clinic</option> <option value="11385">Garsen Health Centre</option> <option value="16444">Garsesala Dispensary</option> <option value="17289">Garseyqoftu Dispensary</option> <option value="12030">Gatab Health Centre</option> <option value="16378">Gatamaiyo Dispensary</option> <option value="10206">Gatamu Medical Clinic</option> <option value="10207">Gatanga Dispensary</option> <option value="10208">Gatangara Dispensary</option> <option value="16230">Gatankene Dispensary</option> <option value="10209">Gatara Health Centre</option> <option value="16463">Gategi Health Centre</option> <option value="10210">Gatei Dispensary</option> <option value="10211">Gateways Medical Clinic</option> <option value="10212">Gathaithi Dispensary</option> <option value="10213">Gathambi Dispensary</option> <option value="10214">Gathanga Dispensary</option> <option value="19965">Gathangari Dispensary</option> <option value="20023">Gathanji Clinic</option> <option value="17058">Gathanji Dispensary</option> <option value="10215">Gathara Dispensary</option> <option value="10216">Gatheru Dispensary</option> <option value="10217">Gathigiriri Dispensary</option> <option value="10219">Gathiruini (PCEA) Dispensary</option> <option value="17305">Gatiaini Dispensary</option> <option value="12031">Gatimbi Health Centre</option> <option value="16838">Gatimbi Medical Clinic</option> <option value="16397">Gatimu Dispensary</option> <option value="18781">Gatimu Health Centre</option> <option value="10220">Gatina Dispensary</option> <option value="16803">Gatina United Clinic</option> <option value="18453">Gatiruri Dispensary</option> <option value="10221">Gatithi Dispensary</option> <option value="10222">Gatitu Dispensary</option> <option value="10223">Gatondo Dispensary (Kipipiri)</option> <option value="10224">Gatondo Dispensary (Nyeri North)</option> <option value="10226">Gatuamba Medical Clinic</option> <option value="10227">Gatuanyaga Dispensary</option> <option value="10228">Gatugi Mission Dispensary</option> <option value="10229">Gatugura Dispensary</option> <option value="10231">Gatukuyu Medical Clinic</option> <option value="10232">Gatumbi (SDA) Dispensary</option> <option value="12032">Gatumbi Dispensary</option> <option value="10233">Gatundu District Hospital</option> <option value="12033">Gatunduri Dispensary</option> <option value="19124">Gatune Clinic</option> <option value="12034">Gatunga Health Centre</option> <option value="18080">Gatunga Model Health Centre</option> <option value="10234">Gatunyu Dispensary</option> <option value="10235">Gatura (PCEA) Dispensary</option> <option value="10236">Gatura Healh Centre</option> <option value="16976">Gaturi Catholic Parish Dispensary</option> <option value="16232">Gaturi Dispensary</option> <option value="10237">Gaturi Medical Clinic</option> <option value="16386">Gatuto Dispensary</option> <option value="10239">Gatwe Dispensary</option> <option value="19006">Gatwell/Lab Medical Clinic</option> <option value="10240">Gawa Medical Clinic</option> <option value="19862">Gazi Bay Medical Clinic</option> <option value="11386">Geca Medical Clinic</option> <option value="17314">Gechiriet Dispensary</option> <option value="18650">Gecy Chemist</option> <option value="11387">Gede Health Centre</option> <option value="11388">Gede Medical Clinic</option> <option value="19611">Gedmed Medical Clinic</option> <option value="13557">Gekano Health Centre (Manga)</option> <option value="14505">Gelegele Dispensary</option> <option value="16571">General Medical Clinic</option> <option value="18705">General Medical Clinic and Lab</option> <option value="16572">General Medical Laboratory</option> <option value="16573">Generation Medical Clinic/Lab</option> <option value="10241">Generations Medical Clinic</option> <option value="16831">Genesis Clinic</option> <option value="16574">Genesis Clinic (Imenti North)</option> <option value="10242">Genesis Clinic (Kirinyaga)</option> <option value="16500">Genesis Community Bamako Initiative</option> <option value="17236">Genesis Medical Clinic</option> <option value="19702">Genesis Medical Clinic Kitengela</option> <option value="16442">Genesis Medicare</option> <option value="12949">Genessaret Clinic</option> <option value="19287">Genus Medical Services & Diagnostic Lab</option> <option value="17461">Gerille Health Centre</option> <option value="16681">Gerol</option> <option value="17725">Gertrude Komarock Clinic</option> <option value="18585">Gertrudes Chidrens Clinic (Ongata Rongai)</option> <option value="19314">Gertrudes Chiildren Clinic (Pangani)</option> <option value="18191">Gertrudes Children Clinic (Kitengela)</option> <option value="12950">Gertrudes Childrens Hospital</option> <option value="12951">Gertrudes Othaya Road Dispensary</option> <option value="13558">Gesabakwa Health Centre</option> <option value="13559">Gesima Health Centre</option> <option value="13560">Gesuguri Dispensary</option> <option value="13561">Gesure Dispensary (Gucha)</option> <option value="13562">Gesure Health Centre (Manga)</option> <option value="13563">Gesusu (SDA) Dispensary</option> <option value="13564">Gesusu Sub-District Hospital</option> <option value="19151">Get Well Clinic and Lab Services</option> <option value="10244">Geta Bush Health Centre</option> <option value="14506">Geta Dispensary</option> <option value="10245">Geta Forest Dispensary</option> <option value="13565">Getambwega Dispensary</option> <option value="13566">Getare Health Centre(Manga)</option> <option value="14507">Getarwet Dispensary</option> <option value="13567">Getembe Hospital</option> <option value="13568">Geteri Dispensary</option> <option value="20102">Gethsemane Garden Mission Hospital</option> <option value="16281">Getiesi Health Centre</option> <option value="13569">Getongoroma Dispensary</option> <option value="13570">Getongoroma Health Centre</option> <option value="13571">Getontira Clinic</option> <option value="12035">Getrude Dispensary</option> <option value="12952">Getrude Donholm Clinic</option> <option value="18395">Getrude Embakasi Clinic</option> <option value="12953">Getrudes Hospital (Nairobi West Clinic)</option> <option value="18969">Geva Family Health Services</option> <option value="11390">Ghazi Dispensary</option> <option value="10246">Giachuki Medical Clinic</option> <option value="10247">Giakaibei Catholic Dispensary</option> <option value="16223">Giaki Clinic</option> <option value="12036">Giaki Sub-District Hospital</option> <option value="13572">Gianchore Health Centre</option> <option value="12037">Gianchuku Dispensary</option> <option value="10248">Giathanini Dispensary</option> <option value="13573">Giatunda Dispensary</option> <option value="17421">Giatutu Dispensary</option> <option value="17365">Gichagini Dispensary</option> <option value="16799">Gichago Dispensary</option> <option value="12038">Gichiche Dispensary</option> <option value="10249">Gichiche Health Centre</option> <option value="10250">Gichiche Medical Clinic</option> <option value="10251">Gichira Health Centre</option> <option value="16400">Gichobo Dispensary</option> <option value="10252">Gichuru Dispensary</option> <option value="13574">Gietai (AIC) Dispensary</option> <option value="11391">Gift Medical Clinic</option> <option value="17645">Giithu Dispensary</option> <option value="10253">Gikoe Dispensary</option> <option value="10254">Gikoe Medical Clinic</option> <option value="16171">Gikono Dispensary</option> <option value="10256">Gikui Health Centre</option> <option value="16853">Gikuuri Dispensary (CDF)</option> <option value="17960">Gil Medical Clinic</option> <option value="14508">Gilgil Astu Dispensary</option> <option value="14509">Gilgil Community Medical Clinic</option> <option value="14511">Gilgil Military Regional Hospital</option> <option value="14510">Gilgil Sub-District Hospital</option> <option value="19916">Gionsaria Dispensary (Nyamache)</option> <option value="12955">Giovanna Dispensary</option> <option value="13575">Girango Dispensary</option> <option value="11392">Giriama Mission Dispensary</option> <option value="13576">Giribe Dispensary</option> <option value="16665">Girigiri Dispensary</option> <option value="13348">Girissa Dispensary</option> <option value="13577">Gisage Dispensary</option> <option value="19538">Gitanga Medical Centre</option> <option value="17843">Gitaraka Dispensary</option> <option value="12039">Gitare Dispensary (Embu)</option> <option value="10257">Gitare Health Centre (Gatundu)</option> <option value="10258">Gitaro Dispensary</option> <option value="12040">Gitaru Clinic</option> <option value="10259">Gitata Medical Clinic</option> <option value="17659">Gitathi Dispensary</option> <option value="10260">Gitaus Medical Clinic</option> <option value="19804">Githabai Medical Clinic</option> <option value="10261">Githagara Health Centre</option> <option value="17253">Githambo Dispensary</option> <option value="10262">Githanga (ACK) Dispensary</option> <option value="13349">Gither Dispensary</option> <option value="10263">Githiga Health Centre</option> <option value="10264">Githiga Midways Clinic</option> <option value="17401">Githiga Private Medical Clinic</option> <option value="19968">Githima Dispensary</option> <option value="17424">Githima Medical Clinic</option> <option value="16394">Githiriga Dispensary</option> <option value="10265">Githirioni Dispensary</option> <option value="18887">Githogoro Runda Baptist Clinic (Getrudes Nairobi)</option> <option value="12041">Githongo District Hospital</option> <option value="10266">Githuani (ACK) Dispensary</option> <option value="10267">Githumu Hospital</option> <option value="10268">Githunguri Dispensary</option> <option value="10269">Githunguri Health Centre</option> <option value="16748">Githunguri Health Centre (Ruiru)</option> <option value="10270">Githunguri Health Services Clinic</option> <option value="10271">Githunguri Heathwatch Clinic</option> <option value="10272">Githunguri Medical Plaza Clinic</option> <option value="10273">Githurai Community Clinic</option> <option value="19264">Githurai Health Care and Dental Hospital</option> <option value="17942">Githurai Liverpool VCT</option> <option value="12956">Githurai Medical Dispensary</option> <option value="12957">Githurai VCT</option> <option value="10274">Githure (ACK) Dispensary</option> <option value="10275">Gitiha Dispensary</option> <option value="12042">Gitine Dispensary</option> <option value="17259">Gitithia Dispensary</option> <option value="18147">Gitombani Dispensary</option> <option value="12044">Gitoro Dispensary</option> <option value="10020">Gituamba (AIPCA) Dispensary</option> <option value="17837">Gituamba Community Dispensary</option> <option value="10277">Gituamba Dispensary</option> <option value="10278">Gituamba Medical Clinic</option> <option value="10279">Gitugi Dispensary (Muranga North)</option> <option value="10280">Gitugi Dispensary (Nyeri South)</option> <option value="10281">Gitundu (ACK) Dispensary</option> <option value="10282">Gitunduti Catholic Dispensary</option> <option value="17408">Gitura Dispensary</option> <option value="17423">Gitura Dispensary-Kenol</option> <option value="18962">Gituuru Dispensary</option> <option value="14512">Gitwamba Health Centre</option> <option value="10284">Gitwe Medical Clinic</option> <option value="17182">Givole Dispensary</option> <option value="15889">Givudimbuli Health Centre</option> <option value="19593">Giwa Health Services</option> <option value="14514">GK Farm Prisons Dispensary (Trans Nzoia)</option> <option value="14516">GK Prison Annex Dispensary (Naivasha)</option> <option value="18308">GK Prison Clinic</option> <option value="10189">GK Prison Dispensary</option> <option value="15890">GK Prison Dispensary ( Bungoma South)</option> <option value="14517">GK Prison Dispensary (Athi River)</option> <option value="12045">GK Prison Dispensary (Embu)</option> <option value="13350">GK Prison Dispensary (Garissa)</option> <option value="10285">GK Prison Dispensary (Gathigiriri )</option> <option value="13578">GK Prison Dispensary (Homa Bay)</option> <option value="12046">GK Prison Dispensary (Isiolo)</option> <option value="10286">GK Prison Dispensary (Kingongo)</option> <option value="12047">GK Prison Dispensary (Kitui)</option> <option value="12048">GK Prison Dispensary (Machakos)</option> <option value="11394">GK Prison Dispensary (Malindi)</option> <option value="12049">GK Prison Dispensary (Meru)</option> <option value="17728">GK Prison Dispensary (Migori)</option> <option value="10287">GK Prison Dispensary (Murang'a)</option> <option value="14518">GK Prison Dispensary (Nandi Central)</option> <option value="10288">GK Prison Dispensary (Ruiru)</option> <option value="11396">GK Prisons Clinic (Malindi)</option> <option value="14523">GK Prisons Dispensary</option> <option value="15891">GK Prisons Dispensary (Busia)</option> <option value="14519">GK Prisons Dispensary (Eldoret East)</option> <option value="15892">GK Prisons Dispensary (Kakamega Central)</option> <option value="14520">GK Prisons Dispensary (Kapenguria)</option> <option value="14521">GK Prisons Dispensary (Kericho)</option> <option value="10290">GK Prisons Dispensary (Kiambu East)</option> <option value="13579">GK Prisons Dispensary (Kibos)</option> <option value="13580">GK Prisons Dispensary (Kisii)</option> <option value="14522">GK Prisons Dispensary (Laikipia East)</option> <option value="14524">GK Prisons Dispensary (Ngeria)</option> <option value="11398">GK Prisons Dispensary (Tana River)</option> <option value="14527">GK Prisons Dispensary (Turkana Central)</option> <option value="18616">GK Prisons Medium Dispensary</option> <option value="14528">GK Remand Prisons Dispensary (Trans Nzoia West)</option> <option value="17972">Glaisa Medical Clinic</option> <option value="19927">Global Providers International Clinic</option> <option value="14529">Gloria Health Services</option> <option value="18613">Glory Health Clinic</option> <option value="10291">Glory Medical Clinic</option> <option value="16739">Glory Medical Clinic (Kangundo)</option> <option value="19120">Glory Medical Clinic (Kitui Central)</option> <option value="11399">Glory Medical Clinic (Tana River)</option> <option value="17037">Glory Ministry Medical Clinic</option> <option value="18282">Glovnet VCT</option> <option value="15893">Go Down Clinic</option> <option value="13581">Gobei Health Centre</option> <option value="13582">God Jope Dispensary</option> <option value="13583">God Kwer Dispensary</option> <option value="13584">Godber Dispensary</option> <option value="13585">Godbura Health Centre</option> <option value="11400">Godo Dispensary</option> <option value="13351">Godoma Health Centre (Nep)</option> <option value="12050">Godoma Model Health Centre (Moyale)</option> <option value="13586">Gods Will Clinic</option> <option value="19907">Gogo Disp</option> <option value="14513">GOK Farm (Nahrc) Dispensary</option> <option value="18264">GOK Prison Siaya</option> <option value="16676">GOK Rumuruti Prisons Dispensary</option> <option value="20131">Goldenlife Medical Centre Naivasha</option> <option value="19427">Goldmed Chemists & Clinic</option> <option value="12051">Golole Dispensary</option> <option value="16546">Gombato Dispensary (CDF)</option> <option value="13587">Gongo Dispensary</option> <option value="17516">Gongo Health Centre</option> <option value="11401">Gongoni Health Centre</option> <option value="11402">Gongoni Medical Clinic</option> <option value="14530">Good Health Clinic Ngong</option> <option value="10293">Good Health Medical Clinic</option> <option value="16847">Good Hope Clinic</option> <option value="10294">Good Hope Hospital</option> <option value="10295">Good Hope Medical Clinic</option> <option value="19619">Good Neighbours Medical Clinic (Dandora)</option> <option value="10296">Good Samaritan (ACK) Medical Clinic</option> <option value="12959">Good Samaritan Dispensary</option> <option value="10297">Good Samaritan Health Services (Kirinyaga)</option> <option value="19913">Good Samaritan Medical Centre</option> <option value="17747">Good Shepherd Ang'iya</option> <option value="12960">Good Shepherd Dispensary</option> <option value="10298">Good Shepherd Medical Clinic (Nyeri North)</option> <option value="10299">Good Shepherd Medical Clinic (Nyeri South)</option> <option value="18975">Good Shephered Medical Clinic</option> <option value="12052">Good Will Medical Clinic</option> <option value="10300">Goodwill Clinic</option> <option value="17836">Goodwill Medical Clinic</option> <option value="14531">Gorgor Dispensary</option> <option value="12053">Goro Rukesa Dispensary</option> <option value="11403">Gorofani Medical Clinic</option> <option value="14532">Goseta Dispensary</option> <option value="14533">Gosheni Medical Clinic</option> <option value="13588">Got Agulu Sub-District Hospital</option> <option value="19928">Got Kachola Dispensary</option> <option value="18874">Got Kamondi Dispensary</option> <option value="13589">Got Kojowi Health Centre</option> <option value="13590">Got Matar Dispensary</option> <option value="13591">Got Nyabondo Dispensary</option> <option value="18321">Got Osimbo Dispensary</option> <option value="13592">Got Oyaro Dispensary</option> <option value="17520">Got Regea Dispensary</option> <option value="11404">Gotani Dispensary</option> <option value="13593">Gotichaki Dispensary</option> <option value="10717">Grace Baricho Clinic</option> <option value="17070">Grace Medical Care Centre</option> <option value="14534">Grace Medical Centre</option> <option value="18489">Grace Medical Clinic</option> <option value="18288">Grace Medical Clinic (Imenti South)</option> <option value="18317">Gracious Day Medical Clinic</option> <option value="10301">Gracious M Clinic</option> <option value="14535">Grand Avens Clinic</option> <option value="14536">Grassland Dispensary</option> <option value="14537">Great Comm Medical Clinic</option> <option value="19528">Green Croos Medical and Dental Clinic</option> <option value="19895">Green Cross Medical Clinic</option> <option value="10303">Green Hill Medical Clinic</option> <option value="18740">Green Valley Clinic</option> <option value="14538">Greenview Hospital</option> <option value="13352">Griftu District Hospital</option> <option value="16413">Gsu Dispensary</option> <option value="14539">Gsu Dispensary (Kabarak)</option> <option value="14540">Gsu Dispensary (Kibish)</option> <option value="12961">Gsu Dispensary (Nairobi West)</option> <option value="10304">Gsu Dispensary (Ruiru)</option> <option value="14541">Gsu Field Dispensary (Kajiado)</option> <option value="12963">Gsu Hq Dispensary (Ruaraka)</option> <option value="12962">Gsu Training School</option> <option value="13353">Guba Dispensary</option> <option value="13594">Gucha District Hospital</option> <option value="13595">Gucha Maternity and Nursing Home</option> <option value="19007">Gule Medical Clinic</option> <option value="10305">Gumba Health Centre</option> <option value="19122">Gundua Health Centre</option> <option value="18715">Gunduwa Health Centre</option> <option value="13355">Gurar Health Centre</option> <option value="13596">Guru Nanak Dispensary</option> <option value="12965">Guru Nanak Hospital</option> <option value="13356">Gurufa Dispensary</option> <option value="18213">Gurunanak Medical Clinic</option> <option value="12054">Gus Dispensary</option> <option value="17007">Guticha Dispensary</option> <option value="14542">Guyana Medical Clinic</option> <option value="13597">Gwitembe Dispensary</option> <option value="12966">Gynapaed Dispensary (Kilimani-Westlands)</option> <option value="19205">Gynocare Centre Maternity Home</option> <option value="13357">Habaswein District Hospital</option> <option value="13358">Hadado Health Centre</option> <option value="13359">Hagadera Hospital</option> <option value="17336">Hagarbul Dispensary</option> <option value="17149">Hakati Dspensary</option> <option value="12967">Hakati Medical Clinic</option> <option value="18920">Hakuna Matata Medical Clinic</option> <option value="14885">Halfeez Medical Clinic</option> <option value="19610">Hallal Medical Clinic</option> <option value="10306">Ham Medical Clinic</option> <option value="18801">Hamey Dispensary</option> <option value="15894">Hamisi Sub District Hospital</option> <option value="19970">Hamsadam Medical Clinic</option> <option value="16753">Hamundia Health Centre</option> <option value="19472">Hamza Medical Centre</option> <option value="17751">Hamza Medical Clinic</option> <option value="13360">Handaro Dispensary</option> <option value="13599">Happy Magwagwa Clinic</option> <option value="13361">Hara Health Centre</option> <option value="19801">Haraka Medical Clinic</option> <option value="12055">Hardship Medical Clinic</option> <option value="13362">Hareri Dispensary</option> <option value="17354">Hargal Dispensary</option> <option value="19908">Harmony Medical Clinic</option> <option value="17078">Haroresa</option> <option value="19755"><NAME> Mc</option> <option value="20178">Havillan Medical Center</option> <option value="13600">Hawinga Health Centre</option> <option value="19566">Hazina Medical Clinic</option> <option value="17008">Health Bridge Medical Clinic</option> <option value="19497">Health Care Services</option> <option value="14543">Health For All (ACK) Clinic</option> <option value="19582">Health Matters Medical Centre</option> <option value="13601">Health Mountain Hospital</option> <option value="19597">Health Source Medical Centre</option> <option value="10310">Healthscope Clinic (Muranga North)</option> <option value="14544">Healthway Medical Clinic</option> <option value="18278">Healthways Medical Centre</option> <option value="19824">Hebron CFW Clinic</option> <option value="19813">Hebron CFW Clinic (Kutus)</option> <option value="12057">Heillu Dispensary</option> <option value="14545">Hekima Dispensary</option> <option value="20093">Hekima HTC Center</option> <option value="11408">Hekima Medical Clinic</option> <option value="14546">Helmon Clinic</option> <option value="18373">Helpers of Mary Dispensary</option> <option value="13602">Hema Clinic</option> <option value="13603">Hema Hospital</option> <option value="17674">Hema Medical Clinic</option> <option value="10312">Heni Health Centre</option> <option value="16884">Henzoro Medical Clinic</option> <option value="16180">Heri Medical Centre</option> <option value="19605">Heri Medical Cilinic Bombolulu</option> <option value="19955">Heri Tana Medical Clinic</option> <option value="17364">Heritage Medical Clinic</option> <option value="10313">Heshima Clinic</option> <option value="10314">Heshima Medical Clinic</option> <option value="12058">Heshima Medical Clinic (Kangundo)</option> <option value="14547">Heshima Medical Clinic (Nakuru North)</option> <option value="19112">Heshima Medical Clinic-Masinga</option> <option value="18445">Hessed Clinic Masiro</option> <option value="10316">Hezeman Afya Bora</option> <option value="16522">Hidaya Medical Clinic</option> <option value="19787">High Way Medical Clinic</option> <option value="16851">Highland Clinic</option> <option value="18844">Highrise Medical Services</option> <option value="13363">Highway Clinic (Wajir East)</option> <option value="15895">Highway Maternity and Nursing Home</option> <option value="18022">Highway Mediacl Clinic (Nyeri North)</option> <option value="12060">Highway Medical Clinic</option> <option value="16708">Highway Medical Clinic (Bungoma East)</option> <option value="10318">Highway Medical Clinic (Kirinyaga)</option> <option value="19015">Highway Medical Clinic (Pokot Central)</option> <option value="14548">Highway Medical Clinic (Trans Nzoia East)</option> <option value="18134">Highway Medical Clinic (Wote)</option> <option value="19876">Highway Medical Clinic Iten</option> <option value="10718">Highway Medical Clinic Kibingoti</option> <option value="18924">Highway Medical Clinic Maua</option> <option value="19197">Highway Medical Clinic Yatta</option> <option value="10319">Highway Medical Enterprises</option> <option value="19949">Hilac Medical Clinic-Habaswein</option> <option value="19877">Hillday Medical Clinic</option> <option value="19383">Hillview Park Medical Clinic</option> <option value="19008">Hilwa Pharmacy and Clinic</option> <option value="11409">Hindi Magogoni Dispensary</option> <option value="11410">Hindi Prison Dispensary</option> <option value="13364">Hodhan Dispensary</option> <option value="11411">Hola District Hospital</option> <option value="18035">Holale Medical Clinic ( Moyale)</option> <option value="18950">Holiday Medical Clinic</option> <option value="17118">Holo Dispensary</option> <option value="10321">Holy Cross Dispensary</option> <option value="10320">Holy Family Dispensary</option> <option value="19963">Holy Family Mission Hospital Githunguri</option> <option value="16073">Holy Family Nangina Hospital</option> <option value="13604">Holy Family Oriang Mission Dispensary</option> <option value="10322">Holy Rosary Ikinu Dispensary</option> <option value="14549">Holy Spirit Health Centre</option> <option value="17984">Holy Transfiguration Orthodox Health Centre</option> <option value="14550">Holy Trinity Health Centre (Mai Mahiu)</option> <option value="18063">Homa Bay Central Widows VCT</option> <option value="17926">Homa Bay Community Medical Clinic</option> <option value="13608">Homa Bay District Hospital</option> <option value="13605">Homa Clinic</option> <option value="13606">Homa Hills Health Centre</option> <option value="13607">Homa Lime Health Centre</option> <option value="18056">Homebase Medical Clinic</option> <option value="17676">Homey Medical Clinic</option> <option value="13609">Hongo Ogosa Dispensary</option> <option value="11412">Hongwe Catholic Dispensary</option> <option value="11413">Hongwe Clinic</option> <option value="12969">Hono Clinic</option> <option value="12970">Hope Community VCT</option> <option value="16983">Hope Compassionate (ACK) Dispensary</option> <option value="17446">Hope Medical Clinic</option> <option value="19278">Hope Medical Clinic ( Githurai)</option> <option value="19234">Hope Medical Clinic (Babadogo)</option> <option value="10323">Hope Medical Clinic (Gatundu South)</option> <option value="10324">Hope Medical Clinic (Kigumo)</option> <option value="11414">Hope Medical Clinic (Kilindini)</option> <option value="10325">Hope Medical Clinic (Kirinyaga)</option> <option value="18994">Hope Medical Clinic (Loitokitok)</option> <option value="17869">Hope Medical Clinic (Mariakani)</option> <option value="16686">Hope Medical Clinic (Nakuru)</option> <option value="10327">Hope Medical Clinic (Nyeri North)</option> <option value="18810">Hope Medical Clinic Mwandoni</option> <option value="19649">Hope Medical Clinic Yatta</option> <option value="19128">Hope Medical Laboratory</option> <option value="16724">Hope Nursing Home</option> <option value="19114">Hope World Wide</option> <option value="19890">Hope World Wide (Makindu)</option> <option value="17684">Hope World Wide Kenya Mukuru Clinic</option> <option value="18875">Hope World Wide Nakuru</option> <option value="18493">Hope Worldwide Htc Centre</option> <option value="18543">Hope Worldwide Kenya VCT (Makadara)</option> <option value="19373">Horeb Medical Clinic ( Hunters)</option> <option value="11415">Horesha Medicalicare</option> <option value="19643">Horseet Medical Clinic</option> <option value="16517">Hosana Medical Clinic</option> <option value="16352">Hospice Dispensary</option> <option value="18720">House of Hope Medical Centre</option> <option value="17897">Howdil Aday Clinic</option> <option value="20063">Hoymas VCT (Nairobi)</option> <option value="13610">Huduma Clinic</option> <option value="17393">Huduma Health Centre</option> <option value="16575">Huduma Medical Clinic</option> <option value="18675">Huhoini Dispensary</option> <option value="16205">Hulahula Dispensary</option> <option value="13365">Hulugho Sub-District Hospital</option> <option value="19823">Humanity Medical Clinic (Kir South)</option> <option value="19845">Humanity Medical Clinic (Kir West)</option> <option value="16793">Hungai Dispensary</option> <option value="19302">Hunters Medical Clinic</option> <option value="12061">Hurri-Hills Dispensary</option> <option value="12973">Huruma (EDARP)</option> <option value="12972">Huruma (NCCK) Dispensary</option> <option value="12062">Huruma Clinic (Embu)</option> <option value="14552">Huruma Dispensary</option> <option value="14555">Huruma District Hospital</option> <option value="14553">Huruma Health Centre (Laikipia East)</option> <option value="12974">Huruma Lions Dispensary</option> <option value="12975">Huruma Maternity Hospital</option> <option value="16576">Huruma Medical Centre</option> <option value="18736">Huruma Medical Clinc</option> <option value="17580">Huruma Medical Clinic</option> <option value="18297">Huruma Medical Clinic (Bamba)</option> <option value="19255">Huruma Medical Clinic (Changamwe)</option> <option value="10329">Huruma Medical Clinic (Gatundu)</option> <option value="12064">Huruma Medical Clinic (Imenti Central)</option> <option value="12065">Huruma Medical Clinic (Kangundo)</option> <option value="17879">Huruma Medical Clinic (Kanja)</option> <option value="17898">Huruma Medical Clinic (Moyale)</option> <option value="14554">Huruma Mobile Clinic</option> <option value="12976">Huruma Nursing Home & Maternity</option> <option value="19310">Huruma St Jude's Community Health Services</option> <option value="19983">Hylax Clinic (Masaba North)</option> <option value="18201">I Choose Life Africa</option> <option value="12979">I R Iran Medical Clinic</option> <option value="13611">Ibacho Sub-District Hospital</option> <option value="13612">Ibeno Sub-District Hospital</option> <option value="13366">Ibnu-Sina Medical Clinic</option> <option value="11417">Ibnusina Clinic</option> <option value="18808">Ibrahim Ure Dispensary</option> <option value="10331">Ichagachiru Dispensary</option> <option value="10332">Ichagaki (Mission) Health Centre</option> <option value="10333">Ichamara Dispensary</option> <option value="10334">Ichamara Medical Clinic</option> <option value="10335">Ichichi Dispensary</option> <option value="12067">Ichomba Clinic</option> <option value="18023">Ichuga Medical Clinic</option> <option value="14556">Icross Dispensary</option> <option value="16577">Ideal Health Laboratory</option> <option value="16578">Ideal Medical /Fp Clinic</option> <option value="12068">Ideal Medical Clinic (Kangundo)</option> <option value="10336">Ideal Medical Clinic (Nyeri North)</option> <option value="20145">IDEWES</option> <option value="12980">IDF Mathare Dispensary</option> <option value="11418">Idsowe Dispensary</option> <option value="15896">Iduku Dispensary</option> <option value="19693">IFACO VCT</option> <option value="13367">Ifmaho Medical Clinic and Laboratory</option> <option value="18799">Ifo 2 Hospital</option> <option value="13368">Ifo Hospital</option> <option value="13263">Iftin Medical and Lab Services</option> <option value="19009">Iftin Medical Clinic</option> <option value="13369">Iftin Sub-District Hospital</option> <option value="16449">Igago Dispensary</option> <option value="12069">Igamatundu Dispensary</option> <option value="10337">Igana Dispensary</option> <option value="12070">Igandene Dispensary</option> <option value="16832">Igane Clinic</option> <option value="15897">Igara Dispensary</option> <option value="13613">Igare Medical Clinic (Sameta)</option> <option value="18864">Igarii Dispensary</option> <option value="10338">Igegania Sub-District Hospital</option> <option value="13614">Igena-Itambe Dispensary</option> <option value="19489">Ignane Health Centre</option> <option value="12071">Igoki Dispensary</option> <option value="18340">Igorera Medical Clinic</option> <option value="15899">Iguhu District Hospital</option> <option value="14557">Igure Dispensary</option> <option value="14558">Igwamiti Dispensary</option> <option value="19800">Igwamiti Medical Clinic</option> <option value="10339">Ihuririo Dispensary</option> <option value="10340">Ihururu Health Centre</option> <option value="10341">Ihururu Medical Clinic</option> <option value="10342">Ihwa Medical Clinic</option> <option value="10343">Ihwagi Medical Clinic</option> <option value="12073">Iiani Catholic Dispensary</option> <option value="12072">Iiani Dispensary</option> <option value="17918">Iiani Dispensary (Kibwezi)</option> <option value="12074">Iiani/Kiatineni Dispensary</option> <option value="13406">Ijara District Hospital - Masalani</option> <option value="13370">Ijara Health Centre</option> <option value="12075">Ikaatini Dispensary</option> <option value="16649">Ikalaasa Dispensary</option> <option value="16958">Ikalyoni Dispensary</option> <option value="12077">Ikanga Sub-District Hospital</option> <option value="13615">Ikerege Clinic</option> <option value="13616">Ikobe Health Centre(Manga)</option> <option value="12078">Ikombe Disp</option> <option value="13617">Ikonge Dispensary</option> <option value="17165">Ikonzo Dispensary</option> <option value="10344">Ikumbi Clinic</option> <option value="14559">Ikumbi Health Centre</option> <option value="12079">Ikumbo Dispensary</option> <option value="12080">Ikutha Health Centre</option> <option value="17610">Ikutha Medical Clinic</option> <option value="18883">Ikuu CFW Clinic</option> <option value="12081">Ikuu Dispensary</option> <option value="12082">Ikuyuni Dispensary</option> <option value="16717">Ikuywa Dispensary</option> <option value="14562">Ilaiser Dispensary</option> <option value="12083">Ilalambyu Dispensary</option> <option value="17337">Ilan Dispensary</option> <option value="19976">Ilatu Dispensary (Makindu)</option> <option value="19269">Ilbissil Medical Clinic</option> <option value="20161">Ilbrah Counseling Centre</option> <option value="17053">Ilchalai Dispensary</option> <option value="15900">Ileho Health Centre</option> <option value="12084">Ilengi Dispensary</option> <option value="12085">Ilika Dispensary</option> <option value="14563">Ilkerin Dispensary (Narok South)</option> <option value="14564">Ilkerin Dispensary (Trans Mara)</option> <option value="14565">Ilkilinyet Dispensary</option> <option value="19676">Ilkilorit Dispeensary</option> <option value="17750">Ilkiremisho Dispensary</option> <option value="14567">Illasit Medical Clinic</option> <option value="12086">Illaut Dispensary</option> <option value="12087">Illeret Health Centre (North Horr)</option> <option value="18251">Illikeek Oodupa Clinic</option> <option value="14568">Illinga'rua Dispensary</option> <option value="19724">Ilparakuo Dispensary</option> <option value="14561">Ilpolei Dispensary</option> <option value="15041">Ilpolosat Dispensary</option> <option value="14569">Iltilal Health Centre</option> <option value="14570">Ilula Dispensary</option> <option value="18586">Iluvya</option> <option value="18977">Im-Hotep Medical Centre</option> <option value="16484">Imalaba Dispensary</option> <option value="18941">Imanga Health Centre</option> <option value="16142">Imani Clinic</option> <option value="16357">Imani Dispensary</option> <option value="12088">Imani Health Care (Machakos)</option> <option value="19469">Imani Health Servises</option> <option value="18177">Imani Hospital</option> <option value="19402">Imani Medical Centre</option> <option value="17669">Imani Medical Centre (Athi River)</option> <option value="16579">Imani Medical Clinic</option> <option value="19286">Imani Medical Clinic ( Mathare A 4)</option> <option value="10345">Imani Medical Clinic (Kiambu West)</option> <option value="10347">Imani Medical Clinic (Muranga North)</option> <option value="19808">Imani Medical Clinic (Nyandarua)</option> <option value="10348">Imani Medical Clinic (Nyeri South)</option> <option value="16752">Imani Medical Clinic (Ruiru)</option> <option value="19193">Imani Medical Clinic Yatta</option> <option value="17885">Imani Medical Services</option> <option value="12089">Imani Yako Medical Clinic</option> <option value="18294">Imani Yako Medical Clinic (Joska)</option> <option value="17685">Imara Health Centre</option> <option value="12981">Imara Medical Clinic</option> <option value="19327">Imarba Dispensary</option> <option value="15901">Imbiakalo Dispensary</option> <option value="19108">Imbirikani Dispensary</option> <option value="20019">Imc Tekeleza Dice - Isebania</option> <option value="19929">Imc Tekeleza Dice Clinic Karungu</option> <option value="19930">Imc Tekeleza Dice Clinic Muhuru</option> <option value="14572">Ime (AIC) Health Centre</option> <option value="19574">Imenti Medical Centre</option> <option value="16581">Imenti X-Ray Services</option> <option value="10518">Immaculate Heart Hospital Kereita</option> <option value="10349">Immaculate Heart of Mary Hospital</option> <option value="10351">Immanuel Medical Clinic</option> <option value="14573">Immurtot Health Centre</option> <option value="17736">Impact Rdo Clinic</option> <option value="18456">Impact Research-Tuungane (Nyando)</option> <option value="12983">Imperial Clinic</option> <option value="16481">Imulama Dispensary</option> <option value="17929">Indangalasia Dispensary</option> <option value="19333">Index Medical Services</option> <option value="14575">Industrial Area Dispensary</option> <option value="15898">Ingavira Medical Clinic</option> <option value="13371">Ingirir Dispensary</option> <option value="15902">Ingotse Dispensary</option> <option value="16329">Inkoirienito Dispensary</option> <option value="19458">Innercore Medical Clinic</option> <option value="18002">Innoculation Centre</option> <option value="17585">Integrated Development Fund (IDF) VCT</option> <option value="17846">International Medical Corps Mobile VCT (Mbita)</option> <option value="14576">Intrepids Dispensary</option> <option value="13618">Inuka Hospital & Maternity Home</option> <option value="20097">Inuka Nursing Home</option> <option value="15903">Inyali Dispensary</option> <option value="12091">Inyuu Dispensary</option> <option value="20158">IOM International Organization for migration(girigiri)</option> <option value="19471">Iom Wellness Clinic</option> <option value="15904">Ipali Health Centre</option> <option value="14577">Ipcc Kaimosi Dispensary</option> <option value="19459">Iqlas Medical Clinic</option> <option value="19408">Iqra Medical Centre</option> <option value="19915">Iqra Medical Centre and Nursing Home</option> <option value="14578">Iraa Dispensary</option> <option value="13619">Iraha Dispensary</option> <option value="19421">Iran Medical Clinic (Ngara)</option> <option value="13620">Iranda Health Centre</option> <option value="14579">Irc Kakuma Hospital</option> <option value="11953">Iresaboru Dispensary</option> <option value="13372">Iresteno Dispensary</option> <option value="10352">Iriaini Medical Clinic</option> <option value="12092">Iriga Dispensary</option> <option value="10353">Irigiro Dispensary</option> <option value="13621">Irondi Dispensary</option> <option value="10354">Iruri Dispensary</option> <option value="14580">Irwaga Health Centre</option> <option value="16425">Isamwera Dispensary</option> <option value="13622">Isana Maternity and Nursing</option> <option value="13623">Isecha Health Centre</option> <option value="16464">Ishiara Sub-District Hospital</option> <option value="13624">Isibania Mission Health Centre</option> <option value="13625">Isibania Sub-District Hospital</option> <option value="14581">Isinet Dispensary</option> <option value="18993">Isinet Medical Clinic</option> <option value="14582">Isinya Health Centre</option> <option value="14583">Isinya Medical Care</option> <option value="19348">Isinya Medical Clinic</option> <option value="19293">Isiolo Central Medical Clinic</option> <option value="12094">Isiolo District Hospital</option> <option value="19410">Isiolo Medical Centre</option> <option value="13373">Islamic Relief Agency</option> <option value="10355">Island Farms Dispensary</option> <option value="12066">Ismc Clinic</option> <option value="13626">Isoge Health Centre</option> <option value="18953">Isra Walmiraj Medical Clinic</option> <option value="19991">Isumba Dispensary</option> <option value="12095">Itabua Police Dispensary</option> <option value="18512">Itando Mission of Hope and Health Centre</option> <option value="18680">Itangani Dispensary</option> <option value="10356">Itara Medical Clinic</option> <option value="14584">Itare Dispensary</option> <option value="14585">Itembe Dispensary</option> <option value="16879">Itembu Dispensary</option> <option value="14586">Iten District Hospital</option> <option value="19936">Itendeu Dispensary</option> <option value="20092">Itetani Dispensary</option> <option value="12096">Ithaeni Dispensary</option> <option value="10357">Ithanga Dispensary</option> <option value="16747">Ithanga Medical Clinic</option> <option value="17059">Ithangarari Dispensary</option> <option value="10358">Ithare Medical Clinic</option> <option value="10359">Ithe-Kahuno Medical Clinic</option> <option value="16653">Itheng'eli Dispensary</option> <option value="12097">Ithimbari Dispensary</option> <option value="19934">Ithumbi Dispensary</option> <option value="19762">Ithuthi Healthcare Unit</option> <option value="10360">Itiati Dispensary</option> <option value="19830">Itiati University Campus Dispensary</option> <option value="13627">Itibo Eramani Dispensary</option> <option value="13628">Itibo Mission Health Centre</option> <option value="13629">Itierio Nursing Home</option> <option value="14587">Itigo Dispensary</option> <option value="18684">Itiko Dispensary</option> <option value="16957">Itithini Dispensary</option> <option value="12098">Itoleka Dispenasry</option> <option value="16934">Itoloni Dispensary</option> <option value="12099">Itongolani Dispensary</option> <option value="19999">Itotia Medical Clinic</option> <option value="12100">Itugururu Dispensary</option> <option value="13630">Itumbe Dispensary</option> <option value="17241">Itumbule Dispensary</option> <option value="10361">Itundu Dispensary</option> <option value="10362">Itundu Medical Clinic</option> <option value="12101">Itunduimuni Health Centre</option> <option value="10363">Ituramiro Medical Clinic</option> <option value="12102">Iuani Health Centre</option> <option value="12103">Iuuma Dispensary</option> <option value="19891">Ivingoni Dispensary (Kibwezi)</option> <option value="15905">Ivona Clinic</option> <option value="12104">Ivuusya Dispensary</option> <option value="13631">Iyabe District Hospital (Kisii South)</option> <option value="17826">J A Comenius Medical Clinic</option> <option value="17222">Jabali Dispensary</option> <option value="18559">Jacaranda Health Limited (Ruiru)</option> <option value="18488">Jacaranda Special School</option> <option value="18333">Jacky Medical Clinic</option> <option value="11421">Jadi Medical Clinic</option> <option value="11423">Jaffery Medical Clinic</option> <option value="16709">Jaggery Medical Clinic</option> <option value="14588">Jagoror Dispensary</option> <option value="10364">Jaima Clinic</option> <option value="13632">Jalaram Nursing Home</option> <option value="13374">Jalish Dispensary</option> <option value="18758">Jalsonga Medical Clinic</option> <option value="12984">Jamaa Mission Hospital</option> <option value="10366">Jamaica Medical Clinic</option> <option value="11424">Jambo Clinic</option> <option value="11425">Jambo Medical Clinic</option> <option value="12106">Jambu Medical Clinic</option> <option value="10367">James Clinic and Lab Services</option> <option value="11426">Jamhuri Medical Clinic</option> <option value="18475">Jamia Islamic Intergrated</option> <option value="17366">Jamia Med Clinic</option> <option value="15906">Jamia Medical Centre</option> <option value="17618">Jamia Mosque Dispensary</option> <option value="12107">Jamii Afya Clinic</option> <option value="16827">Jamii Clinic</option> <option value="11427">Jamii Clinic (Lamu)</option> <option value="12985">Jamii Clinic (Westlands)</option> <option value="14590">Jamii Clinical Services</option> <option value="14115">Jamii Clinical Services Clinic</option> <option value="11429">Jamii Health Care Clinic (Kisauni)</option> <option value="18986">Jamii Health Services</option> <option value="15907">Jamii Health Services Medical Clinic</option> <option value="10368">Jamii Hospital</option> <option value="17265">Jamii Med Clinic</option> <option value="19818">Jamii Medical Clinic</option> <option value="19786">Jamii Medical Clinic</option> <option value="10370">Jamii Medical Clinic (Gatundu)</option> <option value="19819">Jamii Medical Clinic (Kirinyaga North)</option> <option value="16193">Jamii Medical Clinic (Malindi)</option> <option value="16585">Jamii Medical Clinic (Meru)</option> <option value="10371">Jamii Medical Clinic (Muranga North)</option> <option value="12108">Jamii Medical Clinic (Mwala)</option> <option value="14591">Jamii Medical Clinic (Namanga)</option> <option value="19232">Jamii Medical Clinic Masimba</option> <option value="19446">Jamii Medical Clinic Mukuru</option> <option value="18926">Jamii Medical Clinic Vihiga</option> <option value="12986">Jamii Medical Hospital</option> <option value="13375">Jamii Nursing Home</option> <option value="16845">Jamii Private Clinic</option> <option value="19433">Jamii Yadah Medical Centre</option> <option value="14592">Jamji Dispensary</option> <option value="10372">Jamwa Medical Clinic</option> <option value="13376">Jarajara Dispensary</option> <option value="13377">Jaribu Medical Clinic</option> <option value="11430">Jaribuni Dispensary</option> <option value="16448">Jasho Medical Clinic 7</option> <option value="13633">Jawabu (Community) Medical Clinic</option> <option value="14593">Jawabu Medical Clinic</option> <option value="19156">Jeddah Nursing Home and Medical Centre</option> <option value="19170">Jeddah Pharmacy</option> <option value="20064">Jeffrey Medical & Diagnostic Centre</option> <option value="10373">Jehova Jireh Clinic</option> <option value="18825">Jehova Rapha Clinic</option> <option value="14594">Jehova Rapha Medical Clinic</option> <option value="19969">Jehovah Shalom Medical Clinic Lodwar</option> <option value="18560">Jeikei Medical Clinic</option> <option value="10374">Jekam Medical Clinic</option> <option value="19490">Jellin Medical Clinic</option> <option value="14595">Jemunada Dispensary</option> <option value="18765">Jena Medical Clinic</option> <option value="16453">Jepkoyai Dispensary</option> <option value="13634">Jera Dispensary</option> <option value="12987">Jerapha Maternity</option> <option value="12988">Jericho Health Centre</option> <option value="11431">Jericho Medical Clinic</option> <option value="12989">Jerusalem Clinic</option> <option value="17295">Jesmah CFW Clinic</option> <option value="10375">Jesmond (ACK) Dispensary (Mburi)</option> <option value="19669">Jesus Heals Mc</option> <option value="19548">Jesus Is Alive Dental Clinic (Nairobi)</option> <option value="15908">Jesus The Healer Clinic</option> <option value="12109">Jetma Clinic</option> <option value="13635">Jevros Clinic</option> <option value="18672">Jeytee</option> <option value="14596">JFK Engineering Disp</option> <option value="14597">JFK Ii Dispensary</option> <option value="11432">Jibana Sub District Hospital</option> <option value="20121">Jilango Dispensary</option> <option value="11433">Jilore Dispensary</option> <option value="19754">Jimron Medical Clinic</option> <option value="12990">Jinnah Ave Clinic</option> <option value="10377">Jirani Medical Clinic</option> <option value="18854">Jirime Dispensary</option> <option value="12991">Jkia Health Centre</option> <option value="10378">Jkuat Hospital</option> <option value="17702">Jkuat Medical Clinic (Taita-Taveta) Campus</option> <option value="11434">Jocham Hospital</option> <option value="18640">Johani Chemist</option> <option value="17650">Johanna Justin-Jinich Community Clinic (Kibera)</option> <option value="13636">Johpas Clinic</option> <option value="11435">Joint Medical Clinic</option> <option value="16455">Joint Partner Medical Clinic</option> <option value="18968">Jolly Medical Clinic</option> <option value="11437">Jomvu Kuu (MCM) Dispensary</option> <option value="11436">Jomvu Model Health Centre</option> <option value="16802">Jonalifa Clinic</option> <option value="14598">Joppa Medical Clinic</option> <option value="16713">Jordan Baptist Medical Clinic</option> <option value="12110">Jordan Hospital</option> <option value="11439">Jordan Medical Clinic</option> <option value="12111">Jordan Medical Clinic (Kangundo)</option> <option value="18570">Jordan Medical Clinic (Ruiru)</option> <option value="12113">Josan Medical Clinic</option> <option value="16837">Josca Medical Centre & Laboratory</option> <option value="14599">Josdidas Medicare</option> <option value="10379">Joshua Memorial Mbai Dispensary</option> <option value="16586">Joska Medical Care</option> <option value="16227">Joska Medical Care Clinic</option> <option value="10380">Joskae Clinic Kibingoti</option> <option value="19814">Joskar CFW Clinic (Kibingiti)</option> <option value="19300">Josnik Clinic</option> <option value="14600">Joster Medical Clinic</option> <option value="19686">Jowabu Modern Med Lab</option> <option value="17981">Jowama Medical Clinic</option> <option value="17355">Jowhar Dispensary</option> <option value="17329">Joy Bells Medical Clinic</option> <option value="16874">Joy Clinic</option> <option value="19228">Joy Clinic Manyatta</option> <option value="11440">Joy Medical Clinic (Changamwe)</option> <option value="11441">Joy Medical Clinic (Mwatate)</option> <option value="10381">Joy Medical Clinic (Thunguma)</option> <option value="19952">Joy Medical Clinic Chuka</option> <option value="10382">Joy Medical Services (Majengo)</option> <option value="18594">Joy Nursing Home and Maternity</option> <option value="10383">Joy Town Clinic</option> <option value="12114">Joykim Nursing Home</option> <option value="10384">Joyland Medical Clinic</option> <option value="16760">Joytown Special School</option> <option value="19398">Jozi Medical Centre</option> <option value="10385">Jubilee Medical Clinic</option> <option value="11442">Judy Medical Clinic</option> <option value="12992">Juhudi Clinic</option> <option value="12115">Juhudi Medical Clinic</option> <option value="10386">Juja Farm Health Centre</option> <option value="19318">Juja Road Hospital (Nairobi)</option> <option value="14601">Juluk Dispensary</option> <option value="16360">Jumia Medical Clinic</option> <option value="17729">Junction Clinic</option> <option value="16450">Junction Medical Clinic</option> <option value="14602">June Mar Maternity and Medical Centre</option> <option value="11444">Junju Dispensary</option> <option value="18407">Just Meno Limited</option> <option value="14603">Jusus Responds Clinic</option> <option value="16843">Juzippos Health Care Clinic</option> <option value="12116">K K Chogoria Clinic</option> <option value="12117">K K Medical Clinic</option> <option value="18872">K K Mwethe Diispensary</option> <option value="13637">K- Met Clinic</option> <option value="17554">K-Met Corkran</option> <option value="20184">Kaalem Dispensary</option> <option value="14604">Kaaleng Dispensary</option> <option value="12118">Kaani Dispensary</option> <option value="18886">Kaanwa CFW Clinic</option> <option value="18882">Kaanwa CFW Clinic</option> <option value="12119">Kaanwa Dispensary</option> <option value="20001">Kaapus Dispensary</option> <option value="12120">Kaare Dispensary</option> <option value="16854">Kaathari Dispensary (CDF)</option> <option value="12121">Kabaa Dispensary</option> <option value="14605">Kabalwat Dispensary</option> <option value="14606">Kabarak Health Centre</option> <option value="18823">Kabarak University Medical Centre</option> <option value="10388">Kabare Health Centre</option> <option value="14607">Kabarnet District Hospital</option> <option value="17492">Kabarnet Faith Clinic</option> <option value="14608">Kabarnet High School Dispensary</option> <option value="17595">Kabarnet Womens' Clinic</option> <option value="14609">Kabartonjo District Hospital</option> <option value="10389">Kabati Dispensary</option> <option value="16677">Kabati Dispensary (Laikipia West)</option> <option value="17449">Kabati Maternity Nursing Home</option> <option value="17448">Kabati Medical Centre</option> <option value="10391">Kabati Medical Clinic</option> <option value="20070">Kabati Medicare Health Services Nursing Home</option> <option value="14610">Kabatini Health Centre</option> <option value="14611">Kabazi Health Centre</option> <option value="18337">Kabebero AIPCA Dispensary</option> <option value="12993">Kabete Approved School Dispensary</option> <option value="12994">Kabete Barracks Dispensary</option> <option value="14612">Kabetwa Health Centre</option> <option value="14613">Kabianga Health Centre</option> <option value="14614">Kabianga Tea Research</option> <option value="14615">Kabichbich Health Centre</option> <option value="14616">Kabichbich Miss Dispensary</option> <option value="14617">Kabiemit Dispensary (Keiyo)</option> <option value="14618">Kabiemit Dispensary (Mosop)</option> <option value="14619">Kabimoi Dispensary</option> <option value="14620">Kabinga (CHBC) Dispensary</option> <option value="14630">Kabirirsang Dispensary</option> <option value="18065">Kabirirsang Youth Centre</option> <option value="12995">Kabiro Medical Clinic</option> <option value="10390">Kabiruini Health Clinic</option> <option value="14621">Kabisaga Dispensary</option> <option value="14622">Kabitungu Dispensary</option> <option value="17087">Kabiyet Dispensary</option> <option value="14623">Kabiyet Health Centre</option> <option value="14624">Kabobo Health Centre</option> <option value="14625">Kaboeito Dispensary</option> <option value="20007">Kabogor Dispensary</option> <option value="17023">Kaboi Dispensary</option> <option value="14626">Kabolecho Dispensary</option> <option value="13638">Kabondo Sub-District Hospital</option> <option value="14627">Kaborok Dispensary</option> <option value="15910">Kaborom Dispensary</option> <option value="14628">Kaboson Health Centre</option> <option value="14629">Kaboswa Tea Dispensary</option> <option value="15909">Kaboywo Dispensary</option> <option value="16164">Kabras Action Group (KAG) Clinic</option> <option value="15911">Kabuchai Health Centre</option> <option value="12122">Kabuguri Dispensary</option> <option value="15912">Kabula Dispensary</option> <option value="14631">Kabulwo Dispensary</option> <option value="14632">Kabunyeria Health Centre</option> <option value="16480">Kabuodo Dispensary</option> <option value="17531">Kabura Dispensary</option> <option value="17766">Kabururu Dispensary</option> <option value="10392">Kabuteti (AIC) Medical Clinic</option> <option value="10393">Kabuti Clinic</option> <option value="14633">Kabutii-Matiret Dispensary</option> <option value="13639">Kabuto Dispensary</option> <option value="14634">Kacheliba District Hospital</option> <option value="14635">Kacheliba Mobile Clinic</option> <option value="19070">Kacheliba South West Clinic</option> <option value="14636">Kachoda Dispensary</option> <option value="18876">Kachuth Dispensary</option> <option value="18937">Kaciongo Medical Clinic</option> <option value="12123">Kadafu Medical Clinic</option> <option value="11445">Kadaina Community Dispensary</option> <option value="13640">Kadem Tb & Leprosy Dispensary</option> <option value="13641">Kadenge Ratuoro Health Centre</option> <option value="11446">Kaderboy Medical Clinic (Old Town)</option> <option value="16769">Kadhola Dispensary</option> <option value="18696">Kadibo Youth Friendly VCT</option> <option value="17648">Kadija Dispensary</option> <option value="16283">Kadinda Health Centre</option> <option value="16702">Kadokong Dispensary</option> <option value="17186">Kadokony Dispensary</option> <option value="17848">Kadvan Medical Clinic</option> <option value="11447">Kadzinuni Dispensary</option> <option value="17381">Kaelo Dispensary</option> <option value="14637">Kaeris Dispensary</option> <option value="18244">Kaewa Dispensary</option> <option value="11448">Kafuduni Dispensary</option> <option value="11449">Kag-Sombo Medical Clinic</option> <option value="10394">Kagaa Dispensary</option> <option value="14638">Kagai (PCEA) Dispensary</option> <option value="12124">Kageni Med Clinic</option> <option value="13642">Kageno Dispensary</option> <option value="13643">Kager Dispensary</option> <option value="10396">Kagere Dispensary</option> <option value="10397">Kagicha Dispensary</option> <option value="10398">Kagio Catholic Dispensary (Mary Immucate Catholic </option> <option value="10399">Kagio Nursing Home (Kagio)</option> <option value="19937">Kagio Nursing Home (Kerugoya)</option> <option value="18227">Kagioini Catholic Dispensary</option> <option value="12125">Kagoji Dispensary</option> <option value="10400">Kagonye Dispensary</option> <option value="19778">Kagumo Boys High School Clinic</option> <option value="10401">Kagumo College Dispensary</option> <option value="10402">Kagumo Dispensary</option> <option value="10403">Kagumo Live Giving Dispensary/Laboratory</option> <option value="10404">Kagumo Maternity</option> <option value="19775">Kagumo Teachers College Dispensary</option> <option value="10405">Kagumoini Dispensary (Muranga North)</option> <option value="10406">Kagumoini Dispensary (Muranga South)</option> <option value="16971">Kagunduini Dispensary</option> <option value="10408">Kagunduini Medical Clinic (Nyeri South)</option> <option value="10410">Kaguthi Dispensary</option> <option value="13644">Kagwa Health Centre</option> <option value="10411">Kagwathi (SDA) Dispensary</option> <option value="10412">Kagwe Catholic Dispensary</option> <option value="10413">Kagwe Dispensary</option> <option value="10415">Kagwe Health Services Clinic</option> <option value="18358">Kahaaro Dispensary</option> <option value="19774">Kahaaro Medical Clinic</option> <option value="11450">Kahada Medical Clinic</option> <option value="10416">Kahara Medical Clinic</option> <option value="10417">Kaharo Dispensary</option> <option value="10418">Kahatia Medical Clinic</option> <option value="13645">Kahawa Dispensary</option> <option value="12996">Kahawa Garrison Health Centre</option> <option value="10308">Kahawa Wendani Hospital</option> <option value="12997">Kahawa West Health Centre</option> <option value="10419">Kahembe Health Centre</option> <option value="10420">Kaheti Dispensary & Maternity</option> <option value="10421">Kahiga Dispensary</option> <option value="10422">Kahuhia (ACK) Clinic</option> <option value="10423">Kahuho I (AIC) Dispensary</option> <option value="10424">Kahuho Private Dispensary</option> <option value="10425">Kahuro Medical Clinic</option> <option value="10426">Kahuru Dispensary (Nyandarua South)</option> <option value="10427">Kahuru Dispensary (Nyeri North)</option> <option value="10428">Kahuti Medical Clinic</option> <option value="16961">Kaia Dispensary</option> <option value="12127">Kaiani (ABC) Dispensary</option> <option value="17049">Kaiani Dispensary</option> <option value="14639">Kaibei Dispensary</option> <option value="14640">Kaiboi Mission Health Centre</option> <option value="14641">Kaibos Dipensary</option> <option value="14642">Kaigat (SDA) Health Centre</option> <option value="14643">Kaikor Health Centre</option> <option value="16930">Kaikungu Dispensary</option> <option value="10429">Kaimbaga Dispensary</option> <option value="15913">Kaimosi Mission Hospital</option> <option value="14644">Kaimosi Tea Dispensary</option> <option value="14645">Kainuk Health Centre</option> <option value="10430">Kairi Medical Clinic</option> <option value="10431">Kairini Dispensary</option> <option value="10432">Kairo Dispensary</option> <option value="10433">Kairo Medical Clinic</option> <option value="12128">Kairungu Dispensary (Kyuso)</option> <option value="12129">Kairungu Dispensary (Mwingi)</option> <option value="12130">Kairuri Health Centre</option> <option value="10434">Kairuthi Dispensary</option> <option value="14646">Kaisagat Dispensary</option> <option value="14647">Kaisugu Dispensary</option> <option value="17477">Kaitese Dispensary</option> <option value="16225">Kaithe Medical Clinic</option> <option value="16587">Kaithe Stage Medcare</option> <option value="16224">Kaithe Stage Medcare Clinic</option> <option value="14649">Kaitui Dispensary</option> <option value="10435">Kaiyaba Dispensary</option> <option value="17695">Kajabdar Medical Clinic</option> <option value="14650">Kajiado (AIC) Dispensary</option> <option value="14651">Kajiado Christian Medical Centre</option> <option value="14652">Kajiado District Hospital</option> <option value="12131">Kajiampau Dispensary</option> <option value="13646">Kajieyi Dispensary</option> <option value="11451">Kajire Dispensary</option> <option value="12132">Kajuki Health Centre</option> <option value="13647">Kajulu/Gita Dispensary</option> <option value="18928">Kaka Health Clinic</option> <option value="19541">Kaka Medical Centre (Race Course Rd)</option> <option value="15844">Kakamega Central Nursing Home</option> <option value="15914">Kakamega Forest Dispensary</option> <option value="18101">Kakamega Police Line VCT</option> <option value="15915">Kakamega Provincial General Hospital (PGH)</option> <option value="18100">Kakamega VCT Centre (Stand Alone)</option> <option value="12134">Kakeani Dispensary</option> <option value="17961">Kaki Family Medical Clinic</option> <option value="14653">Kakiptui Dispensary</option> <option value="12135">Kako Dispensary</option> <option value="11452">Kakoneni Dispensary</option> <option value="12136">Kakongo Dispensary</option> <option value="19925">Kakuku Dispensary</option> <option value="12137">Kakululo Dispensary</option> <option value="14654">Kakuma Medical Clinic</option> <option value="14655">Kakuma Mission Hospital</option> <option value="12138">Kakungu Dispensary</option> <option value="17268">Kakutha Dispensary</option> <option value="12139">Kakuuni Dispensary</option> <option value="11453">Kakuyuni Dispensary (Malindi)</option> <option value="17888">Kakuyuni Facility</option> <option value="16433">Kakuyuni Health Centre</option> <option value="10437">Kakuzi Limited Dispensary</option> <option value="14656">Kakwanyang Dispensary</option> <option value="14657">Kalaacha Dispensary</option> <option value="17100">Kalabata Dispensary</option> <option value="12141">Kalacha (AIC) Dispensary</option> <option value="12142">Kalacha Dispensary (Chalbi)</option> <option value="18855">Kalacha Model Health Centre (Chalbi)</option> <option value="12143">Kalala Dispensary</option> <option value="14659">Kalalu Dispensary</option> <option value="12144">Kalama Dispensary</option> <option value="17602">Kalambani Dispensary</option> <option value="17089">Kalamene Dispensary</option> <option value="12146">Kalandini Health Centre</option> <option value="16654">Kalanga Dispensary</option> <option value="16726">Kalapata Dispensary</option> <option value="16862">Kalatine Dispensary</option> <option value="12147">Kalawa Health Centre</option> <option value="14660">Kalemungorok Dispensary</option> <option value="12148">Kalewa Dispensary</option> <option value="12149">Kali Dispensary</option> <option value="18079">Kaliakakya Dispensary</option> <option value="12150">Kaliani Health Centre</option> <option value="17030">Kalicha Dispensary</option> <option value="16643">Kalii Dispensary</option> <option value="12151">Kaliku Dispensary</option> <option value="12152">Kalikuvu Dispensary</option> <option value="18479">Kaliluni (AIC) Dispensary</option> <option value="18811">Kalima Dispensary</option> <option value="12153">Kalimani Disensary</option> <option value="17919">Kalimani Dispensary</option> <option value="17231">Kalimapus Dispensary</option> <option value="17064">Kalimbene Dispensary</option> <option value="18200">Kalimoni Hospital (Ruiru)</option> <option value="10438">Kalimoni Hospital (Thika)</option> <option value="12154">Kalisasi Dispensary</option> <option value="12155">Kalitini Dispensary</option> <option value="14662">Kalobeyei Dispensary</option> <option value="14663">Kalokol (AIC) Health Centre</option> <option value="12998">Kaloleni Dispensary</option> <option value="12999">Kaloleni Health Servics</option> <option value="19664">Kaloleni Medical Clinic</option> <option value="18516">Kalulini Dispensary</option> <option value="12156">Kalulini Dispensary (Kibwezi)</option> <option value="12157">Kalunga Dispensary</option> <option value="13648">Kaluo Dispensary</option> <option value="14664">Kalwal Dispensary</option> <option value="14665">Kalyet Clinic (Kipkelion)</option> <option value="16346">Kalyet Clinic (Wareng)</option> <option value="17308">Kalyongwet</option> <option value="19312">Kam ENT Services</option> <option value="19313">Kam Health Services</option> <option value="17660">Kama Medical Clinic</option> <option value="12158">Kamacabi Dispensary</option> <option value="10439">Kamacharia Clinic</option> <option value="19727">Kamacharia Dispensary</option> <option value="10440">Kamae Forest Dispensary</option> <option value="17407">Kamae Medical Clinic</option> <option value="13649">Kamagambo Dispenasry</option> <option value="14666">Kamaget Dispensary</option> <option value="14667">Kamaget Dispensary (Trans Mara)</option> <option value="16239">Kamaguna Dispensary</option> <option value="17212">Kamahindu (AIC) Medical Centre</option> <option value="10441">Kamahuha Dispensary</option> <option value="12159">Kamaindi Dispensary</option> <option value="10442">Kamakwa Medical Clinic</option> <option value="12160">Kamandio Dispensary</option> <option value="16331">Kamangunet VCT</option> <option value="12161">Kamanyaki Dispensary</option> <option value="18513">Kamanyi Dispensary</option> <option value="17098">Kamar Dispensary</option> <option value="14668">Kamara Dispensary</option> <option value="18775">Kamarandi Dispensary</option> <option value="14669">Kamasai Dispensary</option> <option value="17209">Kamasega Dispensary</option> <option value="13650">Kamasengere Dispensary</option> <option value="18802">Kamashia</option> <option value="14670">Kamasia Health Centre</option> <option value="14671">Kamawoi Dispensary</option> <option value="13651">Kambajo Dispensary</option> <option value="12162">Kambandi Dispensary</option> <option value="17527">Kambare Dispensary</option> <option value="16192">Kambe Dispensary</option> <option value="17026">Kambe Kikomani Medical Clinic</option> <option value="16745">Kambi Garba Dispensary</option> <option value="16219">Kambi Ya Juu Catholic Dispensary (Isiolo)</option> <option value="16962">Kambimawe Dispensary</option> <option value="15916">Kambiri Health Centre</option> <option value="10443">Kambirwa Health Centre</option> <option value="10445">Kambiti Dispensary</option> <option value="16216">Kamboe Dispensary</option> <option value="17290">Kamboo Dispensary</option> <option value="11962">Kambu Catholic Dispensary</option> <option value="12090">Kambu Integrated Health Clinic</option> <option value="18596">Kambu Model Health Centre</option> <option value="10446">Kambui (PCEA) Dispensary</option> <option value="10447">Kamburaini Dispensary</option> <option value="10448">Kamburu (PCEA) Dispensary</option> <option value="12163">Kambusu Dispensary</option> <option value="14672">Kamelil Dispensary (Tinderet)</option> <option value="19209">Kamelilo Dispensary</option> <option value="15917">Kamenjo Dispensary</option> <option value="10449">Kamfas Clinic</option> <option value="19488">Kamili Organization</option> <option value="17201">Kamirithu Medical Clinic</option> <option value="18942">Kamiti Maximum Clinic</option> <option value="13000">Kamiti Prison Hospital</option> <option value="16375">Kamketo Dispensary</option> <option value="19189">Kamkomani Dispensary</option> <option value="14673">Kamkong Tea Dispensary</option> <option value="16372">Kamla Bamako Initiative Dispensary</option> <option value="16371">Kamla Community Dispensary</option> <option value="14674">Kamogo Health Centre</option> <option value="14675">Kamoi Dispensary</option> <option value="10450">Kamoko Health Centre</option> <option value="17242">Kamolo Dispensary</option> <option value="14676">Kamongil Dispensary</option> <option value="17234">Kamorow Dispensary</option> <option value="14677">Kampi Samaki Health Centre</option> <option value="17261">Kamuchege Dispensary</option> <option value="18577">Kamujohn Medical Clinic</option> <option value="19654">Kamukunji District Health Management Team Offices</option> <option value="15918">Kamukuywa (ACK) Dispensary</option> <option value="18346">Kamukuywa Dispensary</option> <option value="14883">Kamulat Clinic</option> <option value="10453">Kamumo Medical Clinic</option> <option value="12164">Kamumu Dispensary</option> <option value="15919">Kamuneru Dispensary</option> <option value="10454">Kamung'ang'a (ACK) Dispensary</option> <option value="10455">Kamunyaka Clinic</option> <option value="17913">Kamunyange Dispensary</option> <option value="17640">Kamurguiywa Dispensary</option> <option value="14678">Kamurio Dispensary</option> <option value="12165">Kamusiliu Dispensary</option> <option value="19017">Kamuskut Clinic</option> <option value="12166">Kamutei Health Centre</option> <option value="12167">Kamuthanga Dispensary</option> <option value="12168">Kamuthatha Clinic</option> <option value="13378">Kamuthe Health Centre</option> <option value="18760">Kamuthini Dispensary</option> <option value="16588">Kamuti Clinic</option> <option value="12169">Kamuwongo Dispensary</option> <option value="17831">Kamuyu Dispensary</option> <option value="10456">Kamwangi Health Services</option> <option value="12170">Kamwathu Dispensary</option> <option value="19989">Kamwega Dispensary</option> <option value="19777">Kamwenja Teachers Training College</option> <option value="10458">Kamweti Dispensary</option> <option value="14679">Kamwingi Dispensary</option> <option value="19369">Kamwitha Medcal Centre</option> <option value="14680">Kamwosor Health Centre</option> <option value="14681">Kanakurudio Health Centre</option> <option value="11454">Kanamai Health Care</option> <option value="14682">Kanaodon Dispensary</option> <option value="14683">Kanawoi Dispensary</option> <option value="10459">Kandara Health Centre</option> <option value="18721">Kandaria Medical Centre</option> <option value="18869">Kandebene Dispensary</option> <option value="13652">Kandege Dispensary</option> <option value="10460">Kanderendu Dispensary</option> <option value="13653">Kandiege Sub-District Hospital</option> <option value="10461">Kandong'u Dispensary</option> <option value="14684">Kandutura Dispensary</option> <option value="16860">Kandwia Dispensary</option> <option value="14685">Kangagetei Dispensary</option> <option value="10462">Kangaita Health Centre</option> <option value="10463">Kangaita Medical Clinic (Kirinyaga Central)</option> <option value="14686">Kangakipur Dispensary</option> <option value="17476">Kangalita Dispensary</option> <option value="12171">Kangalu Dispensary</option> <option value="15920">Kanganga Dispensary</option> <option value="10465">Kangari Health Centre</option> <option value="10466">Kangari Medical Clinic</option> <option value="12172">Kangaru Dispensary (Embu)</option> <option value="10468">Kangaru Dispensary (Kirinyaga)</option> <option value="12173">Kangaru Hospital</option> <option value="14687">Kangatosa Dispensary</option> <option value="10469">Kangema Medical Clinic</option> <option value="10470">Kangema Sub-District Hospital</option> <option value="19536">Kangemi Gichagi Dispensary</option> <option value="13001">Kangemi Health Centre</option> <option value="17065">Kangeta G K Prison Dispensary</option> <option value="12174">Kangeta Health Centre</option> <option value="17475">Kangirisae Dispensary</option> <option value="16703">Kanglikwan Dispensary</option> <option value="16818">Kangocho Dispensary</option> <option value="16373">Kangoletiang Dispensary</option> <option value="17106">Kangonde Health Centre</option> <option value="20169">Kangri Dispensary</option> <option value="10471">Kangu Dispensary</option> <option value="19771">Kangubiri Girls High School Clinic</option> <option value="12176">Kangundo Community Clinic</option> <option value="12177">Kangundo District Hospital</option> <option value="12178">Kaningo Health Centre</option> <option value="12179">Kanja Health Centre</option> <option value="10472">Kanjama Dispensary</option> <option value="10436">Kanjinji Dispensary</option> <option value="17001">Kanjora (PCEA) Dispensary</option> <option value="10473">Kanjuiri Health Centre</option> <option value="14688">Kanusin Dispensary</option> <option value="12180">Kanyaa Dispensary</option> <option value="13654">Kanyagwal Dispensary</option> <option value="12181">Kanyakine District Hospital</option> <option value="12183">Kanyangi Mission Dispensary</option> <option value="12184">Kanyangi Sub-District Hospital</option> <option value="14689">Kanyarkwat Dispensary</option> <option value="16931">Kanyekini Dispensary</option> <option value="17834">Kanyenyaini ACK Dispensary</option> <option value="10474">Kanyenyaini Health Centre</option> <option value="10475">Kanyenyaini Medical Clinic</option> <option value="20084">Kanyerus Dispensary</option> <option value="18508">Kanyongonyo</option> <option value="12185">Kanyuambora Dispensary</option> <option value="12186">Kanyunga Health Centre</option> <option value="12187">Kanyungu Dispensary</option> <option value="12188">Kanyuru Dispensary</option> <option value="16994">Kanzau Dispensary</option> <option value="18687">Kanzauwu Dispensary</option> <option value="12190">Kanziku Health Centre</option> <option value="12191">Kanzokea Health Centre</option> <option value="18567">Kanzui Dispensary</option> <option value="12192">Kaongo Health Centre</option> <option value="17105">Kaonyweni Dispensary</option> <option value="16335">Kaparon Health Centre</option> <option value="17317">Kapchanga Dispensary</option> <option value="14690">Kapchebar Dispensary</option> <option value="14691">Kapchebau Dispensary</option> <option value="18064">Kapchebwai Dispensary</option> <option value="14692">Kapchelal Dispensary</option> <option value="14693">Kapchemogen Dispensary</option> <option value="18207">Kapchemuta Dispensary</option> <option value="15921">Kapchemwani Dispensary</option> <option value="17635">Kapchepkok Dispensary</option> <option value="14694">Kapchepkor Dispensary</option> <option value="14695">Kapcherop Health Centre</option> <option value="14696">Kapchorua Tea Dispensary</option> <option value="14697">Kapchumba Dispensary</option> <option value="17722">Kapchumbe Dispensary</option> <option value="14699">Kapedo Sub-District Hospital</option> <option value="14700">Kapelibok Dispensary</option> <option value="14701">Kapenguria District Hospital</option> <option value="14702">Kapindasim Dispensary</option> <option value="18506">Kapisimba Dispensary</option> <option value="13655">Kapiyo Dispensary</option> <option value="14703">Kapkagaron Dispensary</option> <option value="14704">Kapkangani Health Centre</option> <option value="19590">Kapkara Dispensary</option> <option value="14705">Kapkata Dispensary</option> <option value="15922">Kapkateny Dispensary</option> <option value="14706">Kapkatet District Hospital</option> <option value="17656">Kapkatet Hospital VCT</option> <option value="14707">Kapkeben Dispensary</option> <option value="14708">Kapkeburu Dispensary</option> <option value="16354">Kapkei Dispensary</option> <option value="14709">Kapkein Dispensary</option> <option value="17293">Kapkelei</option> <option value="14710">Kapkelelwa Dispensary</option> <option value="14711">Kapkenyeloi Dispensary</option> <option value="14713">Kapkeringoon Dispensary</option> <option value="17808">Kapkesembe Dispensary</option> <option value="14714">Kapkesosio Dispensary</option> <option value="17284">Kapkessum Dispensary</option> <option value="19884">Kapket Dispensary</option> <option value="14715">Kapkiam Dispensary</option> <option value="14716">Kapkiamo Dispensary</option> <option value="17642">Kapkibimbir Dispensary</option> <option value="14717">Kapkimolwa Dispensary</option> <option value="14718">Kapkisiara Dispensary</option> <option value="14719">Kapkitony Dispensary</option> <option value="17417">Kapkoi Disp</option> <option value="14720">Kapkoi Dispensary</option> <option value="14721">Kapkoi Health Centre</option> <option value="14722">Kapkoi Mission Dispensary</option> <option value="14723">Kapkole Dispensary</option> <option value="14724">Kapkolei Dispensary</option> <option value="17019">Kapkomoi Dispensary</option> <option value="17152">Kapkoris Dispensary</option> <option value="14726">Kapkormom Dispensary</option> <option value="14727">Kapkoros Dispensary</option> <option value="17772">Kapkoros Dispensary (Tinderet)</option> <option value="14728">Kapkoros Health Centre</option> <option value="17076">Kapkota Dispensary</option> <option value="19013">Kapkres Medical Clinic</option> <option value="14729">Kapkuei Dispensary</option> <option value="14731">Kapkurer Dispensary</option> <option value="14730">Kapkurer Dispensary (Kericho)</option> <option value="14732">Kapkures Dispensary (Baringo)</option> <option value="17318">Kapkures Dispensary (Kericho)</option> <option value="14733">Kapkures Dispensary (Nakuru Central)</option> <option value="16318">Kapkures Dispensary (Sotik)</option> <option value="17756">Kapkwen Dispensary</option> <option value="17301">Kaplamai Dispensary</option> <option value="14734">Kaplamai Health Centre</option> <option value="14735">Kaplel Dispensary</option> <option value="14736">Kaplelach Chepyakwai</option> <option value="19018">Kaplelach Clinic</option> <option value="14737">Kaplelach Tumoge</option> <option value="14738">Kaplelartet Dispensary</option> <option value="14739">Kaplenge Dispensary</option> <option value="16674">Kapletingi Dispensary</option> <option value="16317">Kapletundo Dispensary</option> <option value="14740">Kaplomboi Dispensary</option> <option value="14741">Kaplong Hospital</option> <option value="14742">Kaplong Medical Clinic</option> <option value="14743">Kapluk Dispensary</option> <option value="17312">Kaplutiet</option> <option value="14745">Kapng'ombe Dispensary</option> <option value="14744">Kapngetuny Dispensary</option> <option value="14746">Kapnyeberai Dispensary</option> <option value="14747">Kapoleseroi Dispensary</option> <option value="14748">Kaprachoge Tea Dispensary</option> <option value="19294">Kaproret Dispensary</option> <option value="14749">Kapsabet District Hospital</option> <option value="17632">Kapsabet Health Care Centre</option> <option value="19281">Kapsabet Medicare Centre</option> <option value="19734">Kapsagawat Dispensary</option> <option value="14750">Kapsait Dispensary</option> <option value="17043">Kapsait Dispensary (Pokot South)</option> <option value="15923">Kapsambu Dispensary</option> <option value="14751">Kapsamoch Dispensary</option> <option value="18148">Kapsang'ar Dispensary</option> <option value="17294">Kapsangaru Dispensary</option> <option value="14752">Kapsaos Dispensary</option> <option value="14753">Kapsara District Hospital</option> <option value="14754">Kapsasian Dispensary</option> <option value="14755">Kapseger Dispensary</option> <option value="14756">Kapsengere Dispensary</option> <option value="14757">Kapset Dispensary</option> <option value="14758">Kapsetek Dispensary</option> <option value="14917">Kapsikak Tea Dispensary</option> <option value="16414">Kapsimbeiywo Dispensary</option> <option value="14759">Kapsimotwa Dispensary</option> <option value="14760">Kapsinendet Dispensary</option> <option value="17631">Kapsirichoi Dispensary</option> <option value="14761">Kapsisiywo Dispensary</option> <option value="16401">Kapsita Dispensary</option> <option value="14762">Kapsitwet Dispensary</option> <option value="18209">Kapsiw Dispensary</option> <option value="14763">Kapsiwon Tea Dispensary</option> <option value="17313">Kapsiya</option> <option value="14764">Kapsogut Dispensary</option> <option value="17138">Kapsoit</option> <option value="19361">Kapsoiyo Dispensary</option> <option value="19388">Kapsokwony Medicare</option> <option value="14765">Kapsomboch Dispensary</option> <option value="19157">Kapsongoi Dispensary</option> <option value="14766">Kapsorok Dispenasry</option> <option value="14767">Kapsowar (AIC) Hospital</option> <option value="14768">Kapsowar Dispensary</option> <option value="14769">Kapsoya Health Centre</option> <option value="17139">Kapsuser</option> <option value="14770">Kapsuser Medical Clinic</option> <option value="14772">Kaptabuk Dispensary</option> <option value="14771">Kaptabuk Dispensary (Marakwet)</option> <option value="14773">Kaptagat Forest Dispensary</option> <option value="14774">Kaptalamwa Health Centre</option> <option value="15924">Kaptalelio Dispensary</option> <option value="15925">Kaptama (Friends) Health Centre</option> <option value="15926">Kaptanai Dispensary</option> <option value="14776">Kaptarakwa Sub-District Hospital</option> <option value="14777">Kaptebengwo Dispensary</option> <option value="16456">Kaptech Dispensary</option> <option value="14778">Kaptel Dispensary</option> <option value="19872">Kapteldet</option> <option value="14779">Kapteldon Health Centre</option> <option value="14780">Kaptembwo Dispensary</option> <option value="14781">Kapteren Health Centre</option> <option value="18185">Kapterit Dispensary</option> <option value="14782">Kaptich Dispensary</option> <option value="17130">Kaptien Community Dispensary</option> <option value="14783">Kaptien Dispensary</option> <option value="17638">Kaptildil Dispensary</option> <option value="14784">Kaptimbor Dispensary</option> <option value="14785">Kaptiony Dispensary</option> <option value="14786">Kaptiony Dispensary (Marakwet)</option> <option value="16457">Kaptisi Dispensary</option> <option value="14787">Kaptoboiti Dispensary</option> <option value="14775">Kaptorokwa Dispensary</option> <option value="17254">Kaptoror Dispensary</option> <option value="14788">Kaptum Dispensary</option> <option value="17758">Kaptum Keiyo Dispensary</option> <option value="14789">Kaptumek Dispensary</option> <option value="14790">Kaptumin Dispensary</option> <option value="14791">Kaptumo Dispensary</option> <option value="14792">Kaptumo Sub-District Hospital</option> <option value="14793">Kapturo Dispensary (Bartabwa)</option> <option value="16725">Kaptuya Dispensary</option> <option value="13002">Kapu Medical Clinic</option> <option value="14795">Kapua Dispensary</option> <option value="17321">Kapune Dispensary</option> <option value="16737">Kapunyany Dispensary</option> <option value="14796">Kaputir Dispensary</option> <option value="14797">Kapweria Dispensary</option> <option value="14798">Kapyego Health Centre</option> <option value="14799">Kapyemit Dispensary</option> <option value="14800">Karaba Dispensary (Laikipia West)</option> <option value="12193">Karaba Dispensary (Mbeere)</option> <option value="10476">Karaba Health Centre (Nyeri South)</option> <option value="12194">Karaba Wango Dispensary</option> <option value="14801">Karagita Dispensary</option> <option value="10477">Karaha Dispensary</option> <option value="19665">Karai Medical Clinic</option> <option value="10478">Karaini (ACK) Dispensary</option> <option value="12195">Karama Dispensary</option> <option value="10479">Karandi Health Clinic</option> <option value="12196">Karandini Dispensary</option> <option value="17771">Karandini Medical Clinic</option> <option value="10480">Karangaita Socfinaf Dispensary</option> <option value="10481">Karangatha Health Centre</option> <option value="10482">Karangi Dispensary</option> <option value="10483">Karangia Health Clinic</option> <option value="17377">Karanjee Medical Clinic</option> <option value="12197">Karare Dispensary</option> <option value="17810">Kararia Dispensary</option> <option value="16174">Karathe Medical Clinic</option> <option value="14802">Karati Dispensary</option> <option value="10484">Karatina Catholic Dispensary</option> <option value="10485">Karatina District Hospital</option> <option value="10486">Karatina Home Based Care Dispensary</option> <option value="18832">Karatina Maternity & Nursing Home</option> <option value="10487">Karatina Medical Services</option> <option value="19998">Karatina Model Health Centre</option> <option value="10488">Karatina Nursing Home</option> <option value="19707">Karatina University Dispensary</option> <option value="10489">Karatu Health Centre</option> <option value="12198">Karau Health Centre</option> <option value="18425">Karbururi Dispensary</option> <option value="14803">Karda Dispensary</option> <option value="10490">Karemeno Dispensary</option> <option value="13003">Karen Health Centre</option> <option value="19714">Karen Hospital (Karatina)</option> <option value="10491">Karen Hospital Annex</option> <option value="15481">Karen Roses Dispensary</option> <option value="19100">Karengata Community Medical Centre</option> <option value="18452">Karerema Dispensary</option> <option value="10492">Kareri Medical Clinic</option> <option value="17588">Kargeno VCT</option> <option value="12199">Kargi Dispensary</option> <option value="17920">Kari Dispensary (Kiboko)</option> <option value="13005">Kari Health Clinic</option> <option value="12200">Karia Dispensary</option> <option value="10493">Karia Health Centre</option> <option value="16998">Karia Health Centre (Nyeri South)</option> <option value="16462">Kariakomo Dispensary</option> <option value="18433">Karibaribi Dispensary</option> <option value="16445">Kariko Dispensary</option> <option value="10494">Kariko Dispensary (Nyeri South)</option> <option value="10495">Karima Catholic Dispensary</option> <option value="15927">Karima Dispensary</option> <option value="10496">Karima Dispensary (Nyeri South)</option> <option value="18670">Karimaini Community Dispensary</option> <option value="12201">Karimba Dispensary</option> <option value="12202">Karimonga Dispensary</option> <option value="10497">Karinga Mission</option> <option value="18743">Kariobangi EDARP</option> <option value="13006">Kariobangi Health Centre</option> <option value="17434">Kariobangi South Clinic</option> <option value="13007">Kariokor Clinic</option> <option value="10499">Kariti Dispensary</option> <option value="10500">Kariua Dispensary</option> <option value="10501">Kariumba Medical Clinic</option> <option value="13008">Karma Dispensary</option> <option value="17995">Karomo Medical Clinic</option> <option value="16237">Karuguaru Dispensary</option> <option value="10504">Karumandi Dispensary</option> <option value="14804">Karuna Dispensary</option> <option value="10505">Karundu Dispensary</option> <option value="19769">Karundu Medical Clinic</option> <option value="14805">Karunga Dispensary</option> <option value="13656">Karungu Sub-District Hospital</option> <option value="17533">Karuoth Dispensary</option> <option value="10506">Karura (SDA) Dispensary</option> <option value="16939">Karura Dispensary</option> <option value="13009">Karura Health Centre (Kiambu Rd)</option> <option value="10508">Karure Medical Clinic</option> <option value="10507">Karuri Health Centre</option> <option value="12203">Karurumo Rhtc</option> <option value="15559">Karuturi Hospital</option> <option value="12204">Kasaala Health Centre</option> <option value="16855">Kasafari Dispensary (CDF)</option> <option value="18768">Kasang'u Dispensary</option> <option value="17948">Kasarani Claycity Medical Centre (Kasarani)</option> <option value="19740">Kasarani Dispensary</option> <option value="13010">Kasarani Health Centre</option> <option value="13011">Kasarani Maternity</option> <option value="14806">Kasarani Medical Clinic</option> <option value="18545">Kasarani Medical Clinic Wote</option> <option value="13012">Kasarani Medical Health Centre</option> <option value="20081">Kasarani VCT</option> <option value="14807">Kasei Dispensary</option> <option value="12206">Kaseve Medical Clinic</option> <option value="16928">Kasevi Dispensary</option> <option value="20153">Kasewe Dispensary</option> <option value="14808">Kasheen Dispenasry</option> <option value="14809">Kasiela Dispensary</option> <option value="11455">Kasigau Rdch</option> <option value="12207">Kasikeu Catholic Health Centre</option> <option value="12208">Kasikeu Dispensary </option> <option value="12209">Kasilili Medical Clinic</option> <option value="18158">Kasimba Medical Clinic</option> <option value="14810">Kasisit Dispensary</option> <option value="14811">Kasitet Dispensary</option> <option value="14812">Kasok Dispensary</option> <option value="18908">Kasolina Medical Clinic</option> <option value="16282">Kasongo Dispensary</option> <option value="17219">Kasphat Dispensary</option> <option value="10509">Kasuku Health Centre</option> <option value="12210">Kasunguni Dispensary</option> <option value="14813">Kasuroi Dispensary</option> <option value="12211">Kasyala Dispensary</option> <option value="14814">Kataboi Dispensary</option> <option value="12212">Katagini Dispensary</option> <option value="12213">Katakani Dispensary</option> <option value="12214">Katalwa Dispensary</option> <option value="12215">Katangi Health Centre</option> <option value="19196">Katangi Medical Clinic</option> <option value="12216">Katangi Mission Health Centre</option> <option value="12217">Katani Dispensary</option> <option value="14815">Kataret Dispensary</option> <option value="17668">Kate Dispensary</option> <option value="14816">Katee Dispensary</option> <option value="12218">Katethya Medical Clinic</option> <option value="17616">Kathaana Dispensary</option> <option value="12220">Kathama Dispensary</option> <option value="12221">Kathande Medical Clinic</option> <option value="12222">Kathangacini Dispensary</option> <option value="19227">Kathangari CFW Clinic</option> <option value="12223">Kathangari Dispensary</option> <option value="12224">Kathangariri (ACK) Clinic</option> <option value="12225">Kathangariri Dispensary</option> <option value="12226">Kathanje Dispensary</option> <option value="12227">Kathanjuri Dispensary</option> <option value="19992">Kathathani Medical Clinic</option> <option value="16434">Katheka Dispensary</option> <option value="17382">Kathelwa Dispensary</option> <option value="12228">Kathelwa Medical Clinic</option> <option value="12229">Kathera Dispensary</option> <option value="17216">Katheri Health Centre</option> <option value="19160">Kathiani Clinic</option> <option value="12230">Kathiani District Hospital</option> <option value="18902">Kathiani Medical Clinic</option> <option value="12232">Kathigu Health Centre</option> <option value="12233">Kathiranga Dispensary</option> <option value="16844">Kathiranga Medical Clinic</option> <option value="12234">Kathithi Dispensary</option> <option value="18847">Kathithine Dispensary</option> <option value="18514">Kathome Dispensary</option> <option value="20182">Kathome Dispensary (Kangundo)</option> <option value="16251">Kathome Medical Clinic</option> <option value="12235">Kathonzweni Catholic Dispensary</option> <option value="12236">Kathonzweni Health Centre</option> <option value="12237">Kathukini Dispensary</option> <option value="12238">Kathulumbi Dispensary</option> <option value="19148">Kathungi Dispensary</option> <option value="12239">Kathunguri Dispensary</option> <option value="12240">Kathyaka Dispensary</option> <option value="14817">Katibel Dispensary</option> <option value="20125">Katilini Dispensary</option> <option value="12241">Katilini Health Cetre</option> <option value="14818">Katilu District Hospital</option> <option value="20040">Katingani Dispensary</option> <option value="16969">Katipanga Dispensary</option> <option value="16940">Katithini Dispensary</option> <option value="13657">Katito Health Centre</option> <option value="18421">Katolo-Manyatta Health Centre</option> <option value="17356">Katote Dispensary</option> <option value="18246">Katothya Dispensary</option> <option value="12242">Katse Health Centre</option> <option value="12243">Katse Medical Clinic</option> <option value="14819">Katuiyo Dispensary</option> <option value="12244">Katulani Health Centre</option> <option value="16991">Katulani Sub District Hospital (Kitui)</option> <option value="12246">Katulye Dispensary</option> <option value="19888">Katulye Dispensary (Kibwezi)</option> <option value="17433">Katulye Dispensary-Nzaui</option> <option value="12247">Katumani Dispensary</option> <option value="12248">Katumbu Dispensary</option> <option value="19235">Katune Dispensary</option> <option value="12249">Katutu Dispensary</option> <option value="12388">Katwala Dispensary</option> <option value="12250">Katwanyaa Medical Clinic</option> <option value="12251">Katyethoka Health Centre</option> <option value="11456">Kau Dispensary</option> <option value="12252">Kauma Dispensary (Kitui)</option> <option value="13658">Kauma Health Centre (Rachuonyo)</option> <option value="12253">Kaumu Dispensary</option> <option value="12720">Kaune's Medical Clinic</option> <option value="18316">Kaunguni Dispensary</option> <option value="14820">Kauriong Dispensary</option> <option value="18230">Kauthulini Dispensary</option> <option value="12255">Kauwi Sub-District Hospital</option> <option value="12256">Kavata Nzou Dispensary</option> <option value="17163">Kavatanzou Dispensary</option> <option value="19977">Kavete Dispensary (Makindu)</option> <option value="12257">Kaviani Health Centre</option> <option value="12258">Kavindu Health Centre</option> <option value="12259">Kavisuni Dispensary</option> <option value="12260">Kavisuni Health Care Clinic</option> <option value="19988">Kavuko Dispensary</option> <option value="12261">Kavumbu Dispensary</option> <option value="16650">Kavumbu Dispensary (Mwala)</option> <option value="12262">Kavuta Dispensary</option> <option value="12263">Kavuthu H/Centre</option> <option value="12264">Kavuvwani Dispensary</option> <option value="19513">Kawangware Health Centre</option> <option value="17615">Kawauni Dispensary</option> <option value="10511">Kaweru Medical Clinic</option> <option value="12265">Kawethei Medical Clinic</option> <option value="12266">Kawiria Maternity and Nursing Home</option> <option value="17262">Kawiru Dispensary</option> <option value="19076">Kawongo Medical Centre</option> <option value="16340">Kayanet Clinic</option> <option value="12267">Kayatta Dispensary</option> <option value="16710">Kayaya Dispensary</option> <option value="13014">Kayole Hospital</option> <option value="13015">Kayole I Health Centre</option> <option value="13016">Kayole Ii Sub-District Hospital</option> <option value="12268">Kea Dispensary</option> <option value="13659">Kebaroti Dispensary</option> <option value="14821">Keben Dispensary</option> <option value="14822">Kebeneti (SDA) Health Centre</option> <option value="14823">Kebeneti Dispensary</option> <option value="13660">Kebirigo Mission Health Centre</option> <option value="14824">Kedowa Dispensary</option> <option value="16960">Kee Dispensary</option> <option value="17958">Keega Medical Clinic</option> <option value="17435">Keera Dispensary</option> <option value="18729">Kefra Clinic</option> <option value="13661">Kegati Medical Clinic</option> <option value="13662">Kegogi Health Centre</option> <option value="15928">Kegondi Health Centre</option> <option value="13663">Kegonga District Hospital</option> <option value="13664">Kehancha Clinic</option> <option value="13665">Kehancha Nursing and Maternity Home</option> <option value="19752">Keiyo Dispensary</option> <option value="17504">Kema Medical Clinic</option> <option value="17083">Kembu Dispensary</option> <option value="14825">Kemeloi Health Centre</option> <option value="13666">Kemera Dispensary (Manga)</option> <option value="18301">Kemri Clinic</option> <option value="18505">Kemri Mimosa</option> <option value="11458">Kemri Staff Clinic and VCT Centre</option> <option value="13019">Kemri VCT</option> <option value="20146">KEMRI/CDC Health Services</option> <option value="18357">Kemsa Staff Clinic</option> <option value="19084">Kemu Medical Clinic</option> <option value="19871">Ken Ame Health Centre</option> <option value="18620">Kendi Medical Clinic</option> <option value="13667">Kendu Adventist Hospital</option> <option value="13668">Kendu Sub-District Hospital</option> <option value="14826">Kenegut Dispensary</option> <option value="14827">Kenene Dispensary</option> <option value="13669">Kengen Clinic</option> <option value="17332">Kengen Staff Clinic</option> <option value="10512">Kenol Hospital</option> <option value="17544">Kentalya Farm Cilinic</option> <option value="10513">Kenton Dispensary</option> <option value="13020">Kenwa</option> <option value="17489">Kenwa Kiandutu</option> <option value="10514">Kenwa-Nyeri</option> <option value="13670">Kenya Acorn Project (Acorn) Health Centre</option> <option value="13013">Kenya AIDS Vaccine Initiative (Kavi)</option> <option value="18261">Kenya Airports Employees Association</option> <option value="13021">Kenya Airways Medical Centre</option> <option value="18732">Kenya Assemblies of God Medical Clinic</option> <option value="18575">Kenya Assemblies of God Medical Clinic (K<NAME></option> <option value="18385">Kenya Association of Pofessional Counsellors (Kapc</option> <option value="10515">Kenya Institute of Professional Counsellors</option> <option value="19599">Kenya Long Distance Truck Drivers Union VCT</option> <option value="17040">Kenya Medical Training College Lodwar</option> <option value="12517">Kenya Methodist University Dispensary</option> <option value="11459">Kenya Navy (Mir) Hospital</option> <option value="10516">Kenya Nut Company Dispensary</option> <option value="10517">Kenya Police College Dispensary</option> <option value="18212">Kenya Ports Authority Staff Clinic</option> <option value="13022">Kenya Utalii Dispensary</option> <option value="14828">Kenyagoro Dispensary</option> <option value="13671">Kenyambi Health Centre</option> <option value="16980">Kenyambi Health Centre (Nyamira)</option> <option value="13023">Kenyatta National Hospital</option> <option value="19093">Kenyatta National Hospital Ongata Rongai</option> <option value="13024">Kenyatta University Dispensary</option> <option value="17534">Kenyatta University Health Unit Mombasa Campus</option> <option value="18879">Kenyatta University Kitui Campus Health Unit</option> <option value="13673">Kenyenya District Hospital</option> <option value="20141">Kenyenya Health Centre</option> <option value="17712">Kenyenya Medical Centre (Kenyenya)</option> <option value="17677">Kenyenya Medical Clinic (Kenyenya)</option> <option value="13675">Kenyerere Dispensary (Masaba)</option> <option value="13674">Kenyerere Dispensary (Sameta)</option> <option value="16280">Kenyerere Health Centre (Nyamira)</option> <option value="19996">Kenyoro Dispensary</option> <option value="13676">Kenyoro Health Centre</option> <option value="14829">Kepchomo Tea Dispensary</option> <option value="18336">Keragia Dispensary (Gucha)</option> <option value="14830">Kerenga Dispensary</option> <option value="19257">Kerer Dispensary</option> <option value="19362">Kereri Dispensary</option> <option value="14831">Kericho District Hospital</option> <option value="14832">Kericho Forest Dispensary</option> <option value="14833">Kericho Municipal Health Centre</option> <option value="14834">Kericho Nursing Home</option> <option value="17590">Kericho Youth Centre</option> <option value="18163">Kericho Youth Centre</option> <option value="14835">Keringani Dispensary</option> <option value="14837">Keringet Health Centre</option> <option value="14836">Keringet Health Centre (Kuresoi)</option> <option value="18587">Keringet Youth Friendly Centre</option> <option value="14838">Kerio Health Centre</option> <option value="13677">Keritor Dispensary</option> <option value="17232">Kerobo Health Centre</option> <option value="14839">Kerol Health Centre</option> <option value="14840">Kerol Health Services</option> <option value="10519">Kerugoya Catholic Dispensary</option> <option value="10520">Kerugoya District Hospital</option> <option value="10522">Kerugoya Medical Centre</option> <option value="10525">Kerugoya Medical Laboratory</option> <option value="16502">Kerugoya Medical Services and Advisory Centre</option> <option value="16868">Kerumbe Dispensary</option> <option value="10523">Kesma Clinic</option> <option value="19363">Kesogon Dispensary</option> <option value="17159">Kesot Dispensary</option> <option value="14841">Kesses Health Centre</option> <option value="14842">Ketepa Dispensary (Kericho)</option> <option value="17210">Ketitui Dispensary</option> <option value="14843">Keturwo Dispensary</option> <option value="13679">Keumbu Medical Clinic</option> <option value="13680">Keumbu Sub-District Hospital</option> <option value="12269">Kevote Catholic Dispensary</option> <option value="16415">Kewamoi Dispensary</option> <option value="17327">Keyian SDA Dispensary</option> <option value="18695">Khaburu Chemist</option> <option value="18644">Khaburu Chemist</option> <option value="15929">Khachonge Dispensary</option> <option value="16182">Khadija Medical Clinic</option> <option value="15930">Khaja Medical Clinic</option> <option value="15931">Khalaba Health Centre</option> <option value="17881">Khalaba Medical Clinic</option> <option value="18362">Khalala Dispensary</option> <option value="13379">Khalalio Health Centre</option> <option value="15932">Khalumuli Dispensary</option> <option value="15933">Khaoya Dispensary</option> <option value="15934">Kharanda Dispensary</option> <option value="14844">Khartoum Tea Dispensary</option> <option value="15935">Khasoko Health Centre</option> <option value="15936">Khaunga Dispensary</option> <option value="18240">Khayega Community Clinic</option> <option value="15937">Khayo Dispensary</option> <option value="19097">KHE Farm Dispensary</option> <option value="15484">Khems Medical Clinic</option> <option value="10524">Khilna Medical Clinic</option> <option value="13380">Khorof Harar Sub-District Hospital</option> <option value="17041">Khulwanda Dispensary</option> <option value="15938">Khumsalaba Clinic</option> <option value="15939">Khunyangu Sub-District Hospital</option> <option value="15940">Khwisero Health Centre</option> <option value="10526">Kiaguthu Dispensary</option> <option value="13681">Kiagware Dispensary</option> <option value="10527">Kiahuria Medical Clinic</option> <option value="17953">Kiaibabu Dispensary</option> <option value="10528">Kiairathe Dispensary</option> <option value="10529">Kiairegi Clinic</option> <option value="12270">Kiairugu Dispensary</option> <option value="10530">Kiamabara Dispensary</option> <option value="10531">Kiamagunyi (ACK) Clinic</option> <option value="10532">Kiamanyeki Dispensary</option> <option value="10533">Kiamara Dispensary</option> <option value="10534">Kiamara Medical Clinic</option> <option value="10535">Kiamariga Medical Clinic</option> <option value="10536">Kiamathaga Dispensary</option> <option value="17396">Kiambaa Medical Clinic</option> <option value="12271">Kiambere Dam Dispensary</option> <option value="16465">Kiambere Health Centre</option> <option value="16408">Kiamberiria Dispensary (CDF)</option> <option value="14845">Kiambogo Dispensary (Naivasha)</option> <option value="10537">Kiambogo Dispensary (Nyandarua South)</option> <option value="10538">Kiambogo Medical Clinic</option> <option value="17564">Kiambogo Medical Clinic (Wanjohi)</option> <option value="10539">Kiambu District Hospital</option> <option value="10540">Kiambu Institute of Science and Technology Dispens</option> <option value="18032">Kiambu Medical Centre</option> <option value="17016">Kiambuthia Dispensary</option> <option value="10541">Kiambuthia Medical Clinic</option> <option value="17468">Kiamiriru MCK Dispensary</option> <option value="13683">Kiamokama Health Centre</option> <option value="12272">Kiamuchairu Health Centre</option> <option value="12273">Kiamuchii Dispensary</option> <option value="10542">Kiamuiru Medical Clinic</option> <option value="12274">Kiamuringa Dispensary</option> <option value="12275">Kiamuriuki Dispensary</option> <option value="19431">Kiamuthambi Dispensary</option> <option value="10543">Kiamuthambi Medical Clinic</option> <option value="16497">Kiamutugu CFW Clinic</option> <option value="10544">Kiamutugu Clinic</option> <option value="10545">Kiamutugu Health Centre</option> <option value="10546">Kiamuya Dispensary</option> <option value="10547">Kiamwathi Medical Clinic</option> <option value="17258">Kianda Dispensary</option> <option value="10549">Kiandai Clinic</option> <option value="10551">Kiandegwa (Methodist Church of Kenya) Dispensary</option> <option value="10552">Kiandere Dispensary</option> <option value="19430">Kianderi Dispensary</option> <option value="17709">Kiandiu Dispensary</option> <option value="10553">Kiandu Medical Clinic</option> <option value="16814">Kiandutu Health Centre</option> <option value="10554">Kiane Medical & Eye Clinic</option> <option value="16989">Kiang'inda Health Centre</option> <option value="10555">Kiang'ombe Dispensary</option> <option value="11463">Kiangachinyi Dispensary</option> <option value="10556">Kiangai Dispensary</option> <option value="16503">Kiangai Laboratory</option> <option value="10557">Kiangai Medical Clinic</option> <option value="12276">Kiangini Dispensary</option> <option value="10558">Kiangochi Dispensary</option> <option value="12277">Kiangondu Dispensary</option> <option value="13684">Kiangoso Dispensary</option> <option value="18848">Kiangua Dispensary</option> <option value="10559">Kiangunyi Dispensary</option> <option value="10561">Kiangwenyi Clinic</option> <option value="10562">Kianjege Dispensary</option> <option value="20155">Kianjokoma Muungano SHG Community Dispensary</option> <option value="12278">Kianjokoma (ACK) Trinity Clinic</option> <option value="12279">Kianjokoma Sub-District Hospital</option> <option value="14846">Kianjoya Dispensary</option> <option value="16172">Kianjugu Dispensary</option> <option value="10564">Kianyaga Catholic Health Centre</option> <option value="10565">Kianyaga Sub-District Hospital</option> <option value="12281">Kiaoni Dispensary (Kibwezi)</option> <option value="10566">Kiaragana Dispensary</option> <option value="12283">Kiarago Health Centre (Imenti South)</option> <option value="17571">Kiarithaini Dispensary</option> <option value="10567">Kiaruhiu (PCEA) Health Centre</option> <option value="10568">Kiaruhiu Medical Clinic</option> <option value="13685">Kiaruta Dispensary</option> <option value="17060">Kiarutara Dispensary</option> <option value="13686">Kiasa Dispensary</option> <option value="17935">Kiati Dispensary</option> <option value="19110">Kiatineni Dispensary</option> <option value="18014">Kiawa Medical Clinic</option> <option value="16782">Kiawaithanji Medical Clinic</option> <option value="19595">Kiawakara Dispensary</option> <option value="10570">Kiawarigi Medical Clinic</option> <option value="14847">Kibabet Tea Dispensary</option> <option value="15941">Kibabii Health Centre</option> <option value="14848">Kibagenge Dispensary</option> <option value="18293">Kiban Medical Clinic</option> <option value="12285">Kiban Medical Clinic (Kangundo)</option> <option value="11464">Kibandaongo Dispensary</option> <option value="12280">Kibaranyaki Dispensary</option> <option value="14849">Kibendo Dispensary</option> <option value="12894">Kibera Chemi Chemi Ya Uzima Clinic</option> <option value="13028">Kibera Community Health Centre - Amref</option> <option value="20183">Kibera Community Self Help Program - Migori </option> <option value="13029">Kibera D O Dispensary</option> <option value="18984">Kibera Highway Clinic</option> <option value="13026">Kibera Human Development Clinic</option> <option value="13030">Kibera South (Msf Belgium) Health Centre</option> <option value="17088">Kibias Dispensary</option> <option value="13687">Kibigori Dispensary</option> <option value="14850">Kibigos Dispensary</option> <option value="15942">Kibingei Dispensary</option> <option value="14851">Kibingor Dispensary</option> <option value="14852">Kibini Hill (PCEA) Dispensary</option> <option value="19134">Kibirichia Health & Laboratory Services</option> <option value="16824">Kibirichia Health Services</option> <option value="12284">Kibirichia Maternity and Nursing Home</option> <option value="16825">Kibirichia Medcare</option> <option value="18149">Kibirichia Medical Clinic</option> <option value="12282">Kibirichia Sub-District Hospital</option> <option value="10571">Kibirigwi Health Centre</option> <option value="16504">Kibirigwi Laboratory</option> <option value="17707">Kibiru Dispensary</option> <option value="17102">Kibiryokwonin Dispensary</option> <option value="19366">Kibisem Dispensary</option> <option value="14854">Kibish Dispensary</option> <option value="15943">Kibisi Dispensary</option> <option value="13688">Kibogo Dispensary</option> <option value="14855">Kiboino Dispensary</option> <option value="12286">Kiboko Dispensary (Makindu)</option> <option value="19349">Kiboko Medical Clinic</option> <option value="11465">Kibokoni Medical Clinic</option> <option value="19839">Kibomet Medical Clinic</option> <option value="19364">Kibongwa Dispensary</option> <option value="19390">Kibonze Dispenary</option> <option value="13689">Kibos Sugar Research Dispensary</option> <option value="10573">Kibubuti Dispensary</option> <option value="14856">Kibugat Dispensary</option> <option value="12287">Kibugu Health Centre</option> <option value="12288">Kibugua Health Centre</option> <option value="15944">Kibuke Dispensary</option> <option value="12289">Kibunga Sub-District Hospital</option> <option value="12290">Kiburine Dispensary</option> <option value="10574">Kiburu Dispensary</option> <option value="10575">Kiburu Laboratory</option> <option value="10577">Kibutha Dispensary</option> <option value="10578">Kibutha Medical Clinic</option> <option value="11466">Kibuyuni Dispensary</option> <option value="14857">Kibwareng Health Centre</option> <option value="14858">Kibwari Tea Dispensary</option> <option value="12737">Kibwezi Catholic Dispensary</option> <option value="12056">Kibwezi Health Care Clinic</option> <option value="12063">Kibwezi Huruma Medical Clinic and Laboratory</option> <option value="12291">Kibwezi Sub District Hospital</option> <option value="11467">Kichaka Simba Dispensary</option> <option value="14859">Kichwa Tembo Dispensary</option> <option value="10579">Kids Alive Dispensary</option> <option value="13031">Kie/Kapc</option> <option value="12292">Kiegoi Dispensary</option> <option value="18077">Kiembe Dispensary</option> <option value="11468">Kiembeni Community</option> <option value="18331">Kiembeni Medical Clinic</option> <option value="12294">Kiengu Maternity and Nursing Home</option> <option value="10580">Kieni Dispensary (Gatundu)</option> <option value="12296">Kieni Kia Ndege Dispensary</option> <option value="12295">Kieni Model Health Centre</option> <option value="12297">Kiereni Dispensary</option> <option value="12298">Kigaa Dispensary</option> <option value="10581">Kiganjo Dispensary</option> <option value="10582">Kiganjo Health Centre</option> <option value="10583">Kiganjo Medical Care Clinic</option> <option value="18878">Kiganjo Medical Centre</option> <option value="10584">Kigetuini Dispensary</option> <option value="11469">Kighombo Dispensary</option> <option value="12299">Kigogo Dispensary</option> <option value="10585">Kigongo Medical Clinic</option> <option value="10586">Kigoro Dispensary</option> <option value="16235">Kiguchwa Dispensary</option> <option value="12300">Kigumo Dispensary</option> <option value="10587">Kigumo Health Centre (Kiambu East)</option> <option value="10588">Kigumo Health Centre (Muranga South)</option> <option value="13691">Kigwa Dispensary</option> <option value="10590">Kihaaro Medical Clinic</option> <option value="10591">Kihara Sub-District Hospital</option> <option value="14860">Kihato Dispensary</option> <option value="14861">Kihia Medical Clinic</option> <option value="10592">Kihinga Dispensary</option> <option value="18020">Kihinga Medical Clinic</option> <option value="16390">Kihingo Dispensary (CDF)</option> <option value="10593">Kihora Medical Clinic</option> <option value="10594">Kihoya Dispensary</option> <option value="10595">Kihoya Medical Centre</option> <option value="10596">Kihugiru Maternity Disp</option> <option value="10598">Kihumbu-Ini Community Dispensary</option> <option value="10597">Kihumbuini (PCEA) Dispensary</option> <option value="17000">Kihuri Dispensary</option> <option value="10599">Kihuro (ACK) Dispensary</option> <option value="10600">Kihuti Orthodox Clinic</option> <option value="10601">Kihuyo Dispensary</option> <option value="17214">Kiija Dispensary</option> <option value="19233">Kiima Kiu Dispensary</option> <option value="17443">Kiima Kiu Health Care Services Dispensary</option> <option value="17818">Kiimani Medical Clinic</option> <option value="12301">Kiini Health Centre</option> <option value="12302">Kiirua Dispensary</option> <option value="12304">Kiitini Dispensary</option> <option value="10602">Kijabe (AIC) Hospital</option> <option value="10693">Kijabe (AIC) Hospital Marira Medical Clinic</option> <option value="17821">Kijani (Mirera) Dispensary</option> <option value="13692">Kijauri Sub District Hospital</option> <option value="16765">Kijawa Dispensary</option> <option value="11470">Kikambala Catholic Medical Clinic</option> <option value="11471">Kikambala Medical Services</option> <option value="12305">Kikesa Dispensary</option> <option value="16932">Kikiini Dispensary</option> <option value="19832">Kikinga Medical Clinic</option> <option value="12306">Kikoko Mission Hospital</option> <option value="11472">Kikoneni Health Centre</option> <option value="18944">Kikopey Dispensary</option> <option value="13033">Kikoshep Kenya (Mugumoini)</option> <option value="14863">Kikton Medical Clinic</option> <option value="18689">Kikule Dispensary</option> <option value="12307">Kikumini Dispensary</option> <option value="17147">Kikumini Dispensary (Makueni)</option> <option value="12308">Kikumini Health Centre</option> <option value="18683">Kikuu Dispensary</option> <option value="10603">Kikuyu (PCEA) Hospital</option> <option value="17612">Kikuyuni Dispensary</option> <option value="12309">Kilala Health Centre</option> <option value="16648">Kilawa Dispensary</option> <option value="12310">Kilawani Medical Clinic</option> <option value="16197">Kilelengwani Dispensary</option> <option value="12311">Kilembwa Dispensary</option> <option value="14864">Kilgoris (Cog) Dispensary</option> <option value="14865">Kilgoris Medical Centre</option> <option value="11473">Kilibasi Dispensary</option> <option value="14866">Kilibwoni Health Centre</option> <option value="11474">Kilifi District Hospital</option> <option value="11475">Kilifi Plantation Dispensary</option> <option value="16921">Kiliku Dispensary</option> <option value="12312">Kilili Dispensary</option> <option value="17380">Kililii Dispensary</option> <option value="11476">Kilimangodo Dispensary</option> <option value="18249">Kilimanjaro Medical Clinic</option> <option value="13034">Kilimanjaro Nursing Home</option> <option value="16210">Kilimanjaro Skin & Medical Clinic</option> <option value="20031">Kilimu Dispensary</option> <option value="15945">Kilingili Health Centre</option> <option value="16428">Kilinito Dispensary (CDF)</option> <option value="18004">Kilisa Dispensary</option> <option value="13381">Kiliweheri Health Centre</option> <option value="12313">Kilome Nursing Home</option> <option value="19945">Kiltamany Dispensary</option> <option value="16926">Kilulu Dispensary</option> <option value="12314">Kilungu Sub-District Hospital</option> <option value="16590">Kim's Intergrated Clinic</option> <option value="15946">Kima Mission Hospital</option> <option value="12315">Kimachia Dispensary</option> <option value="15947">Kimaeti Dispensary</option> <option value="10605">Kimahuri Medical Clinic</option> <option value="14867">Kimalel Health Centre</option> <option value="15948">Kimalewa Health Centre</option> <option value="14868">Kimana Health Centre</option> <option value="10606">Kimandi Clinic and Laboratory</option> <option value="12316">Kimangao Dispensary</option> <option value="15949">Kimangeti Dispensary</option> <option value="14869">Kimanjo Dispensary</option> <option value="19967">Kimathi Dispensary</option> <option value="19330">Kimathi Street Medical Centre</option> <option value="18228">Kimathi University College Medical Clinic</option> <option value="16671">Kimawit-Uswet Dispensary</option> <option value="10607">Kimbimbi Medical Clinic</option> <option value="10608">Kimbimbi Medical Laboratory</option> <option value="10609">Kimbimbi Sub-District Hospital</option> <option value="20130">Kimeeni Dispensary</option> <option value="10610">Kimende Orthodox Mission Health Centre</option> <option value="15950">Kimilili District Hospital</option> <option value="14871">Kimilili Medical Clinic</option> <option value="14872">Kiminini Cottage Hospital</option> <option value="16362">Kiminini Health Centre</option> <option value="19681">Kiminini Medical Centre & Laboratory</option> <option value="19680">Kiminini Pag VCT</option> <option value="14873">Kimintet Dispensary</option> <option value="16436">Kimiti Model Health Centre</option> <option value="18885">Kimkan Health Services</option> <option value="17198">Kimlea Medical Clinic</option> <option value="14874">Kimnai Dispensary</option> <option value="16720">Kimng'oror (ACK) Health Centre</option> <option value="20006">Kimngorom Dispensary</option> <option value="16458">Kimogoi Dispensary</option> <option value="16334">Kimoloi Dispensary</option> <option value="14875">Kimolwet Dispensary</option> <option value="14876">Kimondi Forest Dispensary</option> <option value="14877">Kimondo Dispensary</option> <option value="10611">Kimondo Medical Clinic</option> <option value="14878">Kimong Dispensary</option> <option value="13693">Kimonge Dispensary</option> <option value="14879">Kimoning Dispensary</option> <option value="11477">Kimorigho Dispensary</option> <option value="11478">Kimorigo Dispensary</option> <option value="20009">Kimose Dispenary</option> <option value="14870">Kimout Dispensary</option> <option value="19644">Kims Medical Clinic</option> <option value="14880">Kimsaw Medical Clinic</option> <option value="18524">Kimuchul Dispensary</option> <option value="18914">Kimue Medical Clinic and Laboratory</option> <option value="18129">Kimugu Dispensary</option> <option value="16398">Kimugul Dispensary</option> <option value="14881">Kimugul Dispensary (Baringo North)</option> <option value="14882">Kimugul Dispensary (Kipkelion)</option> <option value="17999">Kimulot Dispensary</option> <option value="10612">Kimunyu (PCEA) Dispensary</option> <option value="14884">Kimuren Dispensary</option> <option value="17416">Kimuri Disp</option> <option value="17028">Kimuri Dispensary</option> <option value="12317">Kimutwa Dispensary</option> <option value="12318">Kimutwa Medical Clinic</option> <option value="17605">Kimweli Dispensary</option> <option value="12319">Kina Dispensary</option> <option value="11479">Kinagoni Dispensary</option> <option value="12320">Kinakoni Dispensary</option> <option value="10613">Kinale Forest Dispensary</option> <option value="19790">Kinamba Medical Clinic</option> <option value="11480">Kinango Hospital</option> <option value="16518">Kinango Medical Clinic</option> <option value="12321">Kinanie Dispensary</option> <option value="11481">Kinarani Dispensary</option> <option value="13694">Kinasia Dispensary</option> <option value="13695">Kineni Dispensary</option> <option value="11303">King'orani Prison Dispensary</option> <option value="14887">King'wal Dispensary</option> <option value="19623">Kinga Medical Clinic (Dandora)</option> <option value="20003">Kingorani Community Clinic</option> <option value="17545">Kings Clinic</option> <option value="19436">Kings Cross Medical Clinic</option> <option value="14886">Kings Medical Centre (Delivarance) Nakuru</option> <option value="11482">Kingstone Medical Clinic</option> <option value="12322">Kinisa Dispensary</option> <option value="10614">Kinja Dispensary</option> <option value="16846">Kinjo Medical Clinic</option> <option value="19625">Kinmed Medical Clinic (Dandora)</option> <option value="12323">Kinna Health Centre</option> <option value="16547">Kinondo Kwetu Community Clinic</option> <option value="12324">Kinoro Medical Clinic</option> <option value="12325">Kinoro Sub-District Hospital</option> <option value="12326">Kinoru Dispensary</option> <option value="10615">Kinunga Health Centre</option> <option value="10616">Kinunga Medical Clinic</option> <option value="16381">Kinungi Dispensary</option> <option value="12327">Kinyaata Dispensary</option> <option value="14888">Kinyach Dispensary</option> <option value="16196">Kinyadu Dispensary</option> <option value="19893">Kinyambu Dispensary</option> <option value="20108">Kinyambu Kwitu Medical Clinic</option> <option value="10617">Kinyangi Health Centre</option> <option value="17307">Kinyona Dispensary</option> <option value="10618">Kinyona Health Clinic</option> <option value="19917">Kiobegi Dispensary (Nyamache)</option> <option value="20113">Kioge Disp</option> <option value="13696">Kiogoro Health Centre</option> <option value="16655">Kiomo Dispensary</option> <option value="18678">Kiongwe Dispensary</option> <option value="12328">Kionyo Dispensary (Imenti South)</option> <option value="13697">Kionyo Health Centre (Nyamache)</option> <option value="12329">Kionyo Medical Clinic</option> <option value="11483">Kipao Dispensary</option> <option value="20095">Kipawa Medical Centre</option> <option value="14889">Kipcherere Dispensary</option> <option value="14890">Kipchimchim M Hospital</option> <option value="19251">Kipegenda Dispensary</option> <option value="14891">Kipeto Dispensary</option> <option value="16269">Kipingi Dispensary</option> <option value="11484">Kipini Health Centre</option> <option value="19792">Kipipiri Medical Centre</option> <option value="14892">Kipkabus Forest Dispensary</option> <option value="14893">Kipkabus Health Centre</option> <option value="15951">Kipkaren Clinic</option> <option value="13698">Kipkebe Health Centre</option> <option value="14894">Kipkeibon Tea Dispensary</option> <option value="14895">Kipkeikei Dispensary</option> <option value="14896">Kipkelion (CHFC) Dispensary</option> <option value="14897">Kipkelion Sub District Hospital</option> <option value="14898">Kipkenyo Dispensary</option> <option value="14899">Kipketer Dispensary</option> <option value="17091">Kipkitur Dispensary</option> <option value="14900">Kipkoigen Tea Dispensary</option> <option value="14901">Kipkoimet Tea Dispensary</option> <option value="19883">Kipkonyo Dispensary</option> <option value="17014">Kipkoror Dispensary</option> <option value="18186">Kipkundul Dispensary</option> <option value="14902">Kiplalmat Dispensary</option> <option value="17316">Kiplelgutik Dispensary</option> <option value="14903">Kiplelji Dispensary</option> <option value="18525">Kiplobotwa Dispensary</option> <option value="17299">Kiplobotwo Dispensary</option> <option value="14904">Kiplombe AIC Dispensary</option> <option value="17154">Kiplombe Dispensary (Koibatek)</option> <option value="16733">Kipnai Dispensary</option> <option value="14905">Kipngchoch Medical Clinic</option> <option value="16473">Kiprengwet Dispensary</option> <option value="14907">Kipsacho Dispensary</option> <option value="14909">Kipsaiya Dispensary</option> <option value="14910">Kipsamoite Dispensary</option> <option value="14911">Kipsaos Dispensary</option> <option value="14912">Kipsaraman Dispensary</option> <option value="14913">Kipsegi Dispensary</option> <option value="14914">Kipsigak Baibai Dispensary</option> <option value="14916">Kipsigak Dispensary (Nandi)</option> <option value="14915">Kipsigak Health Centre</option> <option value="15952">Kipsigon (FGC) Health Centre</option> <option value="12330">Kipsing Dispensary</option> <option value="14918">Kipsingei Dispensary</option> <option value="19591">Kipsitet Baptist Dispensary</option> <option value="14919">Kipsitet Dispensary</option> <option value="17283">Kipsoen Dispensary</option> <option value="17099">Kipsogon Dispensary</option> <option value="14920">Kipsonoi Health Centre</option> <option value="17637">Kipsugur Dispensary</option> <option value="14921">Kipsuter Dispensary</option> <option value="14922">Kipsyenan Dispensary</option> <option value="14923">Kiptagich Health Centre</option> <option value="14924">Kiptagich Model Health centre</option> <option value="14925">Kiptagich Tegat Dispensary</option> <option value="14926">Kiptangwanyi Dispensary</option> <option value="13699">Kiptenden Dispensary</option> <option value="14927">Kiptenden Dispensary (Buret)</option> <option value="19282">Kiptenden Dspensary (Nandi Central)</option> <option value="14928">Kiptere Dispensary</option> <option value="14929">Kiptewit Dispensary</option> <option value="20011">Kiptoim Dispensary</option> <option value="14930">Kiptome Dispensary</option> <option value="18742">Kiptome Dispensary (Belgut)</option> <option value="16404">Kiptororo Dispensary</option> <option value="14931">Kiptulos Dispensary</option> <option value="14932">Kiptulwa Dispensary</option> <option value="14933">Kiptuno Dispensary</option> <option value="14934">Kipture Dispensary</option> <option value="11485">Kipungani Dispensary</option> <option value="14935">Kipwastuiyo Health Centre</option> <option value="18526">Kipyosit Dispensary</option> <option value="18881">Kiracha CFW Clinic</option> <option value="10619">Kiracha Medical Clinic</option> <option value="16591">Kiramburune Medical Clinic</option> <option value="17003">Kiraone Dispensary</option> <option value="17912">Kirathe Dispensary</option> <option value="10622">Kirathimo Medical Clinic</option> <option value="14936">Kiratina Medical Clinic</option> <option value="10624">Kiria Health Centre</option> <option value="10625">Kiria-Ini Dispensary</option> <option value="10627">Kiria-Ini Mission Hospital</option> <option value="10626">Kiriaini Medical Clinic</option> <option value="12331">Kiriani Dispensary</option> <option value="12332">Kiriari (ACK) Dispensary</option> <option value="19224">Kiriari Dispensary</option> <option value="14937">Kiribwet Dispensary</option> <option value="14938">Kiricha Dispensary</option> <option value="10628">Kirichu Market Medical Clinic</option> <option value="12333">Kirie Dispensary</option> <option value="12334">Kirie Mission Clinic</option> <option value="16840">Kirigara (MCK) Dispensary</option> <option value="10629">Kiriita Forest Dispensary</option> <option value="10630">Kirima Dispensary</option> <option value="19143">Kirimampio Dispensary</option> <option value="10631">Kirimara Clinic</option> <option value="18906">Kirimara M Clinic</option> <option value="16842">Kirimara Medical Clinic</option> <option value="19770">Kirimara Optical</option> <option value="10632">Kirimukuyu Medical Clinic</option> <option value="14515">Kirimun GK Dispensary</option> <option value="12335">Kirin Agribio (Yoder) Clinic</option> <option value="12336">Kirindine Nursing Home</option> <option value="10633">Kirinyaga Laboratory Supplies</option> <option value="10634">Kiriogo Dispensary</option> <option value="16466">Kiritiri Health Centre</option> <option value="12337">Kirogine Dispensary</option> <option value="16592">Kirogine Medical Clinic</option> <option value="10635">Kirogo Dispensary</option> <option value="10636">Kirogo Health Centre</option> <option value="14939">Kiromwok Dispensary</option> <option value="19391">Kirongoi Dispensary</option> <option value="12338">Kiroo Clinic</option> <option value="18850">Kiroone Dispensary</option> <option value="14906">Kiropket Dispensary</option> <option value="12339">Kirumi Dispensary</option> <option value="16678">Kiruri Dispensary (Laikipia West)</option> <option value="10637">Kiruri Dispensary (Muranga North)</option> <option value="10638">Kirurumi Dispensary</option> <option value="10640">Kirwara Health Clinic</option> <option value="10639">Kirwara Sub District</option> <option value="19345">Kisaju Health Care Isinya</option> <option value="19346">Kisaju Medical Clinic</option> <option value="13700">Kisaku Dispensary</option> <option value="14940">Kisanana Health Centre</option> <option value="19340">Kisangula Medical Clinic</option> <option value="12340">Kisasi Dispensary (Kitui)</option> <option value="16744">Kisasi Medical Clinic</option> <option value="12341">Kisau Sub District Hospital</option> <option value="17911">Kisauni Dispensary</option> <option value="17623">Kisauni Drop In VCT</option> <option value="11487">Kisauni Medical Clinic</option> <option value="12342">Kisayani Health Centre</option> <option value="13701">Kisegi Sub-District Hospital</option> <option value="20044">Kisembe Dispensary</option> <option value="13035">Kisembo Dispensary</option> <option value="14941">Kiserian Dispensary</option> <option value="14942">Kiserian Medical Clinic</option> <option value="12343">Kisesini Dispensary</option> <option value="12345">Kiseuni Dispensary </option> <option value="12344">Kiseuni Dispensary (Kitui)</option> <option value="12346">Kiseveni Dispensary</option> <option value="17160">Kishaunet Dispensary</option> <option value="19736">Kishon</option> <option value="11488">Kishushe Dispensary</option> <option value="13702">Kisii Campus Dispensary</option> <option value="13703">Kisii Hospital (Level 5)</option> <option value="12347">Kisiiki Dispensary</option> <option value="19291">Kisima Community Medical Clinic</option> <option value="14943">Kisima Health Centre</option> <option value="11489">Kisimani Health Services</option> <option value="19628">Kisiwani VCT</option> <option value="20128">Kisoi Munyao Memorial Dispensary</option> <option value="14944">Kisok Dispensary</option> <option value="16672">Kisonei Dispensary</option> <option value="14945">Kisor Dispensary</option> <option value="19935">Kisovo Dispensary</option> <option value="20193">Kisukioni Dispensary</option> <option value="12348">Kisukioni Medical Clinic</option> <option value="13704">Kisumu District Hospital</option> <option value="17553">Kisumu International Airport Dispensary</option> <option value="19869">Kisumu Police Lines Dispensary</option> <option value="18522">Kitaima Dispensary</option> <option value="14946">Kitalale Dispensary</option> <option value="19743">Kitale Cottage Hospital</option> <option value="14947">Kitale District Hospital</option> <option value="19670">Kitale Eye Care Clinic</option> <option value="19744">Kitale Medical Centre - Dr Kamau's MC</option> <option value="19745">Kitale Medical Centre - Dr Kiprop's MC</option> <option value="19691">Kitale Medical Centre - Dr Omunyin</option> <option value="19747">Kitale Medical Centre - Dr Onyango's MC</option> <option value="19847">Kitale Medical Centre - Sloam CBO</option> <option value="14948">Kitale Mobile Clinic</option> <option value="14949">Kitale Nursing Home</option> <option value="19684">Kitale Sch Sanatorium</option> <option value="18441">Kitambaasye Dispensary</option> <option value="17451">Kitamwiki Community Dispensary</option> <option value="12349">Kitangani Dispensary</option> <option value="13705">Kitare Health Centre</option> <option value="17469">Kiteje Dispensary</option> <option value="18401">Kitengela Centre of Hope Medical Clinic</option> <option value="19698">Kitengela Dental Clinic</option> <option value="19677">Kitengela ENT and Medical Centre</option> <option value="14950">Kitengela Health Centre</option> <option value="14951">Kitengela Medical Services</option> <option value="18976">Kitengela Medical Services Kajiado</option> <option value="17840">Kitengela Pona Services</option> <option value="17341">Kitere Dispensary</option> <option value="20026">Kitere Minhaj Dispensary</option> <option value="16849">Kithaku Medical Clinic</option> <option value="12350">Kithatu Medical Clinic</option> <option value="12352">Kithayoni Medical Clinic</option> <option value="12353">Kithegi Dispensary</option> <option value="12354">Kitheo Dispensary</option> <option value="12355">Kitheuni Dispensary</option> <option value="12356">Kithima (ABC) Dispensary</option> <option value="12357">Kithimani Dispensary</option> <option value="12358">Kithimani Medical Clinic</option> <option value="12359">Kithimu Dispensary</option> <option value="17225">Kithithina Dispensary</option> <option value="20021">Kithito Medical Centre</option> <option value="17445">Kithituni Health Care Clinic</option> <option value="18643">Kithoka Chemist</option> <option value="16226">Kithoka Outreach Clinic</option> <option value="12360">Kithuki Health Centre</option> <option value="12361">Kithunguriri Dispensary</option> <option value="16959">Kithuni Dispensary</option> <option value="12362">Kithyoko Health Centre</option> <option value="12363">Kithyoko Mercy Medical Clinic</option> <option value="12364">Kithyululu Dispensary</option> <option value="17742">Kiti Dispensary</option> <option value="12365">Kitise Health Centre</option> <option value="17538">Kitise Rural Development VCT</option> <option value="17643">Kititu Dispensary</option> <option value="14952">Kitoben Dispensary</option> <option value="11490">Kitobo Dispensary (Taita)</option> <option value="11491">Kitobo Dispensary (Taveta)</option> <option value="16472">Kitoi Dispensary</option> <option value="16253">Kitonyoni Dispensary</option> <option value="18905">Kitui Afya Medical</option> <option value="12366">Kitui District Hospital</option> <option value="12367">Kitui Quality Care</option> <option value="13706">Kituka Dispensary</option> <option value="16437">Kituluni Dispensary</option> <option value="18216">Kitum Dispensary</option> <option value="12369">Kitundu (GOK) Dispensary</option> <option value="12368">Kitundu (SDA) Dispensary</option> <option value="19145">Kitundu Dispensary (Katulani District)</option> <option value="12370">Kitunduni Dispensary</option> <option value="12371">Kituneni Medical Clinic</option> <option value="12372">Kitungati Dispensary</option> <option value="14953">Kituro Health Centre</option> <option value="12373">Kituruni Dispensary</option> <option value="12374">Kiu (AIC) Dispensary</option> <option value="10641">Kiumbu Health Centre</option> <option value="11492">Kiunga Health Centre</option> <option value="10642">Kiunyu Dispensary</option> <option value="10643">Kiuu Dispensary</option> <option value="12375">Kivaa Health Centre</option> <option value="12376">Kivaani Health Centre</option> <option value="12377">Kivani Dispensary</option> <option value="18529">Kivani Dispensary (Kitui West)</option> <option value="12378">Kiviu Dispensary</option> <option value="13036">Kivuli Dispensary</option> <option value="12379">Kivuuni Dispensary</option> <option value="13707">Kiwa Island Dispensary</option> <option value="16203">Kiwalwa Dispensary</option> <option value="14954">Kiwamu Dispensary</option> <option value="11493">Kiwandani Dispensary</option> <option value="19712">Kiwara Medical Clinic</option> <option value="16374">Kiwawa (ACCK) Dispensary</option> <option value="20083">Kiwawa GOK Dispensary</option> <option value="11494">Kiwayuu Dispensary</option> <option value="11495">Kizibe Dispensary</option> <option value="11496">Kizingitini Dispensary</option> <option value="11497">Kizingo Health Centre</option> <option value="14955">Kkit Nursing Home</option> <option value="14956">Kkit Nursing Home Annex</option> <option value="12380">Kmc Clinic Mwichune</option> <option value="17903">Kmc Staff Clinic</option> <option value="14957">Kmq Dispensary</option> <option value="13037">Kmtc Dispensary</option> <option value="18347">Kmtc Mombasa Students Clinic</option> <option value="14958">Kobos Dispensary</option> <option value="14959">Kobujoi Forest</option> <option value="17125">Kobujoi Forest Dispensary</option> <option value="14960">Kobujoi Mission Health Centre</option> <option value="13708">Kobuya Dispensary</option> <option value="20134">Kochola Dispensary</option> <option value="14961">Kocholwo Sub-District Hospital</option> <option value="13709">Kodiaga Prison Health Centre</option> <option value="14962">Kodich Dispensary</option> <option value="19861">Koduogo Dispensary</option> <option value="18268">Kogari Dispensary</option> <option value="13710">Kogelo Dispensary</option> <option value="13711">Kogweno Oriang' Dispensary</option> <option value="14963">Koibatal Medical</option> <option value="17639">Koibem Dispensary</option> <option value="14965">Koilot Health Centre</option> <option value="10644">Koimbi Medical Clinic</option> <option value="18664">Koimiret Dispensary</option> <option value="16723">Koisagat Dispensary (Kipkelion)</option> <option value="14966">Koisagat Tea Dispensary</option> <option value="14967">Koitaburot Dispensary</option> <option value="14968">Koitebes Dispensary</option> <option value="14969">Koitugum Dispensary</option> <option value="14970">Koiwa Health Centre</option> <option value="14971">Koiwa Medical Clinic</option> <option value="14972">Koiwalelach Dispensary</option> <option value="14973">Kojonga Dispensary</option> <option value="14974">Kokiselei Dispensary</option> <option value="17017">Kokotoni Dispensary</option> <option value="14975">Kokuro Dispensary</option> <option value="14976">Kokwa Dispensary</option> <option value="13712">Kokwanyo Health Centre</option> <option value="14977">Kokwet Dispensary</option> <option value="17633">Kokwet Medical Clinic</option> <option value="18204">Kokwongoi Dispensary</option> <option value="14978">Kokwototo Dispensary</option> <option value="12381">Kola Health Centre</option> <option value="15953">Kolanya Salavation Army Dispensary</option> <option value="17172">Kolenyo Dispensary</option> <option value="14980">Koloch Dispensary</option> <option value="14981">Kolongolo M Dispensary</option> <option value="17038">Koloo Dispensary</option> <option value="14979">Kolowa Health Centre</option> <option value="17344">Kolwal Dispensary</option> <option value="13038">Komarock Medical Clinic</option> <option value="17717">Komarock Morden Medical Care</option> <option value="16270">Kombato Dispensary</option> <option value="13713">Kombe Dispensary</option> <option value="14982">Kombe Dispensary (Nandi Central)</option> <option value="11498">Kombeni Dispensary</option> <option value="13714">Kombewa District Hospital</option> <option value="14983">Komolion Dispensary</option> <option value="13715">Komomange Dispensary</option> <option value="13716">Komosoko Dispensary</option> <option value="13717">Komotobo Mission Health Centre</option> <option value="15954">Kona Clinic</option> <option value="14984">Kondabilet Dispensary</option> <option value="14985">Kondamet Dispensary</option> <option value="14986">Kongoni Dispensary</option> <option value="15955">Kongoni Health Centre</option> <option value="14987">Kongoro Dispensary</option> <option value="11499">Kongowea Health Centre</option> <option value="11501">Kongowea Medical Clinic</option> <option value="19150">Konton Dispensary</option> <option value="14988">Konyao Dispensary</option> <option value="12383">Konyu Dispensary</option> <option value="13718">Kopanga Dispensary</option> <option value="14989">Kopeeto Dispensary</option> <option value="18050">Kopiata Beach Dispensary (Rarieda)</option> <option value="16873">Kopolo Clinic</option> <option value="15956">Kopsiro Health Centre</option> <option value="13382">Korakora Health Centre</option> <option value="16391">Korao Dispensary</option> <option value="12384">Korbesa Dispensary</option> <option value="14990">Koriema Dispensary</option> <option value="13383">Korisa Dispensary</option> <option value="18895">Korogocho Health Centre</option> <option value="14991">Korokou Dispensary</option> <option value="13384">Korondille Health Centre</option> <option value="14992">Korongoi Dispensary</option> <option value="15958">Korosiandet Dispensary</option> <option value="14993">Koroto Dispensary</option> <option value="12385">Korr Dispensary</option> <option value="17110">Koru Dispensary</option> <option value="13719">Koru Mission Health Centre</option> <option value="13720">Korwenje Dispensary</option> <option value="13721">Kosele Dispensary</option> <option value="17073">Koshok Dispensary</option> <option value="14994">Kosikiria Dispensary</option> <option value="14995">Kositei Dispensary</option> <option value="13385">Kotile Health Centre</option> <option value="13388">Kotulo Health Centre (Mandera Central)</option> <option value="13722">Kowino Dispensary</option> <option value="14996">Koyasa Dispensary</option> <option value="14997">Koyo Health Centre</option> <option value="18531">Koywech Dispensary</option> <option value="11502">Kp&Tc Staff Clinic</option> <option value="12387">Kr Memorial Medical Clinic</option> <option value="19699">Krisvin Medical Clinic</option> <option value="16488">Kubura Dispensary</option> <option value="13723">Kugitimo Health Centre</option> <option value="14998">Kuikui Dispensary</option> <option value="14999">Kuinet Dispensary</option> <option value="20094">Kuira District Disability Network Kuria - Isebania HTC Center</option> <option value="13724">Kuja Dispensary</option> <option value="12389">Kula Mawe Dispensary</option> <option value="17460">Kulaaley Health Centre</option> <option value="13386">Kulan Health Centre</option> <option value="16195">Kulesa Dispensary</option> <option value="16952">Kumahumato Dispensary</option> <option value="16271">Kumoni Dispensary</option> <option value="15000">Kumpa Cmf Dispensary</option> <option value="12390">Kunati Health Centre</option> <option value="12391">Kunene Dispensary</option> <option value="17010">Kuno Dispensary</option> <option value="13725">Kunya Dispensary</option> <option value="15001">Kunyak Dispensary</option> <option value="17171">Kuoyo Kaila Dispensary</option> <option value="15002">Kurangurik Dispensary</option> <option value="16326">Kuresiet Dispensary</option> <option value="16683">Kuresoi Health Centre</option> <option value="13726">Kuria District Hospital</option> <option value="13387">Kursin Health Centre</option> <option value="20191">Kurum Dispensary</option> <option value="18929">Kurungu Dispensary (Loiyangalani)</option> <option value="13727">Kusa Health Centre</option> <option value="13389">Kutulo Health Centre (Wajir East)</option> <option value="10646">Kutus Catholic Dispensary</option> <option value="10647">Kutus Dispensary</option> <option value="15959">Kuvasali Health Centre</option> <option value="16541">Kuze Health Care</option> <option value="12392">Kwa Judy Medical Clinic</option> <option value="16933">Kwa Kavoo Dispensary</option> <option value="19242">Kwa Kilui Dispensary</option> <option value="19417">Kwa Kulu Dispensary</option> <option value="17499">Kwa Mbekenya Dispensary</option> <option value="12393">Kwa Mulungu Dispensary</option> <option value="18449">Kwa Mutalia Dispensary</option> <option value="12394">Kwa Mutonga Dispenasry</option> <option value="17104">Kwa Mwatu Dispensary</option> <option value="11506">Kwa Ndomo Medical Clinic</option> <option value="10651">Kwa Ng'ang'a Medicare</option> <option value="12395">Kwa Nguu Dispensary</option> <option value="12396">Kwa Vonza Dispensary</option> <option value="18682">Kwa-Amutei Dispensary</option> <option value="11508">Kwa-Mnegwa Dispensary</option> <option value="12397">Kwakala Dispensary</option> <option value="20197">Kwakalusya Dispensary</option> <option value="12398">Kwakavisi Dispensary</option> <option value="12399">Kwale Dispensary</option> <option value="11507">Kwale District Hospital</option> <option value="19926">Kwamaiko Health Clinic</option> <option value="13728">Kwamo Dispensary</option> <option value="12400">Kwamwaura Medical Clinic</option> <option value="15003">Kwanza Health Centre</option> <option value="18521">Kwenik-Ab-Ilet Dispensary</option> <option value="19372">Kwetu Medical Clinic</option> <option value="16178">Kwetu VCT</option> <option value="18558">Kwihota Medical Clinic</option> <option value="12401">Kwitu Medical Clinic</option> <option value="18827">Kwosp (Korogocho)</option> <option value="13729">Kwoyo Kodalo Dispensary</option> <option value="11509">KWS Dispensary</option> <option value="18450">KWS VCT</option> <option value="17939">Kyaango Dispensary</option> <option value="12402">Kyaani Dispensary</option> <option value="20033">Kyaani Dispensary (Matinyani)</option> <option value="19726">Kyaimu Dispensary</option> <option value="17005">Kyalilini Dispensary</option> <option value="17842">Kyaluma Dispensary</option> <option value="12403">Kyamatu Dispensary</option> <option value="12404">Kyambeke Dispensary</option> <option value="18083">Kyambiti Dispensary</option> <option value="19195">Kyandu Medical Clinic</option> <option value="12405">Kyandui Dispensary</option> <option value="20196">Kyanganda Dispensary</option> <option value="18674">Kyango Dispensary</option> <option value="12406">Kyangunga Dispensary</option> <option value="12407">Kyanika Dispensary</option> <option value="19198">Kyanzabe Medical Clinic</option> <option value="12408">Kyanzavi Medical Clinic</option> <option value="12409">Kyasila (AIC) Dispensary</option> <option value="17161">Kyasioni Dispensary</option> <option value="12410">Kyatune Health Centre</option> <option value="16965">Kyau Dispensary</option> <option value="12411">Kyawalia Dispensary</option> <option value="12412">Kyawango Dispensary</option> <option value="18168">Kyazabe Medical Clinic</option> <option value="16438">Kyeleni Health Centre</option> <option value="16967">Kyenzenzeni Dispensary</option> <option value="12414">Kyethani Health Centre</option> <option value="17611">Kyevaluki Dispensary</option> <option value="12415">Kyevaluki Medical Clinic</option> <option value="12416">Kyoani Dispensary</option> <option value="12417">Kyome (AIC) Dispensary</option> <option value="12418">Kyondoni Dispensary</option> <option value="16254">Kyuasini Health Centre</option> <option value="12419">Kyumbe (AIC) Dispensary</option> <option value="18607">Kyumbi Sasa Centre</option> <option value="12420">Kyuso District Hospital</option> <option value="12421">Kyusyani Dispensary</option> <option value="12422">Laare Health Centre</option> <option value="19192">Laare Maternity</option> <option value="17338">Labi Sagale</option> <option value="18466">Laboret Dispensary</option> <option value="10652">Labura/Babito Medical Clinic</option> <option value="19316">Lad Nan Hospital</option> <option value="13390">Ladnan Medical Clinic</option> <option value="18898">Ladopharma Medical Centre</option> <option value="11510"><NAME> Maternity Hospital (CPGH)</option> <option value="16169"><NAME> Dispensary</option> <option value="13391">Lafaley Dispensary</option> <option value="16293">Lafey Nomadic Dispensary</option> <option value="13392">Lafey Sub-District Hospital</option> <option value="17463">Lagboqol Dispensary</option> <option value="13039">Lagos Road Dispensary</option> <option value="18589">Laikipia University Medical Centre</option> <option value="12423">Lailuba Dispensary</option> <option value="19688">Laini Moja Mc & Lab</option> <option value="19993">Laini Saba Health Services</option> <option value="18856">Laisamis Health Centre (Marsabit South)</option> <option value="16215">Laisamis Hospital</option> <option value="13730">Lake Basin Development Authority (Lbda) Dispensary</option> <option value="18991">Lakeside Medical</option> <option value="15004">Lakeview Nursing Home</option> <option value="19850">Lakipia Laboratory</option> <option value="15005">Laliat Dispensary</option> <option value="15006">Lalwet Dispensary</option> <option value="17348">Lamaiwe Dispensary</option> <option value="12424">Lamba Medical Clinic</option> <option value="13731">Lambwe Dispensary</option> <option value="13732">Lambwe Forest Dispensary</option> <option value="16376">Lamorna Farm Clinic</option> <option value="11511">Lamu Clinic</option> <option value="11512">Lamu District Hospital</option> <option value="11513">Lamu Fort VCT</option> <option value="15007">Lamuria Dispensary (Laikipia East)</option> <option value="10653">Lamuria Dispensary (Nyeri North)</option> <option value="13040">Landmawe Medical Services</option> <option value="15008">Lanet Health Centre</option> <option value="19180">Lanet Kiondoo Medical Clinic</option> <option value="17384">Lang'ata Comprehensive Medical Service</option> <option value="18762">Lang'ata Dispensary (Ruiru)</option> <option value="15009">Langa Langa Health Centre</option> <option value="15010">Langa Medical Care</option> <option value="15011">Langas RCEA</option> <option value="15012">Langata Enkima Dispensary</option> <option value="13041">Langata Health Centre</option> <option value="13042">Langata Hospital</option> <option value="13044">Langata Women Prison Dispensary</option> <option value="18250">Langi Kawino Dispensary</option> <option value="11515">Langoni Nursing Home</option> <option value="10654">Lankia (PCEA) Dispensary</option> <option value="17644">Lanyiru Dispensary</option> <option value="15013">Lare Health Centre</option> <option value="10655">Lari Health Centre</option> <option value="12425">Lasida Clinic</option> <option value="15014">Latakweny Dispensary</option> <option value="19503">Latema Medical Services (Nairobi)</option> <option value="11516">Latulla Medical Centre</option> <option value="13045">Lea Toto</option> <option value="16800">Lea Toto Clinic (Nairobi West)</option> <option value="13047">Lea Toto Clinic Kariobangi South</option> <option value="17720">Lea Toto Community Mukuru Reuben</option> <option value="13046">Lea Toto Dagoretti</option> <option value="19914">Lea Toto Kawangware</option> <option value="13048">Lea Toto Kibera</option> <option value="18828">Lea Toto Mwiki</option> <option value="18964">Leah Njoki Ndegwa Dispensary</option> <option value="17361">Leberio Dispensary</option> <option value="15016">Lebolos Dispensary</option> <option value="15017">Ledero Dispensary</option> <option value="18533">Legacy Medical Centre</option> <option value="13394">Leheley Sub District Hospital</option> <option value="13733">Lela (Community) Dispensary</option> <option value="18665">Lelaitich Dispensary</option> <option value="15018">Lelboinet Dispensary (Mosop)</option> <option value="15019">Lelboinet Health Centre (Keiyo)</option> <option value="15020">Lelechwet Dispensary (Kipkelion)</option> <option value="15021">Lelechwet Dispensary (Rongai)</option> <option value="15022">Lelmokwo Dispensary</option> <option value="16337">Lelmolok Nursing Home</option> <option value="15023">Lelu Dispensary</option> <option value="15024">Lemook Clinic</option> <option value="15025">Lemoru Ngeny Dispensary</option> <option value="19116">Lemoru Trinity</option> <option value="15026">Lemotit Dispensary</option> <option value="18784">Lenana Hills Hospital</option> <option value="11517">Lenga Dispensary</option> <option value="15027">Lengenet Dispensary</option> <option value="18590">Lengo Medical Clinic</option> <option value="17749">Lensayu</option> <option value="18538">Leo Surgery</option> <option value="16220">Leparua Dispensary</option> <option value="16806">Lereshwa Dispensary</option> <option value="15028">Lerrata Dispensary</option> <option value="10656">Leshau Medical Clinic</option> <option value="10657">Leshau Pondo Health Centre</option> <option value="17783">Leshuta Dispensary</option> <option value="17275">Lesidai Dispensary</option> <option value="15029">Lesirikan Health Centre</option> <option value="15030">Lessos Community Dispensary</option> <option value="15031">Letea Dispensary</option> <option value="19951">Letuaih VCT</option> <option value="18470">Levice Medical Clinic</option> <option value="12426">Lewa Downs Dispensary</option> <option value="19816">Lex Medical Clinic</option> <option value="18954">Lexa Medical Centre</option> <option value="18235">Leysanyu Dispensary</option> <option value="13049">Lianas Clinic Health Centre</option> <option value="15032">Liavo Medical Clinic (Kwanza)</option> <option value="15033">Liavo Medical Clinic (Trans Nzoia West)</option> <option value="16288">Libahlow Nomadic Clinic</option> <option value="17895">Liban Medical Clinic</option> <option value="13395">Liban Pharmacy</option> <option value="13396">Libehiya Dispensary</option> <option value="12427">Liberty Maternity and Nursing Home</option> <option value="18048">Liberty Medical Clinic</option> <option value="13397">Liboi Clinic</option> <option value="13398">Liboi Health Centre</option> <option value="17525">Lidha Dispensary</option> <option value="17439">Lieta Health Centre (Rarieda)</option> <option value="10659">Life Care Ministry Clinic</option> <option value="18172">Life Water Ndege Mobile Clinic</option> <option value="19720">Lifters Community Medical Clinic</option> <option value="18320">Ligala Dispensary</option> <option value="13735">Ligega Health Centre</option> <option value="11519">Light For Christ Hospital</option> <option value="19334">Light Hospital</option> <option value="20132">Light Medical and Side Lab Naivasha</option> <option value="17512">Lihanda Health Centre</option> <option value="16684">Likia Dispensary</option> <option value="15035">Likii Dispensary</option> <option value="17539">Likii VCT</option> <option value="15960">Likindu Dispensary</option> <option value="11520">Likoni Catholic Dispensary</option> <option value="11522">Likoni District Hospital</option> <option value="18454">Likoni HIV Resource Centre</option> <option value="15961">Likuyani Sub-District Hospital</option> <option value="15036">Likwon Dispensary</option> <option value="10660">Lilian Wachuka Clinic</option> <option value="17833">Lilian Wacuka Medical Clinic</option> <option value="18460">Lilongwe Community Health Care</option> <option value="16593">Lily Clinic</option> <option value="19087">Lilyon Clinical Services</option> <option value="12428">Limauru Dispensay</option> <option value="15037">Limo Surgical Hospital</option> <option value="12429">Limoro Dispensary</option> <option value="10661">Limuru Health Centre</option> <option value="18836">Limuru Medical Clinic</option> <option value="10662">Limuru Nursing Home</option> <option value="18652">Limuru Sasa Centre</option> <option value="19953">Linda Maternity</option> <option value="15038">Lingwai Dispensary</option> <option value="15039">Litein Dispensary</option> <option value="15040">Liter (AIC) Dispensary</option> <option value="18611">Lithi Clinic</option> <option value="10663">Little Flower Dispensary</option> <option value="17589">Live With Hope</option> <option value="13050">Liverpool VCT</option> <option value="16662">Liverpool VCT (Kisumu East)</option> <option value="17664">Liverpool VCT (Machakos)</option> <option value="12430">Liverpool VCT Embu</option> <option value="12431">Liviero Dispensary</option> <option value="10664">Liz Medical Clinic</option> <option value="17145">Lkuroto Dispensary</option> <option value="18737">Lobei Health Centre</option> <option value="15042">Loboi Dispensary</option> <option value="19508">Local Aid Organization</option> <option value="17034">Location Medical Clinic</option> <option value="15043">Locheremoit Dispensary</option> <option value="15044">Lochoraikeny Dispensary</option> <option value="17480">Lochorekuyen Dispensary</option> <option value="15045">Lochwaangikamatak Dispensary</option> <option value="13051">Loco Dispensary</option> <option value="15047">Lodokejek Dispensary</option> <option value="15048">Lodungokwe Health Centre</option> <option value="15049">Lodwar District Hospital</option> <option value="16213">Logologo AIC Dispensary</option> <option value="18857">Logologo Model Health Centre (Marsabit South)</option> <option value="17278">Loikumkum Dispensary</option> <option value="15050">Loima Medical Clinic</option> <option value="15051">Loitokitok District Hospital</option> <option value="15052">Loitokitok Medical Clinic</option> <option value="19254">Loitokitok Medicare Centre</option> <option value="15053">Loiwat Dispensary</option> <option value="12432">Loiyangalani Dispensary</option> <option value="12433">Loiyangalani Health Centre</option> <option value="17196">Lokaburu</option> <option value="15054">Lokamarinyang Dispensary</option> <option value="15055">Lokangae Health Centre</option> <option value="15056">Lokapel Dispensary</option> <option value="15057">Lokichar (RCEA) Health Centre</option> <option value="15058">Lokichoggio Military Dispensary</option> <option value="15059">Lokichogio (AIC) Health Centre</option> <option value="15060">Lokipoto Dispensary</option> <option value="15061">Lokiriama Dispensary</option> <option value="15062">Lokitaung District Hospital</option> <option value="15063">Lokore Dispensary</option> <option value="15064">Lokori (AIC) Health Centre</option> <option value="16324">Lokori Primary Health Care Programme</option> <option value="15065">Lokusero Dispensary</option> <option value="15066">Lokwamosing Dispensary</option> <option value="16697">Lokwatubwa (PAG) Dispensary</option> <option value="15067">Lokwii Dispensary</option> <option value="15068">Lolgorian Sub District Hosp</option> <option value="15069">Lolkeringet Dispensary</option> <option value="15070">Lolminingai Dispensary</option> <option value="17189">Lolmolog Dispensary</option> <option value="14504">Loltulelei Friends Dispensary</option> <option value="20000">Lolupe Dispensary</option> <option value="16875">Lombi Medical Clinic</option> <option value="18370">Lomekwi Dispensary</option> <option value="16698">Lomelo Dispensary</option> <option value="15072">Lomil Dispensary</option> <option value="20048">Lomuke Dispensary</option> <option value="15073">Lomut Dispensary</option> <option value="15074">Londiani District Hospital</option> <option value="17479">Longech Dispensary</option> <option value="15076">Longewan Dispensary</option> <option value="15077">Longisa Distrioct Hospital</option> <option value="15078">Longonot Dispensary</option> <option value="16214">Lontolio Dispensary</option> <option value="15046">Loodoariak Dispensary</option> <option value="17924">Loosho Dispensary</option> <option value="15079">Loosuk GK Dispensary</option> <option value="16699">Lopedur Dispensary</option> <option value="17246">Loperot Dispensary</option> <option value="15081">Lopiding Sub-District Hospital</option> <option value="15083">Lopur Dispensary (Turkana South)</option> <option value="15082">Lopur Dispensary (Turkana West)</option> <option value="16815">Lord of Mercy Clinic</option> <option value="17947">Loreigns Medical Services (Kasarani)</option> <option value="15084">Lorengelup Dispensary</option> <option value="15085">Lorengippi Dispensary</option> <option value="15086">Lorien Dispensary</option> <option value="15087">Lorngoswa Dispensary</option> <option value="15088">Lorogon Dispensary</option> <option value="20076">Lorugum Medical Services Ltd</option> <option value="15091">Loruk Dispensary (East Pokot)</option> <option value="15092">Loruth Dispensary</option> <option value="16369">Losam Dispensary</option> <option value="18265">Losho Dispensary</option> <option value="15093">Losogwa Dispensary</option> <option value="15094">Loturerei Dispensary</option> <option value="17755">Lovic Dermacare Clinic</option> <option value="15095">Loving Care (MCK) Health Centre</option> <option value="15096">Lowarengak Dispensary</option> <option value="13052">Lower Kabete Dispensary (Kabete)</option> <option value="15097">Lower Solai Dispensary</option> <option value="15098">Loyapat Dispensary</option> <option value="17276">Lpartuk Dispensary</option> <option value="15962">Luanda Mch/Fp Clinic</option> <option value="15963">Luanda Town Dispensary</option> <option value="17112">Luanda Wayside Clinic</option> <option value="13736">Luciel Dispensary</option> <option value="10665">Lucimed Clinic</option> <option value="13737">Lucky Youth Dispensary</option> <option value="18287">Ludomic Clinic</option> <option value="15964">Lugari Forest Dispensary</option> <option value="17653">Lughpharm Medical Services (Machakos)</option> <option value="18884">Lugpharm Medicals Limited</option> <option value="15099">Luguget Dispensary</option> <option value="15965">Lugulu Friends Mission Hospital</option> <option value="15100">Lugumek Dispensary</option> <option value="19650">Luisoi Medical Clinic</option> <option value="15966">Lukhome Dispensary (Bungoma West)</option> <option value="15101">Lukhome Dispensary (Trans Nzoia West)</option> <option value="15967">Lukhuna Dispensary</option> <option value="18042">Lukim Medical Clinic</option> <option value="15968">Lukolis Model Health Centre</option> <option value="11525">Lukore Dispensary</option> <option value="17298">Lukoye Health Centre</option> <option value="16711">Lukusi Dispensary</option> <option value="18125">Lukusi Dispensary</option> <option value="15969">Lumakanda District Hospital</option> <option value="15970">Lumani Dispensary</option> <option value="18852">Lumboka Medical Services</option> <option value="18624">Lumino Dispensary</option> <option value="15971">Lumino Maternity and Nursing Home</option> <option value="13738">Lumumba Health Centre</option> <option value="19481">Lumumba Medical Clinic</option> <option value="20156">Lunakwe Dispensary</option> <option value="12435">Lundi Dispensary</option> <option value="15972">Lung'anyiro Dispensary</option> <option value="13053">Lunga Lunga Health Centre</option> <option value="15973">Lungai Dispensary</option> <option value="11526">Lungalunga Dispensary</option> <option value="17494">Lungalunga Health Centre</option> <option value="15974">Lunyito Dispensary</option> <option value="15102">Luoniek Dispensary</option> <option value="15975">Lupida Health Centre</option> <option value="15976">Lurare Dispensary</option> <option value="15977">Lusheya Health Centre</option> <option value="17540">Lusop Clinic</option> <option value="10666">Lussigetti Health Centre</option> <option value="15978">Lutaso Dispensary</option> <option value="11527">Lutsangani Dispensary</option> <option value="17608">Luucho Dispensary</option> <option value="17116">Luuya Dispensary</option> <option value="13740">Lwala Dispensary</option> <option value="17174">Lwala Kadawa Dispensary</option> <option value="16770">Lwanda Awiti Dispensary</option> <option value="13741">Lwanda Dispensary</option> <option value="15979">Lwanda Dispensary (Bungoma West)</option> <option value="13742">Lwanda Gwassi Dispensary</option> <option value="15980">Lwandanyi Dispensary</option> <option value="15981">Lwandeti Dispensary</option> <option value="17155">Lwanyange Dispensary</option> <option value="15982">Lyanaginga Health Centre</option> <option value="16505">M K M Clinic</option> <option value="19175">M K Medical Clinic Ewuaso</option> <option value="19081">Maa Out Patient Centre</option> <option value="12436">Maai Dispensary</option> <option value="17339">Maalimin Dispensary</option> <option value="11528">Maamba Medical Clinic</option> <option value="15103">Maasai Medical Centre</option> <option value="15104">Maasai Nursing Home</option> <option value="17502">Mabanga Medical Clinic</option> <option value="19746">Mabariri Medical Clinic (Nyamira North)</option> <option value="15105">Mabasi Dispensary</option> <option value="11529">Mabati Medical Clinic</option> <option value="13743">Mabinju Dispensary</option> <option value="17297">Mabole Health Centre</option> <option value="10667">Mabroukie Dispensary</option> <option value="19142">Mabruk Medical Clinic</option> <option value="15983">Mabusi Health Centre</option> <option value="13744">Macalder Mission Dispensary</option> <option value="13745">Macalder Sub-District Hospital</option> <option value="12437">Machaka Mission Dispensary</option> <option value="12439">Machakos Health Care Centre</option> <option value="12438">Machakos Level 5 Hospital</option> <option value="12440">Machakos Medical Clinic</option> <option value="12441">Machang'a Dispensary</option> <option value="18970">Machengene Dispensary</option> <option value="19892">Machinery Health Care Centre</option> <option value="17498">Machinery Medical Clinic</option> <option value="19188">Machungulu Dispensary</option> <option value="13746">Machururiati Dispensary</option> <option value="15984">Machwele Dispensary</option> <option value="11530">Mackinnon Medical Clinic</option> <option value="11531">Mackinon Road Dispensary</option> <option value="19600">Madaktari Health Clinic (Njiru)</option> <option value="11532">Madamani Dispensary</option> <option value="18735">Madaraka Health Services</option> <option value="15985">Madende Dispensary</option> <option value="13747">Madiany Sub District Hospital</option> <option value="19220">Madina Health Care Clinic</option> <option value="13055">Madina Nursing Home</option> <option value="17902">Madoadi Dispensary (Sololo)</option> <option value="11533">Madogo Health Centre</option> <option value="11534">Madunguni Dispensary</option> <option value="11535">Madunguni Medical Clinic</option> <option value="18890">Maendeleo Clinic</option> <option value="19473">Maendereo Medical Clinic</option> <option value="15986">Maeni Dispensary</option> <option value="11536">Mafisini Dispensary</option> <option value="19512">Mafra Clinic</option> <option value="15107">Magadi Hospital</option> <option value="18698">Magana Medical Clinic</option> <option value="13748">Magena Dispensary</option> <option value="13749">Magenche Dispensary</option> <option value="12443">Magenka Dispensary</option> <option value="13750">Mageta Dispensary</option> <option value="18430">Magina Dispensary</option> <option value="13751">Magina Health Centre</option> <option value="11537">Magodzoni Dispensary</option> <option value="17134">Magombo Community Dispensary (Manga)</option> <option value="13752">Magombo Health Centre</option> <option value="11538">Magongo (MCM) Dispensary</option> <option value="12444">Magundu Dispensary</option> <option value="13753">Magunga Health Centre</option> <option value="13754">Magura Dispensary</option> <option value="10669">Magutu (PCEA) Dispensary</option> <option value="12445">Magutuni District Hospital</option> <option value="13755">Magwagwa (SDA) Dispensary</option> <option value="13756">Magwagwa Health Centre</option> <option value="18187">Mahandakini Dispensary</option> <option value="15987">Mahanga Dispensary</option> <option value="16388">Mahanga Dispensary</option> <option value="16144">Mahatma Gandi Health Centre</option> <option value="13757">Mahaya Health Centre (Rarieda)</option> <option value="16679">Mahianyu Dispensary</option> <option value="10670">Mahiga (PCEA) Dispensary</option> <option value="15108">Mai Mahiu Health Centre</option> <option value="19139">Mai Mahiu Maternity and Hospital</option> <option value="19554">Maichoma Clinic</option> <option value="15106">Maiela Health Centre</option> <option value="12446">Maikona Dispensary</option> <option value="20002">Maili Saba Dispensary</option> <option value="12447">Mailiari Dispensary</option> <option value="15109">Mailwa Dispensary</option> <option value="10671">Maina & Mwangi Health Centre</option> <option value="15110">Maina Dispensary</option> <option value="18410">Maina Kiganjo Health Clinic</option> <option value="10672">Maina Village Dispensary</option> <option value="17862">Mainland Health Centre (Changamwe)</option> <option value="11539">Mainland Health Centre (Magongo)</option> <option value="11540">Mainview Medical Clinic</option> <option value="17303">Mairi Dispensary</option> <option value="16506">Maisha Bora Clinic</option> <option value="19308">Maisha House VCT (Noset)</option> <option value="19542">Maisha Poa Dispensary</option> <option value="19414">Maiuni Dispensary</option> <option value="12448">Majengo (PCEA) Clinic</option> <option value="15988">Majengo Dispensary</option> <option value="11541">Majengo Dispensary (Mombasa)</option> <option value="11542">Majengo Dispensary (Tana River)</option> <option value="15111">Maji Mazuri Dispensary</option> <option value="15112">Maji Moto Dispensary</option> <option value="15113">Maji Moto Dispensary (Narok South)</option> <option value="15114">Maji Tamu Health Centre</option> <option value="11543">Majimoto Dispensary</option> <option value="17891">Majira Dispensary</option> <option value="15115">Majoh Medical Clinic</option> <option value="11544">Majoreni Dispensary</option> <option value="19341">Majve Medical Clinic</option> <option value="13399">Maka - Al Mukarama Clinic</option> <option value="12449">Makaani Dispensary</option> <option value="12450">Makadara Health Care</option> <option value="13056">Makadara Health Centre</option> <option value="13057">Makadara Mercy Sisters Dispensary</option> <option value="11545">Makamini Dispensary</option> <option value="19304">Makamu Medical Clinic</option> <option value="17346">Makande Healthcare Services</option> <option value="12451">Makandune Dispensary</option> <option value="11547">Makanzani Dispensary</option> <option value="13758">Makararangwe Dispensary</option> <option value="12452">Makengi Clinic</option> <option value="12453">Makengi Dispensary (Embu)</option> <option value="16645">Makengi Dispensary (Maara)</option> <option value="11548">Makere Dispensary</option> <option value="15989">Makhanga Dispensary</option> <option value="15990">Makhonge Health Centre</option> <option value="12454">Makima Dispensary</option> <option value="15116">Makimeny Dispensary</option> <option value="13058">Makina Clinic</option> <option value="11961">Makindu Catholic Dispensary</option> <option value="13759">Makindu Dispensary</option> <option value="12455">Makindu District Hospital</option> <option value="19320">Makindu Nursing Home</option> <option value="19222">Makkah Medical Clinic and Lab</option> <option value="13059">Makkah Nursing Home</option> <option value="13060">Makogeni Clinic</option> <option value="18432">Makongeni Dispensary</option> <option value="19858">Makongeni Health Centre</option> <option value="18681">Makongo Dispensary</option> <option value="19107">Makongoni Dispensary</option> <option value="17744">Makoror Dispensary</option> <option value="11549">Maktau Health Centre</option> <option value="12457">Makueni District Hospital</option> <option value="18139">Makueni Medical Centre</option> <option value="15991">Makunga Rhdc</option> <option value="15458">Makutano (PCEA) Medical Clinic (Trans Nzoia East)</option> <option value="15992">Makutano Dispensary</option> <option value="15117">Makutano Health Centre (Turkana West)</option> <option value="16451">Makutano Medical Clinic</option> <option value="12458">Makutano Medical Clinic (Machakos)</option> <option value="18733">Makutano Medical Clinic (Meru)</option> <option value="16594">Makutano Medical Clinic/Lab</option> <option value="10674">Makuyu Health Centre</option> <option value="10675">Makwa Medical Clinic</option> <option value="11552">Makwasinyi Dispensary</option> <option value="18397">Makyau Dispensary</option> <option value="15118">Makyolok Dispensary</option> <option value="15993">Malaba Dispensary</option> <option value="19258">Malabot Dispensary</option> <option value="18831">Malabot Dispensary (North Horr)</option> <option value="17150">Malaha Dispensary</option> <option value="19622">Malaika Health Centre</option> <option value="15994">Malakisi Health Centre</option> <option value="12459">Malalani Dispensary</option> <option value="11553">Malanga (AIC) Dispensary</option> <option value="15995">Malanga Dispensary</option> <option value="13760">Malanga Health Centre</option> <option value="15996">Malava District Hospital</option> <option value="15997">Malekha Dispensary</option> <option value="13761">Malela Dispensary</option> <option value="20013">Maliera Mission Dispensary</option> <option value="12460">Maliku Dispensary</option> <option value="11556">Malindi Care Services Limited</option> <option value="11555">Malindi District Hospital</option> <option value="11557">Malindi Sea Breeze</option> <option value="15998">Malinya Clinic</option> <option value="12461">Malka Daka Dispensary</option> <option value="12462">Malka Galla Dispensary</option> <option value="13400">Malkagufu Dispensary</option> <option value="13401">Malkamari Health Centre</option> <option value="18487">Malkamari Health Centre</option> <option value="18118">Malkich Dispensary</option> <option value="17853">Maloba Health Clinic</option> <option value="18912">Mama Anns Odede Community Health Centre</option> <option value="13762">Mama Caro Clinic</option> <option value="20012">Mama Clinic</option> <option value="13763">Mama Fridah Clinic</option> <option value="13764">Mama Josphene Clinic</option> <option value="12463">Mama Ken Clinic</option> <option value="17411">Mama Lucy Kibaki Hospital - Embakasi</option> <option value="10676">Mama Margaret Medical Clinic</option> <option value="13765">Mama Maria Clinic</option> <option value="17121">Mama Plister Blair Health Centre</option> <option value="12464">Mama Vero Clinic</option> <option value="18946">Mamakate Medical Clinic</option> <option value="11558">Mamba Dispensary</option> <option value="12465">Mamba Dispensary (Yatta)</option> <option value="18417">Mamboleo Medical Clinic</option> <option value="11559">Mambrui Dispensary</option> <option value="17734">Mamu Medical Clinic</option> <option value="10677">Mamuki Medical Clinic</option> <option value="19659">Mana Medical Clinic</option> <option value="12466">Mananja Health Centre</option> <option value="19374">Manasco Medical Centre (Roysambu)</option> <option value="17681">Manda Dispensary</option> <option value="13402">Mandera District Hospital</option> <option value="16296">Mandera Medicare Clinic</option> <option value="13403">Mandera Medicare Nursing Home</option> <option value="18851">Mandera West Nursing Home</option> <option value="10678">Manesh Clinic</option> <option value="13766">Manga District Hospital</option> <option value="13767">Manga Getobo Clinic</option> <option value="11560">Mangai Dispensary</option> <option value="12468">Mangala Dispensary</option> <option value="17697">Mangani Clinic</option> <option value="13768">Mangima SDA Health Centre</option> <option value="19147">Mangina Dispensary</option> <option value="12469">Mango Dispensary</option> <option value="20120">Mango Tree VCT</option> <option value="10019">Mangu (Aip) Dispensary</option> <option value="15119">Mangu Dispensary (Rongai)</option> <option value="16759">Mangu High School Clinic</option> <option value="10679">Manguo Medical Clinic</option> <option value="10680">Manjo Health Clinic</option> <option value="16310">Mankind Medical Clinic</option> <option value="19347">Manna Medical Clinic Isinya</option> <option value="17127">Manoa Dispensary</option> <option value="16363">Manor House Agricultural Health Clinic</option> <option value="13404">Mansa Health Centre</option> <option value="16292">Mansa Nomadic Clinic</option> <option value="13405">Mansabubu Health Centre</option> <option value="16218">Mansile Dispensary</option> <option value="10681">Manunga Health Centre</option> <option value="15999">Manyala Sub-District Hospital</option> <option value="11561">Manyani Dispensary</option> <option value="13769">Manyatta (SDA) Dispensary</option> <option value="20077">Manyatta Clinic</option> <option value="17581">Manyatta Dispensary</option> <option value="12470">Manyatta Jillo Health Centre</option> <option value="15120">Manyatta Medical Clinic</option> <option value="16773">Manyatta Medical Clinic (Nyeri South)</option> <option value="18679">Manyoeni Dispensary</option> <option value="15121">Manyoror Dispensary</option> <option value="13770">Manyuanda Health Centre</option> <option value="13771">Manyuanda Health Centre (Rarieda)</option> <option value="14126">Manyuanda St Teresas CFW Clinic (Rarieda)</option> <option value="15122">Maparasha Dispensary</option> <option value="16000">Mapengo Dispensary</option> <option value="17692">Mapenya Dispensary</option> <option value="15123">Mara Serena Dispensary</option> <option value="19387">Maraa Catholic Dispensary</option> <option value="11562">Marafa Health Centre</option> <option value="17015">Maragi Dispensary</option> <option value="10683">Maragi Medical Clinic</option> <option value="10684">Maragua (African Christian Churches and Schools) C</option> <option value="10685">Maragua Clinic</option> <option value="10686">Maragua District Hospital</option> <option value="10687">Maragua Ridge Health Centre</option> <option value="15124">Maraigushu Dispensary</option> <option value="16001">Marakusi Dispensary</option> <option value="15125">Maralal Catholic Dispensary</option> <option value="15126">Maralal District Hospital</option> <option value="14526">Maralal GK Prison Dispensary</option> <option value="16322">Maralal Medical Clinic</option> <option value="16258">Maram Dispensary</option> <option value="15127">Maramara Dispensary</option> <option value="19671">Marambach Mc</option> <option value="18985">Maranatha Medical Services</option> <option value="13772">Marani District Hospital</option> <option value="10688">Maranjau Dispensary</option> <option value="15128">Mararianta Dispensary</option> <option value="16595">Marble Clinic</option> <option value="16596">Marble Medical Laboratory</option> <option value="18948">March Medicare</option> <option value="13773">Marenyo Health Centre</option> <option value="11563">Marereni Dispensary</option> <option value="11564">Marereni Medical Clinic</option> <option value="13061">Maria Dominica Dispensary</option> <option value="13062">Maria Immaculate Health Centre</option> <option value="13063">Maria Maternity and Nursing Home</option> <option value="18690">Maria Salus Infirmorum Dispensary</option> <option value="11565">Maria Teressa Nuzzo Health Centre</option> <option value="16970">Mariaini Dispensary</option> <option value="16188">Mariakani Community Health Care Services</option> <option value="18838">Mariakani Cottage Clinic</option> <option value="13064">Mariakani Cottage Hospital Ltd</option> <option value="18084">Mariakani Cottage Hospital Ongatta Rongai</option> <option value="19432">Mariakani Cottage Hospital Utawala Clinic</option> <option value="11566">Mariakani District Hospital</option> <option value="15129">Mariashoni Dispensary</option> <option value="15130">Marich Dispensary</option> <option value="15131">Maridadi RCEA Medical Centre</option> <option value="15132">Marie Stopes ( Nakuru)</option> <option value="15133">Marie Stopes (Naivasha)</option> <option value="17109">Marie Stopes Centre Embu</option> <option value="18615">Marie Stopes Clinic</option> <option value="16166">Marie Stopes Clinic (Dagoretti)</option> <option value="12471">Marie Stopes Clinic (Imenti North)</option> <option value="13065">Marie Stopes Clinic (Kencom)</option> <option value="13774">Marie Stopes Clinic (Kisii)</option> <option value="11569">Marie Stopes Clinic (Kongowea)</option> <option value="18028">Marie Stopes Clinic (Laikipia East)</option> <option value="16167">Marie Stopes Clinic (Langata)</option> <option value="13775">Marie Stopes Clinic (Migori)</option> <option value="16772">Marie Stopes Clinic (Nyeri South)</option> <option value="13066">Marie Stopes Clinic (Pangani)</option> <option value="15134">Marie Stopes Clinic (Trans Nzoia West)</option> <option value="16002">Marie Stopes Clinic (Vihiga)</option> <option value="13067">Marie Stopes Clinic (Westlands)</option> <option value="15135">Marie Stopes Health Centre (Eldoret West)</option> <option value="15136">Marie Stopes Health Centre (Kericho)</option> <option value="18232">Marie Stopes Kenya Bungoma Centre</option> <option value="18400">Marie Stopes Kenya Bungoma Centre</option> <option value="11567">Marie Stopes Kenya Clinic (Malindi)</option> <option value="17967">Marie Stopes Kenya Mld Clinic</option> <option value="11570">Marie Stopes Mombasa Nursing Home</option> <option value="13068">Marie Stopes Nursing Home (Eastleigh)</option> <option value="13776">Marie Stopes Nursing Home (Kisumu)</option> <option value="10690">Marie Stopes Nursing Home (Muranga)</option> <option value="17484">Mariestopes</option> <option value="15137">Marigat Catholic Mission</option> <option value="15138">Marigat Sub District Hospital</option> <option value="10691">Mariine Maternity Home</option> <option value="10692">Mariira Catholic Dispensary</option> <option value="11571">Marikebuni Dispensary</option> <option value="18431">Marimani CDF Dispensary</option> <option value="17658">Marimanti Med Clinic</option> <option value="13777">Marindi Health Centre</option> <option value="13069">Maringo Clinic</option> <option value="15139">Marinyin Dispensary</option> <option value="20089">Marist International University College Medical Clinic</option> <option value="15140">Mariwa Dispensary (Kipkelion)</option> <option value="13778">Mariwa Health Centre</option> <option value="15141">Maron Dispensary</option> <option value="15142">Maron-Marichor Dispensary</option> <option value="19882">Marps -Chuka Dice Clinic</option> <option value="19879">Marps Clinic (Meru)</option> <option value="18767">Marps Drop In Medical Centre</option> <option value="15143">Mars Associate Medical Centre</option> <option value="18160">Mars Medical Clinic</option> <option value="12472">Marsabit District Hospital</option> <option value="12473">Marsabit Medical Clinic</option> <option value="16207">Marsabit Modern Medical Clinic</option> <option value="10694">Martha Medical Clinic</option> <option value="15144">Marti Dispensary</option> <option value="10695">Martmerg Medical Clinic</option> <option value="19705">Maru A Pula Medical Clinic</option> <option value="10696">Marua Dispensary</option> <option value="10697">Marua Medical Clinic</option> <option value="11572">Marungu Health Centre</option> <option value="15145">Marura Dispensary</option> <option value="13070">Marura Nursing Home</option> <option value="18553">Marura Nursing Home (Ruiru)</option> <option value="19723">Marura Nursing Home Kiambu Medical Clinic</option> <option value="13071">Marurui Dispensary</option> <option value="15146">Mary Finch Dispensary</option> <option value="12474">Mary Goretti Health Services</option> <option value="19598">Mary Help Mission Medical Centre</option> <option value="10698">Mary Help of The Sick Hospital</option> <option value="10699">Mary Hill Medical Clinic</option> <option value="12982">Mary Immaculate Clinic Mukuru</option> <option value="11573">Mary Immaculate Cottage Hospital (Mombasa)</option> <option value="15147">Mary Immaculate Dispensary (Eldoret East)</option> <option value="15148">Mary Immaculate Dispensary (Laikipia East)</option> <option value="10700">Mary Immaculate Hospital (Nyeri North)</option> <option value="13072">Mary Immaculate Sisters Dispensary</option> <option value="17514">Mary Mission</option> <option value="16179">Maryango Medical Clinic</option> <option value="17815">Maryland Medical Clinic</option> <option value="11574">Marynoll Dispensary</option> <option value="10701">Masa Medical Clinic (Kirinyaga)</option> <option value="10702">Masa Medical Clinic (Nyeri North)</option> <option value="16715">Masaba Dispensary</option> <option value="13678">Masaba District Hospital</option> <option value="13779">Masaba Health Centre</option> <option value="18414">Masaba Hospital Kisumu</option> <option value="15149">Masaita/ Miti-Tatu Dispensary</option> <option value="13780">Masala Dispensary</option> <option value="18550">Maseki Dispensary</option> <option value="17157">Masendebale Dispensary</option> <option value="13781">Maseno Mission Hospital</option> <option value="13782">Maseno University Medical Clinic</option> <option value="18663">Mashaallah Nursing Home-Habaswein</option> <option value="17111">Mashambani Dispensary</option> <option value="16325">Mashangwa Dispensary</option> <option value="11575">Mashauri Medical Centre</option> <option value="15150">Mashuru Health Centre</option> <option value="17739">Masii Catholic Dispensary</option> <option value="12475">Masii Health Centre</option> <option value="17279">Masikita Dispensary</option> <option value="18509">Masimba</option> <option value="13783">Masimba Sub-District Hospital</option> <option value="16764">Masinde Muliro University of Science and Technolog</option> <option value="12476">Masinga Sub County Hospital</option> <option value="17652">Masingu Health Services</option> <option value="13784">Masogo Dispensary</option> <option value="17518">Masogo Dispensary (Gem)</option> <option value="13785">Masogo Sub District Hospital</option> <option value="19986">Masokani Dispensary</option> <option value="17108">Masol Dispensary</option> <option value="19365">Masombor Community Dispensary</option> <option value="12477">Masongaleni Health Centre</option> <option value="13786">Masongo Dispensary</option> <option value="18676">Mastoo Dispensary</option> <option value="12478">Masumba Dispensary</option> <option value="16787">Masumbi Dispensary</option> <option value="15151">Masurura Dispensary</option> <option value="12479">Masyungwa Health Centre</option> <option value="11576">Mata Dispensary (Taita)</option> <option value="11577">Mata Dispensary (Taveta)</option> <option value="10703">Mataara Dispensary</option> <option value="18868">Matabitabithi Dispensary</option> <option value="12480">Mataka Dispensary</option> <option value="13787">Matangwe Community Health Centre</option> <option value="15152">Matanya Dispensary</option> <option value="10704">Matara ENT Clinic</option> <option value="13788">Matare Mission Dispensary</option> <option value="15153">Matasia Nursing Home</option> <option value="13789">Matata Nursing Hospital</option> <option value="16003">Matayos Community Clinic</option> <option value="16004">Matayos Health Centre</option> <option value="19838">Matches Medical Clinc</option> <option value="19912">Matercare Maternity Hospital</option> <option value="12481">Materi Girls Dispensary</option> <option value="16005">Matete Health Centre</option> <option value="10705">Mathakwaini (PCEA) Dispensary</option> <option value="13075">Mathare 3A (EDARP)</option> <option value="13077">Mathare North Health Centre</option> <option value="13078">Mathare Police Depot</option> <option value="13076">Mathari Hospital</option> <option value="10706">Matharite Dispensary</option> <option value="15154">Matharu Dispensary</option> <option value="18106">Mathigu Road Medical Clinic</option> <option value="12482">Mathima Dispensary</option> <option value="10707">Mathingira Medical Clinic</option> <option value="12483">Mathuki Health Centre</option> <option value="16656">Mathunzini Dispensary</option> <option value="16927">Mathyakani Dispensary</option> <option value="17528">Matibabu Nzoia Clinic</option> <option value="17529">Matibabu Ukwala Clinic</option> <option value="12484">Matiliku Catholic Dispensary</option> <option value="12485">Matiliku District Hospital</option> <option value="12486">Matinyani Dispensary</option> <option value="16006">Matioli Dispensary</option> <option value="15155">Matira Dispensary</option> <option value="17179">Matoi Dispensary</option> <option value="11578">Matolani Dispensary</option> <option value="11579">Matondoni Dispensary</option> <option value="13790">Matongo Dispensary</option> <option value="13791">Matongo Health Centre</option> <option value="13792">Matongo Medical Clinic</option> <option value="13793">Matoso Health Clinic</option> <option value="11580">Matsangoni Model Health Centre</option> <option value="11581">Matuga Dispensary</option> <option value="16389">Matulo Dispensary</option> <option value="16410">Matumaini Dispensary</option> <option value="18095">Matumbi Dispensary</option> <option value="16364">Matunda Dispensary</option> <option value="16007">Matunda Nursing Home</option> <option value="16008">Matunda Sub-District Hospital</option> <option value="16037">Matungu Sub-District Hospital</option> <option value="16439">Matungulu Health Centre</option> <option value="18292">Matungulu Medical Centre</option> <option value="10708">Matura Medical Care</option> <option value="16009">Maturu Dispensary</option> <option value="13794">Matutu Dispensary</option> <option value="17551">Matutu Dispensary (Nzaui)</option> <option value="18379">Matutu Medical Clinic</option> <option value="12487">Matuu Cottage Clinic</option> <option value="12488">Matuu District Hospital</option> <option value="12489">Matuu Mission Hospital</option> <option value="12490">Matuu Nursing Home</option> <option value="15156">Mau Narok Health Centre</option> <option value="15157">Mau Summit Medical Clinic</option> <option value="15158">Mau Tea Dispensary</option> <option value="16412">Mau-Narok Health Services</option> <option value="12491">Maua Cottage</option> <option value="19409">Maua Diagnostic Centre</option> <option value="19261">Maua East Medical Clinic</option> <option value="19263">Maua Medical Clinic</option> <option value="12492">Maua Methodist Hospital</option> <option value="15159">Mauche Dispensary</option> <option value="15160">Mauche Medical Clinic</option> <option value="18858">Maungu Model Health Centre</option> <option value="11582">Maunguja Dispensary</option> <option value="16010">Mautuma Sub-District Hospital</option> <option value="12493">Mavindini Health Centre</option> <option value="18330">Mavindu Dispensary</option> <option value="17256">Mavivye Model Health Centre</option> <option value="12494">Mavoko Medical Clinic</option> <option value="18482">Mavueni Dispensary</option> <option value="12495">Mavui Dispensary</option> <option value="16798">Mawamu Clinic</option> <option value="13795">Mawego Health Centre</option> <option value="12496">Maweli Dispensary</option> <option value="17233">Maweni CDF Dispensary (Kongowea)</option> <option value="18302">Maweni Community Clinic</option> <option value="19253">Mawenzi Care Clinics</option> <option value="15161">Mawepi Medical and VCT Centre</option> <option value="13796">Mawere Dispensary</option> <option value="19403">Max Family Health Care</option> <option value="11584">Maximillan Clinic</option> <option value="15162">Maximum Medical Services</option> <option value="16489">Mayanja Dispensary</option> <option value="13079">Mayflower Clinic</option> <option value="18701">Mayo Clinic</option> <option value="16597">Mayo Medical Clinic</option> <option value="16598">Mayo Medical Laboratory</option> <option value="10709">Mayols Medical Clinic</option> <option value="10710">Mayos Medical Clinic</option> <option value="11585">Mazeras Dispensary</option> <option value="11586">Maziwa Dispensary</option> <option value="11587">Mazumalume Dispensary</option> <option value="17672">Mbaga Dispensary</option> <option value="13797">Mbaga Health Centre</option> <option value="16011">Mbagara Dispensary</option> <option value="13080">Mbagathi District Hospital</option> <option value="20199">Mbaka Oromo Dispensary</option> <option value="11588">Mbalambala Dispensary</option> <option value="11589">Mbale Health Centre</option> <option value="12497">Mbale Medical Clinic</option> <option value="16012">Mbale Rural Health Training Centre</option> <option value="16013">Mbaleway Side Clinic</option> <option value="17622">Mbaraki Police VCT</option> <option value="19964">Mbari Ya Igi Dispensary</option> <option value="18824">Mbaruk Dispensary</option> <option value="17976">Mbaruk-Echareria Dispensary</option> <option value="17260">Mbau-Ini Dispensary</option> <option value="17839">Mbavani Dispensary</option> <option value="16467">Mbeere District Hospital</option> <option value="20088">Mbeere south DHMT</option> <option value="12498">Mbembani Dispensary</option> <option value="12499">Mbenuu H Centre</option> <option value="12500">Mbeu Sub-District Hospital</option> <option value="10711">Mbici Dispensary</option> <option value="19987">Mbiini Dispensary</option> <option value="18174">Mbiri (ACK) Dispensary</option> <option value="10713">Mbiriri Catholic Dispensary</option> <option value="12501">Mbita Dispensary</option> <option value="13798">Mbita District Hospital</option> <option value="16996">Mbitini (ACK) Dispensary</option> <option value="12502">Mbitini Catholic Dispensary</option> <option value="12521">Mbitini Health Centre</option> <option value="12503">Mbiuni Health Centre</option> <option value="12504">Mbiuni VCT</option> <option value="15164">Mbogo Valley Dispensary</option> <option value="15165">Mbogoini Dispensary</option> <option value="12505">Mbondoni Dispensary</option> <option value="16246">Mbondoni Dispensary (Mwingi)</option> <option value="12506">Mbonzuki Dispensary</option> <option value="12507">Mbooni (AIC) Dispensary</option> <option value="12508">Mbooni District Hospital</option> <option value="17287">Mboroga Dispensary</option> <option value="13081">Mbotela Clinic</option> <option value="17061">Mbugiti Dispensary</option> <option value="11590">Mbuguni Dispensary</option> <option value="16968">Mbuini Dispensary</option> <option value="11591">Mbulia Dispensary</option> <option value="18442">Mbuni Dispensary</option> <option value="12509">Mbusyani Dispensary</option> <option value="11592">Mbuta Model Health Centre</option> <option value="10714">Mbuti Medical Clinic</option> <option value="11593">Mbuwani Dispensary</option> <option value="18480">Mbuyu Dispensary</option> <option value="11594">Mbwajumwali Dispensary</option> <option value="18242">Mbwinjeru Methodist Dispensary</option> <option value="19187">Mcf Ndalani</option> <option value="19182">Mcf Yatta</option> <option value="10715">Mchana Estate Dispensary</option> <option value="17215">MCK Kathuine Dispensary</option> <option value="17927">MCK Kiirigu Dispensary</option> <option value="18913">MCK Mbwinjeru Dispensary</option> <option value="11595">Mecca Medical Clinic</option> <option value="13800">Mecheo Dispensary</option> <option value="16014">Mechimeru Dispensary</option> <option value="16694">Med Afric Medical Clinic</option> <option value="13085">Med-Point Dispensary</option> <option value="19482">Medanta Africare</option> <option value="19505">Medanta Africare Clinic</option> <option value="19099">Medical and Dental Clinic</option> <option value="10716">Medical Centre Clinic</option> <option value="19496">Medical Clinic</option> <option value="19493">Medical Link Integrated Health Program</option> <option value="19834">Medical Plaza Clinic Banana</option> <option value="13082">Medical Reception Dispensary</option> <option value="15166">Medical Reception Service - Ist Kr</option> <option value="10719">Medical Training College (Nyeri)</option> <option value="11598">Medicalitech Clinic</option> <option value="13083">Medicare Clinic</option> <option value="13801">Medicare Medical Clinic (Manga)</option> <option value="18647">Medicare Stores Chemist</option> <option value="15167">Mediheal Hospital</option> <option value="18266">Mediheal Hospital Nakuru</option> <option value="19525">Medimark Health Care</option> <option value="19010">Medina Diagnostic</option> <option value="13408">Medina Health Centre</option> <option value="19037">Medina Hospital</option> <option value="11597">Medina Medical Clinic</option> <option value="19519">Medisafe Medical Labaratoty</option> <option value="18040">Meditrust Health Care Services</option> <option value="19820">Medkam Pharmacy</option> <option value="19920">Medlink Medical Clinic</option> <option value="19176">Meds Pharmaciticals Ongata Rongai</option> <option value="16688">Meguara Dispensary</option> <option value="15168">Megwara Dispensary</option> <option value="15169">Meibeki Dispensary</option> <option value="13086">Melchezedek Hospital</option> <option value="20072">Melchizedek Hospital Karen</option> <option value="19055">Melchizedek Hospital Ngong Clinic</option> <option value="18290">Melkasons Clinic</option> <option value="15170">Melwa Health Centre</option> <option value="16255">Memo Clinic</option> <option value="11205">Memon Medical Centre</option> <option value="13087">Memorial Hospital</option> <option value="17025">Menegai Medical Clinic</option> <option value="19959">Menelik Chest Clinic</option> <option value="18688">Menengai Crator Dispensary</option> <option value="17021">Menengai Health Care Services</option> <option value="20138">Menengai Health Centre</option> <option value="15171">Menet Dispensary</option> <option value="15172">Mentera Dispensary</option> <option value="19019">Mephi Medical Clinic</option> <option value="17556">Merciful International Guild</option> <option value="13088">Mercillin Afya Centre</option> <option value="16746">Mercy Afya Clinic</option> <option value="12511">Mercy Clinic (Ikutha)</option> <option value="15173">Mercy Dispensary</option> <option value="16822">Mercy Dispensary (Lare)</option> <option value="17466">Mercy Health Centre</option> <option value="15174">Mercy Hospital</option> <option value="10563">Mercy Medical (Kianugu) Clinic</option> <option value="18135">Mercy Medical Clinic</option> <option value="19179">Mercy Medical Clinic</option> <option value="12512">Mercy Medical Clinic (Embu)</option> <option value="18904">Mercy Medical Clinic (Kitui Central)</option> <option value="10721">Mercy Medical Clinic (Othaya)</option> <option value="18974">Mercy Medical Clinic Engineer</option> <option value="19319">Mercy Medical Services</option> <option value="13089">Mercy Mission Health Centre</option> <option value="18691">Mercy Mission Medical Dispensary</option> <option value="15175">Mercy Mobile Clinic (Kipkelion)</option> <option value="15176">Mercy Mobile Clinic (Molo)</option> <option value="18597">Mercylight Hospital</option> <option value="10722">Mere Dispensary</option> <option value="15177">Merewet Dispensary</option> <option value="13409">Meri Health Centre</option> <option value="13109">Meridian Equator Hospital</option> <option value="18351">Meridian Medical Centre</option> <option value="19546">Meridian Medical Centre</option> <option value="13084">Meridian Medical Centre (Buruburu)</option> <option value="18591">Meridian Medical Centre (Capital Centre)</option> <option value="19395">Meridian Medical Centre (Loita Street)</option> <option value="18916">Meridian Medical Centre (Machakos)</option> <option value="18631">Meridian Medical Centre (Meru)</option> <option value="19550">Meridian Medical Centre (Penson Towers)</option> <option value="19696">Meridian Medical Centre Kitengela</option> <option value="18371">Meridian Medical Centre Nakuru</option> <option value="19799">Meridian Medical Centre Nyeri</option> <option value="18085">Meridian Medical Centre Ongata Rongai</option> <option value="20104">Meridian Medical centre(Nation Centre Bldg )</option> <option value="18528">Meridian Medical Centre- Nyeri Town</option> <option value="17727">Meridian Medical Donholm Clinic</option> <option value="15178">Merigi Dispensary</option> <option value="16217">Merille Dispensary</option> <option value="12513">Merti Catholic Dispensary</option> <option value="12514">Merti Health Centre</option> <option value="15179">Merto Dispensary</option> <option value="12515">Meru Childrens Clinic</option> <option value="16599">Meru Clinic</option> <option value="18731">Meru Consultant Clinic</option> <option value="16600">Meru Consultants</option> <option value="16601">Meru Consultants Laboratory</option> <option value="19073">Meru Cytology Centre</option> <option value="16602">Meru Dental Services</option> <option value="16603">Meru Diagnostic Centre</option> <option value="18700">Meru Diagnostic Centre</option> <option value="16604">Meru Dignostic / Laboratory Services</option> <option value="12516">Meru District Hospital</option> <option value="18653">Meru Eye Care Services</option> <option value="19113">Meru Funeral Home</option> <option value="19102">Meru Gynecologist Centre</option> <option value="19135">Meru Hospice</option> <option value="20053">Meru Kmtc Student/Staff Clinic</option> <option value="18706">Meru Lab Services</option> <option value="18648">Meru Lab Services</option> <option value="16605">Meru Medical /ENT Clinic</option> <option value="16606">Meru Medical Diagnostic Imaging Centre Ltd</option> <option value="16607">Meru Medical Plaza</option> <option value="16608">Meru Medical Plaza Laboratory</option> <option value="17266">Meru Technical Training College Clinic</option> <option value="19063">Meru X-Ray Services</option> <option value="15180">Merueshi Village Community Health Centre</option> <option value="20034">Mesedith Medical Clinic</option> <option value="17251">Meswo Medical Clinic</option> <option value="13802">Metaburo Health Centre</option> <option value="16302">Metameta Clinic</option> <option value="15181">Meteitei Sub-District Hospital</option> <option value="17079">Meti Dispensary</option> <option value="15182">Meto Dispensary</option> <option value="10723">Metro Optician</option> <option value="19463">Metropolitan Dr Plaza</option> <option value="13090">Metropolitan Hospital Nairobi</option> <option value="20200">Metropolitan Medical Clinic - Kehancha</option> <option value="15183">Metta Dispensary</option> <option value="11600">Mewa Hospital</option> <option value="20192">Meyan Dispensary</option> <option value="19303">Mfariji Medical Clinic</option> <option value="11601">Mgamboni Dispensary</option> <option value="11602">Mgange Dawida Dispensary</option> <option value="11603">Mgange Nyika Health Centre</option> <option value="12518">Miambani Catholic</option> <option value="12519">Miambani Health Centre</option> <option value="16972">Miangeni Dispensary (Makueni)</option> <option value="12520">Miangeni Dispensary (Mbooni)</option> <option value="11605">Miasenyi Dispensary</option> <option value="16234">Miathene District Hospital</option> <option value="11606">Michaela Denis Medical Clinic</option> <option value="10724">Micheus Clinic</option> <option value="12522">Micii Mikuru Clinic</option> <option value="13091">Mid Hill Medical Clinic</option> <option value="15184">Mid Hill Medical Clinic Ngong</option> <option value="19633">Mid-Point Health Services</option> <option value="18605">Mid-Town Reoproductive Health and Youth Friendly</option> <option value="13803">Midhine Dispensary</option> <option value="17342">Midida Dispensary</option> <option value="11609">Midoina Dispensary</option> <option value="13804">Midoti Dispensary</option> <option value="10725">Midway Clinic</option> <option value="16015">Miendo Dispensary</option> <option value="13805">Migori District Hospital</option> <option value="17737">Migori Health Station Clinic</option> <option value="13806">Migori T T C Dispensary</option> <option value="13807">Migosi Health Centre</option> <option value="10726">Miguta Dispensary</option> <option value="12523">Migwani Sub-District Hospital</option> <option value="10727">Mihang'o Dispensary</option> <option value="19791">Miharate Medical Clinic</option> <option value="10728">Mihuti Dispensary (Muranga North)</option> <option value="10729">Mihuti Dispensary (Nyeri South)</option> <option value="10730">Mihuti Medical Clinic</option> <option value="16016">Mihuu Dispensary</option> <option value="16017">Mijay Clinic</option> <option value="11610">Mijomboni Dispensary</option> <option value="11611">Mikanjuni Family Medical Clinic</option> <option value="11612">Mikanjuni Medical Clinic</option> <option value="10731">Mikaro Dispensary</option> <option value="19050">Mikeu PCEA Medical Centre</option> <option value="11613">Mikindani (MCM) Dispensary</option> <option value="11614">Mikindani Catholic Dispensary</option> <option value="11615">Mikindani Medical Clinic</option> <option value="12524">Mikinduri Health Centre</option> <option value="12525">Mikinduri Sub-District Hospial</option> <option value="17599">Mikongoni Dispensary</option> <option value="12526">Mikumbune Sub-District Hospital</option> <option value="17004">Mikuyuni Dispensary</option> <option value="19924">Mikuyuni Dispensary-Masinga</option> <option value="18247">Milaani Dispensary</option> <option value="18552">Milcelt Medical Clinic</option> <option value="15185">Mile 46 Health Centre</option> <option value="20018">Milele Integrated Medical Services</option> <option value="19059">Miliki Afya</option> <option value="15186">Milima Tatu Dispensary</option> <option value="19262">Milimani Eye Clinic</option> <option value="13808">Milimani Hospital</option> <option value="12527">Milimani Nursing Home</option> <option value="19212">Millenium Clinic</option> <option value="19478">Millenium Dental Clinic</option> <option value="16018">Milo Health Centre</option> <option value="17792">Miloreni Dispensary</option> <option value="16019">Miluki Dispensary</option> <option value="16766">Miniambo Dispensary</option> <option value="13092">Ministry of Education (Moest) VCT Centre</option> <option value="18072">Minjira Dispensary</option> <option value="15187">Minjore Dispensary</option> <option value="19103">Minoptic Eye Clinic</option> <option value="12528">Minugu Dispensary</option> <option value="13809">Minyenya Dispensary</option> <option value="18075">Miorre Dispensary</option> <option value="19030">Miraj Medical Centre</option> <option value="11616">Miranga Medical Clinic</option> <option value="13810">Miranga Sub District Hospital</option> <option value="10732">Mirangine Health Centre</option> <option value="11617">Mirapera Dispensary</option> <option value="17931">Mirere Health Centre</option> <option value="16610">Mirigamieru Health Facility</option> <option value="18702">Mirigamieru Health Services</option> <option value="11618">Mirihini Dispensary</option> <option value="13811">Miriri Dispensary</option> <option value="17822">Miritini (MCM) Dispensary</option> <option value="11620">Miritini CDF Dispensary</option> <option value="13812">Miriu Health Centre</option> <option value="13813">Mirogi Health Centre</option> <option value="15188">Mirugi Kariuki Dispensary</option> <option value="13814">Misesi Dispensary (Gucha)</option> <option value="11621">Mishoroni Dispensary</option> <option value="19950">Misikhu Main Medical Clinic</option> <option value="17679">Misikhu Medicalcclinic</option> <option value="15189">Miskwony Dispensary</option> <option value="13815">Misori Dispensary</option> <option value="11622">Mission K Clinic</option> <option value="11623">Mission Medical Clinic (Bahari)</option> <option value="16020">Mission of Mercy Clinic</option> <option value="12529">Misyani Catholic Health Centre</option> <option value="12530">Mitaboni Health Centre</option> <option value="12732">Mitaboni Mission Dispensary</option> <option value="12531">Mitamisyi Dispensary</option> <option value="16830">Mitethia Medical Clinic</option> <option value="20032">Mithikwani Dispensary</option> <option value="15190">Miti-Mingi Dispensary</option> <option value="10733">Mitubiri Dispensary</option> <option value="12532">Mituki Medical Clinic</option> <option value="18752">Mitume Dispensary</option> <option value="19260">Mitume Dispensary Kitale</option> <option value="17129">Mitunguu Catholic Dispensary</option> <option value="12533">Mitunguu Ccs Dispensary</option> <option value="12534">Mitunguu Dispensary</option> <option value="12535">Mitunguu Medical Services</option> <option value="16236">Mituntu Cottage Hospital</option> <option value="12536">Mituntu Health Centre</option> <option value="17613">Miu Dispensary</option> <option value="12537">Miu Sub-Health Centre</option> <option value="12538">Miumbuni Dispensary</option> <option value="12539">Mivukoni Health Centre</option> <option value="11624">Mivumoni (Catholic) Dispensary</option> <option value="13816">Miwani Dispensary</option> <option value="11625">Mizijini Dispensary</option> <option value="11626">Mjeni Medical Clinic</option> <option value="13093">Mji Wa Huruma Dispensary</option> <option value="11627">Mkang'ombe Community Dispensary</option> <option value="11628">Mkokoni Dispensary</option> <option value="11629">Mkongani Dispensary</option> <option value="11630">Mkundi Dispensary</option> <option value="13094">Mkunga Clinic</option> <option value="11631">Mkunumbi Dispensary</option> <option value="11633">Mkwiro Dispensary</option> <option value="11634">Mlaleo Health Centre</option> <option value="18210">Mlaleo Health Centre (MOH)</option> <option value="11635">Mlanjo Dispensary</option> <option value="18625">Mlimani Dispensary</option> <option value="18581">Mlolongo Health Centre</option> <option value="18256">Mlolongo VCT</option> <option value="17844">Mlolongo Wellness Centre</option> <option value="18167">Mmak</option> <option value="18275">Mmak Embakasi Stand Alone VCT</option> <option value="18639">Mmak's Homecare Pharmacy</option> <option value="20036">Mmangani Dispensary</option> <option value="13817">Mnara Dispensary</option> <option value="11636">Mnarani Dispensary</option> <option value="11637">Mnazini Dispensary</option> <option value="11638">Mnyenzeni Dispensary</option> <option value="11639">Moa Dispensary</option> <option value="15191">Mobet Dispensary</option> <option value="13818">Mochenwa Dispensary</option> <option value="15192">Mochongoi Health Centre</option> <option value="18367">Modaan Clinic</option> <option value="17126">Modambogho Dispensary</option> <option value="19668">Modern Mc</option> <option value="19793">Modern Medical Clinic</option> <option value="16021">Moding Health Centre</option> <option value="13410">Modogashe Clinic</option> <option value="12540">Modogashe Dispensary</option> <option value="13411">Modogashe District Hospital</option> <option value="15193">Mogil Health Centre</option> <option value="15194">Mogoget Dispensary</option> <option value="15195">Mogogosiek Health Centre</option> <option value="16327">Mogoiywet Dispensary</option> <option value="17713">Mogonga Maternity and Nursing Home (Kenyenya)</option> <option value="17583">Mogonjet Dispensary</option> <option value="15196">Mogoon Dispensary</option> <option value="17323">Mogor Dispensary</option> <option value="16721">Mogori-Komasimo Health Centre</option> <option value="15197">Mogorwa Health Centre</option> <option value="15198">Mogotio Dispensary</option> <option value="18959">Mogotio Medical Clinic</option> <option value="15199">Mogotio Plantation Dispensary</option> <option value="15200">Mogotio Rhdc</option> <option value="20005">Mogotio Town Dispensary</option> <option value="16869">Mogusii Clinic</option> <option value="15201">Mogwa Dispensary</option> <option value="15202">MOH Outreach (Trans Nzoia)</option> <option value="13095">Moi Air Base Hospital</option> <option value="11640">Moi Airport Dispensary</option> <option value="17485">Moi Baracks</option> <option value="11641">Moi District Hospital Voi</option> <option value="15203">Moi Ndabi Dispensary</option> <option value="18363">Moi Teachers College - Baringo</option> <option value="15204">Moi Teaching Refferal Hospital</option> <option value="15205">Moi University Health Centre</option> <option value="20151">Moi University Medical Clinic</option> <option value="15208">Moi's Bridge Catholic</option> <option value="15209">Moi's Bridge Health Centre</option> <option value="16022">Moi's Bridge Nursing Home</option> <option value="15206">Moiben Health Centre</option> <option value="17115">Moigutwo Dispensary</option> <option value="15210">Moka Clinic</option> <option value="13819">Mokason Clinic</option> <option value="13820">Mokomoni Health Centre</option> <option value="15211">Mokong Tea Dispensary</option> <option value="11642">Mokowe Health Centre</option> <option value="17042">Mokoyon Dispensary</option> <option value="15212">Molo District Hospital</option> <option value="15213">Molo Medical Centre</option> <option value="15214">Molo South Dispensary</option> <option value="15215">Molok Dispensary</option> <option value="15216">Molos Dispensary</option> <option value="15217">Molosirwe Dispensary</option> <option value="17625">Mombasa HIV Clinic</option> <option value="11643">Mombasa Hospital</option> <option value="17621">Mombasa Medicare Clinic</option> <option value="17627">Mombasa Polytechnic Clinic</option> <option value="18121">Mombasa Roadside Wellness Centre</option> <option value="16023">Mombasa Royal Clinic</option> <option value="15218">Mombwo Dispensary</option> <option value="15219">Momoniat Health Centre</option> <option value="18576">Mong'oni</option> <option value="16982">Mongorisi Health Centre</option> <option value="17601">Monguni Dispensary</option> <option value="13821">Monianku Health Centre</option> <option value="10734">Monica Clinic</option> <option value="15220">Monirre Dispensary</option> <option value="18447">Moogi Dispensary</option> <option value="15221">Morijo Dispensary</option> <option value="15222">Morijo Loita Dispensary</option> <option value="15223">Mormorio Dispensary</option> <option value="16024">Moru Karisa Dispensary</option> <option value="15225">Morulem Dispensary</option> <option value="12541">Mosa Dispensary</option> <option value="16261">Moshi Clinic</option> <option value="15227">Mosiro Dispensary</option> <option value="15226">Mosiro Dispensary (Kajiado North)</option> <option value="19245">Moso Cheptarit Medical Clinic</option> <option value="18580">Mosobeti Dispensary</option> <option value="20114">Mosocho Market Disp</option> <option value="15228">Mosore Dispensary</option> <option value="19250">Mosoriot Clinic</option> <option value="15229">Mosoriot Rural Health Training Centre</option> <option value="15230">Mosoriot Ttc Dispensary</option> <option value="13823">Mosque Dispensary</option> <option value="17363">Most Precious Blood Sisters Dispensary</option> <option value="13824">Motemorabu Dispensary</option> <option value="13096">Mother & Child Hospital</option> <option value="19277">Mother & Child Meridian & Lab Services</option> <option value="11645">Mother Amadea Health Centre</option> <option value="18298">Mother and Child Clinic Malindi</option> <option value="15231">Mother Franciscan Mission Health Centre</option> <option value="17724">Mother Ippolata Mukuru Clinic</option> <option value="15232">Mother Kevin Dispensary (Catholic)</option> <option value="12542">Mother Land Medical Clinic</option> <option value="17654">Mother of Mercy (Machakos)</option> <option value="11646">Mother Teresa Medical Clinic</option> <option value="13825">Moticho Health Centre</option> <option value="15233">Motiret Dispensary</option> <option value="13826">Motontera Dispensary</option> <option value="16984">Motonto Dispensary (Gucha)</option> <option value="15234">Motosiet Dispensary</option> <option value="11647">Mount View Nursing & Maternity Home</option> <option value="19782">Mountain Med Clinic</option> <option value="16206">Mountain Medical Clinic</option> <option value="17754">Mountain View Clinic</option> <option value="13097">Mow Dispensary</option> <option value="16298">Mowlana Medical Clinic</option> <option value="20066">Mowlem Diagnostic Medical Centre</option> <option value="18037">Moyale Afya Medical Clinic</option> <option value="12543">Moyale Catholic Dispensary</option> <option value="12544">Moyale District Hospital</option> <option value="12545">Moyale Nursing Home</option> <option value="13098">Mp Shah Hospital (Westlands)</option> <option value="17192">Mpala Mobile Clinic</option> <option value="15236">Mpalla Dispensary</option> <option value="18027">Mpalla Mobile Clinic</option> <option value="15237">Mpata Club Dispensary</option> <option value="18419">Mpc Mobile Clinic</option> <option value="11648">Mpeketoni Health Services Clinic</option> <option value="17694">Mpeketoni Health Sevices (Witu)</option> <option value="11649">Mpeketoni Sub-District Hospital</option> <option value="11650">Mpinzinyi Health Centre</option> <option value="12546">Mpukoni Health Centre</option> <option value="11651">Mrima (Catholic) Dispensary</option> <option value="19606">Mrima CDF Health Cenre</option> <option value="11225">Mrs - 77 Artillery Battallion (Mariakani)</option> <option value="11652">Mrughua Dispensary</option> <option value="11655">Msambweni District Hospital</option> <option value="13828">Msare Health Centre</option> <option value="11656">Msau Dispensary</option> <option value="15238">Msekekwa Health Centre</option> <option value="17651">Msf Olympic Centre</option> <option value="20049">Msf- Green House Clinic</option> <option value="20050">Msf- Lavender House Clinic</option> <option value="11657">Msikiti Noor Medical Clinic</option> <option value="18055">Msomi Complex Medical Clinic</option> <option value="11658">Msulwa Dispensary</option> <option value="11659">Msumarini Dispensary</option> <option value="19742">Mt Elgon Annex Clinics</option> <option value="19857">Mt Elgon Annex Clinics -Dr Manuthu</option> <option value="19385">Mt Elgon Clinic</option> <option value="16025">Mt Elgon District Hospital</option> <option value="15239">Mt Elgon Hospital</option> <option value="15240">Mt Elgon National Park Dispensary</option> <option value="19715">Mt Everest Medical Clinic</option> <option value="11661">Mt Harmony Clinic</option> <option value="10738">Mt Kenya (ACK) Hospital</option> <option value="16611">Mt Kenya Herbal Centre</option> <option value="19766">Mt Kenya Junior Academy</option> <option value="18015">Mt Kenya Kabiruini Medical Clinic</option> <option value="10741">Mt Kenya Narumoru Medical Clinic</option> <option value="19765">Mt Kenya Senior Academy</option> <option value="10739">Mt Kenya Sub-District Hospital</option> <option value="15241">Mt Longonot Hospital</option> <option value="10740">Mt Sinai Nursing Home</option> <option value="17269">Mt Zion Community Health Clinic</option> <option value="17568">Mt Zion Mission Medical Clinic</option> <option value="11662">Mtaa Dispensary</option> <option value="11663">Mtaani Clinic</option> <option value="17455">Mtaani VCT</option> <option value="11664">Mtangani Medical Clinic</option> <option value="15242">Mtaragon Health Centre</option> <option value="19594">Mtaro Estate Dispensary and Family Planning</option> <option value="13829">MTC Clinic (Kisumu)</option> <option value="11665">MTC Mombasa</option> <option value="11666">Mtepeni Dispensary</option> <option value="17500">Mteremuko Medical Clinic</option> <option value="12547">Mtito andei Sub District</option> <option value="11667">Mtondia Dispensary</option> <option value="11668">Mtondia Medical Clinic</option> <option value="11669">Mtongwe (MCM) Dispensary</option> <option value="18945">Mtoni Medical Clinic</option> <option value="11670">Mtopanga Clinic</option> <option value="18309">Mtoroni Dispensary</option> <option value="11672">Mtwapa Health Centre</option> <option value="11673">Mtwapa Nursing Home</option> <option value="12548">Mua Hills Dispensary</option> <option value="17603">Muamba Dispensary</option> <option value="17816">Muangeni Dispensary</option> <option value="18066">Mubachi Dispensary</option> <option value="18127">Mubwekas Medical Clinic</option> <option value="12549">Muchagori Dispensary</option> <option value="18753">Mucharage Mlc</option> <option value="17333">Muchatha Dispensary</option> <option value="19831">Muchatha Medical Clinic</option> <option value="13830">Muchebe Dispensary</option> <option value="18269">Muchonoke Dispensary</option> <option value="15243">Muchukwo Dispensary</option> <option value="16476">Muchuro Dispensary</option> <option value="11674">Mudzo Medical Clinic</option> <option value="12550">Mufu Dispensary</option> <option value="18444">Mufutu Medical Clinic</option> <option value="17510">Muga Medical Clinic</option> <option value="16272">Mugabo Dispensary</option> <option value="18779">Mugai Dispensary</option> <option value="15244">Mugango Dispensary</option> <option value="12552">Mugas Clinic</option> <option value="10744">Mugeka Dispensary</option> <option value="19648">Mugi Medical Clinic</option> <option value="10745">Mugoiri Dispensary</option> <option value="17597">Mugomari Dispensary</option> <option value="11675">Mugos Clinic</option> <option value="12551">Mugui Consolata Clinic</option> <option value="12553">Mugui Dispensary</option> <option value="16507">Mugumo Clinic/Laboratory</option> <option value="19288">Mugumo Medical</option> <option value="10747">Mugumo-Ini Medical Clinic</option> <option value="15245">Mugumoini Dispensary (Kipkelion)</option> <option value="10748">Mugumoini Dispensary (Muranga South)</option> <option value="16612">Muguna West Clinic</option> <option value="10749">Mugunda Dispensary</option> <option value="10750">Mugunda Mission Dispensary</option> <option value="10751">Muguo Clinic</option> <option value="15246">Mugurin Dispensary</option> <option value="18391">Mugutha (CDF) Dispensary</option> <option value="12555">Mugwee Clinic</option> <option value="16026">Muhabini Medical Clinic</option> <option value="16027">Muhaka Disensary</option> <option value="11676">Muhaka Dispensary</option> <option value="18788">Muhamarani Dispensary</option> <option value="13831">Muhoroni Sub-District Hospital</option> <option value="13832">Muhoroni Sugar Company (Musco) Dispensary</option> <option value="15247">Muhotetu Dispensary</option> <option value="10752">Muhoya Medical Clinic</option> <option value="13833">Muhuru Health Centre</option> <option value="12556">Mui Dispensary</option> <option value="19848">Muiywek Dispensary</option> <option value="12557">Mujwa Dispensary</option> <option value="18536">Mukanga Dispensary (Muranga North)</option> <option value="12559">Mukangu (ACK) Dispensary</option> <option value="16387">Mukangu Dispensary</option> <option value="10753">Mukarara Community Dispensary</option> <option value="17057">Mukarara Dispensary</option> <option value="10754">Mukarara Medical Clinic</option> <option value="18963">Mukerenju Dispensary</option> <option value="10755">Mukeu (AIC) Dispensary</option> <option value="16028">Mukhe Dispensary</option> <option value="16029">Mukhobola Health Centre</option> <option value="20046">Mukhweso Clinic</option> <option value="10756">Mukindu Dispensary</option> <option value="10757">Mukoe Dispensary</option> <option value="16863">Mukong'a Dispensary</option> <option value="16399">Mukorombosi Dispensary</option> <option value="12560">Mukothima Health Centre</option> <option value="13407">Muktar Dada Medical Clinic</option> <option value="12561">Mukui Health Centre</option> <option value="16030">Mukumu Hospital</option> <option value="10758">Mukungi Dispensary</option> <option value="16435">Mukunike Dispensary</option> <option value="10759">Mukuria Dispensary</option> <option value="13100">Mukuru Crescent Clinic</option> <option value="18463">Mukuru Health Centre</option> <option value="13101">Mukuru Mmm Clinic</option> <option value="10760">Mukurwe (PCEA) Medical Clinic</option> <option value="10761">Mukurwe Dispensary</option> <option value="10763">Mukurweini District Hospital</option> <option value="10762">Mukurweini Medical Clinic</option> <option value="12562">Mukusu Dispensary</option> <option value="15249">Mukutani Dispensary (East Pokot)</option> <option value="12563">Mukuuni Dispensary</option> <option value="12564">Mukuuri Dispensary</option> <option value="16031">Mukuyu Dispensary</option> <option value="10764">Mukuyu Medical Clinic</option> <option value="12565">Mukuyuni Health Centre</option> <option value="13834">Mulaha Dispensary</option> <option value="12566">Mulango (AIC) Dispensary</option> <option value="12567">Mulangoni Dispensary</option> <option value="16032">Mulele Dispensary</option> <option value="16482">Mulembe Clinic</option> <option value="18815">Mulembe Medical Clinic</option> <option value="15250">Mulemi Maternity Home</option> <option value="18863">Mulika Dispensary</option> <option value="16924">Muliluni Dispensary</option> <option value="18451">Mulimani Medical Clinic</option> <option value="16936">Mulinde Dispensary</option> <option value="15251">Mulot Catholic Dispensary</option> <option value="18519">Mulot Dispensary</option> <option value="17740">Mulot Health Centre</option> <option value="19737">Mulot VCT</option> <option value="13018">Multi Media University Dispensary</option> <option value="18377">Multipurpose Village Health Care Centre</option> <option value="16416">Mulukaka Clinic</option> <option value="12568">Mulundi Dispensary</option> <option value="12569">Mulutu Mission Dispensary</option> <option value="16033">Mulwanda Dispensary</option> <option value="10766">Mumbuini Dispensary</option> <option value="16034">Mumbule Dispensary</option> <option value="12570">Mumbuni Dispensary (Maara)</option> <option value="12571">Mumbuni Dispensary (Makueni)</option> <option value="12572">Mumbuni Dispensary (Mwala)</option> <option value="12573">Mumbuni Dispensary (Mwingi)</option> <option value="12574">Mumbuni Nursing Home</option> <option value="16035">Mumias Dispensary</option> <option value="16036">Mumias Maternity</option> <option value="16038">Mumias Sugar Clinic</option> <option value="18714">Mummy Medical Clinic</option> <option value="16039">Mummy's Medical Clinic</option> <option value="12575">Mumo (AIC) Health Centre</option> <option value="12576">Mumoni Dispensary</option> <option value="18951">Mumui Dispensary</option> <option value="20062">Mundika Maternity & Nursing Home</option> <option value="16040">Mundoli Health Centre</option> <option value="17823">Mundoro Community</option> <option value="18658">Mundoro Community Dispensary</option> <option value="10767">Mundoro Medical Clinic</option> <option value="13102">Mundoro Medical Clinic Dandora</option> <option value="12577">Mundu Ta Mundu Clinic</option> <option value="10768">Mung'ang'a (ACK) Dispensary</option> <option value="16041">Mung'ang'a Dispensary</option> <option value="16042">Mung'ung'u Dispensary</option> <option value="17309">Mungaria Dispensary</option> <option value="10769">Mungu Aponya Medical Clinic</option> <option value="15252">Mungwa Dispensary</option> <option value="11677">Municipal Health Centre</option> <option value="16043">Munongo Dispensary</option> <option value="16044">Munoywa Dispensary</option> <option value="10770">Mununga Dispensary</option> <option value="10771">Mununga Health Clinic</option> <option value="16807">Munyaka Dispensary</option> <option value="10772">Munyaka Medical Clinic</option> <option value="10773">Munyange (AIPCA) Dispensary</option> <option value="17883">Munyange Gikoe Dispensary</option> <option value="16045">Munyanza Nursing Home</option> <option value="10774">Munyu Health Centre</option> <option value="10775">Munyu Medical Clinic</option> <option value="10776">Munyu-Ini Dispensary</option> <option value="16046">Munyuki Dispensary</option> <option value="12578">Muono Dispensary</option> <option value="17523">Mur Malanga Dispensary</option> <option value="15253">Muramati Dispensary</option> <option value="12579">Murambani Dispensary</option> <option value="10777">Murang'a District Hospital</option> <option value="16431">Murantawa Dispensary</option> <option value="10778">Murarandia Dispensary</option> <option value="10779">Murarandia Medical Centre</option> <option value="19732">Murarandia Medical Clinic</option> <option value="10780">Mureru Dispensary</option> <option value="15254">Murgor Hills Dispensary</option> <option value="15255">Murgusi Dispensary</option> <option value="16047">Murhanda Medical Clinic</option> <option value="15256">Muricho Dispensary</option> <option value="17191">Murindoku Dispensary</option> <option value="10781">Murinduko Health Centre</option> <option value="12580">Muringombugi Clinic</option> <option value="10782">Muriranjas Sub-District Hospital</option> <option value="12581">Muriri Clinic</option> <option value="15257">Murkwijit Dipensary</option> <option value="20055">Murkwijit Dispensary</option> <option value="19012">Murpus Medical Clinic</option> <option value="17277">Muruangai Dispensary</option> <option value="16048">Murudef Clinic</option> <option value="16613">Murugu Herbal Clinic</option> <option value="16999">Muruguru Dispensary</option> <option value="10783">Muruguru Medical Clinic (Nyeri North)</option> <option value="10784">Muruguru Medical Clinic (Nyeri South)</option> <option value="10785">Muruka Dispensary</option> <option value="17033">Muruku Dispensary</option> <option value="10786">Murungaru Health Centre</option> <option value="11653">Muryachakwe Dispensary</option> <option value="12582">Musalala Dispensary</option> <option value="16049">Musanda (ACK) Clinic</option> <option value="17507">Musau Medical Clinic</option> <option value="20042">Musavani Dispensary</option> <option value="17501">Musco Clinic</option> <option value="18507">Muselele</option> <option value="16865">Musembe Dispensary</option> <option value="16051">Musembe Dispensary (Lugari)</option> <option value="17447">Musengo Medical Clinic</option> <option value="12583">Museve Dispensary</option> <option value="16486">Musibiriri Dispensary</option> <option value="17162">Musingini Dispensary</option> <option value="16052">Musitinyi Dispensary</option> <option value="18434">Muska Medical Centre</option> <option value="15260">Muskut Health Centre</option> <option value="18660">Musoa SDA Dispensary</option> <option value="16053">Musoli Health Clinic</option> <option value="16938">Musovo Dispensary</option> <option value="16247">Musukini Dispensary</option> <option value="18365">Mutanda Community Dispensary</option> <option value="18565">Mutanda Dispensary</option> <option value="15261">Mutara Dispensary</option> <option value="15262">Mutarakwa Dispensary (Molo)</option> <option value="10788">Mutarakwa Dispensary (Nyandarua South)</option> <option value="19500">Mutathamia Medical Clinic</option> <option value="13103">Muteithania Medical Clinic</option> <option value="19881">Mutelai Dispensary</option> <option value="12584">Mutembuku Dispensary</option> <option value="16222">Mutethia Clinic</option> <option value="18931">Mutethia Clinic Magutuni</option> <option value="17661">Mutethia Medical Clinic</option> <option value="16848">Mutethia Medical Clinic (Imenti Central)</option> <option value="10789">Mutethia Medical Clinic (Nyeri South)</option> <option value="12585">Mutethya Medical Clnic</option> <option value="12586">Mutha Health Centre</option> <option value="10790">Muthaara Dispensary</option> <option value="17450">Muthale East Medical Clinic</option> <option value="12587">Muthale Mission Hospital</option> <option value="18899">Muthale Mission Hospital Satelite Clinic</option> <option value="12588">Muthambi Dispensary</option> <option value="12589">Muthambi Health Centre</option> <option value="12590">Muthanthara Dispensary</option> <option value="12591">Muthara Sub-District Hospital</option> <option value="15263">Muthegera Dispensary</option> <option value="10791">Mutheru Dispensary</option> <option value="12592">Muthesya Dispensary</option> <option value="12593">Muthetheni Health Centre</option> <option value="12594">Muthetheni Mission Health Centre</option> <option value="10792">Muthinga Medical Clinic</option> <option value="16175">Muthithi (PCEA) Dispensary</option> <option value="10793">Muthithi Dispensary</option> <option value="18628">Muthua Dispensary</option> <option value="17606">Muthue Dispenary</option> <option value="18673">Muthungue Dispensary</option> <option value="13104">Muthurwa Clinic</option> <option value="10794">Muthuthiini Dispensary</option> <option value="10795">Muthuthiini Medical Clinic</option> <option value="12595">Muthwani (AIC) Dispensary</option> <option value="12596">Mutiluni Dispensary</option> <option value="18707">Mutindwa Clinic and Lab</option> <option value="12597">Mutindwa Dispensary</option> <option value="16615">Mutindwa Laboratory</option> <option value="16616">Mutindwa Med Clinic</option> <option value="16054">Muting'ong'o Dispensary</option> <option value="18132">Mutini Dispensary</option> <option value="17379">Mutiokiama Health Centre</option> <option value="12598">Mutionjuri Health Centre</option> <option value="10796">Mutira (ACK) Dispensary</option> <option value="10797">Mutira Laboratory</option> <option value="18349">Mutithi Dispensary</option> <option value="10798">Mutithi Health Centre</option> <option value="12599">Mutito Catholic Dispensary</option> <option value="10799">Mutitu Community Dispensary</option> <option value="12600">Mutitu Dispensary</option> <option value="10800">Mutitu Gikondi Medical Clinic</option> <option value="12601">Mutitu Sub-District Hospital</option> <option value="12602">Mutituni Dispensary</option> <option value="12603">Mutomo Health Centre</option> <option value="18911">Mutomo Health Clinic</option> <option value="12604">Mutomo Mission Hospital</option> <option value="19932">Mutonya CDF Dispensary</option> <option value="16055">Mutsetsa Dispensary</option> <option value="19237">Mutuati Catholic Hospital</option> <option value="12606">Mutuati Nursing Home</option> <option value="12605">Mutuati Sub-District Hospital</option> <option value="13105">Mutuini Sub-District Hospital</option> <option value="18102">Mutukanio ACK Dispensary</option> <option value="12607">Mutukya Dispensary</option> <option value="18008">Mutulani Dispensary</option> <option value="12608">Mutulu (AIC) Dispensary</option> <option value="12609">Mutune Dispensary</option> <option value="18289">Mutunguru PCEA Dispensary</option> <option value="10802">Mutungus Medical Clinic</option> <option value="19933">Mutwangombe Dispensary</option> <option value="12610">Mutyambua Dispensary</option> <option value="12611">Mutyangome Dispensary</option> <option value="19903">Muua Dispensary</option> <option value="17872">Muuani Rural Health Dispensary</option> <option value="12612">Muumandu Dispensary</option> <option value="19751">Muungano Dispensary</option> <option value="12613">Muusini Dispensary</option> <option value="18413">Muusini Dispensary (Makueni)</option> <option value="12614">Muutine Med Clinic</option> <option value="12615">Muutiokiama Health Centre</option> <option value="17779">Muvuko Dispensary</option> <option value="12616">Muvuti Dispensary</option> <option value="10803">Muwa M Clinic</option> <option value="15264">Muyengwet Dispensary</option> <option value="11678">Muyeye Medical Clinic</option> <option value="12617">Muyuni Dispensary</option> <option value="13412">Muzadilifa Clinic</option> <option value="13835">Mv Patel Clinic</option> <option value="11679">Mvita Dispensary</option> <option value="11680">Mvono Clinic</option> <option value="16956">Mwaani Dispensary</option> <option value="11681">Mwabila Dispensary</option> <option value="16548">Mwachande Medical Clinic</option> <option value="11682">Mwachinga Medical Clinic</option> <option value="18279">Mwafrika Institute of Development</option> <option value="20201">Mwaki Healthcare</option> <option value="11683">Mwakirunge Dispensary</option> <option value="12618">Mwala District Hospital</option> <option value="18262">Mwala Medical Clinic</option> <option value="11684">Mwaluphamba Dispensary</option> <option value="11685">Mwaluvanga Dispensary</option> <option value="11686">Mwambirwa Dispensary</option> <option value="12619">Mwambiu Dispensary</option> <option value="19190">Mwanainchi Medical Clinic</option> <option value="19038">Mwananchi Clinic</option> <option value="16549">Mwananyamala (CDF) Dispensary</option> <option value="11687">Mwanda Dispensary</option> <option value="11688">Mwanda Health Centre (Taita Taveta)</option> <option value="16395">Mwangate Dispensary</option> <option value="11689">Mwangatini Dispensary</option> <option value="16356">Mwangaza Medical Clinic</option> <option value="18350">Mwangaza Medical Clinic (Bakarani)</option> <option value="11690">Mwangaza Medical Clinic (Mombasa)</option> <option value="10804">Mwangaza Medical Clinic (Thika)</option> <option value="20015">Mwangaza Tana Medical Clinic</option> <option value="20091">Mwangaza ulio Na Tumaini clinic</option> <option value="11691">Mwangulu Dispensary</option> <option value="17941">Mwanianga Dispensary</option> <option value="12622">Mwanyani Dispensary</option> <option value="19944">Mwanyani Dispensary (Kitui Central)</option> <option value="11692">Mwanzo Medical Clinic</option> <option value="11693">Mwapala Dispensary</option> <option value="18938">Mwarimba Medical Clinic</option> <option value="16554">Mwashuma Dispensary (CDF)</option> <option value="16056">Mwasi Med Clinc</option> <option value="13106">Mwatate Clinic</option> <option value="19454">Mwatate Healthcare Centre</option> <option value="11694">Mwatate Sisal Estate Clinic</option> <option value="11695">Mwatate Sub-District Hospital</option> <option value="18961">Mwathene Dispensary</option> <option value="16523">Mwavizi Medical Clinic</option> <option value="11696">Mwawesa Medical Clinic</option> <option value="17427">Mwea Dental Clinic</option> <option value="17132">Mwea Diabetes / Hypertension Community Clinic</option> <option value="18833">Mwea Drop Inn Centre</option> <option value="10806">Mwea Medical Centre</option> <option value="16508">Mwea Medical Clinic</option> <option value="10805">Mwea Medical Clinic Kagio</option> <option value="10807">Mwea Medical Laboratory</option> <option value="10808">Mwea Mission (Our Lady of Lourdes) Hospital</option> <option value="10809">Mweiga Health Centre</option> <option value="10810">Mweiga Medical Care</option> <option value="10811">Mweiga Rural Health Clinic</option> <option value="12623">Mweini Dispensary</option> <option value="19239">Mwema Health Care Clinic</option> <option value="11697">Mwembe Tayari Staff Clinic</option> <option value="19803">Mwenda andu Medical Clinic</option> <option value="18989">Mwendantu Amani Clinic</option> <option value="18947">Mwendantu Baraka Clinic</option> <option value="12624">Mwendwa Clinic</option> <option value="10812">Mwendwa Medical Clinic</option> <option value="17604">Mwengea Dispensary</option> <option value="15266">Mwenje Dispensary</option> <option value="16788">Mwer Dispensary</option> <option value="19442">Mwera Medical Clinic</option> <option value="12625">Mweronkaga Dispensary</option> <option value="16229">Mweru Dispensary (Imenti South)</option> <option value="10814">Mweru Dispensary (Nyeri South)</option> <option value="11698">Mwichens Medical Clinic</option> <option value="16057">Mwichio Amua Medical Clinic</option> <option value="16396">Mwigito Dispensary</option> <option value="16058">Mwihila Mission Hospital</option> <option value="17410">Mwikalikha Dispensary</option> <option value="16646">Mwikia Clinic</option> <option value="16194">Mwina Dispensary</option> <option value="16201">Mwina Methodist Dispensary</option> <option value="12626">Mwingi District Hospital</option> <option value="17055">Mwingi Medicare Centre</option> <option value="12627">Mwingi Nursing Home</option> <option value="10815">Mwireri Sunrise Medical Clinic</option> <option value="18104">Mwisho Wa Lami Medical Clinic</option> <option value="12628">Mwitika Dispensary</option> <option value="15267">Mwituria Dispensary</option> <option value="12629">Mwonge Clinic</option> <option value="12630">Mwonge Dispensary</option> <option value="13836">Mwongori Dispensary</option> <option value="19386">Mworoga Catholic Dispensary</option> <option value="19350">Mworoga Dispensary</option> <option value="16617">Myopic Eye Clinic</option> <option value="20096">MYSA VCT</option> <option value="17893">Mzizima (CDF) Dispensary</option> <option value="12631">Naari Health Centre</option> <option value="10817">Naaro Dispensary</option> <option value="15268">Nabkoi Dispensary</option> <option value="16059">Nabongo Dispensary</option> <option value="16478">Nabuganda Dispensary</option> <option value="15269">Nachecheyet Dispensary</option> <option value="15270">Nachola Dispensary</option> <option value="15271">Nachukui Dispensary</option> <option value="15272">Nacoharg Medical Centre</option> <option value="16060">Nadanya Dispensary</option> <option value="15273">Nadapal Dispensary</option> <option value="15274">Nadapal Primary Health Care Programme</option> <option value="15275">Nadoto Dispensary</option> <option value="18099">Nadung'a Dispensary</option> <option value="10818">Nahashon Mwangi Medical Clinic</option> <option value="10819">Naidu Hospital</option> <option value="15276">Naikara Dispensary</option> <option value="17383">Naikuriu Dispensary</option> <option value="13107">Naioth Medical Clinic</option> <option value="15277">Nairagie-Enkare Health Centre</option> <option value="15278">Nairasirasa Dispensary</option> <option value="17280">Nairimirimo Dispensary</option> <option value="13108">Nairobi Deaf (Liverpool)</option> <option value="18394">Nairobi Earc St Anne Medical Clinic</option> <option value="19580">Nairobi Eye Associates</option> <option value="17619">Nairobi Homes Clinic</option> <option value="13110">Nairobi Hospital</option> <option value="13111">Nairobi Outpatient Centre</option> <option value="19477">Nairobi Outreach Services Trust</option> <option value="12632">Nairobi Pathologist Clinic</option> <option value="13161">Nairobi Remand Prison Health Centre</option> <option value="13113">Nairobi South Clinic</option> <option value="13112">Nairobi South Hospital</option> <option value="13114">Nairobi West Chidren Clinic</option> <option value="13115">Nairobi West Hospital</option> <option value="13116">Nairobi West Men's Prison Dispensary</option> <option value="19609">Nairobi Women Hospital Eastleigh</option> <option value="19178">Nairobi Women Hospital Kitengela</option> <option value="18195">Nairobi Women Hospital Ongata Rongai</option> <option value="20061">Nairobi Women's Hospital</option> <option value="13117">Nairobi Womens Hospital (Hurlingham)</option> <option value="16795">Nairobi Womens Hospital Adams</option> <option value="16402">Naishi Game Dispensary</option> <option value="15279">Naisoya Dispensary</option> <option value="18979">Naisula Medical Clinic</option> <option value="12633">Naisura Medical Clinic</option> <option value="16061">Naitiri Sub-District Hospital</option> <option value="15282">Naivasha (AIC) Medical Centre</option> <option value="15280">Naivasha District Hospital</option> <option value="15281">Naivasha Max Prison Health Centre</option> <option value="13280">Najah Medical Clinic</option> <option value="15283">Najile Dispensary</option> <option value="15284">Nakaalei Dispensary</option> <option value="18354">Nakechichok Dispensary</option> <option value="19511">Nakhayo Medical Clinic</option> <option value="16729">Nakoko Dispensary</option> <option value="16700">Nakukulas Dispensary</option> <option value="15285">Nakurio Dispensary</option> <option value="17084">Nakurtakwei Dispensary</option> <option value="15286">Nakuru Clinical Unit</option> <option value="15287">Nakuru Nursing Home</option> <option value="15288">Nakuru Provincial General Hospital (PGH)</option> <option value="15289">Nakuru War Memorial Hospital</option> <option value="15290">Nakuru West (PCEA) Health Centre</option> <option value="15291">Nakururum Dispensary</option> <option value="15292">Nakwamoru Health Centre</option> <option value="16366">Nakwijit Dispensary</option> <option value="17153">Nakwijit Dispensary</option> <option value="16062">Nala Maternity and Nursing Home</option> <option value="18971">Nalala Initiative Community Clinic</option> <option value="15293">Nalepo Medical Clinic</option> <option value="18412">Nalis Medical Centre</option> <option value="16063">Nalondo Cbm Dispensary</option> <option value="17117">Nalondo Health Centre (Model)</option> <option value="16064">Namagara Dispensary</option> <option value="15294">Namanga Health Centre</option> <option value="18491">Namanga Wellness Centre</option> <option value="17994">Namanjalala Dispensary</option> <option value="18930">Namarei Dispensary (Marsabit South)</option> <option value="16065">Namasoli Health Centre</option> <option value="15295">Namayiana Clinic</option> <option value="16273">Namba Kodero Dispensary</option> <option value="16066">Nambale Health Centre</option> <option value="16067">Namboboto Dispensary</option> <option value="16068">Nambuku Model Health Centre</option> <option value="15296">Namelok Health Centre</option> <option value="15297">Namelok Medical Clinic</option> <option value="18091">Namenya CFW Clinic</option> <option value="15298">Nameyana Dispensary</option> <option value="17178">Namirama Dispensary</option> <option value="16380">Namocha Dispensary</option> <option value="15299">Namoruputh (PAG) Health Centre</option> <option value="16069">Namuduru Dispensary</option> <option value="15301">Namukuse Dispensary</option> <option value="16070">Namulungu Dispensary</option> <option value="15300">Namuncha Dispensary</option> <option value="17541">Namunyak Clinic</option> <option value="17773">Namunyak Dispensary</option> <option value="16071">Namwaya Clinic</option> <option value="12634">Nana Dispensary</option> <option value="15303">Nanam Dispensary</option> <option value="10820">Nandarasi Dispensary</option> <option value="14179">Nandi Hills District Hospital</option> <option value="17211">Nandi Hills Doctors Scheme Association Dispensary </option> <option value="19358">Nandi Hills Medicare Clinic</option> <option value="16072">Nangina Dispensary</option> <option value="11699">Nanighi Dispensary (Tana River)</option> <option value="13413">Nanighi Health Centre</option> <option value="10821">Nanyuki Cottage</option> <option value="15304">Nanyuki Cottage Hospital</option> <option value="15305">Nanyuki District Hospital</option> <option value="15307">Naoros Dispensary</option> <option value="17478">Naotin Dispensary</option> <option value="18070">Napeikar Dispensary</option> <option value="15308">Napeililim Dispensary</option> <option value="17249">Napeitom Dispensary</option> <option value="15309">Napusimoru Dispensary</option> <option value="17300">Naramam Dispensary</option> <option value="19208">Naretisho Dispensary</option> <option value="15310">Nariokotome Dispensary</option> <option value="15311">Narok District Hospital</option> <option value="18299">Narok University College Clinic</option> <option value="17326">Narolong Dispensary</option> <option value="16689">Narolong Dispensary (Trans Mara West)</option> <option value="10822">Naromoru Health Centre</option> <option value="15312">Naroosura Health Centre</option> <option value="16221">Narrapu Dispensary</option> <option value="16816">Narumoru Catholic Dispensary</option> <option value="19279">Narzareth Medical Services</option> <option value="15313">Nasaroni Medical Clinic</option> <option value="19338">Nasaruni Medical Clinic</option> <option value="13119">Nascop VCT</option> <option value="16074">Nasewa Health Centre</option> <option value="20056">Nasha Lengot Medical Centre</option> <option value="16075">Nasianda Dispensary</option> <option value="18355">Nasiger Dispensary</option> <option value="19887">Nasira Dispensary</option> <option value="15314">Nasolot Dispensary</option> <option value="17194">Nasusi</option> <option value="16076">Nasusi Dispensary</option> <option value="10824">National Hospital Insurance Fund Central</option> <option value="13194">National Spinal Injury Hospital</option> <option value="16077">National Youth Service Dispensary</option> <option value="13130">National Youth Service Hq Dispensary (Ruaraka)</option> <option value="15315">Natira Dispensary</option> <option value="20045">Natunyi Dispensary</option> <option value="15316">Nauyapong Dispensary</option> <option value="16078">Navakholo Sub-District Hospital</option> <option value="11514">Nawaco Clinic</option> <option value="13837">Naya Health Centre</option> <option value="18025">Nayrus Medical Clinic</option> <option value="18554">Nazarene Medical Clinic</option> <option value="19118">Nazarene Medical Clinic (Kitui West)</option> <option value="18712">Nazarene Sister's Dispensary Rwarera</option> <option value="10825">Nazareth Hospital</option> <option value="17490">Nazareth Hospital (Ruiru)</option> <option value="19323">Nazareth Medical Clinic</option> <option value="16341">Nazareth Medical Clinic (Wareng)</option> <option value="17708">Ncooro Dispensary</option> <option value="18504">Ncunga Catholic Dispensary</option> <option value="15317">Ndabarnach Clinic</option> <option value="15318">Ndabibi Dispensary</option> <option value="10827">Ndakaini Clinic</option> <option value="10828">Ndakaini Dispensary</option> <option value="17817">Ndakani Dispensary</option> <option value="12635">Ndalani Dispensary</option> <option value="19978">Ndalani Dispensary (Makindu)</option> <option value="15319">Ndalat (PCEA) Health Centre</option> <option value="15320">Ndalat Gaa Dispensary</option> <option value="16079">Ndalu Health Centre</option> <option value="17325">Ndamama Dispensary</option> <option value="15321">Ndamichonik Dispensary</option> <option value="15322">Ndanai</option> <option value="10829">Ndaragwa Health Centre</option> <option value="15323">Ndarawetta Dispensary</option> <option value="15324">Ndarugu (PCEA) Dispensary</option> <option value="12636">Ndatani Dispensary</option> <option value="10830">Ndathi Dispensary</option> <option value="11700">Ndau Dispensary</option> <option value="20127">Ndauni Dispensary</option> <option value="11701">Ndavaya Dispensary</option> <option value="13839">Ndeda Dispensary</option> <option value="19029">Ndege Medical Clinic</option> <option value="17345">Ndege Oriedo Dispensary</option> <option value="10831">Ndeiya Health Centre</option> <option value="18245">Ndela Dispensary</option> <option value="19923">Ndelekeni Dispensary</option> <option value="10832">Ndemi Health Centre</option> <option value="20025">Ndenderu Dispensary</option> <option value="19833">Ndenderu Medical Services</option> <option value="20173">Ndere Community Dispensary</option> <option value="13840">Ndere Health Centre</option> <option value="16660">Nderema Dispensary</option> <option value="13841">Ndhiwa Sub-District Hospital</option> <option value="13842">Ndhuru Dispensary</option> <option value="19844">Ndia Chemist Clinic</option> <option value="11702">Ndilidau Dispensary (Jipe)</option> <option value="10833">Ndimaini Dispensary</option> <option value="15325">Ndindika Health Centre</option> <option value="13843">Ndiru Health Centre</option> <option value="16771">Ndisi Dispensary</option> <option value="12637">Ndithini Health Centre</option> <option value="12638">Ndiuni Dispensary</option> <option value="10834">Ndivai Dispensary</option> <option value="13844">Ndiwa Dispensary</option> <option value="15326">Ndoinet Dispensary</option> <option value="17715">Ndoleli MCK Dispensay</option> <option value="11704">Ndome Dispensary (Taita)</option> <option value="11745">Ndongo Purple Clinic</option> <option value="10835">Ndonyero Medical Clinic</option> <option value="15511">Ndonyo Medical Clinic</option> <option value="19336">Ndonyo Medical Clinic (Naivasha Kwa Muya)</option> <option value="19946">Ndonyo Nasipa Dispensary</option> <option value="15327">Ndonyo Wasin Dispensary</option> <option value="13845">Ndori Health Centre</option> <option value="11705">Ndovu Health Centre</option> <option value="17465">Ndubeneti Dispensary</option> <option value="16669">Ndubusat Bethel Dispensary</option> <option value="19868">Nduga Dispensary</option> <option value="10836">Ndugamano Dispensary</option> <option value="10837">Ndula Dispensary</option> <option value="20129">Nduluku Dispensary</option> <option value="19902">Nduluni Dispensary</option> <option value="20111">Ndumbi Dispensary</option> <option value="18462">Ndumoni Dispensary</option> <option value="16922">Ndunduni Dispensary</option> <option value="18958">Ndunguni Dispensary</option> <option value="10839">Ndunyu Chege Dispensary</option> <option value="10840">Ndunyu Njeru Dispensary</option> <option value="19326">Nduri-Sarma Dispensary</option> <option value="10841">Nduriri (AIC) Dispensary</option> <option value="13847">Nduru District Hospital</option> <option value="13848">Nduru Kadero Dispensary</option> <option value="15328">Ndurumo Dispensary</option> <option value="10842">Ndururumo Dispensary</option> <option value="16923">Nduu Dispensary</option> <option value="17814">Nduu Ndune Dispensary</option> <option value="12639">Nduva Na Mwene Medical Clinic</option> <option value="16937">Nduvani Dispensary</option> <option value="16812">Neboi Dispensary</option> <option value="12640">Neema (Midus) Medical Clinic</option> <option value="19132">Neema Afya Centre</option> <option value="20147">Neema Highway Medical Home</option> <option value="12641">Neema Hospital</option> <option value="18061">Neema Hospital (Ruiru)</option> <option value="10843">Neema Medical</option> <option value="17330">Neema Medical Clinic</option> <option value="19161">Neema Medical Clinic (Kibera)</option> <option value="18900">Neema Medical Clinic (Kitui Central)</option> <option value="11707">Neema Medical Clinic (Malindi)</option> <option value="17992">Neema Medical Clinic (Muranga North)</option> <option value="15330">Neema Medical Clinic (Nakuru North)</option> <option value="15329">Neema Medical Clinic (Trans Nzoia West)</option> <option value="18192">Neema Medical Clinic Kitengela</option> <option value="10844">Neema Medicare Centre</option> <option value="16618">Nehema Medical Clinic</option> <option value="16619">Nehema Medical Lab</option> <option value="18130">Nehemah Clinic</option> <option value="18338">Nehemiah International Dispensary</option> <option value="15331">Neissuit Dispensary</option> <option value="15332">Nekeki Clinic (Hbc)</option> <option value="16850">Neki Medical Clinic</option> <option value="17745">Nembu Med</option> <option value="16804">Nembu Medical Clinic</option> <option value="12642">Nembure Health Centre</option> <option value="10847">Neno Clinic</option> <option value="19776">Neno Optical</option> <option value="18403">Nep Medical Centre</option> <option value="15333">Nerkwo Dispensary</option> <option value="18919">Network Integrated Communication Empowerment Medic</option> <option value="19077">New Age VCT</option> <option value="16620">New Avenue Medical Clinic</option> <option value="16080">New Busia Maternity & Nursing Home</option> <option value="19592">New Canaan Idp Dispensary</option> <option value="17698">New Chaani Healthcare Clinic & Laboratory</option> <option value="18734">New Generation Clinic</option> <option value="18792">New Hope Clinic (Nyamira)</option> <option value="18254">New Hope Community Centre</option> <option value="16751">New Hope Medical Clinic</option> <option value="17952">New Hope VCT</option> <option value="11428">New Jamin Medical Clinic</option> <option value="10849">New Kihoya Clinic</option> <option value="13120">New Life Home Childrens Home (Westlands)</option> <option value="15334">New Life Mission Rotary Clinic</option> <option value="10850">New Line Laboratory</option> <option value="10851">New Mawingu Dispensary</option> <option value="17691">New Mbita Clinic</option> <option value="16209">New Moon Medical Clinic</option> <option value="18311">New Mtongwe Medical Clinic</option> <option value="18325">New Mwema Medical Clinic</option> <option value="12643">New Ngei Road Nursing Home</option> <option value="11709">New Nyali Paeds Hospital</option> <option value="18218">New Partner Initiative (Npi) Sasa Centre</option> <option value="18007">New Partners Initiative Scaling Up HIV and AIDS Pr</option> <option value="19509">New Riruta Medical Clinic</option> <option value="11710">New Road Medical Care</option> <option value="16621">New Southlands Laboratory</option> <option value="16622">New Southlands Med Clinic</option> <option value="19158">New Southlands X-Ray Services</option> <option value="10852">New Tumaini Dispensary</option> <option value="17097">Ng'endalel Dispensary</option> <option value="16274">Ng'imalo Dispensary</option> <option value="13852">Ng'iya Health Centre</option> <option value="18076">Ng'odhe Dispensary (Main Land)</option> <option value="13854">Ng'odhe Island Dispensary</option> <option value="11714">Ng'ombeni Dispensary</option> <option value="12644">Ngai Dispensary</option> <option value="15335">Ngai Murunya Health Service</option> <option value="16861">Ngaie Dispensary</option> <option value="13121">Ngaira Rhodes Dispensary</option> <option value="16081">Ngalasia Dispensary</option> <option value="10853">Ngamba Dispensary</option> <option value="15336">Ngambo Dispensary</option> <option value="18473">Ngamwa Dispensary</option> <option value="10854">Ngamwa Medical Laboratory</option> <option value="15337">Nganayio Dispensary</option> <option value="10855">Ngandu Catholic Dispensary</option> <option value="12645">Nganduri Dispensary</option> <option value="12646">Ngangani Dispensary</option> <option value="10856">Ngano Health Centre</option> <option value="11711">Ngao District Hospital</option> <option value="13122">Ngara Health Centre (City Council of Nairobi)</option> <option value="10857">Ngararia Dispensary</option> <option value="10859">Ngarariga Health Centre</option> <option value="12647">Ngaremara Dispensary</option> <option value="17226">Ngarendare Dispensary</option> <option value="15338">Ngarua Catholic Dispensary</option> <option value="15339">Ngarua Health Centre</option> <option value="15340">Ngatataek Dispensary</option> <option value="15341">Ngatha Nursing</option> <option value="11712">Ngathini Dispensary</option> <option value="18284">Ngatu CDF</option> <option value="17454">Ngecha (PCEA) Health Centre</option> <option value="17244">Ngecha Health Centre</option> <option value="10862">Ngecha Orthodox Dispensary</option> <option value="15342">Ngechek Dispensary</option> <option value="13849">Ngegu Dispensary</option> <option value="12648">Ngelani (AIC) Dispensary</option> <option value="18686">Ngelani Dispensary</option> <option value="20181">Ngelechom Community Dispensary</option> <option value="17829">Ngelel Tarit Dispensary</option> <option value="10863">Ngelelya Dispensary</option> <option value="10864">Ngenda Health Centre</option> <option value="15343">Ngendalel Dispensary</option> <option value="18604">Ngenia Dispensary</option> <option value="17641">Ngenybogurio Dispensary</option> <option value="15344">Ngenyilel Dispensary</option> <option value="13850">Ngere Dispensary</option> <option value="11713">Ngerenya Dispensary</option> <option value="17711">Ngeri Dispensary</option> <option value="15345">Ngeria South Dispensary</option> <option value="12649">Ngeru Dispensary</option> <option value="20168">Ngeta Dispensary</option> <option value="12650">Ngetani Dispensary</option> <option value="17122">Ngeteti Community Health Dispensary</option> <option value="15346">Ngetmoi Dispensary</option> <option value="10865">Ngewa Health Centre</option> <option value="18500">Ngieni Community Dispensary</option> <option value="18252">Ngiini Dispensary</option> <option value="20166">Ngiini Dispensary Kathiani</option> <option value="18360">Ngiitakito Dispensary</option> <option value="14459">Ngilai Dispensary</option> <option value="12651">Ngiluni Dispensary</option> <option value="12652">Ngiluni Dispensary (Kitui)</option> <option value="16935">Ngiluni Dispensary (Mwingi)</option> <option value="15347">Nginyang Health Centre</option> <option value="10868">Ngiriambu (ACK) Dispensary</option> <option value="13851">Ngisiru Dispensary</option> <option value="15348">Ngito Dispensary</option> <option value="17052">Ngo'nga Dispensary</option> <option value="15349">Ngobit Dispensary</option> <option value="13853">Ngodhe Dispensary</option> <option value="12653">Ngoleni Dispensary</option> <option value="10869">Ngoliba Health Centre</option> <option value="11715">Ngomeni Dispensary (Malindi)</option> <option value="12654">Ngomeni Health Centre</option> <option value="18510">Ngomoni Dispensary</option> <option value="16382">Ngondi Dispensary</option> <option value="18131">Ngondu Medical Clinic</option> <option value="15350">Ngong Hills Hospital</option> <option value="19060">Ngong Medicare Clinic</option> <option value="18238">Ngong Rapha Hospital</option> <option value="13123">Ngong Road Health Centre</option> <option value="15351">Ngong Sub-District Hospital</option> <option value="18849">Ngongo Dispensary</option> <option value="16864">Ngongoni Dispensary (Kyuso)</option> <option value="12655">Ngongoni Dispensary (Mwingi)</option> <option value="10870">Ngorano Health Centre</option> <option value="10871">Ngorika Dispensary</option> <option value="15352">Ngoron Dispensary</option> <option value="10872">Ngorongo Health Centre</option> <option value="17752">Ngosuani Dispensary</option> <option value="17558">Ngothi Mc</option> <option value="15353">Ngubereti Health Centre</option> <option value="17526">Nguge Dispensary</option> <option value="10873">Nguka Dispensary</option> <option value="13855">Nguku Dispensary</option> <option value="12656">Ngulini Dispensary</option> <option value="12657">Nguluni Health Centre</option> <option value="19236">Ngumba Medical Centre</option> <option value="19415">Ngumbulu Dispensary</option> <option value="12658">Nguni Health Centre</option> <option value="19829">Ngurubani Medical Services</option> <option value="12659">Nguruki-Iruma Dispensary</option> <option value="16819">Ngurumo Dispensary</option> <option value="19658">Ngurumo Medical Clinic</option> <option value="15354">Ngurunga Dispensary</option> <option value="12660">Ngurunit Dispensary</option> <option value="10874">Ngurweini Dispensary</option> <option value="10875">Nguthuru Dispensary</option> <option value="15355">Ngutuk-Engiron Dispensary</option> <option value="12661">Nguuku Dispensary</option> <option value="12662">Nguungani Dispensary</option> <option value="16858">Nguuni Dispensary</option> <option value="11716">Nguuni Health Centre</option> <option value="19226">Nguviu Boys High School Clinic</option> <option value="12663">Ngwata Health Centre</option> <option value="16712">Ngwelo Dispensary</option> <option value="10876">Nhera Clinic</option> <option value="16623">Nica Kaunjira Dispensary</option> <option value="13856">Nightingale Medical Centre</option> <option value="19479">Nile Medical Care</option> <option value="17804">Nile Medical Clinic</option> <option value="13125">Nimoli Medical Centre</option> <option value="19759">Ninami Medical Clinic</option> <option value="17357">Ningaini Dispensary</option> <option value="18798">Nist Dispensary</option> <option value="10878">Njabini Health Centre</option> <option value="10877">Njabini Maternity and Nursing Home</option> <option value="10879">Njambi Nursing Home</option> <option value="17560">Njambini Catholic Dispensary</option> <option value="18966">Njambu Clinic</option> <option value="10880">Njegas Dispensary</option> <option value="10881">Njemuka Clinic</option> <option value="17458">Njemuka Medical Clinic</option> <option value="17367">Njeruri Dispensary</option> <option value="17513">Njete Medical Clinic</option> <option value="10882">Njika Wega Medical Clinic</option> <option value="15356">Njipiship Dispensary</option> <option value="13126">Njiru Dispensary</option> <option value="10883">Njoguini Dispensary</option> <option value="10884">Njoki Dispensary</option> <option value="15357">Njoro (PCEA) Dispensary</option> <option value="15358">Njoro Health Centre</option> <option value="10885">Njukini Clinic</option> <option value="15359">Njukini Dispensary</option> <option value="11718">Njukini Health Centre</option> <option value="18306">Njuruta Dispensary</option> <option value="16835">Njuthine Dispensary</option> <option value="12664">Nkabune Dispensary</option> <option value="15361">Nkama Dispensary</option> <option value="18972">Nkama Medical Clinic</option> <option value="17227">Nkando Dispensary</option> <option value="15362">Nkararo Health Centre</option> <option value="15363">Nkareta Dispensary</option> <option value="19942">Nkaroni Dispensary</option> <option value="12231">Nkathiari Dispensary</option> <option value="19186">Nkirina Medical Clinic</option> <option value="12665">Nkondi Dispensary</option> <option value="15364">Nkorinkori Dispensary</option> <option value="15365">Nku West Health Centre</option> <option value="12666">Nkubu Dispensary</option> <option value="12667">Nkubu Medical Clinic</option> <option value="16841">Nkuene (ACK) Dispensary</option> <option value="16231">Nkunjumu Dispensary</option> <option value="18030">Nkutuk Elmuget Dispensary</option> <option value="17785">Nkutuk Elmuget Dispensary (Duplicate)</option> <option value="10886">No 4 Community Health Clinic</option> <option value="18156">Noble Medical Clinic</option> <option value="18960">Nogoi Medical Clinic</option> <option value="15366">Nolasit Dispensary</option> <option value="17467">Nopri Medical Centre</option> <option value="19749">Norident Dental Clinic Kitale</option> <option value="12668">North Horr Health Centre</option> <option value="10887">North Kinangop Catholic Hospital</option> <option value="17511">North Star Alliance Clinic</option> <option value="18599">North Star Alliance VCT</option> <option value="19206">North Star Alliance Wellness Centre</option> <option value="16301">Northern Medical Clinic</option> <option value="19123">Northstar Alliance Wellness Centre (Mai Mahiu)</option> <option value="13127">Nsis Health Centre (Ruaraka)</option> <option value="12670">Ntemwene Dispensary</option> <option value="12671">Ntemwene Medical Clinic</option> <option value="12672">Ntha Clinic</option> <option value="12673">Nthagaiya Catholic Dispensary</option> <option value="12674">Nthambiro Catholic Dispensary</option> <option value="12675">Nthambiro Dispensary</option> <option value="16954">Nthangu Dispensary</option> <option value="12669">Ntharene Medical Clinic</option> <option value="16955">Nthimbani Dispensary</option> <option value="12676">Nthongoni Dispensary (Kibwezi)</option> <option value="12677">Nthongoni Dispensary (Kitui)</option> <option value="17213">Nthungululu Dispensary</option> <option value="12678">Nthwanguu Dispensary</option> <option value="16624">Ntima Medical Clinic</option> <option value="13857">Ntimaru Clinic</option> <option value="13858">Ntimaru Sub-District Hospital</option> <option value="12679">Ntonyiri Health Services</option> <option value="15367">Ntulele Dispensary</option> <option value="20198">Ntunyigi Medical Clinic</option> <option value="15368">Nturukuma Dispensary</option> <option value="15369">Nturumeti Dispensary</option> <option value="13128">Nuffield Nursing Home</option> <option value="18159">Nunguni Medical Clinic</option> <option value="19172">Nureyn Medical and Lab Services</option> <option value="11719">Nuru Health Care Centre</option> <option value="17955">Nuru Lutheran Media Ministry</option> <option value="12680">Nuu Catholic Dispensary</option> <option value="12681">Nuu Sub-District Hospital</option> <option value="12682">Nyaani Dispensary</option> <option value="17137">Nyabangi Dispensary</option> <option value="13859">Nyabikaye Dispensary</option> <option value="13860">Nyabikomu Dispensary</option> <option value="16880">Nyabiosi Dispensary</option> <option value="16423">Nyabioto Dispensary</option> <option value="13861">Nyabite Clinic</option> <option value="13862">Nyabokarange Dispensary</option> <option value="18865">Nyabola CDF Dispensary</option> <option value="13863">Nyabola Dispensary</option> <option value="13864">Nyabondo Mission Hospital</option> <option value="18867">Nyabondo Rehabilitation Centre</option> <option value="13865">Nyaburi Clinic</option> <option value="13866">Nyabururu Dispensary</option> <option value="11720">Nyache Health Centre</option> <option value="13867">Nyacheki Sub-District Hospital</option> <option value="13868">Nyachenge Dispensary</option> <option value="13869">Nyachogochogo Dispensary</option> <option value="13870">Nyadenda Health Centre</option> <option value="17535">Nyadhi Dispensary</option> <option value="16266">Nyagancha Dispensary</option> <option value="12683">Nyagani Dispensary</option> <option value="16856">Nyagari Dispensary (CDF)</option> <option value="17536">Nyagem Dispensary</option> <option value="13871">Nyagesenda Dispensary</option> <option value="16881">Nyagichenche (SDA) Dispensary</option> <option value="13872">Nyagiki Dispensary</option> <option value="10888">Nyagiti Dispensary</option> <option value="13874">Nyagoko Dispensary</option> <option value="13875">Nyagoro Health Centre</option> <option value="13876">Nyagoto Dispensary</option> <option value="13873">Nyagowa Elck Dispensary</option> <option value="13877">Nyaguda Dispensary</option> <option value="13878">Nyaguta Dispensary</option> <option value="13879">Nyagwethe Dispensary</option> <option value="13880">Nyahera Sub District Hospital</option> <option value="10889">Nyahururu Catholic Dispensary</option> <option value="10890">Nyahururu District Hospital</option> <option value="10891">Nyahururu Private Hospital</option> <option value="20142">Nyaiguta Dispensary</option> <option value="16666">Nyaitara Dispensary</option> <option value="13881">Nyakach (AIC) Dispensary</option> <option value="10892">Nyakahuho Dispensary</option> <option value="13882">Nyakegogi Dispensary</option> <option value="15370">Nyakiambi Dispensary</option> <option value="10893">Nyakianga Health Centre</option> <option value="13884">Nyakongo Dispensary</option> <option value="13885">Nyakuru Dispensary</option> <option value="16275">Nyakurungoto Dispensary</option> <option value="16732">Nyakwala Dispensary</option> <option value="13886">Nyakwana Dispensary</option> <option value="18420">Nyakweri Dispensary</option> <option value="19499">Nyalego Medical Clinic</option> <option value="13887">Nyalenda Health Centre</option> <option value="13888">Nyalenda Nursing Home</option> <option value="13889">Nyalgosi Dispensary</option> <option value="11722">Nyali Barracks Dispensary</option> <option value="16543">Nyali Children Hospital</option> <option value="19065">Nyali Childrens Hospital</option> <option value="15371">Nyalilbuch Dispensary</option> <option value="16986">Nyalkinyi (Jersey) Dispensary</option> <option value="13890">Nyalunya Dispensary</option> <option value="13891">Nyamache District Hospital</option> <option value="16265">Nyamagesa Dispensary</option> <option value="16878">Nyamagiri Dispensary</option> <option value="13892">Nyamagundo Health Centre</option> <option value="13893">Nyamagwa Health Centre</option> <option value="13894">Nyamaiya Health Centre</option> <option value="13895">Nyamakoroto Dispensary</option> <option value="15372">Nyamamithi Dispensary</option> <option value="13896">Nyamanga Dispensary</option> <option value="13897">Nyamaraga Health Centre</option> <option value="13898">Nyamaranya Dispensary</option> <option value="13899">Nyamarimba Dispensary</option> <option value="13900">Nyamasare Dispensary</option> <option value="13901">Nyamasege Dispensary</option> <option value="13902">Nyamasi Dispensary</option> <option value="13903">Nyamasibi Health Centre</option> <option value="15373">Nyamathi Dispensary</option> <option value="18295">Nyamatwoni Dispensary</option> <option value="19867">Nyambare Dispensary</option> <option value="13904">Nyambare Health Centre</option> <option value="13905">Nyambari Geke Dispensary</option> <option value="12684">Nyambene District Hospital</option> <option value="18925">Nyambene Medical & Surgical Centre</option> <option value="12685">Nyambene Nursing Home</option> <option value="13906">Nyambunwa Medical Clinic</option> <option value="13907">Nyamekongoroto Health Centre</option> <option value="13908">Nyamemiso Dispensary</option> <option value="13909">Nyametaburo Health Centre</option> <option value="13910">Nyametembe Dispensary</option> <option value="13911">Nyamira Adventist Health Centre</option> <option value="13912">Nyamira District Hospital</option> <option value="13913">Nyamira Maternity and Nursing Home</option> <option value="18342">Nyamira Royal Clinic</option> <option value="13983">Nyamogonchoro Dispensary</option> <option value="20133">Nyamokenye Health Centre(Sameta)</option> <option value="13914">Nyamonye Mission Dispensary</option> <option value="13915">Nyamrisra Health Centre</option> <option value="13916">Nyamusi Sub-District Hospital</option> <option value="13917">Nyanchonori Dispensary</option> <option value="13918">Nyanchwa Dispensary</option> <option value="13919">Nyandago Koweru Dispensary</option> <option value="16877">Nyandiwa Baptist Dispensary</option> <option value="13920">Nyandiwa Dispensary</option> <option value="13921">Nyando District Hospital</option> <option value="13922">Nyandoche Ibere Dispensary</option> <option value="17264">Nyanduma Dispensary</option> <option value="18786">Nyandusi</option> <option value="13928">Nyang'oma Health Centre</option> <option value="13929">Nyang'oma Mission Health Centre</option> <option value="16082">Nyang'ori Health Centre</option> <option value="20172">Nyangajo Dispensary</option> <option value="13923">Nyangande Dispensary</option> <option value="13925">Nyangena Hospital</option> <option value="13924">Nyangena Sub District Hospital (Manga)</option> <option value="13926">Nyangiela Dispensary</option> <option value="17832">Nyangiti Health Centre</option> <option value="17646">Nyango Medical Clinic</option> <option value="13927">Nyangoge Health Centre</option> <option value="13930">Nyangu Dispensary</option> <option value="16988">Nyangweta Health Centre</option> <option value="13931">Nyanko Dispensary</option> <option value="13932">Nyankono Dispensary</option> <option value="16990">Nyansabakwa Health Centre</option> <option value="13933">Nyansakia Health Centre</option> <option value="13934">Nyansancha Dispensary</option> <option value="13935">Nyansangio Dispensary</option> <option value="13937">Nyansiongo Nursing Home</option> <option value="13938">Nyansira Dispensary</option> <option value="18446">Nyanturago Health Centre</option> <option value="13939">Nyanza Provincial General Hospital (PGH)</option> <option value="16876">Nyaoga Community Dispensary</option> <option value="17714">Nyaore Dispensary</option> <option value="17082">Nyaporo Dispensary</option> <option value="18862">Nyara Tea Estate Dispensary</option> <option value="17738">Nyarami VCT</option> <option value="10894">Nyaribo Dispensary</option> <option value="13940">Nyarongi Dispensary</option> <option value="16083">Nyarotis Clinic</option> <option value="15374">Nyaru Dispensary</option> <option value="19860">Nyarut Health Centre</option> <option value="13941">Nyasese Dispensary</option> <option value="13942">Nyasike Dispensary</option> <option value="20075">Nyasoko Dispensary</option> <option value="13943">Nyasore Dispensary</option> <option value="13944">Nyathengo Dispensary</option> <option value="10895">Nyathuna Sub District Hospital</option> <option value="13945">Nyatike Health Centre</option> <option value="13946">Nyatoto Health Centre</option> <option value="16735">Nyaunyau Dispensary</option> <option value="18051">Nyawango Dispensary</option> <option value="13947">Nyawara Health Centre</option> <option value="19863">Nyawawa Dispensary</option> <option value="18225">Nyaweri Deaf VCT</option> <option value="19864">Nyawita Dispensary</option> <option value="20038">Nyayiera Dispensary</option> <option value="13948">Nyenye Misori Dispensary</option> <option value="10896">Nyeri (Islamic Foundation) Clinic</option> <option value="10897">Nyeri Dental Clinic</option> <option value="19773">Nyeri Endoscopy & Surgicare Centre</option> <option value="19768">Nyeri Good Shepherd Primary Clinic</option> <option value="10898">Nyeri Health Care X Ray Clinic</option> <option value="10899">Nyeri High School Clinic</option> <option value="19767">Nyeri High School Dispensary</option> <option value="17002">Nyeri Hill (PCEA) Dispensary</option> <option value="10900">Nyeri Hospice</option> <option value="10901">Nyeri Medical Clinic</option> <option value="19784">Nyeri Primary School Dispensary</option> <option value="10903">Nyeri Provincial General Hospital (PGH)</option> <option value="10904">Nyeri Surgical Care Centre</option> <option value="19763">Nyeri Technical Dispensary</option> <option value="10905">Nyeri Town Health Centre</option> <option value="10906">Nyeri Youth Heath Centre (Family Health Options Ke</option> <option value="18052">Nyikendo Medical Clinic</option> <option value="17349">Nyimbei Dispensary</option> <option value="13129">Nyina Wa Mumbi Dispensary</option> <option value="18523">Nyongores Dispensary</option> <option value="15375">Nyonjoro Maternity Home</option> <option value="15376">Nyonjoro Medical Clinic (Nakuru)</option> <option value="19191">Nyota Njema Medical Clinic</option> <option value="10816">Nys (National Youth Service) Dispensary Yatta</option> <option value="15377">Nys Dispensary (Gilgil)</option> <option value="15378">Nys Dispensary (Keiyo)</option> <option value="11723">Nys Dispensary (Kilindini)</option> <option value="15379">Nys Dispensary (Kirimun)</option> <option value="12686">Nys Dispensary (Mavoloni)</option> <option value="13949">Nys Dispensary (Suba)</option> <option value="15380">Nys Karate Dispensary</option> <option value="13131">Nyumbani Diagnostic Laboratory and Medical Clinic</option> <option value="18199">Nyumbani Village Catholic Dispensary</option> <option value="12687">Nzaini Dispensary</option> <option value="16992">Nzangathi Dispensary</option> <option value="12689">Nzatani Dispensary (Mwingi)</option> <option value="16929">Nzauni Dispensary</option> <option value="12690">Nzawa Health Centre</option> <option value="12691">Nzeluni Health Centre</option> <option value="12692">Nzeveni Dispensary</option> <option value="18566">Nzinia Dispensary</option> <option value="12693">Nziu Health Centre</option> <option value="16084">Nzoia (ACK) Dispensary</option> <option value="15381">Nzoia Dispensary (Trans Nzoia East)</option> <option value="16086">Nzoia Matete Dispensary</option> <option value="18111">Nzoia Medical Centre</option> <option value="16085">Nzoia Sugar Dispensary</option> <option value="12694">Nzoila Dispensary</option> <option value="19626">Nzukini Dispensary</option> <option value="12695">Nzunguni Dispensary</option> <option value="10907">Oaklands Estate Dispensary</option> <option value="16212">Oasis Diagnostic Laboratory</option> <option value="20051">Oasis Doctors Plaza Medical Centre</option> <option value="18436">Oasis Medical Clinic</option> <option value="17991">Oasis Mission Hospital</option> <option value="13950">Obalwanda Dispensary</option> <option value="13951">Obanga Health Centre</option> <option value="16087">Obekai Dispensary</option> <option value="13953">Ober Health Centre</option> <option value="13952">Ober Kabuoch Dispensary</option> <option value="13954">Ober Kamoth Health Centre</option> <option value="10908">Obeys Medical Clinic</option> <option value="13955">Oboch Dispensary</option> <option value="13956">Obumba Dispensary</option> <option value="13957">Obunga Dispensary</option> <option value="19866">Obuya Dispensary</option> <option value="13958">Obwanda Dispensary</option> <option value="20085">Ocean Breeze Medical Facilty</option> <option value="15382">Ochii Dispensary</option> <option value="16420">Ochude Dispensary</option> <option value="13959">Ochuna Dispensary</option> <option value="11725">Oda Dispensary</option> <option value="12698">Odda Dispensary (Moyale)</option> <option value="19492">Odeon Medical Centre (Nairobi)</option> <option value="17515">Oding Dispensary</option> <option value="13132">ofafa I Clinic</option> <option value="13960">Ogada Dispensary</option> <option value="13961">Ogam Dispensary</option> <option value="13962">Ogande Dispensary</option> <option value="18078">Ogando Dispensary</option> <option value="13963">Ogango Dispensary</option> <option value="13964">Ogango Health Centre</option> <option value="16257">Ogembo Medical Clinic</option> <option value="13965">Ogen Dispensary</option> <option value="13966">Ogero Dispensary</option> <option value="15383">Ogirgir Tea Dispensary</option> <option value="13967">Ogongo Sub-District Hospital</option> <option value="13416">Ogorji Dispensary</option> <option value="13968">Ogra Health Centre</option> <option value="13133">Ogwedhi Dispensary (Nairobi North)</option> <option value="13969">Ogwedhi Health Centre</option> <option value="16276">Ogwedhi Sigawa Dispensary</option> <option value="13970">Ojele Memorial Hospital</option> <option value="16088">Ojm Medical Clinic</option> <option value="13971">Ojola Dispensary</option> <option value="20152">Ojwando Dispensary</option> <option value="13972">Okiki Amayo Health Centre</option> <option value="15385">Okilgei Dispensary</option> <option value="13973">Okitta Maternity Nursing Home</option> <option value="16259">Okok Dispensary</option> <option value="17245">Okook Dispensary</option> <option value="10909">Ol Jabet Medical Clinic</option> <option value="10910">Ol Jororok Medical Clinic</option> <option value="15386">Ol-Arabel Dispensary</option> <option value="15406">Ol-Jorai Dispensary</option> <option value="15413">Ol-Malaika Health Centre</option> <option value="15407">Ol-Njorowa Flower Farm Medical Clinic</option> <option value="15432">Ol-Rongai Dispensary (Rongai)</option> <option value="12699">Ol-Torot Dispensary</option> <option value="13974">Olando Dispensary</option> <option value="13975">Olasi Dispensary</option> <option value="13976">Olasi Dispensary (Nyando)</option> <option value="15387">Olasiti (AIC) Dispensary</option> <option value="10911">Olborosat Dispensary</option> <option value="15388">Olbutyo Health Centre</option> <option value="17802">Olchekut Community Based Clinic</option> <option value="16328">Olchobosei Clinic</option> <option value="17811">Olchorro Dispensary (Loitokitok)</option> <option value="15389">Olchorro Health Centre</option> <option value="10912">Old Mawingu Health Centre</option> <option value="15390">Oldanyati Health Centre</option> <option value="17090">Oldebes Dispensary</option> <option value="15391">Oldepesi Dispensary</option> <option value="15392">Olderkesi Dispensary</option> <option value="17671">Oldoinyo Oibor Dispensary</option> <option value="12697">Oldonyiro Dispensary (Isiolo)</option> <option value="15393">Oldonyo Nyokie Dispensary</option> <option value="15394">Oldonyorok (Cog) Dispensary</option> <option value="15395">Oldorko Dispensary</option> <option value="16383">Olemila Stand Alone VCT</option> <option value="15396">Olemila VCT Centre</option> <option value="15397">Olendeem Dispensary</option> <option value="15398">Olenguruone Sub-District Hospital</option> <option value="16330">Olenkasurai Dispensary</option> <option value="15399">Olepolos Dispensary</option> <option value="19268">Olepolos Medical Clinic</option> <option value="15400">Olereko Dispensary</option> <option value="19738">Olesere Dispensary</option> <option value="15401">Oletukat Dispensary</option> <option value="15402">Olgulului Health Centre</option> <option value="15403">Olgumi Dispensary</option> <option value="19811">Olifras Medical Clinic</option> <option value="17675">Olive Health Care International</option> <option value="16509">Olive Health Care/Laboratory</option> <option value="18797">Olive Link Health Care</option> <option value="18196">Olive Medical Clinic Kitengela</option> <option value="15404">Oljabet Health Centre</option> <option value="17428">Oljabet Medical Clinic</option> <option value="15405">Oljogi Dispensary</option> <option value="10914">Oljororok Catholic Dispensary</option> <option value="17786">Oljorre Dispensary</option> <option value="10915">Olkalou (ACK) Dispensary</option> <option value="10916">Olkalou Sub-District Hospital</option> <option value="15408">Olkinyei Dispensary</option> <option value="15409">Olkiramatian Dispensary</option> <option value="15410">Olkokwe Health Centre</option> <option value="15411">Olkoroi Dispensary</option> <option value="12696">Oll Mwea Hospital Clinic Embu (Satelite)</option> <option value="15412">Ollessos Holy Family Dispensary</option> <option value="13414">Ollo Health Centre</option> <option value="15414">Olmekenyu Dispensary</option> <option value="15415">Olmesutie Dispensary</option> <option value="15416">Olmoran Catholic Dispensary</option> <option value="15417">Olmoran Health Centre</option> <option value="16429">Olnarau Dispensary (CDF)</option> <option value="18257">Oloibon Medical Centre</option> <option value="15418">Oloika Dispensary</option> <option value="19267">Oloimirmir Dispensary</option> <option value="15419">Oloiyangalani Dispensary</option> <option value="15420">Olokurto Health Centre</option> <option value="15421">Olokyin Health Centre</option> <option value="16690">Ololchani Dispensary</option> <option value="15422">Ololpironito Health Centre</option> <option value="15423">Ololulunga District Hospital</option> <option value="19910">Ololulunga VCT</option> <option value="15424">Olooltepes Dispensary</option> <option value="17805">Olooltoto Dispensary</option> <option value="18087">Oloolua Dispensary</option> <option value="15425">Olooseos Dispensary</option> <option value="17867">Oloosirkon Disp</option> <option value="18088">Oloosirkon Dispensary</option> <option value="15426">Olorika Dispensary</option> <option value="17552">Oloropil Dispensary</option> <option value="15428">Olorte Dispensary</option> <option value="15429">Olosho-Oibor Dispensary</option> <option value="17798">Oloshoibor Dispensary</option> <option value="15430">Olpajeta Dispensary</option> <option value="15431">Olposimoru Dispensary</option> <option value="13977">Olps Clinic</option> <option value="15434">Oltepesi Dispensary</option> <option value="15433">Oltepesi Health Clinic</option> <option value="15435">Oltiasika Dispensary</option> <option value="15436">Oltukai Lodge Clinic</option> <option value="19080">Oltukai Medical Clinic</option> <option value="18511">Olturoto Dispensary</option> <option value="11727">Om Dental Centre</option> <option value="13978">Ombek Dispensary</option> <option value="17607">Ombo Bita Dispensary</option> <option value="13979">Ombo Kachieng' Dispensary</option> <option value="17039">Ombo Kowiti Dispensary</option> <option value="13980">Omboga Dispensary</option> <option value="13981">Omiro Dispensary</option> <option value="13982">Omobera Dispensary</option> <option value="13984">Omogwa Dispensary</option> <option value="13985">Omorembe Health Centre (Gucha)</option> <option value="13986">Omosaria Dispensary</option> <option value="18772">Omosocho Medical Clinic (Manga)</option> <option value="16264">Omwabo Medical Clinic</option> <option value="16277">Ondong Dispensary</option> <option value="17735">Ondong Dispensary</option> <option value="16985">Oneno Dispensary</option> <option value="18892">Ong'amo Dispensary</option> <option value="13987">Ong'ielo Health Centre</option> <option value="19094">Ongata Comprehensive Medical Centre</option> <option value="15437">Ongata Dispensary</option> <option value="15438">Ongata Medical Clinic</option> <option value="15439">Ongata Naado Dispensary</option> <option value="15440">Ongata Rongai Health Centre</option> <option value="19091">Ongata Rongai X-Ray Services</option> <option value="15441">Ongatta Cottage Medical Clinic</option> <option value="13988">Ongito Dispensary</option> <option value="13989">Ongo Health Centre</option> <option value="12700">Ontulili Dispensary</option> <option value="17173">Onyinjo Dispensary</option> <option value="13990">Opapla Dispensary</option> <option value="16973">Openda Dispensary</option> <option value="15442">Opiroi Dispensary</option> <option value="19785">Optica Clinic Nyeri</option> <option value="16626">Optician Clinic</option> <option value="18870">Optimum Care Medical</option> <option value="13415">Orahey Medical Clinic</option> <option value="18800">Oren Health Centre</option> <option value="13991">Oresi Health Centre</option> <option value="16284">Oriang (SDA) Health Centre</option> <option value="18422">Oriang Kanyadwera Dispensary</option> <option value="17587">Oriang VCT</option> <option value="18086">Oriang' Alwala Dispensary</option> <option value="16767">Oridi Dispensary</option> <option value="19465">Orient Medical Care</option> <option value="15443">Orinie (AIC) Clinic</option> <option value="17800">Orinie (AIC) Dispensary</option> <option value="13992">Oroche Dispensary</option> <option value="16370">Orolwo Dispensary</option> <option value="15444">Oromodei Dispensary</option> <option value="17412">Orongo Dispensary</option> <option value="15445">Oropoi Dispensary</option> <option value="13135">Orthodox Dispensary</option> <option value="17395">Orthodox Maternity and Health Centre</option> <option value="19014">Ortum Central Clinic</option> <option value="15446">Ortum Hospital</option> <option value="13993">Oruba Nursing and Maternity Home</option> <option value="19638">Orwa Clinic</option> <option value="13994">Orwaki Dispensary</option> <option value="17726">Osani Community Dispensary</option> <option value="13995">Osano Nursing Home</option> <option value="17776">Osarara Dispensary</option> <option value="15447">Oserian Health Centre</option> <option value="20069">Osewre Dispensary</option> <option value="17680">Osieko Dispensary</option> <option value="13996">Osingo Dispensary</option> <option value="15448">Osinoni Dispensary</option> <option value="13997">Osogo Dispensary</option> <option value="15449">Osorongai Dispensary</option> <option value="15450">Osotua Medical Clinic</option> <option value="15451">Osupuko Dispensary</option> <option value="13998">Otacho Dispensary</option> <option value="18877">Otange Dispensary</option> <option value="13999">Otati Dispensary</option> <option value="14000">Othach Dispensary</option> <option value="10918">Othaya Approved Dispensary</option> <option value="10919">Othaya Catholic Dispensary</option> <option value="16777">Othaya Dental Clinic</option> <option value="10920">Othaya Medical Clinic</option> <option value="10921">Othaya Medical Services Clinic</option> <option value="10922">Othaya Sub-District Hospital</option> <option value="14001">Othoch Rakuom Dispensary</option> <option value="14002">Othoro Health Centre (Rachuonyo)</option> <option value="14003">Othoro Sub District Hospital</option> <option value="20024">Otieno Owala Dispensary</option> <option value="10923">Our Choice Medical Clinic</option> <option value="15452">Our Lady of Lords Dispensary</option> <option value="14004">Our Lady of Lourdes Dispensary (Gucha)</option> <option value="16384">Our Lady of Mercy (Magumu)</option> <option value="18093">Our Lady of Perpetual Sisters VCT (Bondo)</option> <option value="17296">Our Lady's Hospice</option> <option value="10924">Outspan Hospital</option> <option value="14005">Ouya Dispensary</option> <option value="14006">Owens Nursing Home</option> <option value="14007">Oyamo Dispensary</option> <option value="14008">Oyani (SDA) Dispensary</option> <option value="14009">Oyani Health Centre</option> <option value="17852">Oyuma Dispensary (Rachuonyo)</option> <option value="11728">Ozi Dispensary</option> <option value="13136">P & T Clinic</option> <option value="15454">P O M Dipensary</option> <option value="11729">Pablo Hortsman Health Centre</option> <option value="10925">Pacco Ebenezer Medical Clinic</option> <option value="18318">Pacific Medical Clinic</option> <option value="13137">Padens Medicare Centre</option> <option value="10926">Paed Afya Clinic</option> <option value="17795">Pakase Dispensary</option> <option value="15455">Pakase Medical Clinic</option> <option value="16430">Pakasse Dispensary</option> <option value="17136">Pakeza Medical Clinic (Manga)</option> <option value="14011">Pala Health Centre</option> <option value="19859">Pala Masogo Health Centre</option> <option value="11730">Palakumi Dispensary</option> <option value="11731">Palani Health Care Clinic</option> <option value="18498">Palm Beach Hospital</option> <option value="20165">Pamar Medical Clinic</option> <option value="16089">Pan M Medical Clinic</option> <option value="16090">Pan Paper Dispensary</option> <option value="14012">Pand Pieri Community Health Centre</option> <option value="15456">Panda Flowers Medical Clinic</option> <option value="11733">Pandanguo Dispensary</option> <option value="11734">Pandya Memorial Hospital</option> <option value="13138">Pangani Dispensary</option> <option value="16339">Panpaper Dispensary</option> <option value="14013">Pap Kodero Health Centre</option> <option value="18387">Paradise Medical Centre</option> <option value="18889">Paradise Medical Centre</option> <option value="13417">Paramount Clinic</option> <option value="16303">Paramount Medical Clinic</option> <option value="18162">Parayon Dispensary</option> <option value="19424">Parkroad Dental Clinic (Ngara)</option> <option value="13139">Parkroad Nursing Home (Nairobi)</option> <option value="16749">Partners In Prevention</option> <option value="18322">Partners In Prevention VCT Centre</option> <option value="17048">Parua Dispensary</option> <option value="10927">Passenga Dispensary</option> <option value="14014">Pastor Machage Memorial Hospital</option> <option value="12977">Patanisho Maternity and Nursing Home</option> <option value="18708">Path Care Kenya</option> <option value="18637">Path Care Kenya</option> <option value="10928">Patmas Medical Clinic</option> <option value="16343">Patrician Dispensary</option> <option value="19025">Patrona Medical Services</option> <option value="11735">Patte Dispensary</option> <option value="16419">Paula Nursing Home</option> <option value="13124">PCEA Clinic (Ngundo)</option> <option value="12910">PCEA Dandora Clinic</option> <option value="16446">PCEA Gateway</option> <option value="19827">PCEA Honi Dispensary</option> <option value="17803">PCEA Kaigai Memorial</option> <option value="19337">PCEA Karero Dispensary</option> <option value="17444">PCEA Karungaru Dispensary</option> <option value="12205">PCEA Kasasule Dispensary</option> <option value="19435">PCEA Kayole Parish Health Centre</option> <option value="17921">PCEA Kibwezi Dispensary</option> <option value="12293">PCEA Kiengu Disp/Mat</option> <option value="18763">PCEA Kuwinda Health Clinic</option> <option value="17878">PCEA Mau-Summit Health Centre</option> <option value="18598">PCEA Mwangaza Dispensary</option> <option value="19700">PCEA Pipeline Clinic</option> <option value="18494">PCEA Silanga Church VCT</option> <option value="18116">PCEA Smyrna</option> <option value="18376">PCEA Upendo Health Centre</option> <option value="17547">PCEA VCT</option> <option value="19289">Peace Medical Clinic</option> <option value="19853">Peace Medical Clinic-Tetu</option> <option value="18380">Peak Health Medical Centre</option> <option value="18725">Pedo Dispensary</option> <option value="17124">Pefa Mercy Medical Centre</option> <option value="15460">Peka Maga Clinic</option> <option value="10929">Pekaru Medical Centre</option> <option value="16426">Pelewa Dispensary (CDF)</option> <option value="18402">Penda Health Medical Clinic</option> <option value="18496">Pendo Medical Clinic</option> <option value="11736">Pendo Medical Clinic (Kilindini)</option> <option value="16519">Pendo Medical Clinic (Kinango)</option> <option value="16757">Penta Flowers Clinic</option> <option value="19975">Pentapharm Limited</option> <option value="19241">Peoples Medical Clinic</option> <option value="12701">Pepo La Tumaini Dispensary</option> <option value="17928">Perani Private Clinic</option> <option value="19753">Perazim Diagnostic Centre</option> <option value="10931">Pesi Dispensary</option> <option value="15461">Pesi Dispensary (Laikipia West)</option> <option value="20167">Pesi Medical Centre</option> <option value="10933">Pharma Point Clinic</option> <option value="19540">Pharmat Health Care</option> <option value="10934">Phase 7 Clinic</option> <option value="10935">Phase Ten Clinic</option> <option value="10936">Phatholab Laboratory</option> <option value="18711">Philia Medical Clinic</option> <option value="18655">Philips Medical Clinic</option> <option value="19483">Philis Medical Laboratory</option> <option value="10937">Physiotherapy Clinic (Kirinyaga)</option> <option value="15462">Piave Dispensary</option> <option value="10938">Piemu Medical Clinic</option> <option value="13141">Piemu Medical Health Centre</option> <option value="18667">Pillar of Development</option> <option value="18785">Pillar of Development</option> <option value="10939">Pilot Medical Clinic</option> <option value="16320">Pims Medical Clinic</option> <option value="13142">Pine Medical Clinic</option> <option value="11738">Pingilikani Dispensary</option> <option value="18534">Pinnacle Health Services</option> <option value="17343">Piny Owacho Dispensary</option> <option value="15463">Pioneer Health Centre</option> <option value="16309">Pioneer Medical Clinic (Mandera East)</option> <option value="13418">Pioneer Medical Clinic (Wajir East)</option> <option value="13143">Pipeline Medical Health Services</option> <option value="12978">Pipeline Nursing Home</option> <option value="10940">Plainsview Nursing Home</option> <option value="15464">Plateau Hospital</option> <option value="16740">Plateau Medical Clinic</option> <option value="10941">Plaza Medical Laboratory</option> <option value="13419">Plaza Nursing Home</option> <option value="19353">Plaza X-Ray Services (Re-Insurance Plaza-Nairobi)</option> <option value="15465">Poi Dispensary</option> <option value="12702">Pole Medical Clinic</option> <option value="19878">Police Central Workshop Dispensary</option> <option value="13420">Police Line Dispensary (Garissa)</option> <option value="10942">Police Line Dispensary (Nyeri South)</option> <option value="10917">Pollen Medical Clinic</option> <option value="10943">Polly Jam Medical Clinic</option> <option value="15466">Polyclinic Hospital</option> <option value="12704">Pona Dispensary</option> <option value="12703">Pona Haraka Clinic</option> <option value="13145">Pona Mat Dispensary</option> <option value="18573">Pona Medical and Eye Care Centre</option> <option value="17851">Pona Medical Clinic</option> <option value="10944">Pona Medical Clinic (Nyeri North)</option> <option value="17854">Pona Services Opd</option> <option value="18943">Pona VCT</option> <option value="12705">Pondeni Medical Clinic</option> <option value="14015">Ponge Dispensary</option> <option value="14016">Ponge Dispensary (Mbita)</option> <option value="16647">Ponya Clinic</option> <option value="18143">Ponya Medical Clinic</option> <option value="18140">Ponya Surgicals Nursing Home</option> <option value="15467">Poole Dispensary</option> <option value="15468">Porro Dispensary</option> <option value="18774">Port Florence Clinic</option> <option value="19875">Port Florence Community Hospital Homa Bay Clinic</option> <option value="14017">Port Florence Hospital</option> <option value="13146">Port Health Dispensary (Langata)</option> <option value="16291">Port Health Dispensary (Wajir East)</option> <option value="18098">Port Health Dispensary Lokichoggio</option> <option value="11740">Port Reitz District Hospital</option> <option value="11741">Port Reitz MTC Dispensary</option> <option value="16091">Port Victoria Hospital</option> <option value="19901">Positive Partner Network VCT</option> <option value="16629">Posland Medical Clinic</option> <option value="20067">Post Bank Staff Clinic</option> <option value="18713">Pr Health Services</option> <option value="16630">Pr Medical Clinic (Buuri)</option> <option value="16631">Pr Medical Clinic (Ngushishi)</option> <option value="19266">Precious Care Medical Centre</option> <option value="19111">Precious Life Health Services</option> <option value="17996">Precious Life Medical Clinic Ruai</option> <option value="10945">Premier Bag and Cordage Dispensary</option> <option value="19498">Premier Laboratory (Nairobi)</option> <option value="18623">Premier Medical Clinic</option> <option value="12706">Premier Medical Clinic (Kangundo)</option> <option value="12707">Premier Medical Clinic (Kitui)</option> <option value="18744">Premium Health Services</option> <option value="16233">Presbyterian Ttc Rubate Health Centre</option> <option value="18556">Prescort Dispensary</option> <option value="19171">Prestige Clinic</option> <option value="19275">Prestige Health Centre (Zimerman)</option> <option value="18110">Primarosa Flower Ltd</option> <option value="17372">Primary Health Services</option> <option value="16775">Prime Care Health Clinic</option> <option value="19104">Prime Dental Clinic</option> <option value="13147">Prime Healthservices Dispensary</option> <option value="15469">Prime Medical Care</option> <option value="10947">Prime Medical Clinic</option> <option value="19440">Primed Medical Centre</option> <option value="19451">Primed Medical Services Komarock</option> <option value="18829">Primo Medical Clinic</option> <option value="16977">Prisca Wakarima (ACK) Dispensary</option> <option value="15470">Prison Dispensary</option> <option value="15471">Pro Esamai Clinic</option> <option value="20163">Proact services</option> <option value="19506">Professional Diagnostic Centre (Nairobi)</option> <option value="19290">Promise Medical Services</option> <option value="13149">Provide Inter Math Dispensary</option> <option value="13148">Provide Internatinal Clinic (Dandora)</option> <option value="13151">Provide International Clinic (Kayole)</option> <option value="17971">Provide International Health Care (Mathare)</option> <option value="19447">Provide International Hospital Mukuru</option> <option value="13150">Provide International Korogocho</option> <option value="12971">Provide International Mutindwa Umoja Clinic</option> <option value="18059">Provide Medical Clinic</option> <option value="19521">Providence Whole Care</option> <option value="19056">Providenve Health Clinic</option> <option value="17474">Provincial Police Hq VCT</option> <option value="18001">Prudent Medical Clinic Kariobangi</option> <option value="16704">Pserum Dispensary</option> <option value="16705">Psigirio Dispensary</option> <option value="15472">Psigor Dispensary</option> <option value="13153">Pstc Health Centre</option> <option value="19523">Psychological Health Services</option> <option value="20135">Psyco Africa Consultancy</option> <option value="16734">Ptigchi Dispensary</option> <option value="15473">Ptoyo Dipensary</option> <option value="13154">Pumwani Clinic</option> <option value="11744">Pumwani Dispensary</option> <option value="13155">Pumwani Majengo Dispensary</option> <option value="13156">Pumwani Maternity Hospital</option> <option value="13157">Pumwani Maternity VCT Centre</option> <option value="18324">Pumzika Medical Clinic</option> <option value="10949">Purity Medical Clinic</option> <option value="15474">Pwani (GOK) Dispensary</option> <option value="16092">Pwani Dispensary</option> <option value="11746">Pwani Maternity and Nursing Home</option> <option value="17662">Pwani University College Clinic</option> <option value="19098">Qarsadamu Dispensary</option> <option value="15475">Quadalupe Sisters Roret</option> <option value="19406">Quality Health Care Clinic (Naivasha)</option> <option value="18527">Quarry VCT Ongata Rongai</option> <option value="13421">Qudama Dispensary</option> <option value="20068">Quebee Health Care</option> <option value="11747">Queen Kadede Medical Clinic</option> <option value="16758">Queen of Peace Clinic</option> <option value="19906">Queens & Kings Health Centre</option> <option value="18757">R - Care Health Clinic</option> <option value="11748">Rabai Rural Health Demonstration Centre</option> <option value="14018">Rabar Dispensary</option> <option value="14019">Rabondo Dispensary</option> <option value="14020">Rabuor Health Centre</option> <option value="15476">Racecourse Clinic</option> <option value="19990">Racecourse Hospital</option> <option value="14021">Rachar Sugar Belt Hospital</option> <option value="14022">Rachuonyo District Hospital</option> <option value="15477">Radat Dispensary</option> <option value="19370">Radiant Hosp Kasarani</option> <option value="13158">Radiant Pangani Hospital</option> <option value="18722">Radienya Dispensary</option> <option value="14023">Radier Dispensary</option> <option value="14024">Rae Dispensary</option> <option value="18326">Rafiki Clinic</option> <option value="17932">Rafiki Kenia (Private) Clinic</option> <option value="16779">Rafiki Medical Clinic</option> <option value="10950">Rafiki Medical Clinic (Muranga North)</option> <option value="19487">Rafiki Medical Clinic (Westlands)</option> <option value="11749">Rafiki Miracle Clinic (Hindi )</option> <option value="14025">Raganga Health Centre</option> <option value="14026">Rageng'ni Dispensary</option> <option value="10951">Ragia Forest Dispensary</option> <option value="18530">Ragwe Dispensary</option> <option value="18211">Railway Dispensary</option> <option value="13168">Railway Training Institute Dispensary South B</option> <option value="15478">Railways Dispensary</option> <option value="14027">Railways Dispensary (Kisumu)</option> <option value="19213">Rainbow Clinic</option> <option value="11751">Rainbow Community Care</option> <option value="11752">Rainbow Medical Burangi</option> <option value="16295">Rainbow Medical Clinic</option> <option value="14028">Ram Hospital</option> <option value="11753">Ramada Dispensary</option> <option value="19295">Ramah Medical Clinic</option> <option value="14029">Ramasha Dispensary</option> <option value="12708">Ramata Health Centre</option> <option value="17437">Rambugu Dispensary (Rarieda)</option> <option value="16789">Rambula Dispensary</option> <option value="10952">Ramos Medical Clinic</option> <option value="14030">Ramula Health Centre</option> <option value="17521">Randago Dispensary</option> <option value="14031">Randung' Dispensary</option> <option value="14032">Ranen (SDA) Dispensary</option> <option value="14033">Rangala Health Centre</option> <option value="14034">Rangenyo Health Centre</option> <option value="14035">Rangwe (SDA) Dispensary</option> <option value="14036">Rangwe Sub-District Hospital</option> <option value="18082">Rapando VCT</option> <option value="14037">Rapcom Nursing and Maternity Home</option> <option value="15480">Rapha Maternity (Nakuru Central)</option> <option value="15479">Rapha Medical Centre</option> <option value="19535">Rapha Medical Clinic</option> <option value="10953">Rapha Medical Clinic (Kirinyaga)</option> <option value="19474">Rapha Mission Clinic</option> <option value="20202">Raphica Medical Clinic</option> <option value="12709">Rapsu Dispensary</option> <option value="14038">Rariw Dispensary</option> <option value="14039">Raruowa Health Centre</option> <option value="14040">Ratta Health Centre</option> <option value="19731">Rau Dispensary</option> <option value="18592">Ravine Glory Health Care Services</option> <option value="19384">Ravine Medical and ENT Clinic</option> <option value="18424">Rawana Dispensary</option> <option value="18255">Ray Comprehensive Youth Centre (Kanco)</option> <option value="13159">Ray of Hope Health Centre</option> <option value="17905">Ray Youth Consortium VCT</option> <option value="13422">Raya Dispensary</option> <option value="17998">Rays International Clinic Kariobangi</option> <option value="11755">Rea Vipingo Dispensary</option> <option value="14041">Reachout Dispensary</option> <option value="18406">Real Healthcare Medical Clinic</option> <option value="20177">Real I P M Company Clinic</option> <option value="18983">Reale Medical Clinic</option> <option value="10954">Reality Medical Clinic</option> <option value="19616">Recovery Medical Clinic (Kariobangi South)</option> <option value="19357">Reddys Medical Clinic</option> <option value="18822">Redeemed Gospel Church VCT</option> <option value="12710">Redeemed Medical Clinic</option> <option value="13160">Redemeed Health Centre</option> <option value="10955">Redland Roses Ltd Clinic</option> <option value="16857">Regional Blood Transfusion Centre (Embu)</option> <option value="17180">Rehema Children Medical Clinic Lodwar</option> <option value="15482">Rehema Dental Health</option> <option value="19673">Rehema MC (Top Station-Kitale)</option> <option value="10956">Rehema Medical Centre</option> <option value="16461">Rehema VCT Centre</option> <option value="17071">Rei Dispensary</option> <option value="18668">Reinha Rosary Medical Clinic (Githunguri)</option> <option value="18927">Rejoice Medical Clinic Lusiola</option> <option value="17114">Rekeke Model Health Centre</option> <option value="17806">Reliance Medical Clinic</option> <option value="17593">Remba Dispensary</option> <option value="19805">Remedy Laboratory Services</option> <option value="19466">Remer Medical Clinic</option> <option value="19620">Remla Medical Clinic (Dandora)</option> <option value="17373">Renguti (PCEA) Women's Guild Clinic</option> <option value="14042">Rera Dispensary</option> <option value="10035">Rescue Centre (Thika)</option> <option value="18375">Restore Life Medical Centre</option> <option value="13173">Reuben Mukuru Health Centre</option> <option value="14043">Reusse Troyer Health Centre</option> <option value="16377">Revival Baptist VCT Centre</option> <option value="16168">Revival Home Based Care Clinic</option> <option value="13423">Rhamu Sub-District Hospital</option> <option value="13424">Rhamudimtu Health Centre</option> <option value="15483">Rhein Valley Hospital</option> <option value="18547">Rheno Medicare Clinic</option> <option value="17963">Rhodes Ches Clinic (Ccn)</option> <option value="13163">Rhodes Chest Clinic</option> <option value="20137">Rhonda Dispensary and Maternity</option> <option value="10957">Riabai Dispensary</option> <option value="12711">Riachina Dispensary</option> <option value="12712">Riakanau Dispensary</option> <option value="16981">Riakinaro Health Centre</option> <option value="19894">Riakithiga Dispensary</option> <option value="14044">Riakworo Dispensary</option> <option value="14045">Riana Health Centre</option> <option value="16468">Riandu Dispensary</option> <option value="14046">Riat Dispensary</option> <option value="14047">Riat Dispensary (Migori)</option> <option value="13425">Riba Dispensary</option> <option value="11756">Ribe Dispensary</option> <option value="13164">Ribeiro Clinic</option> <option value="14048">Riechieri Health Centre</option> <option value="14049">Rietago Dispensary</option> <option value="11757">Riflot Medical Centre</option> <option value="18955">Riflot Medical Clinic</option> <option value="16826">Right Choice Clinic</option> <option value="14050">Rigoko Dispensary</option> <option value="14051">Rigoma Dispensary</option> <option value="17347">Rikendo Dispensary</option> <option value="17678">Rikenye Dispensary (Masaba)</option> <option value="19544">Rimaal Medical Laboratory</option> <option value="15485">Rimoi Dispensary</option> <option value="19475">Rinah Health Consultants</option> <option value="17710">Ringiti Dispensary</option> <option value="14052">Riokindo Health Centre</option> <option value="14053">Riongige Dispensry</option> <option value="15486">Riongo Dispensary</option> <option value="14054">Riotanchi Health Centre</option> <option value="12713">Ripples International Dispensary</option> <option value="17962">Riria Medical Clinic</option> <option value="17248">Rironi Dispensary</option> <option value="13165">Riruta Health Centre</option> <option value="18806">Rithika Medical and Counseling Centre</option> <option value="14055">Ritumbe Health Centre</option> <option value="10958">Riverside Clinic</option> <option value="19495">Riverside Medical Centre</option> <option value="15487">Riwo Dispensary</option> <option value="18259">Riyadh Medical Clinic</option> <option value="14056">Roadblock Clinic</option> <option value="10959">Roadside Clinic (Kagunduini)</option> <option value="10960">Roadside Medical Clinic Kiangai</option> <option value="15488">Robana Medical Clinic</option> <option value="18936">Robins Health Care Clinic</option> <option value="17135">Robinson Medical Clinic (Manga)</option> <option value="15489">Rocco Dispensary</option> <option value="14057">Rodi Dispensary</option> <option value="17077">Roka</option> <option value="11758">Roka Maweni Dispensary</option> <option value="18175">Rokimwi Clinic</option> <option value="12714">Rolex Medical Clinic</option> <option value="19642">Roma Medical Clinic</option> <option value="15490">Rombo Health Centre</option> <option value="17861">Romieva Medical Centre</option> <option value="19456">Romieva Medical Centre Tassia</option> <option value="15491">Romosha Dispensary</option> <option value="17101">Rondonin Dispensary</option> <option value="15493">Rongai Diagnstic Laboratory</option> <option value="15494">Rongai First Medical Centre</option> <option value="15495">Rongai Health Centre</option> <option value="18314">Rongai Orthopaedics Medical Services</option> <option value="15496">Rongai Uzima Medical Clinic</option> <option value="15497">Rongena Dispensary</option> <option value="17781">Rongena Dispensary (Narok South)</option> <option value="14058">Rongo District Hospital</option> <option value="13166">Ronil Medical Clinic (Githurai)</option> <option value="16093">Rophy Clinic</option> <option value="15499">Roret Medical Clinic</option> <option value="15498">Roret Sub-District Hospital</option> <option value="12715">Ros Megg Clinic</option> <option value="10961">Rosa Medical Clinic</option> <option value="18992">Rosade Medical Clinic</option> <option value="19401">Rosadett Medical Clinic</option> <option value="10963">Rose Medical Clinic</option> <option value="18307">Rosewo VCT Centre</option> <option value="18068">Rosewood Nursing Home</option> <option value="20008">Rosoga Dispensary</option> <option value="10964">Rospa Glory Clinic</option> <option value="14060">Rota Dispensary</option> <option value="16094">Rotary Doctors Clinic</option> <option value="15500">Rotary Doctors General Outreach</option> <option value="19940">Rotu Dispensary</option> <option value="17938">Round About Medical Centre</option> <option value="13167">Round About Medical Dispensary</option> <option value="16300">Rowla Medical Clinic</option> <option value="17732">Royal Clinic</option> <option value="16836">Royal Clinic & Laboratory</option> <option value="18988">Royal Clinic-Kibera</option> <option value="19821">Royal Dental Clinic</option> <option value="11759">Royal Health Care</option> <option value="10965">Royal Medical Centre</option> <option value="19956">Royal Medical Clinic</option> <option value="16823">Royal Medical Clinic (Imenti Central)</option> <option value="19106">Royal Medical Clinic (Meru)</option> <option value="10966">Royal Medical Clinic (Thika)</option> <option value="14061">Royal Nursing Home</option> <option value="18572">Royal Run Medical Clinic</option> <option value="19382">Royolk Medical Clinic</option> <option value="18221">Ruai (SDA) Clinic</option> <option value="13170">Ruai Community Clinic</option> <option value="13171">Ruai Health Centre</option> <option value="16487">Ruanda Dispensary</option> <option value="13172">Ruaraka Clinic</option> <option value="18485">Ruaraka Uhai Neema Hospital</option> <option value="10969">Ruchu Dispensary</option> <option value="10967">Ruera Estate Dispensary</option> <option value="18013">Ruguru Community Health Centre</option> <option value="17791">Ruguru Dispensary</option> <option value="16839">Ruiga (MCK) Dispensary</option> <option value="12716">Ruiri Catholic Health Centre</option> <option value="19129">Ruiri MCK Medical Centre</option> <option value="18709">Ruiri Medical Centre</option> <option value="16632">Ruiri Medical Clinic</option> <option value="12717">Ruiri Rural Health Demonstration Centre</option> <option value="10971">Ruiru Diagnostic Centre</option> <option value="10972">Ruiru East Medical Clinic</option> <option value="18184">Ruiru Health Clinic</option> <option value="10974">Ruiru Hospital Limited</option> <option value="10973">Ruiru Sub-District Hospital</option> <option value="16095">Rukala Dispensary</option> <option value="10975">Rukanga Dispensary</option> <option value="16241">Rukenya Dispensary</option> <option value="12718">Rukira Dispensary</option> <option value="18416">Ruma Youth Friendly VCT (Rarieda)</option> <option value="11760">Rumangao Dispensary</option> <option value="16096">Rumbiye Dispensary</option> <option value="15501">Rumuruti Catholic Dispensary</option> <option value="15502">Rumuruti District Hospital</option> <option value="15503">Rumuruti Medical Clinic</option> <option value="12719">Runyenjes District Hospital</option> <option value="17304">Ruona Dispensary</option> <option value="13426">Ruqa Dispensary</option> <option value="13174">Rural Aid VCT</option> <option value="18128">Rural Education and Environmental Program</option> <option value="10976">Rural Medical Clinic (Muranga South)</option> <option value="10977">Rural Medical Clinic (Nyeri South)</option> <option value="10978">Rural Personal Care Centre</option> <option value="10979">Rurii (ACK) Dispensary</option> <option value="10980">Rurii Kiandegwa Dispensary</option> <option value="10981">Ruringu Medical Clinic</option> <option value="10982">Ruruguti Afya Clinic</option> <option value="10983">Ruruguti Dispensary</option> <option value="15504">Rusana Medical Clinic</option> <option value="14062">Rusinga Dispensary</option> <option value="17594">Rusinga Island of Hope Humanist Health Centre</option> <option value="17250">Rwamburi Dispensary</option> <option value="14063">Rwambwa Health Centre</option> <option value="10984">Rwanyambo Dispensary</option> <option value="12721">Rwanyange Dispensary</option> <option value="10985">Rware Clinic</option> <option value="16512">Rwathe Dispensary</option> <option value="10986">Rwathia Dispensary</option> <option value="12722">Rwika Dispensary</option> <option value="17549">Sa/Ahf Kithituni Health Clinic</option> <option value="11761">Sabaki Dispensary</option> <option value="16170">Sabasaba Catholic Dispensary</option> <option value="10987">Sabasaba Health Centre</option> <option value="15505">Sabatia Dispensary</option> <option value="16097">Sabatia Eye Hospital Mission</option> <option value="16098">Sabatia Health Centre</option> <option value="13427">Sabir Medical Clinic</option> <option value="15506">Sabor Dispensary</option> <option value="17890">Sabor Forest Dispensary</option> <option value="15508">Saboti Sub-District Hospital</option> <option value="13428">Sabuli Health Centre</option> <option value="13429">Sabuli Nomadic Dispensary</option> <option value="16099">Sacha Health Centre</option> <option value="15509">Sachang'wan Dispensary</option> <option value="15510">Sacho School Dispensary</option> <option value="17092">Sachora Dispensary</option> <option value="10988">Sacred Heart Dispensary</option> <option value="16252">Sacred Heart Dispensary (Nzaikoni)</option> <option value="10989">Sacred Heart Kangaita Catholic Dispensary</option> <option value="16524">Sacred Heart Medical Clinic</option> <option value="10990">Sacred Heart Mission Dispensary</option> <option value="19039">Safa Medical Centre</option> <option value="16447">Safi Medical Clinic</option> <option value="11763">Sagaighu Dispensary</option> <option value="11764">Sagala Health Centre</option> <option value="17271">Sagala Medical Clinic</option> <option value="14064">Sagam Community Hospital</option> <option value="20057">Sagam Hospital</option> <option value="10991">Sagana Catholic Dispensary</option> <option value="10992">Sagana Medical Care</option> <option value="10993">Sagana Medical Clinic</option> <option value="10994">Sagana Rural Health Demonstration Centre</option> <option value="12723">Sagante Dispensary</option> <option value="15512">Sagat Dispensary</option> <option value="19640">Sahal Medical Clinic</option> <option value="18044">Sahla Medical Clinic</option> <option value="11765">Saifee Foundation Medical Centre</option> <option value="18386">Saika Medical Centre</option> <option value="15513">Saikeri Dispensary</option> <option value="15515">Sajiloni Dispensary</option> <option value="13430">Saka Health Centre</option> <option value="19960">Sakali Dispensary</option> <option value="15516">Sakutiek Health Centre</option> <option value="19115">Sala Dispensary</option> <option value="15517">Salabani Dispensary</option> <option value="17780">Salabwek Dispensary</option> <option value="15518">Salala Medical Clinic</option> <option value="12724">Salama (Baptist) Nursing Home</option> <option value="15519">Salama Clinic</option> <option value="12725">Salama Dawa Health Services</option> <option value="15520">Salama Health Centre (Laikipia West)</option> <option value="17896">Salama Lab Services</option> <option value="10995">Salama Medical Clinic</option> <option value="18237">Salama Medical Clinic (Embu)</option> <option value="11766">Salama Medical Clinic (Mombasa)</option> <option value="13175">Salama Nursing Home</option> <option value="15521">Salawa Catholic Mission Dispensary PHC</option> <option value="15522">Salawa Health Centre</option> <option value="18600">Salgaa Intergrated VCT</option> <option value="18392">Salivin Medical Clinic</option> <option value="19026">Salvage Medical Clinic</option> <option value="19613">Sam Medical Clinic</option> <option value="19203">Samaad Hospital</option> <option value="15523">Samaria (AIC) Mission Dispensary</option> <option value="10996">Samaria Maternity Home</option> <option value="12726">Samaritan Health Services</option> <option value="10997">Samaritan Medical Clinic</option> <option value="13176">Samaritan Medical Services (Dandora)</option> <option value="19054">Samaritan Soul Hospital</option> <option value="11767">Samba Medical Clinic</option> <option value="12727">Samburu Complex</option> <option value="11768">Samburu Health Centre</option> <option value="15524">Samburu Lodge Dispensary</option> <option value="16520">Samburu Medical Centre</option> <option value="19352">Samburu Medical Centre (Outreach Services)</option> <option value="15525">Sambut Dispensary</option> <option value="19728">Samilo Medical Clinic</option> <option value="10998">Samkim Medical Clinic</option> <option value="17944">Samoei Medical Clinic</option> <option value="14065">Samora Clinic</option> <option value="17143">Samutet Dispensary</option> <option value="16525">San Marco Project Clinic</option> <option value="15526">Sancta Maria Clinic</option> <option value="15527">Sandai Dispensary</option> <option value="15529">Sang'alo Dispensary</option> <option value="15528">Sanga Dispensary</option> <option value="13431">Sangailu Health Centre</option> <option value="11769">Sangekoro Dispensary</option> <option value="16100">Sango Dispensary</option> <option value="20186">Sango Kabuyefwe Dispensary</option> <option value="17986">Sango Natiri Dispensary</option> <option value="14066">Sango Rota Dispensary</option> <option value="13432">Sangole Dispensary</option> <option value="15530">Sangurur Dispensary</option> <option value="17957">Sani Medical Clinic</option> <option value="19379">Sanitas Lotus Medical Centre</option> <option value="13433">Sankuri Health Centre</option> <option value="19733">Santa Lucia Medical Clinic</option> <option value="11770">Santa Maria Medical Clinic</option> <option value="17828">Santa Maria Medical Clinic (Kwale)</option> <option value="19445">Santi Meridian Health Care</option> <option value="14067">Saokon Clinic</option> <option value="13178">Saola Maternity and Nursing Home</option> <option value="14068">Saradidi Dispensary</option> <option value="19757">Sarara Chemistry</option> <option value="13434">Saretho Health Centre</option> <option value="13435">Sarif Health Centre</option> <option value="19256">Sarimo Medical Centre</option> <option value="13436">Sarman Dispensary</option> <option value="14069">Saro Dispensary</option> <option value="19706">Sarova Hotels</option> <option value="15532">Saruchat Dispensary</option> <option value="18766">Sasa Centre</option> <option value="18796">Sasa Centre (Makadara)</option> <option value="18773">Sasa Centre (Westlands)</option> <option value="18571">Sasa Centre Naivasha (Drop In Service Centre-Disc)</option> <option value="19311">Sasa Centre-Ngara</option> <option value="15533">Satiet Dispensary</option> <option value="11771">Sau Health Services</option> <option value="11772">Savana Medical Clinic</option> <option value="16101">Savane Dispensary</option> <option value="11773">Savani Medical Centre</option> <option value="15534">Savani Tea Dispensary</option> <option value="18459">Savannah Likoni Medical Centre</option> <option value="15535">Savannah Medical Clinic</option> <option value="16691">Savimbi Medical Clinic</option> <option value="19201">Sawa Ikombe Medical Clinic</option> <option value="19202">Sawa Makutano Medical Clinic</option> <option value="11000">Sawa Medical Consultants</option> <option value="14070">Sayyid Aysha Dispensary</option> <option value="11774">Sayyida Fatimah Hospital</option> <option value="12728">School For The Deaf (Machakos)</option> <option value="19449">Scion Healthcare Ltd Clinic</option> <option value="18593">SDA Health Services Likoni Road Clinic</option> <option value="11777">Sea Breeze Medical Clinic</option> <option value="17630">Seaside Nursing Home</option> <option value="15536">Seed of Hope Medical Clinic</option> <option value="14071">Sega Cottage Hospital</option> <option value="14072">Sega Dispensary</option> <option value="14073">Sega Health Centre</option> <option value="17029">Segera Mission Dispensary</option> <option value="16790">Segere Dispensary</option> <option value="15537">Segero Dispensary</option> <option value="16470">Segetet Dispensary</option> <option value="15538">Sego Dispensary</option> <option value="15539">Segut Dispensary</option> <option value="15540">Segutiet Dispensary</option> <option value="17086">Seguton Dispensary</option> <option value="14074">Seka Health Centre</option> <option value="15541">Sekenani Health Centre</option> <option value="15542">Sekerr Dispensary</option> <option value="15543">Seketet Dispensary</option> <option value="11778">Semikaro Dispensary</option> <option value="14075">Sena Health Centre</option> <option value="18662">Senate Health Services</option> <option value="16440">Sengani Dispensary</option> <option value="14076">Sengera Health Centre (Gucha)</option> <option value="11779">Senior Staff Medical Clinic (MCM)</option> <option value="13179">Senye Medical Clinic</option> <option value="11780">Sera Dispensary</option> <option value="14077">Serawongo Dispensary</option> <option value="19085">Sere Clinic</option> <option value="16102">Seregeya Dispensary</option> <option value="16103">Serem Health Centre</option> <option value="15545">Serem Health Centre (Nandi South)</option> <option value="18749">Serena Beach Hotel & Spa Staff Clinic</option> <option value="17884">Serena Medical Clinic</option> <option value="15546">Sereng Dispensary</option> <option value="15547">Sereolipi Health Centre</option> <option value="15548">Sererit Catholic Dispensary</option> <option value="16730">Seretion Dispensary</option> <option value="15549">Seretunin Health Centre</option> <option value="15550">Seretut Dispensary</option> <option value="17591">Seretut Medical Clinic</option> <option value="15551">Serewo Health Centre</option> <option value="15552">Sergoit Clinic</option> <option value="15553">Sergoit Dispensary (Eldoret East)</option> <option value="15554">Sergoit Dispensary (Keiyo)</option> <option value="12729">Sericho Health Centre</option> <option value="19325">Serotec Medical Clinic</option> <option value="15555">Setano Dispensary</option> <option value="15556">Setek Dispensary</option> <option value="17267">Seth Medical Clinic</option> <option value="13180">Sex Workers Operation Project (Swop)</option> <option value="18176">Sex Workers Outreach Program (Lang'ata)</option> <option value="13181">Sgrr Medical Clinic</option> <option value="13182">Shaam Nursing Home</option> <option value="17647">Shafshafey Health Centre</option> <option value="18595">Shallom Dispensary</option> <option value="18952">Shalom Community Health Centre</option> <option value="17979">Shalom Community Hospital (Athi River)</option> <option value="12730">Shalom Community Hospital (Machakos)</option> <option value="11781">Shalom Health Services</option> <option value="15557">Shalom Medical Centre</option> <option value="20028">Shalom Medical Clinic</option> <option value="12731">Shalom Medical Clinic (Embu)</option> <option value="11002">Shalom Medical Clinic (Thika)</option> <option value="19315">Shalom Medical Clinical</option> <option value="19412">Shalom Satelite Clinic</option> <option value="18555">Shalome Medical Clinic</option> <option value="16104">Shamakhubu Health Centre</option> <option value="11004">Shamata Health Centre</option> <option value="16105">Shamberere Dispensary</option> <option value="11005">Shammah Clinic</option> <option value="18094">Shammah Medical Clinic</option> <option value="16189">Shangia Dispensary</option> <option value="11006">Shanka Medical</option> <option value="15558">Shankoe Dispensary</option> <option value="13437">Shanta Abaq Dispensary (Wajir West)</option> <option value="13438">Shantaabaq Health Centre (Lagdera)</option> <option value="11783">Shanzu Teachers College Clinic</option> <option value="19400">Sharifik Medical Clinic</option> <option value="17375">Sharom Dispensary</option> <option value="17324">Shartuka Dispensary</option> <option value="17374">Shauri Dispensary</option> <option value="13183">Shauri Moyo Baptist VCT Centre</option> <option value="13184">Shauri Moyo Clinic</option> <option value="19636">Shauri Moyo Health Services</option> <option value="18019">Sheikh Nurein Medical Centre</option> <option value="18471">Shekina Medical Clinic</option> <option value="17569">Shekinah Medical Clinic</option> <option value="17120">Shelemba</option> <option value="11784">Shella Dispensary</option> <option value="13185">Shepherds Medical Clinic Maringo</option> <option value="16106">Shianda Baptist Clinic</option> <option value="20194">Shianda Dispensary</option> <option value="18759">Shibanga Medical Clinic</option> <option value="16123">Shibanze Dispensary</option> <option value="16107">Shibwe Sub-District Hospital</option> <option value="18034">Shifa Medical Clinic (Moyale)</option> <option value="13439">Shifaa Nursing Home</option> <option value="16108">Shihalia Dispensary</option> <option value="16109">Shihome Dispensary</option> <option value="11785">Shika Adabu (MCM) Dispensary</option> <option value="11007">Shikamoo Medical Clinic</option> <option value="16110">Shikokho Dispensary</option> <option value="16483">Shikumu Dispensary</option> <option value="16111">Shikunga Health Centre</option> <option value="16112">Shikusa Health Centre</option> <option value="16113">Shikusi Dispensary</option> <option value="11786">Shiloh Nursing Clinic</option> <option value="11787">Shimba Hills Health Centre</option> <option value="13440">Shimbir Fatuma Health Centre</option> <option value="13443">Shimbrey Dispensary</option> <option value="11397">Shimo Borstal Dispensary (GK Prison)</option> <option value="11393">Shimo La Tewa Annex Dispensary (GK Prison)</option> <option value="11788">Shimo La Tewa High School Dispensary</option> <option value="11395">Shimo-La Tewa Health Centre (GK Prison)</option> <option value="11789">Shimoni Dispensary</option> <option value="16718">Shimuli Medical Clinic</option> <option value="16115">Shinutsa Dispensary</option> <option value="16719">Shinyalu Central Clinic</option> <option value="17596">Shinyalu Health Centre</option> <option value="19371">Shiply Medical Centre & Lab</option> <option value="16116">Shiraha Health Centre</option> <option value="14078">Shirikisho Dispensary</option> <option value="16200">Shirikisho Medical Dispensary</option> <option value="16198">Shirikisho Methodist Dispensary</option> <option value="16117">Shiru Health Centre</option> <option value="16118">Shisaba Dispensary</option> <option value="16119">Shiseso Health Centre</option> <option value="16120">Shitoto Medical Clinic</option> <option value="16121">Shitsitswi Health Centre</option> <option value="16122">Shivanga Health Centre</option> <option value="15560">Shompole Dispensary</option> <option value="17389">Shree Cutchhi Leva Samaj Medical Clinic</option> <option value="11791">Shree Cuteh Sat Sanf Swaminara</option> <option value="11792">Shuffa Clinic</option> <option value="18490">Shujaa Project Namanga</option> <option value="20052">Shujaa Satellite Clinic</option> <option value="11793">Shukrani Medical Clinic</option> <option value="18820">Shura Dispensary (Chalbi)</option> <option value="11008">Shwak Medical Clinic</option> <option value="14079">Siabai/Makonge Dispensary</option> <option value="19905">Siakago Boys High School Dispensary</option> <option value="12733">Siakago Clinic</option> <option value="18426">Siala Kaduol</option> <option value="15561">Siana Springs Dispensary</option> <option value="14080">Siaya District Hospital</option> <option value="14081">Siaya Medical Centre</option> <option value="18520">Sibayan Dispensary</option> <option value="15562">Sibilo Dispensary</option> <option value="16124">Siboti Health Centre</option> <option value="14082">Sibuoche Dispensary</option> <option value="14083">Sieka Dispensary</option> <option value="14084">Sifuyo Dispensary</option> <option value="15563">Sigilai (Cmc) Clinic</option> <option value="14085">Sigomere Health Centre</option> <option value="15564">Sigor Sub District Hospital</option> <option value="15565">Sigor Sub-District Hospital</option> <option value="15566">Sigoro Dispensary</option> <option value="15567">Sigot Dispensary</option> <option value="14086">Sigoti Health Centre</option> <option value="15568">Sigowet Sub-District Hospital</option> <option value="14087">Sikalame Dispensary</option> <option value="16485">Sikarira Dispensary</option> <option value="12734">Sikh Temple Hospital</option> <option value="20162">Sikhendu Disp</option> <option value="15569">Sikhendu Medical Clinic</option> <option value="19368">Siksik Dispensary</option> <option value="16125">Sikulu Dispensary</option> <option value="18145">Sikusi Dispensary</option> <option value="11794">Silaloni Dispensary</option> <option value="13186">Silanga (Msf Belgium) Dispensary</option> <option value="17860">Silibwet Dispensary</option> <option value="15570">Silibwet Dispensary (Bomet)</option> <option value="11009">Silibwet Health Centre (Nyandaruawest)</option> <option value="15571">Siloam Hospital</option> <option value="12735">Siloam Mediacl Clinic</option> <option value="11010">Siloam Medical Centre</option> <option value="17825">Siloam Medical Clinic</option> <option value="19635">Siloam Medical Clinic ( Pokot Central)</option> <option value="15572">Siloam Medical Clinic (Kajiado)</option> <option value="19713">Siloam Medical Clinic (Kieni East)</option> <option value="11796">Siloam Medical Clinic (Malindi)</option> <option value="15573">Siloam Medicalclinic</option> <option value="11011">Silver Line Medical Clinic</option> <option value="15574">Simba Health Centre</option> <option value="14088">Simba Opepo Dispensary</option> <option value="15575">Simbi Dispensary</option> <option value="14089">Simbi Kogembo Dispensary</option> <option value="11012">Simbi Roses Clinic</option> <option value="14090">Simbiri Nanbell Health Centre</option> <option value="17988">Simboiyon Dispensary</option> <option value="14091">Simenya Dispensary</option> <option value="17970">Similani Medical Clinic</option> <option value="15576">Simotwet Dispensary</option> <option value="17151">Simotwet Dispensary ( Koibatek)</option> <option value="15577">Simotwo Dispensary (Eldoret East)</option> <option value="15578">Simotwo Dispensary (Keiyo)</option> <option value="15579">Simrose Medical Clinic</option> <option value="15580">Sina Dispensary</option> <option value="11013">Sinai Maternity and Medical Clinic</option> <option value="16834">Sinai Medical Clinic</option> <option value="17123">Sinai Medical Services</option> <option value="15581">Sinai Mount Hospital</option> <option value="20029">Sindo Drop In Centre</option> <option value="17765">Singawa Medical Centre</option> <option value="15582">Singiraine Dispensary</option> <option value="13187">Single Mothers Association of Kenya (Smak)</option> <option value="15583">Singorwet Dispensary</option> <option value="14092">Sino Dispensary</option> <option value="16126">Sinoko Dispensary (Bungoma East)</option> <option value="16127">Sinoko Dispensary (Likuyani)</option> <option value="17240">Sinonin Dispensary</option> <option value="16128">Sio Port District Hospital</option> <option value="15585">Siomo Dispensary</option> <option value="15586">Siongi Dispensary</option> <option value="15587">Siongiroi Health Centre</option> <option value="15588">Sipili Catholic Dispensary</option> <option value="15589">Sipili Health Centre</option> <option value="17148">Sipili Maternity and Nursing Home</option> <option value="18777">Sir John and Mbatia Community Medical Centre</option> <option value="17990">Sirakaru Dispensary</option> <option value="17350">Sirata Dispensary</option> <option value="15590">Sirata Oirobi Dispensary</option> <option value="17140">Sirate Dispensary (Manga)</option> <option value="14093">Sirembe Dispensary</option> <option value="15591">Siret Tea Dispensary</option> <option value="14094">Siriba Dispensary</option> <option value="17858">Sirikwa Peace Dispensary</option> <option value="16129">Sirimba Dispensary</option> <option value="16130">Sirisia Hospital</option> <option value="17177">Sironoi GOK Dispensary</option> <option value="17247">Sironoi SDA Dispensary</option> <option value="17051">Siruti Dispensary</option> <option value="15594">Sirwa Dispensary</option> <option value="15593">Sirwa Dispensary (Mogotio)</option> <option value="16131">Sisenye Dispensary</option> <option value="12736">Sisi Kwa Sisi Medical Clinic</option> <option value="15595">Sisiya Dispensary</option> <option value="20041">Sisokhe Dispensary</option> <option value="15596">Sispar Medical Clinic</option> <option value="19957">Sister Medical Clinic</option> <option value="13442">Sisters Maternity Home (Simaho)</option> <option value="18011">Sisto Mazoldi Dispensary (Rongai)</option> <option value="17027">Sitatunga Dispensary</option> <option value="15597">Sitoi Tea Dispensary</option> <option value="17322">Sitoka Dispensary</option> <option value="11799">Siu Dispensary</option> <option value="16147">Sivilie Dispensary</option> <option value="15598">Siwo Dispensary</option> <option value="15599">Siyiapei (AIC) Dispensary</option> <option value="11775">Skans Health Care Centre</option> <option value="17959">Sky Way Medical Clinic</option> <option value="18622">Skyhill Medical Centre</option> <option value="19639">Skylit Medical Clinic</option> <option value="18000">Skymed Medical Clinic Githunguri</option> <option value="11800">Sloam Medical Clinic</option> <option value="11014">Slope Optician</option> <option value="18717">Slopes Medical Clinic</option> <option value="19994">Slum Medical Clinic</option> <option value="19552">Smiles Medical Centre</option> <option value="19342">Snocx Medical Clinic</option> <option value="16633">Snowview Medical Clinic</option> <option value="15601">Soba River Health Centre</option> <option value="18634">Soceno Pharmacy</option> <option value="15602">Sochoi (AIC) Dispensary</option> <option value="15603">Sochoi Dispensary</option> <option value="19393">Social Service League (Nairobi )</option> <option value="18045">Soget Dispensary</option> <option value="15604">Sogon Dispensary</option> <option value="15605">Sogoo Health Centre</option> <option value="19331">Soin Health Care - Mfangano Street)</option> <option value="14095">Soklo Dispensary</option> <option value="17187">Soko Medical Clinic</option> <option value="11802">Sokoke Dispensary</option> <option value="11803">Sokoke Medical Clinic</option> <option value="13188">Sokoni Arcade VCT</option> <option value="18049">Soldier</option> <option value="11015">Soldier Medical Clinic</option> <option value="11016">Solea Medical Clinic</option> <option value="15606">Solian Dispensary</option> <option value="15607">Soliat Dispensary</option> <option value="17575">Solio Dispensary</option> <option value="17666">Sololo Makutano Dispensary</option> <option value="12739">Sololo Mission Hospital</option> <option value="19041">Solution Medical Clinic</option> <option value="15608">Solyot Dispensary</option> <option value="12740">Somare Dispensary</option> <option value="11804">Sombo Dispensary</option> <option value="11017">Somo Medical Clinic</option> <option value="16132">Sonak Clinic</option> <option value="15609">Sondany Dispensary</option> <option value="14096">Sondu Health Centre</option> <option value="12741">Songa Health Centre</option> <option value="15610">Songeto Dispensary</option> <option value="15611">Songonyet Dispensary</option> <option value="14097">Sony Medical Centre</option> <option value="17809">Sopa Lodge Dispensary</option> <option value="15613">Sore Dispensary</option> <option value="14098">Sori Lakeside Nursing and Maternity Home</option> <option value="16673">Sorok Dispensary</option> <option value="13189">Sos Dispensary</option> <option value="17945">Sos Medical Clinic (Eldoret East)</option> <option value="14099">Sosera Dispensary</option> <option value="15614">Sosian Dispensary</option> <option value="15615">Sosiana Dispensary</option> <option value="15616">Sosiani Health Centre</option> <option value="19389">Sosio Medical Clinic</option> <option value="15617">Sosiot Health Centre</option> <option value="15618">Sosit Dispensary</option> <option value="11805">Sosoni Dispensary</option> <option value="17993">Soteni Dispensary</option> <option value="15619">Sotik Health Centre</option> <option value="14100">Sotik Highlands Dispensary</option> <option value="17880">Sotik Town VCT</option> <option value="15620">Sotit Dispensary</option> <option value="13190">South B Clinic</option> <option value="18005">South B Hospital Ltd</option> <option value="13144">South B Police Band Dispensary</option> <option value="18880">South Eastern Kenya University (Seku) Health Unit</option> <option value="15622">South Horr Catholic Health Centre</option> <option value="15621">South Horr Dispensary</option> <option value="17390">Southern Health Care</option> <option value="17693">Sowa Medcal Clinic</option> <option value="13017">Soweto Kayole PHC Health Centre</option> <option value="17470">Soweto Medical Clinic</option> <option value="15623">Soy Health Centre</option> <option value="16133">Soy Resource Centre</option> <option value="16134">Soy Sambu Dispensary</option> <option value="15624">Soymet Dispensary</option> <option value="16135">Soysambu (ACK) Dispensary</option> <option value="18761">Spa Nursing Home</option> <option value="11807">Sparki Health Services</option> <option value="17483">Speak and Act</option> <option value="13192">Special Provision Clinic</option> <option value="13193">Special Treatment Clinic</option> <option value="18791">Sportlight Empowerment Group</option> <option value="11018">Sports View CFW Medical Clinic</option> <option value="18922">Springs Health Care Clinic</option> <option value="20054">Springs of Life Lutheran Dispensary</option> <option value="19973">Springs of Patmos Health Services</option> <option value="19130">Sr Rhoda Medical Clinic</option> <option value="19547">Srisathya Sai Medical Clinic</option> <option value="11019">Ssema Medical Clinic</option> <option value="16260">St Agnes Clinic</option> <option value="12742">St Agnes Kiaganari</option> <option value="14101">St Akidiva Memorial Hospital</option> <option value="20020">St Akidiva Mindira Hospital - Mabera</option> <option value="18219">St Alice (EDARP) Dandora</option> <option value="18495">St Aloysius Gonzaga School Dispensary</option> <option value="11020">St Andrew Umoja Medical Clinic</option> <option value="17973">St Andrews Cc Rironi Dispensary</option> <option value="11021">St Andrews Kabare (ACK) Dispensary</option> <option value="11808">St Andrews Medical Clinic</option> <option value="18980">St Andrews Medical Clinic - Eldoret</option> <option value="16136">St Andrews Othodox Clinic</option> <option value="11022">St Angela Kingeero Clinic</option> <option value="17362">St Angela Melici Health Centre</option> <option value="17876">St Angela Merici Health Centre (Kingeero)</option> <option value="19034">St Angelas Clinic</option> <option value="12743">St Ann Hospital</option> <option value="11023">St Ann Lioki Dispensary</option> <option value="16805">St Ann Medical Clinic</option> <option value="19716">St Ann Medical Clinic</option> <option value="15625">St Ann Medical Clinic (Naivasha)</option> <option value="13197">St Ann's Clinic</option> <option value="11809">St Ann's Medical Clinic</option> <option value="11024">St Anne (ACK) Dispensary</option> <option value="19825">St Anne CFW Clinic</option> <option value="12744">St Anne Kariene Dispensary</option> <option value="16544">St Anne Medical Centre (Mombasa)</option> <option value="11607">St Anne Mida Catholic Dispensary</option> <option value="16496">St Anne's Cry For The World Clinic (Raimu)</option> <option value="17142">St Annes Health Clinic</option> <option value="19096">St Annes Medical Clinic Ongata Rongai</option> <option value="13196">St Annes Medical Health Centre</option> <option value="17989">St Anns Medical Centre</option> <option value="18756">St Anns Medical Centre</option> <option value="19057">St Anns Medical Clinic</option> <option value="20080">St Anselmo Medical Clinic</option> <option value="15626">St Anthony Lemek Dispensary</option> <option value="17203">St Anthony Medical Clinic</option> <option value="15628">St Antony Health Centre</option> <option value="18113">St Antony Medical Clinic</option> <option value="15627">St Antony's Abossi Health Centre</option> <option value="12745">St Assisi Sisters of Mary Immaculate Nursing Home</option> <option value="11027">St Augastine</option> <option value="15629">St Augustine Youth Friendly Centre</option> <option value="11028">St Austine Medical Clinic</option> <option value="13822">St Barbara Mosocho Health Centre</option> <option value="17723">St Barkita Dispensary Utawala</option> <option value="14102">St Barnabas Dispensary</option> <option value="18115">St Basil's Catholic Dispensary</option> <option value="13198">St Begson Clinic</option> <option value="16526">St Bennedticto Health Centre</option> <option value="15630">St Boniface Dispensary</option> <option value="13199">St Bridget's Mother & Child</option> <option value="14661">St Bridgit Kalemunyang Dispensary</option> <option value="15631">St Brigids Girls High School Dispensary</option> <option value="15632">St Brigitas Health Centre</option> <option value="15633">St Camellus Medical Clinic</option> <option value="19615">St Camillus Health Centres</option> <option value="14103">St Camillus Mission Hospital</option> <option value="13200">St Catherine's Health Centre</option> <option value="15634">St Catherine's Napetet Dispensary</option> <option value="11029">St Cecilia Nursing Home</option> <option value="11030">St Charles Lwanga Dispensary</option> <option value="15957">St Charles Lwanga Health Centre</option> <option value="18405">St Christopher Dispensary</option> <option value="16137">St Claire Dispensary</option> <option value="14104">St Clare Bolo Health Centre</option> <option value="15635">St Clare Dispensary</option> <option value="18465">St Clare Medical Clinic</option> <option value="14105">St Consolata Clinic</option> <option value="16138">St Damiano Nursing Home</option> <option value="11031">St David Medical Clinic</option> <option value="12746">St David's Health Care</option> <option value="19896">St Eliza Medical Clinic</option> <option value="14106">St Elizabeth Chiga Health Centre</option> <option value="15636">St Elizabeth Health Centre</option> <option value="15089">St Elizabeth Lorugum Health Centre</option> <option value="13739">St Elizabeth Lwak Mission Health Centre</option> <option value="11813">St Elizabeth Medical Clinic Bakarani</option> <option value="15637">St Elizabeth Nursing Home</option> <option value="14489">St Faith Medical Clinic (Kimana)</option> <option value="13201">St Florence Medical Care Health Centre</option> <option value="13202">St Francis Com Hospital</option> <option value="17943">St Francis Community Hospital (Kasarani)</option> <option value="12748">St Francis Health Centre</option> <option value="13203">St Francis Health Centre (Nairobi North)</option> <option value="15639">St Francis Health Centre (Nakuru Central)</option> <option value="19828">St Francis Health Clinic</option> <option value="12749">St Francis Medical Clinic (Machakos)</option> <option value="11032">St Francis Medical Clinic (Thika)</option> <option value="18542">St Francis of Assisi Dispensary</option> <option value="15640">St Francis Tinga Health Centre (Kipkelion)</option> <option value="11033">St Frank Dispensing Centre</option> <option value="15641">St Freda's Cottage Hospital</option> <option value="11034">St Gabriel Health Centre</option> <option value="16344">St Getrude Dispensary</option> <option value="15642">St Gladys Njoga Clinic</option> <option value="11815">St Grace Medical Clinic</option> <option value="14108">St Hellens Clinic</option> <option value="11816">St Hillarias Medical Clinic</option> <option value="12750">St Immaculate Clinic</option> <option value="11035">St James Angilcan Church of Kenya Kiaritha Dispens</option> <option value="11036">St James Clinic</option> <option value="19121">St James Clinic</option> <option value="19299">St James Medical Centre</option> <option value="19033">St James Medical Clinic</option> <option value="16685">St James Medical Clinic</option> <option value="16870">St Jane Nursing Home</option> <option value="19729">St John Afya Bora Medical Clinic</option> <option value="12076">St John Baptist Ikalaasa Mission Dispensary</option> <option value="16817">St John Catholic Dispensary (Nyeri North)</option> <option value="15643">St John Cottage Health Centre</option> <option value="13205">St John Hospital</option> <option value="17936">St John Hospital Limited</option> <option value="12510">St John Marieni Dispensary</option> <option value="19448">St John Medical Centre</option> <option value="20117">St John Medical Clinic</option> <option value="15644">St John Medical Clinic (Kajiado)</option> <option value="11038">St John Medical Clinic (Nyeri North)</option> <option value="18411">St John Medical Surgical Centre</option> <option value="11039">St John Ndururumo Medical Clinic</option> <option value="17369">St John Orthodox Dispensary Kahuho</option> <option value="19741">St John's Clinic</option> <option value="18408">St John's Community Centre</option> <option value="18222">St John's Community Clinic Njiru</option> <option value="17570">St John's Dispensary (Kithoka)</option> <option value="14109">St John's Karabach Dispensary</option> <option value="17036">St John's Nyabite</option> <option value="13206">St Johns Ambulance</option> <option value="15645">St Johns Health Care</option> <option value="11040">St Johns Thaita (ACK) Dispensary</option> <option value="16882">St Jones &Ring Road Health Clinic</option> <option value="11043">St Josef Medical Clinic</option> <option value="17368">St Joseph (ACK) Kanyariri Dispensary</option> <option value="13207">St Joseph (EDARP) Clinic</option> <option value="17576">St Joseph Brothers</option> <option value="12751">St Joseph Catholic Dispensary (Igembe)</option> <option value="15646">St Joseph Catholic Dispensary (Laikipia East)</option> <option value="11041">St Joseph Catholic Dispensary (Ruiru)</option> <option value="11042">St Joseph Clinic (Muranga)</option> <option value="12752">St Joseph Dispensary (Kabaa)</option> <option value="15647">St Joseph Hospital</option> <option value="16995">St Joseph Kavisuni Dispensary</option> <option value="16550">St Joseph Maledi Clinic</option> <option value="12753">St Joseph Medical Clinic (Kangundo)</option> <option value="11044">St Joseph Medical Clinic (Thika)</option> <option value="12754">St Joseph Medical Clinic (Yathui)</option> <option value="19119">St Joseph Medical Clinic Kathiani</option> <option value="18601">St Joseph Mission Dispensary Chumvini</option> <option value="14110">St Joseph Mission Hospital</option> <option value="13208">St Joseph Mukasa Dispensary</option> <option value="17933">St Joseph Nursing Home</option> <option value="16409">St Joseph Nursing Home</option> <option value="12755">St Joseph School (Kabaa)</option> <option value="13209">St Joseph W Dispensary (Westlands)</option> <option value="19683">St Joseph's Boys National School Disp</option> <option value="13210">St Joseph's Dispensary (Dagoretti)</option> <option value="16248">St Joseph's Dispensary (Machakos)</option> <option value="19682">St Joseph's Girls High School Disp</option> <option value="13936">St Joseph's Nyansiongo Health Centre</option> <option value="14111">St Joseph's Obaga Dispensary</option> <option value="11817">St Joseph's Shelter of Hope</option> <option value="17807">St Joseph's The Worker</option> <option value="12756">St Joy Afya Clinic</option> <option value="17252">St Jude Catholic Dispensary</option> <option value="11046">St Jude Clinic</option> <option value="14112">St Jude Health Centre (Icipe)</option> <option value="17974">St Jude Medical Clinic</option> <option value="17835">St Jude Medical Clinic</option> <option value="16513">St Jude Medical Clinic (Maragua)</option> <option value="19672">St Jude Theddeus Mc</option> <option value="14113">St Jude's Clinic</option> <option value="13212">St Jude's Health Centre</option> <option value="13211">St Jude's Medical Centre</option> <option value="18198">St Judes Medical Clinic</option> <option value="19603">St Judes Nursing Hospital</option> <option value="15648">St Kevina Dispensary</option> <option value="14114">St Kizito Health Centre</option> <option value="12757">St Kizito Mission</option> <option value="16345">St Ladislaus Dispensary</option> <option value="17517">St Lawrence Dispensary</option> <option value="15649">St Leonard Hospital</option> <option value="19280">St Louis Community Hospital</option> <option value="17370">St Lucy Medical Clinic</option> <option value="12758">St Lucy's Hospital</option> <option value="20139">St Luke Clinic</option> <option value="17238">St Luke Kihuro (ACK) Dispensary</option> <option value="11047">St Luke Medical Care Clinic</option> <option value="17169">St Luke Medical Centre</option> <option value="11818">St Luke's (ACK) Hospital Kaloleni</option> <option value="14116">St Luke's Health Centre (Mbita)</option> <option value="14117">St Luke's Hospital</option> <option value="18303">St Luke's The Physician Medical Centre</option> <option value="13213">St Lukes (Kona) Health Centre</option> <option value="16821">St Lukes (Molo)</option> <option value="12759">St Lukes Cottage Hospital</option> <option value="18776">St Lukes Orthopaedic and Trauma Hospital</option> <option value="17391">St Mac's Hospital</option> <option value="11049">St Margret Family Care Clinic</option> <option value="16742">St Mark Maternity</option> <option value="19657">St Mark Medical Clinic</option> <option value="18606">St Mark Medical Clinic</option> <option value="12760">St Mark Medical Clinic (Kangundo)</option> <option value="13214">St Mark Medical Clinic (Nairobi East)</option> <option value="14118">St Mark's Lela Dispensary</option> <option value="11050">St Mark's Medical Clinic</option> <option value="18047">St Marks</option> <option value="12761">St Marks Dispensary (Kariene)</option> <option value="19655">St Marks Hospital</option> <option value="19231">St Marks Kigari Teachers College Dispensary</option> <option value="17340">St Marks Medical Clinic</option> <option value="17567">St Martin Catholic Social Apostolate</option> <option value="15650">St Martin De Porres (Mobile)</option> <option value="15651">St Martin De Porres (Static)</option> <option value="16644">St Martin Medical Clinic</option> <option value="11048">St Mary (ACK) Dispensary (Ngariama)</option> <option value="10746">St Mary (ACK) Mugumo Dispensary</option> <option value="15652">St Mary Health Centre (Kiserian)</option> <option value="11052">St Mary Health Clinic</option> <option value="11053">St Mary Health Services</option> <option value="11054">St Mary Laboratory (Mwea)</option> <option value="18173">St Mary Magdalene Kanjuu Dispensary</option> <option value="16778">St Mary Medical Clinic</option> <option value="15653">St Mary Medical Clinic (Nakuru North)</option> <option value="17748">St Mary Medical Clinic Gatundu</option> <option value="18248">St Mary's Dispensary</option> <option value="16139">St Mary's Dispensary (Lugari)</option> <option value="13217">St Mary's Health Centre</option> <option value="14119">St Mary's Health Centre (Mbita)</option> <option value="17940">St Mary's Health Services</option> <option value="16140">St Mary's Health Unit Chelelemuk</option> <option value="15654">St Mary's Hospital (Gilgil)</option> <option value="16141">St Mary's Hospital (Mumias)</option> <option value="15656">St Mary's Kalokol Primary Health Care Programme</option> <option value="15655">St Mary's Kapsoya Dispensary</option> <option value="13216">St Mary's Medical Clinic</option> <option value="13215">St Mary's Medical Clinic</option> <option value="11820">St Mary's Medical Clinic (Malindi)</option> <option value="11058">St Mary's Medical Clinic (Muranga South)</option> <option value="11055">St Mary's Medical Clinic (Ruiru)</option> <option value="13218">St Mary's Mission Hospital</option> <option value="18603">St Mary's Mother & Child Medical Services</option> <option value="16418">St Mary's Yala Dispensary</option> <option value="11057">St Marys Clinic (Kangema)</option> <option value="12762">St Marys Dispensary (Mwala)</option> <option value="12763">St Marys Medical Clinic (Kiaragana)</option> <option value="12764">St Marys Medical Clinic (Runyenjes)</option> <option value="11654">St Marys Msabaha Catholic Dispensary</option> <option value="12765">St Marys Nguviu Dispensary</option> <option value="11059">St Mathews and Sarah Dispensary</option> <option value="20037">St Mathews Kandaria Dispensary</option> <option value="15657">St Mathews Maternity and Lab Services</option> <option value="19438">St Maurice Medical Services</option> <option value="14059">St Mercelline Roo Dispensary (Suba)</option> <option value="12766">St Michael (Miaani) Mission Dispensary</option> <option value="13219">St Michael Clinic</option> <option value="19332">St Michael Community Nursing Home</option> <option value="15658">St Michael Dispensary</option> <option value="11060">St Michael Dispensary (Kangaita)</option> <option value="18179">St Michael Goodwill Medical Clinic</option> <option value="17741">St Michael Medical Clinic</option> <option value="11061">St Michael Medical Clinic (Nyeri South)</option> <option value="19194">St Michael Medical Clinic -Kangundo</option> <option value="16250">St Michael Medical Services</option> <option value="12768">St Michael Nursing Home</option> <option value="16657">St Monica Catholic Dispensary (Nguutani)</option> <option value="11062">St Monica Dispensary</option> <option value="14120">St Monica Hospital</option> <option value="17044">St Monica Medical Clinic</option> <option value="15659">St Monica Medical Clinic (Dundori)</option> <option value="15660">St Monica Medical Clinic (Nakuru)</option> <option value="14121">St Monica Rapogi Health Centre</option> <option value="15661">St Monica's Nakwamekwi Dispensary</option> <option value="10765">St Mulumba Mission Hospital</option> <option value="18114">St Nicholas Medical Clinic</option> <option value="14122">St Norah's Clinc</option> <option value="13221">St Odilia's Dispensary</option> <option value="12769">St Orsola Mission Hospital</option> <option value="13222">St Patrick Health Care Centre</option> <option value="19297">St Patrick Medical Centre</option> <option value="15662">St Patrick's Kanamkemer Dispensary</option> <option value="18305">St Patricks Dispensary</option> <option value="14123">St Paul Dispensary</option> <option value="18537">St Paul Ithiki (ACK ) Dispensary</option> <option value="18548">St Paul Kiamuri (ACK) Dispensary</option> <option value="12770">St Paul Medical Clinic (Makutano)</option> <option value="14124">St Paul's Health Centre</option> <option value="18190">St Paul's Hospital</option> <option value="11823">St Paul's Medical Clinic (Malindi)</option> <option value="18477">St Pauline Medical Clinic</option> <option value="16143">St Pauline Nursing Home and Marternity</option> <option value="17930">St Pauls Ejinja Dispensary</option> <option value="17392">St Pery's Medical Clinic</option> <option value="15663">St Peter Claver R Clinic</option> <option value="13223">St Peter Dispensary</option> <option value="15664">St Peter Kware Medical Clinic</option> <option value="17462">St Peter Orthodox Church Dispenasary</option> <option value="17982">St Peter Orthodox Kanjeru Dispensary</option> <option value="11066">St Peter's (ACK) Medical Clinic</option> <option value="18017">St Peter's Catholic Dispensary (Ng'onyi)</option> <option value="11824">St Peter's Hospital</option> <option value="15665">St Peter's Medical Clinic</option> <option value="17983">St Peters (ACK) Dispensary</option> <option value="16978">St Peters Gaitheri (ACK) Dispensary</option> <option value="17141">St Peters Medical Clinic</option> <option value="16050">St Philiphs Mukomari</option> <option value="11067">St Philips (ACK) Dispensary Ndiriti</option> <option value="13224">St Philips Health Centre</option> <option value="12771">St Philomena Medical Clinic</option> <option value="16145">St Pius Musoli Health Centre</option> <option value="17488">St Raphael Arch Medical</option> <option value="18515">St Raphael Dispensary</option> <option value="11366">St Raphael Health Centre</option> <option value="17683">St Raphael's Clinic</option> <option value="18843">St Richard Medical Clinic</option> <option value="14125">St Ruth Clinic</option> <option value="17406">St Stephen (ACK) Cura Dispensary</option> <option value="17440">St Stephen's Children Clinic Gatondo</option> <option value="17429">St Stephen's Kiandagae (ACK) Dispensary</option> <option value="16146">St Susan Clinic</option> <option value="11069">St Teresa Catholic Dispensary</option> <option value="12772">St Teresa Medical Clinic</option> <option value="19380">St Teresa Medical Clinic ( Zimmerman)</option> <option value="11071">St Teresa Nursing Home</option> <option value="15666">St Teresa Olokirikirai Dispensary</option> <option value="13227">St Teresa's Health Centre</option> <option value="13226">St Teresa's Health Centre (Nairobi North)</option> <option value="13225">St Teresa's Parish Dispensary</option> <option value="11072">St Teresia Medical Clinic</option> <option value="11825">St Terezia Medical Clinic</option> <option value="17503">St Thadeus Medical Clinic</option> <option value="11826">St Theresa Dispensary</option> <option value="12303">St Theresa Kiirua Hospital (Kiirua)</option> <option value="12774">St Theresa Thatha Mission Dispensary</option> <option value="12775">St Theresas Riiji Health Centre</option> <option value="15667">St Therese Dispensary</option> <option value="15668">St Theresia of Jesus</option> <option value="18435">St Thomas Maternity</option> <option value="18501">St Thomas The Apostle Athi Catholic Dispensary</option> <option value="11073">St Triza Medical Clinic</option> <option value="19021">St Trizah Medical Clinic</option> <option value="15669">St Ursula Dispensary</option> <option value="11828">St Valeria Medical Clinic</option> <option value="17413">St Veronica</option> <option value="11074">St Veronica Dispensary Mukurweini</option> <option value="18409">St Veronica EDARP Clinic</option> <option value="15670">St Victors Medical Clinic</option> <option value="13230">St Vincent Catholic Clinic</option> <option value="14127">St Vincent Clinic (Kisumu East)</option> <option value="13229">St Vincent Clinic (Nairobi East)</option> <option value="14128">St Vincents De Paul Health Centre</option> <option value="18909">Stadia Medical Clinic</option> <option value="19028">Stage View Medical Clinic</option> <option value="16527">Stanbridge Care Centre</option> <option value="11829">Star Hospital</option> <option value="14129">Star Maternity & Nursing Home</option> <option value="15671">Star Medical Clinic</option> <option value="11830">Star of Good Hope Medical Clinic</option> <option value="20180">Star-Heal Medical Clinic</option> <option value="19422">Starehe Boys Centre School Clinic</option> <option value="16358">Starlight Mti Moja</option> <option value="15672">Starlite Medical Clinic</option> <option value="19276">Stars General Medical Clinic</option> <option value="13231">State House Clinic</option> <option value="11831">State House Dispensary (Mombasa)</option> <option value="13232">State House Dispensary (Nairobi)</option> <option value="15673">State House Dispensary (Nakuru)</option> <option value="15674">State Lodge Dispensary</option> <option value="18018">Station Side Makupa Clinic</option> <option value="11832">Stella Maris Medical Clinic</option> <option value="15675">Stgetrude Dispensary</option> <option value="12776">Stone Athi Medical Clinic</option> <option value="17700">Stops Medical Clinic Kenya Ltd</option> <option value="18973">Stralight Medical Clinic</option> <option value="18574">Strathmore University Medical Centre</option> <option value="15676">Stream of Life Clinic</option> <option value="14130">Suba District Hospital</option> <option value="17790">Subati Medical Clinic</option> <option value="16528">Subira Medical Clinic</option> <option value="15677">Subukia Dispensary (Kipkelion)</option> <option value="15678">Subukia Health Centre</option> <option value="15679">Subuku Dispensary (Molo)</option> <option value="11076">Subuku Dispensary (Nyandarua North)</option> <option value="11077">Subuku Medical Clinic</option> <option value="19381">Success Medical Services</option> <option value="14204">Sucos Hospital</option> <option value="16776">Sugarbaker Memorial Clinic</option> <option value="17331">Sugoi A Dispensary</option> <option value="15680">Sugoi B Dispensary</option> <option value="17093">Sugumerga Dispensary</option> <option value="14131">Suguta Health Centre</option> <option value="15681">Suguta Marmar Catholic Dispensary</option> <option value="15682">Suguta Marmar Health Centre</option> <option value="12018">Suleman Farooq Memorial Centre</option> <option value="12777">Sultan Hamud Sub District Hospital</option> <option value="14132">Sulwe Clinic</option> <option value="14133">Sumba Community Dispensary</option> <option value="18614">Sumba Medical Clinic</option> <option value="15683">Sumbeiywet Dispensary</option> <option value="15684">Sumeiyon Dispensary</option> <option value="15685">Sumek Dispensary</option> <option value="11078">Summit Medical Clinic</option> <option value="16316">Sumoiyot Dispensary</option> <option value="11833">Sun N' Sand Medical Clinic</option> <option value="15687">Sun-Shine Medical Clinic</option> <option value="15688">Sun-Shine Medical Clinic Annex</option> <option value="14134">Suna Nursing and Maternity Home</option> <option value="14135">Suna Rabuor Dispensary</option> <option value="14136">Suna Ragana Dispensary</option> <option value="18281">Sunbeam Medical Centre</option> <option value="17175">Sunga Dispensary</option> <option value="11079">Sunny Medical Clinic (Nyeri North)</option> <option value="11080">Sunny Medical Clinic (Nyeri South)</option> <option value="14137">Sunrise Clinic</option> <option value="15686">Sunrise Evans Hospital</option> <option value="12778">Sunrise Medical Clinic</option> <option value="16304">Sunrise Medical Clinic (Mandera East)</option> <option value="19826">Sunset Medical Clinic</option> <option value="18138">Sunshine Family Health Medicare Centre</option> <option value="19351">Sunshine Medical & Diagnostic Centre (Nairobi)</option> <option value="19530">Sunshine Medical Centre</option> <option value="19052">Sunshine Medical Clinic</option> <option value="17827">Sunshine Medical Clinic (Kwale)</option> <option value="18438">Sunton CFW Clinic</option> <option value="19739">Sunview Maternity & Nursing Home</option> <option value="15689">Supat Med Clinic</option> <option value="19941">Super Drug Nursing Home</option> <option value="11835">Super Medical Clinic</option> <option value="13233">Supkem (Liverpool)</option> <option value="19355">Supreme Health Care (Ktda House-Nairobi)</option> <option value="19852">Supreme Medical Clinic</option> <option value="19637">Sure Drug Medical Clinic</option> <option value="11347">Surgery Clinic</option> <option value="11081">Surgical Consultant (Muranga South)</option> <option value="17964">Surgury Clinic</option> <option value="16407">Sururu Health Centre (CDF)</option> <option value="15690">Survey Dispensary</option> <option value="17686">Susamed Medical Clinic</option> <option value="17103">Sutyechun Dispensary</option> <option value="15692">Suwerwa Health Centre</option> <option value="15693">Swari Model Health Centre</option> <option value="15694">Sweet Waters Dispensary</option> <option value="14138">Swindon Clinic</option> <option value="19023">Swiss Cottage Hospital</option> <option value="19394">Swop Clinic</option> <option value="19719">Swop Kawangware</option> <option value="19271">Swop Korogocho</option> <option value="19429">Swop Outreach Project Clinic</option> <option value="18896">Swop Thika Road</option> <option value="16993">Syathani (Kyathani) Dispensary</option> <option value="20118">Syokimau Medical Centre</option> <option value="18819">Syokimau Medical Services</option> <option value="18551">Syokithumbi Dispensary</option> <option value="12780">Syongila (ACK) Dispensary</option> <option value="12781">Syongila Dispensary</option> <option value="12782">Syumile Dispensary</option> <option value="14139">Tabaka Mission Hospital</option> <option value="15695">Tabare Dispensary</option> <option value="12783">Tabasamu Medical Clinic</option> <option value="19779">Tabby Plaza ENT & Orthopaedic Clinic</option> <option value="13234">Tabitha Medical Clinic</option> <option value="15696">Tabolwa Dispensary</option> <option value="15697">Tabuga (PCEA) Dispensary</option> <option value="18010">Tachasis Dispensary</option> <option value="15698">Tachasis Mission Dispensary</option> <option value="19027">Tahidi Nursing Home</option> <option value="17969">Taiba Medical Centre</option> <option value="17020">Taito Community Dispensary</option> <option value="15699">Taito Tea Dispensary</option> <option value="13445">Takaba District Hospital</option> <option value="16314">Takaba Nomadic Mobile</option> <option value="11836">Takaungu Dispensary</option> <option value="14140">Takawiri Dispensary</option> <option value="15700">Takitech Dispensary</option> <option value="17170">Tala Dispensary</option> <option value="12784">Tala Medical Services</option> <option value="15701">Talai Dispensary</option> <option value="20058">Talau Dispensary</option> <option value="15702">Talek Health Centre</option> <option value="19199">Tamam Medical Clinic</option> <option value="15703">Tambach Sub-District Hospital</option> <option value="16332">Tambach T T College Dispensary</option> <option value="11083">Tambaya Dispensary</option> <option value="11084">Tambaya Medical Clinic</option> <option value="15704">Tamkal Dispensary</option> <option value="16148">Tamlega Dispensary</option> <option value="15705">Tamough Health Centre</option> <option value="14141">Tamu Health Centre</option> <option value="11085">Tana Clinic</option> <option value="12785">Tana Medical Clinic (Machakos)</option> <option value="12786">Tana Medical Clinic (Yatta)</option> <option value="16149">Tanaka Nursing Home</option> <option value="18112">Tanganyika Medical Clinic</option> <option value="15706">Tangasir Dispensary</option> <option value="15707">Tangulbei Health Centre</option> <option value="15708">Tapach Dispensary</option> <option value="17706">Taqwa Nursing Home</option> <option value="14142">Taracha Dispensary</option> <option value="14143">Taragai Dispensary</option> <option value="15710">Tarakwa Dispensary</option> <option value="17255">Tarakwa Dispensary (Eldoret West)</option> <option value="14144">Taranganya Dispensary</option> <option value="11837">Tarasaa Catholic Dispensary</option> <option value="13446">Tarbaj Health Centre</option> <option value="11838">Taru Dispensary</option> <option value="18258">Tasia Family Medical Centre</option> <option value="19152">Tasneem Pharmacy</option> <option value="11086">Tata Hannah (African Christian Churches and School</option> <option value="11087">Tatu Dispensary</option> <option value="17801">Taunet Dispensary</option> <option value="11839">Tausa Health Centre</option> <option value="11840">Taveta District Hospital</option> <option value="11841">Taveta Meditech Centre</option> <option value="12787">Tawa Sub-Distrct Hospial</option> <option value="19044">Tawaheed Community Medical Clinic</option> <option value="19043">Tawaheed Community Nursing Home</option> <option value="19042">Tawakal Medical Clinic</option> <option value="16305">Tawakal Medical Clinic (Mandera East)</option> <option value="16551">Tawakal Medical Clinic (Msambweni)</option> <option value="19061">Tawakal Medical Clinic and Laboratory Services</option> <option value="11843">Tawfiq Muslim Hospital</option> <option value="11844">Tawheed Dispensary</option> <option value="17975">Tayabi Medical and Dental Centre</option> <option value="19283">Tazama Dentel Clinic</option> <option value="11845">Tchamalo Medical Clinic</option> <option value="11846">Tchundwa Dispensary</option> <option value="14473">Tdmp Tangulbei Dispensary</option> <option value="15711">Tea Resaerch Dispensary</option> <option value="16471">Tea Research Foundation Dispensary</option> <option value="13235">Teachers Service Commission</option> <option value="15712">Tebei Dispensary</option> <option value="15713">Tebesonik Dispensary</option> <option value="12788">Tefran Community Clinic</option> <option value="15714">Tegat Health Centre</option> <option value="15715">Tegego Dispensary</option> <option value="12789">Tei Wa Yesu Health Centre</option> <option value="17315">Telanet</option> <option value="13236">Tena (PCEA) Clinic</option> <option value="15716">Tenden Dispensary</option> <option value="19230">Tender Loving Care CFW Clinic</option> <option value="15717">Tenduet Dispensary</option> <option value="17859">Tendwet Dispensary</option> <option value="15718">Tenges Health Centre</option> <option value="15719">Tenwek Mission Hospital</option> <option value="15720">Tenwek Mobile</option> <option value="15721">Teret Dispensary</option> <option value="12773">Tereza D'Lima Dispensary</option> <option value="16417">Terige Dispensary (CDF)</option> <option value="19624">Terminus Medical Clinic (Dandora)</option> <option value="20185">Terry G Medical Clinic</option> <option value="19184">Tesco Pharmacy Limited</option> <option value="16150">Teso District Hospital</option> <option value="18418">Tesorie Dispensary</option> <option value="11095">Tevica Medical Clinic</option> <option value="18058">Tewa Medical Clinic</option> <option value="11088">Tewas Medical Clinic</option> <option value="11848">Tezo Community Health Care</option> <option value="12792">Thaana Nzau Dispensary</option> <option value="11089">Thaara Medical Clinic</option> <option value="18569">Thaene Medical Clinic</option> <option value="19146">Thamare Dispensary</option> <option value="12793">Thanantu Faith Clinic Dispensary</option> <option value="11090">Thangathi Health Centre</option> <option value="11091">Thangathi Health Clinic</option> <option value="12795">Tharaka District Hospital</option> <option value="12794">Tharaka Health Centre</option> <option value="18328">The Aga Khan University Hospital (Meru)</option> <option value="19376">The Arcade Medical Centre</option> <option value="18304">The Co-Operative University College of Kenya Dispe</option> <option value="19247">The Hanna Medicare Centre</option> <option value="18041">The Haven Medical Clinic</option> <option value="18415">The Hope Medical Centre-Awasi</option> <option value="13004">The Karen Hospital</option> <option value="18327">The Karen Hospital (Meru)</option> <option value="18461">The Kitui Marternity and Nursing Home</option> <option value="19434">The Mater Embakasi Clinic</option> <option value="19543">The Mater Hospital (Westlands)</option> <option value="17657">The Mater Hospital Buruburu</option> <option value="13074">The Mater Hospital Mukuru</option> <option value="18476">The Mater Hospital Thika Satellite</option> <option value="19101">The Nairobi Hospital Out-Patient Centre Galeria</option> <option value="19066">The Nyali Childrens Hospital (Mikindani)</option> <option value="17966">The Omari Project</option> <option value="20103">The Savannah Health Services Ltd</option> <option value="16555">Theere Health Centre</option> <option value="18636">Theluji Pharmacy Ltd</option> <option value="15722">Thessalia Health Centre</option> <option value="11092">Thiba Health Centre</option> <option value="11093">Thigio Dispensary (Kiambu West)</option> <option value="15723">Thigio Dispensary (Laikipia West)</option> <option value="18578">Thigirichi Mukui</option> <option value="10138">Thika Arcade Health Services</option> <option value="16754">Thika High School For The Blind</option> <option value="11094">Thika Level 5 Hospital</option> <option value="11096">Thika Medical Clinic ENT</option> <option value="11097">Thika Nursing Home</option> <option value="16755">Thika Primary School For The Blind Clinic</option> <option value="17950">Thika Road Health Services Ltd (Kasarani)</option> <option value="17968">Thika Sasa Centre</option> <option value="16278">Thim Lich Dispensary</option> <option value="16228">Thimangiri Medical Clinic</option> <option value="20073">Thimjope Dispensary</option> <option value="12796">Thinu Health Centre</option> <option value="12797">Thitani Health Centre</option> <option value="12798">Thitha Dispensary</option> <option value="17909">Thome Catholic Dispensary</option> <option value="18029">Thome Clinic</option> <option value="16859">Thonzweni Dispensary</option> <option value="11098">Three In One Clinic</option> <option value="11099">Thuita Clinic</option> <option value="11100">Thumaita (ACK) Dispensary</option> <option value="17066">Thumberera Dispensary</option> <option value="11101">Thunguma Medical Clinic</option> <option value="11102">Thunguri Medical Clinic</option> <option value="11849">Thureya Medical Clinic</option> <option value="11103">Thuthi Medical Clinic</option> <option value="19795">Thuti Medical Clinic</option> <option value="18646">Thuura Health Care</option> <option value="18699">Thuura Health Care</option> <option value="19141">Thuuru Dispensary</option> <option value="20126">Thwake Community Dispensary</option> <option value="20004">Tian Dispensary</option> <option value="19298">Tibaland Chemistry & Lab</option> <option value="16177">Tico - Bao VCT</option> <option value="12799">Tigania Hospital</option> <option value="16151">Tigoi Health Centre</option> <option value="11104">Tigoni District Hospital</option> <option value="12800">Tii Dispensary</option> <option value="16368">Tiinei Dispensary</option> <option value="12801">Timau Catholic Dispensary</option> <option value="19127">Timau Dental Clinic</option> <option value="16634">Timau Integrated Medical Centre</option> <option value="12802">Timau Sub-District Hospital</option> <option value="15724">Timboiywo Dispensary</option> <option value="11851">Timboni Community Dispensary</option> <option value="15725">Timboroa Health Centre</option> <option value="17759">Timbwani Medical Clinic</option> <option value="11105">Time Health Care</option> <option value="11106">Times Clinic</option> <option value="16319">Times Medical Clinic</option> <option value="15726">Tinderet Tea Dispensary</option> <option value="14145">Tindereti Dispensary</option> <option value="15728">Tinet Dispensary</option> <option value="15727">Tinet Dispensary (Koibatek)</option> <option value="14148">Ting'wangi Health Centre</option> <option value="14146">Tinga Health Centre</option> <option value="11107">Tinganga (PCEA) Dispensary</option> <option value="17094">Tinganga Catholic Dispensary</option> <option value="14147">Tingare Dispensary</option> <option value="18746">Tionybei Medical Clinic</option> <option value="15729">Tirimionin Dispensary</option> <option value="15730">Tirriondonin Dispensary</option> <option value="17176">Tiryo Dispensary (Nandi Central)</option> <option value="14149">Tisinye Dispensary</option> <option value="11852">Titila (AIC) Dispensary</option> <option value="12803">Tiva Dispensary</option> <option value="11853">Tiwi Rhtc</option> <option value="15731">Todonyang Dispensary</option> <option value="16315">Tolilet Dispensary</option> <option value="11108">Tom King's Laboratory</option> <option value="15732">Tom Mboya Dispensary</option> <option value="14150">Tom Mboya Memorial Health Centre</option> <option value="18286">Tom Mboyaschool Cp Clinic</option> <option value="14151">Tombe Health Centre (Manga)</option> <option value="14152">Tonga Health Centre</option> <option value="16152">Tongaren Health Centre</option> <option value="15733">Toniok Dispensary</option> <option value="11854">Tononoka Administration Police Dispensary & VCT</option> <option value="18343">Tononoka CPC</option> <option value="16682">Tonymed Medical Clinic</option> <option value="11109">Tonys Medical Clinic</option> <option value="15306">Top Choice Maternity and Nursing Home</option> <option value="17946">Top Hill Medical Centre</option> <option value="15734">Top Station Dispensary</option> <option value="18189">Topcare Nursing Home</option> <option value="17022">Toretmoi Dispensary</option> <option value="19612">Toric's Nursing Home</option> <option value="15735">Torongo Health Centre</option> <option value="16675">Toror Medical Clinic</option> <option value="15736">Tororek Dispensary</option> <option value="15737">Torosei Dispensary</option> <option value="15738">Tot Sub-District Hospital</option> <option value="16403">Total Dispensary</option> <option value="18356">Totoo Medical Clinic</option> <option value="18544">Touch of Health - Well-Being Centre</option> <option value="18957">Towba Clinic</option> <option value="19045">Towfiq Medical Clinic</option> <option value="11855">Town Centre Medical Clinic</option> <option value="16635">Town Clinic Laboratory</option> <option value="14153">Town Hall Dispensary</option> <option value="16636">Town Medical Clinic</option> <option value="12804">Township Dispensary (Kitui)</option> <option value="11110">Trans-Saharan Medical Clinic</option> <option value="13237">Transcom Medical Services</option> <option value="18105">Transcon Wendo Medical Services</option> <option value="15739">Transmara District Hospital</option> <option value="15740">Transmara Medicare</option> <option value="11856">Travellers Medical Clinic</option> <option value="11111">Trinity Afya Centre</option> <option value="16750">Trinity Clinic (Ruiru)</option> <option value="17237">Trinity Githiga (ACK) Dispensary</option> <option value="13238">Trinity Medical Care Health Centre</option> <option value="11858">Trinity Medical Clinic (Kilindini)</option> <option value="20164">Trinity Mission Hospital</option> <option value="19444">Trocare Medical Clinic</option> <option value="19126">Tropical Medical Centre</option> <option value="17767">Tropical Medical Clinic</option> <option value="18335">True Light Medical Clinic</option> <option value="11859">Tsangatsini Dispensary</option> <option value="12805">Tseikuru Sub-District Hospital</option> <option value="11861">Tudor District Hospital (Mombasa)</option> <option value="11862">Tudor Health Care</option> <option value="19069">Tudor Healthcare Services (Mikindani)</option> <option value="18016">Tudor Nursing Home</option> <option value="15741">Tugen Estate Dispensary</option> <option value="16333">Tugumoi Dispensary</option> <option value="15742">Tugumoi Dispensary</option> <option value="16153">Tuikut Dispensary</option> <option value="15743">Tuina Dipensary</option> <option value="15744">Tuiyobei Dispensary</option> <option value="17873">Tuiyoluk Dispensary</option> <option value="15745">Tuiyotich Dispensary</option> <option value="19046">Tulah Medical Services</option> <option value="13447">Tulatula Dispensary</option> <option value="12806">Tulia Dispensary</option> <option value="12807">Tulila Dispensary</option> <option value="12808">Tulimani Dispensary</option> <option value="17403">Tulwet Dispensary</option> <option value="15746">Tulwet Dispensary (Buret)</option> <option value="16393">Tulwet Dispensary (Kuresoi)</option> <option value="15747">Tulwet Health Centre</option> <option value="20190">Tumaini Africa</option> <option value="19647">Tumaini Baraka Medical Clinic</option> <option value="18285">Tumaini Childrens Home Out Patient Clinic</option> <option value="15748">Tumaini Clinic</option> <option value="17371">Tumaini Clinic (Kiambu West)</option> <option value="11115">Tumaini Clinic (Kigumo)</option> <option value="11116">Tumaini Clinic (Mwea)</option> <option value="19092">Tumaini Clinic Voi</option> <option value="16511">Tumaini Clinic/Laboratory</option> <option value="18557">Tumaini DiSC - Asembo Bay</option> <option value="17914">Tumaini Health Services (Makindu)</option> <option value="17917">Tumaini Maternity and Nursing Home (Kibwezi)</option> <option value="16637">Tumaini Medial Clinic (Miriga Mieru West)</option> <option value="16651">Tumaini Medical Centre</option> <option value="17385">Tumaini Medical Centre</option> <option value="18296">Tumaini Medical Centre (Tezo)</option> <option value="19972">Tumaini Medical Centre-Komothai</option> <option value="11863">Tumaini Medical Cl Dzitsoni</option> <option value="11865">Tumaini Medical Clinic</option> <option value="16638">Tumaini Medical Clinic (Buuri)</option> <option value="18478">Tumaini Medical Clinic (Kabaa)</option> <option value="11864">Tumaini Medical Clinic (Kilindini)</option> <option value="12810">Tumaini Medical Clinic (Kitui)</option> <option value="11117">Tumaini Medical Clinic (Makuyu)</option> <option value="16529">Tumaini Medical Clinic (Malindi)</option> <option value="16204">Tumaini Medical Clinic (Marsabit)</option> <option value="18704">Tumaini Medical Clinic (Meru)</option> <option value="11118">Tumaini Medical Clinic (Nyandarua North)</option> <option value="11119">Tumaini Medical Clinic (Nyeri North)</option> <option value="11120">Tumaini Medical Clinic (Nyeri South)</option> <option value="19138">Tumaini Medical Clinic (Tezo)</option> <option value="17866">Tumaini Medical Clinic (Thika West)</option> <option value="15749">Tumaini Medical Clinic (Turkana Central)</option> <option value="15750">Tumaini Medical Clinic (Wareng)</option> <option value="18710">Tumaini Medical Clinic (Yatta)</option> <option value="16639">Tumaini Medical Clinic Laboratory</option> <option value="19183">Tumaini Medical Clinic Yatta</option> <option value="11121">Tumaini Medicare (Kandara)</option> <option value="18771">Tumaini Multi - Counselling Centre</option> <option value="19396">Tumaini Mwangaza ( Korogocho)</option> <option value="11122">Tumaini National Youth Service Dispensary</option> <option value="12809">Tumaini Rh Clinic</option> <option value="15751">Tumoi Dispensary</option> <option value="11124">Tumutumu (PCEA) Hospital</option> <option value="11123">Tumutumu Community Medical Centre</option> <option value="12811">Tunawanjali Clinic</option> <option value="12812">Tungutu Dispensary</option> <option value="11125">Tunuku Medical Clinic</option> <option value="12813">Tunyai Dispensary</option> <option value="15752">Tunyo Dispensary</option> <option value="17620">Tuonane VCT</option> <option value="12814">Tupendane Dispensary</option> <option value="11126">Turasha Dispensary</option> <option value="12815">Turbi Dispensary (Marsabit North)</option> <option value="16154">Turbo Forest Dispensary</option> <option value="15753">Turbo Health Centre</option> <option value="16820">Turi (PCEA) Dispensary</option> <option value="18103">Turi AIC Health Centre</option> <option value="16406">Turi Dispensary (CDF)</option> <option value="15754">Turkwel Dispensary (Loima)</option> <option value="15755">Turkwel Health Centre</option> <option value="11127">Turuturu Dispensary</option> <option value="19553">Tusker Dental Laboratory Services & Laboratory</option> <option value="19555">Tusker House Medical Centre</option> <option value="11129">Tuthu Dispensary</option> <option value="18809">Tutini Dispensary</option> <option value="15756">Tuturung Dispensary</option> <option value="15757">Tuum Dispensary</option> <option value="18109">Tuungane</option> <option value="18503">Tuungane Centre Awendo</option> <option value="18502">Tuungane Centre Rongo</option> <option value="16663">Tuungane Youth Centre (Kisumu East)</option> <option value="14154">Tuungane Youth Centre (Mbita)</option> <option value="17166">Tuungane Youth Transition Centre</option> <option value="12816">Tuuru Catholic Health Centre</option> <option value="12817">Tuvaani Dispensary</option> <option value="16351">Twiga Dispensary</option> <option value="12818">Twimyua Dispensary</option> <option value="19133">Twins Bell</option> <option value="16828">Twins Bell Clinic</option> <option value="12819">Tyaa Kamuthale Dispensary</option> <option value="19652">Tyaa Medical Clinic</option> <option value="17614">Uamani Dispensary</option> <option value="15758">Uasin Gishu District Hospital</option> <option value="11130">Ucheru Community Health Centre</option> <option value="14155">Ugina Health Centre</option> <option value="12820">Ugweri Disp</option> <option value="17532">Uhembo Dispensary</option> <option value="13239">Uhuru Camp Dispensary (O P Admin Police)</option> <option value="15759">Uhuru Dispensary</option> <option value="17404">Uhuru Presitige Health Care</option> <option value="14107">Uhuyi Dispensary</option> <option value="12821">Ukasi Dispensary</option> <option value="18090">Ukasi Model Health Centre</option> <option value="12822">Ukia Dispensary</option> <option value="11867">Ukunda Diani Catholic Dispensary</option> <option value="16552">Ukunda Medical Clinic</option> <option value="16553">Ukunda Primary Health Care Dispensary</option> <option value="18215">Ukuu MCK Dispensary</option> <option value="14156">Ukwala Health Centre</option> <option value="11131">Ukweli Medical Clinic</option> <option value="14157">Ulanda Dispensary</option> <option value="11132">Ultra Sound & X-Ray Clinic</option> <option value="14158">Ulungo Dispensary</option> <option value="13799">Uluthe Dispensary</option> <option value="16791">Umala Dispensary</option> <option value="17530">Umer Dispensary</option> <option value="19607">Umma CBO</option> <option value="13240">Umoja Health Centre</option> <option value="13241">Umoja Hospital</option> <option value="20187">Umoja III Medical Centre</option> <option value="11133">Umoja Medical Clinic</option> <option value="15760">Umoja Medical Clinic (Eldoret West)</option> <option value="18727">Umoja Medical Clinic (Imenti North)</option> <option value="11134">Umoja Medical Clinic (Muranga North)</option> <option value="19627">Umoja Medical Clinic- Bombolulu</option> <option value="18233">Umoja VCT Centre Stand Alone</option> <option value="12823">Ung'atu Dispensary</option> <option value="15761">Unilever Central Hospital</option> <option value="16181">Union Medical Dispensary</option> <option value="18036">Unique Medical Clinic (Moyale)</option> <option value="11135">Unique Tambaya Medical Clinic</option> <option value="17032">Unison Medical Clinic</option> <option value="19948">United States International University VCT</option> <option value="19399">Unity Health Care</option> <option value="18334">Unity Nursing Home</option> <option value="18907">Universal M Clinic</option> <option value="12824">Universal Medical Clinic</option> <option value="19710">Universal Medical Clinic (Nyeri North)</option> <option value="19292">Universal Medical Clinic (Samburu)</option> <option value="17634">University of East Africa-Baraton VCT</option> <option value="18352">University of Nairobi Centre of HIV Prevention and</option> <option value="13242">University of Nairobi Dispensary</option> <option value="19527">University of Nairobi Health Services</option> <option value="20098">University of Nairobi Institute of Tropical and Infections Disease (UNITID)</option> <option value="18518">University of Nairobi Marps Project Clinic</option> <option value="20203">University of Nairobi Marps Project Mwingi</option> <option value="18427">University of Nairobi Staff Students Clinic</option> <option value="11136">Unjiru Health Centre</option> <option value="19285">Unmet Health Foundation</option> <option value="18345">Uon Thika Drop In Centre Ii (Chivpr)</option> <option value="17243">Upec Chebaiywa Dispensary</option> <option value="18726">Upendo Clinic</option> <option value="12825">Upendo Clinic (Imenti North)</option> <option value="16155">Upendo Clinic (Navakholo)</option> <option value="19476">Upendo Clinic Makadara</option> <option value="13243">Upendo Dispensary</option> <option value="11870">Upendo Health Care Clinic</option> <option value="19367">Upendo Medica Clinic</option> <option value="11137">Upendo Medical Care</option> <option value="19375">Upendo Medical Centre (Githurai 44)</option> <option value="19507">Upendo Medical Clinic</option> <option value="12826">Upendo Medical Clinic (Kitui)</option> <option value="16640">Upendo Medical Laboratory</option> <option value="18062">Upendo VCT Centre</option> <option value="11138">Uplands Forest Dispensary</option> <option value="15763">Upper Solai Health Centre</option> <option value="17183">Uradi Health Centre</option> <option value="18142">Urafiki Medical Clinic</option> <option value="12828">Uran Health Centre</option> <option value="14159">Urenga Dispensary</option> <option value="12829">Uringu Health Centre</option> <option value="14160">Uriri Dispensary</option> <option value="14161">Uriri Health Centre</option> <option value="11139">Uruku Dispensary</option> <option value="12830">Uruku GK Dispensary</option> <option value="12831">Uruku Health Centre</option> <option value="19931">Uruku Integrated Medical Clinic</option> <option value="14162">Usao Health Centre</option> <option value="14163">Usenge Dispensary</option> <option value="13245">Ushirika Medical Clinic</option> <option value="18949">Ushirika Medical Clinic Maara</option> <option value="18364">Usiani Dispensary</option> <option value="14164">Usigu Dispensary</option> <option value="16664">Usoma Dispensary</option> <option value="12832">Usueni Dispensary</option> <option value="11873">Utange Dispensary</option> <option value="17838">Utangwa Dispensary</option> <option value="13448">Utawala Dispensary</option> <option value="18464">Utawala Estate Health Centre</option> <option value="11141">Uthiru Dispensary</option> <option value="19796">Utugi (Olk) Medical Clinic</option> <option value="12833">Utugi Medical Clinic</option> <option value="18193">Utugi Medical Clinic Kitengela</option> <option value="12834">Utulivu Clinic</option> <option value="20110">Utuneni Dispensary</option> <option value="17441">Uvete Dispensary</option> <option value="17845">Uviluni Dispensary</option> <option value="16741">Uvoosyo Medical Clinic</option> <option value="14165">Uyawi Dispensary</option> <option value="13846">Uzima Clinic</option> <option value="13246">Uzima Dispensary</option> <option value="19614">Uzima Medical Cliinic</option> <option value="17436">Uzima Medical Clinic</option> <option value="19159">Uzima Medical Clinic (Chuka)</option> <option value="17565">Uzima Medical Clinic (Githamba)</option> <option value="12835">Uzima Medical Clinic (Imenti South)</option> <option value="11876">Uzima Medical Clinic (Kilifi)</option> <option value="11877">Uzima Medical Clinic (Lamu)</option> <option value="11878">Uzima Medical Clinic (Malindi)</option> <option value="19140">Uzima Medical Clinic (Meru)</option> <option value="18243">Uzima Medical Clinic (Nandi Central)</option> <option value="11144">Uzima Medical Clinic (Nyeri North)</option> <option value="11145">Uzima Medical Clinic (Thika)</option> <option value="19049">Uzima Medical Clinic Namanga</option> <option value="18635">Uzima Medical Services</option> <option value="18621">Uzima Medicare Clinic</option> <option value="17956">Uzima VCT Centre</option> <option value="15764">Valley Hospital</option> <option value="17546">Van Den Berg Clinic</option> <option value="11879">Vanga Health Centre</option> <option value="18747">Vegpro Delamere Pivot Medical Clinic (Naivasha)</option> <option value="18202">Vegpro In House Clinic</option> <option value="17887">Venoma Medical Clinic</option> <option value="14166">Verna Health Centre</option> <option value="14167">Viagenco Medical Centre</option> <option value="18619">Vichabem Medical Clinic</option> <option value="18141">Vicodec Medical Clinic</option> <option value="16262">Victoria Clinic</option> <option value="18136">Victoria Medical Centre</option> <option value="18108">Victoria Medical Clinic</option> <option value="17376">Victoria Sub District Hospital</option> <option value="16156">Victorious Living Ministries (Vlm) Dispensary</option> <option value="11146">Victors Medical Clinic</option> <option value="19911">Victory &Hope Medical Clinic Services</option> <option value="13247">Victory Hospital</option> <option value="11147">Victory Medical Clinic</option> <option value="19491">Victory Medicare</option> <option value="17491">Victory Revival Medical Clinic</option> <option value="19667">Viebe MC</option> <option value="11148">Viewpoint Clinic</option> <option value="20157">Vigarace Health services</option> <option value="19086">Vigombonyi SDA Clinic</option> <option value="11880">Vigurungani Dispensary</option> <option value="16157">Vihiga District Hosptial</option> <option value="16158">Vihiga Health Centre</option> <option value="20160">Vijana Against Aids and drug Abuse (juja)</option> <option value="20174">Vikunga Dispensary</option> <option value="16545">Vikwatani Community Medical Clinic</option> <option value="18657">Village Hope Core International</option> <option value="18092">Vines Kenya Htc Centre</option> <option value="15765">Vinet Medical Clinic</option> <option value="18741">Vipawa Medical Services</option> <option value="11881">Vipingo Rural Demonstration Health Centre</option> <option value="19485">Vips Health Servises</option> <option value="17689">Viragoni Dispensary</option> <option value="20175">Virhembe Medical Clinic</option> <option value="11149">Virmo Clinic</option> <option value="11882">Visa Oshwol Dispensary</option> <option value="16190">Vishakani Dispensary</option> <option value="19758">Vision Dental Clinic</option> <option value="19810">Vision Medical Clinic</option> <option value="11150">Vision Medical Clinic</option> <option value="17849">Vision Medical Clinic Butere</option> <option value="13248">Vision Peoples Inter Health Centre</option> <option value="11883">Vitengeni Health Centre</option> <option value="11884">Vitsangalaweni Dispensary</option> <option value="17687">Viva Afya Kayole</option> <option value="19630">Viva Afya Medical Clinic</option> <option value="18368">Viva Afya Medical Clinic (Matopeni)</option> <option value="19089">Voi Dental</option> <option value="17704">Voi Medical Centre</option> <option value="19090">Voi Medical Clinix</option> <option value="17703">Voi Roadside Clinic</option> <option value="17442">Vololo Dispensary</option> <option value="17778">Voo Health Centre</option> <option value="18826">Vorhca Stand Alone</option> <option value="18323">Vostrum Clinic</option> <option value="17937">Vote Dispensary</option> <option value="15766">Vuma VCT</option> <option value="17915">Vumilia Medical Clinic</option> <option value="11886">Vutakaka Medical Clinic</option> <option value="11887">Vyongwani Dispensary</option> <option value="12837">Vyulya Dispensary</option> <option value="18967">Wa Tonny Clinic</option> <option value="11151">Wa-Anne Medical Clinic</option> <option value="15773">Wa-Sammy Medical Clinic</option> <option value="11888">Waa Health Centre</option> <option value="12838">Wachoro Dispensary</option> <option value="16808">Wachoro Medical Clinic</option> <option value="16792">Wagai Dispensary</option> <option value="17820">Wagalla Health Centre</option> <option value="13449">Wagalla Health Centre</option> <option value="13450">Wagberi Dispensary</option> <option value="17438">Wagoro Dispensary (Rarieda)</option> <option value="14168">Wagwe Health Centre</option> <option value="18123">Wahome Health Clinic</option> <option value="11152">Wahundura Dispensary</option> <option value="17841">Waia Dispensary</option> <option value="11153">Waiganjo Clinic</option> <option value="11154">Waihara Medical Clinic</option> <option value="11155">Wairungu Clinic</option> <option value="12839">Waita Health Centre</option> <option value="13249">Waithaka Health Centre</option> <option value="13451">Wajir Bor Health Centre</option> <option value="13452">Wajir District Hospital</option> <option value="17743">Wajir Girls Dispensary</option> <option value="19181">Wajir Medical City Clinic</option> <option value="13453">Wajir Medical Clinic</option> <option value="18166">Wajir North Nomadic Clinic</option> <option value="18651">Wajir Tb Manyatta Sub - District Hospital</option> <option value="11156">Waka Maternity Home</option> <option value="11157">Wakagori Medicalclinic</option> <option value="11158">Wakamata Dispensary</option> <option value="16479">Wakhungu Dispensary</option> <option value="13250">Wakibe Clinic</option> <option value="17045">Wakor Dispensary</option> <option value="14169">Wakula Health Centre</option> <option value="12840">Walda Health Centre</option> <option value="11889">Waldena Dispensary</option> <option value="17923">Walking With Maasai Community Health Clinic (Olort</option> <option value="18164">Walmer Eye Clinic</option> <option value="19943">Waluku Dispensary</option> <option value="11159">Wama Medical Clinic (Kiganjo)</option> <option value="11160">Wama Medical Clinic (Mukaro)</option> <option value="15767">Wama Nursing Home</option> <option value="11161">Wamagana Health Centre</option> <option value="11162">Wamagana Medical Clinic</option> <option value="15768">Wamba Health Centre</option> <option value="18229">Wamboo Dispensary</option> <option value="11164">Wamumu Dispensary</option> <option value="13251">Wamunga Health Clinic</option> <option value="12841">Wamunyu Health Centre</option> <option value="15770">Wanainchi Jamii Materinty and Nursing Home</option> <option value="15265">Wanainchi Medical Clinic</option> <option value="19692">Wanainchi Medical Clinic</option> <option value="11165">Wananchi Clinic</option> <option value="20082">Wananchi Clinic Githunguri- Kiambu</option> <option value="16641">Wananchi Health Services</option> <option value="16642">Wananchi Health Services Laboratory</option> <option value="11166">Wananchi Medical Centre</option> <option value="17414">Wananchi Medical Clinic</option> <option value="15771">Wananchi Medical Clinic (Kajiado)</option> <option value="11890">Wananchi Medical Clinic (Kilindini)</option> <option value="18117">Wananchi Medical Clinic (Mwingi)</option> <option value="20101">Wananchi Medical Clinic (Nyambari)</option> <option value="19789">Wananchi Medical Clinic (Nyandarua)</option> <option value="18933">Wananchi Medical Clinic Maara</option> <option value="11891">Wananchi Nursing Home</option> <option value="11167">Wandumbi Dispensary</option> <option value="11168">Wanduta Medical Clinic</option> <option value="18283">Wanganga Health Centre</option> <option value="11169">Wangema (African Christian Churches and Schools) C</option> <option value="11170">Wangige Health Centre</option> <option value="20074">Wangiya Dispensary</option> <option value="15772">Wangu Maternity Home</option> <option value="13252">Wangu Medical Clinic</option> <option value="11171">Wanjengi Dispensary</option> <option value="11172">Wanjerere Dispensary</option> <option value="11173">Wanjohi Health Centre</option> <option value="17420">Wanyaga Community Dispensary</option> <option value="12842">Wanzoa Dispensary</option> <option value="16813">Warankara Health Centre</option> <option value="13253">Warazo Clinic</option> <option value="19711">Warazo Jet Catholic Dispensary</option> <option value="11175">Warazo Medical Clinic (Ruiru)</option> <option value="11176">Warazo Rural Health Centre</option> <option value="13455">Wargadud Health Centre</option> <option value="19047">Warsan Health Services</option> <option value="11177">Warui Medical Clinic</option> <option value="17031">Wasammy Medical Clinic</option> <option value="17096">Waseges Dispensary</option> <option value="11892">Wasini Dispensary</option> <option value="17774">Waso AIPCA Dispensary (Isiolo)</option> <option value="16953">Waso Rongai Dispensary</option> <option value="16159">Wasundi Clinic</option> <option value="11893">Watamu (SDA) Dispensary</option> <option value="11894">Watamu Community Health Care</option> <option value="11895">Watamu Dispensary</option> <option value="11897">Watamu Hospital</option> <option value="11896">Watamu Maternity and Nursing Home</option> <option value="18012">Watanu SDA Dispensary</option> <option value="14170">Wath Onger Dispensary</option> <option value="12843">Watoto Clinic</option> <option value="11178">Watuka Dispensary</option> <option value="14171">Waware Dispensary</option> <option value="11898">Wayani Medical Clinic (Changamwe)</option> <option value="17667">Waye Godha Dispensary</option> <option value="15775">Wayside Clinic</option> <option value="19284">Wayside Medical & Dental Clinic</option> <option value="17080">Wayu Boru</option> <option value="11900">Wayu Dispensary</option> <option value="16160">Webuye Health Centre</option> <option value="16161">Webuye Hospital</option> <option value="16162">Webuye Nursing Home</option> <option value="16163">Webuye Surgical</option> <option value="11179">Wega Medical Clinic</option> <option value="15776">Wei Dispensary</option> <option value="11180">Weithaga (ACK) Dispensary</option> <option value="20100">Wekoye Medical Clinic</option> <option value="16780">Welfare Medical Clinic</option> <option value="11181">Wellness Medical Clinic</option> <option value="18860">Wellness Program KWS Hq</option> <option value="11901">Wema Catholic Dispensary</option> <option value="11902">Wema Centre Medical Clinic</option> <option value="13255">Wema CFW Clinic</option> <option value="19855">Wema Laboratory</option> <option value="17394">Wema Medical Clinic</option> <option value="19036">Wema Medical Clinic B</option> <option value="18383">Wema Medical Clinic-Mshomoroni</option> <option value="13256">Wema Nursing Home</option> <option value="19997">Wema Private Clinic</option> <option value="18234">Wendani Medical Services</option> <option value="11182">Wendiga Dispensary</option> <option value="11903">Wenje Dispensary</option> <option value="13257">Wentworth Hospital</option> <option value="15777">Weonia Dispensary</option> <option value="12845">Weru Dispensary</option> <option value="11183">Weru Health Centre (Nyandarua South)</option> <option value="11904">Werugha Health Centre</option> <option value="15778">Wesley Health Centre</option> <option value="18918">West End Medical Solutions</option> <option value="15780">West Gate Dispensary</option> <option value="15779">West Health Centre</option> <option value="19211">West Wing Diagnostic and Laboratory</option> <option value="20027">Westgates Medical Centre</option> <option value="19663">Westlands District Health Management Team</option> <option value="11905">Westlands Health Care Services</option> <option value="13258">Westlands Health Centre</option> <option value="19494">Westlands Medical Centre</option> <option value="18455">Westwood Medical Centre</option> <option value="11906">Wesu District Hospital</option> <option value="18448">What Matters Mission Dispensary</option> <option value="18834">Wheel Kenya Medical Clinic</option> <option value="17487">Whemis</option> <option value="19524">Wide Medical Services</option> <option value="14172">Wiga Dispensary</option> <option value="12846">Wii Dispensary</option> <option value="16925">Wikithuki Dispensary</option> <option value="19909">Wikondiek Dispensary</option> <option value="17543">Wildfire Clinic</option> <option value="20017">Wilwinns Nursing Home</option> <option value="19947">Wima Medical Clinic (Samburu East)</option> <option value="15781">Winas Medical Clinic</option> <option value="12848">Wingemi Health Centre</option> <option value="14173">Winjo Dispensary</option> <option value="15782">Winners Medical Clinic</option> <option value="12849">Winzyeei Health Centre</option> <option value="14174">Wire Dispensary</option> <option value="17889">Withare Dispensary</option> <option value="11186">Witima Health Centre</option> <option value="11907">Witu Health Centre</option> <option value="15783">Wiyeta Dispensary</option> <option value="15784">Wiyumiririe Dispensary</option> <option value="19048">Women Initiative Health Services</option> <option value="18873">Wondeni Dispensary</option> <option value="12850">Woodlands Hospital</option> <option value="13259">Woodley Clinic</option> <option value="16514">Woodpark Med Clinic</option> <option value="18214">Woodshaven Medical Centre</option> <option value="13260">Woodstreet Nursing Home</option> <option value="19067">Word of Faith Church Dispensary</option> <option value="18253">World Provision Centre VCT (Athi River)</option> <option value="17906">World Provision VCT</option> <option value="19889">World Provision Wellness Centre</option> <option value="11188">Wote Clinic</option> <option value="18133">Wote Health Clinic</option> <option value="18144">Wote Medical Clinic</option> <option value="18203">Wumiisyo Medical Clinic</option> <option value="19735">Wundanyi GK Prisons</option> <option value="11908">Wundanyi Sub-District Hospital</option> <option value="11909">Wusi-Wutesia (ACK) Dispensary</option> <option value="19502">X Press Medical Clinic</option> <option value="14487">X-Cellent Medical Centre</option> <option value="19854">X-Ray Screening Centre</option> <option value="18492">Xposha VCT Centre</option> <option value="17598">Yaathi Dispensary</option> <option value="17579">Yaballo Dispensary</option> <option value="13456">Yabicho Health Centre</option> <option value="16279">Yago Dispensary</option> <option value="12851">Yakalia Dispensary</option> <option value="17069">Yala Dispensary</option> <option value="14175">Yala Sub-District Hospital</option> <option value="17505">Yanja Medical Clinic</option> <option value="12852">Yanzuu Health Centre</option> <option value="13457">Yassin Clinic</option> <option value="16652">Yathui Dispensary</option> <option value="18206">Yatoi</option> <option value="12853">Yatta Health Centre</option> <option value="12854">Yatwa Dispensary</option> <option value="15785">Yatya Dispensary</option> <option value="16963">Yekanga Dispensary</option> <option value="11911">Yeshua Medical</option> <option value="17550">Yikivumbu Dispensary</option> <option value="12855">Yimwaa Dispensary</option> <option value="17584">Yofak VCT</option> <option value="14176">Yokia Dispensary</option> <option value="12856">Yongela Dispensary</option> <option value="18677">Yoonye Dispensary</option> <option value="17690">Young Generation Centre Dispensary (Med 25)</option> <option value="13458">Young Muslim Dispensary</option> <option value="16165">Your Family Clinic</option> <option value="20124">Youth Empowerment Center Ngong</option> <option value="13459">Yumbis Dispensary</option> <option value="12857">Yumbu Dispensary</option> <option value="20087">Yunasi</option> <option value="12858">Yururu Medical Clinic</option> <option value="15786">Ywalateke Dispensary</option> <option value="19020">Zahri Medical Clinic</option> <option value="11189">Zaina Dispensary</option> <option value="11190">Zakary Ndegwa Laboratory</option> <option value="13460">Zakma Medical Clinic</option> <option value="15787">Zam Zam Medical Services</option> <option value="17863">Zaro Nursing Clinic (Likoni)</option> <option value="11192">Zawadi Clinic</option> <option value="11193">Zena Roses Clinic</option> <option value="18517">Zennith Community Project</option> <option value="18374">Ziani Dispensary</option> <option value="17892">Zigira (Community) Dispensary</option> <option value="19273">Zimerbreeze Medical Centre</option> <option value="19378">Zimma Health Care</option> <option value="13261">Zimmerman Medical Dispensary</option> <option value="13262">Zinduka Clinic</option> <option value="11912">Zion Community Clinic</option> <option value="12859">Zion Medical Clinic</option> <option value="11913">Ziwa La Ng'ombe Medical Clinic</option> <option value="17220">Ziwa SDA</option> <option value="15788">Ziwa Sub-District Hospital</option> <option value="11915">Ziwani Dispensary</option> <option value="12860">Zombe (AIC) Dispensary</option> <option value="16997">Zombe Catholic Dispensary</option> </select> </td></tr> <tr><td colspan="2" align="right"><input type="submit" value="Proceed" /></td></tr> </table> </form> </p> </div> </div> </div> <!-- END ROW-FLUID--> </body> </html> <file_sep>/htdocs/catalog/rejection_phase_delete.php <?php # # Deletes a test category from DB //# Sets disabled flag to true instead of deleting the record //# This maintains info for samples that were linked to this test type previously # include("../includes/db_lib.php"); $saved_session = SessionUtil::save(); $saved_db = DbUtil::switchToGlobal(); $rejection_phase_id = $_REQUEST['rp']; SpecimenRejectionPhases::deleteById($rejection_phase_id); DbUtil::switchRestore($saved_db); SessionUtil::restore($saved_session); header("Location: catalog.php?show_sr=1"); ?> <file_sep>/htdocs/api/Net.old/HL7/Types/CWE.php <?php class Net_HL7_Types_CWE { private $identifier; private $text; private $nameOfCodingSystem; private $alternateIdentifier; private $alternateText; private $nameOfAlternateCodingSystem; private $codingSystemVersionId; private $alternateCodingSystemVersionId; private $originalText; public function __construct($components) { $this->identifier = (empty($components[0])) ? "" : $components[0]; $this->text = (empty($components[1])) ? "" : $components[1]; $this->nameOfCodingSystem = (empty($components[2])) ? "" : $components[2]; $this->alternateIdentifier = (empty($components[3])) ? "" : $components[3]; $this->alternateText = (empty($components[4])) ? "" : $components[4]; $this->nameOfAlternateCodingSystem = (empty($components[5])) ? "" : $components[5]; $this->codingSystemVersionId = (empty($components[6])) ? "" : $components[6]; $this->alternateCodingSystemVersionId = (empty($components[7])) ? "" : $components[7]; $this->originalText = (empty($components[8])) ? "" : $components[8]; } /** * @return Net_HL7_Types_CWE */ public static function template() { return new Net_HL7_Types_CWE(array()); } /** * @return array */ public function toArray() { $components = array(); $components[0] = $this->identifier; $components[1] = $this->text; $components[2] = $this->nameOfCodingSystem; $components[3] = $this->alternateIdentifier; $components[4] = $this->alternateText; $components[5] = $this->nameOfAlternateCodingSystem; $components[6] = $this->codingSystemVersionId; $components[7] = $this->alternateCodingSystemVersionId; $components[8] = $this->originalText; return $components; } /** * @param $identifier string */ public function setIdentifier($identifier) { $this->identifier = $identifier; } /** * @return string */ public function getIdentifier() { return $this->identifier; } /** * @param $text string */ public function setText($text) { $this->text = $text; } /** * @return string */ public function getText() { return $this->text; } /** * @param $nameOfCodingSystem string */ public function setNameOfCodingSystem($nameOfCodingSystem) { $this->nameOfCodingSystem = $nameOfCodingSystem; } /** * @return string */ public function getNameOfCodingSystem() { return $this->nameOfCodingSystem; } /** * @param $alternateIdentifier string */ public function setAlternateIdentifier($alternateIdentifier) { $this->alternateIdentifier = $alternateIdentifier; } /** * @return string */ public function getAlternateIdentifier() { return $this->alternateIdentifier; } /** * @param $alternateText string */ public function setAlternateText($alternateText) { $this->alternateText = $alternateText; } /** * @return string */ public function getAlternateText() { return $this->alternateText; } /** * @param $nameOfAlternateCodingSystem string */ public function setNameOfAlternateCodingSystem($nameOfAlternateCodingSystem) { $this->nameOfAlternateCodingSystem = $nameOfAlternateCodingSystem; } /** * @return string */ public function getNameOfAlternateCodingSystem() { return $this->nameOfAlternateCodingSystem; } /** * @param $codingSystemVersionId string */ public function setCodingSystemVersionId($codingSystemVersionId) { $this->codingSystemVersionId = $codingSystemVersionId; } /** * @return string */ public function getCodingSystemVersionId() { return $this->codingSystemVersionId; } /** * @param $alternateCodingSystemVersionId string */ public function setAlternateCodingSystemVersionId($alternateCodingSystemVersionId) { $this->alternateCodingSystemVersionId = $alternateCodingSystemVersionId; } /** * @return string */ public function getAlternateCodingSystemVersionId() { return $this->alternateCodingSystemVersionId; } /** * @param $originalText string */ public function setOriginalText($originalText) { $this->originalText = $originalText; } /** * @return string */ public function getOriginalText() { return $this->originalText; } } ?> <file_sep>/htdocs/api/get_dashboard_stats.php <?php require_once "authenticate.php"; $date = date('Y-m-d H:i:s'); if ($_REQUEST['date']) $date = $_REQUEST['date']; $rcd = array(); $rcd['location'] = $_REQUEST['location']; $rcd['dashboard_type'] = $_REQUEST['dashboard_type']; $rcd['date'] = $date; $result = API::get_dashboard_stats($rcd); if($result < 1) echo $result; else echo json_encode($result); ?> <file_sep>/htdocs/api/get_worklist.php <?php require_once "authenticate.php"; $params = array(); $params['type'] = $_REQUEST['type']; $params['location'] = $_REQUEST['department']; $status = API::get_worklist($params); echo json_encode($status); ?><file_sep>/htdocs/users/change_pwd.php <?php # # Changes password for the user # Called from edit_profile.php # include("redirect.php"); session_start(); include("includes/db_lib.php"); $username = $_SESSION['username']; $old_password = $_REQUEST['old_password']; $new_password = $_REQUEST['new_password']; # Check if old password matches confirm_and_change_password($username,$old_password,$new_password); ?> <file_sep>/htdocs/reports/reports_consumption.php <?php # # Main page for showing consumption report and options to export # Called via POST from reports.php # include("redirect.php"); include("includes/db_lib.php"); include("includes/stats_lib.php"); include("includes/script_elems.php"); LangUtil::setPageId("reports"); include("../users/accesslist.php"); if(!(isLoggedIn(get_user_by_id($_SESSION['user_id'])))) header( 'Location: home.php' ); $script_elems = new ScriptElems(); $script_elems->enableJQuery(); $script_elems->enableTableSorter(); ?> <html> <head> <script type="text/javascript" src="js/table2CSV.js"></script> <script type='text/javascript'> var curr_orientation = 0; function export_as_word(div_id) { var html_data = $('#'+div_id).html(); $('#word_data').attr("value", html_data); //$('#export_word_form').submit(); $('#word_format_form').submit(); } function export_as_pdf(div_id) { var content = $('#'+div_id).html(); $('#pdf_data').attr("value", content); $('#pdf_format_form').submit(); } function export_as_txt(div_id) { var content = $('#'+div_id).html(); $('#txt_data').attr("value", content); $('#txt_format_form').submit(); } function export_as_csv(table_id, table_id2) { var content = $('#'+table_id).table2CSV({delivery:'value'}) + '\n\n' + $('#'+table_id2).table2CSV({delivery:'value'}); $("#csv_data").val(content); $('#csv_format_form').submit(); } function print_content(div_id) { var DocumentContainer = document.getElementById(div_id); var WindowObject = window.open("", "PrintWindow", "toolbars=no,scrollbars=yes,status=no,resizable=yes"); var html_code = DocumentContainer.innerHTML; var do_landscape = $("input[name='do_landscape']:checked").attr("value"); if(do_landscape == "Y") html_code += "<style type='text/css'> #report_config_content {-moz-transform: rotate(-90deg) translate(-300px); } </style>"; WindowObject.document.writeln(DocumentContainer.innerHTML); WindowObject.document.close(); WindowObject.focus(); WindowObject.print(); WindowObject.close(); //javascript:window.print(); } $(document).ready(function(){ $('#report_content_table1').tablesorter(); $("input[name='do_landscape']").click( function() { change_orientation(); }); change_orientation(); }); function change_orientation() { var do_landscape = $("input[name='do_landscape']:checked").attr("value"); if(do_landscape == "Y" && curr_orientation == 0) { $('#report_config_content').removeClass("portrait_content"); $('#report_config_content').addClass("landscape_content"); curr_orientation = 1; } if(do_landscape == "N" && curr_orientation == 1) { $('#report_config_content').removeClass("landscape_content"); $('#report_config_content').addClass("portrait_content"); curr_orientation = 0; } } </script> </head> <body> <div id='report_content'> <link rel='stylesheet' type='text/css' href='css/table_print.css' /> <style type='text/css'> div.editable { /*padding: 2px 2px 2px 2px;*/ margin-top: 2px; width:900px; height:20px; } div.editable input { width:700px; } div#printhead { position: fixed; top: 0; left: 0; width: 100%; height: 100%; padding-bottom: 5em; margin-bottom: 100px; display:none; } @media all { .page-break { display:none; } } @media print { #options_header { display:none; } /* div#printhead { display: block; } */ div#docbody { margin-top: 5em; } } .landscape_content {-moz-transform: rotate(90deg) translate(600px); } .portrait_content {-moz-transform: translate(1px); rotate(-90deg) } </style> <!--form name='word_format_form' id='word_format_form' action='export_word.php' method='post' target='_blank'> <input type='hidden' name='data' value='' id='word_data' /> <input type='hidden' name='lab_id' value='<?php echo $lab_config_id; ?>' id='lab_id'> <input type='button' onclick="javascript:print_content('report_content');" value='<?php echo LangUtil::$generalTerms['CMD_PRINT']; ?>'></input> &nbsp;&nbsp;&nbsp;&nbsp; <!-- <input type='button' onclick="javascript:export_as_word();" value='<?php echo LangUtil::$generalTerms['CMD_EXPORTWORD']; ?>'></input> --> &nbsp;&nbsp;&nbsp;&nbsp; <!-- <input type='button' onclick="javascript:window.close();" value='<?php echo LangUtil::$generalTerms['CMD_CLOSEPAGE']; ?>'></input> --> </form--> <form name='word_format_form' id='word_format_form' action='export_word.php' method='post' target='_blank'> <input type='hidden' name='data' value='' id='word_data' /> </form> <form name='pdf_format_form' id='pdf_format_form' action='export_pdf.php' method='post' target='_blank'> <input type='hidden' name='data' value='' id='pdf_data' /> </form> <form name='txt_format_form' id='txt_format_form' action='export_txt.php' method='post' target='_blank'> <input type='hidden' name='data' value='' id='txt_data' /> </form> <form name='csv_format_form' id='csv_format_form' action='export_csv.php' method='post' target='_blank'> <input type='hidden' name='csv_data' id='csv_data'> </form> <input type='radio' name='do_landscape' value='N' <?php //if($report_config->landscape == false) echo " checked "; echo " checked "; ?>>Portrait</input> &nbsp;&nbsp; <input type='radio' name='do_landscape' value='Y' <?php //if($report_config->landscape == true) echo " checked "; ?>>Landscape</input>&nbsp;&nbsp; <input type='button' onclick="javascript:print_content('report_config_content');" value='<?php echo LangUtil::$generalTerms['CMD_PRINT']; ?>'></input> &nbsp;&nbsp; <!-- <input type='button' onclick="javascript:export_as_word('report_config_content');" value='<?php echo LangUtil::$generalTerms['CMD_EXPORTWORD']; ?>'></input> --> &nbsp;&nbsp; <input type='button' onclick="javascript:export_as_pdf('report_config_content');" value='<?php echo LangUtil::$generalTerms['CMD_EXPORTPDF']; ?>'></input> &nbsp;&nbsp; <!--input type='button' onclick="javascript:export_as_txt('export_content');" value='<?php echo LangUtil::$generalTerms['CMD_EXPORTTXT']; ?>'></input> &nbsp;&nbsp;--> <input type='button' onclick="javascript:export_as_csv('report_content_header', 'report_content_table1');" value='<?php echo LangUtil::$generalTerms['CMD_EXPORTCSV']; ?>'></input> &nbsp;&nbsp; <!-- <input type='button' onclick="javascript:window.close();" value='<?php echo LangUtil::$generalTerms['CMD_CLOSEPAGE']; ?>'></input> --> &nbsp;&nbsp; <hr> <div id='report_config_content'> <b><?php echo "Consumption Report"; ?></b> <br><br> <?php $lab_config_id = $_REQUEST['location']; $lab_config = LabConfig::getById($lab_config_id); if($lab_config == null) { echo LangUtil::$generalTerms['MSG_NOTFOUND']; return; } $date_from = $_REQUEST['from-report-date']; $date_to = $_REQUEST['to-report-date']; $uiinfo = "from=".$date_from."&to=".$date_to; putUILog('reports_consumption', $uiinfo, basename($_SERVER['REQUEST_URI'], ".php"), 'X', 'X', 'X'); # Fetch site-wide settings //$site_settings = DiseaseReport::getByKeys($lab_config->id, 0, 0); $configArray = getTestCountGroupedConfig($lab_config->id); //echo "--".$configArray['group_by_age'].$configArray['group_by_gender'].$configArray['age_groups'].$configArray['measure_groups'].$configArray['measure_id']."<br>"; # Fetch report configuration $byAge = $configArray['group_by_age']; $age_group_list = decodeAgeGroups($configArray['age_groups']); $byGender = $configArray['group_by_gender']; $bySection = $configArray['measure_id']; $combo = $configArray['test_type_id']; // 1 - registered, 2 - completed, 3 - completed / pending /* $byAge = 1; $bySection = 1; $byGender = 0; */ //$age_group_list = $site_settings->getAgeGroupAsList(); $query = 'SELECT a.name AS Reagent, Unit, SUM(quantity_used) AS `Qty. Consumed` FROM inv_reagent a INNER JOIN inv_usage b ON a.id=b.reagent_id WHERE date_of_use BETWEEN \''.$date_from.'\' AND \''.$date_to.'\' GROUP BY a.id'; global $con; $result = mysql_query($query, $con); ?> <table id='report_content_header' class="print_entry_border draggable"> <tbody> <tr> <td><?php echo LangUtil::$generalTerms['FACILITY']; ?>:</td> <td><?php echo $lab_config->getSiteName(); ?></td> </tr> <tr> <td><?php echo LangUtil::$pageTerms['REPORT_PERIOD']; ?>:</td> <td> <?php if($date_from == $date_to) { echo DateLib::mysqlToString($date_from); } else { echo DateLib::mysqlToString($date_from)." to ".DateLib::mysqlToString($date_to); } ?> </td> </tr> </tbody> </table> <?php $table_css = "style='padding: .3em; border: 1px black solid; font-size:14px;'"; ?> <br> <table id='report_content_table1' class="print_entry_border draggable"> <?php if ($result){ echo '<thead><tr>'; for ($counter=0; $counter<mysql_num_fields($result); $counter++){ echo '<th>'.mysql_field_name($result, $counter).'</th>'; } echo '</tr></thead><tbody>'; while($row = mysql_fetch_assoc($result)){ echo '<tr><td>'.implode($row, '</td><td>').'</tr>'; } echo '</tbody>'; } ?> </table> <br><br><br> ............................................ </div> </div> </body> </html><file_sep>/htdocs/quality_control/quality_control_new.php <?php # # Main page for adding new test category # include("redirect.php"); include("includes/header.php"); require_once("includes/page_elems.php"); require_once("includes/script_elems.php"); LangUtil::setPageId("quality"); ?> <br> <div class="portlet box green"> <div class="portlet-title"> <h4><i class="icon-reorder"></i><?php echo "New Quality Control"; ?></h4> <div class="tools"> <a href="javascript:;" class="collapse"></a> <a href="javascript:;" class="reload"></a> </div> </div> <div class="portlet-body"> <p style="text-align: right;"><a href='#' title='Tips'><?php echo "Use the wizard to define a quality control form"; ?></a> |<a href='quality.php?show_qc=1'><?php echo LangUtil::$generalTerms['CMD_CANCEL']; ?></a></p> <div class='pretty_box'> <!-- BEGIN FORM--> <form action="#" class="form-horizontal" /> <fieldset> <legend>Quality Control Properties</legend> <div class="control-group"> <label class="control-label"><?php echo "Quality Control Name"; ?></label> <div class="controls"> <input type="text" name="qc_name" id="qc_name" class="span6 m-wrap" /> </div> </div> <div class="control-group"> <label class="control-label"><?php echo "Instrument or Reagent or Lot"; ?></label> <div class="controls"> <select name="qc_inst" id="qc_inst" data-placeholder="Instrument/Reagent/Lot" class="chosen span6" tabindex="-1"> <!-- id="selS0V"--> <option value="" /> <optgroup label="CYTOMETRY"> <option />BD FacsFlow </optgroup> <optgroup label="BIOCHEMISTRY"> <option />Udichem </optgroup> <optgroup label="HAEMATOLOGY"> <option />Celtac </optgroup> </select> </div> </div> <div class="control-group"> <label class="control-label"><?php echo "Quality Control Description"; ?></label> <div class="controls"> <textarea name="qc_desc" id="qc_desc" class="span6 m-wrap" rows="3"></textarea> </div> </div> <div class="form-actions"> <button type="submit" onclick="check_input()" class="btn blue">Submit</button> <button type="button" class="btn">Cancel</button> </div> </fieldset> </form> <!-- END FORM--> <fieldset> <!--legend>Quality Control Form Definition</legend> <br /> <div id="my_form_builder"> </div--> <div id='quality_control_help' style='display:none'> <small> Use Ctrl+F to search easily through the list. Ctrl+F will prompt a box where you can enter the test category you are looking for. </small> </div> </div> <script type='text/javascript'> function check_input() { // Validate var qc_name = $('#qc_name').val(); if(qc_name == "") { alert("<?php echo "Error: Missing quality control name"; ?>"); return; } var qc_inst = $('#qc_inst').val(); if(qc_inst == "") { alert("<?php echo "Error: Missing instrument/reagent/log"; ?>"); return; } // All OK $('#new_quality_control_category_form').submit(); } </script> <?php $script_elems->enableFormBuilder(); //$script_elems->enableFacebox(); //$script_elems->enableBootstrap();*/ include("includes/footer.php"); ?><file_sep>/htdocs/catalog/rejection_reason_delete.php <?php # # Deletes a test category from DB //# Sets disabled flag to true instead of deleting the record //# This maintains info for samples that were linked to this test type previously # include("../includes/db_lib.php"); $saved_session = SessionUtil::save(); $saved_db = DbUtil::switchToGlobal(); $rejection_reason_id = $_REQUEST['rr']; SpecimenRejectionReasons::deleteById($rejection_reason_id); DbUtil::switchRestore($saved_db); SessionUtil::restore($saved_session); header("Location: catalog.php?show_sr=1"); ?> <file_sep>/htdocs/api/Net.old/HL7/Types/Types.php <?php include_once("CE.php"); include_once("CQ.php"); include_once("CWE.php"); include_once("CX.php"); include_once("ED.php"); include_once("EI.php"); include_once("EIP.php"); include_once("FN.php"); include_once("HD.php"); include_once("MSG.php"); include_once("PL.php"); include_once("PRL.php"); include_once("PT.php"); include_once("RP.php"); include_once("SAD.php"); include_once("SN.php"); include_once("TS.php"); include_once("VID.php"); include_once("XAD.php"); include_once("XCN.php"); include_once("XON.php"); include_once("XPN.php"); ?> <file_sep>/htdocs/catalog/rejection_reason_updated.php <?php # # Shows confirmation for rejection reason update # include("redirect.php"); include("includes/header.php"); LangUtil::setPageId("catalog"); ?> <br> <b><?php echo "Specimen Rejection Reason Updated"; ?></b> | <a href='catalog.php?show_rp=1'>&laquo; <?php echo LangUtil::$pageTerms['CMD_BACK_TOCATALOG']; ?></a> <br><br> <?php $rejection_reason = get_rejection_reason_by_id($_REQUEST['rr']); $page_elems->getRejectionReasonInfo($rejection_reason->description); include("includes/footer.php"); ?><file_sep>/htdocs/api/update_credentials.php <?php include "../includes/db_lib.php"; $username = null; $password = <PASSWORD>; $new_password = <PASSWORD>; $rnew_password = <PASSWORD>; // mod_php if (isset($_SERVER['PHP_AUTH_USER'])) { $username = $_SERVER['PHP_AUTH_USER']; $password = $_SERVER['PHP_AUTH_PW']; // most other servers } elseif (isset($_SERVER['HTTP_AUTHORIZATION'])) { if (strpos(strtolower($_SERVER['HTTP_AUTHORIZATION']),'basic')===0) list($username,$password) = explode(':',base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6))); } if (isset($_REQUEST['new_password'])) $new_password = $_REQUEST['new_password']; if (isset($_REQUEST['repeated_password'])) $rnew_password = $_REQUEST['repeated_password']; $error_msg = array("ERROR"=>"Error: Invalid credentials!"); if (is_null($username)) { header('WWW-Authenticate: Basic realm="My Realm"'); header('HTTP/1.0 401 Unauthorized'); echo json_encode($error_msg); die(); } else { $tok = API::login($username, $password); if($tok < 0){ echo json_encode($error_msg); die(); }else{ $user_exists = check_user_exists($username); if($user_exists == false){ $error_msg = array("ERROR"=>"Error: User does not exist!"); echo json_encode($error_msg); die(); }else if($new_password != $rnew_password){ $error_msg = array("ERROR"=>"Error: Repeat password mismatch!"); echo json_encode($error_msg); die(); }else{ change_user_password($username, $new_password); echo json_encode(array("MSG"=>"Update successful")); } } } ?> <file_sep>/htdocs/api/submitHl7Order.php <?php include("Net/HL7/Message.php"); include("Net/HL7/Types/Types.php"); # parse an OML_O21 message if(!isset($_REQUEST['hl7'])) { echo -2; return; } // WHEN DONE WITH TESTING UNCOMMENT THIS LINE //$omlString=$_REQUEST['hl7']; // WHEN DONE WITH TESTING COMMENT OUT THIS LINE $omlString="MSH|^~&||KCH^2.16.840.1.113883.3.5986.2.15^ISO||KCH^2.16.840.1.113883.3.5986.2.15^ISO|20150126145826||OML^O21^OML_O21|20150126145826|T|2.5\rPID|1||P17000012293||Doe^John^Q^Jr||19641004|M\rORC||||||||||1^Super^User|||^^^^^^^^MEDICINE||||||||KCH\rTQ1|1||||||||S\rOBR|1|||626-2^MICROORGANISM IDENTIFIED:PRID:PT:THRT:NOM:THROAT CULTURE^LOINC^78335^Throat Culture^L|||20150126145826||||||Rule out diagnosis|||439234^Moyo^Chris\rSPM|1|||THRT^Throat\r"; $omlMsg = new Net_HL7_Message($omlString); $sendingFacility = (new Net_HL7_Types_XON($omlMsg->getSegmentByName("MSH")->getField(4)))->getUniversalId(); $receivingFacility = (new Net_HL7_Types_XON($omlMsg->getSegmentByName("MSH")->getField(6)))->getUniversalId(); $patientId = (new Net_HL7_Types_CX($omlMsg->getSegmentByName("PID")->getField(3)))->getIdNumber(); $patientName = $omlMsg->getSegmentByName("PID")->getField(5); $patientDateOfBirth = $omlMsg->getSegmentByName("PID")->getField(7); $gender = $omlMsg->getSegmentByName("PID")->getField(8)[0]; $messageType = $omlMsg->getSegmentByName("MSH")->getField(9)[2]; $processingId = $omlMsg->getSegmentByName("MSH")->getField(11)[0]; $labAccessionNumber = $omlMsg->getSegmentByName("SPM")->getFields(2)[0]; $typeOfSample = $omlMsg->getSegmentByName("SPM")->getField(4)[0]; $priority = $omlMsg->getSegmentByName("TQ1")->getField(9); $enterer = $omlMsg->getSegmentByName("ORC")->getField(10); $entererLocation = $omlMsg->getSegmentByName("ORC")->getField(13); $testCode = $omlMsg->getSegmentByName("OBR")->getField(4)[0]; $sampleTimeStamp = $omlMsg->getSegmentByName("OBR")->getField(7); $reasonPerformed = $omlMsg->getSegmentByName("OBR")->getField(13); $orderer = $omlMsg->getSegmentByName("OBR")->getField(16); $facilitySiteCode = $omlMsg->getSegmentByName("ORC")->getField(21); // COMMENT OUT THE FOLLOWING LINES WHEN DONE TESTING echo "Sending Facility: " . $sendingFacility ."<br/>\n"; echo "Receiving Facility: " . $receivingFacility ."<br/>\n"; echo "Patient ID: " . $patientId ."<br/>\n"; echo "Patient Name:" . $patientName . "<br/>\n"; echo "Date of Birth: " . $patientDateOfBirth . "<br/>\n"; echo "Gender: " . $gender . "<br\>\n"; echo "Message Type: " . $messageType . "<br/>\n"; echo "Processing ID: " . $processingId . "<br/>\n"; echo "Lab ID / Accession Number: " . $labAccessionNumber . "<br/>\n"; echo "Type of Sample: " . $typeOfSample . "<br/>\n"; echo "Priority: " . $priority . "<br/>\n"; echo "EntererName: " . $enterer . "<br/>\n"; echo "Enterer's Location: " .$entererLocation . "<br/>\n"; echo "Test Code: " . $testCode . "<br/>\n"; echo "Timestamp of when sample collected: " . $sampleTimeStamp . "<br/>\n"; echo "Reason test performed: " . $reasonPerformed . "<br/>\n"; echo "Who ordered the test: " . $orderer . "<br/>\n"; echo "Health Facility Site Code and Name: " . $facilitySiteCode . "<br/>\n"; // ADD YOUR DATABASE CREATE ORDER CODE HERE USING THE VARIABLES ABOVE ?><file_sep>/htdocs/catalog/test_panel_add.php <?php # # Adds a new test panel to catalog in DB # include("redirect.php"); include("includes/db_lib.php"); $ky = null; foreach ($_REQUEST AS $key=>$value){ if(preg_match("/tp_type/", $key)){ $test_type_id = explode('_', $key)[2]; $ky = $test_type_id; if($value == 'on'){ $query_update = "UPDATE test_type SET is_panel = 1 WHERE test_type_id = $test_type_id"; query_update($query_update); } } } if ($ky != null){ header("location: test_panel_edit.php?tid=$ky"); }else { header("location: catalog.php?show_tp=1"); } ?><file_sep>/htdocs/api/orders_search.php <?php require_once "authenticate.php"; $search_string = ''; if ($_REQUEST['search_string']) $search_string = $_REQUEST['search_string']; $result = API::orders_search($search_string); if($result < 1) echo $result; else echo json_encode($result); ?> <file_sep>/htdocs/api/get_status.php <?php require_once "authenticate.php"; $params = array(); $params['accession_num'] = $_REQUEST['accession_number']; if ($_REQUEST['test_name']) $params['test_name'] = $_REQUEST['test_name']; $status = API::getStatus($params); if (strlen($status) < 1 ) echo "Unknown"; else echo $status; ?><file_sep>/htdocs/api/get_lab_sections.php <?php require_once "authenticate.php"; //$specimen_id = $_REQUEST['specimen_id']; //$tok = $_REQUEST['tok']; $result = API::get_lab_sections(); if($result < 1) echo $result; else echo json_encode($result); ?> <file_sep>/htdocs/api/test_type_actions.php <?php require_once "authenticate.php"; $enable = $_REQUEST['enable']; $tid = $_REQUEST['tid']; $result = -2; if ($_REQUEST['action'] == 'test_type_disable') { $result = API::disableTest($tid, $enable); } if($result < 1) echo $result; else echo json_encode($result); ?> <file_sep>/htdocs/api/get_tables.php <?php require_once "authenticate.php"; include("../includes/page_elems.php"); $page_elems = new PageElems(); $result = ""; if ($_REQUEST['table_type'] == 'test_types') $result = $page_elems->getTestTypeTable(127); if ($_REQUEST['table_type'] == 'test_type_info'){ $tid = $_REQUEST['tid']; $name_query = "SELECT name FROM test_type WHERE test_type_id = $tid"; $name_obj = query_associative_one($name_query); if($name_obj){ $result = $page_elems->getTestTypeInfo($name_obj['name']); } } if ($_REQUEST['table_type'] == 'test_type_input_info'){ $tid = $_REQUEST['tid']; $name_query = "SELECT name FROM test_type WHERE test_type_id = $tid"; $name_obj = query_associative_one($name_query); if($name_obj){ $result = $page_elems->getTestTypeInputInfo($name_obj['name']); }else{ $result = $page_elems->getTestTypeInputInfoGeneric(); } } if ($_REQUEST['table_type'] == 'test_categories') $result = $page_elems->getTestCategorySelect(); if ($_REQUEST['table_type'] == 'disabled_status') $result = API::disabledStatus(); if ($_REQUEST['table_type'] == 'compatible_specimens'){ $tid = $_REQUEST['tid']; $result = $page_elems->getSpecimenTypeCheckboxes(127, false, $tid); } if ($_REQUEST['table_type'] == 'measures_data'){ $tid = (int)$_REQUEST['tid']; if ($tid && $tid > 0){ $result = API::get_test_type_measures_all($tid); }else{ $result = array(); } } if ($_REQUEST['table_type'] == 'tb_report'){ $tid = $_REQUEST['tid']; $result = API::tb_report($_REQUEST['year']); } if ($_REQUEST['table_type'] == 'tb_report_mq'){ $tid = $_REQUEST['tid']; $result = API::tb_report_mq($_REQUEST['start_date'], $_REQUEST['end_date']); } if($result < 1) echo $result; else echo json_encode($result); ?> <file_sep>/htdocs/ajax/results_update.php~ <?php # # Marks submitted results as verified, with corrections if any # Called via ajax from verify_results.php # include("../includes/db_lib.php"); $result=$_REQUEST['ver_result']; $comment=$_REQUEST['ver_comment']; $testid=$_REQUEST['testId']; # Helper function # TODO: Move this to Test::verifyAndUpdate() function verify_and_update($result, $comment, $testid) { global $con; # Update with corrections and mark as verified $query_verify ="UPDATE test SET comments='$comment' WHERE test_id=$testid"; mysql_query($query_verify); } verify_and_update($result, $comment, $testid); ?> <div class='sidetip_nopos'> Results verified and updated. </div> <file_sep>/htdocs/api/Net.old/HL7/Messages/OML_O21.php <?php require_once "Net/HL7/Message.php"; /** * Class Net_HL7_Messages_OML_O21 * * Construct a blank OML_O21 message */ class Net_HL7_Messages_OML_O21 { /** * @return Net_HL7_Message * */ public static function template() { return new Net_HL7_Message("MSH||||||||OML^O21^OML_O21|\rPID|1|\rPV1|1|\rIN1|1|\rORC|1|\rTQ1|1|\rOBR|1|\rSPM|1|\r"); } } ?> <file_sep>/htdocs/api/Net.old/HL7/Types/DT.php <?php class Net_HL7_Types_DT { private $ts; private $year, $month, $day; public function __construct() { $this->ts = strftime("%Y%m%d"); } public function setDateTime($year, $month, $day) { $this->year = $year; $this->month = $month; $this->day = $day; $this->updateDate(); } private function updateDate() { $unixTime = mktime(null, null, null, $this->month, $this->day, $this->year); $this->ts = strftime("%Y%m%d", $unixTime); } /** * @return String **/ function toTsString() { return $this->ts; } }<file_sep>/htdocs/regn/accept_reject_specimen.php <?php # # Adds a new test type to catalog in DB # include("redirect.php"); include("includes/db_lib.php"); putUILog('accept_reject_specimen', 'X', basename($_SERVER['REQUEST_URI'], ".php"), 'X', 'X', 'X'); static $STATUS_REJECTED = 6; $reasons_for_rejection = $_REQUEST['reasons']; // Loop through the array of checked box values ... $reason=""; $flag=0; foreach($reasons_for_rejection as $entry){ $reason .= $entry."; "; $flag=1; } if($flag==1){ $reason=rtrim($reason); } $specimen=$_REQUEST['specimen']; $rejection_date=date('Y-m-d H:i:s'); $rejected_by=$_SESSION['username']; $query = mysql_query("UPDATE specimen SET status_code_id=$STATUS_REJECTED, comments='$reason', ts_accept_reject='$rejection_date',accept_rejected_by='$rejected_by' WHERE specimen_id = $specimen") or die(mysql_error()); $query = mysql_query("INSERT INTO rejected_specimen VALUES ($specimen,'$reason','$rejection_date')") or die(mysql_error()); if($query){ header('Location: find_patient.php?show_sc=1'); } else{ echo '<div class="alert alert-error"> <button class="close" data-dismiss="alert"></button> <strong>Error!</strong> The Update has failed. </div>'; } ?>
44a76603b26bf6f4a152be6fe6644f7528eb7c44
[ "Markdown", "SQL", "PHP", "Shell" ]
63
SQL
BaobabHealthTrust/MalawiBLIS
9028791d0bc8862f08c0a5faec7df089798873a6
055d060ed60fa3a8f8c33b0b7a0f22b890dc959a
refs/heads/master
<repo_name>kullapat-t/kt-admin-iam-service<file_sep>/src/test/kotlin/com/kullapat/iam/builder/UserBuilder.kt package com.kullapat.iam.builder import com.kullapat.iam.domain.User class UserBuilder( private var username: String = "jon", private var email: String = "jon", private var firstName: String = "jon", private var enabled: Boolean = true ) { fun build(): User { return User( username = username, email = email, firstName = firstName, enabled = enabled ) } }<file_sep>/src/main/kotlin/com/kullapat/iam/KtIamApplication.kt package com.kullapat.iam import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication @SpringBootApplication class KtIamApplication fun main(args: Array<String>) { runApplication<KtIamApplication>(*args) } <file_sep>/src/main/kotlin/com/kullapat/iam/usecase/user/GetAllUsers.kt package com.kullapat.iam.usecase.user import com.kullapat.iam.domain.User import com.kullapat.iam.usecase.storage.UserStorage import kotlinx.coroutines.flow.Flow class GetAllUsers(private val userStorage: UserStorage) { fun execute(): Flow<User> { return userStorage.findAll() } }<file_sep>/src/main/kotlin/com/kullapat/iam/infrastructure/persistence/SpringUserStorage.kt package com.kullapat.iam.infrastructure.persistence import com.kullapat.iam.domain.User import com.kullapat.iam.usecase.storage.UserStorage import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.reactive.asFlow import kotlinx.coroutines.reactive.awaitFirst import org.springframework.stereotype.Component @Component class SpringUserStorage(private val userRepository: UserRepository): UserStorage { override suspend fun save(user: User): User { return userRepository.save(user).awaitFirst() } override fun findAll(): Flow<User> { return userRepository.findAll().asFlow() } }<file_sep>/src/test/kotlin/com/kullapat/iam/usecase/user/GetAllUsersTest.kt package com.kullapat.iam.usecase.user import com.kullapat.iam.builder.UserBuilder import com.kullapat.iam.usecase.storage.UserStorage import io.kotlintest.matchers.collections.shouldContainExactlyInAnyOrder import io.mockk.coEvery import io.mockk.mockk import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.toList import kotlinx.coroutines.runBlocking import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test class GetAllUsersTest { val userStorage = mockk<UserStorage>() val getAllUsersQuery = GetAllUsers(userStorage) @Nested inner class GivenUsers { val jon = UserBuilder(username = "jon").build() val tom = UserBuilder(username = "tom").build() @Nested inner class WhenGetAllUsers { @BeforeEach fun beforeEach() { coEvery { userStorage.findAll() } returns flowOf(jon, tom) } @Test fun thenAllUsersShouldBeReturned() { runBlocking { val s = getAllUsersQuery.execute() s.toList() shouldContainExactlyInAnyOrder listOf(jon, tom) } } } } }<file_sep>/src/main/kotlin/com/kullapat/iam/infrastructure/persistence/UserRepository.kt package com.kullapat.iam.infrastructure.persistence import com.kullapat.iam.domain.User import org.springframework.data.mongodb.repository.ReactiveMongoRepository interface UserRepository: ReactiveMongoRepository<User, String><file_sep>/README.md # kt-admin-iam-service ### Swagger Swagger-UI > /swagger-ui.html OpenAPI > /v3/api-docs<file_sep>/src/main/kotlin/com/kullapat/iam/infrastructure/http/UserController.kt package com.kullapat.iam.infrastructure.http import com.kullapat.iam.usecase.user.CreateUserInput import com.kullapat.iam.domain.User import com.kullapat.iam.usecase.storage.UserStorage import com.kullapat.iam.usecase.user.CreateUser import com.kullapat.iam.usecase.user.GetAllUsers import kotlinx.coroutines.flow.Flow import org.springframework.web.bind.annotation.* @RestController @RequestMapping("/api/v1/users") class UserController(userStorage: UserStorage) { val createUserCommand: CreateUser = CreateUser(userStorage) val getAllUsersQuery: GetAllUsers = GetAllUsers(userStorage) @PostMapping suspend fun createUser(@RequestBody input: CreateUserInput): User { return createUserCommand.execute(input) } @GetMapping fun getAllUsers(): Flow<User> { return getAllUsersQuery.execute() } }<file_sep>/src/main/kotlin/com/kullapat/iam/usecase/storage/UserStorage.kt package com.kullapat.iam.usecase.storage import com.kullapat.iam.domain.User import kotlinx.coroutines.flow.Flow interface UserStorage { suspend fun save(user: User): User fun findAll(): Flow<User> } <file_sep>/src/main/kotlin/com/kullapat/iam/domain/User.kt package com.kullapat.iam.domain import org.springframework.data.mongodb.core.mapping.Document @Document(collection = "users") data class User( val username: String, val email: String, val firstName: String, val enabled: Boolean )<file_sep>/src/main/kotlin/com/kullapat/iam/infrastructure/config/SwaggerConfig.kt package com.kullapat.iam.infrastructure.config import io.swagger.v3.oas.models.OpenAPI import io.swagger.v3.oas.models.info.Info import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration @Configuration class Swagger { @Bean fun openAPI(): OpenAPI? { return OpenAPI() .info(Info().title("KT Service") .description("KT Service - sample application") .version("1.0.0")) } } <file_sep>/src/main/kotlin/com/kullapat/iam/usecase/user/CreateUserInput.kt package com.kullapat.iam.usecase.user import com.kullapat.iam.domain.User data class CreateUserInput( val username: String, val email: String, val firstName: String, val enabled: Boolean ) { fun toUser(): User { return User(username, email, firstName, enabled) } } <file_sep>/Dockerfile FROM adoptopenjdk/openjdk13-openj9:alpine-slim WORKDIR /output COPY . . RUN ./gradlew clean build -x test COPY /build/libs/*.jar /service.jar ENTRYPOINT [ "sh", "-c", "java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar /service.jar" ]<file_sep>/src/main/kotlin/com/kullapat/iam/usecase/user/CreateUser.kt package com.kullapat.iam.usecase.user import com.kullapat.iam.domain.User import com.kullapat.iam.usecase.storage.UserStorage import kotlinx.coroutines.coroutineScope class CreateUser(private val userStorage: UserStorage) { suspend fun execute(input: CreateUserInput): User = coroutineScope { require(input.username.isNotEmpty()) { "username cannot be empty" } require(input.email.isNotEmpty()) { "email cannot be empty" } return@coroutineScope userStorage.save(input.toUser()) } } <file_sep>/src/test/kotlin/com/kullapat/iam/infrastructure/http/UserControllerTest.kt package com.kullapat.iam.infrastructure.http import com.kullapat.iam.builder.UserBuilder import com.kullapat.iam.domain.User import com.kullapat.iam.usecase.storage.UserStorage import com.kullapat.iam.usecase.user.CreateUserInput import io.kotlintest.shouldBe import kotlinx.coroutines.runBlocking import org.hamcrest.Matchers.hasItems import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import org.springframework.http.MediaType import org.springframework.test.web.reactive.server.WebTestClient import org.springframework.test.web.reactive.server.expectBody import org.springframework.web.reactive.function.BodyInserters @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) class UserControllerTest( @Autowired val client: WebTestClient, @Autowired val userStorage: UserStorage ) { @Test fun `create user, should return a new user`() { val createUserInput = CreateUserInput(username = "nitch", email = "<EMAIL>", firstName = "kt", enabled = true) val result = client.post() .uri("/api/v1/users") .body(BodyInserters.fromValue(createUserInput)) .accept(MediaType.APPLICATION_JSON) .exchange() .expectStatus().isOk .expectBody<User>() .returnResult() .responseBody!! result.username shouldBe createUserInput.username result.email shouldBe createUserInput.email result.firstName shouldBe createUserInput.firstName result.enabled shouldBe createUserInput.enabled } @Test fun `get all users, should return all users`() { val jon = UserBuilder(username = "jon", email = "<EMAIL>", firstName = "jOn", enabled = true).build() val tom = UserBuilder(username = "tom", email = "<EMAIL>", firstName = "TOm", enabled = false).build() runBlocking { userStorage.save(jon) userStorage.save(tom) } client.get() .uri("/api/v1/users") .accept(MediaType.APPLICATION_JSON) .exchange() .expectStatus().isOk .expectBody() .jsonPath("$.length()").isEqualTo(2) .jsonPath("$..username").value(hasItems(jon.username, tom.username)) .jsonPath("$..email").value(hasItems(jon.email, tom.email)) .jsonPath("$..firstName").value(hasItems(jon.firstName, tom.firstName)) .jsonPath("$..enabled").value(hasItems(jon.enabled, tom.enabled)) } }<file_sep>/src/test/kotlin/com/kullapat/iam/usecase/user/CreateUserTest.kt package com.kullapat.iam.usecase.user import com.kullapat.iam.domain.User import com.kullapat.iam.usecase.storage.UserStorage import io.kotlintest.shouldBe import io.kotlintest.shouldThrow import io.kotlintest.specs.BehaviorSpec import io.mockk.* import kotlinx.coroutines.runBlocking class CreateUserTest: BehaviorSpec({ val userStorage = mockk<UserStorage>() val useCase = CreateUser(userStorage) given("Create user input") { var input = CreateUserInput(username = "nitch", email = "<EMAIL>", firstName = "nitch", enabled = true) `when`("create a user") { then("should save and return a user") { runBlocking { val expectedUser = input.toUser() val userSlot = slot<User>() coEvery { userStorage.save(any()) } answers { firstArg() } useCase.execute(input) coVerify(exactly = 1) { userStorage.save(capture(userSlot)) } userSlot.captured shouldBe expectedUser } } } `when`("username is empty") { val input = input.copy(username = "") then("should throw invalid input exception") { val exception = shouldThrow<Exception> { runBlocking { useCase.execute(input) } } exception.message shouldBe "username cannot be empty" } } `when`("email is empty") { val input = input.copy(email = "") then("should throw invalid input exception") { val exception = shouldThrow<Exception> { runBlocking { useCase.execute(input) } } exception.message shouldBe "email cannot be empty" } } } })
4d9a21e93e558e646cf1971b68b030f8829a1693
[ "Markdown", "Kotlin", "Dockerfile" ]
16
Kotlin
kullapat-t/kt-admin-iam-service
e66622e456061d2279a1017cf96aaa55ab93eb43
af0fe5a7b3ac8a74dca544744398bb0305b7d892
refs/heads/main
<file_sep><?php namespace CodeQ\MonocleRenderer\DataSource; use Neos\Flow\Annotations as Flow; use Neos\ContentRepository\Domain\Model\NodeInterface; use Neos\Neos\Service\DataSource\AbstractDataSource; use Sitegeist\Monocle\Fusion\FusionService; use Sitegeist\Monocle\Service\ConfigurationService; class NodeTypeDataSource extends AbstractDataSource { /** * @var string */ static protected $identifier = 'codeq-monoclerenderer-nodetype'; /** * @Flow\Inject * @var FusionService */ protected $fusionService; /** * @Flow\Inject * @var ConfigurationService */ protected $configurationService; /** * @param NodeInterface|null $node * @param array $arguments * * @return array */ public function getData(NodeInterface $node = null, array $arguments = []): array { $sitePackageKey = $node->getContext()->getCurrentSite()->getSiteResourcesPackageKey(); $data = []; foreach($this->getStyleguideObjects($sitePackageKey) as $prototypeName => $styleguideObject) { $data[] = array( 'label' => $styleguideObject['title'], 'value' => $prototypeName, 'icon' => $styleguideObject['structure']['icon'] ); } return $data; } /** * @param $sitePackageKey * @param $styleguideObject * @return array * @throws \Neos\Neos\Domain\Exception */ protected function getStyleguideObjects($sitePackageKey): array { $fusionAst = $this->fusionService->getMergedFusionObjectTreeForSitePackage($sitePackageKey); $styleguideObjects = $this->fusionService->getStyleguideObjectsFromFusionAst($fusionAst); $prototypeStructures = $this->configurationService->getSiteConfiguration($sitePackageKey, 'ui.structure'); foreach ($styleguideObjects as $prototypeName => &$styleguideObject) { $styleguideObject['structure'] = $this->getStructureForPrototypeName($prototypeStructures, $prototypeName); } $hiddenPrototypeNamePatterns = $this->configurationService->getSiteConfiguration($sitePackageKey, 'hiddenPrototypeNamePatterns'); if (is_array($hiddenPrototypeNamePatterns)) { $alwaysShowPrototypes = $this->configurationService->getSiteConfiguration($sitePackageKey, 'alwaysShowPrototypes'); foreach ($hiddenPrototypeNamePatterns as $pattern) { $styleguideObjects = array_filter( $styleguideObjects, function ($prototypeName) use ($pattern, $alwaysShowPrototypes) { if (in_array($prototypeName, $alwaysShowPrototypes, true)) { return true; } return fnmatch($pattern, $prototypeName) === false; }, ARRAY_FILTER_USE_KEY ); } } return $styleguideObjects; } /** * Find the matching structure for a prototype * * @param $prototypeStructures * @param $prototypeName * @return array */ protected function getStructureForPrototypeName($prototypeStructures, $prototypeName) { foreach ($prototypeStructures as $structure) { if (preg_match(sprintf('!%s!', $structure['match']), $prototypeName)) { return $structure; } } return [ 'label' => 'Other', 'icon' => 'icon-question', 'color' => 'white' ]; } } <file_sep>[![Latest Stable Version](https://poser.pugx.org/codeq/monocle-renderer/v/stable)](https://packagist.org/packages/codeq/monocle-renderer) [![License](https://poser.pugx.org/codeq/monocle-renderer/license)](LICENSE) # CodeQ.MonocleRenderer Administrators and everyone with the role `CodeQ.MonocleRenderer:PrototypeRendererNodeEditor` can render arbitrary Monocle components as content nodes. *The development and the public-releases of this package are generously sponsored by [Code Q Web Factory](http://codeq.at).* ## Installation CodeQ.MonocleRenderer is available via packagist. `"codeq/monocle-renderer" : "~1.0"` to the require section of the composer.json or run: ```bash composer require codeq/monocle-renderer ``` We use semantic-versioning so every breaking change will increase the major-version number. ## License Licensed under MIT, see [LICENSE](LICENSE) ## Contribution We will gladly accept contributions. Please send us pull requests.
e46b0f3a290326a1fb95adf638af756b9c9fb352
[ "Markdown", "PHP" ]
2
PHP
code-q-web-factory/CodeQ.MonocleRenderer
4af54fa47837d73c9e6e53c17e9c52ab0a09cbc5
359f924b6c4b16a3d28a01a25043c7efdb2a9cf7
refs/heads/master
<file_sep>using System; /** * Tarea 3. * Autor: <NAME>. */ namespace Ejercicio8 { class Program { static void Main(string[] args) { Console.WriteLine("Excercise 8."); // Create autos Auto auto1 = new Auto("Audi A8", "Black", "AWL-F0-Z4"); Auto auto2 = new Auto("Mazda RX-7", "Red", "QWE-T8-AF"); Auto auto3 = new Auto("Mercedez R350", "White", "AZS-98-W7"); Console.WriteLine(auto1); Console.WriteLine(auto2); Console.WriteLine(auto3); // Accelerate Console.WriteLine("\nAccelerating..."); auto1.Accelerate(10.0); auto2.Accelerate(5.0); auto3.Accelerate(2.0); Console.WriteLine($"{auto1.Plate} => Speed: {auto1.Speed}km/h"); Console.WriteLine($"{auto2.Plate} => Speed: {auto2.Speed}km/h"); Console.WriteLine($"{auto3.Plate} => Speed: {auto3.Speed}km/h"); // Start Console.WriteLine("\nStarting engine..."); auto1.Start(); auto2.Start(); auto3.Start(); Console.WriteLine(auto1); Console.WriteLine(auto2); Console.WriteLine(auto3); // Turn off Console.WriteLine("\nTurning off engine..."); auto1.TurnOff(); auto2.TurnOff(); auto3.TurnOff(); Console.WriteLine(auto1); Console.WriteLine(auto2); Console.WriteLine(auto3); // Turn left Console.WriteLine("\nTurning left..."); auto1.TurnLeft(); auto2.TurnLeft(); auto3.TurnLeft(); Console.WriteLine(auto1); Console.WriteLine(auto2); Console.WriteLine(auto3); // Turn right Console.WriteLine("\nTurning right..."); auto1.TurnRight(); auto2.TurnRight(); auto3.TurnRight(); Console.WriteLine(auto1); Console.WriteLine(auto2); Console.WriteLine(auto3); // Go Forward Console.WriteLine("\nGoing forward..."); auto1.GoForward(); auto2.GoForward(); auto3.GoForward(); Console.WriteLine(auto1); Console.WriteLine(auto2); Console.WriteLine(auto3); // Setters Console.WriteLine("\nPainting... (Setters)"); auto1.Color = "Cyan"; auto2.Color = "Purple"; auto3.Color = "Pink"; Console.WriteLine($"{auto1.Plate} => Color: {auto1.Color}"); Console.WriteLine($"{auto2.Plate} => Color: {auto2.Color}"); Console.WriteLine($"{auto3.Plate} => Color: {auto3.Color}"); // Getters Console.WriteLine("\nGetters:"); Console.WriteLine($"{auto1.Plate}" + $"\n\t=> Model: {auto1.Model}" + $"\n\t=> Color: {auto1.Color}" + $"\n\t=> State: {auto1.State}" + $"\n\t=> Direction: {auto1.Direction}" + $"\n\t=> Speed: {auto1.Speed}km/h"); Console.WriteLine($"{auto2.Plate}" + $"\n\t=> Model: {auto2.Model}" + $"\n\t=> Color: {auto2.Color}" + $"\n\t=> State: {auto2.State}" + $"\n\t=> Direction: {auto2.Direction}" + $"\n\t=> Speed: {auto2.Speed}km/h"); Console.WriteLine($"{auto3.Plate}" + $"\n\t=> Model: {auto3.Model}" + $"\n\t=> Color: {auto3.Color}" + $"\n\t=> State: {auto3.State}" + $"\n\t=> Direction: {auto3.Direction}" + $"\n\t=> Speed: {auto3.Speed}km/h"); Console.WriteLine("\nPress any key to exit..."); Console.ReadKey(); } } } <file_sep>using System; /** * Tarea 3. * Autor: <NAME>. */ /** * Las interfaces nos permiten definir comportamiento sin necesidad de * implementarlo. Además, la diferencia con clases abstractas es que podemos * implementar muchas interfaces. * * En este caso, la interfaz IVideojuego especifica los métodos de MainMenu(), * Play(), Pause() y GameOver() los cuales son los métodos más comunes en un * videojuego. */ namespace Ejercicio14 { class Program { static void Main(string[] args) { Console.WriteLine("Excercise 14."); VideojuegoCarreras carreras = new VideojuegoCarreras("Crash CTR"); VideojuegoPeleas peleas = new VideojuegoPeleas("Bloody Roar"); VideojuegoAventuras aventuras = new VideojuegoAventuras("Spyro"); // Carreras carreras.MainMenu(); Console.WriteLine(); carreras.Play(); Console.WriteLine(); carreras.Pause(); Console.WriteLine(); carreras.GameOver(); // Peleas Console.WriteLine(); peleas.MainMenu(); Console.WriteLine(); peleas.Play(); Console.WriteLine(); peleas.Pause(); Console.WriteLine(); peleas.GameOver(); // Aventuras Console.WriteLine(); aventuras.MainMenu(); Console.WriteLine(); aventuras.Play(); Console.WriteLine(); aventuras.Pause(); Console.WriteLine(); aventuras.GameOver(); Console.WriteLine("\nPress any key to exit..."); Console.ReadKey(); } } } <file_sep>using System; /** * Tarea 3. * Autor: <NAME>. */ namespace Ejercicio16 { class Program { static void Main(string[] args) { Console.WriteLine("Excercise 16."); Estudiante estudiante = new Estudiante("<NAME>", 20, 313237896); EstudianteIngenieria ingenieria = new EstudianteIngenieria( "<NAME>", 22, 365348892); EstudianteCiencias ciencias = new EstudianteCiencias("<NAME> " + "García", 21, 314657492); // Estudia estudiante.Estudia(); ingenieria.Estudia(); ciencias.Estudia(); // Tarea Console.WriteLine(); estudiante.Tarea(); ingenieria.Tarea(); ciencias.Tarea(); // Dormir Console.WriteLine(); estudiante.Dormir(); ingenieria.Dormir(); ciencias.Dormir(); Console.WriteLine("\nPress any key to exit..."); Console.ReadKey(); } } } <file_sep>using System; /** * Tarea 3. * Autor: <NAME>. */ namespace Ejercicio6 { class CuentaBancaria { /// <summary> /// Saldo de la cuenta. /// </summary> public double Saldo { get; set; } /// <summary> /// Nombre de la cuenta. /// </summary> public string Nombre { get; set; } /// <summary> /// Constructor de CuentaBancaria. /// </summary> /// <param name="nombre">Nombre de la cuenta.</param> /// <param name="saldo">Saldo de la cuenta.</param> public CuentaBancaria(string nombre, double saldo) { Nombre = nombre; Saldo = saldo; MostrarInformacion(); } /// <summary> /// Deposita una cantidad a la cuenta bancaria. /// </summary> /// <param name="deposito">Cantidad a depositar.</param> public void Deposito(double deposito) { if (deposito >= 0) { Saldo += deposito; Console.WriteLine("Depósito realizado exitosamente."); MostrarInformacion(); } else Console.WriteLine("Sólo es posible depositar una cantidad " + "mayor a $0."); } /// <summary> /// Retira dinero de la cuenta bancaria. /// </summary> /// <param name="retiro">Cantidad a retirar.</param> public void Retiro(double retiro) { if (Saldo > retiro) { Saldo -= retiro; Console.WriteLine("Retiro realizado exitosamente."); } else Console.WriteLine("El saldo es insuficiente."); MostrarInformacion(); } /// <summary> /// Imprime el nombre de la cuenta y el saldo actual. /// </summary> public void MostrarInformacion() { Console.WriteLine("Nombre de la cuenta: {0}\nSaldo: {1}", Nombre, Saldo); } } } <file_sep>using System; /** * Tarea 3. * Autor: <NAME>. */ namespace Ejercicio15 { static class Calculadora { /// <summary> /// Ejecuta una operación. /// </summary> /// <param name="operation"> /// 1: Suma, 2: Resta, 3: Multiplicación, 4: División. /// </param> private static void ExecOperation(ushort operation) { double n1 = GetDoubleFromSTDIN("Ingresa primer número: "); double n2 = GetDoubleFromSTDIN("Ingresa segundo número: "); double result = operation == 1 ? n1 + n2 : operation == 2 ? n1 - n2 : operation == 3 ? n1 * n2 : n1 / n2; string oper = operation == 1 ? "+" : operation == 2 ? "-" : operation == 3 ? "*" : "/"; Console.WriteLine($"--------------\n{n1} {oper} {n2} = {result}"); } /// <summary> /// Imprime el menú con las opciones. /// </summary> private static void PrintMenu() { Console.Write("\nSeleccione una de las siguientes opciones:" + "\n1] Suma.\n2] Resta.\n3] Multiplicación.\n4] División.\n" + "5] Salir.\n---------------------\nOpción: "); } /// <summary> /// Imprime <paramref name="msg"/> a la salida estándar y obtiene la /// entrada del usuario. /// </summary> /// <param name="msg">Mensaje a imprimir.</param> /// <returns>Entrada del usuario.</returns> private static double GetDoubleFromSTDIN(string msg) { Console.Write(msg); return Convert.ToDouble(Console.ReadLine()); ; } public static void Run() { string opcion; // Opción seleccionada try { do // Realizar operación { PrintMenu(); opcion = Console.ReadLine(); if (opcion.Equals("1")) ExecOperation(1); else if (opcion.Equals("2")) ExecOperation(2); else if (opcion.Equals("3")) ExecOperation(3); else if (opcion.Equals("4")) ExecOperation(4); } while (!opcion.Equals("5")); } catch (FormatException) { Console.WriteLine("Debes ingresar un número."); Run(); } catch (OverflowException) { Console.WriteLine("El número ingresado o el resultado es muy" + "grande. Intente con un valor más pequeño."); Run(); } catch (DivideByZeroException) { Console.WriteLine("No puedes dividir entre cero."); Run(); } } } } <file_sep>using System; /** * Tarea 3. * Autor: <NAME>. */ namespace Ejercicio10 { class Persona { public string Nombre { get; set; } public ushort Edad { get; set; } public double Estatura { get; set; } public double Peso { get; set; } /// <summary> /// Constructor de Persona. /// </summary> /// <param name="nombre">Nombre de la persona.</param> /// <param name="edad">Edad de la persona.</param> /// <param name="estatura">Estatura de la persona.</param> /// <param name="peso">Peso de la persona.</param> public Persona(string nombre, ushort edad, double estatura, double peso) { Nombre = nombre; Edad = edad; Estatura = estatura; Peso = peso; } /// <summary> /// Imprime un saludo. /// </summary> public void Saludar() { Console.WriteLine($"Hola, mi nombre es {Nombre}."); } /// <summary> /// Imprime un mensaje al dormir. /// </summary> public void Dormir() { Console.WriteLine($"{Nombre} está durmiendo... ZzZz..."); } /// <summary> /// Imprime un mensaje al despertar. /// </summary> public void Despertar() { Console.WriteLine("Bueeeeenos días alegriiiiiia... XD"); } /// <summary> /// Retorna la representación en cadena del objeto. /// </summary> /// <returns>Representación en cadena del objeto.</returns> public override string ToString() { return $"Nombre: {Nombre}, Edad: {Edad} años, " + $"Estatura: {Estatura}m, Peso: {Peso}kg."; } } } <file_sep>using System; /** * Tarea 3. * Autor: <NAME>. */ namespace Ejercicio7 { class NumeroComplejo { /// <summary> /// Parte real del número complejo. /// </summary> public double ParteReal { get; set; } /// <summary> /// Parte imaginaria del número complejo. /// </summary> public double ParteImaginaria { get; set; } /// <summary> /// Constructor de un NumeroComplejo. /// </summary> /// <param name="parteReal">Parte real.</param> /// <param name="parteImaginaria">Parte imaginaria.</param> public NumeroComplejo(double parteReal, double parteImaginaria) { ParteReal = parteReal; ParteImaginaria = parteImaginaria; } /// <summary> /// Imprime el número complejo con formato a + bi. /// </summary> public void Imprimir() { Console.WriteLine($"{ParteReal} + {ParteImaginaria}i"); } /// <summary> /// Crea un número complejo a partir de la suma de /// <paramref name="c1"/> con <paramref name="c2"/>. /// </summary> /// <param name="c1">Primer sumando.</param> /// <param name="c2">Segundo sumando.</param> /// <returns>Número complejo resultante.</returns> public static NumeroComplejo Suma(NumeroComplejo c1, NumeroComplejo c2) { return new NumeroComplejo(c1.ParteReal + c2.ParteReal, c1.ParteImaginaria + c2.ParteImaginaria); } } } <file_sep>using System; /** * Tarea 3. * Autor: <NAME>. */ namespace Ejercicio17 { class Program { static void Main(string[] args) { Console.WriteLine("Excercise 17."); Persona persona = new Persona("<NAME>", 28); Estudiante estudiante = new Estudiante("Alan Brito Delgado", 20, 313237896); Trabajador trabajador = new Trabajador("<NAME>", 30, "VECJ880326 XXX"); // ToString Console.WriteLine(persona); Console.WriteLine(estudiante); Console.WriteLine(trabajador); // Respirar Console.WriteLine(); persona.Respirar(); estudiante.Respirar(); trabajador.Respirar(); // Comer Console.WriteLine(); persona.Comer(); estudiante.Comer(); trabajador.Comer(); // Dormir Console.WriteLine(); persona.Dormir(); estudiante.Dormir(); trabajador.Dormir(); // Hacer actividad Console.WriteLine(); persona.HacerActividad(); estudiante.HacerActividad(); trabajador.HacerActividad(); Console.WriteLine("\nPress any key to exit..."); Console.ReadKey(); } } } <file_sep># Tarea 3 - Serie de Ejercicios ## Programación Orienteda a Objetos (C#) ### <NAME> La solución **Tarea3** incluye un proyecto por cada ejercicio de modo que cada ejercicio puede ser ejecutado de forma independiente.<file_sep># CSharpCERT Repositorio para el módulo de Programación Orientada a Objetos (C#) del PBSI 14G. ## <NAME> <file_sep>/** * Tarea 3. * Autor: <NAME>. */ namespace Ejercicio8 { class Auto { /// <summary> /// Car model. /// </summary> public string Model { get; set; } /// <summary> /// Car color. /// </summary> public string Color { get; set; } /// <summary> /// State of the car. True = Engine started, False = Engine turned off. /// </summary> public bool State { get; set; } /// <summary> /// Speed of the car. /// </summary> public double Speed { get; set; } /// <summary> /// Direction of the car. Left = -1, Right = 1, Forward = 0. /// </summary> public short Direction { get; set; } /// <summary> /// Registration plate. /// </summary> public string Plate { get; set; } /// <summary> /// Auto constructor. /// </summary> public Auto() { } /// <summary> /// Auto constructor. /// </summary> /// <param name="model">Car model.</param> /// <param name="color">Car color.</param> /// <param name="plate">Registration plate.</param> public Auto(string model, string color, string plate) { Model = model; Color = color; Plate = plate; } /// <summary> /// Accelerates the car. /// </summary> /// <param name="speed">Speed to accelerate.</param> public void Accelerate(double speed) { Speed += speed; } /// <summary> /// Starts the car engine. /// </summary> public void Start() { State = true; } /// <summary> /// Turns off the car engine. /// </summary> public void TurnOff() { State = false; } /// <summary> /// Sets direction to left. /// </summary> public void TurnLeft() { Direction = -1; } /// <summary> /// Sets direction to right. /// </summary> public void TurnRight() { Direction = 1; } /// <summary> /// Sets direction to forward. /// </summary> public void GoForward() { Direction = 0; } /// <summary> /// Returns the string representation of the object. /// </summary> /// <returns>String representation of the object.</returns> public override string ToString() { string dir = Direction == -1 ? "Left" : (Direction == 1 ? "Right" : "Forward"); string state = State ? "Engine started" : "Engine turned off"; return $"{Plate}\n\tModel => {Model}\n\tColor => {Color}\n\t" + $"State => {state}\n\tSpeed => {Speed}km/h\n\t" + $"Direction => {dir}"; } } } <file_sep>using System; /** * Tarea 3. * Autor: <NAME>. */ namespace Ejercicio12 { class Program { static void Main(string[] args) { Console.WriteLine("Excercise 12."); BecarioMart.Run(); // Ejecución del programa Console.WriteLine("\nPress any key to exit..."); Console.ReadKey(); } } } <file_sep>using System; namespace Ejercicio17 { class Persona { /// <summary>Nombre completo de la persona.</summary> public string NombreCompleto { get; set; } /// <summary>Edad de la persona.</summary> public ushort Edad { get; set; } /// <summary> /// Constructor de una Persona. /// </summary> /// <param name="nombreCompleto">Nombre completo.</param> /// <param name="edad">Edad.</param> public Persona(string nombreCompleto, ushort edad) { NombreCompleto = nombreCompleto; Edad = edad; } /// <summary> /// Imprime un mensaje de que la persona está respirando. /// </summary> public void Respirar() { Console.WriteLine($"{NombreCompleto} está respirando..."); } /// <summary> /// Imprime un mensaje de que la persona está comiendo. /// </summary> public void Comer() { Console.WriteLine($"{NombreCompleto} está comiendo..."); } /// <summary> /// Imprime un mensaje de que la persona está durmiendo. /// </summary> public void Dormir() { Console.WriteLine($"{NombreCompleto} está durmiendo..."); } /// <summary> /// Imprime un mensaje de que la persona hace una actividad. /// </summary> public virtual void HacerActividad() { Console.WriteLine($"{NombreCompleto} está existiendo..."); } /// <summary> /// Retorna la representación en cadena de Persona. /// </summary> /// <returns>Representación en cadena de Persona.</returns> public override string ToString() { return $"Hola, soy {NombreCompleto} y tengo {Edad} años."; } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace Ejercicio14 { class VideojuegoAventuras { public string Nombre { get; set; } public VideojuegoAventuras(string nombre) { Nombre = nombre; } /// <summary> /// Imprime el menú principal. /// </summary> public void MainMenu() { Console.WriteLine($":::::::: {Nombre} ::::::::"); Console.WriteLine("> Continuar aventura <"); Console.WriteLine(" Nueva aventura "); Console.WriteLine(" Configuraciones "); Console.WriteLine(" Créditos "); } /// <summary> /// Inicia el juego. /// </summary> public void Play() { Console.WriteLine("~ Nivel 12 ~"); } /// <summary> /// Pausa el juego. /// </summary> public void Pause() { Console.WriteLine("Juego pausado"); } /// <summary> /// Imprime el mensaje de Game Over. /// </summary> public void GameOver() { Console.WriteLine("Fin del juego"); } } } <file_sep>using System; namespace Ejercicio17 { class Trabajador : Persona { /// <summary>RFC del trabajador.</summary> public string RFC { get; set; } /// <summary> /// Constructor de un Estudiante. /// </summary> /// <param name="nombreCompleto">Nombre completo.</param> /// <param name="edad">Edad.</param> /// <param name="rfc">RFC.</param> public Trabajador(string nombreCompleto, ushort edad, string rfc) : base(nombreCompleto, edad) { RFC = rfc; } /// <summary> /// Imprime un mensaje de que el estudiante está estudiando. /// </summary> public override void HacerActividad() { Console.WriteLine($"El trabajador {NombreCompleto} está " + "trabajando."); } /// <summary> /// Retorna la representación en cadena de Trabajador. /// </summary> /// <returns>Representación en cadena de Trabajador.</returns> public override string ToString() { return $"Hola, soy {NombreCompleto}, tengo {Edad} años y soy " + $"trabajador."; } } } <file_sep>using System; /** * Tarea 2. * Autor: <NAME>. */ namespace Tarea2 { /// <summary> /// Clase que representa a un Alumno. /// </summary> class Alumno { /// <summary> /// Nombre del alumno. /// </summary> public string Nombre { get; set; } /// <summary> /// Apellido paterno. /// </summary> public string ApPaterno { get; set; } /// <summary> /// Apellido materno. /// </summary> public string ApMaterno { get; set; } /// <summary> /// Calificación de proyecto. /// </summary> public int CalProyecto { get; set; } /// <summary> /// Cantidad de tareas. /// </summary> public int CantTareas { get; set; } /// <summary> /// Cantidad de participaciones. /// </summary> public int CantParticipaciones { get; set; } /// <summary> /// Constructor de un Alumno. /// </summary> /// <param name="nombre">Nombre del alumno.</param> /// <param name="apPaterno">Apellido paterno.</param> /// <param name="apMaterno">Apellido materno.</param> /// <param name="calProyecto">Calificación del proyecto.</param> /// <param name="cantTareas">Cantidad de tareas realizadas.</param> /// <param name="cantParticipaciones"> /// Cantidad de participaciones. /// </param> public Alumno(string nombre, string apPaterno, string apMaterno, int calProyecto, int cantTareas, int cantParticipaciones) { Nombre = nombre; ApPaterno = apPaterno; ApMaterno = apMaterno; CalProyecto = calProyecto; CantTareas = cantTareas; CantParticipaciones = cantParticipaciones; } /// <summary> /// Retorna el nombre completo de un alumno. /// </summary> /// <returns>Nombre completo del alumno.</returns> public string GetNombreCompleto() { return Nombre + " " + ApPaterno + " " + ApMaterno; } } /// <summary> /// Clase estática que permite calificar a un grupo de alumnos. /// </summary> static class Calculadora { /// <summary> /// Califica a un grupo de alumnos solicitados al usuario. /// </summary> public static void CalificaAlumnos() { int cant_alumnos; // Cantidad de alumnos a calificar Alumno[] alumnos; // Arreglo de alumnos a calificar int index; // Indice para iteraciones // Datos de alumno string nombre, ap_paterno, ap_materno; int cal_proyecto, cant_tareas, cant_participaciones; // Obtenemos cantidad de alumnos a calificar cant_alumnos = GetValidPositiveInt(0, int.MaxValue, "Ingrese la cantidad de alumnos a calificar: "); alumnos = new Alumno[cant_alumnos]; // Obtenemos datos for(index = 0; index < alumnos.Length; index++) { Console.WriteLine("Datos del alumno {0}", index + 1); nombre = GetValidString("Ingrese el nombre del alumno: "); ap_paterno = GetValidString("Ingrese el apellido paterno del" + " alumno: "); ap_materno = GetValidString("Ingrese el apellido materno del" + " alumno: "); cal_proyecto = GetValidPositiveInt(0, 10, "Ingrese la " + "calificación del proyecto: "); cant_tareas = GetValidPositiveInt(0, 5, "Ingrese " + "la cantidad de tareas realizadas: "); cant_participaciones = GetValidPositiveInt(0, int.MaxValue, "Ingrese la cantidad de participaciones: "); Console.WriteLine(); alumnos[index] = new Alumno(nombre, ap_paterno, ap_materno, cal_proyecto, cant_tareas, cant_participaciones); } // Obtenemos calificaciones Console.WriteLine("Las calificaciones son las siguientes:"); for(index = 0; index < alumnos.Length; index++) Console.WriteLine("La calificación final de {0} es de " + "{1}/100", alumnos[index].GetNombreCompleto(), CalificaAlumno(alumnos[index])); } /// <summary> /// Califica a un alumno y retorna dicha calificación. /// </summary> /// <param name="alumno">Alumno a calificar.</param> /// <returns>Calificación del alumno entre 50 y 100.</returns> private static int CalificaAlumno(Alumno alumno) { int cal = (alumno.CalProyecto * 6) + (alumno.CantTareas * 8) + (alumno.CantParticipaciones > 5 ? 8 : 0); return cal < 50 ? 50 : (cal > 100 ? 100 : cal); } /// <summary> /// Obtiene un entero válido en un rango ingresado por el usuario. /// </summary> /// <param name="lower_boud">Limite inferior.</param> /// <param name="upper_bound">Limite superior.</param> /// <param name="msg">Mensaje a imprimir al solicitar el valor.</param> /// <returns>Entero válido en el rango.</returns> private static int GetValidPositiveInt(int lower_boud, int upper_bound, string msg) { int number = lower_boud - 1; // Valor inicial string input; // Entrada del usuario // Pedimos una cantidad válida while (number < lower_boud || number > upper_bound) { Console.Write(msg); input = Console.ReadLine(); if (!Int32.TryParse(input, out number)) number = lower_boud - 1; number = number >= lower_boud && number <= upper_bound ? number : lower_boud - 1; } return number; } /// <summary> /// Obtiene una cadena válida ingresada por el usuario. /// </summary> /// <param name="msg"> /// Mensaje a imprimir al solicitar la cadena. /// </param> /// <returns>Cadena válida. (No vacía)</returns> private static string GetValidString(string msg) { string str = ""; // Valor inicial while (string.Equals(str, "")) // Pedimos una entrada válida { Console.Write(msg); str = Console.ReadLine(); } return str; } } class Program { static void Main(string[] args) { Calculadora.CalificaAlumnos(); Console.WriteLine("Presione una tecla para salir..."); Console.ReadKey(); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace MiPrimeraGUI { public partial class Form1 : Form { private const string User = "Alexis"; private const string Pass = "<PASSWORD>.,"; public Form1() { InitializeComponent(); } private void label1_Click(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { label1.Text = "Hola mundo desde Windows Forms"; } private void button1_Click_1(object sender, EventArgs e) { string user = TB1.Text; string pass = TB2.Text; if (user.Equals(User) && pass.Equals(Pass)) MessageBox.Show("Acceso correcto."); else MessageBox.Show("Usuario o contraseña incorrectos."); } } } <file_sep>using System; /** * Tarea 3. * Autor: <NAME>. */ namespace Ejercicio10 { class Program { /// <summary> /// Imprime <paramref name="msg"/> a la salida estándar y obtiene la /// entrada del usuario. /// </summary> /// <param name="msg">Mensaje a imprimir.</param> /// <returns>Entrada del usuario.</returns> private static string GetStringFromSTDIN(string msg) { string str = ""; // Entrada del usuario // Obtener entrada del usuario while (str.Equals("")) { Console.Write(msg); str = Console.ReadLine(); } return str; } /// <summary> /// Imprime <paramref name="msg"/> a la salida estándar y obtiene la /// entrada del usuario. /// </summary> /// <param name="msg">Mensaje a imprimir.</param> /// <returns>Entrada del usuario.</returns> private static double GetDoubleFromSTDIN(string msg) { double dbl = 0; // Salida // Obtener entrada del usuario while (dbl <= 0) { Console.Write(msg); dbl = double.TryParse(Console.ReadLine(), out dbl) ? dbl : 0; } return dbl; } /// <summary> /// Imprime <paramref name="msg"/> a la salida estándar y obtiene la /// entrada del usuario. /// </summary> /// <param name="msg">Mensaje a imprimir.</param> /// <returns>Entrada del usuario.</returns> private static ushort GetUShortFromSTDIN(string msg) { ushort usht = 0; // Salida // Obtener entrada del usuario while (usht <= 0) { Console.Write(msg); usht = ushort.TryParse(Console.ReadLine(), out usht) ? usht : (ushort)0; } return usht; } static void Main(string[] args) { Console.WriteLine("Excercise 10."); // Pruebas Persona persona = new Persona( GetStringFromSTDIN("Ingrese nombre: "), GetUShortFromSTDIN("Ingrese edad (en años): "), GetDoubleFromSTDIN("Ingrese estatura (en metros): "), GetDoubleFromSTDIN("Ingrese peso (en kg): ")); Console.WriteLine($"\nToString: {persona}"); persona.Saludar(); persona.Dormir(); persona.Despertar(); Console.WriteLine("\nPress any key to exit..."); Console.ReadKey(); } } } <file_sep>using System; /** * Tarea 3. * Autor: <NAME>. */ namespace Ejercicio16 { class EstudianteIngenieria : Estudiante { /// <summary> /// Constructor de un EstudianteIngenieria. /// </summary> /// <param name="nombreCompleto">Nombre completo.</param> /// <param name="edad">Edad.</param> /// <param name="numeroCuenta">Número de cuenta.</param> public EstudianteIngenieria(string nombreCompleto, ushort edad, int numeroCuenta) : base(nombreCompleto, edad, numeroCuenta) { } /// <summary> /// Imprime un mensaje de que el estudiante está estudiando. /// </summary> public override void Estudia() { Console.WriteLine($"El estudiante {NombreCompleto} está " + "estudiando Ingeniería."); } /// <summary> /// Imprime un mensaje de que el estudiante está haciendo tarea. /// </summary> public override void Tarea() { Console.WriteLine($"El estudiante {NombreCompleto} hace tarea " + "de física."); } /// <summary> /// Imprime un mensaje de que el estudiante duerme. /// </summary> public override void Dormir() { Console.WriteLine($"El estudiante {NombreCompleto} duerme " + "(según)."); } } } <file_sep>using System; namespace Clase1 { class Program { static void Main(string[] args) { Persona el_vene = new Persona("<NAME>", 22); Persona sadman = new Persona("Sadman", 22); Persona seimiuc = new Persona("Seimiuc", 22); // Comparación por referencia Console.WriteLine("Referencias el_vene y sadman son iguales?"); Console.WriteLine(el_vene == sadman); Console.WriteLine("Referencias sadman y seimiuc son iguales?"); Console.WriteLine(sadman == seimiuc); } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace ClasesAbstractas { abstract class Animal { private string nombre; public Animal(string nombre) { NombreComun = nombre; } public string NombreComun { get { return nombre; } set { nombre = value; } } public abstract string Come { get; } public override string ToString() { return NombreComun + "" + Come; } } } <file_sep>using System; /** * Tarea 3. * Autor: <NAME>. */ namespace Ejercicio13 { class Program { static void Main(string[] args) { Console.WriteLine("Excercise 13."); Carro carro = new Carro(1000, 1.5); CarroBMW carroBMW = new CarroBMW(1500, 1.25, "BMW i8"); CarroVW carroVW = new CarroVW(1700, 1.75, "Polo"); // Encender Console.WriteLine("Enceder:"); carro.Encender(); carroBMW.Encender(); carroVW.Encender(); // Apagar Console.WriteLine("\nApagar:"); carro.Apagar(); carroBMW.Apagar(); carroVW.Apagar(); // Estado Console.WriteLine("\nEstado:"); carro.Estado(); carroBMW.Estado(); carroVW.Estado(); // ToString Console.WriteLine("\nToString:"); Console.WriteLine(carro); Console.WriteLine("\n" + carroBMW); Console.WriteLine("\n" + carroVW); Console.WriteLine("\nPress any key to exit..."); Console.ReadKey(); } } } <file_sep>using System; /** * Tarea 3. * Autor: <NAME>. */ namespace Ejercicio6 { class Program { static void Main(string[] args) { Console.WriteLine("Excercise 6."); // Creamos cuentas Console.WriteLine("Creación de cuentas:"); CuentaBancaria cuenta1 = new CuentaBancaria("Alan", 5000.0); CuentaBancaria cuenta2 = new CuentaBancaria("Brito", 1000.0); // Depósitos Console.WriteLine("\nDepósitos:"); cuenta1.Deposito(5000.0); // Saldo: 10,000.0 cuenta2.Deposito(10000.0); // Saldo: 20,000.0 // Retiros Console.WriteLine("\nRetiros:"); cuenta1.Retiro(15000.0); // Saldo insuficiente cuenta2.Retiro(5000.0); // $15,000.0 restante Console.WriteLine("\nPress any key to exit..."); Console.ReadKey(); } } } <file_sep>using System; using System.Collections.Generic; /** * Tarea 3. * Autor: <NAME>. */ namespace Ejercicio12 { static class BecarioMart { /// <summary>Lista de nombres de productos.</summary> private static readonly List<string> productos = new List<string>(); /// <summary>Lista de precios de productos.</summary> private static readonly List<double> precios = new List<double>(); /// <summary>Total a pagar.</summary> private static double total = 0; /// <summary>Dinero disponible</summary> private const double DINERO = 500.0; /// <summary> /// Agrega un producto a las listas. /// </summary> /// <param name="nombre">Nombre del producto.</param> /// <param name="precio">Precio del producto.</param> private static void AgregarProducto(string nombre, double precio) { productos.Add(nombre); precios.Add(precio); total += precio; Console.WriteLine("Producto agregado al carrito."); } /// <summary> /// Elimina un producto en la posición <paramref name="index"/>. /// </summary> /// <param name="index"></param> private static void EliminarProducto(ushort index) { if (index < productos.Count) { total -= precios[index]; productos.RemoveAt(index); precios.RemoveAt(index); Console.WriteLine("Producto descartado."); } else Console.WriteLine("Producto inválido."); } /// <summary> /// Trata de realizar la compra y en caso de que el dinero sea /// insuficiente, se ejecuta la opción de dejar productos. /// </summary> private static void Comprar() { if (total <= DINERO) Console.WriteLine("\nGracias por su compra!"); else { Console.WriteLine("\nDinero insuficiente."); DejarProductos(); } } /// <summary> /// Imprime el menú para dejar un producto y ejecuta la acción /// correspondiente. /// </summary> private static void DejarProductos() { ushort index; string opcion; PrintProductos(); do { index = (ushort)(GetUShortFromSTDIN("\nSeleccione un " + "producto a descartar: ") - 1); EliminarProducto(index); Console.Write("\n¿Desea eliminar otro producto? [S/N]: "); opcion = Console.ReadLine(); } while (opcion.ToUpper().Equals("S")); PrintMenu(); } /// <summary> /// Imprime la lista de productos así como el total a pagar. /// </summary> private static void PrintProductos() { for (int i = 0; i < productos.Count; i++) Console.Write($"\n{i + 1}. {productos[i]}: {precios[i],0:C2}."); Console.WriteLine("\n----------------------------------------"); Console.WriteLine($"Total: {total,0:C2}"); } /// <summary> /// Imprime el menú de comprar o dejar productos y ejecuta las /// opciones correspondientes. /// </summary> private static void PrintMenu() { string opcion; // Opción seleccionada PrintProductos(); // Imprimimos lista de productos. do // Comprar o dejar productos { Console.Write("\nSeleccione una de las siguientes opciones:" + "\n1] Comprar.\n2] Dejar productos.\n---------------------\n" + "Opción: "); opcion = Console.ReadLine(); } while (!opcion.Equals("1") && !opcion.Equals("2")); if (opcion.Equals("1")) // Comprar productos Comprar(); else // Dejar productos DejarProductos(); } /// <summary> /// Imprime <paramref name="msg"/> a la salida estándar y obtiene la /// entrada del usuario. /// </summary> /// <param name="msg">Mensaje a imprimir.</param> /// <returns>Entrada del usuario.</returns> private static string GetStringFromSTDIN(string msg) { string str = ""; // Entrada del usuario // Obtener entrada del usuario while (str.Equals("")) { Console.Write(msg); str = Console.ReadLine(); } return str; } /// <summary> /// Imprime <paramref name="msg"/> a la salida estándar y obtiene la /// entrada del usuario. /// </summary> /// <param name="msg">Mensaje a imprimir.</param> /// <returns>Entrada del usuario.</returns> private static double GetDoubleFromSTDIN(string msg) { double dbl = 0; // Salida // Obtener entrada del usuario while (dbl <= 0) { Console.Write(msg); dbl = double.TryParse(Console.ReadLine(), out dbl) ? dbl : 0; } return dbl; } /// <summary> /// Imprime <paramref name="msg"/> a la salida estándar y obtiene la /// entrada del usuario. /// </summary> /// <param name="msg">Mensaje a imprimir.</param> /// <returns>Entrada del usuario.</returns> private static ushort GetUShortFromSTDIN(string msg) { ushort ushrt = 0; // Salida // Obtener entrada del usuario while (ushrt == 0) { Console.Write(msg); ushrt = ushort.TryParse(Console.ReadLine(), out ushrt) ? ushrt : (ushort)0; } return ushrt; } public static void Run() { string opcion = "S"; // Opción seleccionada string producto; // Nombre del producto double precio; // Precio del producto // Agregar productos Console.WriteLine("Ingrese los productos a comprar: "); while (opcion.ToUpper().Equals("S")) { producto = GetStringFromSTDIN("Nombre del producto: "); precio = GetDoubleFromSTDIN("Precio del producto: "); AgregarProducto(producto, precio); Console.Write("\n¿Desea agregar otro producto? [S/N]: "); opcion = Console.ReadLine(); } PrintMenu(); // Comprar o dejar productos } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace Excepciones2 { class NegativeNumberException : Exception { public NegativeNumberException() : base("Operación inválida con número negativo") { } public NegativeNumberException(string msj) : base(msj) { } } } <file_sep>/** * Tarea 4. * Autor: <NAME>. */ namespace Tarea4 { class Program { static void Main(string[] args) { ConsoleEmulator console = new ConsoleEmulator(); console.Run(); } } } <file_sep>using System; /** * Tarea 3. * Autor: <NAME>. */ namespace Ejercicio9 { class Circulo { /// <summary> /// Radio del círculo. /// </summary> public double Radio { get; set; } /// <summary> /// Constructor de un Circulo. /// </summary> /// <param name="radio">Radio del círculo.</param> public Circulo(double radio) { Radio = radio; } /// <summary> /// Obtiene el diámetro del círculo. /// </summary> /// <returns>Diámetro del círculo.</returns> public double Diametro() { return 2 * Radio; } /// <summary> /// Obtiene el perímetro del círculo. /// </summary> /// <returns>Perímetro del círculo.</returns> public double Perimetro() { return Math.PI * Diametro(); } /// <summary> /// Obtiene el área del círculo. /// </summary> /// <returns>Área del círculo.</returns> public double Area() { return Math.PI * Math.Pow(Radio, 2); } /// <summary> /// Retorna un nuevo círculo a partir de truncar el radio del círculo. /// </summary> /// <returns>Circulo con radio truncado.</returns> public Circulo TruncarCirculo() { return new Circulo(Math.Truncate(Radio)); } /// <summary> /// Retorna un nuevo círculo a partir de redondear el radio del /// círculo. /// </summary> /// <returns>Circulo con radio redondeado.</returns> public Circulo RedondearCirculo() { return new Circulo(Math.Round(Radio)); } /// <summary> /// Retorna la representación en cadena del círculo. /// </summary> /// <returns>Reprensentación en cadena del objeto.</returns> public override string ToString() { return $"Radio: {Radio}"; } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace NameSpace { class Program { static void Main() { var anonimo = new { Modelo = "Bocho", Precio = 80000, Placas = "45RT65" }; Console.WriteLine("Datos del objeto anónimo"); Console.WriteLine(anonimo.Modelo); Console.WriteLine(anonimo.Precio); Console.WriteLine(anonimo.Placas); } } } <file_sep>using System; /** * Tarea 3. * Autor: <NAME>. */ namespace Ejercicio14 { class VideojuegoPeleas { public string Nombre { get; set; } public VideojuegoPeleas(string nombre) { Nombre = nombre; } /// <summary> /// Imprime el menú principal. /// </summary> public void MainMenu() { Console.WriteLine($":::::::: {Nombre} ::::::::"); Console.WriteLine("> 1vs1 <"); Console.WriteLine(" Multiplayer "); Console.WriteLine(" Settings "); Console.WriteLine(" Credits "); } /// <summary> /// Inicia el juego. /// </summary> public void Play() { Console.WriteLine("Ready..."); Console.WriteLine("Fight!"); } /// <summary> /// Pausa el juego. /// </summary> public void Pause() { Console.WriteLine("Game Paused..."); } /// <summary> /// Imprime el mensaje de Game Over. /// </summary> public void GameOver() { Console.WriteLine("You lose!"); } } } <file_sep>using System; /** * Tarea 3. * Autor: <NAME>. */ namespace Ejercicio1 { class Program { /// <summary> /// Add the first N natural numbers. /// </summary> /// <param name="n">Total of natural numbers to be added.</param> /// <returns>The sum of the first N natural numbers.</returns> /// <exception cref="System.FormatException"> /// Thrown when n is lower than 0. /// </exception> private static int SumOfFirstNNumbers(int n) { if (n < 0) throw new FormatException(); return (n * (n + 1)) / 2; } static void Main(string[] args) { Console.WriteLine("Excercise 1."); try { // Get input Console.Write("Enter a natural number: "); int n = Convert.ToInt32(Console.ReadLine()); // Generate output Console.WriteLine("The sum of the first {0} numbers is: {1}", n, SumOfFirstNNumbers(n)); } catch (FormatException) { Console.WriteLine("ERROR: You must provide a natural number."); } Console.WriteLine("\nPress any key to exit..."); Console.ReadKey(); } } } <file_sep># Tarea 2 ## Programación Orienteda a Objetos (C#) ### <NAME><file_sep>using System; /** * Tarea 3. * Autor: <NAME>. */ namespace Ejercicio17 { class Estudiante : Persona { /// <summary>Número de cuenta del estudiante.</summary> public int NumeroCuenta { get; set; } /// <summary> /// Constructor de un Estudiante. /// </summary> /// <param name="nombreCompleto">Nombre completo.</param> /// <param name="edad">Edad.</param> /// <param name="numeroCuenta">Número de cuenta.</param> public Estudiante(string nombreCompleto, ushort edad, int numeroCuenta) : base(nombreCompleto, edad) { NumeroCuenta = numeroCuenta; } /// <summary> /// Imprime un mensaje de que el estudiante está estudiando. /// </summary> public override void HacerActividad() { Console.WriteLine($"El estudiante {NombreCompleto} está " + "estudiando."); } /// <summary> /// Retorna la representación en cadena de Estudiante. /// </summary> /// <returns>Representación en cadena de Estudiante.</returns> public override string ToString() { return $"Hola, soy {NombreCompleto}, tengo {Edad} años y soy " + $"estudiante."; } } } <file_sep>using System; /** * Tarea 3. * Autor: <NAME>. */ /* Investigación: Abs(Decimal) Devuelve el valor absoluto de un número decimal. Abs(Double) Devuelve el valor absoluto de un número de coma flotante de doble precisión. Abs(Int16) Devuelve el valor absoluto de un entero con signo de 16 bits. Abs(Int32) Devuelve el valor absoluto de un entero con signo de 32 bits. Abs(Int64) Devuelve el valor absoluto de un entero con signo de 64 bits. Abs(SByte) Devuelve el valor absoluto de un entero con signo de 8 bits. Abs(Single) Devuelve el valor absoluto de un número de coma flotante de precisión simple. Acos(Double) Devuelve el ángulo cuyo coseno es el número especificado. Asin(Double) Devuelve el ángulo cuyo seno es el número especificado. Atan(Double) Devuelve el ángulo cuya tangente es el número especificado. Atan2(Double, Double) Devuelve el ángulo cuya tangente es el cociente de dos números especificados. BigMul(Int32, Int32) Produce el producto completo de dos números de 32 bits. Ceiling(Decimal) Devuelve el valor entero más pequeño que es mayor o igual que el número decimal especificado. Ceiling(Double) Devuelve el valor entero más pequeño que es mayor o igual que el número de punto flotante de precisión doble especificado. Cos(Double) Devuelve el coseno del ángulo especificado. Cosh(Double) Devuelve el coseno hiperbólico del ángulo especificado. DivRem(Int32, Int32, Int32) Calcula el cociente de dos enteros con signo de 32 bits y también devuelve el resto en un parámetro de salida. DivRem(Int64, Int64, Int64) Calcula el cociente de dos enteros con signo de 64 bits y también devuelve el resto en un parámetro de salida. Exp(Double) Devuelve e elevado a la potencia especificada. Floor(Decimal) Devuelve el valor entero más grande menor o igual que el número decimal especificado. Floor(Double) Devuelve el valor entero más grande menor o igual que el número de punto flotante de precisión doble especificado. IEEERemainder(Double, Double) Devuelve el resto resultante de la división de un número especificado por otro número especificado. Log(Double) Devuelve el logaritmo natural (base e) de un número especificado. Log(Double, Double) Devuelve el logaritmo de un número especificado en una base específica. Log10(Double) Devuelve el logaritmo de base 10 de un número especificado. Max(Byte, Byte) Devuelve el mayor de dos enteros sin signo de 8 bits. Max(Decimal, Decimal) Devuelve el mayor de dos números decimales. Max(Double, Double) Devuelve el mayor de dos números de punto flotante de doble precisión. Max(Int16, Int16) Devuelve el mayor de dos enteros con signo de 16 bits. Max(Int32, Int32) Devuelve el mayor de dos enteros con signo de 32 bits. Max(Int64, Int64) Devuelve el mayor de dos enteros con signo de 64 bits. Max(SByte, SByte) Devuelve el mayor de dos enteros con signo de 8 bits. Max(Single, Single) Devuelve el mayor de dos números de punto flotante de precisión simple. Max(UInt16, UInt16) Devuelve el mayor de dos enteros sin signo de 16 bits. Max(UInt32, UInt32) Devuelve el mayor de dos enteros sin signo de 32 bits. Max(UInt64, UInt64) Devuelve el mayor de dos enteros sin signo de 64 bits. Min(Byte, Byte) Devuelve el menor de dos enteros sin signo de 8 bits. Min(Decimal, Decimal) Devuelve el menor de dos números decimales. Min(Double, Double) Devuelve el menor de dos números de punto flotante de doble precisión. Min(Int16, Int16) Devuelve el menor de dos enteros con signo de 16 bits. Min(Int32, Int32) Devuelve el menor de dos enteros con signo de 32 bits. Min(Int64, Int64) Devuelve el menor de dos enteros con signo de 64 bits. Min(SByte, SByte) Devuelve el menor de dos enteros con signo de 8 bits. Min(Single, Single) Devuelve el menor de dos números de punto flotante de precisión simple. Min(UInt16, UInt16) Devuelve el menor de dos enteros sin signo de 16 bits. Min(UInt32, UInt32) Devuelve el menor de dos enteros sin signo de 32 bits. Min(UInt64, UInt64) Devuelve el menor de dos enteros sin signo de 64 bits. Pow(Double, Double) Devuelve un número especificado elevado a la potencia especificada. Round(Decimal) Redondea un valor decimal al valor entero más cercano y redondea los valores del punto medio al número par más cercano. Round(Decimal, Int32) Redondea un valor decimal a un número específico de dígitos fraccionarios y redondea los valores del punto medio al número par más cercano. Round(Decimal, Int32, MidpointRounding) Redondea un valor decimal a un número específico de dígitos fraccionarios y utiliza la convención de redondeo especificada para valores de punto medio. Round(Decimal, MidpointRounding) Redondea un valor decimal al entero más cercano y utiliza la convención de redondeo especificada para valores de punto medio. Round(Double) Redondea un valor de coma flotante de doble precisión al valor entero más cercano y redondea los valores de punto medio al número par más cercano. Round(Double, Int32) Redondea un valor de coma flotante de doble precisión a un número específico de dígitos fraccionarios, y redondea los valores de punto medio al número par más cercano. Round(Double, Int32, MidpointRounding) Redondea un valor de coma flotante de doble precisión a un número específico de dígitos fraccionarios, y utiliza la convención de redondeo especificada para valores de punto medio. Round(Double, MidpointRounding) Redondea un valor de coma flotante de doble precisión al entero más cercano y utiliza la convención de redondeo especificada para valores de punto medio. Sign(Decimal) Devuelve un número entero que indica el signo de un número decimal. Sign(Double) Devuelve un número entero que indica el signo de un número de coma flotante de doble precisión. Sign(Int16) Devuelve un entero que indica el signo de un entero con signo de 16 bits. Sign(Int32) Devuelve un entero que indica el signo de un entero con signo de 32 bits. Sign(Int64) Devuelve un entero que indica el signo de un entero con signo de 64 bits. Sign(SByte) Devuelve un entero que indica el signo de un entero con signo de 8 bits. Sign(Single) Devuelve un número entero que indica el signo de un número de coma flotante de precisión simple. Sin(Double) Devuelve el seno del ángulo especificado. Sinh(Double) Devuelve el seno hiperbólico del ángulo especificado. Sqrt(Double) Devuelve la raíz cuadrada de un número especificado. Tan(Double) Devuelve la tangente del ángulo especificado. Tanh(Double) Devuelve la tangente hiperbólica del ángulo especificado. Truncate(Decimal) Calcula la parte entera de un número decimal especificado. Truncate(Double) Calcula la parte entera de un número de punto flotante de precisión doble especificado. */ namespace Ejercicio9 { class Program { static void Main(string[] args) { Console.WriteLine("Excercise 9."); // Pruebas Circulo circulo = new Circulo(3.5); Rectangulo rectangulo = new Rectangulo(3.5, 3.5); Console.WriteLine($"Circulo: {circulo}"); Console.WriteLine($"Rectángulo: {rectangulo}"); Console.WriteLine(); Console.WriteLine("Area:"); Console.WriteLine($"Circulo: {circulo.Area()}"); Console.WriteLine($"Rectángulo: {rectangulo.Area()}"); Console.WriteLine(); Console.WriteLine("Perimetro:"); Console.WriteLine($"Circulo: {circulo.Perimetro()}"); Console.WriteLine($"Rectángulo: {rectangulo.Perimetro()}"); Console.WriteLine("\nPress any key to exit..."); Console.ReadKey(); } } } <file_sep>using System; /** * Tarea 3. * Autor: <NAME>. */ namespace Ejercicio14 { class VideojuegoCarreras : IVideojuego { public string Nombre { get; set; } public VideojuegoCarreras(string nombre) { Nombre = nombre; } /// <summary> /// Imprime el menú principal. /// </summary> public void MainMenu() { Console.WriteLine($":::::::: {Nombre} ::::::::"); Console.WriteLine("> Iniciar carrera <"); Console.WriteLine(" Configuraciones "); Console.WriteLine(" Créditos "); } /// <summary> /// Inicia el juego. /// </summary> public void Play() { Console.WriteLine("Comenzando carrera en..."); Console.WriteLine("\t3..."); Console.WriteLine("\t2..."); Console.WriteLine("\t1..."); } /// <summary> /// Pausa el juego. /// </summary> public void Pause() { Console.WriteLine("Juego en pausa..."); } /// <summary> /// Imprime el mensaje de Game Over. /// </summary> public void GameOver() { Console.WriteLine("Fin del juego"); } } } <file_sep>using System; /** * Tarea 3. * Autor: <NAME>. */ namespace Ejercicio11 { class Program { static void Main(string[] args) { Console.WriteLine("Excercise 11."); try { MatrixCalculator.Run(); // Run Matrix Calculator } catch (Exception ex) { if (ex is FormatException || ex is OverflowException) Console.WriteLine("You must provide a positive number"); } Console.WriteLine("\nPress any key to exit..."); Console.ReadKey(); } } } <file_sep>using System; /** * Tarea 3. * Autor: <NAME>. */ namespace Ejercicio5 { class Program { static void Main(string[] args) { Console.WriteLine("Excercise 5."); Phonebook.Run(); // Start Phonebook Console.WriteLine("\nPress any key to exit..."); Console.ReadKey(); } } } <file_sep>using System; namespace Excepciones { class Program { static void Main(string[] args) { try { Console.Write("Ingresa el numerador: "); int numerador = Convert.ToInt32(Console.ReadLine()); Console.Write("Ingresa el denominador: "); int denominador = Convert.ToInt32(Console.ReadLine()); // La división genera DivideByZeroException double resultado = numerador / denominador; Console.WriteLine("\nResultado: {0} / {1} = {2}", numerador, denominador, resultado); } catch (FormatException formatE) { Console.WriteLine("\n{0}", formatE.Message); Console.WriteLine("Debes ingresar números enteros."); } catch (DivideByZeroException divideBZE) { Console.WriteLine("\n{0}", divideBZE.Message); Console.WriteLine("El denominador no puede ser cero."); } finally { Console.WriteLine("Fin del programa"); } Console.ReadKey(); } } } <file_sep>using System; using System.Collections.Generic; namespace Listas { class Program { private static readonly string[] colors = { "Magenta", "" }; private static readonly string[] removeColors = { }; static void Main(string[] args) { List<string> list = new List<string>(); foreach(var color in colors) { list.Add(color); } List<string> removeList = new List<string>(removeColors); MostrarLista(list); Console.ReadKey(); } private static void MostrarLista(List<string> list) { foreach(string str in list) { Console.Write(str); } } } } <file_sep>using System; /** * Tarea 3. * Autor: <NAME>. */ namespace Ejercicio11 { static class MatrixCalculator { /// <summary> /// Adds two matrices. /// </summary> /// <param name="m1">First operating.</param> /// <param name="m2">Second operating.</param> /// <returns>Result of the operation.</returns> private static double[,] Addition(double[,] m1, double[,] m2) { return AdditionSubstraction(m1, m2, true); } /// <summary> /// Substracts two matrices. /// </summary> /// <param name="m1">First operating.</param> /// <param name="m2">Second operating.</param> /// <returns>Result of the operation.</returns> private static double[,] Substraction(double[,] m1, double[,] m2) { return AdditionSubstraction(m1, m2, false); } /// <summary> /// Adds or substracts two matrices <paramref name="m1"/> and /// <paramref name="m2"/>. /// </summary> /// <param name="m1">First operating.</param> /// <param name="m2">Second operating.</param> /// <param name="operation"> /// True if the operation is addition or False if the operation is /// substraction. /// </param> /// <returns>Result of the operation.</returns> private static double[,] AdditionSubstraction(double[,] m1, double[,] m2, bool operation) { // Result and indexes double[,] result = new double[m1.GetLength(0), m1.GetLength(1)]; ushort x, y; // Generate result for (y = 0; y < m1.GetLength(0); y++) for (x = 0; x < m1.GetLength(1); x++) result[y, x] = operation ? m1[y, x] + m2[y, x] : m1[y, x] - m2[y, x]; return result; } /// <summary> /// Returns the product of <paramref name="m1"/> and /// <paramref name="m2"/>. /// </summary> /// <param name="m1">First operating.</param> /// <param name="m2">Second operating.</param> /// <returns></returns> private static double[,] Product(double[,] m1, double[,] m2) { // Result and indexes double[,] result = new double[m1.GetLength(0), m1.GetLength(1)]; ushort x, y, z; // Generate result for (y = 0; y < m1.GetLength(0); y++) for (x = 0; x < m1.GetLength(1); x++) { result[y, x] = 0; for (z = 0; z < m1.GetLength(0); z++) result[y, x] += m1[y, z] * m2[z, x]; } return result; } /// <summary> /// Prints elements of the matrix <paramref name="m"/>. /// </summary> /// <param name="m">Matrix to print.</param> private static void PrintMatrix(double[,] m) { ushort x, y; // Indexes Console.WriteLine(); for (y = 0; y < m.GetLength(0); y++) { for (x = 0; x < m.GetLength(1); x++) Console.Write($"{m[y, x]}\t"); Console.WriteLine(); } } /// <summary> /// Prints the program menu. /// </summary> private static void PrintMenu() { string menu = "Select one of the following options [1-3]:\n" + "1] Matrix sum.\n2] Matrix substraction.\n3] Matrix product." + "\nOther] Exit.\n----------------------------------\nOption: "; Console.Write(menu); } /// <summary> /// Prints the matrix operation with its operatings. /// </summary> /// <param name="m1">First operating.</param> /// <param name="m2">Second operating.</param> /// <param name="m3">Result.</param> /// <param name="oper">Operator.</param> private static void PrintOperation(double[,] m1, double[,] m2, double[,] m3, string oper) { PrintMatrix(m1); Console.WriteLine($" {oper}"); PrintMatrix(m2); Console.WriteLine(" ="); PrintMatrix(m3); } /// <summary> /// Runs the MatrixCalculator program. /// </summary> public static void Run() { string option; // Selected option ushort size; // Matrix size double[,] m1; // First operating double[,] m2; // Second operating double[,] m3; // Result int x, y, z; // Indexes to iterate matrix // Print menu and get option PrintMenu(); option = Console.ReadLine(); if (option.Equals("1") || option.Equals("2") || option.Equals("3")) { // Get size and create matrices Console.Write("Enter matrix size: "); size = Convert.ToUInt16(Console.ReadLine()); m1 = new double[size, size]; m2 = new double[size, size]; // Fill matrices for (z = 1; z <= 2; z++) { Console.WriteLine(); // Line break. for (y = 0; y < size; y++) for (x = 0; x < size; x++) { Console.Write($"Enter value for M{z}[{y},{x}]: "); if (z == 1) m1[y, x] = Convert.ToDouble(Console.ReadLine()); else m2[y, x] = Convert.ToDouble(Console.ReadLine()); } } if (option.Equals("1")) // Addition { m3 = Addition(m1, m2); PrintOperation(m1, m2, m3, "+"); } else if (option.Equals("2")) // Substraction { m3 = Substraction(m1, m2); PrintOperation(m1, m2, m3, "-"); } else if (option.Equals("3")) // Product { m3 = Product(m1, m2); PrintOperation(m1, m2, m3, "*"); } } } } } <file_sep>using System; using System.Collections.Generic; using System.IO; /** * Tarea 4. * Autor: <NAME>. */ namespace Tarea4 { /// <summary> /// Class that emulates a Windows Console (CMD). /// Supported commands: /// <list type="bullet"> /// <item> /// <term>dir [DIRECTORY]</term> /// <description>Lists contents of the DIRECTORY.</description> /// </item> /// <item> /// <term>cd DIRECTORY</term> /// <description>Changes current directory to DIRECTORY.</description> /// </item> /// <item> /// <term>touch FILE_NAME</term> /// <description>Creates/Overwrites FILENAME.</description> /// </item> /// <item> /// <term>move SRC_FILE DEST_FILE</term> /// <description>Move SRC_FILE to DEST_FILE.</description> /// </item> /// <item> /// <term>history</term> /// <description>Shows the command history.</description> /// </item> /// <item> /// <term>cls</term> /// <description>Clears screen.</description> /// </item> /// <item> /// <term>exit</term> /// <description>Exit.</description> /// </item> /// </list> /// </summary> class ConsoleEmulator { /// <summary>Current working directory.</summary> private string Path_ { get; set; } /// <summary>Command Arguments.</summary> private readonly string[] Arguments; /// <summary>Directory separators characters.</summary> private readonly char[] DirSeparatorsChars; /// <summary>Command history.</summary> private readonly List<string> CommandHistory; /// <summary>Available commands.</summary> private enum Commands { DIR, // List directory CD, // Change directory TOUCH, // Create/Overwrite file MOVE, // Move file HISTORY, // Command history CLS, // Clear screen EXIT, // Exit LINEBREAK // Empty strings } /// <summary> /// ConsoleEmulartor constructor. /// </summary> public ConsoleEmulator() { Path_ = Environment.GetFolderPath(Environment.SpecialFolder .MyDocuments); // Inital path (Documents) Arguments = new string[] { "", "" }; // Command arguments // Directory Separators Characters DirSeparatorsChars = new char[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }; CommandHistory = new List<string>(); // Command history } /// <summary> /// Prints the prompt. /// </summary> private void PrintPrompt() { Console.Write($"{Path_}> "); } /// <summary> /// List content of the current directory. /// </summary> private void Dir() { string[] files; // File paths string[] dirs; // Directory paths if (string.IsNullOrWhiteSpace(Arguments[0])) // No arguments { files = Directory.GetFiles(Path_); dirs = Directory.GetDirectories(Path_); } else if (File.Exists(Path.Combine(Path_, Arguments[0]))) throw new DirectoryNotFoundException(); // Is a file else // Is a directory { files = Directory.GetFiles(Path.Combine(Path_, Arguments[0])); dirs = Directory.GetDirectories(Path.Combine(Path_, Arguments[0])); } // Print directories Console.WriteLine("Directories:"); foreach (string dir in dirs) Console.WriteLine($"\t{ dir.Split(DirSeparatorsChars)[^1] }"); // Print files Console.WriteLine("\nFiles:"); foreach (string file in files) Console.WriteLine($"\t{Path.GetFileName(file)}"); } /// <summary> /// Clears the console screen. /// </summary> private void Cls() { Console.Clear(); } /// <summary> /// Shows the command history. /// </summary> private void History() { foreach (string statement in CommandHistory) Console.WriteLine(statement); } /// <summary> /// Moves a source file to destination file. /// </summary> private void Move() { string src_file = Path.Combine(Path_, Arguments[0]); // Src. file string dst_file = Path.Combine(Path_, Arguments[1]); // Dest. file bool overwrite = false; // Flag to overwrite file if (string.IsNullOrWhiteSpace(Arguments[0])) // Not src. file throw new FormatException("Error: You must provide the " + "source path."); if (string.IsNullOrWhiteSpace(Arguments[1])) // Not dest. file throw new FormatException("Error: You must provide the " + "destination path."); if (!File.Exists(src_file)) // Src. file doesn't exist throw new FileNotFoundException(); if (Directory.Exists(dst_file)) // Dest. file is a directory dst_file = Path.Combine(dst_file, Path.GetFileName(src_file)); if (File.Exists(dst_file)) // File already exists { Console.Write("File already exists! Do you want to " + "replace it? [Y/N]: "); overwrite = Console.ReadLine().Trim().ToUpper().Equals("Y"); } if (!File.Exists(dst_file) || overwrite) // Move file File.Move(src_file, dst_file, overwrite); } /// <summary> /// Creates or overwrites a file. /// </summary> private void Touch() { string dst_file = Path.Combine(Path_, Arguments[0]); // Dest. file bool overwrite = false; // Flag to overwrite file if (string.IsNullOrWhiteSpace(Arguments[0])) // No dest. file throw new FormatException("Error: You must provide the " + "destination path."); if (File.Exists(dst_file)) // File already exists { Console.Write("File already exists! Do you want to " + "replace it? [Y/N]: "); overwrite = Console.ReadLine().Trim().ToUpper().Equals("Y"); } if (!File.Exists(dst_file) || overwrite) // Create file File.Create(dst_file).Close(); } /// <summary> /// Changes the current directory. /// </summary> private void Cd() { string newpath = Path.Combine(Path_, Arguments[0]); // Dest. Path if (File.Exists(newpath)) // Is a file throw new DirectoryNotFoundException(); else if (Directory.Exists(newpath))// Is a directory Path_ = Path.GetFullPath(newpath); else // Directory not found throw new DirectoryNotFoundException(); } /// <summary> /// Process the user input and returns the command to execute. /// </summary> /// <returns> /// Returns the Commands enum asociated to the command to execute. /// </returns> private Commands ProcessStatement() { string statement = Console.ReadLine(); // User input string[] tokens = statement.Trim().Split(" "); // Tokens Commands command = (Commands)(-1); // Init with invalid command Arguments[0] = ""; // Init first argument Arguments[1] = ""; // Init second argument if (!string.IsNullOrWhiteSpace(statement)) // It isn't an empty str { CommandHistory.Add(statement); // Add to command history if (tokens[0].Equals("dir")) // Dir { command = Commands.DIR; Arguments[0] = tokens.Length > 1 ? tokens[1] : ""; } else if (tokens[0].Equals("cd")) // Cd { command = Commands.CD; Arguments[0] = tokens.Length > 1 ? tokens[1] : ""; } else if (tokens[0].Equals("touch")) // Touch { command = Commands.TOUCH; Arguments[0] = tokens.Length > 1 ? tokens[1] : ""; } else if (tokens[0].Equals("move")) // Move { command = Commands.MOVE; Arguments[0] = tokens.Length > 1 ? tokens[1] : ""; Arguments[1] = tokens.Length > 2 ? tokens[2] : ""; } else if (tokens[0].Equals("history")) // History command = Commands.HISTORY; else if (tokens[0].Equals("cls")) // Cls command = Commands.CLS; else if (tokens[0].Equals("exit")) // Exit command = Commands.EXIT; } else // Line break command = Commands.LINEBREAK; return command; } /// <summary> /// Starts the console emulator. /// </summary> public void Run() { try { Commands command; // Command to execute PrintPrompt(); // Print prompt while ((command = ProcessStatement()) != Commands.EXIT) { if (command == Commands.DIR) // List directory Dir(); else if (command == Commands.CD) // Change directory Cd(); else if (command == Commands.TOUCH) // Create/Overwrite f. Touch(); else if (command == Commands.MOVE) // Move file Move(); else if (command == Commands.HISTORY) // List command hist. History(); else if (command == Commands.CLS) // Clear screen Cls(); else if(command != Commands.LINEBREAK) // Show input error Console.WriteLine("Error: Command " + $"{CommandHistory[^1]} not found."); Console.WriteLine(); // Line break PrintPrompt(); // Print prompt } } catch (PlatformNotSupportedException) { Console.WriteLine("Error: Platform not supported.\n"); } catch (UnauthorizedAccessException) { Console.WriteLine("Error: Unauthorized Access.\n"); Run(); } catch (System.Security.SecurityException) { Console.WriteLine("Error: Unauthorized Access.\n"); Run(); } catch (PathTooLongException) { Console.WriteLine("Error: Path is too long.\n"); Run(); } catch (DirectoryNotFoundException) { Console.WriteLine("Error: Directory not found.\n"); Run(); } catch (FileNotFoundException) { Console.WriteLine($"Error: File {Arguments[0]} not found.\n"); Run(); } catch (FormatException fe) { Console.WriteLine($"{fe.Message}\n"); Run(); } catch (NotSupportedException) { Console.WriteLine("ERROR: Path has invalid chars.\n"); Run(); } catch (IOException) { Console.WriteLine("ERROR: Invalid input.\n"); Run(); } } } } <file_sep>using System; /** * Tarea 3. * Autor: <NAME>. */ namespace Ejercicio3 { class Program { /// <summary> /// Appends an f before each vowel. /// </summary> /// <param name="str">String to append letters f.</param> private static void AppendFBeforeVowels(string str) { char[] vowels = { 'A', 'E', 'I', 'O', 'U', 'Á', 'É', 'Í', 'Ó', 'Ú' }; foreach (char c in str) { if ($"{c}".ToUpper().IndexOfAny(vowels) != -1) Console.Write("f"); Console.Write(c); } } static void Main(string[] args) { Console.WriteLine("Excercise 3."); // Get Input Console.Write("Enter a phrase: "); string str = Console.ReadLine(); // Generate output AppendFBeforeVowels(str); Console.WriteLine("\n\nPress any key to exit..."); Console.ReadKey(); } } } <file_sep>using System; /** * Tarea 3. * Autor: <NAME>. */ namespace Ejercicio7 { class Program { static void Main(string[] args) { Console.WriteLine("Excercise 7."); // Creamos números complejos NumeroComplejo c1 = new NumeroComplejo(1, 2); NumeroComplejo c2 = new NumeroComplejo(1, 2); // Impresiones Console.WriteLine("Impresiones:"); Console.Write("c1: "); c1.Imprimir(); Console.Write("c2: "); c2.Imprimir(); // Suma Console.Write("\nSuma:\nc1 + c2: "); NumeroComplejo c3 = NumeroComplejo.Suma(c1, c2); c3.Imprimir(); Console.WriteLine("\nPress any key to exit..."); Console.ReadKey(); } } } <file_sep># Tarea 4 - Emulador de consola ## Programación Orienteda a Objetos (C#) ### <NAME> <file_sep>using System; /** * Tarea 3. * Autor: <NAME>. */ namespace Ejercicio15 { class Program { static void Main(string[] args) { Console.WriteLine("Excercise 15."); Calculadora.Run(); // Ejecución de la calculadora Console.WriteLine("\nPress any key to exit..."); Console.ReadKey(); } } } <file_sep>using System; /** * Tarea 3. * Autor: <NAME>. */ namespace Ejercicio9 { class Rectangulo { /// <summary> /// Base del rectángulo. /// </summary> public double Base { get; set; } /// <summary> /// Altura del rectángulo. /// </summary> public double Altura { get; set; } /// <summary> /// Constructor de un Rectangulo. /// </summary> /// <param name="base_">Base del rectángulo.</param> /// <param name="altura">Altura del rectángulo.</param> public Rectangulo(double base_, double altura) { Base = base_; Altura = altura; } /// <summary> /// Obtiene el perímetro del rectángulo. /// </summary> /// <returns>Perímetro del rectángulo.</returns> public double Perimetro() { return (Base * 2) + (Altura * 2); } /// <summary> /// Obtiene el área del rectángulo. /// </summary> /// <returns>Área del rectángulo.</returns> public double Area() { return Base * Altura; } /// <summary> /// Obtiene la longitud de la diagonal del rectángulo. /// </summary> /// <returns>Longitud de la diagonal del rectángulo.</returns> public double Diagonal() { return Math.Sqrt(Math.Pow(Base, 2) + Math.Pow(Altura, 2)); } /// <summary> /// Retorna un nuevo rectángulo a partir de truncar la base y altura /// del rectángulo. /// </summary> /// <returns>Rectangulo con base y altura truncada.</returns> public Rectangulo TruncarRectangulo() { return new Rectangulo(Math.Truncate(Base), Math.Truncate(Altura)); } /// <summary> /// Retorna un nuevo rectángulo a partir de redondear la base y altura /// del rectángulo. /// </summary> /// <returns>Rectangulo con base y altura redondeada.</returns> public Rectangulo RedondearRectangulo() { return new Rectangulo(Math.Round(Base), Math.Round(Altura)); } /// <summary> /// Retorna la representación en cadena del rectángulo. /// </summary> /// <returns>Representación en cadena del objeto.</returns> public override string ToString() { return $"Base: {Base}, Altura: {Altura}."; } } } <file_sep>using System; using System.Linq; using System.Collections.Generic; namespace QuerySintaxis { class Program { static void Main(string[] args) { int[] numeros = { 2, 9, 5, 0, 3, 7, 4, 8, 5 }; Console.WriteLine("Arreglo original:"); Imprime(numeros); // Query obtiene los números mayores a 4 var filtered = from n in numeros where n > 4 select n; Console.WriteLine("Arreglo filtrado:"); Imprime(filtered); // Ordenar el arreglo var sorted = from n in numeros orderby n select n; Console.WriteLine("Arreglo ordenado:"); Imprime(sorted); // Ordenar el arreglo descendentemente var sortedDesc = from n in numeros orderby n descending select n; Console.WriteLine("Arreglo ordenado descendentemente:"); Imprime(sortedDesc); // Filtrados ordenados var sortedFiltered = from n in filtered orderby n select n; Console.WriteLine("Arreglo filtrado ordenado:"); Imprime(sortedFiltered); // ---------- string[] paises = { "México", "Rusia", "Austria", "Cuba", "Canadá", "Alemania", "Perú" }; // Paises cuyo nombre contiene a, ordenados por longitud. IEnumerable<string> query = from p in paises where p.Contains("a") orderby p.Length select p.ToUpper(); Console.WriteLine("Paises que contienen 'a':"); Imprime(query); // Paises cuya longitud de nombre sea mayor a 5; query = from p in paises where p.Length > 5 orderby p select p; Console.WriteLine("Paises cuya longitud de nombre es mayor a 5:"); Imprime(query); // Las iniciales de los paises IEnumerable<char> query3 = from p in paises orderby p.Length select p[0]; Console.WriteLine("Iniciales de los paises:"); Imprime(query3); Console.ReadKey(); } static void Imprime<T>(IEnumerable<T> arreglo) { foreach (var elemento in arreglo) Console.Write($" {elemento} "); Console.WriteLine(); } } } <file_sep>using System; using System.Collections.Generic; /** * Tarea 3. * Autor: <NAME>. */ namespace Ejercicio5 { static class Phonebook { private static Dictionary<string, string> phonebook = new Dictionary<string, string>(); /// <summary> /// Prompts a name to the user and adds or update its respective /// contact. /// </summary> private static void AddContact() { // Name and phone number from user input string name = GetStringFromSTDIN("Enter name: "); string number = GetStringFromSTDIN("Enter number: "); if (phonebook.ContainsKey(name)) // Update contact { phonebook[name] = number; Console.WriteLine($"Contact {name} updated successfully!"); } else // Add contact { phonebook.Add(name, number); Console.WriteLine("Contact added successfully"); } } /// <summary> /// Prompts a name to the user and deletes its respective contact. /// </summary> private static void DeleteContact() { string name = GetStringFromSTDIN("Enter name: "); // Contact name // Try to delete contact if (phonebook.Remove(name)) Console.WriteLine("Contact has been deleted successfully"); else Console.WriteLine("Contact not found."); } /// <summary> /// Prompts a name to the user and shows its respective contact. /// </summary> private static void ShowContact() { string name = GetStringFromSTDIN("Enter name: "); // Contact name // Try to get contact if (phonebook.ContainsKey(name)) Console.WriteLine($"{name}: {phonebook[name]}"); else Console.WriteLine("Contact not found."); } /// <summary> /// Prints <paramref name="msg"/> to STDOUT and gets the user input. /// </summary> /// <param name="msg">Message to print.</param> /// <returns>User input</returns> private static string GetStringFromSTDIN(string msg) { string str = ""; // Input string // Get str from user input while (str.Equals("")) { Console.Write(msg); str = Console.ReadLine(); } return str; } /// <summary> /// Prints menu with the available options. /// </summary> private static void PrintMenu() { string menu = "\nSelect one of the following options: [1-4]\n" + "1] Add contact.\n2] Delete contact.\n3] Show contact.\n" + "4] Exit.\n----------------------------------------\nOption: "; Console.Write(menu); } /// <summary> /// Runs Phonebook program. /// </summary> public static void Run() { string input = ""; // Selected option while (!input.Equals("4")) { PrintMenu(); // Show available options input = Console.ReadLine(); // Get selected option Console.WriteLine(""); switch (input) { case "1": // Add contact AddContact(); break; case "2": // Delete contact DeleteContact(); break; case "3": // Show contact ShowContact(); break; case "4": // Exit Console.WriteLine("See you!"); break; } } } } } <file_sep>using System; /** * Tarea 3. * Autor: <NAME>. */ namespace Ejercicio16 { class Estudiante { /// <summary>Nombre completo del estudiante.</summary> public string NombreCompleto { get; set; } /// <summary>Edad del estudiante.</summary> public ushort Edad { get; set; } /// <summary>Número de cuenta del estudiante.</summary> public int NumeroCuenta { get; set; } /// <summary> /// Constructor de un Estudiante. /// </summary> /// <param name="nombreCompleto">Nombre completo.</param> /// <param name="edad">Edad.</param> /// <param name="numeroCuenta">Número de cuenta.</param> public Estudiante(string nombreCompleto, ushort edad, int numeroCuenta) { NombreCompleto = nombreCompleto; Edad = edad; NumeroCuenta = numeroCuenta; } /// <summary> /// Imprime un mensaje de que el estudiante está estudiando. /// </summary> public virtual void Estudia() { Console.WriteLine($"El estudiante {NombreCompleto} está " + "estudiando."); } /// <summary> /// Imprime un mensaje de que el estudiante está haciendo tarea. /// </summary> public virtual void Tarea() { Console.WriteLine($"El estudiante {NombreCompleto} hace tarea."); } /// <summary> /// Imprime un mensaje de que el estudiante duerme. /// </summary> public virtual void Dormir() { Console.WriteLine($"El estudiante {NombreCompleto} duerme."); } } } <file_sep>using System; using System.IO; /** * Tarea 3. * Autor: <NAME>. */ /* Para la lectura de archivo podemos utilizar la clase StreamReader, el cual permite la lectura de archivos de forma sencilla. Para leer una línea simplemente utilizamos sr.ReadLine(), donde sr es una instancia de StreamReader. En caso de que ya no hayan más líneas por leer, ReadLine devolverá null. */ namespace Ejercicio18 { class Program { static void Main(string[] args) { Console.WriteLine("Excercise 18."); string file; // Archivo a leer string line; // Linea a leer Console.Write("Ingrese el nombre de archivo a desplegar su " + "contenido: "); file = Console.ReadLine(); try { using (StreamReader sr = new StreamReader(file)) { while ((line = sr.ReadLine()) != null) Console.WriteLine(line); } } catch (Exception) { Console.WriteLine($"No fue posible leer el archivo {file}."); } Console.WriteLine("\nPress any key to exit..."); Console.ReadKey(); } } } <file_sep>using System; /** * Tarea 3. * Autor: <NAME>. */ namespace Ejercicio4 { class Program { /// <summary> /// Prints first <paramref name="n"/> Fibonacci terms. /// </summary> /// <param name="n">Last fibonacci term to print.</param> /// <exception cref="System.FormatException"> /// Thrown when <paramref name="n"/> is lower than 0. /// </exception> static void FirstNFibonacciTerms(uint n) { if (n < 0) throw new FormatException(); // Vars to calculate fibonaccie sequence. ulong fib_term = 0, prev_1 = 0, prev_2 = 0, i = 0; Console.WriteLine($"Fibonacci Sequence until term {n}:"); for (; i <= n; i++) { Console.WriteLine($"f{i} = {fib_term}"); // Current term (Fn = Fn-1 + Fn-2) fib_term = fib_term == 0 ? 1 : prev_1 + prev_2; prev_2 = prev_1; // Fn-1 prev_1 = fib_term; // Fn-2 } } static void Main(string[] args) { Console.WriteLine("Excercise 4."); try { // Get input Console.Write("Enter a number: "); uint n = Convert.ToUInt32(Console.ReadLine()); // Generate output FirstNFibonacciTerms(n); } catch (FormatException) { Console.WriteLine("ERROR: You must provide a positive number."); } Console.WriteLine("\nPress any key to exit..."); Console.ReadKey(); } } } <file_sep>/** * Tarea 3. * Autor: <NAME>. */ namespace Ejercicio14 { interface IVideojuego { /// <summary> /// Imprime el menú principal. /// </summary> public void MainMenu(); /// <summary> /// Inicia el juego. /// </summary> public void Play(); /// <summary> /// Pausa el juego. /// </summary> public void Pause(); /// <summary> /// Imprime el mensaje de Game Over. /// </summary> public void GameOver(); } } <file_sep>using System; namespace Excepciones2 { class Program { static void Main(string[] args) { try { Console.Write("Ingresa un valor para calcular s raiz cuadrada: "); double dato = Convert.ToDouble(Console.ReadLine()); double resultado = RaizCuadrada(dato); Console.WriteLine("La raiz cuadrada de {0} es {1}", dato, resultado); } catch (FormatException fe) { Console.WriteLine("\n{0}", fe.Message); Console.WriteLine("Debes ingresar un número."); } catch (NegativeNumberException nne) { Console.WriteLine("\n{0}", nne.Message); Console.WriteLine("Debes ingresar un número no negativo."); } } static double RaizCuadrada(double num) { if (num < 0) throw new NegativeNumberException(); return Math.Sqrt(num); } } } <file_sep>using System; /** * Tarea 3. * Autor: <NAME>. */ namespace Ejercicio13 { class Carro { /// <summary>Peso del carro.</summary> public double Peso { get; set; } /// <summary>Altura del carro.</summary> public double Altura { get; set; } /// <summary> /// Estado del carro. (True: Encendido, False: Apagado) /// </summary> public bool Encendido { get; set; } /// <summary> /// Constructor de un Carro. /// </summary> /// <param name="peso">Peso del carro.</param> /// <param name="altura">Altura del carro.</param> public Carro(double peso, double altura) { Peso = peso; Altura = altura; } /// <summary> /// Enciende el carro. /// </summary> public void Encender() { Encendido = true; Console.WriteLine("El carro está encendido."); } /// <summary> /// Apaga el carro. /// </summary> public void Apagar() { Encendido = false; Console.WriteLine("El carro está apagado."); } /// <summary> /// Retorna el estado del carro. True: Encendido, False: Apagado. /// </summary> /// <returns></returns> public bool Estado() { return Encendido; } /// <summary> /// Retorna la representación en cadena del carro. /// </summary> /// <returns>Representación en cadena del carro.</returns> public override string ToString() { return $"El peso es: {Peso:N0}.\nLa altura es: {Altura:F2}."; } } } <file_sep>/** * Tarea 3. * Autor: <NAME>. */ namespace Ejercicio13 { class CarroBMW : Carro { /// <summary>Modelo del carro.</summary> public string Modelo { get; set; } /// <summary> /// Constructor de un CarroBMW. /// </summary> /// <param name="peso">Peso del carro.</param> /// <param name="altura">Altura del carro.</param> /// <param name="modelo">Modelo del carro.</param> public CarroBMW(double peso, double altura, string modelo) : base(peso, altura) { Modelo = modelo; } /// <summary> /// Retorna la representación en cadena del carro. /// </summary> /// <returns>Representación en cadena del carro.</returns> public override string ToString() { return $"El modelo es: {Modelo}.\nEl peso es: {Peso:N0}.\n" + $"La altura es: {Altura:F2}.\nTengo turbo."; } } } <file_sep>using System; /** * Tarea 3. * Autor: <NAME>. */ namespace Ejercicio2 { class Program { /// <summary> /// Verify if <paramref name="number"/> is multiple of /// <paramref name="match"/> or it contains <paramref name="match"/>. /// </summary> /// <param name="number">Number to analize.</param> /// <param name="match">Number to match.</param> /// <returns></returns> private static bool MatchNumber(int number, int match) { return (number % match == 0) || ($"{number}".Contains($"{match}")); } /// <summary> /// Print all numbers between 1 and 100 but if the number is multiple /// of <paramref name="n1"/> or <paramref name="n2"/>, or it contains /// one of them, the program prints 'clap'. /// </summary> /// <param name="n1">Number between 1 and 9 to check matches.</param> /// <param name="n2">Number between 1 and 9 to check matches.</param> /// <exception cref="System.FormatException"> /// Thrown when <paramref name="n1"/> or <paramref name="n2"/> are /// not between 1 and 9. /// </exception> private static void PrintNumberList(int n1, int n2) { if (n1 < 1 || n1 > 9 || n2 < 1 || n2 > 9) throw new FormatException(); int number = 1; for (; number <= 100; number++) { if (MatchNumber(number, n1) || MatchNumber(number, n2)) Console.WriteLine("clap"); else Console.WriteLine(number); } } static void Main(string[] args) { Console.WriteLine("Excercise 2."); try { // Get input Console.Write("Enter a number between 1 and 9: "); int n1 = Convert.ToInt32(Console.ReadLine()); Console.Write("Enter another number between 1 and 9: "); int n2 = Convert.ToInt32(Console.ReadLine()); // Generate output PrintNumberList(n1, n2); } catch (FormatException) { Console.WriteLine("ERROR: You must provide a number between " + "1 and 9."); } Console.WriteLine("\nPress any key to exit..."); Console.ReadKey(); } } }
5597693dc3760e63427ab6498aa2ef73bcb3dfa9
[ "Markdown", "C#" ]
55
C#
AlexisLM/CSharpCERT
9f9ec78f4f360f22803415dd38f413b3d197e50d
a822dd67d26dafbfa83c104fe6c17279fbd14db9
refs/heads/master
<repo_name>Soap-ya/remove-location-and-phone-info<file_sep>/README.md # remove-location-and-phone-info This is just a simple shell script that uses exiftool to remove the GPS information as well as the camera make and model information from a JPEG file. ### USAGE: ./removeLocationAndPhoneInfo.sh $FILENAME.JPEG **Note:** You need `exiftool` installed on your Linux/Mac for this script to work. <file_sep>/removeLocationAndPhoneInfo.sh #!/bin/bash echo "Input file is $1 and here's all the camera and location metadata in image" exiftool '-*lens*' $1 exiftool '-gps:all' $1 exiftool '-make' $1 exiftool '-model' $1 echo "Removing all this metadata" exiftool -*lensinfo*= $1 exiftool -*lensmodel*= $1 exiftool -*lensmake*= $1 exiftool -gps:all= $1 exiftool -make= $1 exiftool -model= $1
318ab1cc6783106ae3fc3ae120ec78d76f6a0757
[ "Markdown", "Shell" ]
2
Markdown
Soap-ya/remove-location-and-phone-info
c16dd770a969b737bec8d5a4b1401077738e93f5
c96dc212781177f887ad669776f4ddfb2a9cabe2
refs/heads/master
<repo_name>cybertec-postgresql/pg_timetable<file_sep>/internal/pgengine/access_test.go package pgengine_test import ( "context" "errors" "testing" "github.com/cybertec-postgresql/pg_timetable/internal/pgengine" "github.com/pashagolub/pgxmock/v2" "github.com/stretchr/testify/assert" ) func TestDeleteChainConfig(t *testing.T) { initmockdb(t) pge := pgengine.NewDB(mockPool, "pgengine_unit_test") defer mockPool.Close() t.Run("Check DeleteChainConfig if everyhing fine", func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), pgengine.WaitTime+2) defer cancel() mockPool.ExpectExec("DELETE FROM timetable\\.chain").WithArgs(pgxmock.AnyArg()).WillReturnResult(pgxmock.NewResult("EXECUTE", 1)) assert.True(t, pge.DeleteChain(ctx, 0)) }) t.Run("Check DeleteChainConfig if sql fails", func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), pgengine.WaitTime+2) defer cancel() mockPool.ExpectExec("DELETE FROM timetable\\.chain").WithArgs(pgxmock.AnyArg()).WillReturnError(errors.New("error")) assert.False(t, pge.DeleteChain(ctx, 0)) }) assert.NoError(t, mockPool.ExpectationsWereMet(), "there were unfulfilled expectations") } func TestInsertChainRunStatus(t *testing.T) { initmockdb(t) pge := pgengine.NewDB(mockPool, "pgengine_unit_test") pge.ClientName = "test_client" defer mockPool.Close() mockPool.ExpectExec("INSERT INTO timetable\\.active_chain"). WithArgs(0, pge.ClientName, 1). WillReturnError(errors.New("error")) pge.InsertChainRunStatus(context.Background(), 0, 1) assert.NoError(t, mockPool.ExpectationsWereMet(), "there were unfulfilled expectations") } func TestRemoveChainRunStatus(t *testing.T) { initmockdb(t) pge := pgengine.NewDB(mockPool, "pgengine_unit_test") pge.ClientName = "test_client" defer mockPool.Close() mockPool.ExpectExec("DELETE FROM timetable\\.active_chain"). WithArgs(0, pge.ClientName). WillReturnError(errors.New("error")) pge.RemoveChainRunStatus(context.Background(), 0) assert.NoError(t, mockPool.ExpectationsWereMet(), "there were unfulfilled expectations") } func TestSelectChains(t *testing.T) { var c []pgengine.Chain var ic []pgengine.IntervalChain initmockdb(t) pge := pgengine.NewDB(mockPool, "pgengine_unit_test") defer mockPool.Close() for i := 0; i < 3; i++ { mockPool.ExpectQuery("SELECT.+chain_id").WithArgs(pgxmock.AnyArg()).WillReturnError(errors.New("error")) mockPool.ExpectQuery("SELECT.+chain_id").WithArgs(pgxmock.AnyArg()).WillReturnRows(pgxmock.NewRows([]string{"foo"}).AddRow("baz")) } assert.Error(t, pge.SelectChains(context.Background(), &c)) assert.Error(t, pge.SelectChains(context.Background(), &c), "unacceptable columns") assert.Error(t, pge.SelectRebootChains(context.Background(), &c)) assert.Error(t, pge.SelectRebootChains(context.Background(), &c), "unacceptable columns") assert.Error(t, pge.SelectIntervalChains(context.Background(), &ic)) assert.Error(t, pge.SelectIntervalChains(context.Background(), &ic), "unacceptable columns") } func TestSelectChain(t *testing.T) { initmockdb(t) pge := pgengine.NewDB(mockPool, "pgengine_unit_test") defer mockPool.Close() mockPool.ExpectExec("SELECT.+chain_id").WillReturnError(errors.New("error")) assert.Error(t, pge.SelectChain(context.Background(), &pgengine.Chain{}, 42)) } func TestIsAlive(t *testing.T) { initmockdb(t) pge := pgengine.NewDB(mockPool, "pgengine_unit_test") defer mockPool.Close() mockPool.ExpectPing() assert.True(t, pge.IsAlive()) } func TestLogChainElementExecution(t *testing.T) { initmockdb(t) pge := pgengine.NewDB(mockPool, "pgengine_unit_test") defer mockPool.Close() t.Run("Check LogChainElementExecution if sql fails", func(t *testing.T) { mockPool.ExpectExec("INSERT INTO .*execution_log").WithArgs( pgxmock.AnyArg(), pgxmock.AnyArg(), pgxmock.AnyArg(), pgxmock.AnyArg(), pgxmock.AnyArg(), pgxmock.AnyArg(), pgxmock.AnyArg(), pgxmock.AnyArg(), pgxmock.AnyArg(), pgxmock.AnyArg()). WillReturnError(errors.New("Failed to log chain element execution status")) pge.LogTaskExecution(context.Background(), &pgengine.ChainTask{}, 0, "STATUS") }) assert.NoError(t, mockPool.ExpectationsWereMet(), "there were unfulfilled expectations") } <file_sep>/go.mod module github.com/cybertec-postgresql/pg_timetable go 1.21 require ( github.com/cavaliercoder/grab v2.0.0+incompatible github.com/jackc/pgx/v5 v5.4.3 github.com/jessevdk/go-flags v1.5.0 github.com/ory/mail/v3 v3.0.1-0.20210418065910-7f033ddea8dc github.com/pashagolub/pgxmock/v2 v2.11.0 github.com/rifflock/lfshook v0.0.0-20180920164130-b9218ef580f5 github.com/sethvargo/go-retry v0.2.4 github.com/sirupsen/logrus v1.9.3 github.com/spf13/viper v1.16.0 github.com/stretchr/testify v1.8.4 gopkg.in/natefinch/lumberjack.v2 v2.2.1 ) require ( github.com/davecgh/go-spew v1.1.1 // indirect github.com/fsnotify/fsnotify v1.6.0 // indirect github.com/hashicorp/hcl v1.0.0 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect github.com/jackc/puddle/v2 v2.2.1 // indirect github.com/magiconair/properties v1.8.7 // indirect github.com/mitchellh/mapstructure v1.5.0 // indirect github.com/pelletier/go-toml/v2 v2.0.8 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect github.com/spf13/afero v1.9.5 // indirect github.com/spf13/cast v1.5.1 // indirect github.com/spf13/jwalterweatherman v1.1.0 // indirect github.com/spf13/pflag v1.0.5 // indirect github.com/subosito/gotenv v1.4.2 // indirect golang.org/x/crypto v0.10.0 // indirect golang.org/x/sync v0.3.0 // indirect golang.org/x/sys v0.9.0 // indirect golang.org/x/text v0.11.0 // indirect gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) <file_sep>/.gitpod.dockerfile FROM gitpod/workspace-full:latest # Docker build does not rebuild an image when a base image is changed, increase this counter to trigger it. ENV TRIGGER_REBUILD=2 # Install PostgreSQL RUN sudo sh -c 'echo "deb http://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list' RUN wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add - RUN sudo apt-get update RUN sudo apt-get -y install postgresql postgresql-contrib # Check PostgreSQL service is running RUN sudo service postgresql start \ && until pg_isready; do sleep 1; done \ # Create the PostgreSQL user. # Hack with double sudo is because gitpod user cannot run command on behalf of postgres user. && sudo sudo -u postgres psql \ -c "CREATE USER gitpod PASSWORD '<PASSWORD>' SUPERUSER" \ -c "CREATE DATABASE gitpod OWNER gitpod" # This is a bit of a hack. At the moment we have no means of starting background # tasks from a Dockerfile. This workaround checks, on each bashrc eval, if the # PostgreSQL server is running, and if not starts it. RUN printf "\n# Auto-start PostgreSQL server.\nsudo service postgresql start\n" >> ~/.bashrc<file_sep>/samples/NoOp.sql SELECT timetable.add_job( job_name => 'execute noop every minute', job_schedule => '* * * * *', job_command => 'NoOp', job_kind => 'BUILTIN'::timetable.command_kind ) as chain_id;<file_sep>/internal/scheduler/interval_chain_test.go package scheduler import ( "context" "testing" "github.com/cybertec-postgresql/pg_timetable/internal/config" "github.com/cybertec-postgresql/pg_timetable/internal/log" "github.com/cybertec-postgresql/pg_timetable/internal/pgengine" "github.com/pashagolub/pgxmock/v2" "github.com/stretchr/testify/assert" ) func TestIntervalChain(t *testing.T) { mock, err := pgxmock.NewPool(pgxmock.MonitorPingsOption(true)) assert.NoError(t, err) pge := pgengine.NewDB(mock, "scheduler_unit_test") sch := New(pge, log.Init(config.LoggingOpts{LogLevel: "error"})) ichain := IntervalChain{Interval: 42} assert.True(t, ichain.IsListed([]IntervalChain{ichain})) assert.False(t, ichain.IsListed([]IntervalChain{})) assert.False(t, sch.isValid(ichain)) sch.intervalChains[ichain.ChainID] = ichain assert.True(t, sch.isValid(ichain)) t.Run("Check reschedule if self destructive", func(t *testing.T) { mock.ExpectExec("INSERT INTO timetable\\.log").WillReturnResult(pgxmock.NewResult("EXECUTE", 1)) mock.ExpectExec("DELETE").WillReturnResult(pgxmock.NewResult("EXECUTE", 1)) ichain.SelfDestruct = true sch.reschedule(context.Background(), ichain) }) t.Run("Check reschedule if context cancelled", func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) cancel() ichain.SelfDestruct = false sch.reschedule(ctx, ichain) }) t.Run("Check reschedule if everything fine", func(t *testing.T) { ichain.Interval = 1 sch.reschedule(context.Background(), ichain) }) } <file_sep>/internal/pgengine/log_hook.go package pgengine import ( "context" "encoding/json" "time" pgx "github.com/jackc/pgx/v5" "github.com/sirupsen/logrus" ) // LogHook is the implementation of the logrus hook for pgx type LogHook struct { cacheLimit int // hold this number of entries before flush to database cacheTimeout time.Duration // wait this amount of time before flush to database highLoadTimeout time.Duration // wait this amount of time before skip log entry db PgxPoolIface input chan logrus.Entry ctx context.Context lastError chan error pid int32 client string level string } // NewHook creates a LogHook to be added to an instance of logger func NewHook(ctx context.Context, pge *PgEngine, level string) *LogHook { cacheLimit := 500 l := &LogHook{ cacheLimit: cacheLimit, cacheTimeout: 2 * time.Second, highLoadTimeout: 200 * time.Millisecond, db: pge.ConfigDb, input: make(chan logrus.Entry, cacheLimit), lastError: make(chan error), ctx: ctx, pid: pge.Getsid(), client: pge.ClientName, level: level, } go l.poll(l.input) return l } // Fire adds logrus log message to the internal queue for processing func (hook *LogHook) Fire(entry *logrus.Entry) error { if hook.ctx.Err() != nil { return nil } select { case hook.input <- *entry: // entry sent case <-time.After(hook.highLoadTimeout): // entry dropped due to a huge load, check stdout or file for detailed log } select { case err := <-hook.lastError: return err default: return nil } } // Levels returns the available logging levels func (hook *LogHook) Levels() []logrus.Level { switch hook.level { case "none": return []logrus.Level{} case "debug": return logrus.AllLevels case "info": return []logrus.Level{ logrus.PanicLevel, logrus.FatalLevel, logrus.ErrorLevel, logrus.WarnLevel, logrus.InfoLevel, } default: return []logrus.Level{ logrus.PanicLevel, logrus.FatalLevel, logrus.ErrorLevel, } } } // poll checks for incoming messages and caches them internally // until either a maximum amount is reached, or a timeout occurs. func (hook *LogHook) poll(input <-chan logrus.Entry) { cache := make([]logrus.Entry, 0, hook.cacheLimit) tick := time.NewTicker(hook.cacheTimeout) for { select { case <-hook.ctx.Done(): //check context with high priority return default: select { case entry := <-input: cache = append(cache, entry) if len(cache) < hook.cacheLimit { break } tick.Stop() hook.send(cache) cache = cache[:0] tick = time.NewTicker(hook.cacheTimeout) case <-tick.C: hook.send(cache) cache = cache[:0] case <-hook.ctx.Done(): return } } } } func adaptEntryLevel(level logrus.Level) string { switch level { case logrus.TraceLevel, logrus.DebugLevel: return "DEBUG" case logrus.InfoLevel, logrus.WarnLevel: return "INFO" case logrus.ErrorLevel: return "ERROR" case logrus.FatalLevel, logrus.PanicLevel: return "PANIC" } return "UNKNOWN" } // send sends cached messages to the postgres server func (hook *LogHook) send(cache []logrus.Entry) { if len(cache) == 0 { return // Nothing to do here. } _, err := hook.db.CopyFrom( hook.ctx, pgx.Identifier{"timetable", "log"}, []string{"ts", "client_name", "pid", "log_level", "message", "message_data"}, pgx.CopyFromSlice(len(cache), func(i int) ([]interface{}, error) { jsonData, err := json.Marshal(cache[i].Data) if err != nil { return nil, err } return []interface{}{cache[i].Time, hook.client, hook.pid, adaptEntryLevel(cache[i].Level), cache[i].Message, jsonData}, nil }), ) if err != nil { select { case hook.lastError <- err: //error sent to the logger default: //there is unprocessed error already } } } <file_sep>/docs/conf.py # Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html from __future__ import division, print_function, unicode_literals from datetime import datetime from recommonmark.parser import CommonMarkParser extensions = [] templates_path = ['templates', '_templates', '.templates'] source_suffix = ['.rst', '.md'] source_parsers = { '.md': CommonMarkParser, } project = u'pg_timetable' copyright = str(datetime.now().year) # -- Options for EPUB output epub_show_urls = "footnote" exclude_patterns = ['_build'] pygments_style = 'sphinx' htmlhelp_basename = 'pg-timetable' html_theme = 'sphinx_rtd_theme' file_insertion_enabled = False latex_documents = [ ('index', 'pg-timetable.tex', u'pg_timetable Documentation', u'', 'manual'), ] <file_sep>/README.md [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://opensource.org/licenses/MIT) ![](https://github.com/cybertec-postgresql/pg_timetable/workflows/Go%20Build%20&%20Test/badge.svg) [![Coverage Status](https://coveralls.io/repos/github/cybertec-postgresql/pg_timetable/badge.svg?branch=master&service=github)](https://coveralls.io/github/cybertec-postgresql/pg_timetable?branch=master) [![Documentation Status](https://readthedocs.org/projects/pg-timetable/badge/?version=master)](https://pg-timetable.readthedocs.io/en/master/?badge=master) [![Release](https://img.shields.io/github/v/release/cybertec-postgresql/pg_timetable?include_prereleases)](https://github.com/cybertec-postgresql/pg_timetable/releases) [![Github All Releases](https://img.shields.io/github/downloads/cybertec-postgresql/pg_timetable/total?style=flat-square)](https://github.com/cybertec-postgresql/pg_timetable/releases) [![Docker Pulls](https://img.shields.io/docker/pulls/cybertecpostgresql/pg_timetable)](https://hub.docker.com/r/cybertecpostgresql/pg_timetable) [![Go Report Card](https://goreportcard.com/badge/github.com/cybertec-postgresql/pg_timetable)](https://goreportcard.com/report/github.com/cybertec-postgresql/pg_timetable) [![Mentioned in Awesome Go](https://awesome.re/mentioned-badge.svg)](https://github.com/avelino/awesome-go) pg_timetable: Advanced scheduling for PostgreSQL ================================================ **pg_timetable** is an advanced standalone job scheduler for PostgreSQL, offering many advantages over traditional schedulers such as **cron** and others. It is completely database driven and provides a couple of advanced concepts. It allows you to schedule PostgreSQL commands, system programs and built-in operations: ```sql -- Run public.my_func() at 00:05 every day in August: SELECT timetable.add_job('execute-func', '5 0 * 8 *', 'SELECT public.my_func()'); -- Run VACUUM at minute 23 past every 2nd hour from 0 through 20 every day: SELECT timetable.add_job('run-vacuum', '23 0-20/2 * * *', 'VACUUM'); -- Refresh materialized view every 2 hours: SELECT timetable.add_job('refresh-matview', '@every 2 hours', 'REFRESH MATERIALIZED VIEW public.mat_view'); -- Clear log table after pg_timetable restart: SELECT timetable.add_job('clear-log', '@reboot', 'TRUNCATE public.log'); -- Reindex at midnight on Sundays with reindexdb utility: -- using default database under default user (no command line arguments) SELECT timetable.add_job('reindex-job', '0 0 * * 7', 'reindexdb', job_kind := 'PROGRAM'); -- specifying target database and tables, and be verbose SELECT timetable.add_job('reindex-job', '0 0 * * 7', 'reindexdb', '["--table=foo", "--dbname=postgres", "--verbose"]'::jsonb, 'PROGRAM'); -- passing password using environment variable through bash shell SELECT timetable.add_job('reindex-job', '0 0 * * 7', 'bash', '["-c", "PGPASSWORD=<PASSWORD> reindexdb -U postgres -h 192.168.0.221 -v'::jsonb, 'PROGRAM'); ``` ## Documentation https://pg-timetable.readthedocs.io/ ## Main features - Tasks can be arranged in chains - Each task executes SQL, built-in or executable command - Parameters can be passed to tasks - Missed chains (possibly due to downtime) can be retried automatically - Support for configurable repetitions - Builtin tasks such as sending emails, downloading, importing files, etc. - Fully database driven configuration - Full support for database driven logging - Enhanced cron-style scheduling - Optional concurrency protection ## [Installation](https://pg-timetable.readthedocs.io/en/master/installation.html) Complete installation guide can be found in the [documentation](https://pg-timetable.readthedocs.io/en/master/installation.html). Possible choices are: - official [release packages](https://github.com/cybertec-postgresql/pg_timetable/releases); - [Docker images](https://hub.docker.com/r/cybertecpostgresql/pg_timetable); - [build from sources](https://pg-timetable.readthedocs.io/en/master/installation.html#build-from-sources). ## [Quick Start](https://pg-timetable.readthedocs.io/en/master/README.html#quick-start) Complete usage guide can be found in the [documentation](https://pg-timetable.readthedocs.io/en/master/basic_jobs.html). 1. Download **pg_timetable** executable 2. Make sure your **PostgreSQL** server is up and running and has a role with `CREATE` privilege for a target database, e.g. ```sql my_database=> CREATE ROLE scheduler PASSWORD '<PASSWORD>'; my_database=> GRANT CREATE ON DATABASE my_database TO scheduler; ``` 3. Create a new job, e.g. run `VACUUM` each night at 00:30 ```sql my_database=> SELECT timetable.add_job('frequent-vacuum', '30 0 * * *', 'VACUUM'); add_job --------- 3 (1 row) ``` 4. Run the pg_timetable ```terminal # pg_timetable postgresql://scheduler:somestrong@localhost/my_database --clientname=vacuumer ``` 5. PROFIT! ## Supported Environments | Cloud Service | Supported | PostgreSQL Version | Supported | OS | Supported | | ---------------- |:---------:| ------------------- |:---------:| -- |:---------:| | [Alibaba Cloud] | ✅ | [17 (devel)] | ✅ | Linux | ✅ | | [Amazon RDS] | ✅ | [16 (beta)] | ✅ | Darwin | ✅ | | [Amazon Aurora] | ✅ | [15 (current)] | ✅ | Windows | ✅ | | [Azure] | ✅ | [14] | ✅ | FreeBSD\* | ✅ | | [Citus Cloud] | ✅ | [13] | ✅ | NetBSD\* | ✅ | | [Crunchy Bridge] | ✅ | [12] | ✅ | OpenBSD\* | ✅ | | [DigitalOcean] | ✅ | [11] | ✅ | Solaris\* | ✅ | | [Google Cloud] | ✅ | [10] | ✅ | [Heroku] | ✅ | | [Supabase] | ✅ | \* - there are no official release binaries made for these OSes. One would need to [build them from sources](https://pg-timetable.readthedocs.io/en/master/installation.html#build-from-sources). \** - previous PostgreSQL versions may and should work smoothly. Only [officially supported PostgreSQL versions](https://www.postgresql.org/support/versioning/) are listed in this table. [Alibaba Cloud]: https://www.alibabacloud.com/help/doc-detail/96715.htm [Amazon RDS]: https://aws.amazon.com/rds/postgresql/ [Amazon Aurora]: https://aws.amazon.com/rds/aurora/ [Azure]: https://azure.microsoft.com/en-us/services/postgresql/ [Citus Cloud]: https://www.citusdata.com/product/cloud [Crunchy Bridge]: https://www.crunchydata.com/products/crunchy-bridge/ [DigitalOcean]: https://www.digitalocean.com/products/managed-databases/ [Google Cloud]: https://cloud.google.com/sql/docs/postgres/ [Heroku]: https://elements.heroku.com/addons/heroku-postgresql [Supabase]: https://supabase.io/docs/guides/database [17 (devel)]: https://www.postgresql.org/docs/devel/index.html [16 (beta)]: https://www.postgresql.org/docs/16/index.html [15 (current)]: https://www.postgresql.org/docs/15/index.html [14]: https://www.postgresql.org/docs/14/index.html [13]: https://www.postgresql.org/docs/13/index.html [12]: https://www.postgresql.org/docs/12/index.html [11]: https://www.postgresql.org/docs/11/index.html [10]: https://www.postgresql.org/docs/10/index.html [Alibaba Cloud]: https://www.alibabacloud.com/help/doc-detail/96715.htm [Amazon RDS]: https://aws.amazon.com/rds/postgresql/ [Amazon Aurora]: https://aws.amazon.com/rds/aurora/ [Azure]: https://azure.microsoft.com/en-us/services/postgresql/ [Citus Cloud]: https://www.citusdata.com/product/cloud [Crunchy Bridge]: https://www.crunchydata.com/products/crunchy-bridge/ [DigitalOcean]: https://www.digitalocean.com/products/managed-databases/ [Google Cloud]: https://cloud.google.com/sql/docs/postgres/ [Heroku]: https://elements.heroku.com/addons/heroku-postgresql [Supabase]: https://supabase.io/docs/guides/database [14 (devel)]: https://www.postgresql.org/docs/devel/index.html [13 (current)]: https://www.postgresql.org/docs/13/index.html [12]: https://www.postgresql.org/docs/12/index.html [11]: https://www.postgresql.org/docs/11/index.html [10]: https://www.postgresql.org/docs/10/index.html [9.6]: https://www.postgresql.org/docs/9.6/index.html ## Contributing [![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/cybertec-postgresql/pg_timetable) If you want to contribute to **pg_timetable** and help make it better, feel free to open an [issue][issue] or even consider submitting a [pull request][PR]. [issue]: https://github.com/cybertec-postgresql/pg_timetable/issues [PR]: https://github.com/cybertec-postgresql/pg_timetable/pulls ## Support For professional support, please contact [Cybertec](https://www.cybertec-postgresql.com/). ## Authors - Implementation: [<NAME>](https://github.com/pashagolub) - Initial idea and draft design: [<NAME>](https://github.com/postgresql007) ## Star History [![Star History Chart](https://api.star-history.com/svg?repos=cybertec-postgresql/pg_timetable&type=Date)](https://star-history.com/#cybertec-postgresql/pg_timetable&Date) <file_sep>/internal/pgengine/sql_embed.go package pgengine import ( //use blank embed import _ "embed" ) //go:embed sql/init.sql var sqlInit string //go:embed sql/cron.sql var sqlCron string //go:embed sql/ddl.sql var sqlDDL string //go:embed sql/job_functions.sql var sqlJobFunctions string //go:embed sql/json_schema.sql var sqlJSONSchema string <file_sep>/internal/pgengine/migration_test.go package pgengine_test import ( "context" _ "embed" "testing" "github.com/cybertec-postgresql/pg_timetable/internal/migrator" "github.com/cybertec-postgresql/pg_timetable/internal/pgengine" "github.com/stretchr/testify/assert" ) //go:embed sql/migrations/00000.sql var initialsql string func TestMigrations(t *testing.T) { teardownTestCase := SetupTestCase(t) defer teardownTestCase(t) ctx := context.Background() _, err := pge.ConfigDb.Exec(ctx, "DROP SCHEMA IF EXISTS timetable CASCADE") assert.NoError(t, err) _, err = pge.ConfigDb.Exec(ctx, string(initialsql)) assert.NoError(t, err) ok, err := pge.CheckNeedMigrateDb(ctx) assert.NoError(t, err) assert.True(t, ok, "Should need migrations") assert.NoError(t, pge.MigrateDb(ctx), "Migrations should be applied") _, err = pge.ConfigDb.Exec(ctx, "DROP SCHEMA IF EXISTS timetable CASCADE") assert.NoError(t, err) _, err = pge.CheckNeedMigrateDb(ctx) assert.NoError(t, err) } func TestExecuteMigrationScript(t *testing.T) { assert.Error(t, pgengine.ExecuteMigrationScript(context.Background(), nil, "foo"), "File does not exist") } func TestInitMigrator(t *testing.T) { teardownTestCase := SetupTestCase(t) defer teardownTestCase(t) pgengine.Migrations = func() migrator.Option { return migrator.Migrations() } ctx := context.Background() err := pge.MigrateDb(ctx) assert.Error(t, err, "Empty migrations") _, err = pge.CheckNeedMigrateDb(ctx) assert.Error(t, err, "Empty migrations") } <file_sep>/samples/Shell.sql -- An example for using the PROGRAM task. SELECT timetable.add_job( job_name => 'psql chain', job_schedule => '* * * * *', job_kind => 'PROGRAM'::timetable.command_kind, job_command => 'psql', job_parameters => ('[ "-h", "' || host(inet_server_addr()) || '", "-p", "' || inet_server_port() || '", "-d", "' || current_database() || '", "-U", "' || current_user || '", "-w", "-c", "SELECT now();" ]')::jsonb ) as chain_id;<file_sep>/main.go package main import ( "context" "fmt" "os" "os/signal" "runtime/debug" "syscall" "github.com/cybertec-postgresql/pg_timetable/internal/api" "github.com/cybertec-postgresql/pg_timetable/internal/config" "github.com/cybertec-postgresql/pg_timetable/internal/log" "github.com/cybertec-postgresql/pg_timetable/internal/pgengine" "github.com/cybertec-postgresql/pg_timetable/internal/scheduler" ) /** * pg_timetable is the daemon application responsible to execute scheduled SQL tasks that cannot be triggered by the * PostgreSQL server (PostgreSQL does not support time triggers). * * This application may run on the same machine as PostgreSQL server and must grant full access permission to the * timetable tables. */ var pge *pgengine.PgEngine // SetupCloseHandler creates a 'listener' on a new goroutine which will notify the // program if it receives an interrupt from the OS. We then handle this by calling // our clean up procedure and exiting the program. func SetupCloseHandler(cancel context.CancelFunc) { c := make(chan os.Signal, 2) signal.Notify(c, os.Interrupt, syscall.SIGTERM) go func() { <-c cancel() exitCode = ExitCodeUserCancel }() } const ( ExitCodeOK int = iota ExitCodeConfigError ExitCodeDBEngineError ExitCodeUpgradeError ExitCodeUserCancel ExitCodeShutdownCommand ExitCodeFatalError ) var exitCode = ExitCodeOK // version output variables var ( commit = "000000" version = "master" date = "unknown" dbapi = "00573" ) func printVersion() { fmt.Printf(`pg_timetable: Version: %s DB Schema: %s Git Commit: %s Built: %s `, version, dbapi, commit, date) } func main() { cmdOpts, err := config.NewConfig(os.Stdout) if err != nil { if cmdOpts != nil && cmdOpts.VersionOnly() { printVersion() return } fmt.Println("Configuration error: ", err) exitCode = ExitCodeConfigError return } if cmdOpts.Version { printVersion() } logger := log.Init(cmdOpts.Logging) ctx, cancel := context.WithCancel(context.Background()) SetupCloseHandler(cancel) defer func() { cancel() if err := recover(); err != nil { exitCode = ExitCodeFatalError logger.WithField("callstack", string(debug.Stack())).Error(err) } os.Exit(exitCode) }() apiserver := api.Init(cmdOpts.RESTApi, logger) if pge, err = pgengine.New(ctx, *cmdOpts, logger); err != nil { logger.WithError(err).Error("Connection failed") exitCode = ExitCodeDBEngineError return } defer pge.Finalize() if cmdOpts.Start.Upgrade { if err := pge.MigrateDb(ctx); err != nil { logger.WithError(err).Error("Upgrade failed") exitCode = ExitCodeUpgradeError return } } else { if upgrade, err := pge.CheckNeedMigrateDb(ctx); upgrade || err != nil { if upgrade { logger.Error("You need to upgrade your database before proceeding, use --upgrade option") } if err != nil { logger.WithError(err).Error("Migration check failed") } exitCode = ExitCodeUpgradeError return } } if cmdOpts.Start.Init { return } sch := scheduler.New(pge, logger) apiserver.APIHandler = sch if sch.Run(ctx) == scheduler.ShutdownStatus { exitCode = ExitCodeShutdownCommand } } <file_sep>/docs/migration.rst Migration from others schedulers ================================================ Migrate jobs from pg_cron to pg_timetable ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If you want to quickly export jobs scheduled from *pg_cron* to *pg_timetable*, you can use this SQL snippet: .. literalinclude:: ../extras/pg_cron_to_pg_timetable_simple.sql :linenos: :language: SQL The *timetable.add_job()*, however, has some limitations. First of all, the function will mark the task created as **autonomous**, specifying scheduler should execute the task out of the chain transaction. It's not an error, but many autonomous chains may cause some extra connections to be used. Secondly, database connection parameters are lost for source *pg_cron* jobs, making all jobs local. To export every information available precisely as possible, use this SQL snippet under the role they were scheduled in *pg_cron*: .. literalinclude:: ../extras/pg_cron_to_pg_timetable.sql :linenos: :language: SQL Migrate jobs from pgAgent to pg_timetable ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ To migrate jobs from **pgAgent**, please use this script. **pgAgent** doesn't have concept of *PROGRAM* task, thus to emulate *BATCH* steps, **pg_timetable** will execute them inside the shell. You may change the shell by editing *cte_shell* CTE clause. .. literalinclude:: ../extras/pgagent_to_pg_timetable.sql :linenos: :language: SQL<file_sep>/internal/tasks/mail_test.go package tasks import ( "context" "testing" gomail "github.com/ory/mail/v3" "github.com/stretchr/testify/assert" ) type fakeDialer struct { Dialer } func (d *fakeDialer) DialAndSend(context.Context, ...*gomail.Message) error { return nil } func TestTaskSendMail(t *testing.T) { assert.NotNil(t, NewDialer("", 0, "", ""), "Default dialer should be created") NewDialer = func(host string, port int, username, password string) Dialer { return &fakeDialer{} } assert.NoError(t, SendMail(context.Background(), EmailConn{ ServerHost: "smtp.example.com", ServerPort: 587, Username: "user", Password: "pwd", SenderAddr: "<EMAIL>", ToAddr: []string{"<EMAIL>"}, CcAddr: []string{"<EMAIL>"}, BccAddr: []string{"<EMAIL>"}, Attachments: []string{"mail.go"}, AttachmentData: []EmailAttachmentData{{ Name: "File1.txt", Base64Data: []byte("RmlsZSBDb250ZW50"), // "File Content" base64-encoded }}, }), "Sending email with required json input should succeed") } <file_sep>/internal/pgengine/notification_test.go package pgengine_test import ( "context" "testing" "time" "github.com/cybertec-postgresql/pg_timetable/internal/config" "github.com/cybertec-postgresql/pg_timetable/internal/pgengine" "github.com/stretchr/testify/assert" ) // notify sends NOTIFY each second until context is available func notifyAndCheck(ctx context.Context, conn pgengine.PgxIface, t *testing.T, channel string) { vals := []string{ `{"ConfigID": 1, "Command": "STOP", "Ts": 1}`, //{1, "STOP", 1, 0}, `{"ConfigID": 2, "Command": "START", "Ts": 1}`, //{2, "START", 1, 0}, `{"ConfigID": 3, "Command": "START", "Ts": 2, "Delay": 1}`, //{3, "START", 2, 1}, `{"ConfigID": 2, "Command": "START", "Ts": 1, "Delay": 0}`, //ignore duplicate message `{"ConfigID": 0, "Command": "START", "Ts": 3}`, //ignore incorrect ConfigID `{"ConfigID": 4, "Command": "DRIVE", "Ts": 3}`, //ignore incorrect Command `foo bazz`, //ignore corrupted json } for _, msg := range vals { _, err := conn.Exec(ctx, "SELECT pg_notify($1, $2)", channel, msg) assert.NoError(t, err) } var received int for { _ = pge.WaitForChainSignal(ctx) received++ //we will check only the number of received messages due to delay and race conditions select { case <-ctx.Done(): assert.Equal(t, 4, received, "Should receive 3 proper messages + 1 final and ignore all other") return default: //continue } } } func TestHandleNotifications(t *testing.T) { teardownTestCase := SetupTestCaseEx(t, func(c *config.CmdOptions) { c.Start.Debug = true }) defer teardownTestCase(t) ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) defer cancel() go pge.HandleNotifications(ctx) time.Sleep(5 * time.Second) conn, err := pge.ConfigDb.Acquire(ctx) // HandleNotifications() uses blocking manner, so we want another connection assert.NoError(t, err) defer conn.Release() _, err = conn.Exec(ctx, "UNLISTEN *") // do not interfere with the main handler assert.NoError(t, err) notifyAndCheck(ctx, pge.ConfigDb, t, "pgengine_unit_test") } <file_sep>/internal/pgengine/notification.go package pgengine import ( "context" "encoding/json" "fmt" "sync" "time" pgconn "github.com/jackc/pgx/v5/pgconn" ) // NotifyTTL specifies how long processed NOTIFY messages should be stored var NotifyTTL int64 = 60 // ChainSignal used to hold asynchronous notifications from PostgreSQL server type ChainSignal struct { ConfigID int // chain configuration ifentifier Command string // allowed: START, STOP Ts int64 // timestamp NOTIFY sent Delay int64 // delay in seconds before start } // Since there are usually multiple opened connections to the database, all of them will receive NOTIFY messages. // To process each NOTIFY message only once we store each message with TTL 1 minute because the max idle period for a // a connection is the main loop period of 1 minute. var mutex sync.Mutex var notifications = func() (m map[ChainSignal]struct{}) { m = make(map[ChainSignal]struct{}) go func() { for now := range time.Tick(time.Duration(NotifyTTL) * time.Second) { mutex.Lock() for k := range m { if now.Unix()-k.Ts > NotifyTTL { delete(m, k) } } mutex.Unlock() } }() return }() // NotificationHandler consumes notifications from the PostgreSQL server func (pge *PgEngine) NotificationHandler(c *pgconn.PgConn, n *pgconn.Notification) { l := pge.l.WithField("pid", c.PID()).WithField("notification", *n) l.Debug("Notification received") var signal ChainSignal var err error if err = json.Unmarshal([]byte(n.Payload), &signal); err == nil { mutex.Lock() if _, ok := notifications[signal]; ok { l.WithField("handled", notifications).Debug("Notification already handled") mutex.Unlock() return } notifications[signal] = struct{}{} mutex.Unlock() switch signal.Command { case "STOP", "START": if signal.ConfigID > 0 { l.WithField("signal", signal).Info("Adding asynchronous chain to working queue") pge.chainSignalChan <- signal return } err = fmt.Errorf("Unknown chain ID: %d", signal.ConfigID) default: err = fmt.Errorf("Unknown command: %s", signal.Command) } } l.WithError(err).Error("Syntax error in payload") } // WaitForChainSignal returns configuration id from the notifications func (pge *PgEngine) WaitForChainSignal(ctx context.Context) ChainSignal { select { case <-ctx.Done(): return ChainSignal{} case signal := <-pge.chainSignalChan: return signal } } // HandleNotifications consumes notifications in blocking mode func (pge *PgEngine) HandleNotifications(ctx context.Context) { conn, err := pge.ConfigDb.Acquire(ctx) if err != nil { pge.l.WithError(err).Error() } defer conn.Release() for { select { case <-ctx.Done(): return default: } c := conn.Conn() if n, err := c.WaitForNotification(ctx); err == nil { pge.NotificationHandler(c.PgConn(), n) } if err != nil { pge.l.WithError(err).Error() } } } <file_sep>/internal/pgengine/copy_test.go package pgengine_test import ( "context" "os" "testing" "github.com/cybertec-postgresql/pg_timetable/internal/pgengine" "github.com/stretchr/testify/assert" ) func TestCopyFromFile(t *testing.T) { teardownTestCase := SetupTestCase(t) defer teardownTestCase(t) ctx := context.Background() _, err := pge.CopyFromFile(ctx, "fake.csv", "COPY location FROM STDIN") assert.Error(t, err, "Should fail for missing file") _, err = pge.ConfigDb.Exec(ctx, "CREATE UNLOGGED TABLE csv_test(id integer, val text)") assert.NoError(t, err, "Should create temporary table") defer func() { _, err = pge.ConfigDb.Exec(ctx, "DROP TABLE csv_test") assert.NoError(t, err, "Should drop temporary table") }() assert.NoError(t, os.WriteFile("test.csv", []byte("1,foo\n2,bar"), 0666), "Should create source CSV file") cnt, err := pge.CopyFromFile(ctx, "test.csv", "COPY csv_test FROM STDIN (FORMAT csv)") assert.NoError(t, err, "Should copy from file") assert.True(t, cnt == 2, "Should copy exactly 2 rows") assert.NoError(t, os.RemoveAll("test.csv"), "Test output should be removed") } func TestCopyToFile(t *testing.T) { teardownTestCase := SetupTestCase(t) defer teardownTestCase(t) ctx := context.Background() _, err := pge.CopyToFile(ctx, "", "COPY location TO STDOUT") assert.Error(t, err, "Should fail for empty file name") cnt, err := pge.CopyToFile(ctx, "test.csv", "COPY (SELECT generate_series(1,5)) TO STDOUT (FORMAT csv)") assert.NoError(t, err, "Should copy to file") assert.True(t, cnt == 5, "Should copy exactly 5 rows") assert.NoError(t, os.RemoveAll("test.csv"), "Test output should be removed") } func TestCopyErrors(t *testing.T) { initmockdb(t) pge := pgengine.NewDB(mockPool, "pgengine_unit_test") defer mockPool.Close() _, err := pge.CopyFromFile(context.Background(), "foo", "boo") assert.Error(t, err, "Should fail in pgxmock Acquire()") _, err = pge.CopyToFile(context.Background(), "foo", "boo") assert.Error(t, err, "Should fail in pgxmock Acquire()") } <file_sep>/internal/pgengine/types.go package pgengine import ( "context" "strings" "time" pgconn "github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgtype" ) type executor interface { Exec(ctx context.Context, sql string, arguments ...interface{}) (commandTag pgconn.CommandTag, err error) } // Chain structure used to represent tasks chains type Chain struct { ChainID int `db:"chain_id"` ChainName string `db:"chain_name"` SelfDestruct bool `db:"self_destruct"` ExclusiveExecution bool `db:"exclusive_execution"` MaxInstances int `db:"max_instances"` Timeout int `db:"timeout"` OnErrorSQL pgtype.Text `db:"on_error"` } // IntervalChain structure used to represent repeated chains. type IntervalChain struct { Chain Interval int `db:"interval_seconds"` RepeatAfter bool `db:"repeat_after"` } func (ichain IntervalChain) IsListed(ichains []IntervalChain) bool { for _, ic := range ichains { if ichain.ChainID == ic.ChainID { return true } } return false } // ChainTask structure describes each chain task type ChainTask struct { ChainID int `db:"-"` TaskID int `db:"task_id"` Script string `db:"command"` Kind string `db:"kind"` RunAs pgtype.Text `db:"run_as"` IgnoreError bool `db:"ignore_error"` Autonomous bool `db:"autonomous"` ConnectString pgtype.Text `db:"database_connection"` Timeout int `db:"timeout"` // in milliseconds StartedAt time.Time `db:"-"` Duration int64 `db:"-"` // in microseconds Txid int64 `db:"-"` } func (task *ChainTask) IsRemote() bool { return task.ConnectString.Valid && strings.TrimSpace(task.ConnectString.String) != "" } <file_sep>/internal/scheduler/chain_test.go package scheduler import ( "context" "errors" "sync" "testing" "time" "github.com/cybertec-postgresql/pg_timetable/internal/config" "github.com/cybertec-postgresql/pg_timetable/internal/log" "github.com/cybertec-postgresql/pg_timetable/internal/pgengine" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgtype" "github.com/pashagolub/pgxmock/v2" "github.com/stretchr/testify/assert" ) func TestSchedulerExclusiveLocking(*testing.T) { sch := &Scheduler{exclusiveMutex: sync.RWMutex{}} sch.Lock(true) sch.Unlock(true) sch.Lock(false) sch.Unlock(false) } func TestAsyncChains(t *testing.T) { mock, err := pgxmock.NewPool(pgxmock.MonitorPingsOption(true)) assert.NoError(t, err) pge := pgengine.NewDB(mock, "scheduler_unit_test") sch := New(pge, log.Init(config.LoggingOpts{LogLevel: "error"})) n1 := &pgconn.Notification{Payload: `{"ConfigID": 1, "Command": "START"}`} n2 := &pgconn.Notification{Payload: `{"ConfigID": 2, "Command": "START"}`} ns := &pgconn.Notification{Payload: `{"ConfigID": 24, "Command": "STOP"}`} //add correct chain pge.NotificationHandler(&pgconn.PgConn{}, n1) pge.NotificationHandler(&pgconn.PgConn{}, ns) mock.ExpectQuery("SELECT.+chain_id"). WillReturnRows(pgxmock.NewRows([]string{"chain_id", "task_id", "chain_name", "self_destruct", "exclusive_execution", "max_instances"}). AddRow(24, 24, "foo", false, false, 16)) if pge.Verbose() { mock.ExpectExec("INSERT.+log").WillReturnResult(pgxmock.NewResult("EXECUTE", 1)) } ctx, cancel := context.WithTimeout(context.Background(), time.Second*2) defer cancel() sch.retrieveAsyncChainsAndRun(ctx) //add incorrect chain pge.NotificationHandler(&pgconn.PgConn{}, n2) mock.ExpectQuery("SELECT.+chain_id").WillReturnError(errors.New("error")) mock.ExpectExec("INSERT.+log").WillReturnResult(pgxmock.NewResult("EXECUTE", 1)) ctx, cancel = context.WithTimeout(context.Background(), time.Second*2) defer cancel() sch.retrieveAsyncChainsAndRun(ctx) } func TestChainWorker(t *testing.T) { mock, err := pgxmock.NewPool() assert.NoError(t, err) pge := pgengine.NewDB(mock, "-c", "scheduler_unit_test", "--password=<PASSWORD>") sch := New(pge, log.Init(config.LoggingOpts{LogLevel: "error"})) chains := make(chan Chain, 16) t.Run("Check chainWorker if context cancelled", func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) cancel() chains <- Chain{} sch.chainWorker(ctx, chains) }) t.Run("Check chainWorker if everything fine", func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() mock.ExpectQuery("SELECT count").WillReturnError(pgx.ErrNoRows) mock.ExpectBegin().WillReturnError(errors.New("expected")) mock.ExpectExec("INSERT INTO timetable\\.log").WillReturnResult(pgxmock.NewResult("INSERT", 1)) mock.ExpectExec("INSERT INTO timetable\\.log").WillReturnResult(pgxmock.NewResult("INSERT", 1)) mock.ExpectExec("DELETE").WillReturnResult(pgxmock.NewResult("DELETE", 1)) chains <- Chain{SelfDestruct: true} sch.chainWorker(ctx, chains) }) t.Run("Check chainWorker if cannot proceed with chain execution", func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), pgengine.WaitTime+2) defer cancel() mock.ExpectQuery("SELECT count").WillReturnError(errors.New("expected")) mock.ExpectExec("INSERT INTO timetable\\.log").WillReturnResult(pgxmock.NewResult("INSERT", 1)) mock.ExpectQuery("SELECT count").WillReturnError(errors.New("expected")) mock.ExpectExec("INSERT INTO timetable\\.log").WillReturnResult(pgxmock.NewResult("INSERT", 1)) chains <- Chain{} sch.chainWorker(ctx, chains) }) } func TestExecuteChain(t *testing.T) { mock, err := pgxmock.NewPool() assert.NoError(t, err) pge := pgengine.NewDB(mock, "-c", "scheduler_unit_test", "--password=<PASSWORD>") sch := New(pge, log.Init(config.LoggingOpts{LogLevel: "error"})) ctx, cancel := context.WithCancel(context.Background()) defer cancel() sch.executeChain(ctx, Chain{Timeout: 1}) } func TestExecuteChainElement(t *testing.T) { mock, err := pgxmock.NewPool() assert.NoError(t, err) pge := pgengine.NewDB(mock, "-c", "scheduler_unit_test", "--password=<PASSWORD>") sch := New(pge, log.Init(config.LoggingOpts{LogLevel: "error"})) ctx, cancel := context.WithCancel(context.Background()) defer cancel() mock.ExpectQuery("SELECT").WillReturnRows(pgxmock.NewRows([]string{"value"}).AddRow("foo")) sch.executeTask(ctx, mock, &pgengine.ChainTask{Timeout: 1}) } func TestExecuteOnErrorHandler(t *testing.T) { c := Chain{ChainID: 42, OnErrorSQL: pgtype.Text{String: "FOO", Valid: true}} mock, err := pgxmock.NewPool() assert.NoError(t, err) pge := pgengine.NewDB(mock, "-c", "scheduler_unit_test", "--password=<PASSWORD>") sch := New(pge, log.Init(config.LoggingOpts{LogLevel: "error"})) t.Run("check error handler if everything is fine", func(t *testing.T) { mock.ExpectExec("FOO").WillReturnResult(pgxmock.NewResult("FOO", 1)) sch.executeOnErrorHandler(context.Background(), c) assert.NoError(t, mock.ExpectationsWereMet()) }) t.Run("check error handler if context cancelled", func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) cancel() sch.executeOnErrorHandler(ctx, c) }) t.Run("check error handler if error", func(t *testing.T) { mock.ExpectExec("FOO").WillReturnError(errors.New("Syntax error near FOO")) sch.executeOnErrorHandler(context.Background(), c) }) assert.NoError(t, mock.ExpectationsWereMet()) } <file_sep>/samples/ErrorHandling.sql SELECT timetable.add_job( job_name => 'fail', job_schedule => '* * * * *', job_command => 'SELECT 42/0', job_kind => 'SQL'::timetable.command_kind, job_live => TRUE, job_ignore_errors => FALSE, job_on_error => $$SELECT pg_notify('monitoring', format('{"ConfigID": %s, "Message": "Something bad happened"}', current_setting('pg_timetable.current_chain_id')::bigint))$$ )<file_sep>/docs/samples.rst Samples ======== Basic ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This sample demonstrates how to create a basic one-step chain with parameters. It uses CTE to directly update the **timetable** schema tables. .. literalinclude:: ../samples/Basic.sql :linenos: :language: SQL Send email ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This sample demonstrates how to create an advanced email job. It will check if there are emails to send, will send them and log the status of the command execution. You don't need to setup anything, every parameter can be specified during the chain creation. .. literalinclude:: ../samples/Mail.sql :linenos: :language: SQL Download, Transform and Import ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This sample demonstrates how to create enhanced three-step chain with parameters. It uses DO statement to directly update the **timetable** schema tables. .. literalinclude:: ../samples/Download.sql :linenos: :language: SQL Run tasks in autonomous transaction ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This sample demonstrates how to run special tasks out of chain transaction context. This is useful for special routines and/or non-transactional operations, e.g. *CREATE DATABASE*, *REINDEX*, *VACUUM*, *CREATE TABLESPACE*, etc. .. literalinclude:: ../samples/Autonomous.sql :linenos: :language: SQL Shutdown the scheduler and terminate the session ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This sample demonstrates how to shutdown the scheduler using special built-in task. This can be used to control maintenance windows, to restart the scheduler for update purposes, or to stop session before the database should be dropped. .. literalinclude:: ../samples/Shutdown.sql :linenos: :language: SQL Access previous task result code and output from the next task ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This sample demonstrates how to check the result code and output of a previous task. If the last task failed, that is possible only if *ignore_error boolean = true* is set for that task. Otherwise, a scheduler will stop the chain. This sample shows how to calculate failed, successful, and the total number of tasks executed. Based on these values, we can calculate the success ratio. .. literalinclude:: ../samples/ManyTasks.sql :linenos: :language: SQL <file_sep>/docs/components.rst Components ================================================ The scheduling in **pg_timetable** encompasses three different abstraction levels to facilitate the reuse with other parameters or additional schedules. :Command: The base level, **command**, defines *what* to do. :Task: The second level, **task**, represents a chain element (step) to run one of the commands. With **tasks** we define order of commands, arguments passed (if any), and how errors are handled. :Chain: The third level represents a connected tasks forming a chain of tasks. **Chain** defines *if*, *when*, and *how often* a job should be executed. Command ------------------------------------------------ Currently, there are three different kinds of commands: ``SQL`` SQL snippet. Starting a cleanup, refreshing a materialized view or processing data. ``PROGRAM`` External Command. Anything that can be called as an external binary, including shells, e.g. ``bash``, ``pwsh``, etc. The external command will be called using golang's `exec.CommandContext <https://pkg.go.dev/os/exec#CommandContext>`_. ``BUILTIN`` Internal Command. A prebuilt functionality included in **pg_timetable**. These include: * *NoOp*, * *Sleep*, * *Log*, * *SendMail*, * *Download*, * *CopyFromFile*, * *CopyToFile*, * *Shutdown*. Task ------------------------------------------------ The next building block is a **task**, which simply represents a step in a list of chain commands. An example of tasks combined in a chain would be: #. Download files from a server #. Import files #. Run aggregations #. Build report #. Remove the files from disk .. note:: All tasks of the chain in **pg_timetable** are executed within one transaction. However, please, pay attention there is no opportunity to rollback ``PROGRAM`` and ``BUILTIN`` tasks. Table timetable.task ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ``chain_id bigint`` Link to the chain, if ``NULL`` task considered to be disabled ``task_order DOUBLE PRECISION`` Indicates the order of task within a chain. ``kind timetable.command_kind`` The type of the command. Can be *SQL* (default), *PROGRAM* or *BUILTIN*. ``command text`` Contains either a SQL command, a path to application or name of the *BUILTIN* command which will be executed. ``run_as text`` The role as which the task should be executed as. ``database_connection text`` The connection string for the external database that should be used. ``ignore_error boolean`` Specify if the next task should proceed after encountering an error (default: ``false``). ``autonomous boolean`` Specify if the task should be executed out of the chain transaction. Useful for ``VACUUM``, ``CREATE DATABASE``, ``CALL`` etc. ``timeout integer`` Abort any task within a chain that takes more than the specified number of milliseconds. .. warning:: If the **task** has been configured with ``ignore_error`` set to ``true`` (the default value is ``false``), the worker process will report a success on execution *even if the task within the chain fails*. As mentioned above, **commands** are simple skeletons (e.g. *send email*, *vacuum*, etc.). In most cases, they have to be brought to live by passing input parameters to the execution. Table timetable.parameter ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ``task_id bigint`` The ID of the task. ``order_id integer`` The order of the parameter. Several parameters are processed one by one according to the order. ``value jsonb`` A JSON value containing the parameters. Parameter value format ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Depending on the **command** kind argument can be represented by different *JSON* values. Kind Schema Example ``SQL`` ``array`` .. code-block:: SQL '[ "one", 2, 3.14, false ]'::jsonb ``PROGRAM`` ``array of strings`` .. code-block:: SQL '["-x", "Latin-ASCII", "-o", "orte_ansi.txt", "orte.txt"]'::jsonb ``BUILTIN: Sleep`` ``integer`` .. code-block:: SQL '5' :: jsonb ``BUILTIN: Log`` ``any`` .. code-block:: SQL '"WARNING"'::jsonb '{"Status": "WARNING"}'::jsonb ``BUILTIN: SendMail`` ``object`` .. code-block:: SQL '{ "username": "<EMAIL>", "password": "<PASSWORD>", "serverhost": "smtp.example.com", "serverport": 587, "senderaddr": "<EMAIL>", "ccaddr": ["<EMAIL>"], "bccaddr": ["<EMAIL>"], "toaddr": ["<EMAIL>"], "subject": "pg_timetable - No Reply", "attachment": ["/temp/attachments/Report.pdf","config.yaml"], "attachmentdata": [{"name": "File.txt", "base64data": "RmlsZSBDb250ZW50"}], "msgbody": "<h2>Hello User,</h2> <p>check some attachments!</p>", "contenttype": "text/html; charset=UTF-8" }'::jsonb ``BUILTIN: Download`` ``object`` .. code-block:: SQL '{ "workersnum": 2, "fileurls": ["http://example.com/foo.gz", "https://example.com/bar.csv"], "destpath": "." }'::jsonb ``BUILTIN: CopyFromFile`` ``object`` .. code-block:: SQL '{ "sql": "COPY location FROM STDIN", "filename": "download/orte_ansi.txt" }'::jsonb ``BUILTIN: CopyToFile`` ``object`` .. code-block:: SQL '{ "sql": "COPY location TO STDOUT", "filename": "download/location.txt" }'::jsonb ``BUILTIN: Shutdown`` *value ignored* ``BUILTIN: NoOp`` *value ignored* Chain ------------------------------------------------ Once tasks have been arranged, they have to be scheduled as a **chain**. For this, **pg_timetable** builds upon the enhanced **cron**-string, all the while adding multiple configuration options. Table timetable.chain ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ``chain_name text`` The unique name of the chain. ``run_at timetable.cron`` Standard *cron*-style value at Postgres server time zone or ``@after``, ``@every``, ``@reboot`` clause. ``max_instances integer`` The amount of instances that this chain may have running at the same time. ``timeout integer`` Abort any chain that takes more than the specified number of milliseconds. ``live boolean`` Control if the chain may be executed once it reaches its schedule. ``self_destruct boolean`` Self destruct the chain after successful execution. Failed chains will be executed according to the schedule one more time. ``exclusive_execution boolean`` Specifies whether the chain should be executed exclusively while all other chains are paused. ``client_name text`` Specifies which client should execute the chain. Set this to `NULL` to allow any client. ``timeout integer`` Abort a chain that takes more than the specified number of milliseconds. ``on_error`` Holds SQL to execute if an error occurs. If task produced an error is marked with ``ignore_error`` then nothing is done. .. note:: All chains in **pg_timetable** are scheduled at the PostgreSQL server time zone. You can change the `timezone <https://www.postgresql.org/docs/current/datatype-datetime.html#DATATYPE-TIMEZONES>`_ for the **current session** when adding new chains, e.g. .. code-block:: SQL SET TIME ZONE 'UTC'; -- Run VACUUM at 00:05 every day in August UTC SELECT timetable.add_job('execute-func', '5 0 * 8 *', 'VACUUM'); <file_sep>/samples/Shutdown.sql -- This one-task chain (aka job) will terminate pg_timetable session. -- This is useful for maintaining purposes or before database being destroyed. -- One should take care of restarting pg_timetable if needed. SELECT timetable.add_job ( job_name => 'Shutdown pg_timetable session on schedule', job_schedule => '* * 1 * *', job_command => 'Shutdown', job_kind => 'BUILTIN' );<file_sep>/samples/Sleep.sql SELECT timetable.add_job( job_name => 'sleep every minute', job_schedule => '@every 10 seconds', job_command => 'Sleep', job_parameters => '20' :: jsonb, job_kind => 'BUILTIN'::timetable.command_kind, job_client_name => NULL, job_max_instances => 1, job_live => TRUE ) as chain_id;<file_sep>/internal/log/log_test.go package log_test import ( "context" "os" "testing" "github.com/cybertec-postgresql/pg_timetable/internal/config" "github.com/cybertec-postgresql/pg_timetable/internal/log" "github.com/jackc/pgx/v5/tracelog" "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" ) func TestInit(t *testing.T) { assert.NotNil(t, log.Init(config.LoggingOpts{LogLevel: "debug"})) l := log.Init(config.LoggingOpts{LogLevel: "foobar"}) assert.Equal(t, l.(*logrus.Logger).Level, logrus.InfoLevel) pgxl := log.NewPgxLogger(l) assert.NotNil(t, pgxl) ctx := log.WithLogger(context.Background(), l) assert.True(t, log.GetLogger(ctx) == l) assert.True(t, log.GetLogger(context.Background()) == log.FallbackLogger) } func TestFileLogger(t *testing.T) { l := log.Init(config.LoggingOpts{LogLevel: "debug", LogFile: "test.log", LogFileFormat: "text"}) assert.Equal(t, l.(*logrus.Logger).Level, logrus.DebugLevel) l.Info("test") assert.FileExists(t, "test.log", "Log file should be created") _ = os.Remove("test.log") } func TestPgxLog(*testing.T) { pgxl := log.NewPgxLogger(log.Init(config.LoggingOpts{LogLevel: "trace"})) var level tracelog.LogLevel for level = tracelog.LogLevelNone; level <= tracelog.LogLevelTrace; level++ { pgxl.Log(context.Background(), level, "foo", map[string]interface{}{"func": "TestPgxLog"}) } } <file_sep>/docs/background.rst Project background ================== The pg_timetable project got started back in 2019 for internal scheduling needs at Cybertec. For more background on the project motivations and design goals see the original series of blogposts announcing the project and the following feature updates. Cybertec also provides commercial 9-to-5 and 24/7 support for pg_timetable. * `Project announcement <https://www.cybertec-postgresql.com/en/pg_timetable-advanced-postgresql-job-scheduling/>`_ * `v2 released <https://www.cybertec-postgresql.com/en/pg_timetable-advanced-postgresql-cron-like-scheduler-released/>`_ * `Start-up improvements <https://www.cybertec-postgresql.com/en/pg_timetable-start-up-improvements/>`_ * `v3 released <https://www.cybertec-postgresql.com/en/pg_timetable-v3-is-out/>`_ * `Exclusive jobs explained <https://www.cybertec-postgresql.com/en/postgresql-exclusive-cron-jobs-using-pg_timetable-scheduler/>`_ * `Asynchronous chain execution <https://www.cybertec-postgresql.com/en/pg_timetable-asynchronous-chain-execution/>`_ * `v4 released <https://www.cybertec-postgresql.com/en/pg_timetable_v4-is-out/>`_ * `PostgreSQL schedulers: comparison table <https://www.cybertec-postgresql.com/en/postgresql-schedulers-comparison-table/>`_ Project feedback ---------------- For feature requests or troubleshooting assistance please open an issue on project's `Github page <https://github.com/cybertec-postgresql/pg_timetable>`_.<file_sep>/internal/migrator/migrator.go package migrator import ( "context" "errors" "fmt" pgx "github.com/jackc/pgx/v5" pgconn "github.com/jackc/pgx/v5/pgconn" ) // PgxIface is interface for database connection or transaction type PgxIface interface { Begin(ctx context.Context) (pgx.Tx, error) Exec(context.Context, string, ...interface{}) (pgconn.CommandTag, error) QueryRow(context.Context, string, ...interface{}) pgx.Row Query(ctx context.Context, query string, args ...interface{}) (pgx.Rows, error) Ping(ctx context.Context) error } const defaultTableName = "migrations" // Migrator is the migrator implementation type Migrator struct { TableName string migrations []interface{} onNotice func(string) } // Option sets options such migrations or table name. type Option func(*Migrator) // TableName creates an option to allow overriding the default table name func TableName(tableName string) Option { return func(m *Migrator) { m.TableName = tableName } } // SetNotice overrides the default standard output function func SetNotice(noticeFunc func(string)) Option { return func(m *Migrator) { m.onNotice = noticeFunc } } // Migrations creates an option with provided migrations func Migrations(migrations ...interface{}) Option { return func(m *Migrator) { m.migrations = migrations } } // New creates a new migrator instance func New(opts ...Option) (*Migrator, error) { m := &Migrator{ TableName: defaultTableName, onNotice: func(msg string) { fmt.Println(msg) }, } for _, opt := range opts { opt(m) } if len(m.migrations) == 0 { return nil, errors.New("Migrations must be provided") } for _, m := range m.migrations { switch m.(type) { case *Migration: case *MigrationNoTx: default: return nil, errors.New("Invalid migration type") } } return m, nil } // Migrate applies all available migrations func (m *Migrator) Migrate(ctx context.Context, db PgxIface) error { // create migrations table if doesn't exist _, err := db.Exec(ctx, fmt.Sprintf(` CREATE TABLE IF NOT EXISTS %s ( id INT8 NOT NULL, version TEXT NOT NULL, PRIMARY KEY (id) ); `, m.TableName)) if err != nil { return err } pm, count, err := m.Pending(ctx, db) if err != nil { return err } // plan migrations for idx, migration := range pm { insertVersion := fmt.Sprintf("INSERT INTO %s (id, version) VALUES (%d, '%s')", m.TableName, idx+count, migration.(fmt.Stringer).String()) switch mm := migration.(type) { case *Migration: if err := migrate(ctx, db, insertVersion, mm, m.onNotice); err != nil { return fmt.Errorf("Error while running migrations: %w", err) } case *MigrationNoTx: if err := migrateNoTx(ctx, db, insertVersion, mm, m.onNotice); err != nil { return fmt.Errorf("Error while running migrations: %w", err) } } } return nil } // Pending returns all pending (not yet applied) migrations and count of migration applied func (m *Migrator) Pending(ctx context.Context, db PgxIface) ([]interface{}, int, error) { count, err := countApplied(ctx, db, m.TableName) if err != nil { return nil, 0, err } if count > len(m.migrations) { count = len(m.migrations) } return m.migrations[count:len(m.migrations)], count, nil } // NeedUpgrade returns True if database need to be updated with migrations func (m *Migrator) NeedUpgrade(ctx context.Context, db PgxIface) (bool, error) { exists, err := tableExists(ctx, db, m.TableName) if !exists { return true, err } mm, _, err := m.Pending(ctx, db) return len(mm) > 0, err } func countApplied(ctx context.Context, db PgxIface, tableName string) (int, error) { // count applied migrations var count int err := db.QueryRow(ctx, fmt.Sprintf("SELECT count(*) FROM %s", tableName)).Scan(&count) if err != nil { return 0, err } return count, nil } func tableExists(ctx context.Context, db PgxIface, tableName string) (bool, error) { var exists bool err := db.QueryRow(ctx, "SELECT to_regclass($1) IS NOT NULL", tableName).Scan(&exists) if err != nil { return false, err } return exists, nil } // Migration represents a single migration type Migration struct { Name string Func func(context.Context, pgx.Tx) error } // String returns a string representation of the migration func (m *Migration) String() string { return m.Name } // MigrationNoTx represents a single not transactional migration type MigrationNoTx struct { Name string Func func(context.Context, PgxIface) error } func (m *MigrationNoTx) String() string { return m.Name } func migrate(ctx context.Context, db PgxIface, insertVersion string, migration *Migration, notice func(string)) error { tx, err := db.Begin(ctx) if err != nil { return err } defer func() { if err != nil { if errRb := tx.Rollback(ctx); errRb != nil { err = fmt.Errorf("Error rolling back: %s\n%s", errRb, err) } return } err = tx.Commit(ctx) }() notice(fmt.Sprintf("Applying migration named '%s'...", migration.Name)) if err = migration.Func(ctx, tx); err != nil { return fmt.Errorf("Error executing golang migration: %w", err) } if _, err = tx.Exec(ctx, insertVersion); err != nil { return fmt.Errorf("Error updating migration versions: %w", err) } notice(fmt.Sprintf("Applied migration named '%s'", migration.Name)) return err } func migrateNoTx(ctx context.Context, db PgxIface, insertVersion string, migration *MigrationNoTx, notice func(string)) error { notice(fmt.Sprintf("Applying no tx migration named '%s'...", migration.Name)) if err := migration.Func(ctx, db); err != nil { return fmt.Errorf("Error executing golang migration: %w", err) } if _, err := db.Exec(ctx, insertVersion); err != nil { return fmt.Errorf("Error updating migration versions: %w", err) } notice(fmt.Sprintf("Applied no tx migration named '%s'...", migration.Name)) return nil } <file_sep>/internal/scheduler/tasks.go package scheduler import ( "context" "encoding/json" "errors" "fmt" "strconv" "time" "github.com/cybertec-postgresql/pg_timetable/internal/log" "github.com/cybertec-postgresql/pg_timetable/internal/tasks" ) // BuiltinTasks maps builtin task names with event handlers var BuiltinTasks = map[string](func(context.Context, *Scheduler, string) (string, error)){ "NoOp": taskNoOp, "Sleep": taskSleep, "Log": taskLog, "SendMail": taskSendMail, "Download": taskDownload, "CopyFromFile": taskCopyFromFile, "CopyToFile": taskCopyToFile, "Shutdown": taskShutdown} func (sch *Scheduler) executeBuiltinTask(ctx context.Context, name string, paramValues []string) (stdout string, err error) { var s string f := BuiltinTasks[name] if f == nil { return "", errors.New("No built-in task found: " + name) } l := log.GetLogger(ctx) l.WithField("name", name).Debugf("Executing builtin task with parameters %+q", paramValues) if len(paramValues) == 0 { return f(ctx, sch, "") } for _, val := range paramValues { if s, err = f(ctx, sch, val); err != nil { return } stdout = stdout + fmt.Sprintln(s) } return } func taskNoOp(_ context.Context, _ *Scheduler, val string) (stdout string, err error) { return "NoOp task called with value: " + val, nil } func taskSleep(ctx context.Context, _ *Scheduler, val string) (stdout string, err error) { var d int if d, err = strconv.Atoi(val); err != nil { return "", err } dur := time.Duration(d) * time.Second select { case <-ctx.Done(): return "", ctx.Err() case <-time.After(dur): return "Sleep task called for " + dur.String(), nil } } func taskLog(ctx context.Context, _ *Scheduler, val string) (stdout string, err error) { log.GetLogger(ctx).Print(val) return "Logged: " + val, nil } func taskSendMail(ctx context.Context, _ *Scheduler, paramValues string) (stdout string, err error) { conn := tasks.EmailConn{ServerPort: 587, ContentType: "text/plain"} if err := json.Unmarshal([]byte(paramValues), &conn); err != nil { return "", err } return "", tasks.SendMail(ctx, conn) } func taskCopyFromFile(ctx context.Context, sch *Scheduler, val string) (stdout string, err error) { type copyFrom struct { SQL string `json:"sql"` Filename string `json:"filename"` } var ct copyFrom if err := json.Unmarshal([]byte(val), &ct); err != nil { return "", err } count, err := sch.pgengine.CopyFromFile(ctx, ct.Filename, ct.SQL) if err == nil { stdout = fmt.Sprintf("%d rows copied from %s", count, ct.Filename) } return stdout, err } func taskCopyToFile(ctx context.Context, sch *Scheduler, val string) (stdout string, err error) { type copyTo struct { SQL string `json:"sql"` Filename string `json:"filename"` } var ct copyTo if err := json.Unmarshal([]byte(val), &ct); err != nil { return "", err } count, err := sch.pgengine.CopyToFile(ctx, ct.Filename, ct.SQL) if err == nil { stdout = fmt.Sprintf("%d rows copied to %s", count, ct.Filename) } return stdout, err } func taskDownload(ctx context.Context, _ *Scheduler, paramValues string) (stdout string, err error) { type downloadOpts struct { WorkersNum int `json:"workersnum"` FileUrls []string `json:"fileurls"` DestPath string `json:"destpath"` } var opts downloadOpts if err := json.Unmarshal([]byte(paramValues), &opts); err != nil { return "", err } if len(opts.FileUrls) == 0 { return "", errors.New("Files to download are not specified") } return tasks.DownloadUrls(ctx, opts.FileUrls, opts.DestPath, opts.WorkersNum) } func taskShutdown(_ context.Context, sch *Scheduler, val string) (stdout string, err error) { sch.l.WithField("message", val).Info("Shutdown command received") sch.Shutdown() return "Shutdown task called", nil } <file_sep>/docs/index.rst Welcome to pg_timetable's documentation! ======================================== .. toctree:: :numbered: :maxdepth: 2 :caption: Contents: README background installation components basic_jobs samples migration api database_schema Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search`<file_sep>/internal/scheduler/shell_test.go package scheduler_test import ( "context" "encoding/json" "fmt" "os/exec" "strings" "testing" "github.com/cybertec-postgresql/pg_timetable/internal/config" "github.com/cybertec-postgresql/pg_timetable/internal/log" "github.com/cybertec-postgresql/pg_timetable/internal/pgengine" "github.com/cybertec-postgresql/pg_timetable/internal/scheduler" "github.com/pashagolub/pgxmock/v2" "github.com/stretchr/testify/assert" ) type testCommander struct{} // overwrite CombinedOutput function of os/exec so only parameter syntax and return codes are checked... func (c testCommander) CombinedOutput(_ context.Context, command string, args ...string) ([]byte, error) { if strings.HasPrefix(command, "ping") { return []byte(fmt.Sprint(command, args)), nil } return []byte(fmt.Sprintf("Command %s not found", command)), &exec.Error{Name: command, Err: exec.ErrNotFound} } func TestShellCommand(t *testing.T) { scheduler.Cmd = testCommander{} var err error var out string var retCode int mock, err := pgxmock.NewPool() //pgxmock.MonitorPingsOption(true) assert.NoError(t, err) pge := pgengine.NewDB(mock, "scheduler_unit_test") scheduler := scheduler.New(pge, log.Init(config.LoggingOpts{LogLevel: "error"})) ctx := context.Background() _, _, err = scheduler.ExecuteProgramCommand(ctx, "", []string{""}) assert.EqualError(t, err, "Program command cannot be empty", "Empty command should out, fail") _, out, err = scheduler.ExecuteProgramCommand(ctx, "ping0", nil) assert.NoError(t, err, "Command with nil param is out, OK") assert.True(t, strings.HasPrefix(string(out), "ping0"), "Output should containt only command ") _, _, err = scheduler.ExecuteProgramCommand(ctx, "ping1", []string{}) assert.NoError(t, err, "Command with empty array param is OK") _, _, err = scheduler.ExecuteProgramCommand(ctx, "ping2", []string{""}) assert.NoError(t, err, "Command with empty string param is OK") _, _, err = scheduler.ExecuteProgramCommand(ctx, "ping3", []string{"[]"}) assert.NoError(t, err, "Command with empty json array param is OK") _, _, err = scheduler.ExecuteProgramCommand(ctx, "ping3", []string{"[null]"}) assert.NoError(t, err, "Command with nil array param is OK") _, _, err = scheduler.ExecuteProgramCommand(ctx, "ping4", []string{`["localhost"]`}) assert.NoError(t, err, "Command with one param is OK") _, _, err = scheduler.ExecuteProgramCommand(ctx, "ping5", []string{`["localhost", "-4"]`}) assert.NoError(t, err, "Command with many params is OK") _, _, err = scheduler.ExecuteProgramCommand(ctx, "pong", nil) assert.IsType(t, (*exec.Error)(nil), err, "Uknown command should produce error") retCode, _, err = scheduler.ExecuteProgramCommand(ctx, "ping5", []string{`{"param1": "localhost"}`}) assert.IsType(t, (*json.UnmarshalTypeError)(nil), err, "Command should fail with mailformed json parameter") assert.NotEqual(t, 0, retCode, "return code should indicate failure.") } <file_sep>/internal/log/log_file_test.go package log import ( "testing" "github.com/cybertec-postgresql/pg_timetable/internal/config" "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" "gopkg.in/natefinch/lumberjack.v2" ) func TestGetLogFileWriter(t *testing.T) { assert.IsType(t, getLogFileWriter(config.LoggingOpts{LogFileRotate: true}), &lumberjack.Logger{}) assert.IsType(t, getLogFileWriter(config.LoggingOpts{LogFileRotate: false}), "string") } func TestGetLogFileFormatter(t *testing.T) { assert.IsType(t, getLogFileFormatter(config.LoggingOpts{LogFileFormat: "json"}), &logrus.JSONFormatter{}) assert.IsType(t, getLogFileFormatter(config.LoggingOpts{LogFileFormat: "blah"}), &logrus.JSONFormatter{}) assert.IsType(t, getLogFileFormatter(config.LoggingOpts{LogFileFormat: "text"}), &logrus.TextFormatter{}) } <file_sep>/internal/config/cmdparser.go package config import ( "io" "os" flags "github.com/jessevdk/go-flags" ) // ConnectionOpts specifies the database connection options type ConnectionOpts struct { Host string `short:"h" long:"host" description:"PostgreSQL host" default:"localhost" env:"PGTT_PGHOST"` Port int `short:"p" long:"port" description:"PostgreSQL port" default:"5432" env:"PGTT_PGPORT"` DBName string `short:"d" long:"dbname" description:"PostgreSQL database name" default:"timetable" env:"PGTT_PGDATABASE"` User string `short:"u" long:"user" description:"PostgreSQL user" default:"scheduler" env:"PGTT_PGUSER"` Password string `long:"password" description:"PostgreSQL user password" env:"PGTT_PGPASSWORD"` SSLMode string `long:"sslmode" default:"disable" description:"Connection SSL mode" env:"PGTT_PGSSLMODE" choice:"disable" choice:"require"` PgURL string `long:"pgurl" description:"PostgreSQL connection URL" env:"PGTT_URL"` Timeout int `long:"timeout" description:"PostgreSQL connection timeout" env:"PGTT_TIMEOUT" default:"90"` } // LoggingOpts specifies the logging configuration type LoggingOpts struct { LogLevel string `long:"log-level" mapstructure:"log-level" description:"Verbosity level for stdout and log file" choice:"debug" choice:"info" choice:"error" default:"info"` LogDBLevel string `long:"log-database-level" mapstructure:"log-database-level" description:"Verbosity level for database storing" choice:"debug" choice:"info" choice:"error" choice:"none" default:"info"` LogFile string `long:"log-file" mapstructure:"log-file" description:"File name to store logs"` LogFileFormat string `long:"log-file-format" mapstructure:"log-file-format" description:"Format of file logs" choice:"json" choice:"text" default:"json"` LogFileRotate bool `long:"log-file-rotate" mapstructure:"log-file-rotate" description:"Rotate log files"` LogFileSize int `long:"log-file-size" mapstructure:"log-file-size" description:"Maximum size in MB of the log file before it gets rotated" default:"100"` LogFileAge int `long:"log-file-age" mapstructure:"log-file-age" description:"Number of days to retain old log files, 0 means forever" default:"0"` LogFileNumber int `long:"log-file-number" mapstructure:"log-file-number" description:"Maximum number of old log files to retain, 0 to retain all" default:"0"` } // StartOpts specifies the application startup options type StartOpts struct { File string `short:"f" long:"file" description:"SQL script file to execute during startup"` Init bool `long:"init" description:"Initialize database schema to the latest version and exit. Can be used with --upgrade"` Upgrade bool `long:"upgrade" description:"Upgrade database to the latest version"` Debug bool `long:"debug" description:"Run in debug mode. Only asynchronous chains will be executed"` } // ResourceOpts specifies the maximum resources available to application type ResourceOpts struct { CronWorkers int `long:"cron-workers" mapstructure:"cron-workers" description:"Number of parallel workers for scheduled chains" default:"16"` IntervalWorkers int `long:"interval-workers" mapstructure:"interval-workers" description:"Number of parallel workers for interval chains" default:"16"` ChainTimeout int `long:"chain-timeout" mapstructure:"chain-timeout" description:"Abort any chain that takes more than the specified number of milliseconds"` TaskTimeout int `long:"task-timeout" mapstructure:"task-timeout" description:"Abort any task within a chain that takes more than the specified number of milliseconds"` } // RestAPIOpts fot internal web server impleenting REST API type RestAPIOpts struct { Port int `long:"rest-port" mapstructure:"rest-port" description:"REST API port" env:"PGTT_RESTPORT" default:"0"` } // CmdOptions holds command line options passed type CmdOptions struct { ClientName string `short:"c" long:"clientname" description:"Unique name for application instance" env:"PGTT_CLIENTNAME"` Config string `long:"config" description:"YAML configuration file"` Connection ConnectionOpts `group:"Connection" mapstructure:"Connection"` Logging LoggingOpts `group:"Logging" mapstructure:"Logging"` Start StartOpts `group:"Start" mapstructure:"Start"` Resource ResourceOpts `group:"Resource" mapstructure:"Resource"` RESTApi RestAPIOpts `group:"REST" mapstructure:"REST"` NoProgramTasks bool `long:"no-program-tasks" mapstructure:"no-program-tasks" description:"Disable executing of PROGRAM tasks" env:"PGTT_NOPROGRAMTASKS"` NoHelpMessage bool `long:"no-help" mapstructure:"no-help" hidden:"system use"` Version bool `short:"v" long:"version" mapstructure:"version" description:"Output detailed version information" env:"PGTT_VERSION"` } // Verbose returns true if the debug log is enabled func (c CmdOptions) Verbose() bool { return c.Logging.LogLevel == "debug" } // VersionOnly returns true if the `--version` is the only argument func (c CmdOptions) VersionOnly() bool { return len(os.Args) == 2 && c.Version } // NewCmdOptions returns a new instance of CmdOptions with default values func NewCmdOptions(args ...string) *CmdOptions { cmdOpts := new(CmdOptions) _, _ = flags.NewParser(cmdOpts, flags.PrintErrors).ParseArgs(args) return cmdOpts } var nonOptionArgs []string // Parse will parse command line arguments and initialize pgengine func Parse(writer io.Writer) (*flags.Parser, error) { cmdOpts := new(CmdOptions) parser := flags.NewParser(cmdOpts, flags.PrintErrors) var err error if nonOptionArgs, err = parser.Parse(); err != nil { if !flags.WroteHelp(err) && !cmdOpts.NoHelpMessage { parser.WriteHelp(writer) return nil, err } } if cmdOpts.Start.File != "" { if _, err := os.Stat(cmdOpts.Start.File); os.IsNotExist(err) { return nil, err } } //non-option arguments if len(nonOptionArgs) > 0 && cmdOpts.Connection.PgURL == "" { cmdOpts.Connection.PgURL = nonOptionArgs[0] } return parser, nil } <file_sep>/internal/scheduler/tasks_test.go package scheduler import ( "context" "testing" "github.com/cybertec-postgresql/pg_timetable/internal/config" "github.com/cybertec-postgresql/pg_timetable/internal/log" "github.com/cybertec-postgresql/pg_timetable/internal/pgengine" "github.com/pashagolub/pgxmock/v2" "github.com/stretchr/testify/assert" ) func TestExecuteTask(t *testing.T) { mock, err := pgxmock.NewPool() //pgxmock.MonitorPingsOption(true) assert.NoError(t, err) pge := pgengine.NewDB(mock, "scheduler_unit_test") mocksch := New(pge, log.Init(config.LoggingOpts{LogLevel: "error"})) et := func(task string, params []string) (err error) { _, err = mocksch.executeBuiltinTask(context.TODO(), task, params) return } assert.Error(t, et("foo", []string{})) assert.Error(t, et("Sleep", []string{"foo"})) assert.NoError(t, et("Sleep", []string{"1"})) assert.NoError(t, et("NoOp", []string{})) assert.NoError(t, et("NoOp", []string{"foo", "bar"})) assert.NoError(t, et("Log", []string{"foo"})) assert.Error(t, et("CopyFromFile", []string{"foo"}), "Invalid json") assert.Error(t, et("CopyFromFile", []string{`{"sql": "COPY", "filename": "foo"}`}), "Acquire() should fail") assert.Error(t, et("CopyToFile", []string{"foo"}), "Invalid json") assert.Error(t, et("CopyToFile", []string{`{"sql": "COPY", "filename": "foo"}`}), "Acquire() should fail") assert.Error(t, et("SendMail", []string{"foo"}), "Invalid json") assert.Error(t, et("SendMail", []string{`{"ServerHost":"smtp.example.com","ServerPort":587,"Username":"user"}`})) assert.Error(t, et("Download", []string{"foo"}), "Invalid json") assert.EqualError(t, et("Download", []string{`{"workersnum": 0, "fileurls": [] }`}), "Files to download are not specified", "Download with empty files should fail") assert.Error(t, et("Download", []string{`{"workersnum": 0, "fileurls": ["http://foo.bar"], "destpath": "" }`}), "Downlod incorrect url should fail") assert.NoError(t, et("Shutdown", []string{})) } <file_sep>/internal/scheduler/chain.go package scheduler import ( "context" "fmt" "strings" "time" "github.com/cybertec-postgresql/pg_timetable/internal/log" "github.com/cybertec-postgresql/pg_timetable/internal/pgengine" pgx "github.com/jackc/pgx/v5" ) type ( Chain = pgengine.Chain ChainSignal = pgengine.ChainSignal ) // SendChain sends chain to the channel for workers func (sch *Scheduler) SendChain(c Chain) { select { case sch.chainsChan <- c: sch.l.WithField("chain", c.ChainID).Debug("Sent chain to the execution channel") default: sch.l.WithField("chain", c.ChainID).Error("Failed to send chain to the execution channel") } } // Lock locks the chain in exclusive or non-exclusive mode func (sch *Scheduler) Lock(exclusiveExecution bool) { if exclusiveExecution { sch.exclusiveMutex.Lock() } else { sch.exclusiveMutex.RLock() } } // Unlock releases the lock after the chain execution func (sch *Scheduler) Unlock(exclusiveExecution bool) { if exclusiveExecution { sch.exclusiveMutex.Unlock() } else { sch.exclusiveMutex.RUnlock() } } func (sch *Scheduler) retrieveAsyncChainsAndRun(ctx context.Context) { for { chainSignal := sch.pgengine.WaitForChainSignal(ctx) if chainSignal.ConfigID == 0 { return } err := sch.processAsyncChain(ctx, chainSignal) if err != nil { sch.l.WithError(err).Error("Could not process async chain command") } } } func (sch *Scheduler) processAsyncChain(ctx context.Context, chainSignal ChainSignal) error { switch chainSignal.Command { case "START": var c Chain if err := sch.pgengine.SelectChain(ctx, &c, chainSignal.ConfigID); err != nil { return fmt.Errorf("Cannot start chain with ID: %d; %w", chainSignal.ConfigID, err) } go func() { select { case <-ctx.Done(): return case <-time.After(time.Duration(chainSignal.Delay) * time.Second): sch.SendChain(c) } }() case "STOP": if cancel, ok := sch.activeChains[chainSignal.ConfigID]; ok { cancel() return nil } return fmt.Errorf("Cannot stop chain with ID: %d. No running chain found", chainSignal.ConfigID) } return nil } func (sch *Scheduler) retrieveChainsAndRun(ctx context.Context, reboot bool) { var err error var headChains []Chain msg := "Retrieve scheduled chains to run" if reboot { msg = msg + " @reboot" } if reboot { err = sch.pgengine.SelectRebootChains(ctx, &headChains) } else { err = sch.pgengine.SelectChains(ctx, &headChains) } if err != nil { sch.l.WithError(err).Error("Could not query pending tasks") return } headChainsCount := len(headChains) sch.l.WithField("count", headChainsCount).Info(msg) // now we can loop through the chains for _, c := range headChains { // if the number of chains pulled for execution is high, try to spread execution to avoid spikes if headChainsCount > sch.Config().Resource.CronWorkers*refetchTimeout { time.Sleep(time.Duration(refetchTimeout*1000/headChainsCount) * time.Millisecond) } sch.SendChain(c) } } func (sch *Scheduler) addActiveChain(id int, cancel context.CancelFunc) { sch.activeChainMutex.Lock() sch.activeChains[id] = cancel sch.activeChainMutex.Unlock() } func (sch *Scheduler) deleteActiveChain(id int) { sch.activeChainMutex.Lock() delete(sch.activeChains, id) sch.activeChainMutex.Unlock() } func (sch *Scheduler) terminateChains() { for id, cancel := range sch.activeChains { sch.l.WithField("chain", id).Debug("Terminating chain...") cancel() } for { time.Sleep(1 * time.Second) // give some time to terminate chains gracefully if len(sch.activeChains) == 0 { return } sch.l.Debugf("Still active chains running: %d", len(sch.activeChains)) } } func (sch *Scheduler) chainWorker(ctx context.Context, chains <-chan Chain) { for { select { case <-ctx.Done(): //check context with high priority return default: select { case chain := <-chains: chainL := sch.l.WithField("chain", chain.ChainID) chainContext := log.WithLogger(ctx, chainL) if !sch.pgengine.InsertChainRunStatus(ctx, chain.ChainID, chain.MaxInstances) { chainL.Info("Cannot proceed. Sleeping") continue } chainL.Info("Starting chain") sch.Lock(chain.ExclusiveExecution) chainContext, cancel := context.WithCancel(chainContext) sch.addActiveChain(chain.ChainID, cancel) sch.executeChain(chainContext, chain) sch.deleteActiveChain(chain.ChainID) cancel() sch.Unlock(chain.ExclusiveExecution) case <-ctx.Done(): return } } } } func getTimeoutContext(ctx context.Context, t1 int, t2 int) (context.Context, context.CancelFunc) { timeout := max(t1, t2) if timeout > 0 { return context.WithTimeout(ctx, time.Millisecond*time.Duration(timeout)) } return ctx, nil } func (sch *Scheduler) executeOnErrorHandler(ctx context.Context, chain Chain) { if ctx.Err() != nil || !chain.OnErrorSQL.Valid { return } l := sch.l.WithField("chain", chain.ChainID) l.Info("Starting error handling") if _, err := sch.pgengine.ConfigDb.Exec(ctx, chain.OnErrorSQL.String); err != nil { l.Info("Error handler failed") return } l.Info("Error handler executed successfully") } /* execute a chain of tasks */ func (sch *Scheduler) executeChain(ctx context.Context, chain Chain) { var ChainTasks []pgengine.ChainTask var bctx context.Context var cancel context.CancelFunc var txid int64 chainCtx, cancel := getTimeoutContext(ctx, sch.Config().Resource.ChainTimeout, chain.Timeout) if cancel != nil { defer cancel() } chainL := sch.l.WithField("chain", chain.ChainID) tx, txid, err := sch.pgengine.StartTransaction(chainCtx) if err != nil { chainL.WithError(err).Error("Cannot start transaction") return } chainL = chainL.WithField("txid", txid) err = sch.pgengine.GetChainElements(chainCtx, &ChainTasks, chain.ChainID) if err != nil { chainL.WithError(err).Error("Failed to retrieve chain elements") sch.pgengine.RollbackTransaction(chainCtx, tx) return } /* now we can loop through every element of the task chain */ for _, task := range ChainTasks { task.ChainID = chain.ChainID task.Txid = txid l := chainL.WithField("task", task.TaskID) l.Info("Starting task") taskCtx := log.WithLogger(chainCtx, l) retCode := sch.executeTask(taskCtx, tx, &task) // we use background context here because current one (chainCtx) might be cancelled bctx = log.WithLogger(ctx, l) if retCode != 0 { if !task.IgnoreError { chainL.Error("Chain failed") sch.pgengine.RemoveChainRunStatus(bctx, chain.ChainID) sch.pgengine.RollbackTransaction(bctx, tx) sch.executeOnErrorHandler(bctx, chain) return } l.Info("Ignoring task failure") } } bctx = log.WithLogger(chainCtx, chainL) sch.pgengine.CommitTransaction(bctx, tx) chainL.Info("Chain executed successfully") sch.pgengine.RemoveChainRunStatus(bctx, chain.ChainID) if chain.SelfDestruct { sch.pgengine.DeleteChain(bctx, chain.ChainID) } } /* execute a task */ func (sch *Scheduler) executeTask(ctx context.Context, tx pgx.Tx, task *pgengine.ChainTask) int { var ( paramValues []string err error out string retCode int cancel context.CancelFunc ) l := log.GetLogger(ctx) err = sch.pgengine.GetChainParamValues(ctx, &paramValues, task) if err != nil { l.WithError(err).Error("cannot fetch parameters values for chain: ", err) return -1 } ctx, cancel = getTimeoutContext(ctx, sch.Config().Resource.TaskTimeout, task.Timeout) if cancel != nil { defer cancel() } task.StartedAt = time.Now() switch task.Kind { case "SQL": out, err = sch.pgengine.ExecuteSQLTask(ctx, tx, task, paramValues) case "PROGRAM": if sch.pgengine.NoProgramTasks { l.Info("Program task execution skipped") return -2 } retCode, out, err = sch.ExecuteProgramCommand(ctx, task.Script, paramValues) case "BUILTIN": out, err = sch.executeBuiltinTask(ctx, task.Script, paramValues) } task.Duration = time.Since(task.StartedAt).Microseconds() if err != nil { if retCode == 0 { retCode = -1 } out = strings.Join([]string{out, err.Error()}, "\n") l.WithError(err).Error("Task execution failed") } else { l.Info("Task executed successfully") } sch.pgengine.LogTaskExecution(context.Background(), task, retCode, out) return retCode } <file_sep>/internal/tasks/files_test.go package tasks import ( "bufio" "context" "fmt" "net/http" "net/http/httptest" "os" "testing" "github.com/stretchr/testify/assert" ) var ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if filenamep := r.URL.Query().Get("filename"); filenamep != "test.txt" { w.WriteHeader(http.StatusNotFound) return } w.Header().Set("Content-Disposition", fmt.Sprintf("attachment;filename=\"%s\"", "test.txt")) bw := bufio.NewWriterSize(w, 4096) for i := 0; i < 4096; i++ { _, _ = bw.Write([]byte{byte(i)}) } _ = bw.Flush() w.WriteHeader(http.StatusOK) })) func TestDownloadFile(t *testing.T) { ctx := context.Background() _, err := DownloadUrls(ctx, []string{ts.URL + `?filename=nonexistent.txt`}, "", 0) assert.Error(t, err, "Downlod with non-existent directory or insufficient rights should fail") _, err = DownloadUrls(ctx, []string{ts.URL + `?filename=test.txt`}, ".", 0) assert.NoError(t, err, "Downlod with correct json input should succeed") assert.NoError(t, os.RemoveAll("test.txt"), "Test output should be removed") _, err = DownloadUrls(ctx, []string{"\t"}, "", 1) assert.Error(t, err, "Download with incorrect URL should fail") } <file_sep>/extras/pg_cron_to_pg_timetable_simple.sql SELECT timetable.add_job( job_name => COALESCE(jobname, 'job: ' || command), job_schedule => schedule, job_command => command, job_kind => 'SQL', job_live => active ) FROM cron.job;<file_sep>/internal/tasks/mail.go package tasks import ( "bytes" "context" gomail "github.com/ory/mail/v3" ) // Attachment file type // Has pair: name and content (base64-encoded) of attachment file type EmailAttachmentData struct { Name string `json:"name"` Base64Data []byte `json:"base64data"` } // EmailConn structure represents a connection to a mail server and mail fields type EmailConn struct { Username string `json:"username"` Password string `json:"<PASSWORD>"` ServerHost string `json:"serverhost"` ServerPort int `json:"serverport"` SenderAddr string `json:"senderaddr"` CcAddr []string `json:"ccaddr"` BccAddr []string `json:"bccaddr"` ToAddr []string `json:"toaddr"` Subject string `json:"subject"` MsgBody string `json:"msgbody"` Attachments []string `json:"attachment"` AttachmentData []EmailAttachmentData `json:"attachmentdata"` ContentType string `json:"contenttype"` } // Dialer implements DialAndSend function for mailer type Dialer interface { DialAndSend(ctx context.Context, m ...*gomail.Message) error } // NewDialer returns a new gomail dialer instance var NewDialer = func(host string, port int, username, password string) Dialer { return gomail.NewDialer(host, port, username, password) } // SendMail sends mail message specified by conn within context ctx func SendMail(ctx context.Context, conn EmailConn) error { mail := gomail.NewMessage() mail.SetHeader("From", conn.SenderAddr) //Multiple Recipients addresses torecipients := make([]string, len(conn.ToAddr)) for i, toAddr := range conn.ToAddr { torecipients[i] = mail.FormatAddress(toAddr, " ") } mail.SetHeader("To", torecipients...) // Multiple CC Addresses ccrecipients := make([]string, len(conn.CcAddr)) for i, ccaddr := range conn.CcAddr { ccrecipients[i] = mail.FormatAddress(ccaddr, " ") } mail.SetHeader("Cc", ccrecipients...) // Multiple bCC Addresses bccrecipients := make([]string, len(conn.BccAddr)) for i, bccaddr := range conn.BccAddr { bccrecipients[i] = mail.FormatAddress(bccaddr, " ") } mail.SetHeader("Bcc", bccrecipients...) mail.SetHeader("Subject", conn.Subject) mail.SetBody(conn.ContentType, conn.MsgBody) //attach multiple documents for _, attachment := range conn.Attachments { mail.Attach(attachment) } // Attach file with contents for _, attachmentData := range conn.AttachmentData { mail.AttachReader(attachmentData.Name, bytes.NewReader([]byte(attachmentData.Base64Data))) } // Send Mail dialer := NewDialer(conn.ServerHost, conn.ServerPort, conn.Username, conn.Password) return dialer.DialAndSend(ctx, mail) } <file_sep>/internal/pgengine/bootstrap.go package pgengine import ( "context" "errors" "fmt" "math/rand" "os" "strings" "time" "github.com/cybertec-postgresql/pg_timetable/internal/config" "github.com/cybertec-postgresql/pg_timetable/internal/log" pgx "github.com/jackc/pgx/v5" pgconn "github.com/jackc/pgx/v5/pgconn" pgtype "github.com/jackc/pgx/v5/pgtype" pgxpool "github.com/jackc/pgx/v5/pgxpool" tracelog "github.com/jackc/pgx/v5/tracelog" retry "github.com/sethvargo/go-retry" ) // WaitTime specifies amount of time in seconds to wait before reconnecting to DB const WaitTime = 5 * time.Second // maximum wait time before reconnect attempts const maxWaitTime = WaitTime * 16 // create a new exponential backoff to be used in retry attempts var backoff = retry.WithCappedDuration(maxWaitTime, retry.NewExponential(WaitTime)) // PgxIface is common interface for every pgx class type PgxIface interface { Begin(ctx context.Context) (pgx.Tx, error) Exec(context.Context, string, ...interface{}) (pgconn.CommandTag, error) QueryRow(context.Context, string, ...interface{}) pgx.Row Query(ctx context.Context, query string, args ...interface{}) (pgx.Rows, error) Ping(ctx context.Context) error CopyFrom(ctx context.Context, tableName pgx.Identifier, columnNames []string, rowSrc pgx.CopyFromSource) (int64, error) } // PgxConnIface is interface representing pgx connection type PgxConnIface interface { PgxIface Close(ctx context.Context) error } // PgxPoolIface is interface representing pgx pool type PgxPoolIface interface { PgxIface Acquire(ctx context.Context) (*pgxpool.Conn, error) Close() } // PgEngine is responsible for every database-related action type PgEngine struct { l log.LoggerHookerIface ConfigDb PgxPoolIface config.CmdOptions // NOTIFY messages passed verification are pushed to this channel chainSignalChan chan ChainSignal sid int32 logTypeOID uint32 } // Getsid returns the pseudo-random session ID to use for the session identification. // Previously `os.Getpid()` used but this approach is not producing unique IDs for docker containers // where all IDs are the same across all running containers, e.g. 1 func (pge *PgEngine) Getsid() int32 { if pge.sid == 0 { r := rand.New(rand.NewSource(time.Now().UnixNano())) pge.sid = r.Int31() } return pge.sid } var sqls = []string{sqlInit, sqlCron, sqlDDL, sqlJSONSchema, sqlJobFunctions} var sqlNames = []string{"Schema Init", "Cron Functions", "Tables and Views", "JSON Schema", "Job Functions"} // New opens connection and creates schema func New(ctx context.Context, cmdOpts config.CmdOptions, logger log.LoggerHookerIface) (*PgEngine, error) { var ( err error connctx = ctx conncancel context.CancelFunc ) pge := &PgEngine{ l: logger, ConfigDb: nil, CmdOptions: cmdOpts, chainSignalChan: make(chan ChainSignal, 64), } pge.l.WithField("sid", pge.Getsid()).Info("Starting new session... ") if cmdOpts.Connection.Timeout > 0 { // Timeout less than 0 allows endless connection attempts connctx, conncancel = context.WithTimeout(ctx, time.Duration(cmdOpts.Connection.Timeout)*time.Second) defer conncancel() } config := pge.getPgxConnConfig() if err = retry.Do(connctx, backoff, func(ctx context.Context) error { if pge.ConfigDb, err = pgxpool.NewWithConfig(connctx, config); err == nil { err = pge.ConfigDb.Ping(connctx) } if err != nil { pge.l.WithError(err).Error("Connection failed") pge.l.Info("Sleeping before reconnecting...") return retry.RetryableError(err) } return nil }); err != nil { return nil, err } pge.l.Info("Database connection established") if err := pge.ExecuteSchemaScripts(ctx); err != nil { return nil, err } pge.AddLogHook(ctx) //schema exists, we can log now if cmdOpts.Start.File != "" { if err := pge.ExecuteCustomScripts(ctx, cmdOpts.Start.File); err != nil { return nil, err } } return pge, nil } // NewDB creates pgengine instance for already opened database connection, allowing to bypass a parameters based credentials. // We assume here all checks for proper schema validation are done beforehannd func NewDB(DB PgxPoolIface, args ...string) *PgEngine { return &PgEngine{ l: log.Init(config.LoggingOpts{LogLevel: "error"}), ConfigDb: DB, CmdOptions: *config.NewCmdOptions(args...), chainSignalChan: make(chan ChainSignal, 64), } } func quoteIdent(s string) string { return `"` + strings.Replace(s, `"`, `""`, -1) + `"` } // getPgxConnConfig transforms standard connestion string to pgx specific one with func (pge *PgEngine) getPgxConnConfig() *pgxpool.Config { var connstr string if pge.Connection.PgURL != "" { connstr = pge.Connection.PgURL } else { connstr = fmt.Sprintf("host='%s' port='%d' dbname='%s' sslmode='%s' user='%s'", pge.Connection.Host, pge.Connection.Port, pge.Connection.DBName, pge.Connection.SSLMode, pge.Connection.User) if pge.Connection.Password != "" { connstr = connstr + fmt.Sprintf(" password='%s'", pge.Connection.Password) } } connConfig, err := pgxpool.ParseConfig(connstr) if err != nil { pge.l.WithError(err).Error("Cannot parse connection string") return nil } // in the worst scenario we need separate connections for each of workers, // separate connection for Scheduler.retrieveChainsAndRun(), // separate connection for Scheduler.retrieveIntervalChainsAndRun(), // and another connection for LogHook.send() connConfig.MaxConns = int32(pge.Resource.CronWorkers) + int32(pge.Resource.IntervalWorkers) + 3 connConfig.ConnConfig.RuntimeParams["application_name"] = "pg_timetable" connConfig.ConnConfig.OnNotice = func(c *pgconn.PgConn, n *pgconn.Notice) { pge.l.WithField("severity", n.Severity).WithField("notice", n.Message).Info("Notice received") } connConfig.AfterConnect = func(ctx context.Context, pgconn *pgx.Conn) (err error) { pge.l.WithField("pid", pgconn.PgConn().PID()). WithField("client", pge.ClientName). Debug("Trying to get lock for the session") if err = pge.TryLockClientName(ctx, pgconn); err != nil { return err } _, err = pgconn.Exec(ctx, "LISTEN "+quoteIdent(pge.ClientName)) if pge.logTypeOID == InvalidOid { err = pgconn.QueryRow(ctx, "select coalesce(to_regtype('timetable.log_type')::oid, 0)").Scan(&pge.logTypeOID) } pgconn.TypeMap().RegisterType(&pgtype.Type{Name: "timetable.log_type", OID: pge.logTypeOID, Codec: &pgtype.EnumCodec{}}) return err } // reset session before returning connection to the pool // after task completion, if the task is not properly finalized (especially when running in autonomous mode), // some objects and/or setting changes will still exist in the session connConfig.AfterRelease = func(pgconn *pgx.Conn) bool { var err error if _, err = pgconn.Exec(context.Background(), "DISCARD ALL"); err == nil { _, err = pgconn.Exec(context.Background(), "LISTEN "+quoteIdent(pge.ClientName)) } return err != nil } if !pge.Start.Debug { //will handle notification in HandleNotifications directly connConfig.ConnConfig.OnNotification = pge.NotificationHandler } tracelogger := &tracelog.TraceLog{ Logger: log.NewPgxLogger(pge.l), LogLevel: map[bool]tracelog.LogLevel{false: tracelog.LogLevelWarn, true: tracelog.LogLevelDebug}[pge.Verbose()], } connConfig.ConnConfig.Tracer = tracelogger return connConfig } // AddLogHook adds a new pgx log hook to logrus logger func (pge *PgEngine) AddLogHook(ctx context.Context) { pge.l.AddHook(NewHook(ctx, pge, pge.Logging.LogDBLevel)) } // QueryRowIface specifies interface to use QueryRow method type QueryRowIface interface { QueryRow(context.Context, string, ...interface{}) pgx.Row } // TryLockClientName obtains lock on the server to prevent another client with the same name func (pge *PgEngine) TryLockClientName(ctx context.Context, conn QueryRowIface) error { sql := "SELECT COALESCE(to_regproc('timetable.try_lock_client_name')::int4, 0)" var procoid int // check if the schema is available first if err := conn.QueryRow(ctx, sql).Scan(&procoid); err != nil { return err } if procoid == 0 { //there is no schema yet, will lock after bootstrapping pge.l.Debug("There is no schema yet, will lock after bootstrapping") return nil } sql = "SELECT timetable.try_lock_client_name($1, $2)" var locked bool if e := conn.QueryRow(ctx, sql, pge.Getsid(), pge.ClientName).Scan(&locked); e != nil { return e } else if !locked { return errors.New("Cannot obtain lock for a session") } return nil } // ExecuteCustomScripts executes SQL scripts in files func (pge *PgEngine) ExecuteCustomScripts(ctx context.Context, filename ...string) error { for _, f := range filename { sql, err := os.ReadFile(f) if err != nil { pge.l.WithError(err).Error("Cannot read command file") return err } pge.l.Info("Executing script: ", f) if _, err = pge.ConfigDb.Exec(ctx, string(sql)); err != nil { pge.l.WithError(err).Error("Script execution failed") return err } pge.l.Info("Script file executed: ", f) } return nil } // ExecuteSchemaScripts executes initial schema scripts func (pge *PgEngine) ExecuteSchemaScripts(ctx context.Context) error { var exists bool err := pge.ConfigDb.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM pg_namespace WHERE nspname = 'timetable')").Scan(&exists) if err != nil { return err } if !exists { for i, sql := range sqls { sqlName := sqlNames[i] pge.l.Info("Executing script: ", sqlName) if _, err = pge.ConfigDb.Exec(ctx, sql); err != nil { pge.l.WithError(err).Error("Script execution failed") pge.l.Warn("Dropping \"timetable\" schema...") _, err = pge.ConfigDb.Exec(ctx, "DROP SCHEMA IF EXISTS timetable CASCADE") if err != nil { pge.l.WithError(err).Error("Schema dropping failed") } return err } pge.l.Info("Schema file executed: " + sqlName) } pge.l.Info("Configuration schema created...") } return nil } // Finalize closes session func (pge *PgEngine) Finalize() { pge.l.Info("Closing session") sql := `WITH del_ch AS (DELETE FROM timetable.active_chain WHERE client_name = $1) DELETE FROM timetable.active_session WHERE client_name = $1` _, err := pge.ConfigDb.Exec(context.Background(), sql, pge.ClientName) if err != nil { pge.l.WithError(err).Error("Cannot finalize database session") } pge.ConfigDb.Close() pge.ConfigDb = nil } <file_sep>/internal/pgengine/sql/migrations/00575.sql ALTER TABLE timetable.chain ADD COLUMN on_error TEXT;<file_sep>/internal/api/api.go package api import ( "context" "fmt" "net/http" "time" "github.com/cybertec-postgresql/pg_timetable/internal/config" "github.com/cybertec-postgresql/pg_timetable/internal/log" ) // RestHandler is a common interface describing the current status of a connection type RestHandler interface { IsReady() bool StartChain(context.Context, int) error StopChain(context.Context, int) error } type RestAPIServer struct { APIHandler RestHandler l log.LoggerIface http.Server } func Init(opts config.RestAPIOpts, logger log.LoggerIface) *RestAPIServer { s := &RestAPIServer{ nil, logger, http.Server{ Addr: fmt.Sprintf(":%d", opts.Port), ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, MaxHeaderBytes: 1 << 20, }, } http.HandleFunc("/liveness", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) // i'm serving hence I'm alive }) http.HandleFunc("/readiness", s.readinessHandler) http.HandleFunc("/startchain", s.chainHandler) http.HandleFunc("/stopchain", s.chainHandler) if opts.Port != 0 { logger.WithField("port", opts.Port).Info("Starting REST API server...") go func() { logger.Error(s.ListenAndServe()) }() } return s } func (Server *RestAPIServer) readinessHandler(w http.ResponseWriter, r *http.Request) { Server.l.Debug("Received /readiness REST API request") if Server.APIHandler == nil || !Server.APIHandler.IsReady() { w.WriteHeader(http.StatusServiceUnavailable) return } w.WriteHeader(http.StatusOK) r.Context() } <file_sep>/internal/pgengine/log_hook_test.go package pgengine import ( "context" "errors" "testing" "time" "github.com/pashagolub/pgxmock/v2" "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" ) func TestLogHook(t *testing.T) { var h LogHook mockPool, err := pgxmock.NewPool(pgxmock.MonitorPingsOption(true)) assert.NoError(t, err) func() { //fake NewHook h = LogHook{ctx: context.Background(), db: mockPool, cacheLimit: 2, cacheTimeout: time.Second, input: make(chan logrus.Entry, 2), level: "debug", } go h.poll(h.input) }() entries := []logrus.Entry{ //2 entries by cacheLimit and 1 by cacheTimeout {Level: logrus.DebugLevel}, {Level: logrus.InfoLevel}, {Level: logrus.ErrorLevel}, {Level: logrus.FatalLevel}, {Level: 42}, } for _, e := range entries { _ = h.Fire(&e) _ = adaptEntryLevel(e.Level) } levels := []string{"debug", "info", "warn", "fatal", "foobar"} for _, level := range levels { h.level = level assert.NotEmpty(t, h.Levels()) } h.level = "none" assert.Empty(t, h.Levels()) <-time.After(time.Second) } func TestCancelledContext(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) cancel() h := NewHook(ctx, &PgEngine{}, "debug") assert.Equal(t, h.Levels(), logrus.AllLevels) assert.NoError(t, h.Fire(&logrus.Entry{})) } func TestFireError(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() h := NewHook(ctx, &PgEngine{}, "debug") err := errors.New("fire error") go func() { h.lastError <- err }() <-time.After(time.Second) assert.Equal(t, err, h.Fire(&logrus.Entry{})) } <file_sep>/internal/scheduler/scheduler.go package scheduler import ( "context" "sync" "time" "github.com/cybertec-postgresql/pg_timetable/internal/config" "github.com/cybertec-postgresql/pg_timetable/internal/log" "github.com/cybertec-postgresql/pg_timetable/internal/pgengine" ) // the main loop period. Should be 60 (sec) for release configuration. Set to 10 (sec) for debug purposes const refetchTimeout = 60 // the min capacity of chains channels const minChannelCapacity = 1024 // RunStatus specifies the current status of execution type RunStatus int const ( // RunningStatus specifies the scheduler is in the main loop processing chains RunningStatus RunStatus = iota // ContextCancelledStatus specifies the context has been cancelled probably due to timeout ContextCancelledStatus // Shutdown specifies proper termination of the session ShutdownStatus ) // Scheduler is the main class for running the tasks type Scheduler struct { pgengine *pgengine.PgEngine l log.LoggerIface chainsChan chan Chain // channel for passing chains to workers ichainsChan chan IntervalChain // channel for passing interval chains to workers exclusiveMutex sync.RWMutex //read-write mutex for running regular and exclusive chains activeChains map[int]func() // map of chain ID with context cancel() function to abort chain by request activeChainMutex sync.Mutex intervalChains map[int]IntervalChain // map of active chains, updated every minute intervalChainMutex sync.Mutex shutdown chan struct{} // closed when shutdown is called status RunStatus } // New returns a new instance of Scheduler func New(pge *pgengine.PgEngine, logger log.LoggerIface) *Scheduler { return &Scheduler{ l: logger, pgengine: pge, chainsChan: make(chan Chain, max(minChannelCapacity, pge.Resource.CronWorkers*2)), ichainsChan: make(chan IntervalChain, max(minChannelCapacity, pge.Resource.IntervalWorkers*2)), activeChains: make(map[int]func()), //holds cancel() functions to stop chains intervalChains: make(map[int]IntervalChain), shutdown: make(chan struct{}), status: RunningStatus, } } // Shutdown terminates the current session func (sch *Scheduler) Shutdown() { close(sch.shutdown) } // Config returns the current configuration for application func (sch *Scheduler) Config() config.CmdOptions { return sch.pgengine.CmdOptions } // IsReady returns True if the scheduler is in the main loop processing chains func (sch *Scheduler) IsReady() bool { return sch.status == RunningStatus } func (sch *Scheduler) StartChain(ctx context.Context, chainID int) error { return sch.processAsyncChain(ctx, ChainSignal{ ConfigID: chainID, Command: "START", Ts: time.Now().Unix()}) } func (sch *Scheduler) StopChain(ctx context.Context, chainID int) error { return sch.processAsyncChain(ctx, ChainSignal{ ConfigID: chainID, Command: "STOP", Ts: time.Now().Unix()}) } // Run executes jobs. Returns RunStatus why it terminated. // There are only two possibilities: dropped connection and cancelled context. func (sch *Scheduler) Run(ctx context.Context) RunStatus { // create sleeping workers waiting data on channel for w := 1; w <= sch.Config().Resource.CronWorkers; w++ { workerCtx, cancel := context.WithCancel(ctx) defer cancel() go sch.chainWorker(workerCtx, sch.chainsChan) } for w := 1; w <= sch.Config().Resource.IntervalWorkers; w++ { workerCtx, cancel := context.WithCancel(ctx) defer cancel() go sch.intervalChainWorker(workerCtx, sch.ichainsChan) } ctx = log.WithLogger(ctx, sch.l) /* Loop forever or until we ask it to stop. First loop fetches notifications. Main loop works every refetchTimeout seconds and runs chains. */ sch.l.Info("Accepting asynchronous chains execution requests...") go sch.retrieveAsyncChainsAndRun(ctx) if sch.Config().Start.Debug { //run blocking notifications receiving sch.pgengine.HandleNotifications(ctx) return ContextCancelledStatus } sch.l.Debug("Checking for @reboot task chains...") sch.retrieveChainsAndRun(ctx, true) for { sch.l.Debug("Checking for task chains...") go sch.retrieveChainsAndRun(ctx, false) sch.l.Debug("Checking for interval task chains...") go sch.retrieveIntervalChainsAndRun(ctx) select { case <-time.After(refetchTimeout * time.Second): // pass case <-ctx.Done(): sch.status = ContextCancelledStatus case <-sch.shutdown: sch.status = ShutdownStatus sch.terminateChains() } if sch.status != RunningStatus { return sch.status } } } <file_sep>/internal/scheduler/interval_chain.go package scheduler import ( "context" "time" "github.com/cybertec-postgresql/pg_timetable/internal/log" "github.com/cybertec-postgresql/pg_timetable/internal/pgengine" ) type IntervalChain = pgengine.IntervalChain // SendIntervalChain sends interval chain to the channel for workers func (sch *Scheduler) SendIntervalChain(c IntervalChain) { select { case sch.ichainsChan <- c: sch.l.WithField("chain", c.ChainID).Debug("Sent interval chain to the execution channel") default: sch.l.WithField("chain", c.ChainID).Error("Failed to send interval chain to the execution channel") } } func (sch *Scheduler) isValid(ichain IntervalChain) bool { sch.intervalChainMutex.Lock() defer sch.intervalChainMutex.Unlock() return (IntervalChain{}) != sch.intervalChains[ichain.ChainID] } func (sch *Scheduler) reschedule(ctx context.Context, ichain IntervalChain) { if ichain.SelfDestruct { sch.pgengine.DeleteChain(ctx, ichain.ChainID) return } log.GetLogger(ctx).Debug("Sleeping before next execution of interval chain") select { case <-time.After(time.Duration(ichain.Interval) * time.Second): if sch.isValid(ichain) { sch.SendIntervalChain(ichain) } case <-ctx.Done(): return } } func (sch *Scheduler) retrieveIntervalChainsAndRun(ctx context.Context) { var ichains []IntervalChain err := sch.pgengine.SelectIntervalChains(ctx, &ichains) if err != nil { sch.l.WithError(err).Error("Could not query pending interval tasks") } else { sch.l.WithField("count", len(ichains)).Info("Retrieve interval chains to run") } // delete chains that are not returned from the database sch.intervalChainMutex.Lock() for id, ichain := range sch.intervalChains { if !ichain.IsListed(ichains) { delete(sch.intervalChains, id) } } // update chains from the database and send to working channel new one for _, ichain := range ichains { if (IntervalChain{}) == sch.intervalChains[ichain.ChainID] { sch.SendIntervalChain(ichain) } sch.intervalChains[ichain.ChainID] = ichain } sch.intervalChainMutex.Unlock() } func (sch *Scheduler) intervalChainWorker(ctx context.Context, ichains <-chan IntervalChain) { for { select { case <-ctx.Done(): //check context with high priority return default: select { case ichain := <-ichains: if !sch.isValid(ichain) { // chain not in the list of active chains continue } chainL := sch.l.WithField("chain", ichain.ChainID) chainContext := log.WithLogger(ctx, chainL) chainL.Info("Starting chain") if !ichain.RepeatAfter { go sch.reschedule(chainContext, ichain) } if !sch.pgengine.InsertChainRunStatus(ctx, ichain.ChainID, ichain.MaxInstances) { chainL.Info("Cannot proceed. Sleeping") if ichain.RepeatAfter { go sch.reschedule(chainContext, ichain) } continue } sch.Lock(ichain.ExclusiveExecution) sch.executeChain(chainContext, ichain.Chain) sch.Unlock(ichain.ExclusiveExecution) if ichain.RepeatAfter { go sch.reschedule(chainContext, ichain) } case <-ctx.Done(): return } } } } <file_sep>/samples/CronStyle.sql -- Create a job with the timetable.add_job function in cron style -- In order to demonstrate Cron style schduling of job execution, we will create a table(One time) for inserting of data CREATE TABLE IF NOT EXISTS timetable.dummy_log ( log_ID BIGSERIAL, event_name TEXT, timestmp TIMESTAMPTZ DEFAULT TRANSACTION_TIMESTAMP(), PRIMARY KEY (log_ID)); ----CRON-Style -- * * * * * command to execute -- ┬ ┬ ┬ ┬ ┬ -- │ │ │ │ │ -- │ │ │ │ └──── day of the week (0 - 7) (Sunday to Saturday)(0 and 7 is Sunday); -- │ │ │ └────── month (1 - 12) -- │ │ └──────── day of the month (1 - 31) -- │ └────────── hour (0 - 23) -- └──────────── minute (0 - 59) SELECT timetable.add_job ( job_name => 'cron_Job run after 40th minutes after 2 hour on 27th of every month ', job_schedule => '40 */2 27 * *', job_command => $$INSERT INTO timetable.dummy_log (event_name) VALUES ('Cron test')$$ );<file_sep>/internal/api/api_test.go package api_test import ( "context" "errors" "io" "net/http" "testing" "github.com/cybertec-postgresql/pg_timetable/internal/api" "github.com/cybertec-postgresql/pg_timetable/internal/config" "github.com/cybertec-postgresql/pg_timetable/internal/log" "github.com/stretchr/testify/assert" ) type apihandler struct { } func (r *apihandler) IsReady() bool { return true } func (r *apihandler) StartChain(_ context.Context, chainID int) error { if chainID == 0 { return errors.New("invalid chain id") } return nil } func (r *apihandler) StopChain(context.Context, int) error { return nil } var restsrv *api.RestAPIServer func init() { restsrv = api.Init(config.RestAPIOpts{Port: 8080}, log.Init(config.LoggingOpts{LogLevel: "error"})) } func TestStatus(t *testing.T) { r, err := http.Get("http://localhost:8080/liveness") assert.NoError(t, err) assert.Equal(t, http.StatusOK, r.StatusCode) r, err = http.Get("http://localhost:8080/readiness") assert.NoError(t, err) assert.Equal(t, http.StatusServiceUnavailable, r.StatusCode) restsrv.APIHandler = &apihandler{} r, err = http.Get("http://localhost:8080/readiness") assert.NoError(t, err) assert.Equal(t, http.StatusOK, r.StatusCode) } func TestChainManager(t *testing.T) { restsrv.APIHandler = &apihandler{} r, err := http.Get("http://localhost:8080/startchain") assert.NoError(t, err) assert.Equal(t, http.StatusBadRequest, r.StatusCode) b, _ := io.ReadAll(r.Body) assert.Contains(t, string(b), "invalid syntax") r, err = http.Get("http://localhost:8080/startchain?id=1") assert.NoError(t, err) assert.Equal(t, http.StatusOK, r.StatusCode) r, err = http.Get("http://localhost:8080/stopchain?id=1") assert.NoError(t, err) assert.Equal(t, http.StatusOK, r.StatusCode) r, err = http.Get("http://localhost:8080/startchain?id=0") assert.NoError(t, err) assert.Equal(t, http.StatusBadRequest, r.StatusCode) b, _ = io.ReadAll(r.Body) assert.Contains(t, string(b), "invalid chain id") } <file_sep>/internal/pgengine/sql/migrations/00560.sql ALTER TABLE timetable.execution_log ALTER txid TYPE BIGINT;<file_sep>/internal/pgengine/migration.go package pgengine import ( "context" "embed" "github.com/cybertec-postgresql/pg_timetable/internal/log" "github.com/cybertec-postgresql/pg_timetable/internal/migrator" pgx "github.com/jackc/pgx/v5" ) //go:embed sql/migrations/*.sql var migrationsFiles embed.FS // MigrateDb upgrades database with all migrations func (pge *PgEngine) MigrateDb(ctx context.Context) error { m, err := pge.initMigrator() if err != nil { return err } pge.l.Info("Upgrading database...") conn, err := pge.ConfigDb.Acquire(ctx) defer conn.Release() if err != nil { return err } return m.Migrate(ctx, conn.Conn()) } // CheckNeedMigrateDb checks need of upgrading database and throws error if that's true func (pge *PgEngine) CheckNeedMigrateDb(ctx context.Context) (bool, error) { m, err := pge.initMigrator() if err != nil { return false, err } pge.l.Debug("Check need of upgrading database...") ctx = log.WithLogger(ctx, pge.l) conn, err := pge.ConfigDb.Acquire(ctx) defer conn.Release() if err != nil { return false, err } return m.NeedUpgrade(ctx, conn.Conn()) } // ExecuteMigrationScript executes the migration script specified by fname within transaction tx func ExecuteMigrationScript(ctx context.Context, tx pgx.Tx, fname string) error { sql, err := migrationsFiles.ReadFile("sql/migrations/" + fname) if err != nil { return err } _, err = tx.Exec(ctx, string(sql)) return err } // Migrations holds function returning all updgrade migrations needed var Migrations func() migrator.Option = func() migrator.Option { return migrator.Migrations( &migrator.Migration{ Name: "00259 Restart migrations for v4", Func: func(ctx context.Context, tx pgx.Tx) error { // "migrations" table will be created automatically return nil }, }, &migrator.Migration{ Name: "00305 Fix timetable.is_cron_in_time", Func: func(ctx context.Context, tx pgx.Tx) error { return ExecuteMigrationScript(ctx, tx, "00305.sql") }, }, &migrator.Migration{ Name: "00323 Append timetable.delete_job function", Func: func(ctx context.Context, tx pgx.Tx) error { return ExecuteMigrationScript(ctx, tx, "00323.sql") }, }, &migrator.Migration{ Name: "00329 Migration required for some new added functions", Func: func(ctx context.Context, tx pgx.Tx) error { return ExecuteMigrationScript(ctx, tx, "00329.sql") }, }, &migrator.Migration{ Name: "00334 Refactor timetable.task as plain schema without tree-like dependencies", Func: func(ctx context.Context, tx pgx.Tx) error { return ExecuteMigrationScript(ctx, tx, "00334.sql") }, }, &migrator.Migration{ Name: "00381 Rewrite active chain handling", Func: func(ctx context.Context, tx pgx.Tx) error { return ExecuteMigrationScript(ctx, tx, "00381.sql") }, }, &migrator.Migration{ Name: "00394 Add started_at column to active_session and active_chain tables", Func: func(ctx context.Context, tx pgx.Tx) error { return ExecuteMigrationScript(ctx, tx, "00394.sql") }, }, &migrator.Migration{ Name: "00417 Rename LOG database log level to INFO", Func: func(ctx context.Context, tx pgx.Tx) error { return ExecuteMigrationScript(ctx, tx, "00417.sql") }, }, &migrator.Migration{ Name: "00436 Add txid column to timetable.execution_log", Func: func(ctx context.Context, tx pgx.Tx) error { return ExecuteMigrationScript(ctx, tx, "00436.sql") }, }, &migrator.Migration{ Name: "00534 Use cron_split_to_arrays() in cron domain check", Func: func(ctx context.Context, tx pgx.Tx) error { return ExecuteMigrationScript(ctx, tx, "00534.sql") }, }, &migrator.Migration{ Name: "00560 Alter txid column to bigint", Func: func(ctx context.Context, tx pgx.Tx) error { return ExecuteMigrationScript(ctx, tx, "00560.sql") }, }, &migrator.Migration{ Name: "00573 Add ability to start a chain with delay", Func: func(ctx context.Context, tx pgx.Tx) error { return ExecuteMigrationScript(ctx, tx, "00573.sql") }, }, &migrator.Migration{ Name: "00575 Add on_error handling", Func: func(ctx context.Context, tx pgx.Tx) error { return ExecuteMigrationScript(ctx, tx, "00575.sql") }, }, // adding new migration here, update "timetable"."migration" in "sql/init.sql" // and "dbapi" variable in main.go! // &migrator.Migration{ // Name: "000XX Short description of a migration", // Func: func(ctx context.Context, tx pgx.Tx) error { // return executeMigrationScript(ctx, tx, "000XX.sql") // }, // }, ) } func (pge *PgEngine) initMigrator() (*migrator.Migrator, error) { m, err := migrator.New( migrator.TableName("timetable.migration"), migrator.SetNotice(func(s string) { pge.l.Info(s) }), Migrations(), ) if err != nil { pge.l.WithError(err).Error("Cannot initialize migration") } return m, err } <file_sep>/internal/migrator/migrator_test.go package migrator_test import ( "context" "errors" "fmt" "math" "strings" "testing" "github.com/cybertec-postgresql/pg_timetable/internal/config" "github.com/cybertec-postgresql/pg_timetable/internal/log" "github.com/cybertec-postgresql/pg_timetable/internal/migrator" "github.com/cybertec-postgresql/pg_timetable/internal/pgengine" pgx "github.com/jackc/pgx/v5" "github.com/pashagolub/pgxmock/v2" "github.com/stretchr/testify/assert" ) var cmdOpts = config.NewCmdOptions("-c", "migrator_unit_test", "--password=<PASSWORD>") var migrations = []interface{}{ &migrator.Migration{ Name: "Using tx, encapsulate two queries", Func: func(ctx context.Context, tx pgx.Tx) error { if _, err := tx.Exec(ctx, "CREATE TABLE foo (id INT PRIMARY KEY)"); err != nil { return err } if _, err := tx.Exec(ctx, "INSERT INTO foo (id) VALUES (1)"); err != nil { return err } return nil }, }, &migrator.MigrationNoTx{ Name: "Using db, execute one query", Func: func(ctx context.Context, db migrator.PgxIface) error { if _, err := db.Exec(ctx, "INSERT INTO foo (id) VALUES (2)"); err != nil { return err } return nil }, }, } func migrateTest() error { migrator, err := migrator.New(migrator.Migrations(migrations...)) if err != nil { return err } // Migrate up ctx := context.Background() pge, err := pgengine.New(ctx, *cmdOpts, log.Init(config.LoggingOpts{LogLevel: "error"})) if err != nil { return err } _, _ = pge.ConfigDb.Exec(ctx, "DROP TABLE IF EXISTS foo, bar, baz, migration") db, err := pge.ConfigDb.Acquire(ctx) if err != nil { return err } defer db.Release() return migrator.Migrate(ctx, db.Conn()) } func mustMigrator(migrator *migrator.Migrator, err error) *migrator.Migrator { if err != nil { panic(err) } return migrator } func TestPostgres(t *testing.T) { if err := migrateTest(); err != nil { t.Fatal(err) } } func TestBadMigrations(t *testing.T) { pge, err := pgengine.New(context.Background(), *cmdOpts, log.Init(config.LoggingOpts{LogLevel: "error"})) if err != nil { t.Fatal(err) } defer pge.Finalize() ctx := context.Background() db, err := pge.ConfigDb.Acquire(ctx) if err != nil { t.Fatal(err) } defer db.Release() var migrators = []struct { name string input *migrator.Migrator want error }{ { name: "bad tx migration", input: mustMigrator(migrator.New(migrator.Migrations(&migrator.Migration{ Name: "bad tx migration", Func: func(ctx context.Context, tx pgx.Tx) error { if _, err := tx.Exec(ctx, "FAIL FAST"); err != nil { return err } return nil }, }))), }, { name: "bad db migration", input: mustMigrator(migrator.New(migrator.Migrations(&migrator.MigrationNoTx{ Name: "bad db migration", Func: func(ctx context.Context, db migrator.PgxIface) error { if _, err := db.Exec(ctx, "FAIL FAST"); err != nil { return err } return nil }, }))), }, } for _, tt := range migrators { _, err := db.Exec(ctx, fmt.Sprintf("DROP TABLE IF EXISTS %s", tt.input.TableName)) if err != nil { t.Fatal(err) } t.Run(tt.name, func(t *testing.T) { err := tt.input.Migrate(context.Background(), db.Conn()) if err != nil && !strings.Contains(err.Error(), "syntax error") { t.Fatal(err) } }) } } func TestPending(t *testing.T) { pge, err := pgengine.New(context.Background(), *cmdOpts, log.Init(config.LoggingOpts{LogLevel: "error"})) if err != nil { t.Fatal(err) } defer pge.Finalize() ctx := context.Background() db, err := pge.ConfigDb.Acquire(ctx) if err != nil { t.Fatal(err) } defer db.Release() migrator := mustMigrator(migrator.New(migrator.Migrations( &migrator.Migration{ Name: "Using tx, create baz table", Func: func(ctx context.Context, tx pgx.Tx) error { if _, err := tx.Exec(ctx, "CREATE TABLE baz (id INT PRIMARY KEY)"); err != nil { return err } return nil }, }, ))) pending, _, err := migrator.Pending(context.Background(), db.Conn()) if err != nil { t.Fatal(err) } if len(pending) != 1 { t.Fatalf("pending migrations should be 1, got %d", len(pending)) } } func TestMigratorConstructor(t *testing.T) { _, err := migrator.New() //migrator.Migrations(migrations...) assert.Error(t, err, "Should throw error when migrations are empty") _, err = migrator.New(migrator.Migrations(struct{ Foo string }{Foo: "bar"})) assert.Error(t, err, "Should throw error for unknown migration type") } func TestTableExists(t *testing.T) { mock, err := pgxmock.NewPool() assert.NoError(t, err) defer mock.Close() m, err := migrator.New(migrator.Migrations(migrations...)) assert.NoError(t, err) assert.NotNil(t, m) sqlresults := []struct { testname string tableexists bool appliedcount int needupgrade bool tableerr error counterr error }{ { testname: "table exists and no migrations applied", tableexists: true, appliedcount: 0, needupgrade: true, tableerr: nil, counterr: nil, }, { testname: "table exists and a lot of migrations applied", tableexists: true, appliedcount: math.MaxInt32, needupgrade: false, tableerr: nil, counterr: nil, }, { testname: "error occurred during count query", tableexists: true, appliedcount: 0, needupgrade: false, tableerr: nil, counterr: errors.New("internal error"), }, { testname: "error occurred during table exists query", tableexists: false, appliedcount: 0, needupgrade: true, tableerr: errors.New("internal error"), counterr: nil, }, } var expectederr error for _, res := range sqlresults { if q := mock.ExpectQuery("SELECT to_regclass").WithArgs(pgxmock.AnyArg()); res.tableerr != nil { q.WillReturnError(res.tableerr) expectederr = res.tableerr } else { q.WillReturnRows(pgxmock.NewRows([]string{"to_regclass"}).AddRow(res.tableexists)) } if q := mock.ExpectQuery("SELECT count"); res.counterr != nil { q.WillReturnError(res.counterr) expectederr = res.counterr } else { q.WillReturnRows(pgxmock.NewRows([]string{"count"}).AddRow(res.appliedcount)) } need, err := m.NeedUpgrade(context.Background(), mock) assert.Equal(t, expectederr, err, "NeedUpgrade test failed: ", res.testname) assert.Equal(t, res.needupgrade, need, "NeedUpgrade incorrect return: ", res.testname) } } func TestMigrateExists(t *testing.T) { mock, err := pgxmock.NewPool() assert.NoError(t, err) defer mock.Close() m, err := migrator.New(migrator.Migrations(migrations...)) assert.NoError(t, err) assert.NotNil(t, m) expectederr := errors.New("internal error") mock.ExpectExec("CREATE TABLE").WillReturnResult(pgxmock.NewResult("DDL", 0)) mock.ExpectQuery("SELECT count").WillReturnError(expectederr) err = m.Migrate(context.Background(), mock) assert.Equal(t, expectederr, err, "Migrate test failed: ", err) if err := mock.ExpectationsWereMet(); err != nil { t.Errorf("there were unfulfilled expectations: %s", err) } } func TestMigrateNoTxError(t *testing.T) { mock, err := pgxmock.NewPool() assert.NoError(t, err) defer mock.Close() m, err := migrator.New(migrator.Migrations(&migrator.MigrationNoTx{Func: func(context.Context, migrator.PgxIface) error { return nil }})) assert.NoError(t, err) assert.NotNil(t, m) expectederr := errors.New("internal error") mock.ExpectExec("CREATE TABLE").WillReturnResult(pgxmock.NewResult("DDL", 0)) mock.ExpectQuery("SELECT count").WillReturnRows(pgxmock.NewRows([]string{"count"}).AddRow(0)) mock.ExpectExec("INSERT").WillReturnError(expectederr) err = m.Migrate(context.Background(), mock) for errors.Unwrap(err) != nil { err = errors.Unwrap(err) } assert.Equal(t, expectederr, err, "MigrateNoTxError test failed: ", err) if err := mock.ExpectationsWereMet(); err != nil { t.Errorf("there were unfulfilled expectations: %s", err) } } func TestMigrateTxError(t *testing.T) { mock, err := pgxmock.NewPool() assert.NoError(t, err) defer mock.Close() m, err := migrator.New(migrator.Migrations(&migrator.Migration{Func: func(context.Context, pgx.Tx) error { return nil }})) assert.NoError(t, err) assert.NotNil(t, m) expectederr := errors.New("create table error") mock.ExpectExec("CREATE TABLE").WillReturnError(expectederr) err = m.Migrate(context.Background(), mock) assert.Equal(t, expectederr, err, "MigrateTxError test failed: ", err) expectederr = errors.New("internal tx error") mock.ExpectExec("CREATE TABLE").WillReturnResult(pgxmock.NewResult("DDL", 0)) mock.ExpectQuery("SELECT count").WillReturnRows(pgxmock.NewRows([]string{"count"}).AddRow(0)) mock.ExpectBegin().WillReturnError(expectederr) err = m.Migrate(context.Background(), mock) for errors.Unwrap(err) != nil { err = errors.Unwrap(err) } assert.Equal(t, expectederr, err, "MigrateTxError test failed: ", err) expectederr = errors.New("internal tx error") mock.ExpectExec("CREATE TABLE").WillReturnResult(pgxmock.NewResult("DDL", 0)) mock.ExpectQuery("SELECT count").WillReturnRows(pgxmock.NewRows([]string{"count"}).AddRow(0)) mock.ExpectBegin() mock.ExpectExec("INSERT").WillReturnError(expectederr) err = m.Migrate(context.Background(), mock) for errors.Unwrap(err) != nil { err = errors.Unwrap(err) } assert.Equal(t, expectederr, err, "MigrateTxError test failed: ", err) if err := mock.ExpectationsWereMet(); err != nil { t.Errorf("there were unfulfilled expectations: %s", err) } } func TestMigratorOptions(t *testing.T) { O := migrator.TableName("foo") m := &migrator.Migrator{} O(m) assert.Equal(t, "foo", m.TableName) f := func(string) {} O = migrator.SetNotice(f) O(m) } <file_sep>/extras/pg_cron_to_pg_timetable.sql SET ROLE 'scheduler'; -- set the role used by pg_cron WITH cron_chain AS ( SELECT nextval('timetable.chain_chain_id_seq'::regclass) AS cron_id, jobname, schedule, active, command, CASE WHEN database != current_database() OR nodename != 'localhost' OR username != CURRENT_USER OR nodeport != inet_server_port() THEN format('host=%s port=%s dbname=%s user=%s', nodename, nodeport, database, username) END AS connstr FROM cron.job ), cte_chain AS ( INSERT INTO timetable.chain (chain_id, chain_name, run_at, live) SELECT cron_id, COALESCE(jobname, 'cronjob' || cron_id), schedule, active FROM cron_chain ), cte_tasks AS ( INSERT INTO timetable.task (chain_id, task_order, kind, command, database_connection) SELECT cron_id, 1, 'SQL', command, connstr FROM cron_chain RETURNING chain_id, task_id ) SELECT * FROM cte_tasks;<file_sep>/internal/log/formatter_test.go package log_test import ( "bytes" "fmt" "os" "path" "regexp" "runtime" "strings" "testing" formatter "github.com/cybertec-postgresql/pg_timetable/internal/log" "github.com/sirupsen/logrus" ) func ExampleFormatter_Format_default() { l := logrus.New() l.SetOutput(os.Stdout) l.SetLevel(logrus.DebugLevel) l.SetFormatter(&formatter.Formatter{ NoColors: true, TimestampFormat: "-", }) l.Debug("test1") l.Info("test2") l.Warn("test3") l.Error("test4") // Output: // - [DEBU] test1 // - [INFO] test2 // - [WARN] test3 // - [ERRO] test4 } func ExampleFormatter_Format_full_level() { l := logrus.New() l.SetOutput(os.Stdout) l.SetLevel(logrus.DebugLevel) l.SetFormatter(&formatter.Formatter{ NoColors: true, TimestampFormat: "-", ShowFullLevel: true, }) l.Debug("test1") l.Info("test2") l.Warn("test3") l.Error(" test4") // Output: // - [DEBUG] test1 // - [INFO] test2 // - [WARNING] test3 // - [ERROR] test4 } func ExampleFormatter_Format_show_keys() { l := logrus.New() l.SetOutput(os.Stdout) l.SetLevel(logrus.DebugLevel) l.SetFormatter(&formatter.Formatter{ NoColors: true, TimestampFormat: "-", HideKeys: false, }) ll := l.WithField("category", "rest") l.Info("test1") ll.Info("test2") // Output: // - [INFO] test1 // - [INFO] [category:rest] test2 } func ExampleFormatter_Format_hide_keys() { l := logrus.New() l.SetOutput(os.Stdout) l.SetLevel(logrus.DebugLevel) l.SetFormatter(&formatter.Formatter{ NoColors: true, TimestampFormat: "-", HideKeys: true, }) ll := l.WithField("category", "rest") l.Info("test1") ll.Info("test2") // Output: // - [INFO] test1 // - [INFO] [rest] test2 } func ExampleFormatter_Format_sort_order() { l := logrus.New() l.SetOutput(os.Stdout) l.SetLevel(logrus.DebugLevel) l.SetFormatter(&formatter.Formatter{ NoColors: true, TimestampFormat: "-", HideKeys: false, }) ll := l.WithField("component", "main") lll := ll.WithField("category", "rest") l.Info("test1") ll.Info("test2") lll.Info("test3") // Output: // - [INFO] test1 // - [INFO] [component:main] test2 // - [INFO] [category:rest] [component:main] test3 } func ExampleFormatter_Format_field_order() { l := logrus.New() l.SetOutput(os.Stdout) l.SetLevel(logrus.DebugLevel) l.SetFormatter(&formatter.Formatter{ NoColors: true, TimestampFormat: "-", FieldsOrder: []string{"component", "category"}, HideKeys: false, }) ll := l.WithField("component", "main") lll := ll.WithField("category", "rest") l.Info("test1") ll.Info("test2") lll.Info("test3") // Output: // - [INFO] test1 // - [INFO] [component:main] test2 // - [INFO] [component:main] [category:rest] test3 } func ExampleFormatter_Format_no_fields_space() { l := logrus.New() l.SetOutput(os.Stdout) l.SetLevel(logrus.DebugLevel) l.SetFormatter(&formatter.Formatter{ NoColors: true, TimestampFormat: "-", FieldsOrder: []string{"component", "category"}, HideKeys: false, NoFieldsSpace: true, }) ll := l.WithField("component", "main") lll := ll.WithField("category", "rest") l.Info("test1") ll.Info("test2") lll.Info("test3") // Output: // - [INFO] test1 // - [INFO][component:main] test2 // - [INFO][component:main][category:rest] test3 } func ExampleFormatter_Format_no_uppercase_level() { l := logrus.New() l.SetOutput(os.Stdout) l.SetLevel(logrus.DebugLevel) l.SetFormatter(&formatter.Formatter{ NoColors: true, TimestampFormat: "-", FieldsOrder: []string{"component", "category"}, NoUppercaseLevel: true, }) ll := l.WithField("component", "main") lll := ll.WithField("category", "rest") llll := ll.WithField("category", "other") l.Debug("test1") ll.Info("test2") lll.Warn("test3") llll.Error("test4") // Output: // - [debu] test1 // - [info] [component:main] test2 // - [warn] [component:main] [category:rest] test3 // - [erro] [component:main] [category:other] test4 } func ExampleFormatter_Format_trim_message() { l := logrus.New() l.SetOutput(os.Stdout) l.SetLevel(logrus.DebugLevel) l.SetFormatter(&formatter.Formatter{ TrimMessages: true, NoColors: true, TimestampFormat: "-", }) l.Debug(" test1 ") l.Info("test2 ") l.Warn(" test3") l.Error(" test4 ") // Output: // - [DEBU] test1 // - [INFO] test2 // - [WARN] test3 // - [ERRO] test4 } func TestFormatter_Format_with_report_caller(t *testing.T) { output := bytes.NewBuffer([]byte{}) l := logrus.New() l.SetOutput(output) l.SetLevel(logrus.DebugLevel) l.SetFormatter(&formatter.Formatter{ NoColors: true, TimestampFormat: "-", }) l.SetReportCaller(true) l.Debug("test1") line, err := output.ReadString('\n') if err != nil { t.Errorf("Cannot read log output: %v", err) } expectedRegExp := "- \\[DEBU\\] test1 \\(.+\\.go:[0-9]+ .+\\)\n$" match, err := regexp.MatchString( expectedRegExp, line, ) if err != nil { t.Errorf("Cannot check regexp: %v", err) } else if !match { t.Errorf( "logger.SetReportCaller(true) output doesn't match, expected: %s to find in: '%s'", expectedRegExp, line, ) } } func TestFormatter_Format_with_report_caller_and_CallerFirst_true(t *testing.T) { output := bytes.NewBuffer([]byte{}) l := logrus.New() l.SetOutput(output) l.SetLevel(logrus.DebugLevel) l.SetFormatter(&formatter.Formatter{ NoColors: true, TimestampFormat: "-", CallerFirst: true, }) l.SetReportCaller(true) l.Debug("test1") line, err := output.ReadString('\n') if err != nil { t.Errorf("Cannot read log output: %v", err) } expectedRegExp := "- \\(.+\\.go:[0-9]+ .+\\) \\[DEBU\\] test1\n$" match, err := regexp.MatchString( expectedRegExp, line, ) if err != nil { t.Errorf("Cannot check regexp: %v", err) } else if !match { t.Errorf( "logger.SetReportCaller(true) output doesn't match, expected: %s to find in: '%s'", expectedRegExp, line, ) } } func TestFormatter_Format_with_report_caller_and_CustomCallerFormatter(t *testing.T) { output := bytes.NewBuffer([]byte{}) l := logrus.New() l.SetOutput(output) l.SetLevel(logrus.DebugLevel) l.SetFormatter(&formatter.Formatter{ NoColors: true, TimestampFormat: "-", CallerFirst: true, CustomCallerFormatter: func(f *runtime.Frame) string { s := strings.Split(f.Function, ".") funcName := s[len(s)-1] return fmt.Sprintf(" [%s:%d][%s()]", path.Base(f.File), f.Line, funcName) }, }) l.SetReportCaller(true) l.Debug("test1") line, err := output.ReadString('\n') if err != nil { t.Errorf("Cannot read log output: %v", err) } expectedRegExp := "- \\[.+\\.go:[0-9]+\\]\\[.+\\(\\)\\] \\[DEBU\\] test1\n$" match, err := regexp.MatchString( expectedRegExp, line, ) if err != nil { t.Errorf("Cannot check regexp: %v", err) } else if !match { t.Errorf( "logger.SetReportCaller(true) output doesn't match, expected: %s to find in: '%s'", expectedRegExp, line, ) } } <file_sep>/internal/pgengine/sql/migrations/00417.sql ALTER TYPE timetable.log_type RENAME VALUE 'LOG' TO 'INFO'; <file_sep>/internal/pgengine/access.go package pgengine import ( "context" "fmt" "strings" "github.com/jackc/pgx/v5" ) // InvalidOid specifies value for non-existent objects const InvalidOid = 0 // DeleteChain delete chain configuration for self destructive chains func (pge *PgEngine) DeleteChain(ctx context.Context, chainID int) bool { pge.l.WithField("chain", chainID).Info("Deleting self destructive chain configuration") res, err := pge.ConfigDb.Exec(ctx, "DELETE FROM timetable.chain WHERE chain_id = $1", chainID) if err != nil { pge.l.WithError(err).Error("Failed to delete self destructive chain") return false } return err == nil && res.RowsAffected() == 1 } // IsAlive returns true if the connection to the database is alive func (pge *PgEngine) IsAlive() bool { return pge.ConfigDb != nil && pge.ConfigDb.Ping(context.Background()) == nil } // LogTaskExecution will log current chain element execution status including retcode func (pge *PgEngine) LogTaskExecution(ctx context.Context, task *ChainTask, retCode int, output string) { _, err := pge.ConfigDb.Exec(ctx, `INSERT INTO timetable.execution_log ( chain_id, task_id, command, kind, last_run, finished, returncode, pid, output, client_name, txid) VALUES ($1, $2, $3, $4, clock_timestamp() - $5 :: interval, clock_timestamp(), $6, $7, NULLIF($8, ''), $9, $10)`, task.ChainID, task.TaskID, task.Script, task.Kind, fmt.Sprintf("%f seconds", float64(task.Duration)/1000000), retCode, pge.Getsid(), strings.TrimSpace(output), pge.ClientName, task.Txid) if err != nil { pge.l.WithError(err).Error("Failed to log chain element execution status") } } // InsertChainRunStatus inits the execution run log, which will be use to effectively control scheduler concurrency func (pge *PgEngine) InsertChainRunStatus(ctx context.Context, chainID int, maxInstances int) bool { const sqlInsertRunStatus = `INSERT INTO timetable.active_chain (chain_id, client_name) SELECT $1, $2 WHERE ( SELECT COALESCE(count(*) < $3, TRUE) FROM timetable.active_chain ac WHERE ac.chain_id = $1 )` res, err := pge.ConfigDb.Exec(ctx, sqlInsertRunStatus, chainID, pge.ClientName, maxInstances) if err != nil { pge.l.WithError(err).Error("Cannot save information about the chain run status") return false } return res.RowsAffected() == 1 } func (pge *PgEngine) RemoveChainRunStatus(ctx context.Context, chainID int) { const sqlRemoveRunStatus = `DELETE FROM timetable.active_chain WHERE chain_id = $1 and client_name = $2` _, err := pge.ConfigDb.Exec(ctx, sqlRemoveRunStatus, chainID, pge.ClientName) if err != nil { pge.l.WithError(err).Error("Cannot save information about the chain run status") } } // Select live chains with proper client_name value const sqlSelectLiveChains = `SELECT chain_id, chain_name, self_destruct, exclusive_execution, COALESCE(max_instances, 16) as max_instances, COALESCE(timeout, 0) as timeout, on_error FROM timetable.chain WHERE live AND (client_name = $1 or client_name IS NULL)` // SelectRebootChains returns a list of chains should be executed after reboot func (pge *PgEngine) SelectRebootChains(ctx context.Context, dest *[]Chain) error { const sqlSelectRebootChains = sqlSelectLiveChains + ` AND run_at = '@reboot'` rows, err := pge.ConfigDb.Query(ctx, sqlSelectRebootChains, pge.ClientName) if err != nil { return err } *dest, err = pgx.CollectRows(rows, pgx.RowToStructByPos[Chain]) return err } // SelectChains returns a list of chains should be executed at the current moment func (pge *PgEngine) SelectChains(ctx context.Context, dest *[]Chain) error { const sqlSelectChains = sqlSelectLiveChains + ` AND NOT COALESCE(starts_with(run_at, '@'), FALSE) AND timetable.is_cron_in_time(run_at, now())` rows, err := pge.ConfigDb.Query(ctx, sqlSelectChains, pge.ClientName) if err != nil { return err } *dest, err = pgx.CollectRows(rows, pgx.RowToStructByPos[Chain]) return err } // SelectIntervalChains returns list of interval chains to be executed func (pge *PgEngine) SelectIntervalChains(ctx context.Context, dest *[]IntervalChain) error { const sqlSelectIntervalChains = `SELECT chain_id, chain_name, self_destruct, exclusive_execution, COALESCE(max_instances, 16), COALESCE(timeout, 0), on_error, EXTRACT(EPOCH FROM (substr(run_at, 7) :: interval)) :: int4 as interval_seconds, starts_with(run_at, '@after') as repeat_after FROM timetable.chain WHERE live AND (client_name = $1 or client_name IS NULL) AND substr(run_at, 1, 6) IN ('@every', '@after')` rows, err := pge.ConfigDb.Query(ctx, sqlSelectIntervalChains, pge.ClientName) if err != nil { return err } *dest, err = pgx.CollectRows(rows, pgx.RowToStructByPos[IntervalChain]) return err } // SelectChain returns the chain with the specified ID func (pge *PgEngine) SelectChain(ctx context.Context, dest *Chain, chainID int) error { // we accept not only live chains here because we want to run them in debug mode const sqlSelectSingleChain = `SELECT chain_id, chain_name, self_destruct, exclusive_execution, COALESCE(timeout, 0) as timeout, COALESCE(max_instances, 16) as max_instances, on_error FROM timetable.chain WHERE (client_name = $1 OR client_name IS NULL) AND chain_id = $2` rows, err := pge.ConfigDb.Query(ctx, sqlSelectSingleChain, pge.ClientName, chainID) if err != nil { return err } *dest, err = pgx.CollectOneRow(rows, pgx.RowToStructByName[Chain]) return err } // GetChainElements returns all elements for a given chain func (pge *PgEngine) GetChainElements(ctx context.Context, chainTasks *[]ChainTask, chainID int) error { const sqlSelectChainTasks = `SELECT task_id, command, kind, run_as, ignore_error, autonomous, database_connection, timeout FROM timetable.task WHERE chain_id = $1 ORDER BY task_order ASC` rows, err := pge.ConfigDb.Query(ctx, sqlSelectChainTasks, chainID) if err != nil { return err } *chainTasks, err = pgx.CollectRows(rows, pgx.RowToStructByName[ChainTask]) return err } // GetChainParamValues returns parameter values to pass for task being executed func (pge *PgEngine) GetChainParamValues(ctx context.Context, paramValues *[]string, task *ChainTask) error { const sqlGetParamValues = `SELECT value FROM timetable.parameter WHERE task_id = $1 AND value IS NOT NULL ORDER BY order_id ASC` rows, err := pge.ConfigDb.Query(ctx, sqlGetParamValues, task.TaskID) if err != nil { return err } *paramValues, err = pgx.CollectRows(rows, pgx.RowTo[string]) return err } <file_sep>/Dockerfile # When building an image it is recommended to provide version arguments, e.g. # docker build --no-cache -t cybertecpostgresql/pg_timetable:<tagname> \ # --build-arg COMMIT=`git show -s --format=%H HEAD` \ # --build-arg VERSION=`git describe --tags --abbrev=0` \ # --build-arg DATE=`git show -s --format=%cI HEAD` . FROM golang:alpine AS builder ARG COMMIT ARG VERSION ARG DATE # Set necessary environmet variables needed for our image ENV GO111MODULE=on \ CGO_ENABLED=0 \ GOOS=linux \ GOARCH=amd64 # Move to working directory /build WORKDIR /build # Update certificates RUN apk update && apk upgrade && apk add --no-cache ca-certificates RUN update-ca-certificates # Copy and download dependency using go mod COPY go.mod . COPY go.sum . RUN go mod download # Copy the code into the container COPY . . # Build the application RUN go build -buildvcs=false -ldflags "-X main.commit=${COMMIT} -X main.version=${VERSION} -X main.date=${DATE}" -o pg_timetable . FROM alpine # Install psql client RUN apk --no-cache add postgresql-client curl # Copy the binary and certificates into the container COPY --from=builder /build/pg_timetable / COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ # Command to run the executable ENTRYPOINT ["/pg_timetable"] # Expose REST API if needed ENV PGTT_RESTPORT 8008 EXPOSE 8008 <file_sep>/internal/scheduler/shell.go package scheduler import ( "context" "encoding/json" "errors" "fmt" "os/exec" "strings" ) type commander interface { CombinedOutput(context.Context, string, ...string) ([]byte, error) } type realCommander struct{} // CombinedOutput executes program command and returns combined stdout and stderr func (c realCommander) CombinedOutput(ctx context.Context, command string, args ...string) ([]byte, error) { cmd := exec.CommandContext(ctx, command, args...) cmd.Stdin = nil return cmd.CombinedOutput() } // Cmd executes a command var Cmd commander = realCommander{} // ExecuteProgramCommand executes program command and returns status code, output and error if any func (sch *Scheduler) ExecuteProgramCommand(ctx context.Context, command string, paramValues []string) (code int, stdout string, stderr error) { command = strings.TrimSpace(command) if command == "" { return -1, "", errors.New("Program command cannot be empty") } if len(paramValues) == 0 { //mimic empty param paramValues = []string{""} } for _, val := range paramValues { params := []string{} if val > "" { if err := json.Unmarshal([]byte(val), &params); err != nil { return -1, "", err } } out, err := Cmd.CombinedOutput(ctx, command, params...) // #nosec cmdLine := fmt.Sprintf("%s %v: ", command, params) stdout = strings.TrimSpace(string(out)) l := sch.l.WithField("command", cmdLine). WithField("output", string(out)) if err != nil { //check if we're dealing with an ExitError - i.e. return code other than 0 if exitError, ok := err.(*exec.ExitError); ok { exitCode := exitError.ProcessState.ExitCode() l.WithField("retcode", exitCode).Debug("Program run", cmdLine, exitCode) return exitCode, stdout, exitError } return -1, stdout, err } l.WithField("retcode", 0).Debug("Program run") } return 0, stdout, nil } <file_sep>/internal/config/config_test.go package config import ( "os" "testing" "github.com/stretchr/testify/assert" ) func TestConfig(t *testing.T) { os.Args = []string{0: "config_test", "--config=../../config.example.yaml"} _, err := NewConfig(nil) assert.NoError(t, err) os.Args = []string{0: "config_test", "--unknown"} _, err = NewConfig(nil) assert.Error(t, err) os.Args = []string{0: "config_test"} // clientname arg is missing _, err = NewConfig(nil) assert.Error(t, err) os.Args = []string{0: "config_test", "--config=foo.boo.bar.baz.yaml"} _, err = NewConfig(nil) assert.Error(t, err) os.Args = []string{0: "config_test"} // clientname arg is missing, but set PGTT_CLIENTNAME assert.NoError(t, os.Setenv("PGTT_CLIENTNAME", "worker001")) _, err = NewConfig(nil) assert.NoError(t, err) } <file_sep>/internal/api/chainapi.go package api import ( "net/http" "strconv" ) func (Server *RestAPIServer) chainHandler(w http.ResponseWriter, r *http.Request) { Server.l.Debug("Received chain REST API request") chainID, err := strconv.Atoi(r.URL.Query().Get("id")) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } switch r.URL.Path { case "/startchain": err = Server.APIHandler.StartChain(r.Context(), chainID) case "/stopchain": err = Server.APIHandler.StopChain(r.Context(), chainID) } if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } w.WriteHeader(http.StatusOK) } <file_sep>/docs/installation.rst Installation ================================================ **pg_timetable** is compatible with the latest supported `PostgreSQL versions <https://www.postgresql.org/support/versioning/>`_: 11, 12, 13, 14 (stable); 15 (dev). .. note:: .. raw:: html <details> <summary>If you want to use <strong>pg_timetable</strong> with older versions (9.5, 9.6 and 10)...</summary> please, execute this SQL command before running pg_timetable: .. code-block:: SQL CREATE OR REPLACE FUNCTION starts_with(text, text) RETURNS bool AS $$ SELECT CASE WHEN length($2) > length($1) THEN FALSE ELSE left($1, length($2)) = $2 END $$ LANGUAGE SQL IMMUTABLE STRICT PARALLEL SAFE COST 5; .. raw:: html </details> Official release packages ------------------------------------------------ You may find binary package for your platform on the official `Releases <https://github.com/cybertec-postgresql/pg_timetable/releases>`_ page. Right now **Windows**, **Linux** and **macOS** packages are available. Docker ------------------------------------------------ The official docker image can be found here: https://hub.docker.com/r/cybertecpostgresql/pg_timetable .. note:: The ``latest`` tag is up to date with the `master` branch thanks to `this github action <https://github.com/cybertec-postgresql/pg_timetable/blob/master/.github/workflows/docker.yml>`_. In production you probably want to use the latest `stable tag <https://hub.docker.com/r/cybertecpostgresql/pg_timetable/tags>`_. Run **pg_timetable** in Docker: .. code-block:: console docker run --rm \ cybertecpostgresql/pg_timetable:latest \ -h 10.0.0.3 -p 54321 -c worker001 Run **pg_timetable** in Docker with Environment variables: .. code-block:: console docker run --rm \ -e PGTT_PGHOST=10.0.0.3 \ -e PGTT_PGPORT=54321 \ cybertecpostgresql/pg_timetable:latest \ -c worker001 Build from sources ------------------------------------------------ 1. Download and install `Go <https://golang.org/doc/install>`_ on your system. #. Clone **pg_timetable** repo:: $ git clone https://github.com/cybertec-postgresql/pg_timetable.git $ cd pg_timetable #. Run **pg_timetable**:: $ go run main.go --dbname=dbname --clientname=worker001 --user=scheduler --password=<PASSWORD> #. Alternatively, build a binary and run it:: $ go build $ ./pg_timetable --dbname=dbname --clientname=worker001 --user=scheduler --password=<PASSWORD> #. (Optional) Run tests in all sub-folders of the project:: $ psql --command="CREATE USER scheduler PASSWORD '<PASSWORD>'" $ createdb --owner=scheduler timetable $ go test -failfast -timeout=300s -count=1 -p 1 ./... <file_sep>/internal/pgengine/transaction.go package pgengine import ( "context" "encoding/json" "errors" "fmt" "strconv" "strings" "github.com/cybertec-postgresql/pg_timetable/internal/log" pgx "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgtype" ) // StartTransaction returns transaction object, transaction id and error func (pge *PgEngine) StartTransaction(ctx context.Context) (tx pgx.Tx, txid int64, err error) { if tx, err = pge.ConfigDb.Begin(ctx); err != nil { return } err = tx.QueryRow(ctx, "SELECT txid_current()").Scan(&txid) return } // CommitTransaction commits transaction and log error in the case of error func (pge *PgEngine) CommitTransaction(ctx context.Context, tx pgx.Tx) { err := tx.Commit(ctx) if err != nil { log.GetLogger(ctx).WithError(err).Error("Application cannot commit after job finished") } } // RollbackTransaction rollbacks transaction and log error in the case of error func (pge *PgEngine) RollbackTransaction(ctx context.Context, tx pgx.Tx) { err := tx.Rollback(ctx) if err != nil { log.GetLogger(ctx).WithError(err).Error("Application cannot rollback after job failed") } } // MustSavepoint creates SAVDEPOINT in transaction and log error in the case of error func (pge *PgEngine) MustSavepoint(ctx context.Context, tx pgx.Tx, taskID int) { if _, err := tx.Exec(ctx, fmt.Sprintf("SAVEPOINT task_%d", taskID)); err != nil { log.GetLogger(ctx).WithError(err).Error("Savepoint failed") } } // MustRollbackToSavepoint rollbacks transaction to SAVEPOINT and log error in the case of error func (pge *PgEngine) MustRollbackToSavepoint(ctx context.Context, tx pgx.Tx, taskID int) { if _, err := tx.Exec(ctx, fmt.Sprintf("ROLLBACK TO SAVEPOINT task_%d", taskID)); err != nil { log.GetLogger(ctx).WithError(err).Error("Rollback to savepoint failed") } } // ExecuteSQLTask executes SQL task func (pge *PgEngine) ExecuteSQLTask(ctx context.Context, tx pgx.Tx, task *ChainTask, paramValues []string) (out string, err error) { switch { case task.IsRemote(): return pge.ExecRemoteSQLTask(ctx, task, paramValues) case task.Autonomous: return pge.ExecAutonomousSQLTask(ctx, task, paramValues) default: return pge.ExecLocalSQLTask(ctx, tx, task, paramValues) } } // ExecLocalSQLTask executes local task in the chain transaction func (pge *PgEngine) ExecLocalSQLTask(ctx context.Context, tx pgx.Tx, task *ChainTask, paramValues []string) (out string, err error) { if err := pge.SetRole(ctx, tx, task.RunAs); err != nil { return "", err } if task.IgnoreError { pge.MustSavepoint(ctx, tx, task.TaskID) } pge.SetCurrentTaskContext(ctx, tx, task.ChainID, task.TaskID) out, err = pge.ExecuteSQLCommand(ctx, tx, task.Script, paramValues) if err != nil && task.IgnoreError { pge.MustRollbackToSavepoint(ctx, tx, task.TaskID) } if task.RunAs.Valid { pge.ResetRole(ctx, tx) } return } // ExecStandaloneTask executes task against the provided connection interface, it can be remote connection or acquired connection from the pool func (pge *PgEngine) ExecStandaloneTask(ctx context.Context, connf func() (PgxConnIface, error), task *ChainTask, paramValues []string) (string, error) { conn, err := connf() if err != nil { return "", err } defer pge.FinalizeDBConnection(ctx, conn) if err := pge.SetRole(ctx, conn, task.RunAs); err != nil { return "", err } pge.SetCurrentTaskContext(ctx, conn, task.ChainID, task.TaskID) return pge.ExecuteSQLCommand(ctx, conn, task.Script, paramValues) } // ExecRemoteSQLTask executes task against remote connection func (pge *PgEngine) ExecRemoteSQLTask(ctx context.Context, task *ChainTask, paramValues []string) (string, error) { return pge.ExecStandaloneTask(ctx, func() (PgxConnIface, error) { return pge.GetRemoteDBConnection(ctx, task.ConnectString.String) }, task, paramValues) } // ExecAutonomousSQLTask executes autonomous task in an acquired connection from pool func (pge *PgEngine) ExecAutonomousSQLTask(ctx context.Context, task *ChainTask, paramValues []string) (string, error) { return pge.ExecStandaloneTask(ctx, func() (PgxConnIface, error) { return pge.GetLocalDBConnection(ctx) }, task, paramValues) } // ExecuteSQLCommand executes chain command with parameters inside transaction func (pge *PgEngine) ExecuteSQLCommand(ctx context.Context, executor executor, command string, paramValues []string) (out string, err error) { var ct pgconn.CommandTag var params []interface{} if strings.TrimSpace(command) == "" { return "", errors.New("SQL command cannot be empty") } if len(paramValues) == 0 { //mimic empty param ct, err = executor.Exec(ctx, command) out = ct.String() return } for _, val := range paramValues { if val > "" { if err = json.Unmarshal([]byte(val), &params); err != nil { return } ct, err = executor.Exec(ctx, command, params...) out = out + ct.String() + "\n" } } return } // GetLocalDBConnection acquires a connection from a local pool and returns it func (pge *PgEngine) GetLocalDBConnection(ctx context.Context) (conn PgxConnIface, err error) { c, err := pge.ConfigDb.Acquire(ctx) if err != nil { return nil, err } return c.Hijack(), nil } // GetRemoteDBConnection create a remote db connection object func (pge *PgEngine) GetRemoteDBConnection(ctx context.Context, connectionString string) (conn PgxConnIface, err error) { conn, err = pgx.Connect(ctx, connectionString) if err != nil { return nil, err } log.GetLogger(ctx).Info("Remote connection established...") return } // FinalizeDBConnection closes session func (pge *PgEngine) FinalizeDBConnection(ctx context.Context, remoteDb PgxConnIface) { l := log.GetLogger(ctx) l.Info("Closing remote session") if err := remoteDb.Close(ctx); err != nil { l.WithError(err).Error("Cannot close database connection:", err) } remoteDb = nil } // SetRole - set the current user identifier of the current session func (pge *PgEngine) SetRole(ctx context.Context, executor executor, runUID pgtype.Text) error { if !runUID.Valid || strings.TrimSpace(runUID.String) == "" { return nil } log.GetLogger(ctx).Info("Setting Role to ", runUID.String) _, err := executor.Exec(ctx, fmt.Sprintf("SET ROLE %v", runUID.String)) return err } // ResetRole - RESET forms reset the current user identifier to be the current session user identifier func (pge *PgEngine) ResetRole(ctx context.Context, executor executor) { l := log.GetLogger(ctx) l.Info("Resetting Role") _, err := executor.Exec(ctx, `RESET ROLE`) if err != nil { l.WithError(err).Error("Failed to set a role", err) } } // SetCurrentTaskContext - set the working transaction "pg_timetable.current_task_id" run-time parameter func (pge *PgEngine) SetCurrentTaskContext(ctx context.Context, executor executor, chainID int, taskID int) { _, err := executor.Exec(ctx, `SELECT set_config('pg_timetable.current_task_id', $1, false), set_config('pg_timetable.current_chain_id', $2, false), set_config('pg_timetable.current_client_name', $3, false)`, strconv.Itoa(taskID), strconv.Itoa(chainID), pge.ClientName) if err != nil { log.GetLogger(ctx).WithError(err).Error("Failed to set current task context", err) } } <file_sep>/internal/config/config.go package config import ( "bytes" "errors" "fmt" "io" flags "github.com/jessevdk/go-flags" "github.com/spf13/viper" ) type cmdArg struct { fullName string *flags.Option } func (a cmdArg) HasChanged() bool { return a.IsSet() && !a.IsSetDefault() } func (a cmdArg) Name() string { return a.fullName } func (a cmdArg) ValueString() string { return fmt.Sprintf("%v", a.Value()) } func (a cmdArg) ValueType() string { return a.Field().Type.Name() } type cmdArgSet struct { *flags.Parser } func eachGroup(g *flags.Group, f func(*flags.Group)) { f(g) for _, gg := range g.Groups() { eachGroup(gg, f) } } func eachOption(g *flags.Group, f func(*flags.Group, *flags.Option)) { eachGroup(g, func(g *flags.Group) { for _, option := range g.Options() { f(g, option) } }) } // VisitAll will execute fn() for all options found in command line. // Since we have only two level of nesting it's enough to use simplified group-prefixed name. func (cmdSet cmdArgSet) VisitAll(fn func(viper.FlagValue)) { root := cmdSet.Parser.Group.Find("Application Options") eachOption(root, func(g *flags.Group, o *flags.Option) { name := o.LongName if g != root { name = g.ShortDescription + cmdSet.Parser.NamespaceDelimiter + name } fn(cmdArg{name, o}) }) } func (cmdSet cmdArgSet) setDefaults(v *viper.Viper) { eachOption(cmdSet.Parser.Group, func(g *flags.Group, o *flags.Option) { if o.Default != nil && o.IsSetDefault() { name := o.LongName if g != cmdSet.Parser.Group { name = g.ShortDescription + cmdSet.Parser.NamespaceDelimiter + name } v.SetDefault(name, o.Value()) } }) } // NewConfig returns a new instance of CmdOptions func NewConfig(writer io.Writer) (*CmdOptions, error) { v := viper.New() p, err := Parse(writer) if err != nil { return nil, err } flagSet := cmdArgSet{p} if err = v.BindFlagValues(flagSet); err != nil { return nil, fmt.Errorf("cannot bind command-line flag values with viper: %w", err) } flagSet.setDefaults(v) if v.IsSet("config") { v.SetConfigFile(v.GetString("config")) err := v.ReadInConfig() // Find and read the config file if err != nil { // Handle errors reading the config file return nil, fmt.Errorf("Fatal error reading config file: %w", err) } } conf := &CmdOptions{} if err = v.Unmarshal(conf); err != nil { return nil, fmt.Errorf("Fatal error unmarshalling config file: %w", err) } if conf.ClientName == "" { buf := bytes.NewBufferString("The required flag `-c, --clientname` was not specified\n") p.WriteHelp(buf) return conf, errors.New(buf.String()) } return conf, nil } <file_sep>/docs/README.rst Introduction ================================================ **pg_timetable** is an advanced job scheduler for PostgreSQL, offering many advantages over traditional schedulers such as **cron** and others. It is completely database driven and provides a couple of advanced concepts. Main features -------------- - Tasks can be arranged in chains - A chain can consist of built-int commands, SQL and executables - Parameters can be passed to chains - Missed tasks (possibly due to downtime) can be retried automatically - Support for configurable repetitions - Built-in tasks such as sending emails, etc. - Fully database driven configuration - Full support for database driven logging - Cron-style scheduling at the PostgreSQL server time zone - Optional concurrency protection - Task and chain can have execution timeout settings Quick Start ------------ 1. Download pg_timetable executable 2. Make sure your PostgreSQL server is up and running and has a role with ``CREATE`` privilege for a target database, e.g. .. code-block:: SQL my_database=> CREATE ROLE scheduler PASSWORD '<PASSWORD>'; my_database=> GRANT CREATE ON DATABASE my_database TO scheduler; 3. Create a new job, e.g. run ``VACUUM`` each night at 00:30 Postgres server time zone .. code-block:: SQL my_database=> SELECT timetable.add_job('frequent-vacuum', '30 * * * *', 'VACUUM'); add_job --------- 3 (1 row) 4. Run the **pg_timetable** .. code-block:: # pg_timetable postgresql://scheduler:somestrong@localhost/my_database --clientname=vacuumer 5. PROFIT! Command line options ------------------------ .. code-block:: # ./pg_timetable Application Options: -c, --clientname= Unique name for application instance [$PGTT_CLIENTNAME] --config= YAML configuration file --no-program-tasks Disable executing of PROGRAM tasks [$PGTT_NOPROGRAMTASKS] -v, --version Output detailed version information [$PGTT_VERSION] Connection: -h, --host= PostgreSQL host (default: localhost) [$PGTT_PGHOST] -p, --port= PostgreSQL port (default: 5432) [$PGTT_PGPORT] -d, --dbname= PostgreSQL database name (default: timetable) [$PGTT_PGDATABASE] -u, --user= PostgreSQL user (default: scheduler) [$PGTT_PGUSER] --password= PostgreSQL user password [$PGTT_PGPASSWORD] --sslmode=[disable|require] Connection SSL mode (default: disable) [$PGTT_PGSSLMODE] --pgurl= PostgreSQL connection URL [$PGTT_URL] --timeout= PostgreSQL connection timeout (default: 90) [$PGTT_TIMEOUT] Logging: --log-level=[debug|info|error] Verbosity level for stdout and log file (default: info) --log-database-level=[debug|info|error|none] Verbosity level for database storing (default: info) --log-file= File name to store logs --log-file-format=[json|text] Format of file logs (default: json) --log-file-rotate Rotate log files --log-file-size= Maximum size in MB of the log file before it gets rotated (default: 100) --log-file-age= Number of days to retain old log files, 0 means forever (default: 0) --log-file-number= Maximum number of old log files to retain, 0 to retain all (default: 0) Start: -f, --file= SQL script file to execute during startup --init Initialize database schema to the latest version and exit. Can be used with --upgrade --upgrade Upgrade database to the latest version --debug Run in debug mode. Only asynchronous chains will be executed Resource: --cron-workers= Number of parallel workers for scheduled chains (default: 16) --interval-workers= Number of parallel workers for interval chains (default: 16) --chain-timeout= Abort any chain that takes more than the specified number of milliseconds --task-timeout= Abort any task within a chain that takes more than the specified number of milliseconds REST: --rest-port= REST API port (default: 0) [$PGTT_RESTPORT] Contributing ------------ If you want to contribute to **pg_timetable** and help make it better, feel free to open an `issue <https://github.com/cybertec-postgresql/pg_timetable/issues>`_ or even consider submitting a `pull request <https://github.com/cybertec-postgresql/pg_timetable/pulls>`_. You also can give a `star <https://github.com/cybertec-postgresql/pg_timetable/stargazers>`_ to **pg_timetable** project, and to tell the world about it. Support ------------ For professional support, please contact `Cybertec <https://www.cybertec-postgresql.com/>`_. Authors --------- Implementation: `<NAME> <https://github.com/pashagolub>`_ Initial idea and draft design: `<NAME> <https://github.com/postgresql007>`_ <file_sep>/samples/ManyTasks.sql WITH cte_chain (v_chain_id) AS ( -- let's create a new chain and add tasks to it later INSERT INTO timetable.chain (chain_name, run_at, max_instances, live) VALUES ('many tasks', '* * * * *', 1, true) RETURNING chain_id ), cte_tasks(v_task_id) AS ( -- now we'll add 500 tasks to the chain, some of them will fail INSERT INTO timetable.task (chain_id, task_order, kind, command, ignore_error) SELECT v_chain_id, g.s, 'SQL', 'SELECT 1.0 / round(random())::int4;', true FROM cte_chain, generate_series(1, 500) AS g(s) RETURNING task_id ), report_task(v_task_id) AS ( -- and the last reporting task will calculate the statistic INSERT INTO timetable.task (chain_id, task_order, kind, command) SELECT v_chain_id, 501, 'SQL', $CMD$DO $$ DECLARE s TEXT; BEGIN WITH report AS ( SELECT count(*) FILTER (WHERE returncode = 0) AS success, count(*) FILTER (WHERE returncode != 0) AS fail, count(*) AS total FROM timetable.execution_log WHERE chain_id = current_setting('pg_timetable.current_chain_id')::bigint AND txid = txid_current() ) SELECT 'Tasks executed:' || total || '; succeeded: ' || success || '; failed: ' || fail || '; ratio: ' || 100.0*success/GREATEST(total,1) INTO s FROM report; RAISE NOTICE '%', s; END; $$ $CMD$ FROM cte_chain RETURNING task_id ) SELECT v_chain_id FROM cte_chain<file_sep>/internal/scheduler/scheduler_test.go package scheduler import ( "context" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/cybertec-postgresql/pg_timetable/internal/config" "github.com/cybertec-postgresql/pg_timetable/internal/log" "github.com/cybertec-postgresql/pg_timetable/internal/pgengine" ) var pge *pgengine.PgEngine // SetupTestCase used to connect and to initialize test PostgreSQL database func SetupTestCase(t *testing.T) func(t *testing.T) { cmdOpts := config.NewCmdOptions("-c", "pgengine_unit_test", "--password=<PASSWORD>") t.Log("Setup test case") timeout := time.After(6 * time.Second) done := make(chan bool) go func() { pge, _ = pgengine.New(context.Background(), *cmdOpts, log.Init(config.LoggingOpts{LogLevel: "error"})) done <- true }() select { case <-timeout: t.Fatal("Cannot connect and initialize test database in time") case <-done: } return func(t *testing.T) { _, _ = pge.ConfigDb.Exec(context.Background(), "DROP SCHEMA IF EXISTS timetable CASCADE") t.Log("Test schema dropped") } } func TestRun(t *testing.T) { teardownTestCase := SetupTestCase(t) defer teardownTestCase(t) require.NotNil(t, pge.ConfigDb, "ConfigDB should be initialized") err := pge.ExecuteCustomScripts(context.Background(), "../../samples/Exclusive.sql") assert.NoError(t, err, "Creating interval tasks failed") err = pge.ExecuteCustomScripts(context.Background(), "../../samples/Autonomous.sql") assert.NoError(t, err, "Creating autonomous tasks failed") err = pge.ExecuteCustomScripts(context.Background(), "../../samples/RemoteDB.sql") assert.NoError(t, err, "Creating remote tasks failed") err = pge.ExecuteCustomScripts(context.Background(), "../../samples/Basic.sql") assert.NoError(t, err, "Creating sql tasks failed") err = pge.ExecuteCustomScripts(context.Background(), "../../samples/NoOp.sql") assert.NoError(t, err, "Creating built-in tasks failed") err = pge.ExecuteCustomScripts(context.Background(), "../../samples/Shell.sql") assert.NoError(t, err, "Creating program tasks failed") err = pge.ExecuteCustomScripts(context.Background(), "../../samples/ManyTasks.sql") assert.NoError(t, err, "Creating many tasks failed") sch := New(pge, log.Init(config.LoggingOpts{LogLevel: "error"})) assert.NoError(t, sch.StartChain(context.Background(), 1)) assert.ErrorContains(t, sch.StopChain(context.Background(), -1), "No running chain found") go func() { time.Sleep(10 * time.Second) sch.Shutdown() }() assert.Equal(t, 1, max(0, 1)) assert.Equal(t, 1, max(1, 0)) assert.True(t, sch.IsReady()) assert.Equal(t, ShutdownStatus, sch.Run(context.Background())) } <file_sep>/internal/pgengine/bootstrap_test.go package pgengine_test import ( "context" "errors" "fmt" "reflect" "testing" "time" "github.com/cybertec-postgresql/pg_timetable/internal/pgengine" pgx "github.com/jackc/pgx/v5" "github.com/pashagolub/pgxmock/v2" "github.com/stretchr/testify/assert" ) func TestExecuteSchemaScripts(t *testing.T) { initmockdb(t) defer mockPool.Close() mockpge := pgengine.NewDB(mockPool, "pgengine_unit_test") t.Run("Check schema scripts if error returned for SELECT EXISTS", func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() mockPool.ExpectQuery("SELECT EXISTS").WillReturnError(errors.New("expected")) assert.Error(t, mockpge.ExecuteSchemaScripts(ctx)) }) t.Run("Check schema scripts if error returned", func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() mockPool.ExpectQuery("SELECT EXISTS").WillReturnRows(pgxmock.NewRows([]string{"exists"}).AddRow(false)) mockPool.ExpectExec("CREATE SCHEMA timetable").WillReturnError(errors.New("expected")) mockPool.ExpectExec("DROP SCHEMA IF EXISTS timetable CASCADE").WillReturnError(errors.New("expected")) assert.Error(t, mockpge.ExecuteSchemaScripts(ctx)) }) t.Run("Check schema scripts if everything fine", func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() mockPool.ExpectQuery("SELECT EXISTS").WillReturnRows(pgxmock.NewRows([]string{"exists"}).AddRow(false)) for i := 0; i < 5; i++ { mockPool.ExpectExec(".*").WillReturnResult(pgxmock.NewResult("EXECUTE", 1)) } assert.NoError(t, mockpge.ExecuteSchemaScripts(ctx)) }) } func TestExecuteCustomScripts(t *testing.T) { initmockdb(t) defer mockPool.Close() mockpge := pgengine.NewDB(mockPool, "pgengine_unit_test") t.Run("Check ExecuteCustomScripts for non-existent file", func(t *testing.T) { assert.Error(t, mockpge.ExecuteCustomScripts(context.Background(), "foo.bar")) }) t.Run("Check ExecuteCustomScripts if error returned", func(t *testing.T) { mockPool.ExpectExec("SELECT timetable.add_job").WillReturnError(errors.New("expected")) assert.Error(t, mockpge.ExecuteCustomScripts(context.Background(), "../../samples/Basic.sql")) }) t.Run("Check ExecuteCustomScripts if everything fine", func(t *testing.T) { mockPool.ExpectExec("SELECT timetable.add_job").WillReturnResult(pgxmock.NewResult("EXECUTE", 1)) mockPool.ExpectExec("INSERT INTO timetable\\.log").WillReturnResult(pgxmock.NewResult("EXECUTE", 1)) assert.NoError(t, mockpge.ExecuteCustomScripts(context.Background(), "../../samples/Basic.sql")) }) } func TestFinalizeConnection(t *testing.T) { initmockdb(t) mockpge := pgengine.NewDB(mockPool, "pgengine_unit_test") mockPool.ExpectExec(`DELETE FROM timetable\.active_session`). WithArgs(mockpge.ClientName). WillReturnResult(pgxmock.NewResult("EXECUTE", 0)) mockPool.ExpectClose() mockpge.Finalize() assert.NoError(t, mockPool.ExpectationsWereMet()) } type mockpgrow struct { results []interface{} } func (r *mockpgrow) Scan(dest ...interface{}) error { if len(r.results) > 0 { if err, ok := r.results[0].(error); ok { r.results = r.results[1:] return err } destv := reflect.ValueOf(dest[0]) typ := destv.Type() if typ.Kind() != reflect.Ptr { return fmt.Errorf("dest must be pointer; got %T", destv) } destv.Elem().Set(reflect.ValueOf(r.results[0])) r.results = r.results[1:] return nil } return errors.New("mockpgrow error") } type mockpgconn struct { r pgx.Row } func (m mockpgconn) QueryRow(context.Context, string, ...interface{}) pgx.Row { return m.r } func TestTryLockClientName(t *testing.T) { pge := pgengine.NewDB(nil, "pgengine_unit_test") defer func() { pge = nil }() t.Run("query error", func(t *testing.T) { r := &mockpgrow{} m := mockpgconn{r} assert.Error(t, pge.TryLockClientName(context.Background(), m)) }) t.Run("no schema yet", func(t *testing.T) { r := &mockpgrow{results: []interface{}{ 0, //procoid }} m := mockpgconn{r} assert.NoError(t, pge.TryLockClientName(context.Background(), m)) }) t.Run("locking error", func(t *testing.T) { r := &mockpgrow{results: []interface{}{ 1, //procoid errors.New("locking error"), //error }} m := mockpgconn{r} assert.Error(t, pge.TryLockClientName(context.Background(), m)) }) t.Run("locking successful", func(t *testing.T) { r := &mockpgrow{results: []interface{}{ 1, //procoid true, //locked }} m := mockpgconn{r} assert.NoError(t, pge.TryLockClientName(context.Background(), m)) }) } <file_sep>/samples/ManyChains.sql SELECT timetable.add_job( job_name => 'HelloWorld' || g.i, job_schedule => '* * * * *', job_kind => 'PROGRAM'::timetable.command_kind, job_command => 'bash', job_parameters => jsonb_build_array('-c', 'echo Hello World from ' || g.i), job_live => TRUE, job_ignore_errors => TRUE ) as chain_id FROM generate_series(1, 500) AS g(i);<file_sep>/internal/log/log.go package log import ( "context" "os" "github.com/cybertec-postgresql/pg_timetable/internal/config" "github.com/jackc/pgx/v5/tracelog" "github.com/rifflock/lfshook" "github.com/sirupsen/logrus" "gopkg.in/natefinch/lumberjack.v2" ) type ( // LoggerIface is the interface used by all components LoggerIface logrus.FieldLogger //LoggerHookerIface adds AddHook method to LoggerIface for database logging hook LoggerHookerIface interface { LoggerIface AddHook(hook logrus.Hook) } loggerKey struct{} ) func getLogFileWriter(opts config.LoggingOpts) any { if opts.LogFileRotate { return &lumberjack.Logger{ Filename: opts.LogFile, MaxSize: opts.LogFileSize, MaxBackups: opts.LogFileNumber, MaxAge: opts.LogFileAge, } } return opts.LogFile } func getLogFileFormatter(opts config.LoggingOpts) logrus.Formatter { if opts.LogFileFormat == "text" { return &logrus.TextFormatter{} } return &logrus.JSONFormatter{} } // Init creates logging facilities for the application func Init(opts config.LoggingOpts) LoggerHookerIface { var err error l := logrus.New() l.Out = os.Stdout if opts.LogFile > "" { l.AddHook(lfshook.NewHook(getLogFileWriter(opts), getLogFileFormatter(opts))) } l.Level, err = logrus.ParseLevel(opts.LogLevel) if err != nil { l.Level = logrus.InfoLevel } l.SetFormatter(&Formatter{ HideKeys: false, FieldsOrder: []string{"chain", "task", "sql", "params"}, TimestampFormat: "2006-01-02 15:04:05.000", ShowFullLevel: true, }) l.SetReportCaller(l.Level > logrus.InfoLevel) return l } // PgxLogger is the struct used to log using pgx postgres driver type PgxLogger struct { l LoggerIface } // NewPgxLogger returns a new instance of PgxLogger func NewPgxLogger(l LoggerIface) *PgxLogger { return &PgxLogger{l} } // Log transforms logging calls from pgx to logrus func (pgxlogger *PgxLogger) Log(ctx context.Context, level tracelog.LogLevel, msg string, data map[string]any) { logger := GetLogger(ctx) if logger == FallbackLogger { //switch from standard to specified logger = pgxlogger.l } if data != nil { logger = logger.WithFields(data) } switch level { case tracelog.LogLevelTrace: logger.WithField("PGX_LOG_LEVEL", level).Debug(msg) case tracelog.LogLevelDebug, tracelog.LogLevelInfo: //pgx is way too chatty on INFO level logger.Debug(msg) case tracelog.LogLevelWarn: logger.Warn(msg) case tracelog.LogLevelError: logger.Error(msg) default: logger.WithField("INVALID_PGX_LOG_LEVEL", level).Error(msg) } } // WithLogger returns a new context with the provided logger. Use in // combination with logger.WithField(s) for great effect func WithLogger(ctx context.Context, logger LoggerIface) context.Context { return context.WithValue(ctx, loggerKey{}, logger) } // FallbackLogger is an alias for the standard logger var FallbackLogger = logrus.StandardLogger() // GetLogger retrieves the current logger from the context. If no logger is // available, the default logger is returned func GetLogger(ctx context.Context) LoggerIface { logger := ctx.Value(loggerKey{}) if logger == nil { return FallbackLogger } return logger.(LoggerIface) } <file_sep>/samples/Log.sql SELECT timetable.add_job( job_name => 'Builtin-in Log', job_schedule => NULL, -- same as '* * * * *' job_command => 'Log', job_kind => 'BUILTIN'::timetable.command_kind, job_parameters => '{"Description":"Log Execution"}'::jsonb ) as chain_id;<file_sep>/internal/pgengine/sql/init.sql CREATE SCHEMA timetable; -- define migrations you need to apply -- every change to the database schema should populate this table. -- Version value should contain issue number zero padded followed by -- short description of the issue\feature\bug implemented\resolved CREATE TABLE timetable.migration( id INT8 NOT NULL, version TEXT NOT NULL, PRIMARY KEY (id) ); INSERT INTO timetable.migration (id, version) VALUES (0, '00259 Restart migrations for v4'), (1, '00305 Fix timetable.is_cron_in_time'), (2, '00323 Append timetable.delete_job function'), (3, '00329 Migration required for some new added functions'), (4, '00334 Refactor timetable.task as plain schema without tree-like dependencies'), (5, '00381 Rewrite active chain handling'), (6, '00394 Add started_at column to active_session and active_chain tables'), (7, '00417 Rename LOG database log level to INFO'), (8, '00436 Add txid column to timetable.execution_log'), (9, '00534 Use cron_split_to_arrays() in cron domain check'), (10, '00560 Alter txid column to bigint'), (11, '00573 Add ability to start a chain with delay'), (12, '00575 Add on_error handling');<file_sep>/internal/pgengine/sql/migrations/00436.sql ALTER TABLE timetable.execution_log ADD COLUMN txid INTEGER NOT NULL DEFAULT 0;<file_sep>/docs/basic_jobs.rst Getting started ================================================================ A variety of examples can be found in the :doc:`samples`. If you want to migrate from a different scheduler, you can use scripts from :doc:`migration` chapter. Add simple job ~~~~~~~~~~~~~~ In a real world usually it's enough to use simple jobs. Under this term we understand: * job is a chain with only one **task** (step) in it; * it doesn't use complicated logic, but rather simple **command**; * it doesn't require complex transaction handling, since one task is implicitely executed as a single transaction. For such a group of chains we've introduced a special function ``timetable.add_job()``. .. function:: timetable.add_job(job_name, job_schedule, job_command, ...) RETURNS BIGINT Creates a simple one-task chain :param job_name: The unique name of the **chain** and **command**. :type job_name: text :param job_schedule: Time schedule in сron syntax at Postgres server time zone :type job_schedule: timetable.cron :param job_command: The SQL which will be executed. :type job_command: text :param job_parameters: Arguments for the chain **command**. Default: ``NULL``. :type job_parameters: jsonb :param job_kind: Kind of the command: *SQL*, *PROGRAM* or *BUILTIN*. Default: ``SQL``. :type job_kind: timetable.command_kind :param job_client_name: Specifies which client should execute the chain. Set this to `NULL` to allow any client. Default: ``NULL``. :type job_client_name: text :param job_max_instances: The amount of instances that this chain may have running at the same time. Default: ``NULL``. :type job_max_instances: integer :param job_live: Control if the chain may be executed once it reaches its schedule. Default: ``TRUE``. :type job_live: boolean :param job_self_destruct: Self destruct the chain after execution. Default: ``FALSE``. :type job_self_destruct: boolean :param job_ignore_errors: Ignore error during execution. Default: ``TRUE``. :type job_ignore_errors: boolean :param job_exclusive: Execute the chain in the exclusive mode. Default: ``FALSE``. :type job_exclusive: boolean :returns: the ID of the created chain :rtype: integer Examples ~~~~~~~~~ #. Run ``public.my_func()`` at 00:05 every day in August Postgres server time zone: .. code-block:: SQL SELECT timetable.add_job('execute-func', '5 0 * 8 *', 'SELECT public.my_func()'); #. Run `VACUUM` at minute 23 past every 2nd hour from 0 through 20 every day Postgres server time zone: .. code-block:: SQL SELECT timetable.add_job('run-vacuum', '23 0-20/2 * * *', 'VACUUM'); #. Refresh materialized view every 2 hours: .. code-block:: SQL SELECT timetable.add_job('refresh-matview', '@every 2 hours', 'REFRESH MATERIALIZED VIEW public.mat_view'); #. Clear log table after **pg_timetable** restart: .. code-block:: SQL SELECT timetable.add_job('clear-log', '@reboot', 'TRUNCATE timetable.log'); #. Reindex at midnight Postgres server time zone on Sundays with `reindexdb <https://www.postgresql.org/docs/current/app-reindexdb.html>`_ utility: - using default database under default user (no command line arguments) .. code-block:: SQL SELECT timetable.add_job('reindex', '0 0 * * 7', 'reindexdb', job_kind := 'PROGRAM'); - specifying target database and tables, and be verbose .. code-block:: SQL SELECT timetable.add_job('reindex', '0 0 * * 7', 'reindexdb', '["--table=foo", "--dbname=postgres", "--verbose"]'::jsonb, 'PROGRAM'); - passing password using environment variable through ``bash`` shell .. code-block:: SQL SELECT timetable.add_job('reindex', '0 0 * * 7', 'bash', '["-c", "PGPASSWORD=<PASSWORD>54p4m reindexdb -U postgres -h 192.168.0.221 -v"]'::jsonb, 'PROGRAM'); <file_sep>/docs/database_schema.rst Database Schema ======================================== **pg_timetable** is a database driven application. During the first start the necessary schema is created if absent. Main tables and objects ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. literalinclude:: ../internal/pgengine/sql/ddl.sql :linenos: :language: SQL Jobs related functions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. literalinclude:: ../internal/pgengine/sql/job_functions.sql :linenos: :language: SQL Сron related functions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. literalinclude:: ../internal/pgengine/sql/cron_functions.sql :linenos: :language: SQL ER-Diagram ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. figure:: timetable_schema.png :align: center :alt: Database Schema ER-Diagram<file_sep>/internal/config/cmdparser_test.go package config import ( "os" "testing" "github.com/stretchr/testify/assert" ) func TestParseFail(t *testing.T) { tests := [][]string{ {0: "go-test", "--unknown-oprion"}, {0: "go-test", "-c", "client01", "-f", "foo"}, } for _, d := range tests { os.Args = d _, err := Parse(nil) assert.Error(t, err) } } func TestParseSuccess(t *testing.T) { tests := [][]string{ {0: "go-test", "non-optional-value"}, } for _, d := range tests { os.Args = d _, err := Parse(nil) assert.NoError(t, err) } } func TestLogLevel(t *testing.T) { c := &CmdOptions{Logging: LoggingOpts{LogLevel: "debug"}} assert.True(t, c.Verbose()) c = &CmdOptions{Logging: LoggingOpts{LogLevel: "info"}} assert.False(t, c.Verbose()) } func TestVersionOnly(t *testing.T) { c := &CmdOptions{Version: true} os.Args = []string{0: "go-test", "-v"} assert.True(t, c.VersionOnly()) c = &CmdOptions{Version: false} assert.False(t, c.VersionOnly()) } func TestNewCmdOptions(t *testing.T) { c := NewCmdOptions("-c", "config_unit_test", "--password=<PASSWORD>") assert.NotNil(t, c) } <file_sep>/internal/log/formatter.go package log import ( "bytes" "fmt" "runtime" "sort" "strings" "time" "github.com/sirupsen/logrus" ) // Formatter - logrus formatter, implements logrus.Formatter // Forked from "github.com/antonfisher/nested-logrus-formatter" type Formatter struct { // FieldsOrder - default: fields sorted alphabetically FieldsOrder []string // TimestampFormat - default: time.StampMilli = "Jan _2 15:04:05.000" TimestampFormat string // HideKeys - show [fieldValue] instead of [fieldKey:fieldValue] HideKeys bool // NoColors - disable colors NoColors bool // NoFieldsColors - apply colors only to the level, default is level + fields NoFieldsColors bool // NoFieldsSpace - no space between fields NoFieldsSpace bool // ShowFullLevel - show a full level [WARNING] instead of [WARN] ShowFullLevel bool // NoUppercaseLevel - no upper case for level value NoUppercaseLevel bool // TrimMessages - trim whitespaces on messages TrimMessages bool // CallerFirst - print caller info first CallerFirst bool // CustomCallerFormatter - set custom formatter for caller info CustomCallerFormatter func(*runtime.Frame) string } // Format an log entry func (f *Formatter) Format(entry *logrus.Entry) ([]byte, error) { levelColor := getColorByLevel(entry.Level) timestampFormat := f.TimestampFormat if timestampFormat == "" { timestampFormat = time.StampMilli } // output buffer b := &bytes.Buffer{} // write time b.WriteString(entry.Time.Format(timestampFormat)) // write level var level string if f.NoUppercaseLevel { level = entry.Level.String() } else { level = strings.ToUpper(entry.Level.String()) } if f.CallerFirst { f.writeCaller(b, entry) } if !f.NoColors { fmt.Fprintf(b, "\x1b[%dm", levelColor) } b.WriteString(" [") if f.ShowFullLevel { b.WriteString(level) } else { b.WriteString(level[:4]) } b.WriteString("]") if !f.NoFieldsSpace { b.WriteString(" ") } if !f.NoColors && f.NoFieldsColors { b.WriteString("\x1b[0m") } // write fields if f.FieldsOrder == nil { f.writeFields(b, entry) } else { f.writeOrderedFields(b, entry) } if f.NoFieldsSpace { b.WriteString(" ") } if !f.NoColors && !f.NoFieldsColors { b.WriteString("\x1b[0m") } // write message if f.TrimMessages { b.WriteString(strings.TrimSpace(entry.Message)) } else { b.WriteString(entry.Message) } if !f.CallerFirst { f.writeCaller(b, entry) } b.WriteByte('\n') return b.Bytes(), nil } func trimFilename(s string) string { const sub = "pg_timetable/internal/" idx := strings.Index(s, sub) if idx == -1 { return s } return s[idx+len(sub):] } func (f *Formatter) writeCaller(b *bytes.Buffer, entry *logrus.Entry) { if entry.HasCaller() { if f.CustomCallerFormatter != nil { fmt.Fprint(b, f.CustomCallerFormatter(entry.Caller)) } else { if strings.Contains(entry.Caller.Function, "PgxLogger") { return //skip internal logger function } fmt.Fprintf( b, " (%s:%d %s)", trimFilename(entry.Caller.File), entry.Caller.Line, trimFilename(entry.Caller.Function), ) } } } func (f *Formatter) writeFields(b *bytes.Buffer, entry *logrus.Entry) { if len(entry.Data) != 0 { fields := make([]string, 0, len(entry.Data)) for field := range entry.Data { fields = append(fields, field) } sort.Strings(fields) for _, field := range fields { f.writeField(b, entry, field) } } } func (f *Formatter) writeOrderedFields(b *bytes.Buffer, entry *logrus.Entry) { length := len(entry.Data) foundFieldsMap := map[string]bool{} for _, field := range f.FieldsOrder { if _, ok := entry.Data[field]; ok { foundFieldsMap[field] = true length-- f.writeField(b, entry, field) } } if length > 0 { notFoundFields := make([]string, 0, length) for field := range entry.Data { if !foundFieldsMap[field] { notFoundFields = append(notFoundFields, field) } } sort.Strings(notFoundFields) for _, field := range notFoundFields { f.writeField(b, entry, field) } } } func (f *Formatter) writeField(b *bytes.Buffer, entry *logrus.Entry, field string) { if f.HideKeys { fmt.Fprintf(b, "[%v]", entry.Data[field]) } else { fmt.Fprintf(b, "[%s:%v]", field, entry.Data[field]) } if !f.NoFieldsSpace { b.WriteString(" ") } } const ( colorRed = 31 colorBlue = 36 colorMagenta = 35 colorGreen = 32 // colorYellow = 33 // colorGray = 37 ) func getColorByLevel(level logrus.Level) int { switch level { case logrus.DebugLevel, logrus.TraceLevel: return colorBlue case logrus.WarnLevel: return colorMagenta case logrus.ErrorLevel, logrus.FatalLevel, logrus.PanicLevel: return colorRed default: return colorGreen } } <file_sep>/internal/pgengine/transaction_test.go package pgengine_test import ( "context" "encoding/json" "errors" "testing" "github.com/cybertec-postgresql/pg_timetable/internal/pgengine" "github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgtype" "github.com/pashagolub/pgxmock/v2" "github.com/stretchr/testify/assert" ) var ( mockPool pgxmock.PgxPoolIface mockConn pgxmock.PgxConnIface ) func initmockdb(t *testing.T) { var err error mockPool, err = pgxmock.NewPool(pgxmock.MonitorPingsOption(true)) assert.NoError(t, err) mockConn, err = pgxmock.NewConn() assert.NoError(t, err) } func TestIsIntervalChainListed(t *testing.T) { var a, b pgengine.IntervalChain a.ChainID = 42 b.ChainID = 24 assert.True(t, a.IsListed([]pgengine.IntervalChain{a, b})) assert.False(t, a.IsListed([]pgengine.IntervalChain{b})) } func TestStartTransaction(t *testing.T) { initmockdb(t) defer mockPool.Close() ctx := context.Background() pge := pgengine.NewDB(mockPool, "pgengine_unit_test") mockPool.ExpectBegin().WillReturnError(errors.New("foo")) tx, txid, err := pge.StartTransaction(ctx) assert.Nil(t, tx) assert.Zero(t, txid) assert.Error(t, err) mockPool.ExpectBegin() mockPool.ExpectQuery("SELECT txid_current()").WillReturnRows(pgxmock.NewRows([]string{"txid"}).AddRow(int64(42))) tx, txid, err = pge.StartTransaction(ctx) assert.NotNil(t, tx) assert.Equal(t, int64(42), txid) assert.NoError(t, err) } func TestMustTransaction(t *testing.T) { initmockdb(t) defer mockPool.Close() ctx := context.Background() pge := pgengine.NewDB(mockPool, "pgengine_unit_test") mockPool.ExpectBegin() mockPool.ExpectCommit().WillReturnError(errors.New("error")) tx, err := mockPool.Begin(context.Background()) assert.NoError(t, err) pge.CommitTransaction(ctx, tx) mockPool.ExpectBegin() mockPool.ExpectRollback().WillReturnError(errors.New("error")) tx, err = mockPool.Begin(context.Background()) assert.NoError(t, err) pge.RollbackTransaction(ctx, tx) mockPool.ExpectBegin() mockPool.ExpectExec("SAVEPOINT").WillReturnError(errors.New("error")) tx, err = mockPool.Begin(context.Background()) assert.NoError(t, err) pge.MustSavepoint(ctx, tx, 42) mockPool.ExpectBegin() mockPool.ExpectExec("ROLLBACK TO SAVEPOINT").WillReturnError(errors.New("error")) tx, err = mockPool.Begin(context.Background()) assert.NoError(t, err) pge.MustRollbackToSavepoint(ctx, tx, 42) assert.NoError(t, mockPool.ExpectationsWereMet(), "there were unfulfilled expectations") } func TestExecuteSQLTask(t *testing.T) { initmockdb(t) pge := pgengine.NewDB(mockPool, "pgengine_unit_test") ctx := context.Background() t.Run("Check autonomous SQL task", func(t *testing.T) { _, err := pge.ExecuteSQLTask(ctx, nil, &pgengine.ChainTask{Autonomous: true}, []string{}) assert.ErrorContains(t, err, "pgpool.Acquire() method is not implemented") }) t.Run("Check remote SQL task", func(t *testing.T) { task := pgengine.ChainTask{ConnectString: pgtype.Text{String: "foo", Valid: true}} _, err := pge.ExecuteSQLTask(ctx, nil, &task, []string{}) assert.ErrorContains(t, err, "cannot parse") }) t.Run("Check local SQL task", func(t *testing.T) { mockPool.ExpectBegin() tx, err := mockPool.Begin(ctx) assert.NoError(t, err) _, err = pge.ExecuteSQLTask(ctx, tx, &pgengine.ChainTask{IgnoreError: true}, []string{}) assert.ErrorContains(t, err, "SQL command cannot be empty") }) } func TestExecLocalSQLTask(t *testing.T) { initmockdb(t) pge := pgengine.NewDB(mockPool, "pgengine_unit_test") ctx := context.Background() mockPool.ExpectExec("SET ROLE").WillReturnResult(pgconn.NewCommandTag("SET")) mockPool.ExpectExec("SAVEPOINT task").WillReturnResult(pgconn.NewCommandTag("SAVEPOINT")) mockPool.ExpectExec("SELECT set_config"). WithArgs(pgxmock.AnyArg(), pgxmock.AnyArg(), pgxmock.AnyArg()). WillReturnResult(pgconn.NewCommandTag("SELECT")) mockPool.ExpectExec("FOO").WillReturnError(errors.New(`ERROR: syntax error at or near "FOO"`)) mockPool.ExpectExec("ROLLBACK TO SAVEPOINT").WillReturnResult(pgconn.NewCommandTag("ROLLBACK")) mockPool.ExpectExec("RESET ROLE").WillReturnResult(pgconn.NewCommandTag("RESET")) task := pgengine.ChainTask{ TaskID: 42, IgnoreError: true, Script: "FOO", RunAs: pgtype.Text{String: "Bob", Valid: true}, } _, err := pge.ExecLocalSQLTask(ctx, mockPool, &task, []string{}) assert.Error(t, err) mockPool.ExpectExec("SET ROLE").WillReturnError(errors.New("unknown role Bob")) _, err = pge.ExecLocalSQLTask(ctx, mockPool, &task, []string{}) assert.ErrorContains(t, err, "unknown role Bob") assert.NoError(t, mockPool.ExpectationsWereMet()) } func TestExecStandaloneTask(t *testing.T) { initmockdb(t) pge := pgengine.NewDB(mockPool, "pgengine_unit_test") ctx := context.Background() mockPool.ExpectExec("SET ROLE").WillReturnResult(pgconn.NewCommandTag("SET")) mockPool.ExpectExec("SELECT set_config"). WithArgs(pgxmock.AnyArg(), pgxmock.AnyArg(), pgxmock.AnyArg()). WillReturnResult(pgconn.NewCommandTag("SELECT")) mockPool.ExpectExec("FOO").WillReturnError(errors.New(`ERROR: syntax error at or near "FOO"`)) mockPool.ExpectClose() task := pgengine.ChainTask{ TaskID: 42, IgnoreError: true, Script: "FOO", RunAs: pgtype.Text{String: "Bob", Valid: true}, } cf := func() (pgengine.PgxConnIface, error) { return mockPool.AsConn(), nil } _, err := pge.ExecStandaloneTask(ctx, cf, &task, []string{}) assert.Error(t, err) mockPool.ExpectExec("SET ROLE").WillReturnError(errors.New("unknown role Bob")) mockPool.ExpectClose() _, err = pge.ExecStandaloneTask(ctx, cf, &task, []string{}) assert.ErrorContains(t, err, "unknown role Bob") cf = func() (pgengine.PgxConnIface, error) { return nil, errors.New("no connection") } _, err = pge.ExecStandaloneTask(ctx, cf, &task, []string{}) assert.ErrorContains(t, err, "no connection") assert.NoError(t, mockPool.ExpectationsWereMet()) } func TestExpectedCloseError(t *testing.T) { initmockdb(t) pge := pgengine.NewDB(mockPool, "pgengine_unit_test") mockConn.ExpectClose().WillReturnError(errors.New("Close failed")) pge.FinalizeDBConnection(context.TODO(), mockConn) assert.NoError(t, mockPool.ExpectationsWereMet(), "there were unfulfilled expectations") } func TestExecuteSQLCommand(t *testing.T) { initmockdb(t) defer mockPool.Close() pge := pgengine.NewDB(mockPool, "pgengine_unit_test") ctx := context.Background() _, err := pge.ExecuteSQLCommand(ctx, mockPool, "", []string{}) assert.Error(t, err) mockPool.ExpectExec("correct json").WillReturnResult(pgxmock.NewResult("EXECUTE", 0)) _, err = pge.ExecuteSQLCommand(ctx, mockPool, "correct json", []string{}) assert.NoError(t, err) mockPool.ExpectExec("correct json").WithArgs("John", 30.0, nil).WillReturnResult(pgxmock.NewResult("EXECUTE", 0)) _, err = pge.ExecuteSQLCommand(ctx, mockPool, "correct json", []string{`["John", 30, null]`}) assert.NoError(t, err) mockPool.ExpectExec("incorrect json").WillReturnError(json.Unmarshal([]byte("foo"), &struct{}{})) _, err = pge.ExecuteSQLCommand(ctx, mockPool, "incorrect json", []string{"foo"}) assert.Error(t, err) } func TestGetChainElements(t *testing.T) { initmockdb(t) defer mockPool.Close() pge := pgengine.NewDB(mockPool, "pgengine_unit_test") ctx := context.Background() mockPool.ExpectQuery("SELECT").WithArgs(0).WillReturnError(errors.New("error")) assert.Error(t, pge.GetChainElements(ctx, &[]pgengine.ChainTask{}, 0)) mockPool.ExpectQuery("SELECT").WithArgs(0).WillReturnRows( pgxmock.NewRows([]string{"task_id", "command", "kind", "run_as", "ignore_error", "autonomous", "database_connection", "timeout"}). AddRow(24, "foo", "sql", "user", false, false, "postgres://foo@boo/bar", 0)) assert.NoError(t, pge.GetChainElements(ctx, &[]pgengine.ChainTask{}, 0)) mockPool.ExpectQuery("SELECT").WithArgs(0).WillReturnError(errors.New("error")) assert.Error(t, pge.GetChainParamValues(ctx, &[]string{}, &pgengine.ChainTask{})) mockPool.ExpectQuery("SELECT").WithArgs(0).WillReturnRows(pgxmock.NewRows([]string{"s"}).AddRow("foo")) assert.NoError(t, pge.GetChainParamValues(ctx, &[]string{}, &pgengine.ChainTask{})) } func TestSetRole(t *testing.T) { initmockdb(t) defer mockPool.Close() ctx := context.Background() pge := pgengine.NewDB(mockPool, "pgengine_unit_test") mockPool.ExpectBegin() mockPool.ExpectExec("SET ROLE").WillReturnError(errors.New("error")) tx, err := mockPool.Begin(ctx) assert.NoError(t, err) assert.Error(t, pge.SetRole(ctx, tx, pgtype.Text{String: "foo", Valid: true})) assert.NoError(t, pge.SetRole(ctx, tx, pgtype.Text{String: "", Valid: false}), "Should ignore empty run_as") mockPool.ExpectBegin() mockPool.ExpectExec("RESET ROLE").WillReturnError(errors.New("error")) tx, err = mockPool.Begin(ctx) assert.NoError(t, err) pge.ResetRole(ctx, tx) } <file_sep>/docs/api.rst REST API ================================================ **pg_timetable** has a rich REST API, which can be used by external tools in order to perform start/stop/reinitialize/restarts/reloads, by any kind of tools to perform HTTP health checks, and of course, could also be used for monitoring. Below you will find the list of **pg_timetable** REST API endpoints. Health check endpoints ------------------------------------------------ ``GET /liveness`` Always returns HTTP status code ``200``, indicating that **pg_timetable** is running. ``GET /readiness`` Returns HTTP status code ``200`` when the **pg_timetable** is running, and the scheduler is in the main loop processing chains. If the scheduler connects to the database, creates the database schema, or upgrades it, it will return the HTTP status code ``503``. Chain management endpoints ------------------------------------------------ ``GET /startchain?id=<chain-id>`` Returns HTTP status code ``200`` if the chain with the given id can be added to the worker queue. It doesn't, however, mean the chain execution starts immediately. It is up to the worker to perform load and other checks before starting the chain. In the case of an error, the HTTP status code ``400`` followed by an error message returned. ``GET /stopchain?id=<chain-id>`` Returns HTTP status code ``200`` if the chain with the given id is working at the moment and can be stopped. If the chain is running the cancel signal would be sent immediately. In the case of an error, the HTTP status code ``400`` followed by an error message returned. <file_sep>/samples/Basic.sql SELECT timetable.add_job( job_name => 'notify every minute', job_schedule => '* * * * *', job_command => 'SELECT pg_notify($1, $2)', job_parameters => '[ "TT_CHANNEL", "Ahoj from SQL base task" ]' :: jsonb, job_kind => 'SQL'::timetable.command_kind, job_client_name => NULL, job_max_instances => 1, job_live => TRUE, job_self_destruct => FALSE, job_ignore_errors => TRUE ) as chain_id;<file_sep>/internal/pgengine/pgengine_test.go package pgengine_test import ( "context" "fmt" "os" "testing" "time" pgtype "github.com/jackc/pgx/v5/pgtype" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/cybertec-postgresql/pg_timetable/internal/config" "github.com/cybertec-postgresql/pg_timetable/internal/log" "github.com/cybertec-postgresql/pg_timetable/internal/pgengine" "github.com/cybertec-postgresql/pg_timetable/internal/scheduler" ) // this instance used for all engine tests var pge *pgengine.PgEngine var cmdOpts *config.CmdOptions = config.NewCmdOptions("--clientname=pgengine_unit_test", "--password=<PASSWORD>") // SetupTestCaseEx allows to configure the test case before execution func SetupTestCaseEx(t *testing.T, fc func(c *config.CmdOptions)) func(t *testing.T) { fc(cmdOpts) return SetupTestCase(t) } // SetupTestCase used to connect and to initialize test PostgreSQL database func SetupTestCase(t *testing.T) func(t *testing.T) { t.Helper() timeout := time.After(30 * time.Second) done := make(chan bool) go func() { pge, _ = pgengine.New(context.Background(), *cmdOpts, log.Init(config.LoggingOpts{LogLevel: "error"})) done <- true }() select { case <-timeout: t.Fatal("Cannot connect and initialize test database in time") case <-done: } return func(t *testing.T) { _, _ = pge.ConfigDb.Exec(context.Background(), "DROP SCHEMA IF EXISTS timetable CASCADE") pge.ConfigDb.Close() t.Log("Test schema dropped") } } // setupTestRenoteDBFunc used to connect to remote postgreSQL database var setupTestRemoteDBFunc = func() (pgengine.PgxConnIface, error) { c := cmdOpts.Connection connstr := fmt.Sprintf("host='%s' port='%d' sslmode='%s' dbname='%s' user='%s' password='%s'", c.Host, c.Port, c.SSLMode, c.DBName, c.User, c.Password) return pge.GetRemoteDBConnection(context.Background(), connstr) } func TestInitAndTestConfigDBConnection(t *testing.T) { teardownTestCase := SetupTestCase(t) defer teardownTestCase(t) ctx := context.Background() require.NotNil(t, pge.ConfigDb, "ConfigDB should be initialized") t.Run("Check timetable tables", func(t *testing.T) { var oid int tableNames := []string{"task", "chain", "parameter", "log", "execution_log", "active_session", "active_chain"} for _, tableName := range tableNames { err := pge.ConfigDb.QueryRow(ctx, fmt.Sprintf("SELECT COALESCE(to_regclass('timetable.%s'), 0) :: int", tableName)).Scan(&oid) assert.NoError(t, err, fmt.Sprintf("Query for %s existence failed", tableName)) assert.NotEqual(t, pgengine.InvalidOid, oid, fmt.Sprintf("timetable.%s table doesn't exist", tableName)) } }) t.Run("Check timetable functions", func(t *testing.T) { var oid int funcNames := []string{"_validate_json_schema_type(text, jsonb)", "validate_json_schema(jsonb, jsonb, jsonb)", "add_task(timetable.command_kind, TEXT, BIGINT, DOUBLE PRECISION)", "add_job(TEXT, timetable.cron, TEXT, JSONB, timetable.command_kind, TEXT, INTEGER, BOOLEAN, BOOLEAN, BOOLEAN, BOOLEAN, TEXT)", "is_cron_in_time(timetable.cron, timestamptz)"} for _, funcName := range funcNames { err := pge.ConfigDb.QueryRow(ctx, fmt.Sprintf("SELECT COALESCE(to_regprocedure('timetable.%s'), 0) :: int", funcName)).Scan(&oid) assert.NoError(t, err, fmt.Sprintf("Query for %s existence failed", funcName)) assert.NotEqual(t, pgengine.InvalidOid, oid, fmt.Sprintf("timetable.%s function doesn't exist", funcName)) } }) t.Run("Check timetable.cron type input", func(t *testing.T) { stmts := []string{ //cron "SELECT '0 1 1 * 1' :: timetable.cron", "SELECT '0 1 1 * 1,2' :: timetable.cron", "SELECT '0 1 1 * 1,2,3' :: timetable.cron", "SELECT '0 1 * * 1/4' :: timetable.cron", "SELECT '0 * * 7 1-4' :: timetable.cron", "SELECT '0 * * * 2/4' :: timetable.cron", "SELECT '* * * * *' :: timetable.cron", "SELECT '*/2 */2 * * *' :: timetable.cron", // predefined "SELECT '@reboot' :: timetable.cron", "SELECT '@every 1 sec' :: timetable.cron", "SELECT '@after 1 sec' :: timetable.cron"} for _, stmt := range stmts { _, err := pge.ConfigDb.Exec(ctx, stmt) assert.NoError(t, err, fmt.Sprintf("Wrong input cron format: %s", stmt)) } }) t.Run("Check connection closing", func(t *testing.T) { pge.Finalize() assert.Nil(t, pge.ConfigDb, "Connection isn't closed properly") // reinit connection to execute teardown actions pge, _ = pgengine.New(context.Background(), *cmdOpts, log.Init(config.LoggingOpts{LogLevel: "error"})) }) } func TestFailedConnect(t *testing.T) { c := config.NewCmdOptions("-h", "fake", "-c", "pgengine_test") ctx, cancel := context.WithTimeout(context.Background(), pgengine.WaitTime*2) defer cancel() _, err := pgengine.New(ctx, *c, log.Init(config.LoggingOpts{LogLevel: "error"})) assert.ErrorIs(t, err, ctx.Err()) } func TestSchedulerFunctions(t *testing.T) { teardownTestCase := SetupTestCase(t) defer teardownTestCase(t) ctx := context.Background() t.Run("Check DeleteChainConfig function", func(t *testing.T) { assert.Equal(t, false, pge.DeleteChain(ctx, 0), "Should not delete in clean database") }) t.Run("Check GetChainElements function", func(t *testing.T) { var chains []pgengine.ChainTask tx, txid, err := pge.StartTransaction(ctx) assert.NoError(t, err, "Should start transaction") assert.Greater(t, txid, int64(0), "Should return transaction id") assert.NoError(t, pge.GetChainElements(ctx, &chains, 0), "Should no error in clean database") assert.Empty(t, chains, "Should be empty in clean database") pge.CommitTransaction(ctx, tx) }) t.Run("Check GetChainParamValues function", func(t *testing.T) { var paramVals []string tx, txid, err := pge.StartTransaction(ctx) assert.NoError(t, err, "Should start transaction") assert.Greater(t, txid, int64(0), "Should return transaction id") assert.NoError(t, pge.GetChainParamValues(ctx, &paramVals, &pgengine.ChainTask{ TaskID: 0, ChainID: 0}), "Should no error in clean database") assert.Empty(t, paramVals, "Should be empty in clean database") pge.CommitTransaction(ctx, tx) }) t.Run("Check InsertChainRunStatus function", func(t *testing.T) { var res bool assert.NotPanics(t, func() { res = pge.InsertChainRunStatus(ctx, 0, 1) }, "Should no error in clean database") assert.True(t, res, "Active chain should be inserted") }) t.Run("Check ExecuteSQLCommand function", func(t *testing.T) { tx, txid, err := pge.StartTransaction(ctx) assert.NoError(t, err, "Should start transaction") assert.Greater(t, txid, int64(0), "Should return transaction id") f := func(sql string, params []string) error { _, err := pge.ExecuteSQLCommand(ctx, tx, sql, params) return err } assert.Error(t, f("", nil), "Should error for empty script") assert.Error(t, f(" ", nil), "Should error for whitespace only script") assert.NoError(t, f(";", nil), "Simple query with nil as parameters argument") assert.NoError(t, f(";", []string{}), "Simple query with empty slice as parameters argument") assert.NoError(t, f("SELECT $1::int4", []string{"[42]"}), "Simple query with non empty parameters") assert.NoError(t, f("SELECT $1::int4", []string{"[42]", `[14]`}), "Simple query with doubled parameters") assert.NoError(t, f("SELECT $1::int4, $2::text", []string{`[42, "hey"]`}), "Simple query with two parameters") pge.CommitTransaction(ctx, tx) }) } func TestGetRemoteDBTransaction(t *testing.T) { teardownTestCase := SetupTestCase(t) defer teardownTestCase(t) ctx := context.Background() remoteDb, err := setupTestRemoteDBFunc() defer pge.FinalizeDBConnection(ctx, remoteDb) require.NoError(t, err, "remoteDB should be initialized") require.NotNil(t, remoteDb, "remoteDB should be initialized") assert.NoError(t, pge.SetRole(ctx, remoteDb, pgtype.Text{String: cmdOpts.Connection.User, Valid: true}), "Set Role failed") assert.NotPanics(t, func() { pge.ResetRole(ctx, remoteDb) }, "Reset Role failed") pge.FinalizeDBConnection(ctx, remoteDb) assert.NotNil(t, remoteDb, "Connection isn't closed properly") } func TestSamplesScripts(t *testing.T) { teardownTestCase := SetupTestCase(t) defer teardownTestCase(t) files, err := os.ReadDir("../../samples") assert.NoError(t, err, "Cannot read samples directory") l := log.Init(config.LoggingOpts{LogLevel: "error"}) for _, f := range files { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() assert.NoError(t, pge.ExecuteCustomScripts(ctx, "../../samples/"+f.Name()), "Sample query failed: ", f.Name()) // either context should be cancelled or 'shutdown.sql' will terminate the session assert.True(t, scheduler.New(pge, l).Run(ctx) > scheduler.RunningStatus) _, err = pge.ConfigDb.Exec(context.Background(), "TRUNCATE timetable.task, timetable.chain CASCADE") assert.NoError(t, err) } } <file_sep>/internal/tasks/files.go package tasks import ( "context" "fmt" "github.com/cavaliercoder/grab" ) // DownloadUrls function implemented using grab library func DownloadUrls(ctx context.Context, urls []string, dest string, workers int) (out string, err error) { var req *grab.Request // create multiple download requests reqs := make([]*grab.Request, 0) for _, url := range urls { req, err = grab.NewRequest(dest, url) if err != nil { return } req = req.WithContext(ctx) reqs = append(reqs, req) } // start downloads with workers, if WorkersNum <= 0, then worker for each file client := grab.NewClient() respch := client.DoBatch(workers, reqs...) // check each response var errstrings []string for resp := range respch { if err = resp.Err(); err != nil { errstrings = append(errstrings, err.Error()) } else { out = out + fmt.Sprintf("Downloaded %s to %s\n", resp.Request.URL(), resp.Filename) } } if len(errstrings) > 0 { err = fmt.Errorf("download failed: %v", errstrings) } return } <file_sep>/internal/pgengine/copy.go package pgengine import ( "context" "os" ) // CopyToFile copies data from database into local file using COPY format specified by sql func (pge *PgEngine) CopyToFile(ctx context.Context, filename string, sql string) (int64, error) { dbconn, err := pge.ConfigDb.Acquire(ctx) if err != nil { return -1, err } defer dbconn.Release() f, err := os.Create(filename) defer func() { _ = f.Close() }() if err != nil { return -1, err } res, err := dbconn.Conn().PgConn().CopyTo(ctx, f, sql) return res.RowsAffected(), err } // CopyFromFile copies data from local file into database using COPY format specified by sql func (pge *PgEngine) CopyFromFile(ctx context.Context, filename string, sql string) (int64, error) { dbconn, err := pge.ConfigDb.Acquire(ctx) if err != nil { return -1, err } defer dbconn.Release() f, err := os.Open(filename) defer func() { _ = f.Close() }() if err != nil { return -1, err } res, err := dbconn.Conn().PgConn().CopyFrom(ctx, f, sql) return res.RowsAffected(), err }
9bda14e8738f1c9f8462cdacb41c8abf673cdd9d
[ "SQL", "reStructuredText", "Markdown", "Python", "Go", "Go Module", "Dockerfile" ]
78
Go
cybertec-postgresql/pg_timetable
69e9e7ad25f2cc45bb7f8cb38661a4b756bb2966
f10996d3ee127c3ed326ccfc11e02eac7be35e86
refs/heads/master
<repo_name>ChernyakovSI/ChernyakovSI<file_sep>/example/index.php <?php define("LESSON_NUMBER", "Образец для GeekBrains"); error_reporting(E_ALL); session_start(); include_once "system/base_model.php"; include_once "system/system_model.php"; include_once "system/helper/array_helper.php"; include_once "model/functions_rents_model.php"; include_once "model/functions_types_model.php"; include_once "model/functions.php"; include_once "model/functions_users_model.php"; spl_autoload_register('class_autoloader'); $system = new System(); if (isset($_POST['action'])) { if ($_POST['action'] === 'login') { $username = $_POST['username']; $password = $_POST['<PASSWORD>']; if (isset($_POST['remember'])) { $remember = $_POST['remember']; } else { $remember = false; } $system->user->auth($username, $password, $remember); } if ($_POST['action'] === 'signup') { $username = $_POST['username']; $password = $_POST['<PASSWORD>']; if (isset($_POST['remember'])) { $remember = $_POST['remember']; } else { $remember = false; } $system->user->create_password($password); $system->user->Role = 1; $system->user->Username = $username; $system->user->add(); $system->user->auth($username, $password, $remember); } if ($_POST['action'] === 'tosignup') { echo render("auth/signup", [], true, true); exit(); } } if ($system->user->auth_flow() === false) { echo render("auth/login", [], true, true); exit(); } else { if (isset($_GET['cat'])) { $controller = $_GET['cat']; } else { $controller = 'rents'; } if (isset($_GET['act'])) { $act = $_GET['act']; } else { $act = "all"; } if (($controller === "log") and ($act === "out")) { unset($_SESSION["username"]); unset($_SESSION["password"]); session_destroy(); unset($_GET); header('Location: index.php'); exit(); } $controller_class_name = name2controller_class_name($controller); $controller_function_name = $controller . "_" . $act; $controller_object = new $controller_class_name(); $result = $controller_object->$controller_function_name(); if ($result) echo $result; mysqli_close(Model::get_db()); } <file_sep>/example/controller/controller_rents.php <?php /** * Created by PhpStorm. * User: Paladin * Date: 23.06.2016 * Time: 23:18 */ class RentsController extends general { function rents_all() { if (isset($_POST['action'])) { if ($_POST['action'] === 'view_rent') { $id = $_POST['id']; header("Location: index.php?cat=rents&act=view&id=" . $id); } if ($_POST['action'] === 'edit_rent') { $id = $_POST['id']; header("Location: index.php?cat=rents&act=edit&id=" . $id); } if ($_POST['action'] === 'delete_rent') { $id = $_POST['id']; header("Location: index.php?cat=rents&act=delete&id=" . $id); } if ($_POST['action'] === 'add_rent') { header("Location: index.php?cat=rents&act=add"); } } $rents = rent::all(); $types = type::all(); $types = ArrayHelper::index($types,'ID'); $html_text = render("rent_all", ['rents' => $rents, 'apartment_types' => $types]); return $html_text; } function rents_view() { if (isset($_POST['action'])) { if ($_POST['action'] === 'edit_rent') { $id = $_POST['id']; header("Location: index.php?cat=rents&act=edit&id=" . $id); } } if (isset($_GET['id'])) { $id = $_GET['id']; } else { header("Location: index.php"); } $rent = new rent($id); $types = type::all(); $types = ArrayHelper::index($types,'ID'); if (!$rent->is_loaded()) { die('Нет такого объекта'); } $html_text = render("rent_one", ['rent' => $rent, 'apartment_types' => $types]); return $html_text; } function rents_add() { if (isset($_POST['action'])) { if ($_POST['action'] === 'add_rent') { $rent = new rent; $rent->Name = $_POST['name']; $rent->Type = $_POST['id_type']; $rent->Address = $_POST['address']; $rent->Subscription = $_POST['Subscription']; $rent->Price = $_POST['price']; $rent->Square = $_POST['square']; if ($rent->add() === true) { header("Location: index.php"); } else { echo 'Не удалось добавить данные!'; exit(); } } if ($_POST['action'] === 'cancel_rent') { header("Location: index.php"); } } $types = type::all(); $html_text = render("rent_add", ['types' => $types]); return $html_text; } function rents_edit() { if (isset($_POST['action'])) { if ($_POST['action'] === 'edit_rent') { $rent = new rent($_POST['id']); $rent->Name = $_POST['name']; $rent->Type = $_POST['id_type']; $rent->Address = $_POST['address']; $rent->Subscription = $_POST['subscription']; $rent->Price = $_POST['price']; $rent->Square = $_POST['square']; if ($rent->edit() === true) { header("Location: index.php"); } else { echo 'Не удалось изменить данные!'; exit(); } } } if (isset($_GET['id'])) { $id = $_GET['id']; } else { header("Location: index.php"); } $rent = new rent($id); $types = type::all(); $types = ArrayHelper::index($types,'ID'); $html_text = render("rent_edit", ['rent' => $rent, 'apartment_types' => $types]); return $html_text; } function rents_delete() { if (isset($_POST['action'])) { if ($_POST['action'] === 'delete_rent') { $id = $_POST['id']; $rent = new rent($id); $result = $rent->delete(); if ($result === true) { header("Location: index.php"); } else { echo 'Не удалось удалить данные!'; exit(); } } if ($_POST['action'] === 'cancel_rent') { header("Location: index.php"); } } if (isset($_GET['id'])) { $id = $_GET['id']; } else { header("Location: index.php"); } $rent = new rent($id); $types = type::all(); $types = ArrayHelper::index($types,'ID'); $html_text = render("rent_delete", ['rent' => $rent, 'apartment_types' => $types]); return $html_text; } }<file_sep>/example/system/base_model.php <?php /** * Created by PhpStorm. * User: Paladin * Date: 10.07.2016 * Time: 12:59 */ class Model { const FIELD_NOT_EXIST = "{FIELD_NOT_EXIST}"; const ID_ACCESS_DENIED = "{ID_ACCESS_DENIED}"; const OBJECT_NOT_EXIST = "{OBJECT_NOT_EXIST}"; const UPDATE_FAILED = "{UPDATE_FAILED}"; const OBJECT_ALREADY_EXIST = "{OBJECT_ALREADY_EXIST}"; const CREATE_FAILED = "{CREATE_FAILED}"; const DELETE_FAILED = "{DELETE_FAILED}"; protected static $errors = array( self::FIELD_NOT_EXIST, self::ID_ACCESS_DENIED, self::OBJECT_NOT_EXIST, self::UPDATE_FAILED, self::OBJECT_ALREADY_EXIST, self::CREATE_FAILED, self::DELETE_FAILED ); protected static $behaviours = array(); protected static $fields = array(); protected static $field_types = array(); protected static $db = NULL; protected $is_loaded_from_db; protected $is_changed; protected $data = array(); protected $relations = array(); public function __construct($id = NULL) { if (static::$fields === array()) { static::init_fields(); } if ($id !== NULL) { $id = (int) $id; $rezult = $this->one($id); if ($rezult === true) { $this->is_loaded_from_db = true; } else { echo $rezult; } } else { $this->is_loaded_from_db = false; } $this->is_changed = false; } /*function __destruct() { if (isset($this->db) and $this->db !== NULL) { mysqli_close($this->db); } }*/ public function __get($field) { if (isset($this->data[$field])) { return $this->data[$field]; } else { if (isset($this->relations[$field])) { return $this->relations[$field]; } else { if (in_array($field,array_keys(static::$behaviours))) { $key = static::$behaviours[$field]['key']; if (static::$behaviours[$field]['type'] = 'one') { $class_name = static::$behaviours[$field]['class']; $value = new $class_name($this->$key); } else { $relation_key = static::$behaviours[$field]['relation_key']; $class_name = static::$behaviours[$field]['class']; $value = $class_name::all([$relation_key => $this->$key]); } return $this->relations[$field] = $value; } } } if (!(in_array($field,static::get_fields()))) { return self::FIELD_NOT_EXIST; } else { return NULL; } } public function __set($field, $value) { if ((!in_array($field,static::get_fields()))&&(!in_array($field,$this->get_relation_fields()))) { return self::FIELD_NOT_EXIST; } else { if ($field === 'id') { return self::ID_ACCESS_DENIED; } else { if (in_array($field,static::get_fields())) { $this->data[$field] = $value; if ($this->is_loaded_from_db) { $this->is_changed = true; } return $this->data[$field]; } else { if (in_array($field,array_keys(static::$behaviours))) { $this->relations[$field] = $value; } else { return self::FIELD_NOT_EXIST; } } } } } protected static function init_fields() { $query = "DESCRIBE `".static::tableName()."`;"; $result = mysqli_query(self::get_db(),$query); while($row = mysqli_fetch_assoc($result)) { static::$fields[] = $row['Field']; if (strpos($row['Type'],'(')) { $pie = explode('(',$row['Type'],2); $row['Type'] = $pie[0]; } static::$field_types[$row['Field']] = $row['Type']; } } public static function tableName() { return NULL; } public static function className() { return 'Model'; } public function is_changed() { return $this->is_changed; } public function is_loaded_from_db() { return $this->is_loaded_from_db; } function is_loaded() { return ($this->id !== NULL); } static function get_db() { if (self::$db === NULL) { include("db_connect.php"); self::$db = $link; } return self::$db; } public function one($id) { $query = "SELECT * FROM `".static::tableName()."` WHERE `id` = '{$id}'"; $result = mysqli_query(self::get_db(),$query); if ($row = mysqli_fetch_assoc($result)) { return $this->load($row); } else { return false; } } public function load($data = array()) { foreach($data as $k => $v) { if (!in_array($k,static::get_fields())) { return self::FIELD_NOT_EXIST; } else { $this->data[$k] = $v; } } return true; } protected static function get_fields() { if (static::$fields === array()) { static::init_fields(); } return static::$fields; } protected function get_relation_fields() { return array_keys($this->relations); } protected static function where_condition($array) { $result = ''; foreach ($array as $row) { foreach($row as $k => $v) { if ($result !== '') $result .= ' '; if ((in_array(mb_strtoupper($v),["AND","OR"]))&&(is_numeric($k))) // неассоциативный ключ и ключевое слово sql - признак связки { $result .= "{$v}"; } else { if (!is_array($v)) // просто значение { $result .= "(`{$k}` = '{$v}')"; } else { $in = ''; foreach ($v as $item) // формируем запись ('1','2','4') { if ($in !== '') $in .= ', '; $in .= "'{$item}'"; } $in = "({$in})"; $result .= "(`{$k}` IN {$in})"; } } } } return $result; } public static function all($condition = '1') { if (is_array($condition)) { $condition = self::where_condition($condition); // self gjnjve } $query = "SELECT * FROM `".static::tableName()."` WHERE {$condition}"; $result = mysqli_query(self::get_db(),$query); $all = array(); while ($row = mysqli_fetch_assoc($result)) { $class_name = static::className(); $one = new $class_name(); /* @var $one Model */ if ($one->load($row)) { $all[] = $one; } } return $all; } public function edit() { if ($this->ID === NULL) return self::OBJECT_NOT_EXIST; $query = "UPDATE `".static::tableName()."` SET ".$this->update_query()." WHERE `ID` = '$this->ID'"; $result = mysqli_query(self::get_db(),$query); if ($result) { $this->is_changed = false; return true; } else { return self::UPDATE_FAILED; } } protected function update_query($updated_fields = array()) { $fields = array(); if ($updated_fields === array()) { $fields = static::get_fields(); } else { foreach($updated_fields as $uf) { if (in_array($uf,static::get_fields())) { $fields[] = $uf; } } } $result = ''; foreach($fields as $f) { if ($result !== '') $result .= ', '; if ((isset($this->data[$f]))&&($this->data[$f]!==NULL)) { $result .= "`{$f}` = '{$this->data[$f]}'"; } else { $result .= "`{$f}` = NULL"; } } return $result; } public function add() { if ($this->ID !== NULL) { return self::OBJECT_ALREADY_EXIST; } $query = "INSERT INTO `".static::tableName()."` (".static::fields_query().") VALUES (".$this->values_query().")"; $result = mysqli_query(self::get_db(),$query); if ($result) { $this->data['id'] = mysqli_insert_id(self::get_db()); $this->is_changed = false; return true; } else { return self::CREATE_FAILED; } } protected static function fields_query() { $fields = static::get_fields(); $result = ''; foreach($fields as $f) { if ($result !== '') $result .= ', '; $result .= "`{$f}`"; } return $result; } protected function values_query() { $fields = static::get_fields(); $result = ''; foreach($fields as $f) { if ($result !== '') $result .= ', '; if ((isset($this->data[$f]))&&($this->data[$f]!==NULL)) { $result .= "'{$this->data[$f]}'"; } else { $result .= "NULL"; } } return $result; } public function delete() { if ($this->ID === NULL) return self::OBJECT_NOT_EXIST; $query = "DELETE FROM `".static::tableName()."` WHERE `ID` = '{$this->ID}' LIMIT 1"; $result = mysqli_query(self::get_db(),$query); if ($result) { $this->data['ID'] = NULL; $this->is_changed = false; $this->is_loaded_from_db = false; return true; } else { return self::DELETE_FAILED; } } }<file_sep>/example/view/types_one.php <!-- Page Content --> <div id="page-wrapper"> <div class="container-fluid"> <div class="row"> <div class="col-lg-14"> <h1 class="page-header">Тип помещения</h1> </div> <!-- /.col-lg-12 --> <table class="table table-bordered table-striped"> <thead> <tr> <th> Название: </th> <th> <?= $type->Name ?> </th> </tr> </thead> </table> </br><form action="" method="post"> <input type="hidden" name="action" value="edit_type"/> <input type="hidden" name="id" value="<?= $type->ID ?>"/> <a class ="btn" href="index.php?cat=types&act=edit&id=<?php echo "$type->ID"; ?>">Изменить</a> </form> </div> <!-- /.row --> </div> <!-- /.container-fluid --> </div> <!-- /#page-wrapper --><file_sep>/example/view/types_delete.php <!-- Page Content --> <div id="page-wrapper"> <div class="container-fluid"> <div class="row"> <div class="col-lg-14"> <h1 class="page-header">Удаление типа помещения</h1> </div> <!-- /.col-lg-12 --> <div class="col-lg-14"> Подтвердите удаление записи: </div> <table class="table table-bordered table-striped"> <thead> <tr> <th> Название: </th> <th> <?= $type->Name ?> </th> </tr> </thead> </table> </br> <table> <thead> <tr> <th> <form action="" method="post"> <input type="hidden" name="action" value="delete_type"/> <input type="hidden" name="id" value="<?= $type->ID ?>"/> <button type="submit">Удалить</button> </form> </th> <th> <form action="" method="post"> <input type="hidden" name="action" value="cancel_type"/> <input type="hidden" name="id" value="<?= $type->ID ?>"/> <button type="submit">Отменить</button> </form> </th> </tr> </thead> </table> </div> <!-- /.row --> </div> <!-- /.container-fluid --> </div> <!-- /#page-wrapper --><file_sep>/example/model/functions.php <?php /** * Created by PhpStorm. * User: Paladin * Date: 25.06.2016 * Time: 14:12 */ class general { public function __call($name,$params) { e404("Функция {$name} не обнаружена"); } } function render($view_name, $data = [], $with_layout = true, $logout = false) { ob_start(); if (file_exists("view/{$view_name}.php")) { foreach ($data as $key => $value) { $$key = $value; } require_once("view/{$view_name}.php"); $content = ob_get_contents(); ob_end_clean(); if ($with_layout) { ob_start(); if ($logout === false) { require_once("view/layout/index.php"); } else { require_once("view/layout/index_logout.php"); } $content = ob_get_contents(); ob_end_clean(); } return $content; } else { return false; } } function class_autoloader($classname) { if (mb_substr($classname,-10,NULL,'utf-8') === 'Controller') { $class_string = mb_substr($classname,0,mb_strlen($classname,'utf-8')-10,'utf-8'); $name = preg_replace('/([a-z])([A-Z])/', '$1_$2', $class_string); $file_name = "controller/controller_".mb_strtolower($name,'utf-8').'.php'; if (file_exists($file_name)) { include_once $file_name; } else { e404(); } } } function e404($message = '') { header("HTTP/1.1 404 Not Found"); die($message); } function name2controller_class_name($name) { $pie = explode('_',$name); $result = ''; foreach($pie as $v) { $result .= ucfirst($v); } $result.="Controller"; return $result; }<file_sep>/example/view/types_all.php <!-- Page Content --> <div id="page-wrapper"> <div class="container-fluid"> <div class="row"> <div class="col-lg-14"> <h1 class="page-header">Список типов помещений</h1> </div> <!-- /.col-lg-12 --> </div> <table class="table table-bordered table-striped"> <thead> <tr> <th> Название </th> <th> </th> <th> </th> <th> </th> </tr> </thead> <?php foreach ($types as $Akey => $Avalue) { ?> <tr> <th> <?= $Avalue->Name ?> </th> <th> <form action="" method="post"> <input type="hidden" name="action" value="view_type"/> <input type="hidden" name="id" value="<?= $Avalue->ID ?>"/> <button type="submit"><p class="fa fa-search"></p></button> </form> </th> <th> <form action="" method="post"> <input type="hidden" name="action" value="edit_type"/> <input type="hidden" name="id" value="<?= $Avalue->ID ?>"/> <button type="submit"><p class="fa fa-pencil"></p></button> </form> </th> <th> <form action="" method="post"> <input type="hidden" name="action" value="delete_type"/> <input type="hidden" name="id" value="<?= $Avalue->ID ?>"/> <button type="submit"><p class="fa fa-times"></p></button> </form> </th> </tr> <?php } ?> </table> </br> <table> <thead> <tr> <th> <form action="" method="post"> <input type="hidden" name="action" value="add_type"/> <button type="submit">Добавить</button> </form> </th> </tr> </thead> </table> <!-- /.row --> </div> <!-- /.container-fluid --> </div> <!-- /#page-wrapper --><file_sep>/example/controller/controller_users.php <?php /** * Created by PhpStorm. * User: Paladin * Date: 10.07.2016 * Time: 19:26 */ class UsersController extends general { function __call($name, $params) { e404(); } function users_all() { if (isset($_POST['action'])) { if ($_POST['action'] === 'view_user') { $id = $_POST['id']; header("Location: index.php?cat=users&act=view&id=" . $id); } if ($_POST['action'] === 'edit_user') { $id = $_POST['id']; header("Location: index.php?cat=users&act=edit&id=" . $id); } if ($_POST['action'] === 'delete_user') { $id = $_POST['id']; header("Location: index.php?cat=users&act=delete&id=" . $id); } if ($_POST['action'] === 'add_user') { header("Location: index.php?cat=users&act=add"); } } $users = User::all(); return render('users_all', [ 'users' => $users ]); } function users_add() { if (count($_POST)) { if ($_POST['action'] === 'add_user') { $username = $_POST['username']; $password = $_POST['<PASSWORD>']; $role = $_POST['role']; $user = new User(); $user->Username = $username; $user->Role = $role; $user->create_password($password); // TODO обработать password if ($user->add()!== Model::CREATE_FAILED) { header("Location: index.php?cat=users&view=all"); die(); } else { die("Не удалось добавить"); } } } return render('users_add', [ ]); } function users_view() { if (isset($_POST['action'])) { if ($_POST['action'] === 'edit_user') { $id = $_POST['id']; header("Location: index.php?cat=users&act=edit&id=" . $id); } } if (isset($_GET['id'])) { $id = $_GET['id']; } else { header("Location: index.php?cat=users&act=all"); } $user = new user($id); if (!$user->is_loaded()) { die('Нет такого объекта'); } $html_text = render("users_one", ['user' => $user]); return $html_text; } function users_edit() { if (isset($_POST['action'])) { if ($_POST['action'] === 'edit_user') { $user = new user($_POST['id']); $user->Username = $_POST['Username']; $user->Role = $_POST['Role']; if ($user->edit()) { header("Location: index.php?cat=users&act=all"); } else { echo 'Не удалось изменить данные!'; exit(); } } } if (isset($_GET['id'])) { $id = $_GET['id']; } else { header("Location: index.php?cat=users&act=all"); } $user = new user($id); $html_text = render("users_edit", ['user' => $user]); return $html_text; } function users_delete() { if (isset($_POST['action'])) { if ($_POST['action'] === 'delete_user') { $id = $_POST['id']; $user = new user($id); if ($user->delete()) { header("Location: index.php?cat=users&act=all"); } else { echo 'Не удалось удалить данные!'; exit(); } } if ($_POST['action'] === 'cancel_user') { header("Location: index.php?cat=users&act=all"); } } if (isset($_GET['id'])) { $id = $_GET['id']; } else { header("Location: index.php?cat=users&act=all"); } $user = new user($id); $html_text = render("users_delete", ['user' => $user]); return $html_text; } }<file_sep>/example/controller/controller_types.php <?php /** * Created by PhpStorm. * User: Paladin * Date: 25.06.2016 * Time: 13:25 */ class TypesController extends general { function types_all() { if (isset($_POST['action'])) { if ($_POST['action'] === 'view_type') { $id = $_POST['id']; header("Location: index.php?cat=types&act=view&id=" . $id); } if ($_POST['action'] === 'edit_type') { $id = $_POST['id']; header("Location: index.php?cat=types&act=edit&id=" . $id); } if ($_POST['action'] === 'delete_type') { $id = $_POST['id']; header("Location: index.php?cat=types&act=delete&id=" . $id); } if ($_POST['action'] === 'add_type') { header("Location: index.php?cat=types&act=add"); } } $types = type::all(); $html_text = render("types_all", ['types' => $types]); return $html_text; } function types_view() { if (isset($_POST['action'])) { if ($_POST['action'] === 'edit_type') { $id = $_POST['id']; header("Location: index.php?cat=types&act=edit&id=" . $id); } } if (isset($_GET['id'])) { $id = $_GET['id']; } else { header("Location: index.php?cat=types&act=all"); } $type = new type($id); if (!$type->is_loaded()) { die('Нет такого объекта'); } $html_text = render("types_one", ['type' => $type]); return $html_text; } function types_add() { if (isset($_POST['action'])) { if ($_POST['action'] === 'add_type') { $type = new type; $type->Name = $_POST['name']; if ($type->add()) { header("Location: index.php?cat=types&act=all"); } else { echo 'Не удалось добавить данные!'; exit(); } } if ($_POST['action'] === 'cancel_rent') { header("Location: index.php?cat=types&act=all"); } } $html_text = render("types_add"); return $html_text; } function types_edit() { if (isset($_POST['action'])) { if ($_POST['action'] === 'edit_type') { $type = new type($_POST['id']); $type->Name = $_POST['name']; if ($type->edit()) { header("Location: index.php?cat=types&act=all"); } else { echo 'Не удалось изменить данные!'; exit(); } } } if (isset($_GET['id'])) { $id = $_GET['id']; } else { header("Location: index.php?cat=types&act=all"); } $type = new type($id); $html_text = render("types_edit", ['type' => $type]); return $html_text; } function types_delete() { if (isset($_POST['action'])) { if ($_POST['action'] === 'delete_type') { $id = $_POST['id']; $type = new type($id); if ($type->delete()) { header("Location: index.php?cat=types&act=all"); } else { echo 'Не удалось удалить данные!'; exit(); } } if ($_POST['action'] === 'cancel_type') { header("Location: index.php?cat=types&act=all"); } } if (isset($_GET['id'])) { $id = $_GET['id']; } else { header("Location: index.php?cat=types&act=all"); } $type = new type($id); $html_text = render("types_delete", ['type' => $type]); return $html_text; } }<file_sep>/example/view/auth/login.php <?php /** * Created by PhpStorm. * User: Dusty * Date: 07.07.2016 * Time: 22:50 */ ?> <div class="row"> <div class="col-lg-12"> <h1 class="page-header">Авторизация</h1> <form action="" method="post"> <input type="hidden" name="action" value="login"/> <div class="form-group input-group"> <span class="input-group-addon"><i class="fa fa-user"></i></span> <input type="text" placeholder="<NAME>" class="form-control" name="username"> </div> <div class="form-group input-group"> <span class="input-group-addon"><i class="fa fa-key"></i></span> <input type="<PASSWORD>" placeholder="<PASSWORD>" class="form-control" name="password"> </div> <div class="form-group input-group"> <input type="checkbox" name="remember"> Запомнить </div> <button class="btn btn-success" type="submit">Войти</button> </form> </br> <form action="" method="post"> <input type="hidden" name="action" value="tosignup"/> <button class="btn btn-success" type="submit">Зарегистрироваться</button> </form> </div> <!-- /.col-lg-12 --> </div> <!-- /.row --> <file_sep>/example/system/system_model.php <?php /** * Created by PhpStorm. * User: Paladin * Date: 10.07.2016 * Time: 19:13 */ Class System { protected static $user; public function __get($field) { if ($field === 'user') { if (self::$user === NULL) { self::$user = new User(); self::$user->auth_flow(); } return self::$user; } } }<file_sep>/example/model/functions_rents_model.php <?php class rent extends Model { protected static $behaviours = [ 'type' => [ 'key' => 'type', 'class' => 'type', 'type' => 'one' ] ]; protected static $fields = array(); protected static $field_types = array(); public static function className() { return 'rent'; } public static function tableName() { return 'rentapartment'; } }<file_sep>/example/model/functions_types_model.php <?php class type extends Model { protected static $fields = array(); protected static $field_types = array(); public static function className() { return 'type'; } public static function tableName() { return 'types'; } }<file_sep>/example/realestateagency.sql -- phpMyAdmin SQL Dump -- version 4.5.1 -- http://www.phpmyadmin.net -- -- Хост: 127.0.0.1 -- Время создания: Июл 10 2016 г., 23:08 -- Версия сервера: 10.1.13-MariaDB -- Версия PHP: 7.0.6 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; 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 */; -- -- База данных: `realestateagency` -- -- -------------------------------------------------------- -- -- Структура таблицы `rentapartment` -- CREATE TABLE `rentapartment` ( `ID` int(10) UNSIGNED NOT NULL, `Name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL, `Type` int(10) UNSIGNED NOT NULL, `Address` varchar(150) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL, `Subscription` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL, `Price` float UNSIGNED NOT NULL, `Square` float UNSIGNED NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Дамп данных таблицы `rentapartment` -- INSERT INTO `rentapartment` (`ID`, `Name`, `Type`, `Address`, `Subscription`, `Price`, `Square`) VALUES (2, 'Вторая квартира', 5, 'ул. Вишневая, д. 13, кв. 5', 'Роскошная квартира', 55000, 70), (3, 'Комната на Вишневой', 3, 'ул. Вишневая, д. 5, кв. 5', 'Роскошная комната', 21000, 18), (4, 'Коттедж', 3, 'Вишневая, 3', 'Много вина', 1000000, 160), (5, 'Коттедж на виноградной', 5, 'Виноградная, 2', 'Много-много вина', 2000000, 200), (7, '2', 7, '2', '2', 2, 2); -- -------------------------------------------------------- -- -- Структура таблицы `types` -- CREATE TABLE `types` ( `ID` int(10) UNSIGNED NOT NULL, `Name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Дамп данных таблицы `types` -- INSERT INTO `types` (`ID`, `Name`) VALUES (3, 'Квартира'), (4, 'Комната'), (5, 'Коттедж'), (7, 'Нечто'); -- -------------------------------------------------------- -- -- Структура таблицы `users` -- CREATE TABLE `users` ( `ID` int(10) UNSIGNED NOT NULL, `Role` int(10) UNSIGNED NOT NULL, `Username` varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL, `Password` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL, `Salt` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Дамп данных таблицы `users` -- INSERT INTO `users` (`ID`, `Role`, `Username`, `Password`, `Salt`) VALUES (8, 1, 'Вова', 'a778a1df55a042d<KEY>', '9cAPNBwP8zhkKPaNLC3bJChZM5GauIBb'), (10, 10, 'Макс', '<PASSWORD>', '88y480BhjWWuhFVb7qpirUJjkkIdoqJr'), (11, 10, 'Стас', '<PASSWORD>', '<PASSWORD>'), (12, 1, 'Вася', '<PASSWORD>', '<PASSWORD>'), (13, 1, 'Катя', '6<PASSWORD>', 'HqBZR1HjXrPoBpnGR89ammviagi2TBRT'), (14, 1, 'Ваня', '<PASSWORD>', 'OULeRmEs9QABasNtRNYqIWmiGwFsfA6J'), (15, 1, 'Алина', '381362a5906b8eb910178e7daaaa6610', 'nLpsw8MuGhXaik8kmP3kjUV099sIjETh'); -- -- Индексы сохранённых таблиц -- -- -- Индексы таблицы `rentapartment` -- ALTER TABLE `rentapartment` ADD PRIMARY KEY (`ID`), ADD KEY `Type` (`Type`); -- -- Индексы таблицы `types` -- ALTER TABLE `types` ADD PRIMARY KEY (`ID`); -- -- Индексы таблицы `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`ID`), ADD UNIQUE KEY `Username` (`Username`); -- -- AUTO_INCREMENT для сохранённых таблиц -- -- -- AUTO_INCREMENT для таблицы `rentapartment` -- ALTER TABLE `rentapartment` MODIFY `ID` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8; -- -- AUTO_INCREMENT для таблицы `types` -- ALTER TABLE `types` MODIFY `ID` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9; -- -- AUTO_INCREMENT для таблицы `users` -- ALTER TABLE `users` MODIFY `ID` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=16; /*!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>/example/view/users_edit.php <!-- Page Content --> <div id="page-wrapper"> <div class="container-fluid"> <div class="row"> <div class="col-lg-14"> <h1 class="page-header">Изменение пользователя</h1> </div> <!-- /.col-lg-12 --> <form action="" method="post"> <input type="hidden" name="action" value="edit_user"/><br/> <input type="hidden" name="id" value="<?= $user->ID ?>"/><br/> <table class="table table-bordered table-striped"> <thead> <tr> <th> <label for="Username">Пользователь:</label> </th> <th> <input type="text" name="Username" id="Username" placeholder="Пользователь" value="<?= $user->Username ?>"/> </th> </tr> <tr> <th> <label for="Role">Роль:</label> </th> <th> <select name="Role" id="Role"> <?php foreach (User::$roles as $key => $value) { ?> <option value="<?= $key?>" <?php if ($key == $user->Role) { echo 'selected = "selected"'; } ?>><?= $value ?></option> <?php } ?> </select> </th> </tr> </thead> </table> <table> <tr> <th> <button type="submit">Изменить</button> </th> <th> &nbsp;&nbsp;&nbsp; </th> <th> <a href="index.php?cat=users&act=all">Отменить</a> </th> </tr> </table> </form> </div> <!-- /.row --> </div> <!-- /.container-fluid --> </div> <!-- /#page-wrapper -->
f243fea239b0be4f406845b598e02062c2fc0c30
[ "SQL", "PHP" ]
15
PHP
ChernyakovSI/ChernyakovSI
e3ff5bbf7e3642bd794e0b51b85cc8ec7018067d
db8e7eb80b22c9daa902fea02f83ea1ab495a866
refs/heads/master
<repo_name>mk-pmb/ubborg-sysd-murmurd-pmb-js<file_sep>/src/facts.mjs // -*- coding: utf-8, tab-width: 2 -*- const muSrv = 'mumble-server'; const facts = { muSrv, muSvc: muSrv + '.service', muHome: '/var/lib/' + muSrv, muWrap: 'util/murmur-systemd-wrapper-pmb.sh', }; export default facts; <file_sep>/src/sysdwrap.sh #!/bin/bash # -*- coding: utf-8, tab-width: 2 -*- function sysdwrap () { local -A INI_OPT=( # To generate a default config with explanations, run as not root: # murmur-user-wrapper -i # Network basics [port]=64738 [allowping]=true [users]=32 # Paths [database]='./murmurd.sqlite' [logfile]='./logs/%y%m%d.%H%M%S.log' [pidfile]='./murmurd.pid' # Persistence [sqlite_wal]=2 # Branding [registerName]='Mumble Server' [welcometext]='<br />Welcome to this Murmur server.<br />' # Client security [allowhtml]=false # Access tokens etc. [sysdwrap_supw]= [icesecretread]= [icesecretwrite]= [serverpassword]= [certrequired]=true # Logging settings [sysdwrap_extra_flags]= # e.g. '-v' [obfuscate]=true # Network tweaks [bandwidth]=64k # ^-- Rather conservative. For HQ audio streaming inside a fast LAN, # you could probably afford 192k even. # NB: The maximum quality in the GUI slider in the default client # currently (2021-01-02) goes up to 96k. [timeout]=120 [messageburst]=5 [messagelimit]=1 # Ice stuff [Ice__Warn__UnknownProperties]=1 [Ice__MessageSizeMax]=65536 ) local OP= ARG= RV= local DBGLV="${DEBUGLEVEL:-0}" while [ "$#" -ge 1 ]; do OP="$1"; shift ARG="${OP#*:}" [ "$ARG" == "$OP" ] && ARG= OP="${OP%%:*}" dbgp "op='$OP', arg='$ARG'" sdw_"$OP" "$ARG"; RV=$? dbgp "op='$OP', arg='$ARG', rv=$RV" [ "$RV" == 0 ] || return "$RV" done } function dbgp () { [ "$DBGLV" -ge 2 ] && echo "D: $*" >&2; return 0; } function sdw_serve () { local INI='murmurd.ini.gen' sdw_path_tmpl database sdw_path_tmpl logfile sdw_path_tmpl pidfile >>"$INI" || return $? chmod a=,u+rw -- "$INI" || return $? sdw_render_ini >"$INI" || return $? local MMD_OPT=( -ini "$INI" -fg ${INI_OPT[sysdwrap_extra_flags]} ) sdw_configure_supw || return $? exec murmurd "${MMD_OPT[@]}" || return $? } function sdw_configure_supw () { local VER="$(murmurd --version 2>&1)" case "$VER" in '<F>'*' murmurd -- 1.3.3-1~ppa1~focal1' | \ '<F>UBAR' ) echo "W: skip configuring superuser password: version $( )${VER#* -- } is too broken." >&2 return 0;; esac local SUPW="${INI_OPT[sysdwrap_supw]}" case "$SUPW" in '' ) murmurd "${MMD_OPT[@]}" -disablesu; return $?;; * ) murmurd "${MMD_OPT[@]}" -readsupw <<<"$SUPW"; return $?;; esac } function sdw_path_tmpl () { local KEY="$1" local VAL="${INI_OPT[$KEY]}" if [[ "$VAL" == *'%'* ]]; then VAL="${VAL//%%/%% }" VAL="${VAL//%i/$BASH_PID}" printf -v VAL "%($VAL)T" VAL="${VAL//%% /%%}" fi [ "${VAL:0:2}" == ./ ] || VAL="$PWD${VAL:1}" mkdir --parents -- "$(dirname -- "$VAL")" INI_OPT["$KEY"]="$VAL" } function sdw_dircfg () { local PATH_PFX="$1" local INI= dbgp "$FUNCNAME" "$PATH_PFX" for INI in "$PATH_PFX"*.ini; do dbgp "$FUNCNAME" "$INI?" [ -f "$INI" ] || continue sdw_inicfg "$INI" || return $? done } function sdw_inicfg () { local INI="$1" KEY= VAL= local LINES=() dbgp "$FUNCNAME" "$INI" readarray -t LINES < <(sed -re 's!^\s+!!; s!\s*=\s*!=!' -- "$INI") for VAL in "${LINES[@]}"; do case "$VAL" in '[Ice]' | \ '' | '#'* | ';'* ) continue;; '['*']' ) echo "E: unsupported INI section: $VAL in $INI" >&2; return 3;; esac KEY="${VAL%%=*}" VAL="${VAL#*=}" KEY="${KEY//\./__}" dbgp "$FUNCNAME" "$INI" "$KEY=‹$VAL›" INI_OPT["$KEY"]="$VAL" done } function sdw_envcfg () { local ENV_PFX="${1:-murmur_}" local KEYS=() readarray -t KEYS < <(env | LANG=C grep -oPe '^\w+=') local KEY= VAL= CUT="${#ENV_PFX}" for KEY in "${KEYS[@]}"; do KEY="${KEY%=}" case "$KEY" in "$ENV_PFX"* ) ;; * ) continue;; esac VAL= eval 'VAL="$'"$KEY"'"' [ -z "$VAL" ] || INI_OPT["${KEY:$CUT}"]="$VAL" done } function sdw_render_ini () { local KEY= VAL= local ICE_OPT=() local SORTED=() readarray -t SORTED < <(printf '%s\n' "${!INI_OPT[@]}" | sort -V) for KEY in "${SORTED[@]}"; do VAL= VAL="${INI_OPT[$KEY]}" case "$VAL" in '"'*'"' ) ;; *[^A-Za-z0-9_-]* ) VAL='"'"$VAL"'"';; esac case "${KEY,,}" in ice__* ) KEY="${KEY//__/.}" ICE_OPT+=( "$KEY=$VAL" ) continue;; sysdwrap_* ) continue;; bandwidth ) case "$VAL" in *k ) let VAL="${VAL%k} * 1000";; *K ) let VAL="${VAL%k} * 1024";; esac;; esac echo "$KEY=$VAL" done echo echo "[Ice]" printf '%s\n' "${ICE_OPT[@]}" } sysdwrap "$@"; exit $? <file_sep>/src/dontAutostartDefaultMurmur.mjs // -*- coding: utf-8, tab-width: 2 -*- import facts from './facts'; const { muSvc, } = facts; const EX = async function dontAutostartDefaultMurmur(bun) { await bun.needs('admFile', [ /* unreliable. // import sysdWants from 'ubborg-sysd-wants'; sysdWants.preset({ path: '90-dont-autostart-default-murmur', // higher number = weaker content: 'disable ' + muSvc, }), */ { path: '90-dont-autostart-default-murmur.conf', pathPre: '/lib/systemd/system/' + muSvc + '.d/', mimeType: 'static_ini', content: { Unit: { ConditionFirstBoot: true } }, // [2020-12-30} Apparently, having any config for ${muSvc} prevents // systemd-sysv-generator from adding a service unit based on // /etc/init.d/mumble-server. }, ]); }; export default EX; <file_sep>/docs/sysdwrap.md  Configuring the systemd wrapper for murmurd ------------------------------------------- The important concepts at work here are: * The _instance directory_, i.e. `/var/lib/mumble-server/${svcName}`. * This will be the working directory where the server will be run. * It's also the default place for the database. * The systemd _service unit_ file created from [`src/svcUnitTemplate.mjs`](../src/svcUnitTemplate.mjs). * The _wrapper_ script [`src/sysdwrap.sh`](../src/sysdwrap.sh). Look here for default settings. The condition setting in the _service unit_ ensures that the server is only run on hosts where the _instance directory_ exists. There, the _wrapper_ will create an ini file based on * the default settings. (weakest) * ini files in subdirectory `cfg` (`${instanceDir}/cfg/*.ini`), so you can partially override specific settings using files that may or may not be there, just like with systemd drop-in files. * Ice settings don't need a section; they're identified by their names starting with `Ice.`. * Indentation is ignored. * Space characters around the first `=` in each line will be ignored. * Line comments are ignored. That's any line starting with `;` or `#`. * environment variables starting with `murmur_`. (strongest) * Usually you won't need this, but maybe you like actual systemd drop-in files better than the `cfg/*.ini` method. * For keys that contain dots (probably Ice settings), you have to replace those dots with double underscores (`__`). * Remember to `systemctl daemon-reload` before you `systemctl restart $svcName.service`. … and then invoke a murmurd for that generated ini file. <file_sep>/src/homeFile.mjs // -*- coding: utf-8, tab-width: 2 -*- import mapMerge from 'map-merge-defaults-pmb'; import facts from './facts'; const EX = async function homeFile(bun, specs) { await bun.needs('userFile', mapMerge(EX.defaults, 'path', [].concat(specs))); }; EX.defaults = { owner: facts.muSrv, pathPre: facts.muHome + '/', inheritOwnerWithin: facts.muHome, }; export default EX; <file_sep>/README.md  <!--#echo json="package.json" key="name" underline="=" --> ubborg-sysd-murmurd-pmb ======================= <!--/#echo --> <!--#echo json="package.json" key="description" --> Ubborg config generator for murmurd (mumble-server VoIP) with better systemd startup. <!--/#echo --> API --- This module exports one function: ### setupMurmurd(bun, opt) `bun` is the ubborg bundle on whose behalf all requests shall be issued. `opt` is an optional options object that supports these optional keys: * `debPkg`: Whether and which apt package to install as the server. * `true` (default): Install the default package. * `false`: Don't install, just prepare for installing it. * any string or array: Use these package names. * `userIdNum`: UID to use for the murmur user account. `0` (default) = Don't create the account. * `groupIdNum`: GID to use for the murmur user group. Ignored unless `uid` is set, too. `0` (defalt) = same as UID. * `putIni`: (See chapter "Configuration" below.) An array of config lines (i.e., strings) to put in `/var/lib/mumble-server/${svcName}/cfg/local.ini`. A charset header line might be written in front of your config lines. May also be a dictionary object that maps basenames to such arrays, in which case separate ini files `${basename}.ini` will be created with the lines from the array. <!--#toc stop="scan" --> Configuration ------------- see [docs/sysdwrap.md](docs/sysdwrap.md) Known issues ------------ * Needs more/better tests and docs. &nbsp; License ------- <!--#echo json="package.json" key=".license" --> ISC <!--/#echo --> <file_sep>/src/svcUnitTemplate.mjs // -*- coding: utf-8, tab-width: 2 -*- import dictToEnvPairs from 'dict-to-env-pairs-pmb'; import facts from './facts'; const { muHome, muWrap, muSrv, } = facts; function svcUnitTemplate(svcName) { const instanceDir = `${muHome}/%N`; return { mimeType: 'static_ini; speq', // ubborg's mimeFx magic at work pathPre: '/lib/systemd/system/', path: svcName, pathSuf: '.service', content: { Unit: { ConditionPathIsDirectory: instanceDir, }, Service: { SyslogIdentifier: '%N', User: muSrv, Group: muSrv, WorkingDirectory: instanceDir, ExecStart: ['', `${muHome}/${muWrap} envcfg dircfg:cfg/ serve`], // ^- Hard-coded muHome: systemd v245 doesn't support a placeholder // for the service user's home directory (only homedir of the // user that runs systemd itself). We cannot use paths relative // to the WorkingDirectory either, error message would be // "Neither a valid executable name nor an absolute path". Environment: dictToEnvPairs({ registerName: '%N@%H', welcometext: 'Welcome to %N@%H.', }, { pfx: '"murmur_', suf: '"' }), ProtectSystem: 'full', PrivateDevices: true, PrivateTmp: true, }, }, }; } export default svcUnitTemplate; <file_sep>/src/homeSymDir.mjs // -*- coding: utf-8, tab-width: 2 -*- import mustBe from 'typechecks-pmb/must-be'; import mapMerge from 'map-merge-defaults-pmb'; import facts from './facts'; const { muHome, muSrv, } = facts; const EX = async function homeSymDir(bun, dest) { mustBe('undef | nonEmpty str', 'homeSymDest')(dest); if (!dest) { return; } await bun.needs('userFile', mapMerge({ owner: muSrv }, 'path', [ `${muHome} =-> ${dest}/`, `${dest}/`, // <-- Set owner of link target ])); }; export default EX;
0b2e6b71002b548bf0d0fb8c80459061c35c1252
[ "JavaScript", "Markdown", "Shell" ]
8
JavaScript
mk-pmb/ubborg-sysd-murmurd-pmb-js
c491c562f5201f3da987d3a890cefbde19c20e80
4adf5c197a6b7b66e2c8c13ccf38038f776e203f
refs/heads/master
<file_sep>class Tetris { constructor() { this.velY = 1; this.velX = 0; this.gameOver = false; this.playfieldSize = createVector(10, 20); this.placedBlocks = []; for (let i = 0; i < 21; i += 1) { this.placedBlocks[i] = []; } this.spawnNewForm(false); } updateY() { this.updatePos(0, this.velY); } updateX() { this.updatePos(this.velX, 0); this.velX = 0; } updatePos(velX, velY) { for (let row = 0; row < this.blockFormation.length; row += 1) { for (let column = 0; column < this.blockFormation[row].length; column += 1) { if (!this.blockFormation[row][column]) { continue; } let nextPosX = tetris.blockLocation.x - 1 + column + velX; let nextPosY = tetris.blockLocation.y + row + velY; let nextPos = createVector(nextPosX, nextPosY); if (this.isColliding(nextPos)) { if (nextPos.y == 2) { this.gameOver = true; return; } // if the block lands ON another block if (velY != 0) { this.spawnNewForm(true); } return true; } if (nextPos.x < 0 || nextPos.x >= 10) { return; } } } this.blockLocation.x += velX; this.blockLocation.y += velY; } spawnNewForm(saveOldBlock) { if (saveOldBlock) { for (let row = 0; row < this.blockFormation.length; row += 1) { for (let column = 0; column < this.blockFormation[row].length; column += 1) { if (!this.blockFormation[row][column]) { continue; } let posX = tetris.blockLocation.x - 1 + column; let posY = tetris.blockLocation.y + row; append(this.placedBlocks[posY], posX); } } } this.checkFullRowsAndMoveDown(); this.blockLocation = createVector(5, 1); this.blockFormation = [ [0, 1, 0], [1, 1, 1], [0, 0, 0] ]; } checkFullRowsAndMoveDown() { for (let row = 0; row < this.placedBlocks.length; row += 1) { if (this.placedBlocks[row].length >= 10) { this.removeRow(row); this.moveBlocksDown(row); } } } removeRow(row) { print("removing row " + row); this.placedBlocks[row] = []; } moveBlocksDown(underHeight) { print("Moving rows under " + underHeight + " down!"); for (let row = underHeight - 1; row > 1; row -= 1) { this.placedBlocks[row + 1] = this.placedBlocks[row]; } } isColliding(nextPos) { if (nextPos.y < 1) { return false; } // if the block is touching the floor if (nextPos.y > this.playfieldSize.y) { return true; } // check through all the blocks - if they are touching for (let i = 0; i < this.placedBlocks[nextPos.y].length; i += 1) { if (this.placedBlocks[nextPos.y][i] == nextPos.x) { return true; } } return false; } }<file_sep># tetris Using p5.js, this is an extremely simple script, to play tetris. Controls via A & D, hold S to rise gravity # Demonstration Link to a running demonstration: https://moritzlaichner.github.io/p5.js-projects/tetris/ # What I Learned * "==" vs "===" vs ".equals()" * javascript class syntax * p5.js scaling, key input & editor<file_sep># PI-estimator Using p5.js, this is a simple program to estimate PI. The idea is from The Coding Train Youtube Channel. # Demonstration Link to a running demonstration: https://moritzlaichner.github.io/p5.js-projects/PI-estimation/ GIF: ![showcase](https://user-images.githubusercontent.com/47506586/52718557-0a921a80-2fa4-11e9-971d-c0d79ca3c6d1.gif) # What I Learned * p5.js basic javascript syntax * p5.js simple drawing on canvas <file_sep>function setup() { createCanvas(400, 420); } function random(max){ return Math.floor(Math.random()*max + 1); } var amountCircle = 0; var total = 0; var closest = 99.99; function draw() { fill(color(255,255,255)); background(0); ellipse(200, 200, 400, 400); var x = random(400); var y = random(400); total += 1; // if the pixel is white if (get(x,y)[0] == 255){ amountCircle += 1; } var pi = 4 * (amountCircle / total); if (Math.abs(Math.PI - closest) > Math.abs(Math.PI - pi)){ closest = pi; } fill(color(200,200,200)); rect(-1,400,401,50); fill(color(255,255,255)); text("Pi estimate: "+pi, 3, 416); text("Closest to Pi: "+closest, 230, 416); fill(color(10,200,10)); ellipse(x, y, 10, 10); }<file_sep># p5.js-projects This is a collection of my p5.js projects. I'm trying to to consolidate my JavaScript knowledge and learn p5.js. # Project demos Here is a list of demos of my projects: * Tetris: https://moritzlaichner.github.io/p5.js-projects/tetris/ * PI-Estimator: https://moritzlaichner.github.io/p5.js-projects/PI-estimation/
dc018d9aec9ebf99231ed2a82355614491d23d3f
[ "JavaScript", "Markdown" ]
5
JavaScript
Moritz-github/p5.js-projects
495d9e505dc006a9806ea852bc584de9912e4abd
4ac33d3a1da5c768c36b86c405e7826bd48d4bb1
refs/heads/master
<repo_name>helberhlm/teste-flink<file_sep>/src/auth/dtos/return-login.dto.ts import { User } from "src/user/entities/user.entity"; export class ReturnLoginDto { token: string; user: User; } <file_sep>/src/auth/services/auth.service.ts import { Injectable, UnauthorizedException, } from '@nestjs/common'; import { UserRepository } from '../../user/repositories/users.repository'; import { InjectRepository } from '@nestjs/typeorm'; import { CreateUserDto } from '../../user/dtos/create-user.dto'; import { User } from '../../user/entities/user.entity'; import { CredentialsDto } from '../dtos/credentials.dto'; import { JwtService } from '@nestjs/jwt'; import { ReturnLoginDto } from '../dtos/return-login.dto'; @Injectable() export class AuthService { constructor( @InjectRepository(UserRepository) private userRepository: UserRepository, private jwtService: JwtService, ) { } async register(createUserDto: CreateUserDto): Promise<User> { const user = await this.userRepository.createUser(createUserDto); return user; } async login(credentialsDto: CredentialsDto): Promise<ReturnLoginDto> { const user = await this.userRepository.checkCredentials(credentialsDto); if (user === null) { throw new UnauthorizedException('Login inválido'); } const jwtPayload = { id: user.id, }; const token = await this.jwtService.sign(jwtPayload); user.password = <PASSWORD> = <PASSWORD>; return { token, user }; } } <file_sep>/src/post/controllers/posts.controller.ts import { Controller, Post, Body, ValidationPipe, Put, Param, Get, UseGuards, Delete } from '@nestjs/common'; import { PostService } from '../services/posts.service'; import { CreatePostDto } from '../dtos/create-post.dto'; import { ReturnPostDto } from '../dtos/return-post.dto'; import { UpdatePostDto } from '../dtos/update-post.dto'; import { ApiTags } from '@nestjs/swagger'; import { AuthGuard } from '@nestjs/passport'; @ApiTags('Posts') @Controller('posts') @UseGuards(AuthGuard()) export class PostsController { constructor(private postsService: PostService) { } @Post() async createPost( @Body(ValidationPipe) createPostDto: CreatePostDto, ): Promise<ReturnPostDto> { const post = await this.postsService.createPost(createPostDto); return { post, message: 'Post criado com sucesso!' }; } @Put(':id') async updatePost( @Body(ValidationPipe) updatePostDto: UpdatePostDto, @Param('id') id: string, ) { return this.postsService.updatePost(updatePostDto, id); } @Get(':id') async getPost( @Param('id') id: string, ) { return this.postsService.getPost(id); } @Get() async indexPosts() { return this.postsService.findPosts(); } @Delete(':id') async deletePost(@Param('id') id: string) { return this.postsService.deletePost(id); } } <file_sep>/README.md <p align="center"> <a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo_text.svg" width="320" alt="Nest Logo" /></a> </p> ## Descrição Teste de backend feito em NestJS Esta aplicação utiliza TypeORM e Postgres como banco de dados Principal. Foram utilizadas as boas práticas conforme orientadas pelo framework, com o código dividido em módulos, onde cada módulo possui subpastas para alocar os *Controllers, Services, Repositories e Entities* entre outro. Dessa forma, têm-se agrupado os arquivos de mesmas categorias, ficando apenas os arquivos **.modules.ts* na raiz de cada módulo. ![Lista de Arquivos](assets/tree.png) Também foi inserido o arquivo Dockerfile ao projeto para facilitar a criação de imagem Docker deste projeto. ## Instalação Primeiro baixe o projeto usando o git ```bash $ git clone https://github.com/helberhlm/teste-flink.git ``` Após baixar o repositório, navegue até a pasta do projeto e dê o comando ```bash $ npm install ``` ## Configurações Com um editor de texto de sua preferência, edite o arquivo `src\config\typeorm.config.ts` e insira as configurações referentes à conexão com o banco de dados Postgres. ![Configuração do Banco de Dados](assets/bdconfig.png) ## Execução Para dar início à aplicação, escolha um dos três modos a seguir ```bash # Desenvolvimento $ npm run start # Desenvolvimento com atualizações a cada alteração $ npm run start:dev # Produção $ npm run start:prod ``` Quando executando em modo de desenvolvimento com atualizações a cada alteração, o terminal deve apresentar resultado semelhante à este: ![Terminal](assets/terminal.png) ## Acessando o sistema O sistema irá executar em `http://localhost:3000` A documentação das rotas disponíveis pode ser encontrada em `http://localhost:3000/swagger/` ![Swagger](assets/swagger.png) É possível testar os endpoints da aplicação pela própria documentação ou por outros clientes rest, no caso dos prints a seguir, foi o usado o Insomnia. ##### Users index ![Users index](assets/index_users.png) ##### User Profile ![User Profile](assets/profile.png) ##### User Register ![User Register](assets/register.png) ##### Post Create ![Post Create](assets/post_create.png) ##### Posts Index ![Posts Index](assets/post_index.png) ## Testes Para esta aplicação foram escritos testes unitários que verificam a integridade do código. > Os testes devem executar sem apresentar erros. ```bash # Testes unitários $ npm run test ``` ## Licença Nest is [MIT licensed](LICENSE). <file_sep>/src/app.module.ts import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import * as Joi from '@hapi/joi'; import { UsersModule } from './user/users.module'; import { PostsModule } from './post/posts.module'; import { TypeOrmModule } from '@nestjs/typeorm'; import { typeOrmConfig } from './config/typeorm.config'; import { AuthModule } from './auth/auth.module'; @Module({ imports: [ // ConfigModule.forRoot({ // validationSchema: Joi.object({ // POSTGRES_HOST: Joi.string().required(), // POSTGRES_PORT: Joi.number().required(), // POSTGRES_USER: Joi.string().required(), // POSTGRES_PASSWORD: Joi.string().required(), // POSTGRES_DB: Joi.string().required(), // JWT_SECRET: Joi.string().required(), // PORT: Joi.number(), // }) // }), TypeOrmModule.forRoot(typeOrmConfig), AuthModule, UsersModule, PostsModule, ], controllers: [], providers: [], }) export class AppModule { } <file_sep>/src/post/services/posts.service.ts import { Injectable, NotFoundException } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { PostRepository } from '../repositories/posts.repository'; import { CreatePostDto } from '../dtos/create-post.dto'; import { Post } from '../entities/posts.entity'; import { UpdatePostDto } from '../dtos/update-post.dto'; @Injectable() export class PostService { constructor( @InjectRepository(PostRepository) private postRepository: PostRepository, ) { } async createPost(createPostDto: CreatePostDto): Promise<Post> { return this.postRepository.createPost(createPostDto); } async getPost(postId: string): Promise<Post> { const post = await this.postRepository.findOnePost(postId); if (!post) throw new NotFoundException('Post não encontrado'); return post; } async findPosts(): Promise<Post[]> { const posts = await this.postRepository.findPosts(); return posts; } async updatePost(updatePostDto: UpdatePostDto, id: string): Promise<Post> { const result = await this.postRepository.updatePost(updatePostDto, id); return result; } async deletePost(id: string) { const result = await this.postRepository.delete({ id }); if (result.affected === 0) { throw new NotFoundException( 'Não foi encontrado post com o ID informado', ); } } } <file_sep>/src/post/posts.module.ts import { Module } from '@nestjs/common'; import { PassportModule } from '@nestjs/passport'; import { TypeOrmModule } from '@nestjs/typeorm'; import { PostsController } from './controllers/posts.controller'; import { PostRepository } from './repositories/posts.repository'; import { PostService } from './services/posts.service'; @Module({ imports: [ TypeOrmModule.forFeature([PostRepository]), PassportModule.register({ defaultStrategy: 'jwt' }), ], controllers: [PostsController], providers: [PostService], exports: [PostService] }) export class PostsModule { } <file_sep>/src/post/dtos/find-posts-query-dto.ts import { BaseQueryParametersDto } from '../../common/dto/base-query-paramers.dto'; export class FindPostsQueryDto extends BaseQueryParametersDto { title: string; description: string; } <file_sep>/src/post/entities/posts.entity.ts import { BaseEntity, Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn, } from 'typeorm'; @Entity() export class Post extends BaseEntity { @PrimaryGeneratedColumn() id: string; @Column({ nullable: false, type: 'varchar', length: 200 }) title: string; @Column({ nullable: false, type: 'varchar', length: 200 }) description: string; @Column({ nullable: false, type: 'varchar', length: 200 }) image: string; @CreateDateColumn() createdAt: Date; @UpdateDateColumn() updatedAt: Date; } <file_sep>/src/user/controllers/users.controller.ts import { Controller, Post, Body, ValidationPipe, UseGuards, Get, Param, Delete, Put, Req, } from '@nestjs/common'; import { ApiTags } from '@nestjs/swagger'; import { CreateUserDto } from '../dtos/create-user.dto'; import { UsersService } from '../services/users.service'; import { ReturnUserDto } from '../dtos/return-user.dto'; import { AuthGuard } from '@nestjs/passport'; import { UpdateUserDto } from '../dtos/update-user.dto'; import { User } from '../entities/user.entity'; @ApiTags('Users') @Controller('users') @UseGuards(AuthGuard()) export class UsersController { constructor(private usersService: UsersService) { } @Post() async createAdminUser( @Body(ValidationPipe) createUserDto: CreateUserDto, ): Promise<ReturnUserDto> { const user = await this.usersService.createUser(createUserDto); return { user, message: 'Administrador cadastrado com sucesso', }; } @Get(':id') async findUserById(@Param('id') id): Promise<ReturnUserDto> { const user = await this.usersService.findUserById(id); return { user, message: 'Usuário encontrado', }; } @Put() async updateUser( @Body(ValidationPipe) updateUserDto: UpdateUserDto, @Req() req, ) { return this.usersService.updateUser(updateUserDto, req.user.id); } @Delete(':id') async deleteUser(@Param('id') id: string) { await this.usersService.deleteUser(id); return { message: 'Usuário excluído com sucesso', }; } @Get() async findUsers(): Promise<User[]> { const users = await this.usersService.findUsers(); return users; } } <file_sep>/src/user/services/users.service.ts import { Injectable, NotFoundException, } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { UserRepository } from '../repositories/users.repository'; import { CreateUserDto } from '../dtos/create-user.dto'; import { User } from '../entities/user.entity'; import { UpdateUserDto } from '../dtos/update-user.dto'; @Injectable() export class UsersService { constructor( @InjectRepository(UserRepository) private userRepository: UserRepository, ) { } async createUser(createUserDto: CreateUserDto): Promise<User> { return this.userRepository.createUser(createUserDto); } async findUserById(userId: string): Promise<User> { const user = await this.userRepository.findOne(userId, { select: ['email', 'name', 'id'], }); if (!user) throw new NotFoundException('Usuário não encontrado'); return user; } async updateUser(updateUserDto: UpdateUserDto, id: string) { const result = await this.userRepository.update({ id }, updateUserDto); if (result.affected > 0) { const user = await this.findUserById(id); return user; } else { throw new NotFoundException('Usuário não encontrado'); } } async deleteUser(userId: string) { const result = await this.userRepository.delete({ id: userId }); if (result.affected === 0) { throw new NotFoundException( 'Não foi encontrado um usuário com o ID informado', ); } } async findUsers(): Promise<User[]> { const users = await this.userRepository.findUsers(); return users; } } <file_sep>/src/auth/controllers/auth.controller.ts import { Controller, Post, Body, ValidationPipe, Get, UseGuards, Req, } from '@nestjs/common'; import { ApiTags } from '@nestjs/swagger'; import { AuthService } from '../services/auth.service'; import { CreateUserDto } from '../../user/dtos/create-user.dto'; import { CredentialsDto } from '../dtos/credentials.dto'; import { AuthGuard } from '@nestjs/passport'; import { User } from '../../user/entities/user.entity'; import { ReturnLoginDto } from '../dtos/return-login.dto'; @ApiTags('auth') @Controller('auth') export class AuthController { constructor(private authService: AuthService) { } @Post('/register') async register( @Body(ValidationPipe) createUserDto: CreateUserDto, ): Promise<{ message: string }> { await this.authService.register(createUserDto); return { message: 'Usuário criado com sucesso', }; } @Post('/login') async login( @Body(ValidationPipe) credentiaslsDto: CredentialsDto, ): Promise<ReturnLoginDto> { return await this.authService.login(credentiaslsDto); } @Get('/profile') @UseGuards(AuthGuard()) profile(@Req() req): User { return req.user; } } <file_sep>/src/post/dtos/create-post.dto.ts import { ApiProperty } from '@nestjs/swagger'; import { IsNotEmpty, MaxLength, IsUrl } from 'class-validator'; export class CreatePostDto { @ApiProperty() @IsNotEmpty({ message: 'Informe o título do post', }) @MaxLength(200, { message: 'O título do post deve ter menos de 200 caracteres', }) title: string; @ApiProperty() @IsNotEmpty({ message: 'Informe a descrição do post', }) @MaxLength(200, { message: 'A descrição do post deve ter menos de 200 caracteres', }) description: string; @ApiProperty() @IsNotEmpty({ message: 'Informe a url da imagem do post', }) @MaxLength(200, { message: 'A url da imagem do post deve ter menos de 200 caracteres', }) @IsUrl({}, { message: 'A URL informada não é válida' }) image: string; } <file_sep>/src/post/dtos/return-post.dto.ts import { Post } from "../entities/posts.entity"; export class ReturnPostDto { post: Post; message: string; } <file_sep>/src/user/services/users.service.spec.ts import { Test, TestingModule } from '@nestjs/testing'; import { UserRepository } from '../repositories/users.repository'; import { UsersService } from './users.service'; import { CreateUserDto } from '../dtos/create-user.dto'; import { UnprocessableEntityException, NotFoundException, } from '@nestjs/common'; const mockUserRepository = () => ({ createUser: jest.fn(), findOne: jest.fn(), delete: jest.fn(), findUsers: jest.fn(), }); describe('UsersService', () => { let userRepository; let userService; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ providers: [ UsersService, { provide: UserRepository, useFactory: mockUserRepository, }, ], }).compile(); userRepository = await module.get<UserRepository>(UserRepository); userService = await module.get<UsersService>(UsersService); }); it('should be defined', () => { expect(userService).toBeDefined(); expect(userRepository).toBeDefined(); }); describe('createUser', () => { let mockCreateUserDto: CreateUserDto; beforeEach(() => { mockCreateUserDto = { email: '<EMAIL>', name: '<NAME>', password: '<PASSWORD>', }; }); it('should create an user', async () => { userRepository.createUser.mockResolvedValue('mockUser'); const result = await userService.createUser(mockCreateUserDto); expect(userRepository.createUser).toHaveBeenCalledWith( mockCreateUserDto, ); expect(result).toEqual('mockUser'); }); it('should throw an error if passwords is insecure', async () => { mockCreateUserDto.password = '<PASSWORD>'; expect(userService.createUser(mockCreateUserDto)).rejects.toThrow( UnprocessableEntityException, ); }); }); describe('findUserById', () => { it('should return the found user', async () => { userRepository.findOne.mockResolvedValue('mockUser'); expect(userRepository.findOne).not.toHaveBeenCalled(); const result = await userService.findUserById('mockId'); const select = ['email', 'name', 'id']; expect(userRepository.findOne).toHaveBeenCalledWith('mockId', { select }); expect(result).toEqual('mockUser'); }); it('should throw an error as user is not found', async () => { userRepository.findOne.mockResolvedValue(null); expect(userService.findUserById('mockId')).rejects.toThrow(NotFoundException); }); }); }); <file_sep>/src/post/repositories/posts.repository.ts import { InternalServerErrorException } from '@nestjs/common'; import { EntityRepository, Repository } from 'typeorm'; import { CreatePostDto } from '../dtos/create-post.dto'; import { FindPostsQueryDto } from '../dtos/find-posts-query-dto'; import { UpdatePostDto } from '../dtos/update-post.dto'; import { Post } from '../entities/posts.entity'; @EntityRepository(Post) export class PostRepository extends Repository<Post> { async findPosts(): Promise<Post[]> { return await this.find(); } async findOnePost(id: string): Promise<Post> { return await this.findOneOrFail(id); } async createPost( createPostDto: CreatePostDto, ): Promise<Post> { const { title, description, image } = createPostDto; const post = this.create(); post.title = title; post.description = description; post.image = image; try { await post.save(); return post; } catch (error) { throw new InternalServerErrorException( 'Erro ao criar post, tente novamente', ); } } async updatePost( updatePostDto: UpdatePostDto, id: string, ): Promise<Post> { const { title, description, image } = updatePostDto; const post = await this.findOneOrFail(id); post.title = title; post.description = description; post.image = image; try { await post.save(); return post; } catch (error) { throw new InternalServerErrorException( 'Erro ao atualizar post, tente novamente', ); } } } <file_sep>/src/post/controllers/posts.controller.spec.ts import { Test, TestingModule } from '@nestjs/testing'; import { UnprocessableEntityException, NotFoundException, } from '@nestjs/common'; import { PostRepository } from '../repositories/posts.repository'; import { PostService } from '../services/posts.service'; import { CreatePostDto } from '../dtos/create-post.dto'; import { UpdatePostDto } from '../dtos/update-post.dto'; const mockPostRepository = () => ({ createPost: jest.fn(), updatePost: jest.fn(), getPost: jest.fn(), indexPosts: jest.fn(), deletePost: jest.fn(), }); describe('PostService', () => { let postRepository; let postService; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ providers: [ PostService, { provide: PostRepository, useFactory: mockPostRepository, }, ], }).compile(); postRepository = await module.get<PostRepository>(PostRepository); postService = await module.get<PostService>(PostService); }); it('should be defined', () => { expect(postService).toBeDefined(); expect(postRepository).toBeDefined(); }); describe('createPost', () => { let mockCreatePostDto: CreatePostDto; beforeEach(() => { mockCreatePostDto = { title: 'Primeiro Post', description: 'Post de teste', image: 'http://localhost/image.png', }; }); it('should create an post', async () => { postRepository.createPost.mockResolvedValue('mockPost'); const result = await postService.createPost(mockCreatePostDto); expect(postRepository.createPost).toHaveBeenCalledWith(mockCreatePostDto); expect(result).toEqual('mockPost'); }); it('should throw an error if image URL is invalid', async () => { mockCreatePostDto.image = 'wrongURL'; expect(postService.createPost(mockCreatePostDto)).rejects.toThrow( UnprocessableEntityException, ); }); }); describe('updatePost', () => { let mockUpdatePostDto: UpdatePostDto; beforeEach(() => { mockUpdatePostDto = { title: 'Update Post', description: 'Post de teste', image: 'http://localhost/image.png', }; }); it('should update an post', async () => { postRepository.updatePost.mockResolvedValue('mockPost'); const result = await postService.updatePost(mockUpdatePostDto, 1); expect(postRepository.updatePost).toHaveBeenCalledWith(mockUpdatePostDto, 1); expect(result).toEqual('mockPost'); }); it('should throw an error if image URL is invalid', async () => { mockUpdatePostDto.image = 'wrongURL'; expect(postService.createPost(mockUpdatePostDto)).rejects.toThrow( UnprocessableEntityException, ); }); }); describe('indexPosts', () => { it('should index all posts', async () => { postRepository.indexPosts.mockResolvedValue('mockPost'); expect(postRepository.indexPosts).not.toHaveBeenCalled(); }); }); }); <file_sep>/Dockerfile FROM node:12.16.1-alpine RUN rm -rf /var/www && mkdir /var/www WORKDIR /var/www COPY . /var/www RUN rm -rf .env && \ npm install pm2 -g && \ npm install && \ npm run build EXPOSE 3000 ENTRYPOINT npm run start:prod <file_sep>/.env.example DATABASE_HOST=localhost DATABASE_USER= DATABASE_PASSWORD= DATABASE=flink
fe028a69c037795773b3cefbf83f1b2af1fec807
[ "Markdown", "TypeScript", "Dockerfile", "Shell" ]
19
TypeScript
helberhlm/teste-flink
acdf6e36db2cc997d9dffa3c0a8edf3ba6d6870a
386e8830bbcb18911c04c4d9529ec8da9bd28ed5
refs/heads/master
<file_sep>import React, {PureComponent} from 'react'; import Navbar from './Common/Navbar' import Footer from './Common/Footer' import '../styles/App.scss'; class App extends PureComponent { constructor(props) { super(props) this.state = { me: props.me } } render() { return ( <React.Fragment> <Navbar/> <div className="page" data-spy="scroll" data-target="#navbar" data-offset="0"> {this.props.children} </div> <Footer/> </React.Fragment> ); } } export default App; <file_sep>'use strict'; try { var Spooky = require('spooky'); } catch (e) { var Spooky = require('../lib/spooky'); } module.exports = function (Page) { Page.incrementLike = function (pageId, author, cb) { Page .findOne({where: {id: pageId}}, function (err, res) { if (err) { console.log(err); } if (res !== null) { if (typeof res.likes === 'undefined') { res.likes = [author] } else { res.likes.push(author) } res.updateAttributes({"likes": res.likes}, function (err, res) { if (err) { console.log(err); } cb(null, res.likes); }) } }); } Page.remoteMethod('incrementLike', { accepts: [{arg: 'pageId', type: 'string'}, {arg: 'author', type: 'string'}], returns: {arg: 'done', type: 'array'} }); Page.decrementLike = function (pageId, author, cb) { Page .findOne({where: {id: pageId}}, function (err, res) { if (err) { console.log(err); } if (res !== null) { let filtered = res.likes.filter(function (value, index, arr) { return value !== author; }); res.updateAttributes({"likes": filtered}, function (err, res) { if (err) { console.log(err); } cb(null, res.likes); }) } }); } Page.remoteMethod('decrementLike', { accepts: [{arg: 'pageId', type: 'string'}, {arg: 'author', type: 'string'}], returns: {arg: 'done', type: 'array'} }); Page.incrementView = function (pageId, cb) { Page .findOne({where: {id: pageId}}, function (err, res) { if (err) { console.log(err); } if (res !== null) { if (res.views === '' || isNaN(res.views)) { res.views = 0 } console.log('res.views', res.views) res.views = res.views / 1 + 1 res.updateAttributes({"views": res.views}, function (err, res) { if (err) { console.log(err); } cb(null, true); }) } }); } Page.remoteMethod('incrementView', { accepts: {arg: 'pageId', type: 'string'}, returns: {arg: 'done', type: 'boolean'} }); Page.getAdvertDetails = function (url, cb) { console.log('__________getAdvertDetails___________'); console.log(url) let res = url.split("|||") let pageId = res[0] url = res[1] var spooky = new Spooky({ child: { //transport: 'http' }, casper: { logLevel: 'debug', clientScripts: ["/var/www/parser/server/jquery.min.js"], verbose: true }, cb: cb }, function (err) { if (err) { console.log(err) let e = new Error('Failed to initialize SpookyJS'); e.details = err; throw e; } let imgPath = '/var/www/parser/client/public/images/'; console.log('url') console.log(url) // url = 'https://sport.bazos.cz/inzerat/105820564/MaO.php' spooky.start(url); let cz = url.search(".cz") + 1; let fr = url.search(".fr") + 1; let it = url.search(".it") + 1; let local = 'undefined' if (cz) { spooky.then([{imgPath: imgPath, url: url, x: 100, y: 100}, function () { this.wait(5000, function () { this.then(function () { //this.captureSelector(this.imgPath + "page.png", "html"); var result = this.evaluate(function () { return $("div.popis").html(); }); var subcat = this.evaluate(function () { return $("#zvyraznenikat").html(); }); this.emit('getAdvertDescCz', result + '|||' + subcat); }) this.then(function () { var result = this.evaluate(function () { return $("td.listadvlevo").html(); }); this.emit('getAdvertMoreDescCz', result); }) this.then(function () { var result = this.evaluate(function () { var images = $(".flinavigace").find('img'); return Array.prototype.map.call(images, function (e) { return e.getAttribute('src'); }); }); this.emit('getAdvertImgsCz', result); }); }); }]); spooky.on('getAdvertDescCz', function (textandsubcat) { console.log('__________getAdvertDesc___________'); console.log(textandsubcat); const arr = textandsubcat.split('|||') const text = arr[0] const subcat = arr[1] if (text !== null) { Page .findOne({where: {id: pageId}}, function (err, res) { if (err) { console.log(err); } if (res !== null) { res.updateAttributes({"text": text, "subcategory": subcat}, function (err, res) { if (err) { console.log(err); } console.log(res); }) } }); } else { console.log('pageId ' + pageId + ' disable'); Page .findOne({where: {id: pageId}}, function (err, res) { if (err) { console.log(err); } if (res !== null) { res.updateAttributes({"active": false}, function (err, res) { if (err) { console.log(err); } console.log(res); }) } }); } }); spooky.on('getAdvertMoreDescCz', function (text) { console.log('__________getAdvertMoreDesc___________'); let name = /jmeno=(.*?)\"/.exec(text) console.log('name') const nameDb = name[1] console.log(nameDb) console.log(typeof nameDb) let phone = /telefon=(.*?)&amp/.exec(text) console.log('phone') const phoneDb = phone[1] console.log(phoneDb) console.log(typeof phoneDb) let price = /b>(.*?)Kč</.exec(text) console.log('price') let priceDb = price[1] if (!priceDb) { priceDb = 'NaN' } console.log(priceDb) console.log(typeof priceDb) let location = /lokalita" rel="nofollow">(.*?)</.exec(text) console.log('location') const locationDb = location[1] console.log(locationDb) console.log(typeof locationDb) let locationurl = /place\/(.*?)\"/.exec(text) console.log('location') const locationurlDb = 'https://www.google.com/maps/place/' + locationurl[1] console.log(locationurlDb) console.log(typeof locationurlDb) Page .findOne({where: {id: pageId}}, function (err, res) { if (err) { console.log(err); } if (res !== null) { res.updateAttributes({ "author_name": nameDb, "phone": phoneDb, "price": priceDb, "currency": 'kč', "locality": locationDb, "localityurl": locationurlDb, "parsed": true }, function (err, res) { if (err) { console.log(err); } }) } }); }); spooky.on('getAdvertImgsCz', function (images) { console.log('__________getAdvertImgs___________'); Page .findOne({where: {id: pageId}}, function (err, res) { if (err) { console.log(err); } if (res !== null) { res.updateAttributes({"donor_images": images, "active": true}, function (err, res) { if (err) { console.log(err); } console.log(images); spooky.options.cb(null, true); }) } }); }); } if (it) { console.log('it') spooky.then([{imgPath: imgPath, url: url, x: 100, y: 100}, function () { this.wait(5000, function () { this.then(function () { var result = this.evaluate(function () { return $(".description").html(); }); this.emit('getAdvertDescIt', result); }) this.then(function () { var result = this.evaluate(function () { var subcat = $(".feature").find('.value').html(); var breadcrumbs = $(".breadcrumbs-container").html(); if (breadcrumbs.indexOf('vendita') + 1) { var adType = 'sell' } else if (breadcrumbs.indexOf('compra') + 1) { var adType = 'buy' } else { var adType = 'other' } return subcat + ':::' + adType }); this.emit('getAdvertMoreDescIt', result); }) this.then(function () { var result = this.evaluate(function () { var images = $(".carousel").find('img'); return Array.prototype.map.call(images, function (e) { return e.getAttribute('src') }); }); this.emit('getAdvertImgsIt', result); }); }); }]); spooky.on('getAdvertDescIt', function (text) { console.log('__________getAdvertDescIt___________'); if (text !== null) { Page .findOne({where: {id: pageId}}, function (err, res) { if (err) { console.log(err); } if (res !== null) { res.updateAttributes({"text": text}, function (err, res) { if (err) { console.log(err); } console.log(res); }) } }); } else { console.log('pageId ' + pageId + ' disable'); Page .findOne({where: {id: pageId}}, function (err, res) { if (err) { console.log(err); } if (res !== null) { res.updateAttributes({"active": false}, function (err, res) { if (err) { console.log(err); } console.log(res); }) } }); } }); spooky.on('getAdvertMoreDescIt', function (detailsArr) { //feature console.log('detailsArr') console.log(detailsArr) let authorAndPnone = detailsArr.split(':::'); let author = '' let phone = '' let subcat = authorAndPnone[0]; let type = authorAndPnone[1]; let price = 0 let currency = '' let placeit = 0 if (subcat === 'undefined') { subcat = 'Altro' } Page .findOne({where: {id: pageId}}, function (err, res) { if (err) { console.log(err); } if (res !== null) { res.updateAttributes({ "author_name": author, "price": price, "currency": currency, "phone": phone, "locality": placeit, "subcategory": subcat, "type": type, "parsed": true }, function (err, res) { if (err) { console.log(err); } console.log(res); }) } }); }); spooky.on('getAdvertImgsIt', function (images) { console.log('__________getAdvertImgsIt___________'); console.log(images); Page .findOne({where: {id: pageId}}, function (err, res) { if (err) { console.log(err); } if (res !== null) { res.updateAttributes({"donor_images": images, "active": true}, function (err, res) { if (err) { console.log(err); } console.log(res); // console.log(images); spooky.options.cb(null, true); }) } }); }); } if (fr) { local = 'fr' } spooky.run(); }); } Page.remoteMethod('getAdvertDetails', { accepts: {arg: 'url', type: 'string'}, returns: {arg: 'done', type: 'boolean'} }); Page.pendingList = function (local, cb) { console.log('__________pendingList___________'); let urls = [] if (typeof local == 'undefined') { Page.find({where: {text: 'pending'}}, function (err, data) { if (err) { console.log(err) } if (data) { if (data.length) { data.map(x => { console.log(x.id) if (x.id) { let url = '' if (x.local == 'it') { url = x.url } if (x.local == 'cz') { url = x.urlcategory + x.url } urls.push(x.id + '|||' + url) } }) } console.log(urls) cb(null, urls) } }); } else { Page.find({where: {and: [{text: 'pending'}, {local: local}]}}, function (err, data) { if (err) { console.log(err) } if (data) { if (data.length) { data.map(x => { console.log(x.id) if (x.id) { let url = '' if (x.local == 'it') { url = x.url } if (x.local == 'cz') { url = x.urlcategory + x.url } urls.push(x.id + '|||' + url) } }) } console.log(urls) cb(null, urls) } }); } } Page.remoteMethod('pendingList', { accepts: {arg: 'local', type: 'string'}, http: {path: '/pendingList', verb: 'get'}, returns: {arg: 'urls', type: 'any'} }); Page.saveTitles = function (pagesArr, category, catid, catname, cb) { console.log('__________saveTitles___________'); console.log(catid, catname); let cz = category.search(".cz") + 1; let fr = category.search(".fr") + 1; let it = category.search(".it") + 1; let local = 'undefined' if (cz) { local = 'cz' } if (fr) { local = 'fr' } if (it) { local = 'it' } let ids = [] console.log(pagesArr.pages) pagesArr.pages.map(x => { Page.findOrCreate({ "local": local, "title": x[0], "url": x[1], "urlcategory": category, "category": catid, "category_title": catname, "subcategory": '', "type": '', "text": 'pending', "donor": true, "images": '', "donor_images": [], "edited": false, "author": '5<PASSWORD>', "phone": '', "locality": '', "localityurl": '', "price": '', "currency": '', "tags": '', "views": 0, "likes": [], "comment": '', "commenttype": 'hidden', "parsed": false, "active": false }, function (err, data) { if (err) { console.log(err) ids.push('error') } if (data) { const timestamp = data.id.toString().substring(0, 8) const date = new Date(parseInt(timestamp, 16) * 1000) ids.push(data.id + ' ' + category + ' ' + date) console.log(data) if (pagesArr.pages.length == ids.length) { cb(null, ids) } } }); }) } Page.remoteMethod('saveTitles', { accepts: [{arg: 'pages', type: 'any'}, {arg: 'category', type: 'any'}, { arg: 'catid', type: 'any' }, {arg: 'catname', type: 'any'}], returns: {arg: 'ids', type: 'any'} }); Page.pages = function (url, cb) { var spooky = new Spooky({ child: { //transport: 'http' }, casper: { logLevel: 'debug', clientScripts: ["/var/www/parser/server/jquery.min.js"], verbose: true }, cb: cb }, function (err) { if (err) { console.log(err) let e = new Error('Failed to initialize SpookyJS'); e.details = err; throw e; } let imgPath = '/var/www/parser/client/public/images/'; console.log(url) spooky.start(url); spooky.then([{imgPath: imgPath, url: url, x: 100, y: 100}, function () { this.wait(5000, function () { this.then(function () { // this.captureSelector(this.imgPath + "page.png", "html"); var result = this.evaluate(function () { // let desc = $( "div.popis" ).html(); var images = $(".flinavigace").find('img'); return Array.prototype.map.call(images, function (e) { return [1, e.getAttribute('src').replace("t/", "/")]; }); }); this.emit('getCategoryPage', result); }); }); }]); spooky.on('getCategoryPage', function (pages) { console.log('__________getCategoryPage___________'); console.log(pages); spooky.options.cb(null, pages); }); spooky.run(); }); } Page.remoteMethod('page', { accepts: {arg: 'url', type: 'string'}, returns: {arg: 'page', type: 'string'} }); /* Page.remoteMethod('destroyAll', { description: 'Delete all matching records.', accessType: 'WRITE', accepts: [ {arg: 'where', type: 'object', description: 'filter.where object'}, {arg: 'options', type: 'object', http: 'optionsFromRequest'}, ], returns: { arg: 'count', type: 'object', description: 'The number of instances deleted', root: true, }, http: {verb: 'del', path: '/'}, // shared: false, });*/ Page.countCat = function (local, cb) { if (typeof local === 'undefined') { let local = 'en' } //parsed: true Page.find({where: {and: [{active: true}, {local: local}]}}, function (err, data) { if (err) { console.log(err) } if (data) { if (data.length) { console.log('data ------------------------------------ data ------------------------------------') console.log(data.length) let countCatArr = [] let resp = [] data.forEach((item) => { countCatArr.push(item.category_title) }) let countCats = () => { let array_elements = countCatArr; array_elements.sort(); var current = null; var cnt = 0; for (var i = 0; i < array_elements.length; i++) { if (array_elements[i] != current) { if (cnt > 0) { let count = {} count.category = current count.times = cnt resp.push(count); } current = array_elements[i]; cnt = 1; } else { cnt++; } } if (cnt > 0) { let count = {} count.category = current count.times = cnt resp.push(count); } } countCats() cb(null, resp) } } }); } Page.remoteMethod('countCat', { accepts: {arg: 'local', type: 'string'}, http: {path: '/countCat', verb: 'get'}, returns: {arg: 'resp', type: 'any'} }); } process.on('unhandledRejection', function (err) { throw err; }); process.on('uncaughtException', function (err) { console.log(err) })<file_sep>'use strict'; try { var Spooky = require('spooky'); } catch (e) { var Spooky = require('../lib/spooky'); } module.exports = function (Container) { Container.page = function (url, cb) { var spooky = new Spooky({ child: { //transport: 'http' }, casper: { logLevel: 'debug', clientScripts: ["/var/www/parser/server/jquery.min.js"], verbose: true }, cb: cb }, function (err) { if (err) { console.log(err) e = new Error('Failed to initialize SpookyJS'); e.details = err; throw e; } let imgPath = '/var/www/parser/client/public/images/'; console.log(url) spooky.start(url); spooky.then([{imgPath: imgPath, url: url, x: 100, y: 100}, function () { this.imgPath = imgPath; this.url = url; this.x = x; this.y = y; this.width = 450; var proportion = this.width / this.x; this.height = Math.floor(proportion * this.y); this.wait(5000, function () { // this.callb(null, 'Greetings... '); this.then(function () { //todo: param cat name this.captureSelector(this.imgPath + "page.png", "html"); var result = this.evaluate(function () { // let desc = $( "div.popis" ).html(); var images = $(".flinavigace").find('img'); return Array.prototype.map.call(images, function (e) { return [1, e.getAttribute('src').replace("t/", "/")]; }); /* return Array.prototype.map.call(links, function (e) { return [e.innerHTML, e.getAttribute('href')]; });*/ // return linksArrStr; }); this.emit('getCategoryPage', result); }); }); }]); // spooky.then(function () { // this.emit('hello', 'Hello, from ' + this.evaluate(function () { // return document.title; // })); // }); spooky.on('getCategoryPage', function (greeting) { console.log('__________getCategoryPage___________'); console.log(greeting); spooky.options.cb(null, greeting); }); spooky.run(); }); } Container.remoteMethod('page', { accepts: {arg: 'url', type: 'string'}, returns: {arg: 'greeting', type: 'string'} }); Container.category = function (url, cb) { var spooky = new Spooky({ child: { //transport: 'http' }, casper: { logLevel: 'debug', clientScripts: ["/var/www/parser/server/jquery.min.js"], verbose: true }, cb: cb }, function (err) { if (err) { console.log(err) e = new Error('Failed to initialize SpookyJS'); e.details = err; throw e; } let imgPath = '/var/www/parser/client/public/images/'; console.log(url) spooky.start(url); spooky.then([{imgPath: imgPath, url: url, x: 100, y: 100}, function () { this.imgPath = imgPath; this.url = url; this.x = x; this.y = y; this.width = 450; var proportion = this.width / this.x; this.height = Math.floor(proportion * this.y); this.wait(5000, function () { // this.callb(null, 'Greetings... '); this.then(function () { //todo: param cat name this.captureSelector(this.imgPath + "category.png", "html"); var result = this.evaluate(function () { var links = $(".nadpis").find('a'); return Array.prototype.map.call(links, function (e) { return [e.innerHTML, e.getAttribute('href')]; }); // return linksArrStr; }); this.emit('getCategoryTopics', result); }); }); }]); // spooky.then(function () { // this.emit('hello', 'Hello, from ' + this.evaluate(function () { // return document.title; // })); // }); spooky.on('getCategoryTopics', function (greeting) { console.log('__________getCategoryTopics___________'); console.log(greeting); spooky.options.cb(null, greeting); }); spooky.run(); }); } Container.remoteMethod('category', { accepts: {arg: 'url', type: 'string'}, returns: {arg: 'greeting', type: 'string'} }); Container.greet = function (msg, cb) { //clientScripts: ['../public/javascripts/jquery.min.js'] var spooky = new Spooky({ child: { //transport: 'http' }, casper: { logLevel: 'debug', clientScripts: ["/var/www/parser/server/jquery.min.js"], verbose: true }, cb: cb }, function (err) { if (err) { e = new Error('Failed to initialize SpookyJS'); e.details = err; throw e; } let imgPath = '/var/www/parser/client/public/images/'; let url = 'https://www.bazos.cz'; spooky.start(url); spooky.then([{imgPath: imgPath, url: url, x: 100, y: 100}, function () { this.imgPath = imgPath; this.url = url; this.x = x; this.y = y; this.width = 450; var proportion = this.width / this.x; this.height = Math.floor(proportion * this.y); this.wait(5000, function () { // this.callb(null, 'Greetings... '); this.then(function () { this.captureSelector(this.imgPath + "firstScreen.png", "html"); var result = this.evaluate(function () { /* let linksArrStr = '' $(".nadpisnahlavni").each(function (index, value) { linksArr += value + ',' })*/ var links = $(".nadpisnahlavni").find('a'); return Array.prototype.map.call(links, function (e) { return [e.innerHTML, e.getAttribute('href')]; }); // return linksArrStr; }); this.emit('getCategory', result); /* this.emit('getCategory', this.evaluate(function () { /!* let linksArrStr = '' $(".nadpisnahlavni").find('a').attr('href').each(function (index, value) { linksArr += value + ',' });*!/ return $(".nadpisnahlavni").find('a').attr('href').length; }));*/ /* this.capture(this.imgPath, { top: 60, left: 0, width: this.width, height: this.height });*/ }); }); }]); spooky.then(function () { this.emit('hello', 'Hello, from ' + this.evaluate(function () { return document.title; })); }); /* spooky.then(function () { });*/ spooky.run(); }); spooky.on('error', function (e, stack) { console.error(e); if (stack) { console.log(stack); } }); /* // Uncomment this block to see all of the things Casper has to say. // There are a lot. // He has opinions. */ spooky.on('console', function (line) { console.log(line); }); spooky.on('hello', function (greeting) { console.log(greeting); spooky.options.greeting = greeting; }); spooky.on('getCategory', function (greeting) { console.log('__________getCategory___________'); console.log(greeting); //spooky.options.cb(null, spooky.options.greeting); spooky.options.cb(null, greeting); }); //nadpisnahlavni /* this.emit('hello', this.evaluate(function () { return $('#list_parent').html(); }));*/ spooky.on('log', function (log) { if (log.space === 'remote') { console.log(log.message.replace(/ \- .*/, '')); } }); } Container.remoteMethod('greet', { accepts: {arg: 's', type: 'string'}, returns: {arg: 'greeting', type: 'string'} }); Container.putContainer = function (container, cb) { Container.getContainer(container, function (err, c) { // if (err) // return cb(err) if (c && c.name) { console.log('CONTAINER ALREADY EXIST', container); cb(null, c.name) } else { Container.createContainer({name: container}, function (err, c) { if (err) return cb(err); console.log('CONTAINER CREATED', container); cb(null, c.name) }); } }); }; }; <file_sep>'use strict'; {/* <VirtualHost *:3003> ServerName vazoga.com ServerAlias www.vazoga.com ServerAdmin <EMAIL> ProxyPreserveHost On ProxyRequests Off ProxyPass / http://127.0.0.1:3003/ ProxyPassReverse / http://127.0.0.1:3003 </VirtualHost> <VirtualHost *:80> ServerName blog.vazoga.com ServerAlias www.blog.vazoga.com ServerAdmin <EMAIL> #referring the user to the recipes application DocumentRoot /var/www/html <Directory /var/www/html> Options Indexes FollowSymLinks MultiViews AllowOverride All Order allow,deny allow from all # Uncomment this directive is you want to see apache2's # default start page (in /apache2-default) when you go to / #RedirectMatch ^/$ /apache2-default/ </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> */} const fs = require('fs'); module.exports = (app) => { if (!app.get('initialData')) return; const User = app.models.user; const Role = app.models.Role; const RoleMapping = app.models.RoleMapping; const Category = app.models.category; // destination.txt will be created or overwritten by default. fs.copyFile('client/src/components/MyAds/style.css', 'client/node_modules/react-dropzone-uploader/dist/styles.css', (err) => { if (err) throw err; console.log('source src/components/MyAds/style.css was copied to destination node_modules/react-dropzone-uploader/dist/styles.css'); }); // create a user User.findOrCreate({where: {email: '<EMAIL>'}}, { name: 'Admin', surname: '-', username: 'admin', email: '<EMAIL>', password: '<PASSWORD>', emailVerified: true } , function (err, user) { if (err) console.log('ERROR', err); console.log('Created user:', user); //create the admin role Role.findOrCreate({where: {name: 'admin'}}, { name: 'admin' }, function (err, role) { if (err) console.log('ERROR', err); // make an admin user RoleMapping.findOrCreate({ where: { principalId: user.id, roleId: role.id } }, { principalType: RoleMapping.USER, principalId: user.id, roleId: role.id }, function (err, principal) { if (err) console.log('ERROR', err); console.log('Created principal:', principal); }); }); }); User.findOrCreate({where: {email: '<EMAIL>'}}, { name: 'Editor', surname: '-', username: 'editor', email: '<EMAIL>', password: '<PASSWORD>', emailVerified: true } , function (err, user) { if (err) console.log('ERROR', err); console.log('Created user:', user); //create the editor role Role.findOrCreate({where: {name: 'editor'}}, { name: 'editor' }, function (err, role) { if (err) console.log('ERROR', err); // make an editor user RoleMapping.findOrCreate({ where: { principalId: user.id, roleId: role.id } }, { principalType: RoleMapping.USER, principalId: user.id, roleId: role.id }, function (err, principal) { if (err) console.log('ERROR', err); console.log('Created principal:', principal); }); }); }); User.findOrCreate({where: {email: '<EMAIL>'}}, { name: 'Manager', surname: '-', username: 'manager', email: '<EMAIL>', password: '<PASSWORD>', emailVerified: true } , function (err, user) { if (err) console.log('ERROR', err); console.log('Created user:', user); //create the editor role Role.findOrCreate({where: {name: 'manager'}}, { name: 'manager' }, function (err, role) { if (err) console.log('ERROR', err); // make an editor user RoleMapping.findOrCreate({ where: { principalId: user.id, roleId: role.id } }, { principalType: RoleMapping.USER, principalId: user.id, roleId: role.id }, function (err, principal) { if (err) console.log('ERROR', err); console.log('Created principal:', principal); }); }); }); User.findOrCreate({where: {email: '<EMAIL>'}}, { name: 'Worker', surname: '-', username: 'worker', email: '<EMAIL>', password: '<PASSWORD>', emailVerified: true } , function (err, user) { if (err) console.log('ERROR', err); console.log('Created user:', user); //create the editor role Role.findOrCreate({where: {name: 'worker'}}, { name: 'worker' }, function (err, role) { if (err) console.log('ERROR', err); // make an editor user RoleMapping.findOrCreate({ where: { principalId: user.id, roleId: role.id } }, { principalType: RoleMapping.USER, principalId: user.id, roleId: role.id }, function (err, principal) { if (err) console.log('ERROR', err); console.log('Created principal:', principal); }); }); }); User.findOrCreate({where: {email: '<EMAIL>'}}, { name: 'User', surname: '-', username: 'user', email: '<EMAIL>', password: '<PASSWORD>', emailVerified: true } , function (err, user) { if (err) console.log('ERROR', err); console.log('Created user:', user); }); /** * --------------------Category animals----------------------*/ /* * */ Category.findOrCreate({where: {publicname: 'animals'}}, { local: 'cz', buysell: true, publicname: 'animals', icon: 'fa fa-firefox', name: 'zvirata', url: 'https://zvirata.bazos.cz/', active: true, parent: 'none', subcat: 'Akvarijní ryby,Drobní savci,Kočky,Koně,Koně - potřeby,Koně - služby,Psi,Ptactvo,Terarijní zvířata,Ostatní domácí,Krytí,Ztraceni a nalezeni,Chovatelské potřeby,Služby pro zvířata,Drůbež,Králíci,Ovce a kozy,Prasata,Skot,Ostatní hospodářská' } , function (err, category) { if (err) console.log('ERROR', err); console.log('Created category:', category); }); Category.findOrCreate({where: {publicname: 'animals'}}, { local: 'it', buysell: true, publicname: 'animals', icon: 'fa fa-firefox', name: 'animali', url: 'https://www.subito.it/annunci-italia/vendita/animali/', active: true, parent: 'none', subcat: 'Cane,Gatto,Pesce,Cavallo,Uccelli,Altro' } , function (err, category) { if (err) console.log('ERROR', err); console.log('Created category:', category); }); Category.findOrCreate({where: {publicname: 'animals'}}, { local: 'fr', buysell: true, publicname: 'animals', icon: 'fa fa-firefox', name: 'animaux', url: 'https://www.leboncoin.fr/animaux/offres/', active: true, parent: 'none', subcat: null } , function (err, category) { if (err) console.log('ERROR', err); console.log('Created category:', category); }); /** * --------------------Category realty----------------------*/ Category.findOrCreate({where: {publicname: 'realty'}}, { local: 'cz', buysell: true, publicname: 'realty', icon: 'fa fa-building', name: 'realty', url: 'https://realty.bazos.cz/', active: true, parent: 'none', subcat: null } , function (err, category) { if (err) console.log('ERROR', err); console.log('Created category:', category); }); Category.findOrCreate({where: {publicname: 'realty'}}, { local: 'it', buysell: true, publicname: 'realty', icon: 'fa fa-building', name: 'immobili', url: 'https://www.subito.it/annunci-italia/vendita/immobili/', active: true, parent: 'none', subcat: null } , function (err, category) { if (err) console.log('ERROR', err); console.log('Created category:', category); }); Category.findOrCreate({where: {publicname: 'realty'}}, { local: 'fr', buysell: true, publicname: 'realty', icon: 'fa fa-building', name: 'immobilier', url: 'https://www.leboncoin.fr/_immobilier_/offres/', active: false, parent: 'none', subcat: null } , function (err, category) { if (err) console.log('ERROR', err); console.log('Created category:', category); }); /** * --------------------Category kids----------------------*/ Category.findOrCreate({where: {publicname: 'kids'}}, { local: 'cz', buysell: true, publicname: 'kids', icon: 'fa fa-child', name: 'děti', url: 'https://deti.bazos.cz/', active: true, parent: 'none', subcat: null } , function (err, category) { if (err) console.log('ERROR', err); console.log('Created category:', category); }); Category.findOrCreate({where: {publicname: 'kids'}}, { local: 'it', buysell: true, publicname: 'kids', icon: 'fa fa-child', name: 'bambini', url: 'https://www.subito.it/annunci-italia/vendita/bambini-giocattoli/', active: true, parent: 'none', subcat: null } , function (err, category) { if (err) console.log('ERROR', err); console.log('Created category:', category); }); /** * --------------------Category jobs----------------------*/ Category.findOrCreate({where: {publicname: 'jobs'}}, { local: 'cz', buysell: false, publicname: 'jobs', icon: 'fa fa-pencil', name: 'prace', url: 'https://prace.bazos.cz/', active: true, parent: 'none', subcat: null } , function (err, category) { if (err) console.log('ERROR', err); console.log('Created category:', category); }); Category.findOrCreate({where: {publicname: 'jobs'}}, { local: 'it', buysell: false, publicname: 'jobs', icon: 'fa fa-pencil', name: 'lavoro', url: 'https://www.subito.it/annunci-italia/vendita/lavoro/', active: true, parent: 'none', subcat: null } , function (err, category) { if (err) console.log('ERROR', err); console.log('Created category:', category); }); Category.findOrCreate({where: {publicname: 'jobs'}}, { local: 'fr', buysell: false, publicname: 'jobs', icon: 'fa fa-pencil', name: 'jobs', url: 'https://www.leboncoin.fr/offres_d_emploi/offres/', active: false, parent: 'none', subcat: null } , function (err, category) { if (err) console.log('ERROR', err); console.log('Created category:', category); }); /** * --------------------Category auto----------------------*/ Category.findOrCreate({where: {publicname: 'auto'}}, { local: 'cz', buysell: true, publicname: 'auto', icon: 'fa fa-car', name: 'car', url: 'https://auto.bazos.cz/', active: true, parent: 'none', subcat: 'Alfa Romeo,Audi,BMW,Citroën,Dacia,Fiat,Ford,Honda,Hyundai,Chevrolet,Kia,Mazda,Mercedes-Benz,Mitsubishi,Nissan,Opel,Peugeot,Renault,Seat,Suzuki,Škoda,Toyota,Volkswagen,Volvo,Ostatní značky,Autorádia,GPS navigace,Havarovaná auta,Náhradní díly,Pneumatiky kola,Příslušenství,Tuning,Veteráni,Autobusy,Dodávky,Mikrobusy,Karavany vozíky,Nákladní auta,Pick-up,Stroje,Ostatní,Havarovaná,Náhradní díly' } , function (err, category) { if (err) console.log('ERROR', err); console.log('Created category:', category); }); Category.findOrCreate({where: {publicname: 'auto'}}, { local: 'it', buysell: true, publicname: 'auto', icon: 'fa fa-car', name: 'motor', url: 'https://www.subito.it/annunci-italia/vendita/auto/', active: true, parent: 'none', subcat: 'Utilitaria,Station Wagon,Monovolume,SUV/Fuoristrada,Cabrio,Coupé,City Car,Altro' } , function (err, category) { if (err) console.log('ERROR', err); console.log('Created category:', category); }); Category.findOrCreate({where: {publicname: 'auto'}}, { local: 'fr', buysell: true, publicname: 'autofr', icon: 'fa fa-car', name: 'voitures', url: 'https://www.leboncoin.fr/voitures/offres/', active: false, parent: 'none', subcat: null } , function (err, category) { if (err) console.log('ERROR', err); console.log('Created category:', category); }); /** * --------------------Category motorcycles----------------------*/ Category.findOrCreate({where: {publicname: 'motorcycles'}}, { local: 'cz', buysell: true, publicname: 'motorcycles', icon: 'fa fa-motorcycle', name: 'motorky', url: 'https://motorky.bazos.cz/', active: true, parent: 'none', subcat: null } , function (err, category) { if (err) console.log('ERROR', err); console.log('Created category:', category); }); Category.findOrCreate({where: {publicname: 'motorcycles'}}, { local: 'it', buysell: true, publicname: 'motorcycles', icon: 'fa fa-motorcycle', name: 'moto', url: 'https://www.subito.it/annunci-italia/vendita/moto-e-scooter/', active: true, parent: 'none', subcat: null } , function (err, category) { if (err) console.log('ERROR', err); console.log('Created category:', category); }); Category.findOrCreate({where: {publicname: 'motorcycles'}}, { local: 'fr', buysell: true, publicname: 'motorcycles', icon: 'fa fa-motorcycle', name: 'motos', url: 'https://www.leboncoin.fr/motos/offres/', active: false, parent: 'none', subcat: null } , function (err, category) { if (err) console.log('ERROR', err); console.log('Created category:', category); }); /** * --------------------Category machines----------------------*/ Category.findOrCreate({where: {publicname: 'machines'}}, { local: 'cz', buysell: true, publicname: 'machines', icon: 'fa fa-truck', name: 'stroje', url: 'https://stroje.bazos.cz/', active: true, parent: 'none', subcat: null } , function (err, category) { if (err) console.log('ERROR', err); console.log('Created category:', category); }); Category.findOrCreate({where: {publicname: 'machines'}}, { local: 'it', buysell: true, publicname: 'machines', icon: 'fa fa-truck', name: 'veicoli', url: 'https://www.subito.it/annunci-italia/vendita/veicoli-commerciali/', active: true, parent: 'none', subcat: null } , function (err, category) { if (err) console.log('ERROR', err); console.log('Created category:', category); }); /** * --------------------Category machines----------------------*/ Category.findOrCreate({where: {publicname: 'house'}}, { local: 'cz', buysell: true, publicname: 'house', icon: 'fa fa-home', name: 'dum', url: 'https://dum.bazos.cz/', active: true, parent: 'none', subcat: null } , function (err, category) { if (err) console.log('ERROR', err); console.log('Created category:', category); }); Category.findOrCreate({where: {publicname: 'house'}}, { local: 'it', buysell: true, publicname: 'house', icon: 'fa fa-home', name: 'fai-da-te', url: 'https://www.subito.it/annunci-italia/vendita/giardino-fai-da-te/', active: true, parent: 'none', subcat: null } , function (err, category) { if (err) console.log('ERROR', err); console.log('Created category:', category); }); /** * --------------------Category informatica----------------------*/ Category.findOrCreate({where: {publicname: 'pc'}}, { local: 'cz', buysell: true, publicname: 'pc', icon: 'fa fa-windows', name: 'pc', url: 'https://pc.bazos.cz/', active: true, parent: 'none', subcat: null } , function (err, category) { if (err) console.log('ERROR', err); console.log('Created category:', category); }); Category.findOrCreate({where: {publicname: 'pc'}}, { local: 'it', buysell: true, publicname: 'pc', icon: 'fa fa-windows', name: 'informatica', url: 'https://www.subito.it/annunci-italia/vendita/informatica/', active: true, parent: 'none', subcat: null } , function (err, category) { if (err) console.log('ERROR', err); console.log('Created category:', category); }); /** * --------------------Category mobile----------------------*/ Category.findOrCreate({where: {publicname: 'mobile'}}, //https://www.subito.it/annunci-italia/vendita/telefonia/ { local: 'cz', buysell: true, publicname: 'mobile', icon: 'fa fa-mobile', name: 'mobil', url: 'https://mobil.bazos.cz/', active: true, parent: 'none', subcat: null } , function (err, category) { if (err) console.log('ERROR', err); console.log('Created category:', category); }); Category.findOrCreate({where: {publicname: 'mobile'}}, { local: 'it', buysell: true, publicname: 'mobile', icon: 'fa fa-mobile', name: 'telefonia', url: 'https://www.subito.it/annunci-italia/vendita/telefonia/', active: true, parent: 'none', subcat: null } , function (err, category) { if (err) console.log('ERROR', err); console.log('Created category:', category); }); /** * --------------------Category photo----------------------*/ Category.findOrCreate({where: {publicname: 'photo'}}, { local: 'cz', buysell: true, publicname: 'photo', icon: 'fa fa-camera', name: 'foto', url: 'https://foto.bazos.cz/', active: true, parent: 'none', subcat: null } , function (err, category) { if (err) console.log('ERROR', err); console.log('Created category:', category); }); Category.findOrCreate({where: {publicname: 'photo'}}, { local: 'it', buysell: true, publicname: 'photo', icon: 'fa fa-camera', name: 'fotografia', url: 'https://www.subito.it/annunci-italia/vendita/fotografia/', active: true, parent: 'none', subcat: null } , function (err, category) { if (err) console.log('ERROR', err); console.log('Created category:', category); }); /** * --------------------Category photo----------------------*/ Category.findOrCreate({where: {publicname: 'electro'}}, { local: 'cz', buysell: true, publicname: 'electro', icon: 'fa fa-tv', name: 'elektro', url: 'https://elektro.bazos.cz/', active: true, parent: 'none', subcat: null } , function (err, category) { if (err) console.log('ERROR', err); console.log('Created category:', category); }); Category.findOrCreate({where: {publicname: 'electro'}}, { local: 'it', buysell: true, publicname: 'electro', icon: 'fa fa-tv', name: 'audio-video', url: 'https://www.subito.it/annunci-italia/vendita/audio-video/', active: true, parent: 'none', subcat: null } , function (err, category) { if (err) console.log('ERROR', err); console.log('Created category:', category); }); /** * --------------------Category photo----------------------*/ Category.findOrCreate({where: {publicname: 'sport'}}, { local: 'cz', buysell: true, publicname: 'sport', icon: 'fa fa-futbol-o', name: 'sportcz', url: 'https://sport.bazos.cz/', active: true, parent: 'none', subcat: null } , function (err, category) { if (err) console.log('ERROR', err); console.log('Created category:', category); }); Category.findOrCreate({where: {publicname: 'sport'}}, { local: 'it', buysell: true, publicname: 'sport', icon: 'fa fa-futbol-o', name: 'sportit', url: 'https://www.subito.it/annunci-italia/vendita/sport/', active: true, parent: 'none', subcat: null } , function (err, category) { if (err) console.log('ERROR', err); console.log('Created category:', category); }); Category.findOrCreate({where: {publicname: 'music'}}, { local: 'cz', buysell: true, publicname: 'music', icon: 'fa fa-music', name: 'hudba', url: 'https://hudba.bazos.cz/', active: true, parent: 'none', subcat: null } , function (err, category) { if (err) console.log('ERROR', err); console.log('Created category:', category); }); Category.findOrCreate({where: {publicname: 'music'}}, { local: 'it', buysell: true, publicname: 'music', icon: 'fa fa-music', name: 'strumenti', url: 'https://www.subito.it/annunci-italia/vendita/strumenti-musicali/', active: true, parent: 'none', subcat: null } , function (err, category) { if (err) console.log('ERROR', err); console.log('Created category:', category); }); Category.findOrCreate({where: {publicname: 'tickets'}}, { local: 'cz', buysell: true, publicname: 'tickets', icon: 'fa fa-plane', name: 'vstupenky', url: 'https://vstupenky.bazos.cz/', active: true, parent: 'none', subcat: null } , function (err, category) { if (err) console.log('ERROR', err); console.log('Created category:', category); }); /** * --------------------Category books----------------------*/ Category.findOrCreate({where: {publicname: 'books'}}, { local: 'cz', buysell: true, publicname: 'books', icon: 'fa fa-book', name: 'knihy', url: 'https://knihy.bazos.cz/', active: true, parent: 'none', subcat: null } , function (err, category) { if (err) console.log('ERROR', err); console.log('Created category:', category); }); Category.findOrCreate({where: {publicname: 'books'}}, { local: 'it', buysell: true, publicname: 'books', icon: 'fa fa-book', name: 'libri', url: 'https://www.subito.it/annunci-italia/vendita/libri-riviste/', active: true, parent: 'none', subcat: null } , function (err, category) { if (err) console.log('ERROR', err); console.log('Created category:', category); }); /** * --------------------Category furniture----------------------*/ Category.findOrCreate({where: {publicname: 'furniture'}}, { local: 'cz', buysell: true, publicname: 'furniture', icon: 'fa fa-cube', name: 'nabytek', url: 'https://nabytek.bazos.cz/', active: true, parent: 'none', subcat: null } , function (err, category) { if (err) console.log('ERROR', err); console.log('Created category:', category); }); Category.findOrCreate({where: {publicname: 'furniture'}}, { local: 'it', buysell: true, publicname: 'furniture', icon: 'fa fa-cube', name: 'arredamento', url: 'https://www.subito.it/annunci-italia/vendita/arredamento-casalinghi/', active: true, parent: 'none', subcat: null } , function (err, category) { if (err) console.log('ERROR', err); console.log('Created category:', category); }); /** * --------------------Category clothing----------------------*/ Category.findOrCreate({where: {publicname: 'clothing'}}, { local: 'cz', buysell: true, publicname: 'clothing', icon: 'fa fa-user', name: 'obleceni', url: 'https://obleceni.bazos.cz/', active: true, parent: 'none', subcat: null } , function (err, category) { if (err) console.log('ERROR', err); console.log('Created category:', category); }); Category.findOrCreate({where: {publicname: 'clothing'}}, { local: 'it', buysell: true, publicname: 'clothing', icon: 'fa fa-user', name: 'abbigliamento', url: 'https://www.subito.it/annunci-italia/vendita/abbigliamento-accessori/', active: true, parent: 'none', subcat: null } , function (err, category) { if (err) console.log('ERROR', err); console.log('Created category:', category); }); /** * --------------------Category services----------------------*/ Category.findOrCreate({where: {publicname: 'services'}}, { local: 'cz', buysell: false, publicname: 'services', icon: 'fa fa-cogs', name: 'sluzby', url: 'https://sluzby.bazos.cz/', active: true, parent: 'none', subcat: null } , function (err, category) { if (err) console.log('ERROR', err); console.log('Created category:', category); }); Category.findOrCreate({where: {publicname: 'services'}}, { local: 'it', buysell: false, publicname: 'services', icon: 'fa fa-cogs', name: 'servizi', url: 'https://www.subito.it/annunci-italia/vendita/servizi/', active: true, parent: 'none', subcat: null } , function (err, category) { if (err) console.log('ERROR', err); console.log('Created category:', category); }); /** * --------------------Category other----------------------*/ Category.findOrCreate({where: {publicname: 'other'}}, { local: 'cz', buysell: false, publicname: 'other', icon: 'fa fa-magic', name: 'ostatni', url: 'https://ostatni.bazos.cz/', active: true, parent: 'none', subcat: null } , function (err, category) { if (err) console.log('ERROR', err); console.log('Created category:', category); }); Category.findOrCreate({where: {publicname: 'other'}}, { local: 'it', buysell: false, publicname: 'other', icon: 'fa fa-magic', name: 'hobby', url: 'https://www.subito.it/annunci-italia/vendita/hobby-collezionismo/', active: true, parent: 'none', subcat: '' } , function (err, category) { if (err) console.log('ERROR', err); console.log('Created category:', category); }); }; <file_sep>import React from 'react'; import {connect} from 'react-redux' class SystemMessages extends React.Component { destroyer = false; constructor(props) { super(props); this.state = { messages: [] } } onClick = (index) => { let messages = this.state.messages; messages.splice(index, 1); if (!messages.length) { clearTimeout(this.destroyer); this.destroyer = false; } this.setState({ messages: messages }); }; delayedRemove = () => { if (!this.destroyer) this.destroyer = setTimeout(() => { let messages = this.state.messages; messages.pop(); this.setState({ messages: messages }); clearTimeout(this.destroyer); this.destroyer = false; if (messages.length) this.delayedRemove(); }, 3000) }; componentWillReceiveProps = (props) => { const error = props.system && props.system.error && props.system.error.data && props.system.error.data.error; const success = props.system && props.system.message; if (error || success) { let messages = this.state.messages || []; const message = error ? {type: 'error', ...error} : {type: 'success', ...success}; messages.push(message); this.setState({ messages: messages }); } }; /*<div id="systemMessages">{ this.state.messages.map((message, key) => { const className = message.type === 'error' ? 'alert-danger' : 'alert-success'; return <div key={key} className={"col-sm-12 col-md-6 col-lg-5 mx-auto alert alert-dismissible show " + className}> <i className="fa fa-exclamation-triangle mr-2"/> <strong>{message.name}:</strong> {message.message} <button type="button" className="close" data-dismiss="alert" aria-label="Close" onClick={() => { this.onClick(key) }}> <span aria-hidden="true">&times;</span> </button> {this.delayedRemove(key)} </div> })} </div>*/ render() { return (<div /> ); } } const mapStateToProps = (state) => { return {system: state.system} }; export default connect(mapStateToProps, null)(SystemMessages);<file_sep>'use strict'; module.exports = function(Likes) { }; <file_sep>import React from 'react'; import {Route, Switch} from 'react-router-dom'; import App from '../components/App'; import MyAds from '../components/MyAds'; import SignUp from '../components/Auth/SignUp'; import SignIn from '../components/Auth/SignIn'; import SignOut from '../components/Auth/SignOut'; import Reset from '../components/Auth/Reset'; import NewPassword from '../components/Auth/NewPassword'; import Welcome from '../components/Welcome'; import Features from '../components/Features'; import Home from '../components/Home'; import Profile from '../components/Profile'; import Settings from '../components/Settings'; import Users from '../components/Users'; import User from '../components/User'; import Ads from '../components/Ads'; import UserEdit from '../components/User/Edit'; import NoMatch from '../components/NoMatch'; import About from "../components/StaticPages/About"; import TermsOfService from "../components/StaticPages/TermsOfService"; import PrivacyPolicy from "../components/StaticPages/PrivacyPolicy"; const Routes = () => { return ( <App> <Switch> <Route exact path="/" component={Welcome}/> <Route exact path="/myads" component={MyAds}/> <Route exact path="/newad" component={MyAds}/> <Route exact path="/messages" component={MyAds}/> <Route exact path="/features" component={Features}/> <Route exact path="/aboutus" component={About}/> <Route exact path="/tos" component={TermsOfService}/> <Route exact path="/privacy" component={PrivacyPolicy}/> <Route exact path="/signin" component={SignIn}/> <Route exact path="/signout" component={SignOut}/> <Route exact path="/signup" component={SignUp}/> <Route exact path="/reset" component={Reset}/> <Route exact path="/newpassword/:token" component={NewPassword}/> <Route exact path="/home" component={Home}/> <Route exact path="/profile" component={Profile} username="me"/> <Route exact path="/settings/:page?" component={Settings}/> <Route exact path="/users/:page?/:id?" component={Users}/> <Route exact path="/users/:id" component={User}/> <Route exact path="/ads/:id" component={Ads}/> <Route exact path="/users/:id/edit" component={UserEdit}/> <Route exact path="/:username" component={Profile}/> <Route component={NoMatch}/> </Switch> </App> ); }; export default Routes; <file_sep>import React, {Component} from 'react'; import {connect} from 'react-redux'; import axios from 'axios'; import {getAd, getRelatedImgs, getComments, setLike, getLikes} from "../../actions"; import Gallery from 'react-photo-gallery'; import ImageGallery from 'react-image-gallery'; import "react-image-gallery/styles/css/image-gallery.css"; import CommentsBlock from 'simple-react-comments'; const STRAPI_URL = 'https://vazoga.com:1337'; const API_URL = process.env.REACT_APP_API_URL; class Ads extends Component { constructor(props) { super(props); this.state = { ad: null, adid: null, me: props.me, imgs: [], likes: [], categories: [], comments: [], langs: props.langs }; } getAdData(props) { let id = props.match.params.id; this.setState({adid: id}); getAd(id) .then(ad => { this.setState({ad}); }) .catch(error => { this.setState({'error': error}); }); getRelatedImgs(id) .then(imgs => { this.setState({imgs: imgs}); }) .catch(error => { this.setState({'error': error}); }); getComments(id) .then(comments => { this.setState({'comments': comments}); }) .catch(error => { this.setState({'error': error}); }); getLikes(id) .then(likes => { this.setState({likes}); }) .catch(error => { this.setState({'error': error}); }); } componentDidMount() { this.getAdData(this.props); axios.post(`${API_URL}/pages/incrementView`, { pageId: this.props.match.params.id }).then(function(response) { console.log('incrementView'); console.log(response); }); } changeLike = (adid, author) => { setLike(adid, author) .then(likes => { this.setState({likes}); }) .catch(error => { this.setState({'error': error}); }); return true; }; GetAvatar = (thumb) => { if (!(thumb.indexOf('holder') + 1)) { return thumb; } else if (typeof this.state.me.imageSocial != 'undefined') { return this.state.me.imageSocial; } else { return thumb; } }; getCategory = (category) => { category = category.substring(0, category.length - 1); let url = 'https://vazoga.com:3003/api/pages?filter=%7B%22where%22%3A%20%7B%22and%22%3A%20%5B%7B%22urlcategory%22%3A%20%22' + category + '%22%7D%2C%20%7B%22tags%22%3A%20%22last%22%7D%5D%7D%7D'; console.log(url); axios.all([ axios.get(url) ]).then(axios.spread((resPages) => { console.log(resPages); let tblData = []; resPages.data.forEach((item) => { if (item.text !== 'pending') { if (typeof item.donor_images[0] == 'string') { item.imageUrl = item.donor_images[0]; } else { item.imageUrl = 'https://dummyimage.com/160x160/000/fff.png&text=not+found'; } item.text = item.text = item.text.replace(/(<([^>]+)>)/ig, ""); tblData.push(item); } }); console.log(tblData); this.setState({tblData}); })); this.setState({showMe: category}); }; render() { const GetImages = (props) => { console.log('this.state.imgs.length'); console.log(this.state.imgs.length); if (this.state.imgs.length) { const images = []; this.state.imgs.forEach(function(element, index) { let item = {}; item.original = `${STRAPI_URL}` + element.url; item.thumbnail = `${STRAPI_URL}` + element.url; images.push(item); }); console.log('this.state.imgs.length 1'); return <ImageGallery items={images}/>; } else if (props.ad && props.ad.donor_images.length > 1) { /* props.ad.donor_images.forEach((src) => { let item = {} item.src = src /!* item.width = 1 item.height = 1*!/ PHOTO_SET.push(item) })*/ let PHOTO_SET = []; props.ad.donor_images.forEach((src) => { let item = {}; item.src = src; /* item.width = 1 item.height = 1*/ PHOTO_SET.push(item); }); //todo : get from console.log('this.state.imgs.length 2'); console.log(props.ad); console.log(props.ad.donor_images); return <Gallery photos={PHOTO_SET}/>; // return <ImageGallery items={images} /> } else { console.log('this.state.imgs.length 3'); return <div/>; } }; const GetLike = (props) => { if (props.ad) { let icon = "fa fa-heart-o"; if (typeof this.state.me !== 'undefined') { if (this.state.likes.includes(this.state.me.id)) { icon = "fa fa-heart"; } return <div> <i className={icon} style={{cursor: 'pointer'}} onClick={this.changeLike.bind(props.that, props.ad.id, this.state.me.id)}/> {this.state.likes.length === 0 ? '' : ' ' + this.state.likes.length} </div>; } else { return <div> <i className="fa fa-heart"/> {this.state.likes.length === 0 ? '' : ' ' + this.state.likes.length} </div>; } } else { return <div/>; } }; const GetTitle = (props) => { if (props.ad) { return <h1>{props.ad.title}</h1>; } else { return <div/>; } }; const GetText = (props) => { if (props.ad) { return <h5>{props.ad.text}</h5>; } else { return <div/>; } }; const RegionLink = (props) => { console.log(props); if (typeof props.addressregion != 'undefined' && props.addressregion !== '') { return <span><br/><span className="label-ad">region:</span> {props.addressregion}</span>; } else { return <span/>; } }; const AdType = (props) => { console.log(props); if (typeof props.type != 'undefined' && props.type !== '') { return <span><br/><span className="label-ad">{this.state.langs.strings.type}:</span> {props.type}</span>; } else { return <span/>; } }; const SubCategory = (props) => { console.log(props); if (typeof props.subcategory != 'undefined' && props.subcategory !== '') { return <span><br/><span className="label-ad">{this.state.langs.strings.subcategory}:</span> {props.subcategory}</span>; } else { return <span/>; } }; const AddressDetails = (props) => { console.log(props); if (typeof props.addressdetails != 'undefined' && props.addressdetails !== '') { return <span><br/><span className="label-ad">{this.state.langs.strings.address}:</span> {props.addressdetails}</span>; } else { return <span/>; } }; const Author = (props) => { console.log(props); if (typeof props.author != 'undefined' && props.author !== '') { return <span><br/><span className="label-ad">{this.state.langs.strings.author}:</span> {props.author}</span>; } else { return <span/>; } }; /*const GetPrice = (props) => { if (props.price !== '') { return <span><br/><span className="label-ad">price:</span> {props.price}{props.currency}</span>; } else { return <span/> } }*/ const GetDesc = (props) => { //return(<Gallery images={IMAGES}/>,) /* console.log('props.rowData') console.log(props.rowData)*/ if (props.ad) { return ( <div> {/*<br/><span className="label-ad">author:</span> {props.ad.author}*/} {/*<br/><span className="label-ad">phone:</span> {props.ad.phone}*/} <AdType type={props.ad.type}/> <SubCategory subcategory={props.ad.subcategory}/> <RegionLink addressregion={props.ad.addressregion}/> <AddressDetails addressdetails={props.ad.addressdetails}/> <Author author={props.ad.author_name}/> {/* <GetPrice price={props.ad.price} currency={props.ad.currency}/>*/} {/* <BaseProductTblPriceComponent rowData={props.rowData}/> <br/><span className="label-ad">source:</span> <SourceLink rowData={props.rowData}/>*/} </div> ); } else { return <div/>; } }; return <section className="container"> <div className="row justify-content-center"> <main role="main" className="col-md-12 ml-sm-auto col-lg-12 px-4"> <div className="col-md-12"> <br/> <div><GetTitle ad={this.state.ad}/></div> <div><GetImages ad={this.state.ad}/></div> <div><GetText ad={this.state.ad}/></div> <div><GetDesc ad={this.state.ad}/></div> </div> </main> <GetLike ad={this.state.ad} that={this}/>&nbsp;&nbsp;&nbsp;&nbsp; {/* renderAvatar() {//this.state.me && this.state.me.image if (!(this.state.me.image.thumb.indexOf('holder') + 1)) { return <img className="navbar-avatar" src={this.state.me.image.thumb} alt={this.state.me.name}/>; } else if (typeof this.state.me.imageSocial != 'undefined') { return <img className="navbar-avatar" src={this.state.me.imageSocial} alt={this.state.me.name}/>; } else { return <img className="navbar-avatar" src={this.state.me.image.thumb} alt={this.state.me.name}/>; } }*/} <CommentsBlock comments={this.state.comments} signinUrl={'/signin'} isLoggedIn={this.state.me} reactRouter // set to true if you are using react-router onSubmit={text => { if (text.length > 0) { const sendData = { ad: 'comment_' + this.state.adid, authorUrl: '/' + this.state.me.username, avatarUrl: this.GetAvatar(this.state.me.image.thumb), createdAt: new Date(), fullName: this.state.me.username, text }; this.setState({ comments: [ ...this.state.comments, sendData ] }); console.log('submit:', text); axios.post(`${API_URL}/comments`, sendData) .then(function(response) { console.log('response'); console.log(response); }) .catch(function(error) { console.log(error); }); } }} /> </div> </section>; } } const mapStateToProps = (state) => { return {me: state.auth.me, langs: state.langs}; }; export default connect(mapStateToProps)(Ads); <file_sep># loopback-react playground loopback (mongodb) - react, router, redux, axios, formik, bootstrap 4 (reactstrap) fullstack playground with authentication and user management This a full stack playground for developing a Loopback - React application. And it's _under the development_ still. For more info you can check: - https://loopback.io/doc/en/lb3/index.html - https://github.com/facebook/create-react-app - https://reacttraining.com/react-router/web/guides/philosophy - https://redux.js.org/ - https://github.com/jaredpalmer/formik - https://getbootstrap.com/docs/4.1/getting-started/introduction/ - https://reactstrap.github.io/ ### Install ``` yarn install && cd client && yarn install ``` ### Run Loopback ``` yarn start ``` The server run on **vazoga.com:3003** and **server/boot/init.js** will create three users _(admin, editor and user)_ You can reach the Api Explorer via **vazoga.com:3003/explorer** ### Run Client (React) ``` cd client && yarn start ``` The client run on **localhost:3000** and talking with api on **vazoga.com:3003** ##### Add a React Componnet ``` cd client/ npx crcf src/components/NewComponent ``` #### Build and Serve the Client ``` cd client/ yarn build ``` After the build to serve the client you should edit the **server/middleware.json** like below ``` "files": { "loopback#static": [ { "paths": ["/"], "params": "$!../client/build" }, { "paths": ["*"], "params": "$!../client/build" } ] } ``` to more info https://loopback.io/doc/en/lb3/Defining-middleware.html ## Routes ``` / /feature /signin /signup /signout /reset /newpassword/:token /tos /privacy - /home /profile /settings/:page? (default /settings/account) /users/:page?/:id? (default /users/list) /user/:id /user/:id/edit /:username (run as /profile) ``` in client/src/routes/index.js <file_sep>import React, {Component} from 'react'; import {connect} from 'react-redux'; import {getProfile} from "../../actions"; import "./Profile.css"; import Breadcrumbs from '../Breadcrumbs'; class Profile extends Component { constructor(props) { super(props); this.state = { isLoading: true, user: null }; } getProfile(props) { let username = props.match.params.username || this.props.me.username; if (username !== this.state.username) { this.props.getProfile(username); } } componentWillReceiveProps(props) { if (this.props.match.params.username !== props.match.params.username) { this.setState({ isLoading: true }); this.getProfile(props); } if (this.state.user !== props.user) { this.setState({ isLoading: false, user: props.user }); } } componentDidMount() { this.getProfile(this.props); } render() { const user = this.state.user; if (this.state.isLoading) { return <section className="container"> <div className="profile">Loading...</div> </section>; } if (!user.name) { return <section className="container"> <div className="profile"><h3>User not found!</h3> <p>{JSON.stringify(process.env)}</p></div> </section>; } const fullName = user.name + ' ' + user.surname; let adminInfo = ''; /*if (user.username === 'admin') { adminInfo = <pre><br/><br/>admin section<hr className="border-primary"/><p>Сайт прототип: https://claz.org/</p><p>CMS: https://vazoga.com:1337/admin</p> {JSON.stringify(process.env)}<br/><br/><br/> </pre> }*/ return <section className="container"> <div className="breadcrumbs"> <Breadcrumbs/> </div> <div className="profile"> <div className="fb-profile"> <img align="left" className="fb-image-lg img-fluid" src={user.cover.normal} alt="{fullName}"/> <img align="left" className="fb-image-profile img-thumbnail" src={user.image.normal} alt="{fullName}"/> <div className="fb-profile-text"> <h1>{fullName}</h1> <p>{user.username}</p> <p>{user.bio && user.bio}</p> <p>{adminInfo}</p> </div> </div> </div> </section>; } } const mapStateToProps = (state) => { return {me: state.auth.me, user: state.system.data}; }; const mapDispatchToProps = (dispatch) => { return { getProfile: (values) => { dispatch(getProfile(values)); }, } }; export default connect(mapStateToProps, mapDispatchToProps)(Profile); <file_sep>import {combineReducers} from 'redux'; import {reducer as systemReducer} from './system'; import {reducer as authReducer} from './auth'; import {reducer as settingsReducer} from './settings'; import {reducer as langsReducer} from './langs'; const rootReducer = combineReducers({ system: systemReducer, auth: authReducer, settings: settingsReducer, langs: langsReducer }); export default rootReducer; <file_sep>const config = require('../../server/config.json'); const sharp = require('sharp'); const nodemailer = require("nodemailer"); const mandrillTransport = require('nodemailer-mandrill-transport'); const from = config.fromMail; const mailgun = require("mailgun-js"); const transport = nodemailer.createTransport(mandrillTransport({ auth: { apiKey: config.mandrillApiKey }, mandrillOptions: { async: false } })); const templateMail = function(title, html) { return `<html><head> <meta name="viewport" content="width=device-width" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>${title}</title> </head><body bgcolor="#FFFFFF"> <table style="max-width:600px;margin: 0 auto;"><tr><td style="padding:15px;text-align: center;"> <a href="${config.url}"><img src="${config.url}/favicon.png" alt="${config.name}" style="border:0; max-width:240px; max-height:100px;"></a></td></tr> <tr><td>${html}</td></tr> <tr><td style="padding:15px;font-size: small; color: #444444;">You’re receiving this email because you have an account in <a href="${config.url}">${config.name}</a>. If you are not sure why you’re receiving this, please contact us.</td> </tr></table> </body></html>`; }; module.exports = function(User) { User.observe('before save', function(context, next) { if (context.instance) { delete context.instance.unsetAttribute('roles'); } else { delete context.data.roles; } next(); }); User.afterRemote('create', function(context, user, next) { console.log('create afterRemote'); User.generateVerificationToken(user, null, function(err, token) { if (err) { return next(err); } user.status = true; user.verificationToken = token; user.save(function(err) { if (err) { return next(err); } const title = 'Account Verification'; const link = config.url + '/api/users/confirm?uid=' + user.id + '&redirect=/signin&token=' + token; const html = `<table><tr><td style="padding:15px">Hi <strong>${user.name}</strong>;<br><br> Thanks so much joining ${config.name}! To finish your register you just need to confirm that we got your email right. </td></tr><tr><td style="padding:15px;text-align: center"> <a href="${link}" style="display:inline-block;margin:0 auto;padding:15px 20px;border-radius:10px;background:#20a8d8;color: #ffffff;text-decoration:none;"> Confirm your account</a> </td></tr><tr><td style="padding:15px">Button not working? Try pasting this link into your browser:<br><br> ${link}</td></tr></table>`; /* User.app.models.Email.send({ to: '<EMAIL>, YOU@YOUR_DOMAIN_NAME', //user.email, from: 'sandbox <<EMAIL>>', subject: title, html: templateMail(title, html) }, function (err, res) { if (err) return console.log('> error sending verify email', err); console.log('> sending verify reset email to:', user.email, res); });*/ console.log('VERIFICATION LINK', link); console.log('------------------from'); console.log('user.email', user.email); console.log('from', from); // ---- tmp const DOMAIN = '<EMAIL>'; const apiKey = 'ee572264d1f5f072576b6e10f7784806-4167c382-c63fa152'; const mg = mailgun({apiKey: apiKey, domain: DOMAIN}); console.log('------------------apiKey'); console.log(apiKey); const data = { from: 'vazoga.com <<EMAIL>>', to: '<EMAIL>, YOU@YOUR_DOMAIN_NAME', subject: 'Account Verification www.vazoga.com', html: templateMail(title, html) }; mg.messages().send(data, function(error, body) { console.log('error'); console.log(error); console.log('body'); console.log(body); }); // ---- transport.sendMail({ mandrillOptions: { async: false }, from: from, to: user.email, subject: title, html: templateMail(title, html) }, function(err, info) { if (err) { console.error(err); } else { console.log(info); } }); }); }); next(); }); // // Method to render // User.afterRemote('prototype.verify', function (context, user, next) { // context.res.render('response', { // title: 'A Link to verify your identity has been sent ' + // 'to your email successfully', // content: 'Please check your email and click on the verification link ' + // 'before logging in', // redirectTo: '/', // redirectToLinkText: 'Log in' // }); // }); //send password reset link when requested User.on('resetPasswordRequest', function(user) { const url = config.url + '/newpassword'; const html = `Click the link to reset your password <br><a href="${url}/${user.accessToken.id}"> ${url}/${user.accessToken.id}</a>`; console.log('html', html); transport.sendMail({ from: from, to: user.email, subject: 'Password Reset', html: templateMail('Password Reset', html) }, function(err, info) { if (err) { return console.log('Error sending password reset email'); } else { console.log('Sending password reset email to:', user.email, info); } }); }); User.socialLogin = function(user, cb) { User.findOrCreate({where: {email: user.email}}, user , function(err, user) { if (err) console.log('ERROR', err); console.log('Created user:', user); cb(null, user); } ); }; User.approve = function(id, cb) { User.findById(id, function(err, user) { if (err) { cb(err); } else { user.emailVerified = true; user.adminVerified = true; user.save(function(err) { if (err) { console.log(err); next(err); } else { const html = '<div style="text-align: center"><h3>Good News</h3>' + '<p> We have just approved your account. ' + '</p></div>'; transport.sendMail({ from: from, to: user.email, subject: 'Account Approved', html: templateMail('Account Approved', html) }, function(err, info) { if (err) { console.log(err); cb(err); } console.log('Sending password reset email to:', user.email, info); cb(null, user); }); } }); } }); }; User.profile = function(username, cb) { User.findOne({"where": {"username": username}}, function(err, user) { if (err) { cb(err); } else { cb(null, user); } }); }; User.cover = function(id, context, options, cb) { const Container = User.app.models.Container; const token = options && options.accessToken; const root = User.app.dataSources.storage.settings.root; User.findById(token && token.userId, function(err, user) { if (err) { cb(err); } else { // each user has own container as named by user id Container.putContainer(user.id.toString(), function(err, container) { if (err) { cb(err); } else { console.log('CONTAINER CHECK', container); Container.upload(context.req, context.res, {container: container}, function(err, file) { if (err) { cb(err); } else { file = file.files.file && file.files.file.pop(); console.log('FILE UPLOADING', file); //console.log('USER IMAGE', user); const normal = file.name.replace(/\./, '_normal.'); sharp(root + file.container + '/' + file.name) .resize(1200, 360, {fit: 'cover'}) .on('error', function(err) { console.log(err); }) .jpeg() .toFile(root + file.container + '/' + normal) .then(function() { const thumb = file.name.replace(/\./, '_thumb.'); sharp(root + file.container + '/' + file.name) .resize(400, 120) .toFile(root + file.container + '/' + thumb) .then(function() { user.updateAttributes({ 'cover': { name: file.name, type: file.type, container: file.container, url: '/api/containers/' + file.container + '/download/' + file.name, normal: '/api/containers/' + file.container + '/download/' + normal, thumb: '/api/containers/' + file.container + '/download/' + thumb } }, function(err) { if (err) { console.log(err); cb(err); } console.log('USER COVER SAVED', user); cb(null, user); //return user.image; }); }) .catch(err => { throw err; }); }) .catch(err => { throw err; }); } }); } }); } }); }; User.image = function(id, context, options, cb) { const Container = User.app.models.Container; const token = options && options.accessToken; const root = User.app.dataSources.storage.settings.root; //console.log(cb); //cb = function(){return console.log()}; User.findById(token && token.userId, function(err, user) { if (err) { cb(err); } else { // each user has own container as named by user id Container.putContainer(user.id.toString(), function(err, container) { if (err) { cb(err); } else { Container.upload(context.req, context.res, {container: container}, function(err, file) { if (err) { cb(err); } else { file = file.files.file.pop(); //console.log('FILE UPLOADED', file); console.log('FILE UPLOADED', root + file.container + '/' + file.name); const normal = file.name.replace(/\./, '_normal.'); sharp(root + file.container + '/' + file.name) .resize(360, 360, {fit: 'cover'}) //.crop(sharp.strategy.attention) .on('error', function(err) { console.log(err); }) .jpeg() .toFile(root + file.container + '/' + normal) .then(function() { const thumb = file.name.replace(/\./, '_thumb.'); sharp(root + file.container + '/' + file.name) .resize(50, 50) .toFile(root + file.container + '/' + thumb) .then(function() { user.updateAttributes({ 'image': { name: file.name, type: file.type, container: file.container, url: '/api/containers/' + file.container + '/download/' + file.name, normal: '/api/containers/' + file.container + '/download/' + normal, thumb: '/api/containers/' + file.container + '/download/' + thumb } }, function(err) { if (err) { console.log(err); cb(err); } console.log('USER IMAGE SAVED', user); cb(null, user); //return user.image; }); }) .catch(err => { throw err; }); }) .catch(err => { throw err; }); } }); } }); } }); }; const setACL = (id, cb, type) => { const Role = User.app.models.Role; const RoleMapping = User.app.models.RoleMapping; User.findById(id, function(err, user) { if (err) { cb(err); } else { Role.findOrCreate({where: {name: type}}, { name: type }, function(err, role) { if (err) cb(err); RoleMapping.find({ where: { principalId: user.id, roleId: role.id } }, function(err, principal) { if (err) cb(err); if (!principal.length) { RoleMapping.create({ principalType: RoleMapping.USER, principalId: user.id, roleId: role.id }, function(err) { if (err) cb(err); User.findById(id, function(err, user) { if (err) { cb(err); } cb(null, user); }); }); } else { RoleMapping.destroyById(principal[0].id, function(err) { if (err) cb(err); User.findById(id, function(err, user) { if (err) { cb(err); } cb(null, user); }); }); } }); }); } }); }; User.toggleAdmin = function(id, cb) { setACL(id, cb, 'admin'); }; User.toggleEditor = function(id, cb) { setACL(id, cb, 'editor'); }; User.toggleManager = function(id, cb) { setACL(id, cb, 'manager'); }; User.toggleWorker = function(id, cb) { setACL(id, cb, 'worker'); }; User.toggleStatus = function(id, cb) { User.findById(id, function(err, user) { if (err) { cb(err); } else { user.status = !user.status; user.save(function(err) { if (err) { cb(err); } else { User.findById(id, function(err, user) { if (err) { cb(err); } cb(null, user); }); } }); } }); }; }; <file_sep>import React, {Component} from 'react'; import {connect} from "react-redux"; import {getAboutText, getAboutTitle} from "../../actions"; import MDReactComponent from 'markdown-react-js'; import Breadcrumbs from '../Breadcrumbs'; class About extends Component { constructor(props) { super(props); this.state = { me: props.me, articleText: '', articleTitle: '' }; } componentDidMount() { getAboutText() .then(text => { this.setState({ articleText: text }); }) .catch(error => { this.setState({'error': error}) }) getAboutTitle() .then(title => { this.setState({ articleTitle: title }); }) .catch(error => { this.setState({'error': error}) }) } render() { return <section id="privacyPolicy"> <div className="container"> <div className="breadcrumbs"> <Breadcrumbs/> </div> <h1 className="h3">{this.state.articleTitle}</h1> <hr className="border-primary"/> <p><MDReactComponent text={this.state.articleText}/></p> </div> </section>; } } const mapStateToProps = (state) => { return {me: state.auth.me, user: state.system.data} }; export default connect(mapStateToProps)(About); <file_sep>import React from 'react'; import {Field, Form, withFormik} from 'formik'; import * as Yup from 'yup'; import {settingsChangePassword} from '../../actions'; import {connect} from 'react-redux'; import Breadcrumbs from '../Breadcrumbs'; let setSubmittingHigher; const FormikForm = ({ values, touched, errors, isSubmitting }) => ( <div> <div className="breadcrumbs"> <Breadcrumbs/> </div> <div className="row justify-content-md-center"> <Form className="col-md-6"> <fieldset className="form-group"> <label>Old Password</label> <Field className="form-control" type="password" name="oldPassword" placeholder="<PASSWORD>"/> {touched.oldPassword && errors.oldPassword && <small className="form-text text-danger">{errors.oldPassword}</small>} </fieldset> <fieldset className="form-group"> <label>New Password</label> <Field className="form-control" type="password" name="newPassword" placeholder="<PASSWORD>"/> {touched.newPassword && errors.newPassword && <small className="form-text text-danger">{errors.newPassword}</small>} </fieldset> <fieldset className="form-group"> <label>Confirm New Password</label> <Field className="form-control" type="password" name="passwordConfirmation" placeholder="New Password Confirmation"/> {touched.passwordConfirmation && errors.passwordConfirmation && <small className="form-text text-danger">{errors.passwordConfirmation}</small>} </fieldset> <button className="btn btn-primary" type="submit" disabled={isSubmitting}> {isSubmitting && <span><i className="fa fa-circle-notch fa-spin"/>&nbsp;</span>} Change my password </button> </Form> </div> </div> ); const EnhancedForm = withFormik({ mapPropsToValues() { return { oldPassword: '', newPassword: '', passwordConfirmation: '' }; }, validationSchema: Yup.object().shape({ oldPassword: Yup.string().min(3, 'Password must be 3 characters or longer').required('Password is required'), newPassword: Yup.string().min(8, 'Password must be 8 characters or longer') .matches(/[a-z]/, 'Password must contain at least one lowercase char') .matches(/[A-Z]/, 'Password must contain at least one uppercase char') .matches(/[a-zA-Z]+[^a-zA-Z\s]+/, 'at least 1 number or special char (@,!,#, etc).'), passwordConfirmation: Yup.string() .oneOf([Yup.ref('newPassword'), null], 'Passwords do not match').required('Password is required') }), handleSubmit(values, {props, setSubmitting}) { setSubmittingHigher = setSubmitting; props.settingsChangePassword(values); } })(FormikForm); const mapStateToProps = (state) => { typeof setSubmittingHigher === 'function' && setSubmittingHigher(false); return {system: state.system}; }; const mapDispatchToProps = (dispatch) => { return { settingsChangePassword: (values) => { dispatch(settingsChangePassword(values)); } }; }; export default connect(mapStateToProps, mapDispatchToProps)(EnhancedForm); <file_sep>import React from 'react'; import { shallow } from 'enzyme'; import Breadcrumbs from './Breadcrumbs'; describe('<Breadcrumbs />', () => { test('renders', () => { const wrapper = shallow(<Breadcrumbs />); expect(wrapper).toMatchSnapshot(); }); }); <file_sep>import {getLocalizedStrings} from "../actions"; import LocalizedStrings from "react-localization"; //import {EN, IT, CZ} from '../actions/types'; //import {EN, CZ, IT} from '../actions/types'; //import cookie from 'browser-cookies'; export const reducer = (state = {}, action) => {// var strings = new LocalizedStrings(getLocalizedStrings()) return {...state, strings: strings}; }; /* export const reducer = (state = {}, action) => {// var strings = new LocalizedStrings(getLocalizedStrings()) switch (action.type) { case EN: return {...state, strings: strings.setLanguage('en')}; case CZ: return {...state, strings: strings.setLanguage('cz')}; case IT: return {...state, strings: strings.setLanguage('it')}; default: return {...state, strings: strings}; } };*/ <file_sep>import React from 'react'; import { shallow } from 'enzyme'; import SortableTbl from './SortableTbl'; describe('<SortableTbl />', () => { test('renders', () => { const wrapper = shallow(<SortableTbl />); expect(wrapper).toMatchSnapshot(); }); }); <file_sep>ps -ef | grep phantomjs | awk '{print $2}' | xargs sudo kill -9 <file_sep>const axios = require('axios') const osu = require('node-os-utils') const cpu = osu.cpu const mem = osu.mem const bucket = require('../node_modules/node-os-utils/lib/bucket.js') bucket.osCmd = { topCpu: bucket.exec('ps -eo pcpu,user,args --no-headers | sort -k 1 -n | tail -n 10 | sort -k 1 -nr | cut -c 1-70'), topMem: bucket.exec('ps -eo pmem,pid,cmd | sort -k 1 -n | tail -n 10 | sort -k 1 -nr | cut -c 1-70'), vmstats: bucket.exec('vmstat -S m'), processesUsers: bucket.exec('ps hax -o user | sort | uniq -c'), diskUsage: bucket.exec('df -h'), who: bucket.exec('who'), whoami: bucket.exec('whoami'), openPorts: bucket.exec('lsof -Pni4 | grep ESTABLISHED'), ifconfig: bucket.exec('ifconfig'), phantomjsKill: bucket.exec('ps -ef | grep phantomjs | awk \'{print $2}\' | xargs kill -9') } setInterval(function () { axios.all([ axios.get('https://vazoga.com:3003/api/pages/pendingList?local=it'), //todo: record log ]).then(axios.spread((response, log) => { console.log(response.data) let i = [] let urls = [] let c = 0 response.data.urls.map(x => { i.push(c) urls.push(x) c++ }) // console.log(urls) // let i = urls; let promiseFactoriesOrWhatever = []; let results = []; function work(t) { return new Promise((resolve, reject) => { console.log('running ' + t); cpu.free() .then(freeInfo => { console.log('cpu free _________________________________________' + freeInfo + '%') cpu.usage() .then(usageInfo => { console.log('cpu usage ________________________________________' + usageInfo + '%') mem.info() .then(info => { console.log(info) console.log('freeMemMb ________________________________________' + info.freeMemMb) //if (freeInfo > 20) { if (freeInfo > 10 && info.freeMemMb > 100) { if (typeof timeOut !== 'undefined') { clearTimeout(timeOut) } axios.post('https://vazoga.com:3003/api/pages/getAdvertDetails', { url: urls[t] }).then(function (response) { console.log("response.data"); console.log(response.data); if (t === urls.length - 1) { console.log(t + ' rejecting ' + urls[t]) return reject(urls.length) } console.log(t + ' resolving ' + urls[t]) resolve(t) }).catch(function (error) { console.log(error); }); } else { console.log(t + ' freeInfo ' + freeInfo + ' timeout ' + urls[t]) bucket.osCmd.whoami().then((response) => { console.log('whoami response: ' + response) }) /* bucket.osCmd.openPorts().then((response)=>{ console.log('openPorts response: ' + response) })*/ // {"where": {"and": [{"urlcategory": "https://zvirata.bazos.cz"}, {"tags": "last"}]}} bucket.osCmd.phantomjsKill().then((response) => { var timeOut = setTimeout(function () { console.log('--------------------------------------------') console.log('timeout phantomjs kill response: ' + response) console.log('--------------------------------------------') resolve('timeout ' + response) }, 10000); }) } }) }) }) }) } for (let a of i) { promiseFactoriesOrWhatever.push( () => { console.log('current results', results) return work(a).then((r) => { results.push(r) }) } ) } function queue(promiseFactories, finalResolve, finalReject) { let chain = new Promise(resolve => resolve()); let loop = async () => { let current = promiseFactories.shift() if (current) { await current(); return loop(); } else { finalResolve() } } chain.then(loop).catch(finalReject) return chain; } queue( promiseFactoriesOrWhatever, r => { console.log('final resolve', r) }, e => { console.log('final reject', e) }, results ) })).catch(error => { console.log(error); }); }, 40000) //1200000 = 40min process.on('unhandledRejection', function (err) { throw err; }); process.on('uncaughtException', function (err) { console.log(err) })<file_sep>import React from 'react'; import {Link} from 'react-router-dom'; import {Field, Form, withFormik} from 'formik' import * as Yup from 'yup' import {signUp} from '../../../actions' import {connect} from 'react-redux' import ReCAPTCHA from "react-google-recaptcha" function onChange(value) { console.log("Captcha value:", value); } const FormikForm = ({ values, touched, errors, status, isSubmitting }) => (<section style={{width: '400px'}}> <div className="container"> <div className="row h-100 justify-content-md-center"> <Form className="card border-0 p-4 shadow"> <h1 className="h4 lined"><span>SIGN UP</span></h1> <fieldset className="form-group"> <label className="small">Username</label> <Field className="form-control" type="text" name="username" placeholder="Username"/> {touched.username && errors.username && <small className="form-text text-danger">{errors.username}</small>} </fieldset> <fieldset className="form-group"> <label className="small">Email</label> <Field className="form-control" type="text" name="email" placeholder="<EMAIL>"/> <Field type="hidden" name="ip" value={window.ip}/> {touched.email && errors.email && <small className="form-text text-danger">{errors.email}</small>} </fieldset> <div className="row"> <fieldset className="col-md-6 form-group"> <label className="small">Name</label> <Field className="form-control" type="text" name="name" placeholder="Name"/> {touched.name && errors.name && <small className="form-text text-danger">{errors.name}</small>} </fieldset> <fieldset className="col-md-6 form-group"> <label className="small">Surname</label> <Field className="form-control" type="text" name="surname" placeholder="Surname"/> {touched.surname && errors.surname && <small className="form-text text-danger">{errors.surname}</small>} </fieldset> </div> <fieldset className="form-group"> <label className="small">Password</label> <Field className="form-control" type="password" name="password" placeholder="<PASSWORD>"/> {touched.password && errors.password && <small className="form-text text-danger">{errors.password}</small>} </fieldset> {status && status.error && <div className="alert alert-danger"> <small>{status.error}</small> </div>} {status && status.success && <div className="alert alert-success"> <small>{status.success}</small> </div>} <p className="text-muted text-center small">By creating an account, you agree to our <Link to="/tos">Terms of Service</Link>&nbsp; and <Link to="/privacy">Privacy Policy</Link>. </p> <p><ReCAPTCHA sitekey="<KEY>" onChange={onChange} /></p> <button className="btn btn-primary w-100" type="submit" disabled={isSubmitting}> {isSubmitting && <span><i className="fa fa-circle-notch fa-spin"></i>&nbsp;</span>} Create my account </button> <p className="pt-4 text-center small">You can <Link to="/signin">sign in</Link> if you have an account already.</p> </Form> </div> </div> </section> ); const EnhancedForm = withFormik({ mapPropsToValues() { let ip = null if (typeof window.ip !== 'undefined') { ip = window.ip } return { username: '', ip: '', email: '', name: '', surname: '', password: '', } }, validationSchema: Yup.object().shape({ username: Yup.string().matches(/^[A-Za-z0-9]+(?:[._-][A-Za-z0-9]+)*$/, 'Username only contain english characters and (_,-,.). Also usernames must start and end with a letter or number.') .required('Username is required'), email: Yup.string().email('Please write a correct email address').required('Email is required'), name: Yup.string().required('Name is required'), surname: Yup.string().required('Surname is required'), password: Yup.string().min(8, 'Password must be 8 characters or longer') .matches(/[a-z]/, 'Password must contain at least one lowercase char') .matches(/[A-Z]/, 'Password must contain at least one uppercase char') .matches(/[a-zA-Z]+[^a-zA-Z\s]+/, 'at least 1 number or special char (@,!,#, etc).'), }), async handleSubmit(values, {props, resetForm, setFieldError, setSubmitting, setStatus}) { setStatus(null); try { await props.signUp(values); setStatus({'success': 'Your account has been created successfully!'}) window.signUp = 1 setSubmitting(false); //resetForm(); } catch (errors) { //setStatus({'error': errors}) //setSubmitting(false); } } })(FormikForm); const mapStateToProps = (state) => { return {me: state.auth.me, langs: state.langs} }; const mapDispatchToProps = (dispatch) => { return { signUp: (values) => { dispatch(signUp(values)); }, } }; export default connect(mapStateToProps, mapDispatchToProps)(EnhancedForm); <file_sep>import {EN, CZ, IT} from '../actions/types'; export const reducer = (state = {}, action) => { switch (action.type) { case EN: return {...state, local: 'en'; case CZ: return {...state, local: 'cz'}; case IT: return {...state, local: 'it'}; default: return {...state, local: 'en'}; } }; <file_sep>import React, {Component} from 'react'; import {BootstrapTable, TableHeaderColumn, InsertModalFooter} from 'react-bootstrap-table'; import {connect} from "react-redux"; import axios from 'axios'; import cookie from 'browser-cookies'; import Breadcrumbs from '../Breadcrumbs'; const API_URL = process.env.REACT_APP_API_URL; const STRAPI_URL = process.env.STRAPI_URL; class DataGrid extends Component { constructor(props) { super(props); this.state = { me: props.me, items: [], categories: [] }; } getState = () => { return this.state; }; createCustomModalFooter = (closeModal, save) => { return ( <InsertModalFooter className='my-custom-class' saveBtnText='Create Your Add!' closeBtnText='Close' closeBtnContextual='btn-warning' saveBtnContextual='btn-success' closeBtnClass='my-close-btn-class' saveBtnClass='my-save-btn-class' beforeClose={this.beforeClose} beforeSave={this.beforeSave} onModalClose={() => this.handleModalClose(closeModal)} onSave={() => this.handleSave(save)}/> ); // If you want have more power to custom the child of InsertModalFooter, // you can do it like following // return ( // <InsertModalFooter // onModalClose={ () => this.handleModalClose(closeModal) } // onSave={ () => this.handleSave(save) }> // { ... } // </InsertModalFooter> // ); }; onClickDel(cell, row, rowIndex) { console.log('Product #', rowIndex); console.log(row.id); var that = this; axios.delete(`${API_URL}/pages/${row.id}`, {data: {id: row.id}}) .then(function(response) { console.log(response.data); if (response.data.count) { that.requestData(); } }); } cellButton(cell, row, enumObject, rowIndex) { return ( <div> <button className="btn btn-sm btn-danger" type="button" onClick={() => this.onClickDel(cell, row, rowIndex) } ><span className="fas fa-times"></span>&nbsp; </button> <a href={'ads/' + row.id}> <button className="btn btn-sm btn-info" type="button"> <span className="fas fa-eye"></span>&nbsp; </button> </a> {/* <Uploader />*/} </div> /* '<button type="button" class="btn btn-xs btn-info">\n' + ' <span class="fas fa-pencil-square-o"></span>&nbsp;\n' + '</button>';*/ ); } requestData() { console.log('this.state.me'); console.log(this.state.me.id); axios.all([ axios.get(`${API_URL}/pages?filter=%7B%22where%22%3A%7B%22author%22%3A%22${this.state.me.id}%22%7D%7D`), axios.get(`${API_URL}/upload_files`), axios.get(`${API_URL}/categories?filter[where][local]=${cookie.get('local')}`) ]).then(axios.spread((pages, files, cats) => { console.log(pages); let categories = []; for (let i = 0; i < cats.data.length; i++) { categories.push(cats.data[i].name); } let newProducts = []; for (let i = 0; i < pages.data.length; i++) { let imgSrc = 'https://dummyimage.com/160x160/000/fff.png&text=not+found'; if (typeof pages.data[i].donor_images != 'undefined' && pages.data[i].donor_images.length) { imgSrc = pages.data[i].donor_images[0]; } for (let c = 0; c < files.data.length; c++) { if (files.data[c].related.length) { if (pages.data[i].id === files.data[c].related[0].ref) { imgSrc = `${STRAPI_URL}/${files.data[c].url}`; } } } console.log(this.state.me.username); console.log(this.state.me.id); newProducts.push({ id: pages.data[i].id, category: pages.data[i].category_title, title: pages.data[i].title, text: pages.data[i].text, locality: pages.data[i].locality, price: pages.data[i].price, currency: pages.data[i].currency, local: pages.data[i].local, phone: pages.data[i].phone, image: imgSrc }); setTimeout(() => { var formsCollection = document.getElementsByClassName("imgUpload"); for (var i = 0; i < formsCollection.length; i++) { console.log('formsCollection[i].id'); console.log(formsCollection[i].id); const formElement = document.getElementById(formsCollection[i].id); let img = document.getElementById('img_' + formsCollection[i].id); formElement.addEventListener('submit', (e) => { e.preventDefault(); const request = new XMLHttpRequest(); request.onreadystatechange = function() { console.log(request.responseText); try { console.log(request.responseText); var imgObj = JSON.parse(request.responseText); // eslint-disable-next-line if (request.readyState == 4 && request.status == 200) { if (typeof imgObj[0].url === 'string') { /* if (imgObj[0].url.indexOf('localhost')) { imgObj[0].url = imgObj[0].url.replace('localhost', 'localhost') }*/ console.log(imgObj[0].url); console.log(imgObj[0].url); img.src = imgObj[0].url; img.alt = imgObj[0].name; } } else { //alert('something went wrong, request state ' + request.readyState) } } catch (err) { console.log(err.message); } }; request.open('POST', `${STRAPI_URL}/upload`); request.send(new FormData(formElement)); }); } }, 500); } this.setState({ items: newProducts, categories: categories.sort() }); console.log(this.state); })); } componentDidMount() { this.requestData(); } customLocalField = (column, attr, editorClass, ignoreEditable) => { return (<div>&nbsp; <select name="local" {...attr}> <option key='cz' value='cz'>cz</option> <option key='it' value='it'>it</option> </select>&nbsp; {/*<input type="text" value="title" name="title" placeholder="Title" style={{width:'250px'}} { ...attr }/>&nbsp;*/} </div> ); }; customAuthorHiddenField = (column, attr, editorClass, ignoreEditable) => { return (<input style={{height: 0}} name="author" type="hidden" value={this.state.me.id} {...attr} />); }; customAuthorNameHiddenField = (column, attr, editorClass, ignoreEditable) => { return (<input name="author_name" type="hidden" value={this.state.me.username} {...attr} />); }; customCurrencyField = (column, attr, editorClass, ignoreEditable) => { return (<div>&nbsp; {/*<input type="text" name="price" style={{width: '70px'}}/>&nbsp;*/} <select name="currency" {...attr}> <option key='noval' value='noval'>currency</option> <option key='kč' value='kč'>kč</option> <option key='eur' value='eur'>eur</option> </select> </div> ); }; createCustomModalHeader(onClose, onSave) { /* const headerStyle = { fontWeight: 'bold', textAlign: 'center', lineHeight: 0.3, margin: 0, padding: 0 };*/ return ( <span/> ); } beforeClose(e) { console.log(` [Custom Event ]: Modal close event triggered !`); } beforeSave(e) { console.log(` [Custom Event ]: Modal save event triggered !`); } handleModalClose(closeModal) { // Custom your onCloseModal event here, // it's not necessary to implement this function if you have no any process before modal close console.log('This is my custom function for modal close event'); closeModal(); } handleSave(save) { // Custom your onSave event here, // it's not necessary to implement this function if you have no any process before save console.log('This is my custom function for save event'); //console.log(save); save(); } onAfterInsertRow(row) { axios.all([ axios.get(`${API_URL}/categories`) ]).then(axios.spread((cats) => { cats.data.forEach(myFunction); let catName = ''; let catId = ''; let catUrl = ''; function myFunction(item, index) { if (item.name === row.category) { catName = item.name; catId = item.id; catUrl = item.url; var sendData = { "local": row.local, "title": row.title, "category": catId, "category_title": catName, "urlcategory": catUrl, "url": catUrl, "text": row.text, "images": "string", "donor_images": [ {} ], "donor": false, "edited": false, "author_name": row.author_name, "author": row.author, "phone": "string", "locality": row.locality, "localityurl": "", "price": row.price, "currency": row.currency, "views": "string", "comment": "string", "commenttype": "string", "parsed": true, "active": true }; axios.post(`${API_URL}/pages`, sendData) .then(function(response) { window.location.reload(); console.log('response'); console.log(response); }) .catch(function(error) { console.log(error); }); } } })); } render() { const options = { headerTitle: true, insertModalHeader: this.createCustomModalHeader, insertModalFooter: this.createCustomModalFooter, // insertModalBody: this.createCustomModalBody, afterInsertRow: this.onAfterInsertRow }; return ( <div> <div className="breadcrumbs"> <Breadcrumbs/> </div> <BootstrapTable data={this.state.items} options={options} insertRow={false} remote striped hover condensed > <TableHeaderColumn dataField="title" editable={{type: 'text'}}>Title (required)</TableHeaderColumn> <TableHeaderColumn dataField="category" editable={{ type: 'select', options: {values: this.state.categories, defaultValue: 1} }} isKey dataAlign="center" dataSort>Category</TableHeaderColumn> <TableHeaderColumn dataField="text" hidden={true} editable={{type: 'textarea'}}>Description (required)</TableHeaderColumn> <TableHeaderColumn dataField="price" hidden={true} editable={{type: 'text'}}>Price</TableHeaderColumn> <TableHeaderColumn dataField="currency" hidden={true} customInsertEditor={{getElement: this.customCurrencyField}}>Currency</TableHeaderColumn> <TableHeaderColumn dataField="locality" hidden={true} editable={{type: 'text'}} dataAlign="center" dataSort>Address</TableHeaderColumn> <TableHeaderColumn dataField="phone" hidden={true} editable={{type: 'text'}} dataAlign="center" dataSort>Phone</TableHeaderColumn> <TableHeaderColumn width='100px' editable={{type: 'hidden'}} dataField='button' dataFormat={this.cellButton.bind(this)} /> </BootstrapTable> </div> ); } } const mapStateToProps = (state) => { return {me: state.auth.me, user: state.system.data}; }; export default connect(mapStateToProps)(DataGrid); <file_sep>import React from 'react'; import {Field, Form, withFormik} from 'formik'; import * as Yup from 'yup'; import {settingsAccount} from '../../actions'; import {bindActionCreators} from 'redux'; import {connect} from 'react-redux'; import Breadcrumbs from '../Breadcrumbs'; let setSubmittingHigher; const FormikForm = ({ values, touched, errors, isSubmitting }) => ( <div> <div className="breadcrumbs"> <Breadcrumbs/> </div> <div className="row justify-content-md-center"> <Form className="col-md-6"> <fieldset className="form-group"> <Field className="form-control" type="text" name="username" placeholder="Username"/> {touched.username && errors.username && <small className="form-text text-danger">{errors.username}</small>} </fieldset> <fieldset className="form-group"> <Field className="form-control" type="text" name="email" placeholder="<EMAIL>"/> {touched.email && errors.email && <small className="form-text text-danger">{errors.email}</small>} </fieldset> <div className="row"> <fieldset className="col-md-6 form-group"> <label>Name</label> <Field className="form-control" type="text" name="name" placeholder="Name"/> {touched.name && errors.name && <small className="form-text text-danger">{errors.name}</small>} </fieldset> <fieldset className="col-md-6 form-group"> <label>Surname</label> <Field className="form-control" type="text" name="surname" placeholder="Surname"/> {touched.surname && errors.surname && <small className="form-text text-danger">{errors.surname}</small>} </fieldset> </div> <fieldset className="form-group"> <Field className="form-control" component="textarea" name="bio" placeholder="Write something short about you"/> {touched.bio && errors.bio && <small className="form-text text-danger">{errors.bio}</small>} </fieldset> <button className="btn btn-primary" type="submit" disabled={isSubmitting}> {isSubmitting && <span><i className="fa fa-circle-notch fa-spin"/>&nbsp;</span>} Update my Account </button> </Form> </div> </div> ); const EnhancedForm = withFormik({ mapPropsToValues({me}) { return { username: me.username || '', email: me.email || '', name: me.name || '', surname: me.surname || '', bio: me.bio || '' }; }, validationSchema: Yup.object().shape({ username: Yup.string().required('Username is required'), email: Yup.string().email('Please write a correct email address').required('Email is required'), name: Yup.string().required('Name is required'), surname: Yup.string().required('Surname is required'), bio: Yup.string().max(200, 'Short bio must be under 200 characters or shorter') }), handleSubmit(values, {props, setSubmitting}) { setSubmittingHigher = setSubmitting; props.settingsAccount(values); } })(FormikForm); const mapStateToProps = (state) => { typeof setSubmittingHigher === 'function' && setSubmittingHigher(false); return {authenticated: state.auth.authenticated, me: state.auth.me}; }; const mapDispatchToProps = dispatch => (bindActionCreators({ settingsAccount }, dispatch)); export default connect(mapStateToProps, mapDispatchToProps)(EnhancedForm); <file_sep>export const ERROR = 'error'; export const SUCCESS = 'success'; export const DATA = 'data'; export const FILE = 'file'; export const EN = 'en'; export const CZ = 'cz'; export const IT = 'it'; export const AUTH_USER = 'auth_user'; export const UNAUTH_USER = 'unauth_user'; export const AUTH_ERROR = 'auth_error'; export const CHANGEPASSWORD_ERROR = 'changepassword_error'; export const CHANGEPASSWORD_SUCCESS = 'changepassword_success'; <file_sep>import React, {Component} from 'react'; import {Link} from 'react-router-dom'; import {connect} from 'react-redux'; import {getUsers} from '../../actions'; class List extends Component { constructor(props) { super(props); this.state = { me: props.me, users: null, } } componentWillReceiveProps(props) { if (this.state.users !== props.users) { this.setState({ users: props.users }) } } componentDidMount() { //if (!this.state.me) // return History.push('/signin'); this.props.getUsers(); } renderUsers() { // if(typeof this.props.users.map === 'function') return this.state.users.map(user => { return <div className="col-sm-4" key={user.id}> <div className="card mb-2"> <div className="card-body p-2"> <img className="img-thumbnail rounded-circle float-left mr-2" src={user.image.thumb} alt={user.name} width="100" /> <div className=""> <h3 className="h5 card-title"> <i className={user.icon}/>&nbsp;&nbsp;{user.username}</h3> <p> <small>{user.name} {user.surname}</small> </p> <div className="text-right"> <Link to={user.username} className="btn btn-sm btn-primary">PROFILE</Link> {(this.props.me.isAdmin || this.props.me.isEditor) && <Link to={'/users/edit/' + user.id} className="btn btn-sm btn-success ml-1">EDIT</Link>} </div> </div> </div> </div> </div>; }) } render() { if (!this.state.users) { return <div>Loading...</div>; } return (<React.Fragment> <div className="row"> {this.renderUsers()} </div> </React.Fragment> ); } } const mapStateToProps = (state) => { return {me: state.auth.me, users: state.system.data} }; const mapDispatchToProps = (dispatch) => { return { getUsers: () => { dispatch(getUsers()); }, } }; export default connect(mapStateToProps, mapDispatchToProps)(List);
0ec972a88411ecc0bbb8257fadcd4254c2d54c26
[ "JavaScript", "Markdown", "Shell" ]
25
JavaScript
chess4pr/classified
79cc932f939e3c143bfb3c892cc283e73f25362e
a2da3147a1f3f8d32d3226f9d8c31732cdf9420e
refs/heads/master
<file_sep>/*! * protocols.h * * Created on: Sep 19, 2012 * Author: Marco.HenryGin */ #ifndef PROTOCOLS_H_ #define PROTOCOLS_H_ /************************************************************************* * $INCLUDES *************************************************************************/ #include "hart_r3.h" /************************************************************************* * $DEFINES *************************************************************************/ #define XMIT_PREAMBLE_BYTES 8 // 9900 response, max size 15 bytes #define MAX_9900_RESP_SIZE 15 /************************************************************************* * $GLOBAL PROTOTYPES *************************************************************************/ // HART Frame Handlers void hartReceiver(WORD data); WORD sendHartFrame (void); // void initHartRxSm(void); void initRespBuffer(void); //void rtsRcv(void); /************************************************************************* * $GLOBAL VARIABLES *************************************************************************/ // Utilities extern unsigned long int flashWriteCount; // exported HART timer variables extern unsigned char szHartCmd []; // The HART Command buffer extern unsigned char szHartResp []; // The HART response buffer extern unsigned int respBufferSize; // The size of the response buffer extern int rcvBroadcastAddr; // broadcas error received flag extern unsigned long int dataTimeStamp; // Timer added for command 9 (type corrected 12/5/12 ) extern float lastRequestedCurrentValue; // The laast commanded current from command 40 // Message Counters extern unsigned long xmtMsgCounter; extern unsigned long errMsgCounter; extern unsigned long numMsgProcessed; extern unsigned long numMsgUnableToProcess; extern unsigned long numMsgReadyToProcess; extern unsigned char lastCharRcvd; //!< Last character pulled from Hart UART fifo extern unsigned char command; //!< MH: Hart received command informaiton // long address flag extern int longAddressFlag; // address byte index extern unsigned char addressStartIdx; /*! * Indicates a valid command frame has been received * * This flag is set in the main loop, when the Hart Rx state machine finds that * the LRC is correct and a valid address for this module */ extern unsigned char hartFrameRcvd; extern unsigned char addressValid; extern int parityErr; extern int overrunErr; extern int rcvLrcError; // Received LRC error flag extern WORD hartDataCount; //!< The number of data field bytes extern BYTE expectedByteCnt; //!< The received byte count, to know when we're done // Command ready for processing flag extern int commandReadyToProcess; extern unsigned char hartCommand; // flags to make sure that the loop value does not // get reported if an update is in progress extern unsigned char updateRequestSent; extern int8u loopMode; // Device Variable Status for PV extern unsigned char PVvariableStatus; // The HART error register extern unsigned int HartErrRegister; /************************************************************************* * $INLINE FUNCTIONS *************************************************************************/ #endif /* PROTOCOLS_H_ */ <file_sep>/* * \file hartMain.h * \brief Hart main application exported information * \author MH * Created on: Sep 28, 2012 */ #ifndef HARTMAIN_H_ #define HARTMAIN_H_ /************************************************************************* * $INCLUDES *************************************************************************/ /************************************************************************* * $DEFINES *************************************************************************/ /*! * Enumerated events * * These are the registered events that Hart module responds to * */ typedef enum { evNull=0, //!< Strictly is an event occupying bit location in Event memory, but ordinal gives zero evHsbRecComplete, //!< Hsb Command message has been received, 12/26/12 Moved to 1st priority // Hart Receiver evHartRxChar, //!< Hart receiver has a new element data + status in input stream, moved to 2nd priority, still 9.1mS for next evHartRcvGapTimeout, //!< Inter-character time exceded evHartRcvReplyTimer, //<! Just a silent time between master command and a slave reply evHartTransactionDone, //<! The Hart modem is set to LISTEN mode after the reply is complete, we still have // around ~78mS silent line before the bits from following Hart frame arrive ///////////////////////////// ////////////////////////// // System evTimerTick, //!< general purpose System Time tick evLastEvent //!< For implementation use: define last event } tEvent; /*! * Hsb states * * Create a basic state machine to recover from errors and trigger a signal * */ typedef enum { smHsbInit=0, //!< Initial State for the HSB smHsbDbXchg, //!< Data Base Exchange smHsbSync //!< After Data Base has been loaded, Hsb is sync. (is when Low power is possible) } tHsbStates; /************************************************************************* * $GLOBAL PROTOTYPES *************************************************************************/ void main (void); void _c_int00(void); //!< Entry point if we are commanded to reset /************************************************************************* * $GLOBAL VARIABLES * */ extern volatile unsigned int sEvents[]; // Word array where events are stored /************************************************************************* * $INLINE FUNCTIONS *************************************************************************/ // Note on implementation of Events: // A bit within a word is assigned for every event. Basic macro operations are provided: set, clear and test // When implementation finds an event as a #define, it should promote the use of preprocessor arithmetic // when it finds as a variable, a call to function is generated // 12/28/12 = We need a Atomic operation that summarizes a no-event condition. This restriction reduces to only 16 events. // #define SET_SYSTEM_EVENT(e) ( sEvents[0] |= 0x0001 << e ) /* set the indicated event */ #define CLEAR_SYSTEM_EVENT(e) ( sEvents[0] &= ~(0x0001 << e)) /* clear the indicated event */ #define IS_SYSTEM_EVENT(e) (sEvents[0] & (0x0001<< e) ) /* Is the event set? */ #define ANY_EVENT() (sEvents[0] ? : 1 :0) /* gives a TRUE if at least one event, false other wise */ #define NO_EVENT() (sEvents[0]== 0 ? 1 : 0) /* Returns TRUE if no event , false otherwise ==>safe condition to sleep*/ #endif /* HARTMAIN_H_ */ <file_sep>/*! * \file main9900_r3.c * \brief Command for handling the High Speed serial Bus to 9900 * Recoded on: Nov 9, 2012 * \author: MH * * Revision History: * Date Rev. Engineer Description * -------- ----- ------------ -------------- * 04/01/11 0 <NAME> Creation * */ /////////////////////////////////////////////////////////////////////////////////////////// // INCLUDES /////////////////////////////////////////////////////////////////////////////////////////// #include <msp430f5528.h> #include <string.h> #include "hardware.h" #include "hart_r3.h" #include "main9900_r3.h" #include "driverUart.h" #include "protocols.h" /////////////////////////////////////////////////////////////////////////////////////////// // LOCAL DEFINES /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// // LOCAL PROTOTYPES. /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// // GLOBAL DATA /////////////////////////////////////////////////////////////////////////////////////////// U_DATABASE_9900 u9900Database; //!< 9900 Database BOOLEAN hostActive = FALSE; //!< Flag indicating that we have a host actively communicating BOOLEAN comm9900started = FALSE; BOOLEAN updateMsgRcvd = FALSE; //!< Flag indicating an update message has been received from the 9900 and HART communications can begin BOOLEAN databaseOk = FALSE; //!< Database loaded OK flag /////////////////////////////////////////////////////////////////////////////////////////// // LOCAL DATA /////////////////////////////////////////////////////////////////////////////////////////// // Diagnostics unsigned long numMessagesRcvd = 0; unsigned long numMessagesErrored = 0; // Is the host in an comm error condition? int hostError = FALSE; // flags for determining status // The most recent comm status from the 9900 int8u lastCommStatus = POLL_LAST_REQ_GOOD; // the most recent variable status from the 9900 int8u lastVarStatus = UPDATE_STATUS_INIT; int8u varStatus = UPDATE_STATUS_GOOD; /////////////////////////////////////////////////////////////////////////////////////////// // FUNCTIONS /////////////////////////////////////////////////////////////////////////////////////////// // RE-ARRANGING CODE BELLOW // Buffer for the commands from the 9900 unsigned char sz9900CmdBuffer [MAX_9900_CMD_SIZE]; // Buffer for the response to the 9900 unsigned char sz9900RespBuffer [MAX_9900_RESP_SIZE]; // the size of the response volatile unsigned int responseSize = 0; // This is a critical variable 12/21/12 // Transmitted character counter unsigned int numMainXmitChars = 0; // If the update is delayed, set this flag int8u updateDelay = FALSE; // A request is made by the HART master int8u request = RESP_REQ_SAVE_AND_RESTART_LOOP; // There is usually a value for a request float requestValue = 0.0; float rangeRequestUpper = 0.0; // Loop mode is either operational, fixed 4, or fixed 20 int8u loopMode = LOOP_OPERATIONAL; // We have to queue requests for responses 1 and 3 int8u queueResp1 = FALSE; int8u queueResp3 = FALSE; // If we go to constant current mode, we need to see whether a save // is required when the loop goes operational again int8u saveRequested = FALSE; // flags to make sure that the loop value does not // get reported if an update is in progress unsigned char updateInProgress = FALSE; unsigned char updateRequestSent = FALSE; // Trim command flags unsigned char setToMinValue = FALSE; unsigned char setToMaxValue = FALSE; // Transmit flag. Set when transmit is active. Used to insure that the // transmit & rcv ISRs don't run simultaneously unsigned char transmitMode = FALSE; // Add a counter to remind the 9900 of the current mode every (actually) 20 update messages // MH - changed to unsigned int 1/24/13 unsigned int modeUpdateCount = 0; // Device Variable Status for PV. initialize to BAD, constant unsigned char PVvariableStatus = VAR_STATUS_BAD | LIM_STATUS_CONST; // The timer for signaling HART is update messages don't occur unsigned long UpdateMsgTimeout = 0; // local prototype void killMainTransmit(void); // 9900 Factory database const DATABASE_9900 factory9900db = { 62, // DB Length "4640500111", // serial number "3-9900-1X ", // Model string "10-04a", // SW REV 0.0, // LOOP_SET_LOW_LIMIT 15.0, // LOOP_SET_HIGH_LIMIT 0.0, // LOOP_SETPOINT_4MA 14.0, // LOOP_SETPOINT_20MA 4.0, // LOOP_ADJ_4MA 20.0, // LOOP_ADJ_20MA 1, // LOOP_ERROR_VAL 0, // LOOP_MODE; 2, // MEASUREMENT_TYPE; 'A', // GF9900_MS_PARAMETER_REVISION; 'Q', // Hart_Dev_Var_Class; 0x3b, // UnitsPrimaryVar; 0x20, // UnitsSecondaryVar; 0, // Pad; // Just to be even 0x0972 // checksum; }; /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: Process9900Command() // // Description: // // Processes the command from the 9900 UART, sends response // // Parameters: void // // Return Type: void. // // Implementation notes: // // // /////////////////////////////////////////////////////////////////////////////////////////// BOOLEAN Process9900Command(void) { // First, make sure the command is for the HART modem. // First character must be an ATTENTION character, followed // by the HART_COMMAND character. If not, then return. if ((ATTENTION != sz9900CmdBuffer[CMD_ATTN_IDX]) || (HART_ADDRESS != sz9900CmdBuffer[CMD_ADDR_IDX])) { // either it isn't a command or it's not for the HART module return FALSE; } // The command type is the 3rd character in the command switch (sz9900CmdBuffer[CMD_CMD_IDX]) { case HART_POLL: Process9900Poll(); break; case HART_UPDATE: // Code for QUICK_START is always in // if this is the first update message, check the current mode, and set . if ((FALSE == comm9900started) || (UPDATE_REMINDER_COUNT <= modeUpdateCount)) { // reset the update reminder count modeUpdateCount = 0; if (databaseOk) { // Now check the flash to make sure the current mode is // set correctly if (CURRENT_MODE_DISABLE == startUpDataLocalNv.currentMode) { // Tell the 9900 to go to fixed current mode at 4 mA setFixedCurrentMode(4.0); setPrimaryStatusBits(FD_STATUS_PV_ANALOG_FIXED); setSecondaryStatusBits(FD_STATUS_PV_ANALOG_FIXED); currentMsgSent = FIXED_CURRENT_MESSAGE_SENT; } else // NOT in multidrop mode { // If the loop reporting is not operational, we want to make sure // the 9900 is reminded about the fixed current output if (LOOP_OPERATIONAL == loopMode) { // Tell the 9900 to go to loop reporting current mode setFixedCurrentMode(0.0); clrPrimaryStatusBits(FD_STATUS_PV_ANALOG_FIXED); clrSecondaryStatusBits(FD_STATUS_PV_ANALOG_FIXED); currentMsgSent = LOOP_CURRENT_MESSAGE_SENT; } else { // Tell the 9900 to go to fixed current mode at // the last requested command value setFixedCurrentMode(lastRequestedCurrentValue); setPrimaryStatusBits(FD_STATUS_PV_ANALOG_FIXED); setSecondaryStatusBits(FD_STATUS_PV_ANALOG_FIXED); } } // Set the 9900 comm flag true so that the timeout will not occur comm9900started = TRUE; } } Process9900Update(); modeUpdateCount++; break; case HART_DB_LOAD: Process9900DatabaseLoad(); break; default: // We have no idea what the message is, but it has a <CR>, so NACK it Nack9900Msg(); break; } return TRUE; } /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: Process9900Poll() // // Description: // // Processes the poll command from the 9900 UART, sends response // // Parameters: void // // Return Type: void. // // Implementation notes: // // // /////////////////////////////////////////////////////////////////////////////////////////// void Process9900Poll(void) { // Set the response size to 0 to start responseSize = 0; // capture the last comm status lastCommStatus = sz9900CmdBuffer[CMD_FIRST_DATA]; // determine the status to reply with int8u status; if (databaseOk) { if (hostActive) { if (hostError) { status = RESP_HOST_ERROR; } else { status = RESP_ACTIVE_HOST; } } else { status = RESP_GOOD_NO_ACTIVE_HOST; } } else { status = RESP_NO_OR_BAD_DB; } // Build the poll response sz9900RespBuffer[RSP_ADDR_IDX] = HART_ADDRESS; ++responseSize; sz9900RespBuffer[RSP_ADDR_IDX+1] = HART_SEPARATOR; ++responseSize; sz9900RespBuffer[RSP_REQ_IDX] = request; ++responseSize; sz9900RespBuffer[RSP_REQ_IDX+1] = HART_SEPARATOR; ++responseSize; sz9900RespBuffer[RSP_STATUS_IDX] = status; ++responseSize; if (RESP_REQ_NO_REQ == request) { sz9900RespBuffer[RSP_STATUS_IDX+1] = HART_MSG_END; ++responseSize; } else { // Put in the separator sz9900RespBuffer[responseSize] = HART_SEPARATOR; ++responseSize; // Send the value back convertFloatToAscii(requestValue, &(sz9900RespBuffer[responseSize])); responseSize += 8; // Carriage return sz9900RespBuffer[responseSize] = HART_MSG_END; ++responseSize; // Now, reset the request to none, 1, or 3 if (queueResp1) { queueResp1 = FALSE; request = RESP_REQ_SAVE_AND_RESTART_LOOP; requestValue = 0.0; } else if (queueResp3) { queueResp3 = FALSE; queueResp1 = TRUE; request = RESP_REQ_CHANGE_20MA_POINT; requestValue = rangeRequestUpper; } else { request = RESP_REQ_NO_REQ; } } // Signal that a loop change request has been sent if (TRUE == updateInProgress) { updateRequestSent = TRUE; } // Load the transmit buffer & send startMainXmit(); } /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: Process9900Update() // // Description: // // Processes the update command from the 9900 UART, sends response // // Parameters: void // // Return Type: void. // // Implementation notes: // // // /////////////////////////////////////////////////////////////////////////////////////////// void Process9900Update(void) { fp32 tempVal; int index; int success; int8u tempChar; responseSize = 0; // Work through the message, upadating everything // grab the PV as bytes for (index = 0; index < 4; ++index) { success = HexAsciiToByte(sz9900CmdBuffer+UPDATE_PV_START_INDEX + (2*index), &tempChar); if (success) { tempVal.byteVal[index] = tempChar; } else { // respond with a NACK Nack9900Msg(); // no sense going further, return return; } } // If we're here, it means we picked up the PV, so write the new value PVvalue = tempVal.floatVal; // the next 4 bytes are the secondary value, which may or may not be real. for (index = 0; index < 4; ++index) { success = HexAsciiToByte(sz9900CmdBuffer+UPDATE_SV_START_INDEX + (2*index), &tempChar); if (success) { tempVal.byteVal[index] = tempChar; } else { // respond with a NACK Nack9900Msg(); // no sense going further, return return; } } // If we're here, it means we picked up the SV, so write the new value SVvalue = tempVal.floatVal; // the next 4 bytes are the loop current value. for (index = 0; index < 4; ++index) { success = HexAsciiToByte(sz9900CmdBuffer+UPDATE_MA4_20_START_INDEX + (2*index), &tempChar); if (success) { tempVal.byteVal[index] = tempChar; } else { // respond with a NACK Nack9900Msg(); // no sense going further, return return; } } // If we're here, it means we picked up the loop current, so write the new value ma4_20 = tempVal.floatVal; // Now the var status varStatus = sz9900CmdBuffer[UPDATE_VAR_STATUS_INDEX]; // Per +GF+, set the "PV out of range" bit when the status is anything other // than good from the 9900 if (UPDATE_STATUS_GOOD == varStatus) { clrPrimaryStatusBits(FD_STATUS_PV_OUT_OF_LIMITS); clrSecondaryStatusBits(FD_STATUS_PV_OUT_OF_LIMITS); startUpDataLocalV.StandardStatus0 &= ~SS0_HARDWARE_PROBLEM; if (varStatus != lastVarStatus) { clrPrimaryMoreAvailable(); clrSecondaryMoreAvailable(); } } else { setPrimaryStatusBits(FD_STATUS_PV_OUT_OF_LIMITS); setSecondaryStatusBits(FD_STATUS_PV_OUT_OF_LIMITS); startUpDataLocalV.StandardStatus0 |= SS0_HARDWARE_PROBLEM; if (varStatus != lastVarStatus) { setPrimaryMoreAvailable(); setSecondaryMoreAvailable(); } } // Save the var status for the next update lastVarStatus = varStatus; // Now save the comm status lastCommStatus = sz9900CmdBuffer[UPDATE_COMM_STATUS_INDEX]; // If we're here, we can build a normal response // determine the status to reply with // If both update flags are set, clear them if ((TRUE == updateInProgress) && (TRUE == updateRequestSent) && (POLL_LAST_REQ_GOOD == lastCommStatus)) { updateRequestSent = FALSE; updateInProgress = FALSE; } int8u status; if (databaseOk) { if (hostActive) { if (hostError) { status = RESP_HOST_ERROR; } else { status = RESP_ACTIVE_HOST; } } else { status = RESP_GOOD_NO_ACTIVE_HOST; } } else { status = RESP_NO_OR_BAD_DB; } // Build the update response sz9900RespBuffer[RSP_ADDR_IDX] = HART_ADDRESS; ++responseSize; sz9900RespBuffer[RSP_ADDR_IDX+1] = HART_SEPARATOR; ++responseSize; sz9900RespBuffer[RSP_REQ_IDX] = request; ++responseSize; sz9900RespBuffer[RSP_REQ_IDX+1] = HART_SEPARATOR; ++responseSize; sz9900RespBuffer[RSP_STATUS_IDX] = status; ++responseSize; if (RESP_REQ_NO_REQ == request) { sz9900RespBuffer[RSP_STATUS_IDX+1] = HART_MSG_END; ++responseSize; } else { // Put in the request sz9900RespBuffer[responseSize] = HART_SEPARATOR; ++responseSize; // Send the value back convertFloatToAscii(requestValue, &(sz9900RespBuffer[responseSize])); responseSize += 8; // Carriage return sz9900RespBuffer[responseSize] = HART_MSG_END; ++responseSize; // Now, reset the request to none, 1, or 3 if (queueResp1) { queueResp1 = FALSE; request = RESP_REQ_SAVE_AND_RESTART_LOOP; requestValue = 0.0; } else if (queueResp3) { queueResp3 = FALSE; queueResp1 = TRUE; request = RESP_REQ_CHANGE_20MA_POINT; requestValue = rangeRequestUpper; } else { request = RESP_REQ_NO_REQ; } } // Signal that a loop change request has been sent if (TRUE == updateInProgress) { updateRequestSent = TRUE; } // Load the transmit buffer & send startMainXmit(); // Set the flag TRUE so HART communications can begin updateMsgRcvd = TRUE; // Calculate the status for HART updatePVstatus(); } /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: Process9900DatabaseLoad() // // Description: // // Processes the database load command from the 9900 UART, sends response // // Parameters: void // // Return Type: void. // // Implementation notes: // // // /////////////////////////////////////////////////////////////////////////////////////////// void Process9900DatabaseLoad(void) { int success; int8u index; int8u numDbBytesSent; int8u startAddress; int8u currentData; int8u msgStatus; // Process the request to load the database // Grab the starting offset into the DB success = HexAsciiToByte((sz9900CmdBuffer+DB_ADDR_START_IDX), &startAddress); if (!success) { // Set the flag to indicate there's a DB problem databaseOk = FALSE; // respond with a NACK Nack9900Msg(); // no sense going further, return return; } // grab the number of bytes being transmitted success = HexAsciiToByte((sz9900CmdBuffer+DB_BYTE_COUNT_IDX), &numDbBytesSent); if (!success) { // Set the flag to indicate there's a DB problem databaseOk = FALSE; // respond with a NACK Nack9900Msg(); // no sense going further, return return; } // Now pull off the status - is this the last message? msgStatus = sz9900CmdBuffer[DB_STATUS_IDX]; // Check to make sure the status is valid, bail if it isn't if (!((DB_EXPECT_MORE_DATA == msgStatus) || (DB_LAST_MESSAGE == msgStatus))) { // Set the flag to indicate there's a DB problem databaseOk = FALSE; // respond with a NACK Nack9900Msg(); // no sense going further, return return; } // Now convert the data, one character pair at a time for (index = 0; index < numDbBytesSent; ++index) { success = HexAsciiToByte((sz9900CmdBuffer+DB_FIRST_DATA_IDX+(2*index)), &currentData); if (!success) { // Set the flag to indicate there's a DB problem databaseOk = FALSE; // respond with a NACK Nack9900Msg(); // no sense going further, return return; } // write to the DB u9900Database.bytes[startAddress+index] = currentData; } if (DB_LAST_MESSAGE == msgStatus) { // Compare the calculated checksum to the downloaded checksum if (Calc9900DbChecksum() == u9900Database.db.checksum) { // Set the flag to indicate we're good databaseOk = TRUE; // Respond with and ACK Ack9900Msg(); // Now update the default sensor type UpdateSensorType(); } else { // Set the flag to indicate there's a DB problem databaseOk = FALSE; // respond with a NACK Nack9900Msg(); } } else { // Just respond with an ACK Ack9900Msg(); } } /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: Nack9900Msg() // // Description: // // Sends 9900 NACK response // // Parameters: void // // Return Type: void. // // Implementation notes: // // // /////////////////////////////////////////////////////////////////////////////////////////// void Nack9900Msg(void) { responseSize = 0; // Build the NACK response sz9900RespBuffer[RSP_ADDR_IDX] = HART_ADDRESS; ++responseSize; sz9900RespBuffer[RSP_ADDR_IDX+1] = HART_SEPARATOR; ++responseSize; sz9900RespBuffer[RSP_REQ_IDX] = HART_NACK; ++responseSize; sz9900RespBuffer[ACK_NACK_CR_IDX] = HART_MSG_END; ++responseSize; // Load the transmit buffer & send startMainXmit(); } /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: Ack9900Msg() // // Description: // // Sends a 9900 ACK response // // Parameters: void // // Return Type: void. // // Implementation notes: // // // /////////////////////////////////////////////////////////////////////////////////////////// void Ack9900Msg(void) { responseSize = 0; // Build the ACK response sz9900RespBuffer[RSP_ADDR_IDX] = HART_ADDRESS; ++responseSize; sz9900RespBuffer[RSP_ADDR_IDX+1] = HART_SEPARATOR; ++responseSize; sz9900RespBuffer[RSP_REQ_IDX] = HART_ACK; ++responseSize; sz9900RespBuffer[ACK_NACK_CR_IDX] = HART_MSG_END; ++responseSize; // Load the transmit buffer & send startMainXmit(); } /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: Calc9900DbChecksum() // // Description: // // Calculates the checksum on the 9900 database // // Parameters: void // // Return Type: int16u - the calculated checksum. // // Implementation notes: // // // /////////////////////////////////////////////////////////////////////////////////////////// int16u Calc9900DbChecksum(void) { int index; int16u calcChksum = 0; // Now just add up all the bytes, except the checksum at the end for (index = 0; index < sizeof(DATABASE_9900)-2; ++index) { calcChksum += (int16u)(u9900Database.bytes[index]); } return calcChksum; } /****************************************************** * * A0 (Main) UART Functions * ******************************************************/ /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: startMainXmit() // // Description: // // Adds characters to the main transmit queue. Returns TRUE if there's room to accept them all, // FALSE otherwise. It also signals the UART to start transmitting // // Parameters: void // // Return Type: void // // Implementation notes: // // // /////////////////////////////////////////////////////////////////////////////////////////// void startMainXmit (void) { // Make sure we actually have something to transmit // 12/17/2012 MH- Validate MAX size if (0 == responseSize || responseSize > MAX_9900_RESP_SIZE) { return; } BYTE *pChar= sz9900RespBuffer; while(responseSize--) putcUart(*pChar++, &hsbUart); } /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: resetForNew9900Message() // // Description: // // Sets up to start receiving a new message after a timeout // // Parameters: void // // Return Type: void. // // Implementation notes: // // // /////////////////////////////////////////////////////////////////////////////////////////// void resetForNew9900Message(void) { // stop the timer //==> TODO any side effect? stopMainMsgTimer(); // Make sure the flags are clear // make sure the characters can be received //==> TODO any side effect? enableMainRcvIntr(); responseSize = 0; } /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: setFixedCurrentMode() // // Description: // // Utility to set fixed current mode // // Parameters: void // // Return Type: unsigned char: // 0 = RESP_SUCCESS, // 3 = PASSED_PARM_TOO_LARGE // 4 = PASSED_PARM_TOO_SMALL // // Implementation notes: // // /////////////////////////////////////////////////////////////////////////////////////////// unsigned char setFixedCurrentMode(float cmdValue) { unsigned char resp = RESP_SUCCESS; // if we are here, we are in the correct loop mode, so see if we can adjust if (0.00 == cmdValue) { #if 0 MH- Using different HSB control 11/27/12 // Shut off the 9900 interrupts disableMainRcvIntr(); disableMainTxIntr(); #endif // the request is 7 to leave the fixed current state loopMode = LOOP_OPERATIONAL; request = (FALSE == saveRequested) ? RESP_REQ_CHANGE_RESUME_NO_SAVE : RESP_REQ_SAVE_AND_RESTART_LOOP; saveRequested = FALSE; requestValue = cmdValue; // Clear the trim flags setToMinValue = FALSE; setToMaxValue = FALSE; #if 0 MH- Using different HSB control 11/27/12 // re-enable the interrupts if (TRUE == transmitMode) { enableMainTxIntr(); } enableMainRcvIntr(); #endif } else { // limit check first if (cmdValue < ADJ_4MA_LIMIT_MIN) { resp = PASSED_PARM_TOO_SMALL; } if (cmdValue > ADJ_20MA_LIMIT_MAX) { resp = PASSED_PARM_TOO_LARGE; } // store the value and mode if (!resp) { #if 0 MH- Using different HSB control 11/27/12// Shut off the 9900 interrupts disableMainRcvIntr(); disableMainTxIntr(); #endif loopMode = LOOP_FIXED_CURRENT; requestValue = cmdValue; request = RESP_REQ_CHANGE_SET_FIXED; setToMinValue = (4.0 == cmdValue) ? TRUE : FALSE; setToMaxValue = (20.0 == cmdValue) ? TRUE : FALSE; #if 0 MH- Different HSB control 11/27/12 // re-enable the interrupts if (TRUE == transmitMode) { enableMainTxIntr(); } enableMainRcvIntr(); #endif } } return resp; } /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: trimLoopCurrentZero() // // Description: // Trims the loop current to minimum // // Parameters: float - measured loop current level // // Return Type: unsigned char: // 0 = RESP_SUCCESS, // 3 = PASSED_PARM_TOO_LARGE // 4 = PASSED_PARM_TOO_SMALL // 9 = INCORRECT_LOOP_MODE, // // Implementation notes: // // /////////////////////////////////////////////////////////////////////////////////////////// unsigned char trimLoopCurrentZero(float level) { unsigned char resp = (LOOP_OPERATIONAL == loopMode) ? INCORRECT_LOOP_MODE : RESP_SUCCESS; // If the mode is wrong, just bail now if (resp) { return resp; } // Now verify the request is in limits if (level > ADJ_4MA_LIMIT_MAX) { resp = PASSED_PARM_TOO_LARGE; } else if (level < ADJ_4MA_LIMIT_MIN) { resp = PASSED_PARM_TOO_SMALL; } if (!resp) { #if 0 MH- Using different HSB control 11/27/12// Shut off the 9900 interrupts disableMainRcvIntr(); disableMainTxIntr(); #endif // We are OK so make the request to the 9900 requestValue = level; request = RESP_REQ_CHANGE_4MA_ADJ; // Queue the request to save & restart the loop saveRequested = TRUE; #if 0 MH- Different HSB control 11/27/12 // re-enable the interrupts if (TRUE == transmitMode) { enableMainTxIntr(); } enableMainRcvIntr(); #endif } return resp; } /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: trimLoopCurrentGain() // // Description: // Trims the loop current gain // // Parameters: float - measured loop current level // // Return Type: unsigned char: // 0 = RESP_SUCCESS, // 3 = PASSED_PARM_TOO_LARGE // 4 = PASSED_PARM_TOO_SMALL // 9 = INCORRECT_LOOP_MODE, // // Implementation notes: // // /////////////////////////////////////////////////////////////////////////////////////////// unsigned char trimLoopCurrentGain(float level) { unsigned char resp = (LOOP_OPERATIONAL == loopMode) ? INCORRECT_LOOP_MODE : RESP_SUCCESS; // If the mode is wrong, just bail now if (resp) { return resp; } // Now verify the request is in limits if (level > ADJ_20MA_LIMIT_MAX) { resp = PASSED_PARM_TOO_LARGE; } else if (level < ADJ_20MA_LIMIT_MIN) { resp = PASSED_PARM_TOO_SMALL; } if (!resp) { #if 0 MH- Using different HSB control 11/27/12// Shut off the 9900 interrupts disableMainRcvIntr(); disableMainTxIntr(); #endif // We are OK so make the request to the 9900 requestValue = level; request = RESP_REQ_CHANGE_20MA_ADJ; // Queue the request to save & restart the loop saveRequested = TRUE; #if 0 MH- Different HSB control 11/27/12 // re-enable the interrupts if (TRUE == transmitMode) { enableMainTxIntr(); } enableMainRcvIntr(); #endif } return resp; } /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: setUpperRangeVal() // // Description: // Sets the upper range value (span) to the present PV // // Parameters: void // // Return Type: void // // Implementation notes: // // /////////////////////////////////////////////////////////////////////////////////////////// void setUpperRangeVal(void) { #if 0 MH- Using different HSB control 11/27/12// Shut off the 9900 interrupts disableMainRcvIntr(); disableMainTxIntr(); #endif // Update the local DB with the requested values so // the modem can respond quickly u9900Database.db.LOOP_SET_HIGH_LIMIT.floatVal = PVvalue; // The present PV is the request value requestValue = PVvalue; request = RESP_REQ_CHANGE_20MA_POINT; // Queue the request for response 1 queueResp1 = TRUE; #if 0 MH- Different HSB control 11/27/12 // re-enable the interrupts if (TRUE == transmitMode) { enableMainTxIntr(); } enableMainRcvIntr(); #endif } /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: setLowerRangeVal() // // Description: // Sets the lower range value to the present PV // // Parameters: void // // Return Type: void // // Implementation notes: // // /////////////////////////////////////////////////////////////////////////////////////////// void setLowerRangeVal(void) { #if 0 MH- Using different HSB control 11/27/12// Shut off the 9900 interrupts disableMainRcvIntr(); disableMainTxIntr(); #endif // Update the local DB with the requested value so // the modem can respond quickly u9900Database.db.LOOP_SET_LOW_LIMIT.floatVal = PVvalue; // The present PV is the request value requestValue = PVvalue; request = RESP_REQ_CHANGE_4MA_POINT; // Queue the request for response 1 queueResp1 = TRUE; #if 0 MH- Different HSB control 11/27/12 // re-enable the interrupts if (TRUE == transmitMode) { enableMainTxIntr(); } enableMainRcvIntr(); #endif } /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: setBothRangeVals() // // Description: // Sets the lower range value and queues the request for the upper // // Parameters: float - upper range value // float - lower range value // // Return Type: void // // Implementation notes: // // /////////////////////////////////////////////////////////////////////////////////////////// void setBothRangeVals(float upper, float lower) { #if 0 MH- Using different HSB control 11/27/12// Shut off the 9900 interrupts disableMainRcvIntr(); disableMainTxIntr(); #endif // Update the local DB with the requested values so // the modem can respond quickly u9900Database.db.LOOP_SET_HIGH_LIMIT.floatVal = upper; u9900Database.db.LOOP_SET_LOW_LIMIT.floatVal = lower; // The present PV is the request value requestValue = lower; request = RESP_REQ_CHANGE_4MA_POINT; // Queue the request for response 3 rangeRequestUpper = upper; queueResp3 = TRUE; #if 0 MH- Different HSB control 11/27/12 // re-enable the interrupts if (TRUE == transmitMode) { enableMainTxIntr(); } enableMainRcvIntr(); #endif } /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: convertFloatToAscii() // // Description: // converts a float into an eight-byte ASCII string (little-endian) // // Parameters: float - the value to convert // unsigned char * - the 8-byte result buffer // // Return Type: void // // Implementation notes: // // /////////////////////////////////////////////////////////////////////////////////////////// void convertFloatToAscii(float value, unsigned char * respBuffer) { fp32 val; val.floatVal = value; int count; for (count = 0; count < 4; ++count) { ByteToHexAscii(val.byteVal[count], respBuffer+(2*count)); } } /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: copy9900factoryDb() // // Description: // // copy the factory database to the local // // Parameters: void // // Return Type: void. // // Implementation notes: // // // /////////////////////////////////////////////////////////////////////////////////////////// void copy9900factoryDb(void) { memcpy(&u9900Database, &factory9900db, sizeof(DATABASE_9900)); } #if 0 /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: killMainTransmit() // // Description: // // kills the transmit process // // Parameters: void // // Return Type: void. // // Implementation notes: // // // /////////////////////////////////////////////////////////////////////////////////////////// void killMainTransmit(void) { // disable the Tx interrupt disableMainTxIntr(); // turn the transmit mode flag off transmitMode = FALSE; } #endif /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: updatePVstatus() // // Description: // // updates the device variable status of PV // // Parameters: void // // Return Type: void. // // Implementation notes: // // // /////////////////////////////////////////////////////////////////////////////////////////// void updatePVstatus(void) { // Decide the PV status based upon the value of the variable status switch(varStatus) { case UPDATE_STATUS_GOOD: PVvariableStatus = VAR_STATUS_GOOD; break; case UPDATE_STATUS_CHECK_SENSOR_BAD_VALUE: // Check to see where the limits are PVvariableStatus = VAR_STATUS_BAD; if (PVvalue >= u9900Database.db.LOOP_SET_HIGH_LIMIT.floatVal) { PVvariableStatus |= LIM_STATUS_HIGH; } if (PVvalue <= u9900Database.db.LOOP_SET_LOW_LIMIT.floatVal) { PVvariableStatus |= LIM_STATUS_LOW; } break; case UPDATE_STATUS_SENSOR_NOT_PRESENT: case UPDATE_STATUS_SENSOR_UNDEFINED: case UPDATE_STATUS_WRONG_SENSOR_FOR_TYPE: default: PVvariableStatus = VAR_STATUS_BAD; break; } // Per +GF+, set the "PV out of range" bit when the status is anything other // than good from the 9900 if (UPDATE_STATUS_GOOD == varStatus) { clrPrimaryStatusBits(FD_STATUS_PV_OUT_OF_LIMITS); clrSecondaryStatusBits(FD_STATUS_PV_OUT_OF_LIMITS); startUpDataLocalV.StandardStatus0 &= ~SS0_HARDWARE_PROBLEM; if (varStatus != lastVarStatus) { clrPrimaryMoreAvailable(); clrSecondaryMoreAvailable(); } } else { setPrimaryStatusBits(FD_STATUS_PV_OUT_OF_LIMITS); setSecondaryStatusBits(FD_STATUS_PV_OUT_OF_LIMITS); startUpDataLocalV.StandardStatus0 |= SS0_HARDWARE_PROBLEM; if (varStatus != lastVarStatus) { setPrimaryMoreAvailable(); setSecondaryMoreAvailable(); } } // Save the var status for the next update lastVarStatus = varStatus; // reset the update timer UpdateMsgTimeout = 0; } <file_sep>/* * fifo.c * * Created on: Oct 1, 2012 * Author: <NAME> */ //============================================================================== // INCLUDES //============================================================================== #include "fifo.h" #include "string.h" //============================================================================== // LOCAL DEFINES //============================================================================== //============================================================================== // LOCAL PROTOTYPES. //============================================================================== //============================================================================== // GLOBAL DATA //============================================================================== //============================================================================== // LOCAL DATA //============================================================================== //============================================================================== // FUNCTIONS //============================================================================== /*! * \function void resetFifo(stFifo *pFifo, BYTE *pBuffer) * \brief reset the indicated fifo structure to initial state * * \param pFifo This is the fifo we want to reset * \param pBuffer The memory block where the fifo is located * \return none * \sa Rev3 */ /// resetFifo() /// Initialize all indexes to zero, point to buffer memory location /// /// /// void resetFifo(stFifo *pFifo, BYTE *pBuffer) { pFifo->buffer = pBuffer; pFifo->readIndex =0; pFifo->writeIndex =0; pFifo->currentLength =0; } /// /// putFifoFifo() /// put the element to the indicated Fifo /// /// \param data is the element to the fifo /// \param pFifo a pointer to the Fifo /// \return true if element gets into, FALSE if Fifo is full /// \sa Rev3 /// BOOLEAN putFifo(stFifo *pFifo, BYTE data) { if (pFifo->currentLength < pFifo->maxLength) { pFifo->buffer[pFifo->writeIndex++] = data; if(pFifo->writeIndex >= pFifo->maxLength) pFifo->writeIndex = 0; pFifo->currentLength++; return TRUE; } else return FALSE; } /// /// getFifo() /// get the oldest BYTE element from the indicated Fifo /// /// \param pFifo a pointer to the Fifo /// \return the element. Zero if no element (test before calling) /// \sa Rev3 /// BYTE getFifo(stFifo *pFifo) { if (pFifo->currentLength != 0) { BYTE tmp = pFifo->buffer[pFifo->readIndex++]; if (pFifo->readIndex >= pFifo->maxLength) pFifo->readIndex = 0; pFifo->currentLength--; return tmp; } else return '\0'; } /// /// getwFifo() /// get the oldest WORD element from the indicated Fifo /// /// \param pFifo a pointer to the Fifo /// \return the oldest WORD. Zero if no element (test before calling) /// \sa Rev3 /// WORD getwFifo(stFifo *pFifo) { if (pFifo->currentLength != 0) { WORD tmp = ((WORD *)pFifo->buffer)[pFifo->readIndex++]; if (pFifo->readIndex >= pFifo->maxLength) pFifo->readIndex = 0; pFifo->currentLength--; return tmp; } else return '\0'; } /// /// putWFifo() /// put the WORD to the indicated Fifo /// /// \param data is a WORD element to the fifo /// \param pFifo a pointer to the Fifo /// \return true if element gets into, FALSE if Fifo is full /// \sa Rev3 /// BOOLEAN putwFifo(stFifo *pFifo, WORD data) { if (pFifo->currentLength < pFifo->maxLength) { ((WORD *)pFifo->buffer)[pFifo->writeIndex++] = data; if(pFifo->writeIndex >= pFifo->maxLength) pFifo->writeIndex = 0; pFifo->currentLength++; return TRUE; } else return FALSE; } <file_sep>/*! * \file driverUart.c * \brief Serial interface for GF Hart implementation * Created on: Sep 20, 2012 * \author: MH */ //============================================================================== // INCLUDES //============================================================================== #include "define.h" #include "msp_port.h" #include "hardware.h" #include "driverUart.h" #include "hartMain.h" #include "main9900_r3.h" //============================================================================== // LOCAL DEFINES //============================================================================== /*! * Rx buffer is just for contention when CPU is busy and to avoid overrun */ #define hartRxFifoLen 8 /*! * We would like to write the whole message to buffer and go to sleep */ #define hartTxFifoLen 80 /*! * Max Rx data is 67 chars for the 50mS time slot plus gap and tolerance (+10%) */ #define hsbRxFifoLen 80 /*! * Max Tx data is 32 chars for the 50mS time slot plus gap and tolerance (+10%) */ #define hsbTxFifoLen 32 //============================================================================== // LOCAL PROTOTYPES. //============================================================================== static void initHartUart(void); static void initHsbUart(void); extern BYTE hartRxfifoBuffer[], hartTxfifoBuffer[], hsbRxfifoBuffer[], hsbTxfifoBuffer[]; // defined bellow //============================================================================== // GLOBAL DATA //============================================================================== BOOLEAN HartRxCharError; //!< The most current received data has error BOOLEAN hartRxFrameError, //!< The serial isr receiver has detected errors in present serial frame hartNewCharInRxFifo, //!< New character has been moved to the Hart receiver fifo HartRxFifoError; //!< Indicates a problem in the whole Hart Receiver Fifo (overrun) extern volatile WORD iTx9900CmdBuf; //!< Index for transmit the received command in the RX ISR stSerialStatus HartUartCharStatus; //!< the status of UartChar stSerialStatus SerialStatus; //!< a running summary of the UART // // Let the compiler do the pointer setting /*! * hartUart is the Uart instance for Hart communication */ stUart hartUart = { hartRxFifoLen, //!< Rx Buffer lengths (defines) hartTxFifoLen, //!< Tx Buffer lengths (defines) initHartUart, //!< points to msp430 init hartRxfifoBuffer, //!< static allocation for the Rx Fifo hartTxfifoBuffer, //!< static allocation for the Tx Fifo TRUE, //!< bRtsControl = TRUE // Rx Interrupt Handlers {enableHartRxIntr,disableHartRxIntr,isHartRxIntrEnabled}, // Tx Interrupt Handlers {enableHartTxIntr,disableHartTxIntr,isHartTxIntrEnabled}, // Tx Driver {enableHartTxDriver,disableHartTxDriver,isEnabledHartTxDriver}, // NULL if no function used // Feed Tx back to RX {enableHartLoopBack,disableHartLoopBack,isEnabledHartLoopBack}, // NULL if no function used // Writes to TXBUF and clears TXIF hartTxChar, }; /*! * hsbUart is the Uart instance for High Speed Bus communication */ stUart hsbUart = { hsbRxFifoLen, //!< Rx Buffer lengths (defines) hsbTxFifoLen, //!< Tx Buffer lengths (defines) initHsbUart, //!< points to msp430 init hsbRxfifoBuffer, //!< static allocation for the Rx Fifo hsbTxfifoBuffer, //!< static allocation for the Tx Fifo FALSE, // bRtsControl = FALSE, we don't have a TxDriver // Rx Interrupt Handlers {enableHsbRxIntr,disableHsbRxIntr,isHsbRxIntrEnabled}, // Tx Interrupt Handlers {enableHsbTxIntr,disableHsbTxIntr,isHsbTxIntrEnabled}, // Tx Driver {NULL, NULL, NULL}, // Hsb has no RTS or TX Driver // Feed Tx back to RX {enableHsbLoopBack,disableHsbLoopBack,isEnabledHsbLoopBack}, // NULL if no function used // Writes to TXBUF and clears TXIF hsbTxChar }; volatile BOOLEAN hsbActivitySlot = TRUE; //!< Indicates HSB active or preparing to RX frame, No low power while this is TRUE volatile BOOLEAN flashWriteEnable = FALSE; //!< Indicates to the main loop that it is the best time to write to Flash //============================================================================== // LOCAL DATA //============================================================================== BYTE hartRxfifoBuffer[hartRxFifoLen*2]; //!< Allocates static memory for Hart Receiver Buffer (data, status) BYTE hartTxfifoBuffer[hartTxFifoLen]; //!< Allocates static memory for Hart Transmit Buffer BYTE hsbRxfifoBuffer[hsbRxFifoLen]; //!< Allocates static memory for High Speed Serial Bus receiver buffer BYTE hsbTxfifoBuffer[hsbTxFifoLen]; //!< Allocates static memory for High Speed Serial transmit Buffer //============================================================================== // FUNCTIONS //============================================================================== /*! * \fn BOOLEAN initUart(stUart *pUart) * \brief Initialize the indicated Uart * * Init members: fifos pointers and set buffer size, call the Ucsi initilization to set baud rate, parity, clk source * If the uart requires RTS control, the disable() function is called (constructor) * \param pUart points to the uart structure * * Date Created: Sep 20,2012 * Author: MH * */ BOOLEAN initUart(stUart *pUart) { // Set Fifos max length pUart->rxFifo.maxLength = pUart->nRxBufSize; pUart->txFifo.maxLength = pUart->nTxBufSize; // // Init internal pointers resetFifo(&pUart->rxFifo, pUart->fifoRxAlloc); resetFifo(&pUart->txFifo, pUart->fifoTxAlloc); // pUart->bRxError = FALSE; pUart->bNewRxChar = FALSE; pUart->bUsciTxBufEmpty = TRUE; pUart->bTxMode = FALSE; pUart->bRxFifoOverrun = FALSE; pUart->bTxDriveEnable = FALSE; // If Uart requires RTS control provide it here if( pUart->bRtsControl && pUart->hTxDriver.disable != NULL) pUart->hTxDriver.disable(); pUart->initUcsi(); // Configure the msp ucsi for odd parity 1200 bps return TRUE; } /*! * \fn initHartUart() * \brief Initializes the Hart Uart to 1200, 8,o,1 using * - SMCLK @1.048576 MHz (if HART_UART_USES_SMCLK defined) * - ACLK @32.768KHz (if defined HART_UART_USES_ACLK == Product will use this option) * */ static void initHartUart(void) { UCA1CTL1 = UCSWRST; // Reset internal SM #ifdef HART_UART_USES_SMCLK #ifdef HART_UART_USES_ACLK #error Define only one clk source #endif UCA1CTL1 |= UCSSEL_2; // SMCLK as source UCA1BR0 = 0x6A; // BR= 1048576/1200 = 873.8133 ~ 874 UCA1BR1 = 0x03; UCA1MCTL =0; // No modulation #else #ifdef HART_UART_USES_ACLK UCA1CTL1 |= UCSSEL_1; // ACLK as source ==> This will be the preferred if LPM3 UCA1BR0 = 0x1B; // BR= 32768/1200 = 27.306 = 0x1B + 2/8 UCA1BR1 = 0x00; UCA1MCTL = UCBRS_2; // Second modulation stage = 2 (.306 * 8 ~aprox 2) #else #error Define either HART_UART_USES_ACLK or HART_UART_USES_SMCLK for Hart UART #endif #endif // case PARITY_ODD: UCA1CTL0 |= UCPEN; // set parity UCA1CTL0 &= ~UCPAR; // Odd // Generate an Rx Interrupt when chars have errors UCA1CTL1|= UCRXEIE; // /////////////// UCA1CTL1 &= ~UCSWRST; // Initialize USCI state machine } /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: initHsbUart() // // Description: // // Sets up the A0 UART for 19,200 baud // // Parameters: int - initial parity setting // // Return Type: void. // // Implementation notes: // // Assumes SMCLK at 1 Mhz // /////////////////////////////////////////////////////////////////////////////////////////// static void initHsbUart(void) { P3SEL = BIT4 | BIT3; // P3.4,3 = USCI_A0 TXD/RXD UCA0CTL1 = UCSWRST; // reset the UART UCA0CTL1 |= UCSSEL_2; // SMCLK source UCA0BR0 = 3; // 1.048 MHz 19,200 UCA0BR1 = 0; // 1.048 MHz 19,200 UCA0MCTL = UCBRF_6 | UCBRS0 | UCOS16; // Modln UCBRS =1, UCBRF =6, over sampling // Set for 7-bit data UCA0CTL0 |= UC7BIT; // Odd is default for HART // case PARITY_ODD: UCA0CTL0 |= UCPEN; // setMainOddParity(); UCA0CTL0 &= ~UCPAR; UCA0CTL1 &= ~UCSWRST; // **Initialize USCI state machine** } /*! * \fn hartSerialIsr() * \brief Handles the Rx/Tx interrupts for Hart * * This is the Rx/Tx interrupt for the Hart at USCI_A1_VECTOR (46) * */ #pragma vector=USCI_A1_VECTOR __interrupt void hartSerialIsr(void) { _no_operation(); // recommended by TI errata -VJ (I just left Here MH) static volatile WORD rxword; static volatile WORD u ; static BYTE status; // see recycle #2 u =UCA1IV; // Get the Interrupt source switch(u) { case 0: // Vector 0 - no interrupt default: // or spurious break; case 2: // Vector 2 - RXIFG rxword = (status = UCA1STAT) << 8 | UCA1RXBUF; // read & clears the RX interrupt flag and UCRXERR status flag if( hartUart.bTxMode ) // Loopback interrupt { if( hartUart.bUsciTxBufEmpty) // Ignore everything but last char { hartUart.hLoopBack.disable(); // Disable loop back hartUart.hTxDriver.disable(); // Disable the Tx Driver hartUart.bTxMode = FALSE; // Tx is done SET_SYSTEM_EVENT(evHartTransactionDone); // Signal the end of command-reply transaction // see recycle #3 ///////////////////////////////////////////////////////////////////////////////////////////////////////////// // // 12/27/12 - Releasing the RTS line makes RX lines goes from low to hi after some time (4mS observed) // ON-A519 Modem says 4 consecutive carrier clock cycles - 1.8 to 3.3mS (depending on 1200 or 2200Hz) // This RX transition is detected as a bad reception or good one, depending on the transition time of RX. // After TX is done, we need to clean the RX to avoid receiving the extra char, easiest way is to use // the UCSWRST software reset bit to init uart internal state machine. This affects also the TX, but it // safe. The RX being low is not detected, as msp430 will looks for edges to establish a start bit. UCA1CTL1 |= UCSWRST; // Reset internal SM _no_operation(); UCA1CTL1 &= ~UCSWRST; // Initialize USCI state machine // Need to manually enable interrupts again hartUart.hRxInter.enable(); hartUart.hTxInter.enable(); // ///////////////////////////////////////////////////////////////////////////////////////////////////////////// CLEARB(TP_PORTOUT, TP1_MASK); // Indicate Hart ends (move bellow to test the Uart reset) // Flash Write sync flashWriteEnable = hsbActivitySlot ? FALSE : TRUE; // The combination of HSB and Hart conditions to write to Flash } } else { // Uart is in Recvd Mode kickHartGapTimer(); // kick the Gap timer as soon as received the 11th bit // 1/15/2013 We read everything (error included) and take decisions at later on as response depends on error location if(!isRxFull(&hartUart)) // put data in input stream if no errors { if(status & UCRXERR || status & UCBRK) // Any (FE PE OE) error? or ==== NO BREAK detected==== 12/26/12 { hartUart.bRxError = TRUE; // ==> power save ==> discard current frame //TOGGLEB(TP_PORTOUT, TP3_MASK); // catch errors: errors observed when shorting/disconnecting Hart, no errors on protocol } hartUart.bNewRxChar = putwFifo(&hartUart.rxFifo, rxword); // Signal an Event to main loop SET_SYSTEM_EVENT(evHartRxChar); // see recycle #1 } else hartUart.bRxFifoOverrun = TRUE; // Receiver Fifo overrun!! } break; case 4: // Vector 4 - TXIFG if(!isEmpty(&hartUart.txFifo)) { hartUart.txChar(getFifo(&hartUart.txFifo)); hartUart.bUsciTxBufEmpty = FALSE; // enable "chain" isrs } else { // in Half DUplex we reach this point (look oscope carefully) while moving last char //volatile BYTE i; for(i=0; i < 100; ++i) __no_operation(); hartUart.bUsciTxBufEmpty = TRUE; // Prepare to disable RTS line after Rx complete in next RX isr -> //Wrong hartUart.hLoopBack.enable(); // Enabling loopback here is 960 after the start-bit } break; } #ifdef LOW_POWERMODE_ENABLED _bic_SR_register_on_exit(LPM_BITS); _no_operation(); // _no_operation(); _no_operation(); #endif } /*! * \fn hsbSerialIsr() USCI_A0_VECTOR (56) * Handles the Rx/Tx interrupts for High Speed Bus * */ #pragma vector=USCI_A0_VECTOR __interrupt void hsbSerialIsr(void) { _no_operation(); // recommended by TI errata -VJ (I just left Here MH) // volatile BYTE rxbyte; volatile BYTE status; static volatile BOOLEAN hsbMsgInProgress = FALSE; static volatile BYTE bLastRxChar; static volatile WORD i9900CmdBuf; // This is the local Index BOOLEAN volatile rxError = FALSE; // Take same action for Rx error at the end volatile WORD u =UCA0IV; // Get the Interrupt source switch(u) { case 0: // Vector 0 - no interrupt default: // or spurious break; case 2: // Vector 2 - RXIFG status = UCA0STAT; rxbyte = UCA0RXBUF; // read & clears the RX interrupt flag and UCRXERR status flag // if( hsbUart.bTxMode ) // Loopback interrupt { if( hsbUart.bUsciTxBufEmpty) // Ignore everything but last char { hsbUart.hLoopBack.disable(); // Disable loop back hsbUart.bTxMode = FALSE; // Tx is done hsbUart.hRxInter.disable(); // ===== THIS comes from TX ==== // HSB has finished here hsbActivitySlot = FALSE; // HSB for Hart has ended, allow to sleep and ignore any traffic until wake-up hsbMsgInProgress = FALSE; // Everything has been shifted out CLEARB(TP_PORTOUT,TP2_MASK); // HSB message 4) End of HSB message } } else if(status & UCRXERR || status & UCBRK ) // Any (FE PE OE) error or BREAK error ? rxError = TRUE; else { // Code for reception of a character UART-error free: if(hsbMsgInProgress) { // Bare bone reception is done here if(rxbyte == HART_MSG_END) { SET_SYSTEM_EVENT(evHsbRecComplete); CLEARB(TP_PORTOUT, TP2_MASK); // HSB message 2) All characters in buffer hsbMsgInProgress = FALSE; // hsbUart.hRxInter.disable(); // We can't do this here - need to disable at TX shift out } else // Keep storing rx chars if(i9900CmdBuf < MAX_9900_CMD_SIZE) sz9900CmdBuffer[i9900CmdBuf++] = rxbyte; else rxError = TRUE; // command buffer overrun } else if( bLastRxChar == ATTENTION && rxbyte == HART_ADDRESS ) // We get the start of a $H { startHsbAttentionTimer(); // This will Enable RXIE again before Attention arrives SETB(TP_PORTOUT, TP2_MASK); // HSB message 1) Start detected $H hsbMsgInProgress = TRUE; // To be compatible with what Process9900Command() requires first two be '$','H' sz9900CmdBuffer[0] = ATTENTION; i9900CmdBuf=1; sz9900CmdBuffer[i9900CmdBuf++] = HART_ADDRESS; } bLastRxChar = rxbyte; // The sequence of last two chars is the signature } break; case 4: // Vector 4 - TXIFG if(!isEmpty(&hsbUart.txFifo)) { hsbUart.txChar(getFifo(&hsbUart.txFifo)); hsbUart.bUsciTxBufEmpty = FALSE; // enable "chain" isrs } else { // in Half DUplex we reach this point (look oscope carefully) while moving last char //volatile BYTE i; for(i=0; i < 100; ++i) __no_operation(); hsbUart.bUsciTxBufEmpty = TRUE; // Prepare to disable RTS line after Rx complete in next RX isr -> //Wrong hsbUart.hLoopBack.enable(); // Enabling loopback here is 960 after the start-bit } break; } // end switch // // All Hsb UART error actions are taken here - We allow TX to send its previous (Abort not implemented) // -- 12/28/12 Added a Flag to skip the RXBUF wrong data after sleeping if(rxError && !hsbUart.bTxMode) { // TOGGLEB(TP_PORTOUT, TP3_MASK); // catch errors: Errors are detected when shorting HSB bus, no errors due protocol handling hsbUart.bRxError = TRUE; // signal the error bLastRxChar =0; // Reset start sequence hsbActivitySlot = TRUE; // HSB do not sleep, listen everything // In error condition This is my basic Failure State Recover // 1) UART should be listening but buffers set to init conditions i9900CmdBuf =0; // Loog for the $H again hsbMsgInProgress = FALSE; // Reset the simple two-state machine } #ifdef LOW_POWERMODE_ENABLED _bic_SR_register_on_exit(LPM_BITS); _no_operation(); // _no_operation(); _no_operation(); #endif } /*! * \fn putcUart(BYTE ch, stUart *pUart) * Put a character into the output stream * * If the output stream is full, the routine waits for an empty position. If the ostream * and Transmit register are empty, routine writes direct to transmit register. * * * \param ch is the byte to be sent to the output stream * \param *pUart is the Uart's fifo * * \return TRUE if character goes into the output stream or direct to txbuf */ BOOLEAN putcUart(BYTE ch, stUart *pUart) { BOOLEAN sent = FALSE; // Disable TxInterrupt only when no chars in TxFifo while (isFull(&pUart->txFifo)); // (38mS?) wait until there is room in the fifo TODO: worth turn OFF power?, TXIE always ON #if 0 // We are always having TXIE = TRUE if(!pUart->hTxInter.isEnabled()) // If TxIntr not enabled, enable it as we don't want infinite loop { __disable_interrupt(); pUart->hTxInter.enable(); __enable_interrupt(); // Start the Tx or continue with the previous } #endif // Lock the TxFifo __disable_interrupt(); // Handle the TxDriver if Hardware Flow-Control if(pUart->bRtsControl) pUart->hTxDriver.enable(); // enable it now if(pUart->bUsciTxBufEmpty && isTxEmpty(pUart)) // Ask if we write direct to SBUF { pUart->hLoopBack.enable(); // Enable loop back TODO: be sure Rx line is not floating, add pull up in initHardware --Remove a BUG pUart->txChar(ch); // this clears TXIF pUart->bUsciTxBufEmpty = FALSE; } else sent = putFifo(&pUart->txFifo, ch); // Write using buffer pUart->bTxMode = TRUE; // signal the Rx/Tx isr we are in TxMode __enable_interrupt(); // Start the Tx or continue with the previous // A TX ISR will be generated here return sent; } /*! * \fn BYTE getcUart(stUart *pUart) * \brief Gets a byte from the indicated input stream. * * Gets a byte from the indicated input stream. If the Rx fifo is empty, it waits here for data (TBD sleep mode??)\n * Interrupts are disabled to lock the RxFifo (assumes interrupts are always enabled) * * \param pUart pointer to the uart * \retval Oldest BYTE from the RxFifo * */ BYTE getcUart(stUart *pUart) { while(isEmpty(&pUart->rxFifo)); // (38mS?) Just wait here until a character arrives // Critical Zone _disable_interrupt(); BYTE ch = getFifo(&pUart->rxFifo); _enable_interrupt(); return ch; } /*! * \fn WORD getwUart(stUart *pUart) * \brief Gets a WORD from the indicated input stream. * * Gets a word from the indicated input stream. If the Rx fifo is empty, it waits here for data (TBD sleep mode??)\n * Interrupts are disabled to lock the RxFifo (assumes interrupts are always enabled) * * \param pUart pointer to the uart * \retval Oldest WORD from the RxFifo * \sa putwUart() * */ WORD getwUart(stUart *pUart) { while(isEmpty(&pUart->rxFifo)); // (38mS?) Just wait here until a character arrives // Critical Zone _disable_interrupt(); WORD u = getwFifo(&pUart->rxFifo); _enable_interrupt(); return u; } // Remove inlines <file_sep>/*! * \file protocols.c * \brief Hart Receiver state machine and all auxiliary functions to handle * message reception has been grouped in this file * * * Created on: Sep 19, 2012 * \author: MH */ //============================================================================== // INCLUDES //============================================================================== #include <msp430f5528.h> #include <string.h> #include "define.h" #include "msp_port.h" #include "protocols.h" #include "driverUart.h" #include "hart_r3.h" #include "main9900_r3.h" #include "hardware.h" #include "utilities_r3.h" //============================================================================== // LOCAL DEFINES //============================================================================== // Other size definitions #define MAX_HART_XMIT_BUF_SIZE 267 #define MAX_RCV_BYTE_COUNT 267 #define MAX_HART_DATA_SIZE 255 // Defines #define MIN_PREAMBLE_BYTES 2 #define MAX_PREAMBLE_BYTES 30 // SOM delimiter defines #define BACK 0x01 #define STX 0x02 #define ACK 0x06 #define LONG_ADDR_MASK 0x80 #define FRAME_MASK 0x07 #define EXP_FRAME_MASK 0x60 #define LONG_ADDR_SIZE 5 #define SHORT_ADDR_SIZE 1 #define LONG_COUNT_OFFSET 7 #define SHORT_COUNT_OFFSET 3 //============================================================================== // LOCAL PROTOTYPES. //============================================================================== static int isAddressValid(void); //============================================================================== // GLOBAL DATA //============================================================================== /// /// command information /// unsigned char hartCommand = 0xff; unsigned char addressValid = FALSE; unsigned char hartFrameRcvd; //!< Flag is set after a successfully Lrc and address is for us WORD hartDataCount; //!< The number of data field bytes BYTE expectedByteCnt; //!< The received byte count, to know when we're done int longAddressFlag = FALSE; //!< long address flag unsigned char addressStartIdx = 0; //!< address byte index int commandReadyToProcess = FALSE; //!< Is the command ready to process? unsigned long errMsgCounter = 0; //!< Message Counters unsigned long numMsgProcessed = 0; unsigned long numMsgReadyToProcess = 0; unsigned long numMsgUnableToProcess = 0; // Parity & overrun error flags int parityErr; int overrunErr; int rcvLrcError; //!< Did the LRC compute OK unsigned int respBufferSize; //!< size of the response buffer unsigned int HartErrRegister = NO_HART_ERRORS; //!< The HART error register unsigned int respXmitIndex = 0; //!< The index of the next response byte to transmit float lastRequestedCurrentValue = 0.0; //!< The last commanded current value from command 40 is here int checkCarrierDetect (void); //!< other system prototypes unsigned long xmtMsgCounter = 0; //!< MH: counts Hart messages at some point in SM unsigned char szHartResp [MAX_HART_XMIT_BUF_SIZE]; //!< start w/preambles unsigned char szHartCmd [MAX_RCV_BYTE_COUNT]; //!< Rcvd message buffer (start w/addr byte) //============================================================================== // LOCAL DATA //============================================================================== // detect compile error static unsigned char * pRespBuffer = NULL; //!< Pointer to the response buffer /*! * Flag to indicate that Hart receiver state machine should be initiated * * This flag is set to reset the Hart Receiver State Machine to init state. Initialization * happens at next state call. * */ static BOOLEAN bInitHartSm = FALSE; //============================================================================== // FUNCTIONS //============================================================================== /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: hartReceiverSm() // // Description: // // The actual work done in the receive ISR. Checks errors, puts the received character // into the RX queue // // Parameters: void // // Return Type: void. // // Implementation notes: // // Checks the receive error flags, as well as checks to make sure the character // got written to the RX queue successfully // /////////////////////////////////////////////////////////////////////////////////////////// // Diagnostic RX error count array unsigned int ErrReport[15] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; // Index 0 = the number of times the rcv funct is called // Index 1 = the number of BREAK characters processed // Index 2 = the number of FRAMING errors // Index 3 = the number of OVERFLOW errors // Index 4 = the number of PARITY errors // Index 5 = the number of excess preambles // Index 6 = the number of insufficient preambles // Index 7 = the number of STX errors // Index 8 = the number of bad byte errors // Index 9 = the number of bad LRC // Index 10 = the number of default/idle cases // Index 11 = the number of stored characters // Index 12 = the number of characters used to calculate LRC // Index 13 = the number of times the address wasn't valid // Index 14 = SPARE /*! * \fn initHartRxSm() * * This function perform the global init of Hart Receiver state machine. Ideally this * functionshould be implemented inside the state function, but the spread of globals * makes this very hard * * Implementation notes: * Here the global variables that were used by previous state machine are reset. * Other variables are initalized internally in the internal init state. * The signal bInitHartSm is set to perform the remainder initialization inside * the function, which is performed when the new character event is captured at main loop * * This function partially replaces prepareToRxFrame(), rest is done at its context */ void initHartRxSm(void) { // Hart Reception Results - Start reply hartFrameRcvd = FALSE; commandReadyToProcess = FALSE; // Status Report // hostActive = FALSE; //MH logic moved to main loop with a timeout 1/24/12 // Used in processHartCommand(), executeCommand() hartCommand = 0xfe; // Make the command invalid // Hart Error or Status Register HartErrRegister = RCV_BAD_LRC; // Clear the HART error register, except for the assumed LRC error // Used to calculate the Address in Hart Command message - addressStartIdx = 0; // hart.c::isAddressValid() longAddressFlag = FALSE; addressValid = FALSE; // hartCommand.c::processHartCommand () // Data section of command message. First member is used everywhere hartDataCount = 0; //!< The number of data field bytes expectedByteCnt = 0; //!< The received byte count, to know when we're done // Sttus of current Cmd Message - used on processHartCommand() rcvLrcError = TRUE; // Assume an error until the LRC is OK overrunErr = FALSE; parityErr = FALSE; // Signal the Hart Receiver State MAchine to do the rest bInitHartSm = TRUE; } /*! * hartReceiver() * Implement the Hart Receiver state machine * \param data Receiver character (lo byte) and its status (Hi byte) * * \returns the result of the hart building * - hrsIdle the internal SM is waiting for preamble * - hrsValidFrame Valid frame with the address of this module has been received * - hrsDone a valid frame and at least one extra byte has been received (current idl * - hrsErrorDump an internal error has been detected - rest of message dumped * - hrsErrorReport message wt this point contain errors, mus reply with a status * - hrsBusy * * Implementation notes: * The routine is called everytime a new char has arrived at Hart receiver. * The message is built through several internal states. At power Up (or on request) the state is eRccPrepareToRx, when * called it will set all pointers and data to prepare a new reception. * * ValidFrame will transition to * Done and Error will end */ void hartReceiver(WORD data) //===> BOOLEAN HartReceiverSm() Called every time a HartRxChar event is detected { /// HART receive state machine typedef enum { eRcvInit, //!< Set the initial counters and pointer in position // Follwoing states are the same as described in Documentation eRcvSom, //!< Start of Message - Idle waiting for Start Delimiter eRcvAddr, //!< eRcvCmd, eRcvByteCount, eRcvData, eRcvLrc, eRcvXtra } eRcvState; unsigned char nextByte; unsigned char statusReg; // Here come the list of Statics static BYTE expectedAddrByteCnt; //!< the number of address bytes expected static eRcvState ePresentRcvState = eRcvSom; static BYTE calcLrc; static unsigned char rcvAddrCount; //!< The number of address bytes received static unsigned char rcvByteCount; //!< The total number of received bytes, starting with the SOM static WORD preambleByteCount; //!< the number of preamble bytes received static unsigned char totalRcvByteCount; // Hart Receiver State Machine Initialization - perform before increment error counters if(bInitHartSm ) // Init is a pseudo state -> eRcvSom { bInitHartSm = FALSE; // Initialization done // locals expectedByteCnt = calcLrc = rcvByteCount = rcvAddrCount = totalRcvByteCount = 0; preambleByteCount = 0; //pRespBuffer = szHartResp; // Set the transmit pointer back to the beginning of the buffer // stop (if running) the Reply timer (made one shot on 12/26/12 ) ePresentRcvState = eRcvSom; // Set the state machine to look for the start of message } // Process Received Character nextByte = data; // !MH:--> HART_RXBUF; statusReg = data >>8; // debugging HART_STAT; /*! * If we are in sleep mode, kicking timers here may be late and a Gap timer may time-out * Move this to ISR - RX */ //kickHartRecTimers(); // kick the Gap and Response timers, they will generate wake-up events to main loop // ++ErrReport[0]; // hostActive = TRUE; // If we are receiving characters, the host is active ==MH 1/24/13 Logic moved to Mainloop in a complete message // // Check for errors before calling the state machine, since any comm error resets the state machine // // BRK: Break Detected (all data, parity and stop bits are low) if (statusReg & UCBRK) // ++ErrReport[1]; // Status was cleared when happened, just report here // FE: Frame error (low stop bit) if (statusReg & UCFE) { HartErrRegister |= RCV_FRAMING_ERROR; ++ErrReport[2]; ++startUpDataLocalV.errorCounter[0]; } // OE: Buffer overrun (previous rx overwritten) if (statusReg & UCOE) { // if we're still receiving preamble bytes, just clear the OE flag otherwise, bail on the reception if (eRcvSom != ePresentRcvState) { overrunErr = TRUE; HartErrRegister |= BUFFER_OVERFLOW; ++ErrReport[3]; ++startUpDataLocalV.errorCounter[2]; } else ++startUpDataLocalV.errorCounter[14]; } // PE: Parity Error if (statusReg & UCPE) { // if the parity error occurs after the command byte, we will respond with a tx error message. // Otherwise, just ignore the message parityErr = TRUE; HartErrRegister |= RCV_PARITY_ERROR; ++ErrReport[4]; ++startUpDataLocalV.errorCounter[1]; } // increment the total byte count totalRcvByteCount++; // The receive state machine: What we do depends on the current state switch (ePresentRcvState) { case eRcvSom: // A parity or framing error here is fatal, so check if ((statusReg & UCPE) || (statusReg & UCFE)) { ++startUpDataLocalV.errorCounter[10]; // We are not going to respond, so we will wait until the next message starts // 1) prepareToRxFrame(); initHartRxSm(); return; } // is it a preamble character? if (HART_PREAMBLE == nextByte) { //intrDcd = TRUE; // increment the preamble byte count ++preambleByteCount; // Check for too many preamble characters if (MAX_PREAMBLE_BYTES < preambleByteCount) { // Set the HART error register HartErrRegister |= EXCESS_PREAMBLE; // Set the state machine to Idle, because we're not processing any more bytes on this frame - TO BE VERIFIED // 2) prepareToRxFrame(); initHartRxSm(); ++ErrReport[5]; ++startUpDataLocalV.errorCounter[4]; } // Do not store the character return; } else if (STX == (nextByte & (FRAME_MASK | EXP_FRAME_MASK))) { if (MIN_PREAMBLE_BYTES > preambleByteCount) { // Set the HART error register HartErrRegister |= INSUFFICIENT_PREAMBLE; // If we haven't seen enough preamble bytes, we are not going to respond at all, so set the state machine to idle // 3)prepareToRxFrame(); initHartRxSm(); errMsgCounter++; ++ErrReport[6]; ++startUpDataLocalV.errorCounter[3]; return; // If < 2 preambles, do nothing & return } // How many address bytes to expect? expectedAddrByteCnt = (nextByte & LONG_ADDR_MASK) ? LONG_ADDR_SIZE : SHORT_ADDR_SIZE; addressStartIdx = rcvByteCount+1; // the first address byte is the next character // is this a long address? longAddressFlag = (nextByte & LONG_ADDR_MASK) ? TRUE : FALSE; // change the state ePresentRcvState = eRcvAddr; // Start Checking time between chars as a valid frame has started bHartRecvFrameCompleted= FALSE; // Clear the event blocking startGapTimerEvent(); SETB(TP_PORTOUT, TP1_MASK); // Mark the init of HART frame as seen by module } else { // Set the HART error register HartErrRegister |= STX_ERROR; // Increment the error counters ++ErrReport[7]; errMsgCounter++; ++startUpDataLocalV.errorCounter[5]; // Something's wrong. Just set the preamble count back to zero and start over after recording the error diagnostics // 4) prepareToRxFrame(); initHartRxSm(); return; } break; case eRcvAddr: // A parity, overrun or framing error here is fatal, so check if ((statusReg & UCPE) || (statusReg & UCFE) || (statusReg & UCOE)) { // We are not going to respond, so we will wait until the next message starts // 5) prepareToRxFrame(); initHartRxSm(); ++startUpDataLocalV.errorCounter[11]; return; } // increment the count of the address bytes rcvd ++rcvAddrCount; if (rcvAddrCount == expectedAddrByteCnt) { // Store the last byte of the address here to // make sure that isAddressValid() will work correctly. Do NOT // increment rcvByteCount!! szHartCmd[rcvByteCount] = nextByte; // Check to see if the address is for us. If not, start // looking for the beginning of the next message addressValid = isAddressValid(); if (!addressValid) { ++ErrReport[13]; ++startUpDataLocalV.errorCounter[15]; // x) prepareToRxFrame(); - BMD removed. Do not start to look for a new frame until the current one is completely done // MH: Agree with BMD return; } // we're done with address, move to command ePresentRcvState = eRcvCmd; } break; case eRcvCmd: // ready to receive byte count ePresentRcvState = eRcvByteCount; // signal that the command byte has been received, and we have to process the command commandReadyToProcess = TRUE; numMsgReadyToProcess++; // Now that we have to respond, set the error register. We'll clear it later if all is OK HartErrRegister |= RCV_BAD_LRC; break; case eRcvByteCount: // A parity, overrun or framing error here is fatal, so check if ((statusReg & UCPE) || (statusReg & UCFE) || (statusReg & UCOE)) { ++startUpDataLocalV.errorCounter[12]; // We are not going to respond, so we will wait until the next message starts // 6) prepareToRxFrame(); initHartRxSm(); return; } expectedByteCnt = nextByte; if (expectedByteCnt > MAX_HART_DATA_SIZE) //MH This never happens, as left value is byte and right is 255 { HartErrRegister |= RCV_BAD_BYTE_COUNT; // 7) prepareToRxFrame(); initHartRxSm(); ++ErrReport[8]; errMsgCounter++; ++startUpDataLocalV.errorCounter[7]; } else if (0 == expectedByteCnt) ePresentRcvState = eRcvLrc; else { hartDataCount = 0; ePresentRcvState = eRcvData; } break; case eRcvData: ++hartDataCount; // Are we done? if (hartDataCount == expectedByteCnt) ePresentRcvState = eRcvLrc; break; case eRcvLrc: bHartRecvFrameCompleted = TRUE; // ACK - Gap timer must be ignored // 12/26/12 We couldn't move the start of Reply timer in ISR, we keep it Here, reply will have some latency startReplyTimerEvent(); if (calcLrc == nextByte) { HartErrRegister &= ~RCV_BAD_LRC; // Clear the bad CRC error rcvLrcError = FALSE; // process the command } else { rcvLrcError = TRUE; HartErrRegister |= RCV_BAD_LRC; ++ErrReport[9]; ++startUpDataLocalV.errorCounter[6]; } // If the address is for us, pick up extra characters // If the message isn't for us, start looking for a new message asap if (addressValid) { hartFrameRcvd = TRUE; ePresentRcvState = eRcvXtra; } else // 8) prepareToRxFrame(); initHartRxSm(); break; case eRcvXtra: //==TOGGLEB(TP_PORTOUT, TP2_MASK); // Provisional see the xtra chars in scope HartErrRegister |= EXTRA_CHAR_RCVD; //#ifdef STORE_EXTRA_CHARS if (FALSE == checkCarrierDetect()) HartErrRegister |= EXTRA_CHAR_RCVD; break; //#else#endif default: ++ErrReport[10]; // 9) prepareToRxFrame(); // Get ready for the next message initHartRxSm(); return; // Do not store the character } // Here we build the Hart Command Buffer & calc LRC - Not idle, or msg cancelled if (MAX_RCV_BYTE_COUNT > rcvByteCount) // Make sure we don't overrun the buffer { ++ErrReport[11]; szHartCmd[rcvByteCount] = nextByte; ++rcvByteCount; } calcLrc ^= nextByte; // calculateLrc(nextByte); ++ErrReport[12]; } /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: checkCarrierDetect() // // Description: // // Checks the state of the CD pin. Return TRUE if the carrier is detected, FALSE otherwise // // Parameters: void // // Return Type: int // // Implementation notes: // // // /////////////////////////////////////////////////////////////////////////////////////////// int checkCarrierDetect (void) { int rtnVal; // read port 1 int port1value; port1value = P1IN; // mask the value of the port rtnVal = (port1value & BIT2) ? TRUE : FALSE; return rtnVal; } /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: isAddressValid() // // Description: // // Verify that the address is either a broadcast address or is an exact match // to the poll address in the database. Returns TRUE if either conditions // met, FALSE otherwise // // Parameters: // unsigned char * pCommand: pointer to the HART command to check the address of. // // Return Type: unsigned int. // // Implementation notes: // // // /////////////////////////////////////////////////////////////////////////////////////////// // HART 7 compliant static int isAddressValid(void) { union { unsigned int i; unsigned char b[2]; } myDevId; int index; // Mask the Primary bit out of the poll address unsigned char pollAddress = szHartCmd[addressStartIdx] & ~(PRIMARY_MASTER | BURST_MODE_BIT); // Now capture if it is from the primary or secondary master startUpDataLocalV.fromPrimary = (szHartCmd[addressStartIdx] & PRIMARY_MASTER) ? TRUE : FALSE; int isValid = FALSE; // Set the broadcast flag to FALSE rcvBroadcastAddr = FALSE; // Remove the Burst mode bit szHartCmd[addressStartIdx] &= ~BURST_MODE_BIT; if (longAddressFlag) { // We only need to compare to the lower 14 bits myDevId.i = startUpDataLocalV.expandedDevType & EXT_DEV_TYPE_ADDR_MASK; // Now XOR out the recieved address for each myDevId.b[1] ^= szHartCmd[addressStartIdx] & POLL_ADDR_MASK; myDevId.b[0] ^= szHartCmd[addressStartIdx+1]; // If the ID is 0, check for a unique address if (!myDevId.i) { // Now compare the last 3 bytes of address if (!(memcmp(&szHartCmd[addressStartIdx+2], &startUpDataLocalNv.DeviceID, 3))) { isValid = TRUE; } } // If the address is not a unique address for me, // look for the broadcast address if (!isValid) { // Check to see if it is a broadcast. We have to check the first byte // separately, since it may have the primary master bit set. // Mask out the primary master bit of the first byte if (0 != (szHartCmd[addressStartIdx] & ~PRIMARY_MASTER)) { return isValid; } // Now check the following 4 bytes for (index = 1; index < LONG_ADDR_SIZE; ++index) { // the rest of the bytes are 0 if this is a broadcast address if(0 != szHartCmd[addressStartIdx+index]) { return isValid; } } rcvBroadcastAddr = TRUE; isValid = TRUE; } } else // short Polling address for Cmd0? { if (startUpDataLocalNv.PollingAddress == pollAddress) { isValid = TRUE; } } return isValid; } /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: initRespBuffer() // // Description: // // Set up the initial response buffer // // Parameters: void // // Return Type: void. // // Implementation notes: // In addition to setting up the beginning of the response buffer, this function also // captures some information used in later procesing // /////////////////////////////////////////////////////////////////////////////////////////// void initRespBuffer(void) { int i, addrSize; // Delimiter - Mask out expansion bytes & physical layer type bits szHartResp[0] = ACK | (szHartCmd[0] & (STX | LONG_ADDR_MASK)); // Copy Address field addrSize = (szHartCmd[0] & LONG_ADDR_MASK) ? LONG_ADDR_SIZE : SHORT_ADDR_SIZE; for (i = 1; i <= addrSize; ++i) { szHartResp[i] = szHartCmd[i]; } // Now remove the burst mode bit szHartResp[1] &= ~BURST_MODE_BIT; // Command byte hartCommand = szHartResp[i] = szHartCmd[i]; // set frame offset for building the command to the next position respBufferSize = i + 1; } #if 0 /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: rtsRcv() // // Description: // // Set the RTS line high (receive mode) // // Parameters: void // // Return Type: void. // // Implementation notes: // // // /////////////////////////////////////////////////////////////////////////////////////////// /* inline */ void rtsRcv(void) { P4OUT |= BIT0; } #endif /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: sendHartFrame() // // Description: // // Starts the transmit of the completed response // // Parameters: void // // Return Type: Number of bytes sent to output stream // // Implementation notes: // pRespBuffer // // /////////////////////////////////////////////////////////////////////////////////////////// WORD sendHartFrame (void) { WORD i; volatile BYTE calcLrc =0; _no_operation(); // debug point // Send preambles for(i=0; i < XMIT_PREAMBLE_BYTES; ++i) putcUart(HART_PREAMBLE, &hartUart);// write the character to Hart outstream // Send the response buffer WORD nTotal = (szHartResp[0] & LONG_ADDR_MASK) ? \ (szHartResp[LONG_COUNT_OFFSET] + LONG_COUNT_OFFSET) : \ (szHartResp[SHORT_COUNT_OFFSET] + SHORT_COUNT_OFFSET); for(i=0; i<= nTotal; ++i) // nTotal+1 iterations because need to include nData byte itself { calcLrc ^= szHartResp[i]; // Calculate the LRC putcUart(szHartResp[i], &hartUart); // Transmit the character } // Send calculated Lrc putcUart(calcLrc, &hartUart); // count the transmitted message xmtMsgCounter++; // Clear the appropriate cold start bit if (startUpDataLocalV.fromPrimary) clrPrimaryStatusBits(FD_STATUS_COLD_START); else clrSecondaryStatusBits(FD_STATUS_COLD_START); // 12/6/12 No commands to RESET Hart module are supported #if 0 // If cmdReset is set and we are here, we should not respond again until we emerge from the reset, // so set the do not respondflag if (TRUE == cmdReset) doNotRespond = TRUE; #endif // Get ready for next frame // 10) prepareToRxFrame(); initHartRxSm(); return nTotal +2 + XMIT_PREAMBLE_BYTES; // Frame total size = Frame + 1 + LRC + Preambles } <file_sep>/////////////////////////////////////////////////////////////////////////////////////////// // Copyright (C) AB Tech Solution LLC 2011 All Rights Reserved. // // This code may not be copied without the express written consent of // AB Tech Solution LLC. // // // Client: GF // // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY // KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // /////////////////////////////////////////////////////////////////////////////////////////// // // Header File Name: utilitiesr3.h // // Description: // // This module provides utility functions for the flash memory, and other // miscellaneous functions. Functions are implemented in the file, utilities.c // // Revision History: // Date Rev. Engineer Description // -------- ----- ------------ -------------- // 04/04/11 0 <NAME> Creation // // 04/07/11 0 Patel Add funcations // /////////////////////////////////////////////////////////////////////////////////////////// #ifndef UTILITIES_H_ #define UTILITIES_H_ // Misc. defines // Flash function prototypes int copyMainFlashToMem (unsigned char *, unsigned char *, int); int copyMemToMainFlash (unsigned char *, unsigned char *, int); int eraseMainSegment(unsigned char *, int); int verifyFlashContents(unsigned char *, unsigned char *, int); void syncToRam(unsigned char *, unsigned char *, int); int syncToFlash(unsigned char *, unsigned char *, int); int calcNumSegments (int); // Flash definitions #define MAIN_SEGMENT_SIZE 128 // Four segments (2048 bytes) are valid for writing, starting at 0x1000 // The Information memory segment starts at 0x18OO and goes to address 0x1c00, // So these areas must be avoided. Program memory starts at 0x4400, at // the other end of the flash memory #define VALID_SEGMENT_1 (unsigned char *)0x1800 #define VALID_SEGMENT_2 (unsigned char *)(VALID_SEGMENT_1+MAIN_SEGMENT_SIZE) // 1200 #define VALID_SEGMENT_3 (unsigned char *)(VALID_SEGMENT_2+MAIN_SEGMENT_SIZE) // 1400 #define VALID_SEGMENT_4 (unsigned char *)(VALID_SEGMENT_3+MAIN_SEGMENT_SIZE) // 1600 #define INFO_MEMORY_END (unsigned char *)0x1A00 // Misc. utility prototypes float IntToFloat (int); #endif /*UTILITIES_H_*/ <file_sep>/*! * \file hardware.c * \brief Provides the hardware interface for GF Hart implementation * * * Created on: Sep 28, 2012 * \author: MH */ //============================================================================== // INCLUDES //============================================================================== #include "define.h" #include "msp_port.h" #include "hardware.h" #include "driverUart.h" #include "hartMain.h" //============================================================================== // LOCAL DEFINES //============================================================================== //============================================================================== // LOCAL PROTOTYPES. //============================================================================== static void toggleRtsLine(); //============================================================================== // GLOBAL DATA //============================================================================== volatile WORD SistemTick125mS=0; unsigned char currentMsgSent = NO_CURRENT_MESSAGE_SENT; volatile BOOLEAN bHartRecvFrameCompleted = FALSE; // volatile WORD flashWriteTimer =0; // Original timer was 4000 mS, local var //============================================================================== // LOCAL DATA //============================================================================== //============================================================================== // FUNCTIONS //============================================================================== /*! * \fn INIT_SVS_supervisor() * * \brief Enables supply voltage supervision and monitoring * */ void INIT_SVS_supervisor(void) { // remove the SVS from the circuit to prevent uncommanded resets PMMCTL0_H = 0xA5; // Un-Lock PMM module registers for write access SVSMLCTL &= ~( SVMLE + SVSLE); // Disable Low side SVM SVSMHCTL &= ~( SVMHE + SVSHE); // Disable High side SVM PMMCTL0_H = 0x00; // Lock PMM module registers for write access } /*! * \fn INIT_set_Vcore * * \brief Set The VCore Voltage * \param Vcore Level * \return none * */ void INIT_set_Vcore (unsigned char level) { PMMCTL0_H = 0xA5; // Unlock PMM module registers to allow write access // Set SVS/M high side to new level SVSMHCTL = (SVSMHCTL & ~(SVSHRVL0*3 + SVSMHRRL0)) | \ (SVSHE + SVSHRVL0 * level + SVMHE + SVSMHRRL0 * level); // Set SVM new Level SVSMLCTL = SVSLE + SVMLE + SVSMLRRL0 * level; // Set SVS/M low side to new level SVSMLCTL = (SVSMLCTL & ~(SVSMLRRL_3)) | (SVMLE + SVSMLRRL0 * level); while ((PMMIFG & SVSMLDLYIFG) == 0); // Wait till SVM is settled (Delay) PMMCTL0_L = PMMCOREV0 * level; // Set VCore to x PMMIFG &= ~(SVMLVLRIFG + SVMLIFG); // Clear already set flags if ((PMMIFG & SVMLIFG)) while ((PMMIFG & SVMLVLRIFG) == 0); // Wait till level is reached // Set SVS/M Low side to new level SVSMLCTL = (SVSMLCTL & ~(SVSLRVL0*3 + SVSMLRRL_3)) | \ (SVSLE + SVSLRVL0 * level + SVMLE + SVSMLRRL0 * level); PMMCTL0_H = 0x00; // Lock PMM module registers to prevent write access } /*! * \fn checkClock * Checks and clear any oscillator fault * Periodically (100 to 500 mS) call this routine to assure XT1 oscillator is ON * JY */ void checkClock(void) { while ( (SFRIFG1 & OFIFG)) // Check OFIFG fault flag { // Clear OSC fault flags UCSCTL7 &= ~(DCOFFG + XT1LFOFFG + /* XT1HFOFFG */ + XT2OFFG); SFRIFG1 &= ~OFIFG; // Clear OFIFG fault flag } } /*! * \fn initClock(void) * \brief Set clocks MCLK & SMCLK - DCO 1.048576MHz enable FLL:XT1, * ACLK -XT1 xtal 32.768KHz * * Main clock MCLK source is DCO, maximum permissible freq is 1.048MHz for Low power * DCO stabilized by FLL (as default) but using XT1 as the reference clock. * SMCLK will be used for HSB Uart, ACLK for Hart Uart and system timers * * 12/11/12 * - FLL is enabled at Power up. After XT1 starts up, we disable FLL and leave DCO without compensation * (this is a temp solution since our Hart HW has silicon rev. E with the UCS10 errata) * - Future designs expect silicon rev F/G/H+ without FLL -clock jump problem * * \author MH 9/29/12 */ void initClock(void) { // X2 should be off after POR - Turn it off if we came from a Soft-reset UCSCTL6 |= XT2OFF; // Set XT2 Off // Enable XT1 Clock pins XT1_PORTREN &= ~(XIN_MASK | XOUT_MASK); // remove resistors (if any) from Xtal pins XT1_PORTDIR |= XOUT_MASK; // XOUT as output (JY) XT1_PORTOUT |= XOUT_MASK; // XOUT high (JY lowest drive?) XT1_PORTSEL |= XIN_MASK | XOUT_MASK; // Xtal function, this enables XT1 oscillator but uses REFO until XT1 stabilizes // Values from TI examples are the defaults after a POR- MH 11/19/12 // XT2DRIVE=3, X2TOFF=1, XT1DRIVE=3, XTS=0, XT1BYPASS=0, SMCLKOFF=0, XCAP=3 (12pF), XT1OFF=1 // Use no internal caps as this board has external 22pF - Recommend CL external value should be 12pF each UCSCTL6 &= ~(XCAP0_L | XCAP1_L | XT1OFF); // Clear defaults XCAP_3 and XT1OFF // ==> set the internal Caps as necessary UCSCTL6 |= XCAP_x // // Setup DCO frequency by the FLL frequency multiplier FLLN and loop divider FLLD // After stabilization: DCOCLK = (32768/1 ) * ( 1 * (31+1)) = 1,048,576 Hz // UCSCTL2 = FLLD__1 | // FLLD=0 divide-feedback-by-1 ?? default is 1 and still div-by-1 // 0x001F; // FLLN=31 divide feedback by 31+1 // ===> UCSCTL2 = 0x101F is the default as TI example: 0x101F -MH 11/19/12 // Set FLL clock reference and its divider FLLREFDIV UCSCTL3 = SELREF_0 | // SELREF = 0 FLL reference is XT1 = 32768 Hz, XT1 should start from here FLLREFDIV__1; // FLLREFDIV=0 FLL reference div-by-1 // Select the system clocks (same as TI example, default 0x0044) as Some favor DCOCLKDIV over DCOCLK (less jitter) // ACLK = XT1CLK, SMCLK = DCOCLKDIV, MCLK = DCOCLKDIV UCSCTL4 = SELA_0 | // ACLK = XT1CLK = 32.768Khz external crystal SELS_4 | // SMCLK = DCOCLKDIV= 1,048,576 as TI Example (default) MH -11/19/12 SELM_4; // MCLK = DCOCLKDIV= 1,048,576 as TI Example (default) MH -11/19/12 // Set clocks Dividers DIVPA = DIVA = DIVS = DIVM = 1 (these are Defaults and same as TI example) UCSCTL5 = DIVPA_0 | // ACLKpin = ACLK /1 DIVA_0 | // ACLK /1 DIVS_0 | // SMCLK /1 DIVM_0; // MCLK /1 // Loop until XT1 & DCO stabilize. // Clearing fault generated by XT1 allows the FLL to switch from REFO to XT1 again, until XT1 exceeds fault level // We stay in this loop for ~800mS, (maximum startup time is 500mS: 3V, 32Khz,XTS=0,XT1DRIVE=3,CLeff=12pF). // After clearing OFIFG fault, we wait 10mS before testing the bit // WORD u=0; do { UCSCTL7 &= ~(XT1LFOFFG | DCOFFG); // Clear XT1 and DCO fault flags SFRIFG1 &= ~OFIFG; // Clear fault flags __delay_cycles(10000); // 10mS @1Mhz - this is a delay before asking for Flasg status } while (u++ < 80 || (SFRIFG1&OFIFG) ); // Force to test oscillator fault flag for at least 800mS // #ifdef MONITOR_ACLK // Monitor Clocks: ACLK --> P1.0 P1DIR |= BIT0; P1SEL |= BIT0; //P1.0 is ACLK 32.768KHz _no_operation(); // Debug point: DCO calibrated close to 32*32768 ~ 1.048MHz and FLL OFF #endif #ifdef MONITOR_SMCLK // Monitor Clocks: SMCLK --> P2.2 P2DIR |= BIT2; P2SEL |= BIT2; //P2.2 is SMCLK 1.048MHz _no_operation(); // Debug point: DCO calibrated close to 32*32768 ~ 1.048MHz and FLL OFF #endif // // Done with system clock settings // TEMPORARY code: Turn OFF FLL. // FINALLY Enable FLL __bis_SR_register(SCG0); // Disable the FLL control loop === Will be applied during the Idle Slot === // 12/06/12 FLL will be always ON - unless evaluation of Rev. F shows a lot improvement // _no_operation(); _no_operation(); _no_operation(); // Debug point: DCO calibrated close to 32*32768 ~ 1.048MHz and FLL OFF } /*! * \fn initTimers() * Configure the msp430 timers as follows: * - System timer: TB, TBCLK = ACLK/8 = 4096Hz, 8 ticks/sec, * - HSB slot timeout, up, ACLK/8 = 4096Hz * - Hart receiver gap between characters TA1, up, ACLK/8 = 4096Hz * - Hart slave message reply TA2, up, ACLK/8 = 4096Hz, */ initTimers() { // Timer B0 = System Timer TBCCTL0 = CCIE; // TRCCR0 interrupt enabled TBCCR0 = SYSTEM_TICK_TPRESET; TBCTL = TBSSEL_1 | // TBCLK -> ACLK source MC_1 | // Up Mode ID_3 | // TBCLK = ACLK/8 = 4096 Hz TBCLR; // Clear // Timer A1 = Hart Rec. GAP timing HART_RCV_GAP_TIMER_CTL = TASSEL_1 | // Clock Source = ACLK ID_3 | // /8 TACLR; // Clear HART_RCV_GAP_TIMER_CCR = GAP_TIMER_PRESET; // CCR0 preset HART_RCV_GAP_TIMER_CCTL = CCIE; // Enable CCR0 interrupt // Timer A2 = Hart Rec. Slave reply time HART_RCV_REPLY_TIMER_CTL = TASSEL_1 | // Clock Source = ACLK ID_3 | // /8 TACLR; // Clear HART_RCV_REPLY_TIMER_CCR = REPLY_TIMER_PRESET;// CCR0 HART_RCV_REPLY_TIMER_CCTL = CCIE; // Enable CCR0 interrupt // Timer A0 = HSB Attention timer: Enables the RXIE to get the starting command HSB_ATTENTION_TIMER_CTL = TASSEL_1 | // Clock Source = ACLK ID_3 | // /8 TACLR; // Clear HSB_ATTENTION_TIMER_CCR = HSB_ATTENTION_CCR_PRESET; HSB_ATTENTION_TIMER_CCTL = CCIE; // Enable interrupt } /* * \fn initHardware * Initializes clock system, set GPIOs, init USB power, set Hart in Rx mode, init uC Uarts and timers * */ void initHardware(void) { stopWatchdog(); ///////////////////////////////////////////////////////////////////////////// // 2/5/13 === RTS on Modem A5191 side should be High during Reset // Hart Transmit control HART_UART_TXCTRL_PORTSEL &= ~HART_UART_TXCTRL_MASK; // Make sure pin is GPIO out HART_UART_TXCTRL_PORTDIR |= HART_UART_TXCTRL_MASK; HART_UART_TXCTRL_PORTOUT |= HART_UART_TXCTRL_MASK; // app disableHartTxDriver(); // Put Modem Line in listen mode // ///////////////////////////////////////////////////////////////////////////// // Increase RTS Drive strength 2/4/13 !MH HART_UART_TXCTRL_PORTDS |= HART_UART_TXCTRL_MASK; // toggleRtsLine(); // ///////////////////////////////////////////////////////////////////////////// // Change clock initialization earlier initClock(); // // Set up GPIO test pins P1OUT &= ~0xF0; // We are using TPS to trigger data logging TP_PORTDIR = (TP1_MASK | TP2_MASK | TP3_MASK | TP4_MASK); // Test Points as Outputs // //!MH These original configurations looks like we can have a soft-reset P1SEL &= ~(BIT2|BIT3); // i/o pins P1DIR &= ~(BIT2|BIT3); // input P1DS &= ~(BIT2|BIT3); // Drive strength low P1IES &= ~(BIT2|BIT3); // lo->hi transition (for now) P1IFG &= ~(BIT2|BIT3); // clear IFG in case it's set // Hart Uart Pins HART_UART_PORTSEL |= HART_UART_RX_MASK | HART_UART_TX_MASK; HART_UART_PORTDIR |= HART_UART_TX_MASK; HART_UART_PORTDS |= HART_UART_TX_MASK; // Full output drive strength in TX // initialize the clock system initClock(); _disable_interrupts(); //vj make sure all irq are disable // Pulse TxRxHart line to Tx mode two times and leave it in Rx Mode toggleRtsLine(); // Added the following function: stopWatchdog(); // Disable VUSB LDO and SLDO USBKEYPID = 0x9628; // set USB KEYandPID to 0x9628: access to USB config registers enabled USBPWRCTL &= ~(SLDOEN+VUSBEN); // Disable the VUSB LDO and the SLDO USBKEYPID = 0x9600; // access to USB config registers disabled unsigned int pmmReg; // Make Sure the power control is low as possible pmmReg = PMMCTL0; pmmReg &= 0x00FC; PMMCTL0 = PMMPW | pmmReg; // // // Set VCore INIT_set_Vcore(PMMCOREV_0); // initTimers(); //USE_PMM_CODE INIT_SVS_supervisor(); /// Here we go, Enable watchdog() startWatchdog(); } /*! * \fn toggleRtsLine * Toggle TxRx Hart line to have extern FF in a defined state and levae it at Receiver mode * * This function assures that the TxRx will always be on RxMode, by toggling the TxRx line * into TxMode two times 140uS ea. It uses software delay with clock at 1.048Mhz * * !MH == 2/4/13 The 140uS is marginal for the hardware AC-coupling: R8=499 Ohms, C7=0.033uS * 4*T*= 67us, Rise + Fall + 2 Level *1.1 margin = * Pulse width at least 300uS * Optocoupler also contributes with 7.5*2uS = 15uS * Patch will provide double= 500uS pulse delay * 2/5/13== only a single positive transition is necessary * * \param none * \return none * * */ void toggleRtsLine() { volatile int i; _no_operation(); for(i=0; i< 1; ++i) // 2/5/13 Only One positve transition is necessary { disableHartTxDriver(); _delay_cycles(500); enableHartTxDriver(); _delay_cycles(500); kickWatchdog(); } disableHartTxDriver(); // make sure rts is in receive mode // // P1IFG &= ~(BIT2|BIT3); // clear the DCD flags just in case they've been set } /*! * Timer B0 interrupt service routine for CCR0 * TB0 TB0CCR0 59 * */ #pragma vector=TIMER0_B0_VECTOR __interrupt void _hart_TIMER0_B0_VECTOR(void) { _no_operation(); ++SistemTick125mS; SET_SYSTEM_EVENT(evTimerTick); #ifdef LOW_POWERMODE_ENABLED _bic_SR_register_on_exit(LPM_BITS); _no_operation(); // _no_operation(); _no_operation(); #endif } /*! * Timer A0 interrupt service routine for CC0 TIMER0_A0_VECTOR (53) * HSB Slot Timer - Active (50mS) and Idle (100mS) * */ #pragma vector=TIMER0_A0_VECTOR __interrupt void hsbAttentionTimerISR(void) { //TOGGLEB(TP_PORTOUT, TP2_MASK); // Mark the Enable POINT hsbUart.hRxInter.enable(); stopHsbAttentionTimer(); // Stop This event (corrected typo error) hsbActivitySlot = TRUE; // We are preparing for RX, DO NOT WRITE NOW ON, DO NOT FALL TO SLEEP // This is the best time to clear the HSB === 12/28/12 BYTE rxbyte = UCA0RXBUF; // read & clears the RX interrupt flag and UCRXERR status flag //while(1); // Trap #ifdef LOW_POWERMODE_ENABLED _bic_SR_register_on_exit(LPM_BITS); _no_operation(); // _no_operation(); _no_operation(); #endif } /*! * Timer A1 interrupt service routine for CC0, TA1CCR0 (49) * Hart Inter-character GAP expired * 12/26/12 the gap timer is one shot * */ #pragma vector=TIMER1_A0_VECTOR __interrupt void gapTimerISR(void) { //SETB(TP_PORTOUT, TP3_MASK); // Indicate an Gap Error and leave pin there if(!bHartRecvFrameCompleted) // We time-out but hartReceiver() has ACK and waiting to Reply SET_SYSTEM_EVENT(evHartRcvGapTimeout); // Stop the timer (Only one shot) HART_RCV_GAP_TIMER_CTL &= ~MC_3; // This makes MC_0 = stop counting HART_RCV_GAP_TIMER_CTL |= TACLR; // Clear TAR // while(1); // TRAP HART PROBLEM == Didn't get Gap Error => Looking for STACK #ifdef LOW_POWERMODE_ENABLED _bic_SR_register_on_exit(LPM_BITS); _no_operation(); // _no_operation(); _no_operation(); #endif } /*! * Timer A2 interrupt service routine for CC0, TA2CCR0 (44) * Hart slave response time, we also stop the timer here to * have a ONE shot timer. Main loop doesn't need to control timer * */ #pragma vector=TIMER2_A0_VECTOR __interrupt void slaveReplyTimerISR(void) { SET_SYSTEM_EVENT(evHartRcvReplyTimer); // 12/26/12 Stop timer from an ISR HART_RCV_REPLY_TIMER_CTL &= ~MC_3; // This makes MC_0 = stop counting HART_RCV_REPLY_TIMER_CTL |= TACLR; // Clear the counting register TAR #ifdef LOW_POWERMODE_ENABLED _bic_SR_register_on_exit(LPM_BITS); _no_operation(); // _no_operation(); _no_operation(); #endif //while(1); // Trap } <file_sep>/* * driverHuart.h * * Created on: Sep 20, 2012 * Author: Marco.HenryGin */ #ifndef DRIVERHUART_H_ #define DRIVERHUART_H_ /************************************************************************* * $INCLUDES *************************************************************************/ #include "fifo.h" #include "define.h" /************************************************************************* * $DEFINES *************************************************************************/ /// /// the following are counters used for debugging serial communications */ /// typedef struct { unsigned long TxChar; unsigned long RxChar; unsigned long FramingError; unsigned long ParityError; unsigned long OverrunError; unsigned long RxError; } stSerialStatus; typedef enum { CharAvailable = 0x00, /* character available */ NoChar = 0x01, /* no character available */ ModbusSilentInterval = 0x02, /* an RTU framing character found (not used in present project)*/ BreakDetect = 0x10, OverrunError = 0x20, ParityError = 0x40, FramingError = 0x80 } stUartStatus; /*! * Provide a object-like artifact to abstract hardware uart * * */ typedef struct { // Initialized Members - Mostly constants const WORD nRxBufSize, nTxBufSize; //!< Internal buffer sizes void (*initUcsi)(void); //!< Function to initialize msp Uart int8u *fifoRxAlloc, *fifoTxAlloc; //!< Pointers to static memory allocation const BOOLEAN bRtsControl; //!< TRUE if Tx Requires hardware control \sa Tx handler functions const stFuncCtrl hRxInter, hTxInter, //!< Rx and Tx Interrupts handlers //TODO: interrupt Enable/Disable is not used hTxDriver, //!< Tx driver (RTS) (off when bit ==1) hLoopBack; //!< Feed Tx back to Rx void (*txChar)(BYTE); //!< Writes direct to TXBUF to start chained TX isrs // Dynamic members stFifo rxFifo, txFifo; // Input and Output streams // Status flags volatile BOOLEAN bRxError, //!< A global error in Rx = cancel current Frame bNewRxChar, //!< New Char has arrived bUsciTxBufEmpty, //!< Status of msp430 Serial buffer (write direct to txsbuf) bTxMode, //!< When Half Duplex, ignore Rx characters but last one bRxFifoOverrun, //!< Fifo overrun indicator bTxDriveEnable; //!< Indicates TxMode in Half-Duplex, TRUE in Full-Duplex } stUart; /************************************************************************* * $GLOBAL PROTOTYPES *************************************************************************/ BOOLEAN putcUart(BYTE ch, stUart *pUart); //!< Put a BYTE into output stream // // Two Implementations for getting data from output stream, use the one // that matches the one used on RXISR (i.e putFifo or putwFifo) BYTE getcUart(stUart *pUart); // Get a BYTE from the input stream WORD getwUart(stUart *pUart); // Get a WORD from the output stream BOOLEAN initUart(stUart *pUart); // Initialize the indicated Uart /************************************************************************* * $GLOBAL VARIABLES *************************************************************************/ /// /// Global Data /// extern BOOLEAN hartRxFrameError, //!< The serial isr receiver has detected errors in present serial frame hartNewCharInRxFifo, //!< New character has been moved to the Hart receiver fifo hartRxFifoError, //!< Indicates a problem in the whole Hart Receiver Fifo (overrun) hartTxFifoEmpty; //!< The Hart Transmitter Fifo has no more bytes to send (shift reg may still be sending) extern stUart hartUart, hsbUart; /*! * hsbActivitySlot * This flag indicates that HSB is in the traffic slot for the hart module, * It is TRUE when Hsb attention timer prepares the reception by enabling the RXIE and FALSE after Hsb has send it last TX bit * While this condition is TRUE no Low power mode is allowed */ extern volatile BOOLEAN hsbActivitySlot; //!< This flag indicates the Flash write window opportunity for HSB /*! * flashWriteEnable * This flag is evaluated at the end of Hart frame and takes into account the HSB flash write slot. * Test this flag (Read Only) in the main loop before writing to flash. * */ extern volatile BOOLEAN flashWriteEnable; /*! * iTx9900CmdBuf * This a global version of the reception command index. Once the Hsb receiver ISR ends receiving data, it load its * internal pointer to the global value. That way the internal state can be reset */ extern volatile WORD iTx9900CmdBuf; //!< This flag indicates the Flash write window opportunity for HSB /************************************************************************* * $INLINE FUNCTIONS *************************************************************************/ //=========================================INLINES=============================================== /* * \fn isRxEmpty * Returns TRUE if the input stream is empty */ inline BOOLEAN isRxEmpty(stUart *pUart) { return isEmpty(&(pUart->rxFifo)); } /* * \fn isRxFull * Returns TRUE if the input stream is full */ inline BOOLEAN isRxFull(stUart *pUart) { return isFull(&(pUart->rxFifo)); } /* * \fn isTxEmpty * Returns TRUE if the output stream is empty */ inline BOOLEAN isTxEmpty(stUart *pUart) { return isEmpty(&(pUart->txFifo)); } /* * \fn isTxFull * Returns TRUE if the output stream is full */ inline BOOLEAN isTxFull(stUart *pUart) { return isFull(&(pUart->txFifo)); } /////////// Hart Rx, Tx, RxMode ////////////// /* * \fn disableHartRxInter * Disable Hart serial transmit interrupt - */ inline void disableHartRxIntr(void) { UCA1IE &= ~UCRXIE; } /* * \fn enableHartRxInter * Enable Hart transmit serial interrupt - */ inline void enableHartRxIntr(void) { UCA1IE |= UCRXIE; } /* * \fn isHartRxIntrEnabled * Enable Hart transmit serial interrupt - */ inline BOOLEAN isHartRxIntrEnabled(void) { return (UCA1IE & UCRXIE) ? TRUE : FALSE; } /* * \fn disableHartTxInter * Disable Hart serial transmit interrupt - */ inline void disableHartTxIntr(void) { UCA1IE &= ~UCTXIE; } /* * \fn enableHartTxInter * Enable Hart transmit serial interrupt - */ inline void enableHartTxIntr(void) { UCA1IE |= UCTXIE; } /* * \fn isHartTxIntrEnabled * Enable Hart transmit serial interrupt - */ inline BOOLEAN isHartTxIntrEnabled(void) { return (UCA1IE & UCTXIE) ? TRUE : FALSE; } //////// TxDriver /*! * \fn disableHartTxDriver() * Put the hart modem in listen mode */ inline void disableHartTxDriver(void) { HART_UART_TXCTRL_PORTOUT |= HART_UART_TXCTRL_MASK; } /*! * \fn enableHartTxDriver() * Put the hart modem in talk mode */ inline void enableHartTxDriver(void) { HART_UART_TXCTRL_PORTOUT &= ~HART_UART_TXCTRL_MASK; } /* * \fn isHartTxIntrEnabled * Enable Hart transmit serial interrupt - */ inline BOOLEAN isEnabledHartTxDriver(void) { return (HART_UART_TXCTRL_PORTOUT & HART_UART_TXCTRL_MASK) ? FALSE : TRUE; // 1= Disabled } /* * \fn hartTxChar * Just an abstraction of the TXSBUF */ inline void hartTxChar(BYTE ch) { UCA1TXBUF = ch; } //////// Tx/Rx Loopback /*! * \fn disableHartLoopBack() * Remove internal connection between RX and TX line */ inline void disableHartLoopBack(void) { UCA1STAT &= ~UCLISTEN; } /*! * \fn enableHartLoopBack() * Connect internally RX and TX line */ inline void enableHartLoopBack(void) { UCA1STAT |= UCLISTEN; } /* * \fn isEnabledHartLoopBack * Get the status of internal TX and RX loopback */ inline BOOLEAN isEnabledHartLoopBack(void) { return (UCA1STAT & UCLISTEN) ? TRUE : FALSE; } ///=== /////////// HSB- High Speed Bus Rx, Tx ////////////// /* * \fn disableHsbRxInter * Disable Hsb serial transmit interrupt - */ inline void disableHsbRxIntr(void) { UCA0IE &= ~UCRXIE; } /* * \fn enableHsbRxInter * Enable Hsb transmit serial interrupt - */ inline void enableHsbRxIntr(void) { UCA0IE |= UCRXIE; } /* * \fn isHsbRxIntrEnabled * Enable Hsb transmit serial interrupt - */ inline BOOLEAN isHsbRxIntrEnabled(void) { return (UCA0IE & UCRXIE) ? TRUE : FALSE; } /* * \fn disableHsbTxInter * Disable Hsb serial transmit interrupt - */ inline void disableHsbTxIntr(void) { UCA0IE &= ~UCTXIE; } /* * \fn enableHsbTxInter * Enable Hsb transmit serial interrupt - */ inline void enableHsbTxIntr(void) { UCA0IE |= UCTXIE; } /* * \fn isHsbTxIntrEnabled * Enable Hsb transmit serial interrupt - */ inline BOOLEAN isHsbTxIntrEnabled(void) { return (UCA0IE & UCTXIE) ? TRUE : FALSE; } //////// Tx/Rx Loopback /*! * \fn disableHsbLoopBack() * Remove internal connection between RX and TX line */ inline void disableHsbLoopBack(void) { UCA0STAT &= ~UCLISTEN; } /*! * \fn enableHsbLoopBack() * Connect internally RX and TX line */ inline void enableHsbLoopBack(void) { UCA0STAT |= UCLISTEN; } /* * \fn isEnabledHsbLoopBack * Get the status of internal TX and RX loopback */ inline BOOLEAN isEnabledHsbLoopBack(void) { return (UCA0STAT & UCLISTEN) ? TRUE : FALSE; } /* * \fn hsbTxChar * Just an abstraction of the TXSBUF */ inline void hsbTxChar(BYTE ch) { UCA0TXBUF = ch; } #endif /* DRIVERHUART_H_ */ <file_sep>/*! * \file fifo.h * \brief Provides basic FIFO operations for both byte and word fifos * * Created on: Oct 1, 2012 * Author: MH */ #ifndef FIFO_H_ #define FIFO_H_ /************************************************************************* * $INCLUDES *************************************************************************/ #include "define.h" /************************************************************************* * $DEFINES *************************************************************************/ /// /// Define a general Fifo structure /// typedef struct { BYTE *buffer; //!< Data storage WORD readIndex, writeIndex; //!< Separate indexes for accessing the buffer WORD maxLength, currentLength; //!< Defines the maximum element length and current size } stFifo; /************************************************************************* * $GLOBAL PROTOTYPES *************************************************************************/ // Basic Fifo operations BYTE getFifo(stFifo *pFifo); BOOLEAN putFifo(stFifo *pFifo, BYTE data); WORD getwFifo(stFifo *pFifo); BOOLEAN putwFifo(stFifo *pFifo, WORD data); void resetFifo(stFifo *pFifo, BYTE *pBuffer); BOOLEAN initFifo(stFifo *pFifo, WORD byteSize); /************************************************************************* * $GLOBAL VARIABLES *************************************************************************/ /************************************************************************* * $INLINE FUNCTIONS *************************************************************************/ inline BOOLEAN isFull(stFifo *pFifo) { return (pFifo->currentLength == pFifo->maxLength); } //=================================================================================================== inline BOOLEAN isEmpty(stFifo *pFifo) { return (pFifo->currentLength == 0); } #endif /* FIFO_H_ */ <file_sep>#ifndef MAIN9900_H_ #define MAIN9900_H_ /////////////////////////////////////////////////////////////////////////////////////////// // // Header File Name: Main9900.h // // Description: // // This module provides HART to 9900 main interface. Functions are implemented in // the file, Main9900.c // // Revision History: // Date Rev. Engineer Description // -------- ----- ------------ -------------- // 06/29/11 0 <NAME> Creation // 11/9/12 3 <NAME> Changed communication drivers, created app layers // // /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// // $INCLUDES /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// // $DEFINES /////////////////////////////////////////////////////////////////////////////////////////// // #define MAX_9900_CMD_SIZE 67 /* 9900 command, max 67 bytes*/ #define MAX_9900_RESP_SIZE 15 /* 9900 response, max size 15 byte*/ #define SENSOR_UPDATE_TIME 150 /* Sensor update rate from the 9900 can be as fast as once every 150 mS*/ #define MAXIMUM_UPDATE_INTERVAL 10000 /* According to John at GF, the maximum update gap should be less than 10 secs*/ /*! * Every so many update messages, we need to remind the 9900 if it is in a fixed current state * 1/24/13 MH - moved from 3 seconds to aprox 1 Hr, per CG and JY * Every count is aprox 0.15 secs, 133 counts ~ 20 Secs * 20 min= 20 * 60/.15 = 8000 */ #define UPDATE_REMINDER_COUNT 8000 /* test with one minute 400-> final is 20 mins ~24000*/ /*! * The 9900 Data Base */ typedef struct st9900database { int16u DATABASE_LENGTH; char SERIAL_NUMBER [10]; char MODEL_STR [10]; char SW_VER_NUM [6]; fp32 LOOP_SET_LOW_LIMIT; fp32 LOOP_SET_HIGH_LIMIT; fp32 LOOP_SETPOINT_4MA; fp32 LOOP_SETPOINT_20MA; fp32 LOOP_ADJ_4MA; fp32 LOOP_ADJ_20MA; int8u LOOP_ERROR_VAL; int8u LOOP_MODE; int8u MEASUREMENT_TYPE; char GF9900_MS_PARAMETER_REVISION; int8u Hart_Dev_Var_Class; int8u UnitsPrimaryVar; int8u UnitsSecondaryVar; int8u Pad; // Just to be even int16u checksum; } DATABASE_9900; /*! * Database 9900 union * * For quick updates, union the database with a byte array. Just declare this as the database so the utilities will work */ typedef union u9900database { int8u bytes[sizeof(DATABASE_9900)]; DATABASE_9900 db; } U_DATABASE_9900; // HART <--> 9900 special characters #define ATTENTION '$' #define HART_ADDRESS 'H' #define HART_UPDATE 'U' #define HART_POLL 'P' #define HART_DB_LOAD 'D' #define HART_ACK 'a' #define HART_NACK 'n' #define HART_MSG_END '\r' #define HART_SEPARATOR ',' /* Comma character */ // 9900 Command Message Indicies #define CMD_ATTN_IDX 0 /* The attention character is always first */ #define CMD_ADDR_IDX CMD_ATTN_IDX+1 /* Followed by the address */ #define CMD_CMD_IDX CMD_ADDR_IDX+1 /* Followed by the command */ #define CMD_1ST_SEP_IDX CMD_CMD_IDX+1 /* Followed by the first separator */ #define CMD_FIRST_DATA CMD_1ST_SEP_IDX+1 /* Followed by the first data */ // 9900 Response message indicies #define RSP_ADDR_IDX 0 /* The return address is first */ #define RSP_1ST_SEP_IDX RSP_ADDR_IDX+1 /* Followed by a separator */ #define RSP_REQ_IDX RSP_1ST_SEP_IDX+1 /* Followed by a request */ #define RSP_2ND_SEP_IDX RSP_REQ_IDX+1 /* Followed by a separator */ #define RSP_STATUS_IDX RSP_2ND_SEP_IDX+1 /* Followed by status */ #define ACK_NACK_CR_IDX RSP_REQ_IDX+1 /* Index for ACK/NAK response */ // HART POLL message // Comm Status 9900 --> HART #define POLL_LAST_REQ_BAD '0' #define POLL_LAST_REQ_GOOD '1' #define POLL_LAST_REQ_GOOD_BUT_INCOMPLETE '2' // HART --> 9900 Response Status #define RESP_GOOD_NO_ACTIVE_HOST '0' #define RESP_ACTIVE_HOST '1' #define RESP_HOST_ERROR '2' #define RESP_NO_OR_BAD_DB '3' // HART --> 9900 Response Requests #define RESP_REQ_NO_REQ '0' #define RESP_REQ_SAVE_AND_RESTART_LOOP '1' #define RESP_REQ_CHANGE_4MA_POINT '2' #define RESP_REQ_CHANGE_20MA_POINT '3' #define RESP_REQ_CHANGE_4MA_ADJ '4' #define RESP_REQ_CHANGE_20MA_ADJ '5' #define RESP_REQ_CHANGE_SET_FIXED '6' #define RESP_REQ_CHANGE_RESUME_NO_SAVE '7' // HART UPDATE message // Variable Status 9900 --> HART #define UPDATE_STATUS_GOOD '0' #define UPDATE_STATUS_WRONG_SENSOR_FOR_TYPE '1' #define UPDATE_STATUS_CHECK_SENSOR_BAD_VALUE '2' #define UPDATE_STATUS_SENSOR_NOT_PRESENT '3' #define UPDATE_STATUS_SENSOR_UNDEFINED '4' #define UPDATE_STATUS_INIT 'F' // Adjustment limits #define ADJ_4MA_LIMIT_MIN 3.8 #define ADJ_4MA_LIMIT_MAX 5.0 #define ADJ_20MA_LIMIT_MIN 19.0 #define ADJ_20MA_LIMIT_MAX 21.0 // Loop Modes #define LOOP_OPERATIONAL 0 #define LOOP_FIXED_CURRENT 1 // Update command Message Indicies #define UPDATE_PV_START_INDEX CMD_FIRST_DATA /* PV is the first data */ #define UPDATE_SV_START_INDEX UPDATE_PV_START_INDEX+9 /* PV=8 bytes + separator */ #define UPDATE_MA4_20_START_INDEX UPDATE_SV_START_INDEX+9 /* SV=8 bytes + separator */ #define UPDATE_VAR_STATUS_INDEX UPDATE_MA4_20_START_INDEX+9 /* MA=8 bytes + separator */ #define UPDATE_COMM_STATUS_INDEX UPDATE_VAR_STATUS_INDEX+2 // Database Load message status #define DB_EXPECT_MORE_DATA '0' #define DB_LAST_MESSAGE '1' // Database Load message indices #define DB_ADDR_START_IDX CMD_FIRST_DATA /* The DB offset is the first data */ #define DB_BYTE_COUNT_IDX DB_ADDR_START_IDX+3 /* 2 bytes + separator */ #define DB_STATUS_IDX DB_BYTE_COUNT_IDX+3 /* 2 bytes + separator */ #define DB_FIRST_DATA_IDX DB_STATUS_IDX+2 /* 1 byte + separator */ // Message constants #define MIN_9900_CMD_SIZE 6 /* The poll message is at least 6 characters */ #define TIMEOUT_9900 50 /* 50 milliseconds between messages */ // Hart module should know at least these from 9900 // Device Variable Classification Codes - from HCF_SPEC-183, Table 21 #define DVC_DEVICE_VAR_NOT_CLASSIFIED 0 /* Response to a non-signal channel - DEPRECATED?? seems NOT_USED MH 1/17/13 */ #define DVC_ANALYTICAL 81 /* Default DB */ #define DVC_TEMPERATURE 64 /* Most SV are classified as TEMP */ #define DVC_LEVEL 92 /* Level can be per Volume or Mass */ #define DVC_VOLUME_PER_VOLUME 88 #define DVC_VOLUME_PER_MASS 89 #define VOLUME_PER_MASS_UNITS_LB 63 #define VOLUME_PER_MASS_UNITS_KG 61 /////////////////////////////////////////////////////////////////////////////////////////// // $GLOBAL PROTOTYPES /////////////////////////////////////////////////////////////////////////////////////////// // prototypes BOOLEAN Process9900Command(void); void Process9900Poll(void); void Process9900Update(void); void Process9900DatabaseLoad(void); void Nack9900Msg(void); void Ack9900Msg(void); int16u Calc9900DbChecksum(void); // Main UART Prototypes void resetForNew9900Message(void); void startMainXmit (void); // Trim the PV to 0 // unsigned char trimPvToZero(void); // Trim loop current unsigned char trimLoopCurrentZero(float); unsigned char trimLoopCurrentGain(float); void setUpperRangeVal(void); void setLowerRangeVal(void); void setBothRangeVals(float upper, float lower); void convertFloatToAscii(float, unsigned char *); void copy9900factoryDb(void); void updatePVstatus(void); // Utility to set fixed current mode unsigned char setFixedCurrentMode(float); /////////////////////////////////////////////////////////////////////////////////////////// // $GLOBAL VARIABLES /////////////////////////////////////////////////////////////////////////////////////////// /*! * MH - Changed scope of modeUpdateCount variable, * Variable is reset every time the CMD45 and CMD46 is executed * When modeUpdateCount exceeds UPDATE_REMINDER_COUNT (counting update messagges from 9900) * the Hart Module reminds the 9900 that is in fixed current mode and sends value * */ extern unsigned int modeUpdateCount; extern unsigned long UpdateMsgTimeout; /* According to John at GF, the maximum update gap should be less than 10 secs*/ extern unsigned char sz9900CmdBuffer [MAX_9900_CMD_SIZE]; /* Buffer for the commands from the 9900 */ extern unsigned char sz9900RespBuffer [MAX_9900_RESP_SIZE]; /* Buffer for the response to the 9900 */ // // flags to make sure that the loop value does not get reported if an update is in progress extern unsigned char updateInProgress; extern unsigned char updateRequestSent; extern int8u loopMode; extern unsigned char PVvariableStatus; /* Device Variable Status for PV */ // exported database extern U_DATABASE_9900 u9900Database; extern const DATABASE_9900 factory9900db; extern int8u updateDelay; // Trim command flags extern unsigned char setToMinValue; extern unsigned char setToMaxValue; extern BOOLEAN comm9900started; //!< This is an inherited Global Variable that has several uses: // - Is set TRUE when the first Update from 9900 command is received, // - after is set, extern BOOLEAN hostActive; /* Do we have a host actively communicating? */ extern BOOLEAN updateMsgRcvd; /* A flag that indicates that an update message has been received from the 9900 */ extern BOOLEAN databaseOk; /* database loaded OK flag */ /////////////////////////////////////////////////////////////////////////////////////////// // $INLINE FUNCTIONS /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: CalculateDatabaseChecksum() // // Description: // // Calculates the checksum of the 9900 database. // // Parameters: void // // // Return Type: int16u - the calculated chaecksum. // // Implementation notes: // // /////////////////////////////////////////////////////////////////////////////////////////// inline int16u CalculateDatabaseChecksum(void) { int iIdx; int16u calcCkSum = 0; for (iIdx = 0; iIdx < sizeof(DATABASE_9900); ++iIdx) { calcCkSum += u9900Database.bytes[iIdx]; } return calcCkSum; } /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: HexAsciiToByte() // // Description: // // converts a two-byte to hexadecimal string to it's numerical equivalent. A variant of atoh(). // // Parameters: // int8u * inString - the input two-byte string // int8u * outByte - pointer to the output byte // // Return Type: int - TRUE if the input was a valid hex number, FALSE otherwise. // // Implementation notes: // // /////////////////////////////////////////////////////////////////////////////////////////// inline int HexAsciiToByte (int8u* inString, int8u* outByte) { int Success = FALSE; // Deal with the high nibble first int8u temp = inString[0]; // If the character is NOT a valid hex character, bail. Only uppercase alpha is valid if ((temp < '0') || (temp > 'F') || ((temp > '9') && (temp < 'A'))) { return Success; } // it's valid, so convert it temp = (temp > 0x39) ? ((temp - 7) - 0x30) : (temp - 0x30); // shift to make room for the low nibble *outByte = (temp << 4); temp = inString[1]; // If the character is NOT a valid hex character, bail. Only uppercase alpha is valid if ((temp < '0') || (temp > 'F') || ((temp > '9') && (temp < 'A'))) { return Success; } // it's valid, so convert it temp = (temp > 0x39) ? ((temp - 7) - 0x30) : (temp - 0x30); *outByte += temp; //. We succeeded, so return success Success = TRUE; return Success; } /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: ByteToHexAscii() // // Description: // // converts a byte to the ASCII hex string. A variant of itoa(). // // Parameters: // int8u inByte - the input byte to convert // int8u * outString - the output two-byte string // // Return Type: void. // // Implementation notes: // // outString MUST point to a two-byte buffer // /////////////////////////////////////////////////////////////////////////////////////////// inline void ByteToHexAscii (int8u inByte, int8u * outString) { // Convert the high nibble int8u temp = (inByte >> 4) | 0x30; temp = (temp > 0x39) ? (temp + 7) : temp; *outString = temp; // convert the low nibble temp = (inByte & 0x0F) | 0x30; temp = (temp > 0x39) ? (temp + 7) : temp; *(outString+1) = temp; } #endif /*MAIN9900_H_*/ <file_sep>/*! * pre_init.c * This routine provides a pre initialization of CCS * * Disables Watch dog as standard 32mS time slot is not enough to init all global and static * * Created on: Nov 29, 2012 * Author: MH * Disable Watchdog before running zero initialization segment * */ #include <msp430f5528.h> //int _system_pre_init (void) int _system_pre_init (void) { // disable watchdog timer //------------------------ WDTCTL = WDTPW + WDTHOLD; // Stop WDT // place your code for hardware initialization here /*==================================*/ /* Choose if segment initialization */ /* should be done or not. */ /* Return: 0 to omit seg_init */ /* 1 to run seg_init */ /*==================================*/ return (1); } <file_sep>/*! * \file hartMain.c * \brief Main application entry point for GF Hart implementation * Created on: Sep 28, 2012 * \author: MH * * \mainpage Hart Communication Module Firmware Documentation * * \section intro_sec Introduction * * This document is extracted from the current firmware code tree.\n * Major features added to original revision 2 are the following: * - Serial communication drivers for Hart and High speed Serial bus * - Fifo buffers to isolate interrupt service routines from foreground tasks * - Low power operation * \n * Firmware was developed with CCS V5.1\n * Last code is stored at * and there is a remote repository at https://github.com/MarcoHG/GFHart.git * * * * \n * \version 2b * Revision History: * \verbatim - Date - Rev Engineer Description - 03/24/11 0 <NAME> Creation - 04/02/11 1 BDM Add funcations - 05/27/11 2 BMD Clean up code - 09/13/12 2a MH New code made from above references - 12/11/12 2b MH Last revision for testing - 2/4/13 2c MH - RTS pulses during power up, 150 to 600uS * * \endverbatim * * */ //============================================================================== // INCLUDES //============================================================================== #include "define.h" #include "msp_port.h" #include "hardware.h" #include "hartMain.h" #include "driverUart.h" #include "protocols.h" #include "hartcommand_r3.h" #include "main9900_r3.h" #include <string.h> //============================================================================== // LOCAL DEFINES //============================================================================== //============================================================================== // LOCAL PROTOTYPES. //============================================================================== void initSystem(void); void hsbErrorHandler(void); void pulseTp4(BYTE errCode); //============================================================================== // GLOBAL DATA //============================================================================== volatile unsigned int sEvents[1 + (evLastEvent +1)/16]; // Array where events are stored #ifdef FORCE_FLASH_WRITE WORD testWriteFlash =0; #endif //============================================================================== // LOCAL DATA //============================================================================== #if 0 // Testing Active vs. Lowpower volatile int16u low_power=0; BOOLEAN lowPowerModeEnabled= FALSE; #endif WORD flashWriteTimer=0;// nBytesHartRx; /*! * Monitor HSB activity * * Monitor the HSB for activity, * (These may be promoted to local scope under main() ) */ volatile int16u hsbNoActivityTimer=0; volatile BOOLEAN hsbNoActivityError= FALSE; volatile BOOLEAN bRequestHsbErrorHandle= FALSE; volatile WORD hsbWAtchDog; //HICCUP: flashWriteCount was declared as unsigned int but used as long unsigned long int flashWriteCount=0; unsigned long int dataTimeStamp=0; //============================================================================== // FUNCTIONS //============================================================================== //HICCUP #include "utilities_r3.h" /*! * initialize local data structure for the first time, or if the NV memory is ever corrupted. * * If the NV memory is corrupt, copy the factory structure into ram, then copy the RAM to the FLASH */ void initializeLocalData (void) { int numSegsToErase; // Clear the local structure memset(&startUpDataLocalNv, 0, sizeof(HART_STARTUP_DATA_NONVOLATILE)); // Now copy the factory image into RAM memcpy(&startUpDataLocalNv, &startUpDataFactoryNv, sizeof(HART_STARTUP_DATA_NONVOLATILE)); // Now copy in the NV unique device ID copyNvDeviceIdToRam(); // erase the segment of FLASH so it can be reprogrammed numSegsToErase = calcNumSegments (sizeof(HART_STARTUP_DATA_NONVOLATILE)); eraseMainSegment(VALID_SEGMENT_1, (numSegsToErase*MAIN_SEGMENT_SIZE)); // Copy the local data into NV memory copyMemToMainFlash (VALID_SEGMENT_1, ((unsigned char *)&startUpDataLocalNv), sizeof(HART_STARTUP_DATA_NONVOLATILE)); } void initStartUpData() { // Load up the volatile startup data // Clear the local structure memset(&startUpDataLocalV, 0, sizeof(HART_STARTUP_DATA_VOLATILE)); // Now copy the factory image into RAM memcpy(&startUpDataLocalV, &startUpDataFactoryV, sizeof(HART_STARTUP_DATA_VOLATILE)); // Load up the nonvolatile startup data // Load the startup data from NV memory syncToRam(VALID_SEGMENT_1, ((unsigned char *)&startUpDataLocalNv), sizeof(HART_STARTUP_DATA_NONVOLATILE)); // If the local data structure has bad values, initialize them if (GF_MFR_ID != startUpDataLocalNv.ManufacturerIdCode) { initializeLocalData(); } else { // Make sure we have the correct Device ID in any case verifyDeviceId(); } // Set the COLD START bit for primary & secondary setPrimaryStatusBits(FD_STATUS_COLD_START); setSecondaryStatusBits(FD_STATUS_COLD_START); ++startUpDataLocalV.errorCounter[8]; } /*! * System level initialization * * Performs an ordered start up of the Hart micro controller, low level hardware first, clock, * peripherals and then data base. * */ void initSystem(void) { initHardware(); // Initialize clock system, GPIO, timers and peripherals initUart(&hartUart); // Initialize Hart Uart @1200bps, 8,o,1 // Hart Starts First hartUart.hTxInter.enable(); hartUart.hRxInter.enable(); initHartRxSm(); // Init Global part, static vars are initialized at first call // High Speed Bus initialization - RX is enabled some time after OR few Hart transactions initUart(&hsbUart); // Initialize High Speed Bus Uart @19200bps, 7,o,1 hsbUart.hTxInter.enable(); // MH - Just to be sure on timming kickWatchdog(); // Merging original code = higher level inits // copy in the 9900 database copy9900factoryDb(); //USE_PMM_CODE-> move to Hw INIT_SVS_supervisor(); // MH: I am trying to collect all initializations in a single function // and also to understand the interface, keeping high level here initStartUpData(); } /*! * Waits for the next event to happen * * This is where the main event loop spend its time when there is nothing else to do. * The wait is executed at LPM0 and it takes an interrupt to get it started.\n * Once an interrupt is received, the MCLK starts, and the first thing checked is if any interrupt * that can generate an event is the source. If not, we go back to sleep.\n * If waken up by an event creating interrupt [Note!!! there can be multiple sources at the same time], * they are check them as follows:\n * - Hart events: evHartRxChar, evHartTxChar, evHartRcvGapTimeout, evHartRcvReplyTimer, evHartTransactionDone * - High Speed Bus events: evHsbRxChar, evHsbTxChar, evHsbRcvReplyTimer, evHsbTxDone, evHsbSlotTimeout * - System Events: evTimerTick * * \sa #tEvent #sEvents */ tEvent waitForEvent() { // Wait until something happens while( NO_EVENT() ) // 12/28/12 This MACRO collects all events in Atomic instruction { /*! * stop_oscillator() * Stops the CPU clock and puts the processor in sleep mode. * Sleep mode can only be exited by interrupt that restarts the clock. * */ _no_operation(); // Just a Breakpoint //CLEARB(TP_PORTOUT, TP2_MASK); // LPM indicate going to sleep #ifdef LOW_POWERMODE_ENABLED if(!hsbActivitySlot) // Real power save is done when no HSB activity, { __bis_SR_register(LPM_BITS); // Enter into indicated Low Power mode _no_operation(); _no_operation(); _no_operation(); // Allow some debug } // SETB(TP_PORTOUT, TP2_MASK); // LPM Indicate Active CPU #endif _no_operation(); // Just a Breakpoint } // There is an event, need to find from registered ones tEvent event = evNull; while(event < evLastEvent) if( IS_SYSTEM_EVENT(event)) // This is a macro, providing NZ if TRUE { _disable_interrupt(); CLEAR_SYSTEM_EVENT(event); _enable_interrupt(); return event; // return the First event found (lower number attended first) } else event++; return evNull; // Never happens, unless unregistered event. Returning NULL is safer (I think) } /*1 * pulseTp4() * This function sends a pulse to TP4, duration of pulse is errorCode x 100uS * */ void pulseTp4(BYTE errorCode) { // Generate a TP pulse BYTE i; SETB(TP_PORTOUT, TP4_MASK); // Rising Edge of error code for(i=0; i< errorCode; ++i) // Delay the Indicated Error code _delay_cycles(100); CLEARB(TP_PORTOUT, TP4_MASK); // Falling Edge of error code } /*! * HSB Error Handler * * The function does a cleaning of the serial port, UART status is set to its POR state. * All pointers and fifo are initialized * * \returns always returns FALSE */ void hsbErrorHandler() { // The only place outside the isr where we access Hsb timer stopHsbAttentionTimer(); // This set the UART to PUC status (interrupts disabled) UCA0CTL1 |= UCSWRST; // Reset internal SM _no_operation(); UCA0CTL1 &= ~UCSWRST; // Initialize USCI state machine hsbUart.hTxInter.disable(); // just to make sure (debugger doesn't match user manual) // Set Buffers to init hsbUart.bRxError = FALSE; // Clear Error code hsbActivitySlot = TRUE; // Keep HSB awake at all times // Reset Fifos // Init internal pointers proper allocated memory, fifo length to zero resetFifo(&hsbUart.rxFifo,hsbUart.fifoRxAlloc); // resetFifo(&hsbUart.txFifo,hsbUart.fifoTxAlloc); // // Internal Uart status hsbUart.bRxError = FALSE; hsbUart.bNewRxChar = FALSE; hsbUart.bUsciTxBufEmpty = TRUE; hsbUart.bTxMode = FALSE; hsbUart.bRxFifoOverrun = FALSE; // Return Interrupts to proper operation hsbUart.hTxInter.enable(); hsbUart.hRxInter.enable(); } void clock_patch() { do { UCSCTL7 &= ~(XT2OFFG | XT1LFOFFG | DCOFFG); // Clear XT2,XT1,DCO fault flags SFRIFG1 &= ~OFIFG; // Clear fault flags // Reconfig XT1 as the clk source to FLL every loop XT1, such that above fault osc is referred to XT1 UCSCTL3 = SELREF_0 | // SELREF = 0 FLL reference is XT1 = 32768 Hz, XT1 should start from here FLLREFDIV__1; // FLLREFDIV=0 FLL reference div-by-1 } while (SFRIFG1&OFIFG); // Test oscillator fault flag } /*! * This routine synchronizes the startUpDataLocalNv with flash * If conditions met: updateNvRam, flashWriteTimer and the HSB flashWriteEnable flag is set * the local StartUpdata is synch with flash */ void pollSyncNvRam() { if ( updateNvRam && flashWriteTimer >= (FLASH_WRITE_MS/SYSTEM_TICK_MS) && updateNvRam && // Leave 2 secs between continuous writes flashWriteEnable) // This condition tells that HSB is not receiving or transmitting { #ifndef DISABLE_INTERNAL_FLASH_WRITE // flashWriteTimer =0; updateNvRam = FALSE; ++flashWriteCount; // To take real advantage of skip Hsb response, syncNvRam() should return TRUE if a real flash (erase, write) is performed // bBlockThisHsbResponse =syncNvRam(); syncNvRam(); #endif } } ///////////////////////////////// #define smallBufSize 80 void main() { volatile unsigned int i; volatile WORD hartBeatTick; BOOLEAN hartCommStarted; //!< The flag is set to FALSE when stopHartComm() to indicate that Hart has been stopped, // every system tick is polled to reestablished when Database is Ok again volatile BOOLEAN bBlockThisHsbResponse = FALSE; // Block response if Flash enter the narrow door WORD hostActiveCounter =0; //!< This is a watchdog for Hart Message activity WORD comm9900counter =0; BYTE hsbRecoverAttempts =0; // We don't want to fill Astro-Med HDD up // see recycle #6 #ifdef HSB_SEQUENCER WORD hartHsbSequenceCtr=0; //!< Delay to start Hart first and then Hsb (125mS ticks) #endif //////////////////////////////////////// // Indicate a POR in pin TP3 P1DIR |= TP3_MASK; // set as out TOGGLEB(TP_PORTOUT,TP3_MASK); // Indicate a Power UP reset sequence __delay_cycles(2000); TOGGLEB(TP_PORTOUT,TP3_MASK); // Indicate a Power UP reset sequence __delay_cycles(2000); ////////////////////////////////// initSystem(); // Individual serial interrupts Settings before enter endless loop // HART: RX=Enabled, TX=Enabled // HSB: RX= Disabled, TX= Enabled // Global Interrupt enable from here // Testing HSB //!div-n-conq // 1 no HSB for now: hsbUart.hRxInter.enable(); // 2 No system timer //TBCCTL0 &= ~CCIE; // TRCCR0 interrupt enabled // 3 No signature // #undef DEBUG_SIGN_MAINLOOP_TOGGLE _enable_interrupt(); //< Enable interrupts after all hardware and peripherals set volatile BYTE ch= 'A', rP=0,LoadSize=1, echo=0; i=0; CLEARB(TP_PORTOUT, TP1_MASK); // Indicate we are running tEvent systemEvent; initHartRxSm(); // Init Global part, static are intialized at first call volatile BYTE bLastRxChar; // Following LOCs are the prerequisites to run using same original sw hartCommStarted = TRUE; // All pre-requisites ready to start communcation with HART CLEARB(TP_PORTOUT,TP2_MASK); // Start with LOW WORD loopTimes =0; volatile tEvent switchTask; // /////////////////////////////////////////// while(1) // continuous loop { systemEvent = waitForEvent(); kickWatchdog(); #ifdef DEBUG_SIGN_MAINLOOP_TOGGLE TOGGLEB(TP_PORTOUT, TP3_MASK); // Measure main LOOP scan time - optionaly signed at end of scan #endif switch(systemEvent) { //////////////////////////////// The HSB responds to Only ONE Event //////////////////////////////////////////// // 1 EVENT // Command buffer is ready case evHsbRecComplete: _no_operation(); if(bBlockThisHsbResponse) bBlockThisHsbResponse = FALSE; // Only one response blocked per incident else { // Main loop is too slow for a single HSB. Received data is prepared under ISR SETB(TP_PORTOUT, TP2_MASK); // HSB message 3) Send Data to TX buffer Process9900Command(); // Returns TRUE if valid command hsbNoActivityTimer =0; // hsbErrorHandler(4,TP4_MASK); // Error code 4= Malformed command } break; // //////////////////////////////////// END of HSB Events /////////////////////////////////////////////// ///////////////////////////////////////// HART Events /////////////////////////////////////////////// case evHartRxChar: while(!isRxEmpty(&hartUart)) // Debug Low power mode == Missing the LRC byte, 17th char in CMD 1 & 2 { //SETB(TP_PORTOUT, TP1_MASK); // ++nBytesHartRx; // Count every received char at Hart (loop back doesn't generate and event) // Just test we are receiving a 475 Frame hartReceiver(getwUart(&hartUart)); //CLEARB(TP_PORTOUT, TP1_MASK); } break; case evHartRcvGapTimeout: if(bHartRecvFrameCompleted) // Just in case a Race condition - ignore this event break; // This is an Error: Hart master transmitter exceeds maximum Gap time //Astro-Med ===> // SETB(TP_PORTOUT, TP3_MASK); // Indicate an GAP timer Error if(hartFrameRcvd ==FALSE) // Cancel current Hart Command Message, prepare to Rx a new one initHartRxSm(); HartErrRegister |= GAP_TIMER_EXPIRED; // Record the Fault // Lets do some Debug This generates an event in AstroMed pulseTp4(2); break; case evHartRcvReplyTimer: // Process the frame (same as original project) //SETB(TP_PORTOUT, TP2_MASK); // Indicate Start of response if (commandReadyToProcess) { // clear the flag commandReadyToProcess = FALSE; // Initialize the response buffer initRespBuffer(); // Process the HART command if (processHartCommand() ) // && !doNotRespond) // note that doNotRespond is always FALSE as we don;t support CMD_42 { // see recycle #4 // recycle #7 sendHartFrame(); _no_operation(); // Debug number of Rx // recycle #5 } else { // This command was not for this address or invalid // Get ready to start another frame initHartRxSm(); //MH: TODO: Look for side effects on Globals } } // No more need to stopReplyTimerEvent(); as is one shot //CLEARB(TP_PORTOUT, TP2_MASK); // Indicate END of response (CPU processing) break; case evHartTransactionDone: //////////////////////////////////////////////////////////////////////////////////////////// // If HSB has been shutd-down by any error on bus or itself, we need to put it up if(bRequestHsbErrorHandle) { bRequestHsbErrorHandle = FALSE; hsbErrorHandler(); // Error code 1= Sync lost pulseTp4(1); break; // We allow only ONE system event per Hart frame complete } // MH = 1/24/13 Logic to Set the hostActive: Any complete message sets the host indicator hostActive = TRUE; hostActiveCounter =0; // Keep resting the time-out counter ////////////////////////////////////////////////////////////////////////////////////////// // // Write to Flash is Critical Task - We don't disable interrupts but do test // several times that HSB is not about to end reception before writing to Flash // // 1/18/13 Hart Test ULA038a - If we don't have a Hart Master with cyclic message, we need // to syncNvRam() under another event user case where there is no any other if(updateNvRam) pollSyncNvRam(); hartBeatTick =0; // Indicate the presence of a Hart Master Frame break; //////////////////////////// END of HART Events /////////////////////////////////////////////// ////////////////////////////////// SYSTEM EVENTS /////////////////////////////////////////////// // // case evTimerTick: // System timer event - Get here every 125mS // MH Logic to reset hostActive bit 1/24/13 if( hostActiveCounter < HOST_ACTIVE_TIMEOUT && ++hostActiveCounter == HOST_ACTIVE_TIMEOUT) hostActive = FALSE; #ifdef FORCE_FLASH_WRITE ++testWriteFlash; /// DEBUG #endif // 1/18/13 Hart Test ULA038a - // If we don't have a Hart Master with cyclic messages, syncNvRam() with a timed event if(updateNvRam && ++hartBeatTick > HART_CONFIG_CHANGE_SYNC_TICKS ) // MH- For now just 1.5 secs after last Hart message that intends to change memory pollSyncNvRam(); // TICKS TIMERS if (NUMBER_OF_MS_IN_24_HOURS <= (dataTimeStamp +=SYSTEM_TICK_MS) ) // dataTime stamp (mS) and rolled every 24 Hrs / Hart CMD_9 dataTimeStamp = 0; ++flashWriteTimer; // Flash write stress protection SistemTick125mS =0; // Assumes no task takes more than 125mS w/o CPU attention // Check for Oscillator Flag if(SFRIFG1&OFIFG) do { UCSCTL7 &= ~(XT1LFOFFG | XT2OFFG| DCOFFG); // Clear XT1 and DCO fault flags SFRIFG1 &= ~OFIFG; // Clear fault flags } while (SFRIFG1&OFIFG); // While oscillator fault flag ==== YES this could be a problem #ifdef HSB_SEQUENCER // Receiving HSB Cmd and acting when ready doesn't need a sequence power-up // Hart -> HSB Start sequence if( hartHsbSequenceCtr < HART_HSB_SEQUENCE_DELAY && ++hartHsbSequenceCtr == HART_HSB_SEQUENCE_DELAY) hsbUart.hRxInter.enable(); // (This is Done only at power up) #endif // // Stop HART communication after 4 Sec (MAX_9900_TIMEOUT) with no 9900 communication // (only POWER-UP sequence, not sure if this needs to be checked every certain time) // stopHartComm() if ( !comm9900started && ++comm9900counter > MAX_9900_TIMEOUT) // ==> DEBUG LOW POWER MODE 0) //// HART_ALONE_LPM, original code: { comm9900counter = 0; // Flags affected by stopHartComm(), original function also disabled Hart with HART_IE &= ~UCRXIE; // If we are in the middle of a transmission, we just wait until TxFifo empties by itself // hartUart.hTxDriver.disable(); can ABORT current, but no specs hartUart.hRxInter.disable(); // Disable RX interrupts hartCommStarted = FALSE; databaseOk = FALSE; updateMsgRcvd = FALSE; } /// // This code was part of loop forever and was polled every scan, let's poll it every 125mS for now // Make sure the 9900 database and updates are occurring so that we can begin HART communications if ((!hartCommStarted) && updateMsgRcvd && databaseOk) { // Need more intelligent trap compiler is removing === while(1); // TRAP HART // The very first thing sis to enable interrupts and try to Flush RxFifo at End, as we may get // bogus interrupts while the UART was disabled and Hart master sending data hartUart.hRxInter.enable(); // Start listening to Hart modem == We need to Flush RxFIFO at the end // hartCommStarted = TRUE; // Send the initial current mode based upon what came out of FLASH if (CURRENT_MODE_DISABLE == startUpDataLocalNv.currentMode) { // Tell the 9900 to go to fixed current mode at 4 mA setFixedCurrentMode(4.0); setPrimaryStatusBits(FD_STATUS_PV_ANALOG_FIXED); setSecondaryStatusBits(FD_STATUS_PV_ANALOG_FIXED); } else { // Tell the 9900 to go to loop reporting current mode setFixedCurrentMode(0.0); clrPrimaryStatusBits(FD_STATUS_PV_ANALOG_FIXED); clrSecondaryStatusBits(FD_STATUS_PV_ANALOG_FIXED); } #if 0 // ====== HART is working properly - about 24hrs ==== // Eventualy HSB responds late -- removing or analyzing all code with TAG: (38mS?) // Return if HART fails after solving HSB // 12/21/12 //!< \note Original statement: // "Clean out the UART of any errors caused by a Hart Master trying to talk before the unit was ready" // We have saved Status and data en the hart double Rx Fifo (status, data). Uart's rx errors were cleared // on the isr, just flush the RxFifo will clear flags. while(!isRxEmpty(&hartUart)) getwUart(&hartUart); // discard status,data #endif } // // Supervisory: Hart-->HSB-->monitor HSB // Monitor HSB activity and request a HSB reset if inactive for 1.125 secs // // if(++testErrorHandler > 80 && hartHsbSequenceCtr == HART_HSB_SEQUENCE_DELAY && if(hsbNoActivityTimer < HSB_NO_ACTIVITY_TIMEOUT && !bRequestHsbErrorHandle && ++hsbNoActivityTimer >= HSB_NO_ACTIVITY_TIMEOUT && hsbRecoverAttempts++ <= 5) // For Astro-Med storage we limit to 5 tries { hsbNoActivityTimer=0; // Keep monitoring bRequestHsbErrorHandle = TRUE; // Request to Flush the HSB serial port after Hart message has been handled } break; // // // // ///////////////////////////////////// All System EVENTS /////////////////////////////////////// // case evNull: default: // evNull or any non enumerated _no_operation(); break; } #ifdef DEBUG_SIGN_MAINLOOP_TOGGLE // Sign the source with TP3 switchTask = (systemEvent == evNull) ? evLastEvent : systemEvent; // _disable_interrupt(); for(i=0; i< switchTask; ++i) TOGGLEB(TP_PORTOUT, TP3_MASK); // sign the current event _enable_interrupt(); #endif } } <file_sep>/*! * \file common_h_cmd_r3.c * \brief This module provides command handling for flow sensor commands. * * Revision History: * Date Rev. Engineer Description * -------- ----- ------------ -------------- * 04/23/11 0 <NAME> Creation * 12/11/12 MH Revision */ #include <msp430f5528.h> #include <string.h> #include "hardware.h" #include "protocols.h" #include "hart_r3.h" #include "main9900_r3.h" #include "utilities_r3.h" #include "common_h_cmd_r3.h" /*! * This flag is used by commands 11 & 21 to indicate the tag did not match, and that * processHartCommand() should return false. All other commands set the value to false. */ unsigned char badTagFlag = FALSE; /*! * \fn common_cmd_0() * \brief Process the HART command 0 : Transmit Unique ID * * Implementation notes: * MH- Added Byte order from HCF_SPEC-127 Rev 7.1 * * */ void common_cmd_0(void) { // Byte Count szHartResp[respBufferSize] = 24; // Byte count ++respBufferSize; // Device Status High Byte szHartResp[respBufferSize] = 0; // Device Status high byte ++respBufferSize; // Status Low Byte szHartResp[respBufferSize] = (startUpDataLocalV.fromPrimary) ? startUpDataLocalNv.Primary_status : startUpDataLocalNv.Secondary_status; // status byte ++respBufferSize; // 0 - Response Code szHartResp[respBufferSize] = 254; // Response Code ++respBufferSize; // 1-2 Expanded Device Type copyIntToRespBuf(startUpDataLocalV.expandedDevType); // 3 Min number of preambles M -> S szHartResp[respBufferSize] = startUpDataLocalV.minPreamblesM2S; ++respBufferSize; // 4 HART revision szHartResp[respBufferSize] = startUpDataLocalV.majorHartRevision; ++respBufferSize; // 5 Device Revision szHartResp[respBufferSize] = startUpDataLocalV.deviceRev; ++respBufferSize; // 6 sw revision szHartResp[respBufferSize] = startUpDataLocalV.swRev; ++respBufferSize; // 7 hw revision (5 msb) & signal code (3-lsb) combined unsigned char temp = startUpDataLocalV.hwRev << 3; temp |= (startUpDataLocalV.physSignalCode & 0x07); szHartResp[respBufferSize] = temp; ++respBufferSize; // 8 flags szHartResp[respBufferSize] = startUpDataLocalV.flags; ++respBufferSize; // 9-11 Device ID memcpy(&(szHartResp[respBufferSize]), &startUpDataLocalNv.DeviceID, 3); respBufferSize += 3; // 12 Min number of preambles S -> M szHartResp[respBufferSize] = startUpDataLocalV.minPreamblesS2M; ++respBufferSize; // 13 Max device vars szHartResp[respBufferSize] = startUpDataLocalV.maxNumDevVars; ++respBufferSize; // 14-15 config change counter copyIntToRespBuf(startUpDataLocalNv.configChangeCount); // 16 Extended field device status szHartResp[respBufferSize] = startUpDataLocalV.extendFieldDevStatus; ++respBufferSize; // 17-18 Manufacturer ID copyIntToRespBuf(startUpDataLocalNv.ManufacturerIdCode); // 19-20 Private Label distributor ID copyIntToRespBuf(startUpDataLocalV.PrivDistCode); // 21 Device Profile szHartResp[respBufferSize] = startUpDataLocalV.devProfile; ++respBufferSize; } /*! * \fn common_cmd_1() * \brief Process the HART command 1 : Read PV */ void common_cmd_1(void) { unsigned char respCode = (updateDelay) ? UPDATE_FAILURE : RESP_SUCCESS; if (respCode) { szHartResp[respBufferSize] = 3; // Byte count } else { szHartResp[respBufferSize] = 7; // Byte count } ++respBufferSize; szHartResp[respBufferSize] = 0; // Device Status high byte ++respBufferSize; szHartResp[respBufferSize] = (startUpDataLocalV.fromPrimary) ? startUpDataLocalNv.Primary_status : startUpDataLocalNv.Secondary_status; // Status byte ++respBufferSize; if (respCode) { szHartResp[respBufferSize] = respCode; // Command-specific response code ++respBufferSize; } else { szHartResp[respBufferSize] = u9900Database.db.UnitsPrimaryVar; // PV Units ++respBufferSize; copyFloatToRespBuf(PVvalue); } } /*! * \fn common_cmd_2() * \brief Process the HART command 2 : Transmit PV current, PV % range */ void common_cmd_2(void) { // Capture the loop current value first so it doesn't change // while building the response float loopCurrent = (TRUE == updateInProgress) ? reportingLoopCurrent : ma4_20; float pvPercent = CalculatePercentRange(u9900Database.db.LOOP_SET_HIGH_LIMIT.floatVal, u9900Database.db.LOOP_SET_LOW_LIMIT.floatVal, PVvalue); unsigned char respCode = (updateDelay) ? UPDATE_FAILURE : RESP_SUCCESS; if (respCode) { szHartResp[respBufferSize] = 3; // Byte count } else { szHartResp[respBufferSize] = 10; // Byte count } ++respBufferSize; szHartResp[respBufferSize] = 0; // Device Status high byte ++respBufferSize; szHartResp[respBufferSize] = (startUpDataLocalV.fromPrimary) ? startUpDataLocalNv.Primary_status : startUpDataLocalNv.Secondary_status; // Status byte ++respBufferSize; if (respCode) { szHartResp[respBufferSize] = respCode; // Command-specific response code ++respBufferSize; } else { // Loop current copyFloatToRespBuf(loopCurrent); // Now PV as a % of range copyFloatToRespBuf(pvPercent); } } /*! * \fn common_cmd_3() * \brief Process the HART command 3 : Transmit current PV & dynamic variables */ void common_cmd_3(void) { float loopCurrent = (TRUE == updateInProgress) ? reportingLoopCurrent : ma4_20; unsigned char respCode = (updateDelay) ? UPDATE_FAILURE : RESP_SUCCESS; // Make sure the SV units returned are capped at 250 unsigned char SVunits = (250 <= u9900Database.db.UnitsSecondaryVar) ? NOT_USED : u9900Database.db.UnitsSecondaryVar; if (respCode) { szHartResp[respBufferSize] = 3; // Byte count } else { // returning both PV & SV //szHartResp[respBufferSize] = 16; // Byte count //!MH 1/17/13 Fix: UAL011b 3262 Command 9 and Command 3 secondary values are not consist // We should not send more than supported szHartResp[respBufferSize] = (NOT_USED == SVunits) ? 11 : 16; // Byte count } ++respBufferSize; szHartResp[respBufferSize] = 0; // Device Status high byte ++respBufferSize; szHartResp[respBufferSize] = (startUpDataLocalV.fromPrimary) ? startUpDataLocalNv.Primary_status : startUpDataLocalNv.Secondary_status; // Status byte ++respBufferSize; if (respCode) { // Cmd-specific response code szHartResp[respBufferSize] = respCode; // Command-specific response code ++respBufferSize; } else { // Loop current first copyFloatToRespBuf(loopCurrent); // Now the PV szHartResp[respBufferSize] = u9900Database.db.UnitsPrimaryVar; ++respBufferSize; copyFloatToRespBuf(PVvalue); if (NOT_USED != SVunits) //!MH - DO not send ANY reference to SV if instrument can't handle { szHartResp[respBufferSize] = SVunits; ++respBufferSize; copyFloatToRespBuf(SVvalue); } } } /*! * \fn common_cmd_6() * \brief Process the HART command 6 : Save Polling address */ void common_cmd_6(void) { unsigned char pollAddress; // First check to see if we have too few bytes unsigned char respCode = (0 == hartDataCount) ? TOO_FEW_DATA_BYTES : RESP_SUCCESS; // If we have enough bytes, make sure the poll address is valid if (!respCode) { pollAddress = (longAddressFlag) ? szHartCmd[LONG_DATA_OFFSET] : szHartCmd[SHORT_DATA_OFFSET]; if (63 < pollAddress) { respCode = INVALID_POLL_ADDR_SEL; } } // If we have a non-zero code, send back the error return if (respCode) { common_tx_error(respCode); } else // We can execute the command from here { // Change the poll address in the local startup data startUpDataLocalNv.PollingAddress = pollAddress; // Now grab the current mode from the command buffer if it is there if (2 == hartDataCount) { startUpDataLocalNv.currentMode = (longAddressFlag) ? szHartCmd[LONG_DATA_OFFSET+1] : szHartCmd[SHORT_DATA_OFFSET+1]; } else if ((1 == hartDataCount) && (0 < pollAddress)) { // Current mode is disabled for a single byte, non-0 poll address startUpDataLocalNv.currentMode = CURRENT_MODE_DISABLE; } else if ((1 == hartDataCount) && (0 == pollAddress)) { // Current mode is disabled for a single byte, non-0 poll address startUpDataLocalNv.currentMode = CURRENT_MODE_ENABLE; } // Now set the current based upon the command if (CURRENT_MODE_DISABLE == startUpDataLocalNv.currentMode) { // Tell the 9900 to go to fixed current mode at 4 mA setFixedCurrentMode(4.0); setPrimaryStatusBits(FD_STATUS_PV_ANALOG_FIXED); setSecondaryStatusBits(FD_STATUS_PV_ANALOG_FIXED); } else { // Tell the 9900 to go to loop reporting current mode setFixedCurrentMode(0.0); clrPrimaryStatusBits(FD_STATUS_PV_ANALOG_FIXED); clrSecondaryStatusBits(FD_STATUS_PV_ANALOG_FIXED); } // Set the change flags setPrimaryMasterChg(); setSecondaryMasterChg(); incrementConfigCount(); // Set up to write RAM to FLASH updateNvRam = TRUE; // Now build the response buffer szHartResp[respBufferSize] = 4; ++respBufferSize; szHartResp[respBufferSize] = 0; // Device Status high byte ++respBufferSize; szHartResp[respBufferSize] = (startUpDataLocalV.fromPrimary) ? startUpDataLocalNv.Primary_status : startUpDataLocalNv.Secondary_status; // Status byte ++respBufferSize; // Parrot back the poll address szHartResp[respBufferSize] = startUpDataLocalNv.PollingAddress; ++respBufferSize; // Return the current mode szHartResp[respBufferSize] = startUpDataLocalNv.currentMode; ++respBufferSize; } } /*! * \fn common_cmd_7() * \brief Process the HART command 7 : Read Loop Configuration */ void common_cmd_7(void) { // This command always succeeds szHartResp[respBufferSize] = 4; // Byte count ++respBufferSize; szHartResp[respBufferSize] = 0; // Device Status high byte ++respBufferSize; szHartResp[respBufferSize] = (startUpDataLocalV.fromPrimary) ? startUpDataLocalNv.Primary_status : startUpDataLocalNv.Secondary_status; // Status byte ++respBufferSize; szHartResp[respBufferSize] = startUpDataLocalNv.PollingAddress; // Polling address ++respBufferSize; szHartResp[respBufferSize] = startUpDataLocalNv.currentMode; // Loop current mode ++respBufferSize; } /*! * \fn common_cmd_8() * \brief Process the HART command 8 : Read dynamic Variable classification */ void common_cmd_8(void) { szHartResp[respBufferSize] = 6; // Byte count ++respBufferSize; szHartResp[respBufferSize] = 0; // Device Status high byte ++respBufferSize; szHartResp[respBufferSize] = (startUpDataLocalV.fromPrimary) ? startUpDataLocalNv.Primary_status : startUpDataLocalNv.Secondary_status; // Status byte ++respBufferSize; // unsigned char PvHartClassification = u9900Database.db.Hart_Dev_Var_Class; // PV classification szHartResp[respBufferSize] = PvHartClassification; ++respBufferSize; // //!MH 1/17/13 Fix to pass test UAL012 unsigned char SvHartClassification = DVC_TEMPERATURE; // Works for most SV if (250 <= u9900Database.db.UnitsSecondaryVar) // We don't have SV SvHartClassification = NOT_USED; // !MH was 0; else /* We have a SV and need to know its classification, Temp is set as default */ if(PvHartClassification == DVC_LEVEL) // Is the special case LEVEL */ if(u9900Database.db.UnitsSecondaryVar == VOLUME_PER_MASS_UNITS_LB || u9900Database.db.UnitsSecondaryVar == VOLUME_PER_MASS_UNITS_KG ) // last 2 cases by asking used units in SV SvHartClassification = DVC_VOLUME_PER_MASS; else SvHartClassification = DVC_VOLUME_PER_VOLUME; szHartResp[respBufferSize] = SvHartClassification; ++respBufferSize; // units are the TV units szHartResp[respBufferSize] = NOT_USED; ++respBufferSize; // units are the QV units szHartResp[respBufferSize] = NOT_USED; ++respBufferSize; } /*! * \fn common_cmd_9() * \brief Process the HART command 9 : Read Device Variables with Status */ void common_cmd_9(void) { float loopCurrent = (TRUE == updateInProgress) ? reportingLoopCurrent : ma4_20; float pvPercent = CalculatePercentRange(u9900Database.db.LOOP_SET_HIGH_LIMIT.floatVal, u9900Database.db.LOOP_SET_LOW_LIMIT.floatVal, PVvalue); unsigned char respCode = (deviceBusyFlag) ? HART_DEVICE_BUSY : RESP_SUCCESS; // Make sure we don't respond to more than 8 requests unsigned char numVars = (hartDataCount > 8) ? 8 : hartDataCount; unsigned char index, reqVar, reqVarIdx; // Did we request too few variables? if (0 == hartDataCount) { respCode = TOO_FEW_DATA_BYTES; } // get the index to the first requested variable reqVarIdx = respBufferSize+1; // Now determine if there is an invalid selection of 0xFF. If any requested variable // is illegal, set the response code & exit with error for (index = 0; index < numVars; ++index) { if (DVC_INVALID_SELECTION == szHartCmd[index + reqVarIdx]) { respCode = INVALID_SELECTION; break; } } if (respCode) { common_tx_error(respCode); } else { // Calculate response size szHartResp[respBufferSize] = (numVars * 8) + 7; // Byte count ++respBufferSize; szHartResp[respBufferSize] = respCode; // Device Status high byte (response code) ++respBufferSize; szHartResp[respBufferSize] = (startUpDataLocalV.fromPrimary) ? startUpDataLocalNv.Primary_status : startUpDataLocalNv.Secondary_status; // Status byte ++respBufferSize; // First byte: extended status szHartResp[respBufferSize] = startUpDataLocalV.extendFieldDevStatus; ++respBufferSize; // now loop through each request. Only respond t 0 & 1 for (index = 0; index < numVars; ++index) { // What variable is requested? reqVar = szHartCmd[index + reqVarIdx]; // what we do depends on the variable requested switch (reqVar) { case DVC_PV: // return PV case DVC_PRIMARY_VARIABLE: // Device Variable code szHartResp[respBufferSize] = reqVar; ++respBufferSize; // Device variable classification - read from 9900 database szHartResp[respBufferSize] = u9900Database.db.Hart_Dev_Var_Class; ++respBufferSize; // Units code szHartResp[respBufferSize] = u9900Database.db.UnitsPrimaryVar; ++respBufferSize; // Value copyFloatToRespBuf(PVvalue); // Status szHartResp[respBufferSize] = PVvariableStatus; ++respBufferSize; break; case DVC_SV: // return SV case DVC_SECONDARY_VARIABLE: // Device Variable code szHartResp[respBufferSize] = reqVar; ++respBufferSize; if (NOT_USED > u9900Database.db.UnitsSecondaryVar) { // Device variable classification szHartResp[respBufferSize] = u9900Database.db.Hart_Dev_Var_Class; ++respBufferSize; // Units code szHartResp[respBufferSize] = u9900Database.db.UnitsSecondaryVar; ++respBufferSize; // Value copyFloatToRespBuf(SVvalue); // Status - it is just considered good szHartResp[respBufferSize] = PVvariableStatus; ++respBufferSize; } else { //!MH 1/17/13 Set Variable status as indicated in Hart HCF_SPEC-127 Rev. 7.1 for Command 9, unsupported variables (section 6.10) // // Device VAriable Classification = 0 (DVC_DEVICE_VAR_NOT_CLASSIFIED) // Value = 0x7F, 0xA0, 0x00, 0x00 // Status = BAD, Limit= CONSTANT, Unit code 250 (NOT_USED) // Device variable classification szHartResp[respBufferSize] = DVC_DEVICE_VAR_NOT_CLASSIFIED; ++respBufferSize; // Units code szHartResp[respBufferSize] = NOT_USED; ++respBufferSize; // Value szHartResp[respBufferSize] = 0x7F; ++respBufferSize; szHartResp[respBufferSize] = 0xA0; ++respBufferSize; szHartResp[respBufferSize] = 0; ++respBufferSize; szHartResp[respBufferSize] = 0; ++respBufferSize; // Status szHartResp[respBufferSize] = VAR_STATUS_BAD | LIM_STATUS_CONST; ++respBufferSize; } break; case DVC_PERCENT_RANGE: // Device Variable code szHartResp[respBufferSize] = reqVar; ++respBufferSize; // Device variable classification szHartResp[respBufferSize] = u9900Database.db.Hart_Dev_Var_Class; ++respBufferSize; // Units code szHartResp[respBufferSize] = PERCENT; ++respBufferSize; // calculate the % of range copyFloatToRespBuf(pvPercent); // Status szHartResp[respBufferSize] = PVvariableStatus; ++respBufferSize; break; case DVC_LOOP_CURRENT: // Device Variable code szHartResp[respBufferSize] = reqVar; ++respBufferSize; // Device variable classification szHartResp[respBufferSize] = u9900Database.db.Hart_Dev_Var_Class; ++respBufferSize; // Units code szHartResp[respBufferSize] = MILLIAMPS; ++respBufferSize; // Value copyFloatToRespBuf(loopCurrent); // Status szHartResp[respBufferSize] = PVvariableStatus; ++respBufferSize; break; default: // return the not supported response // Device Variable code szHartResp[respBufferSize] = reqVar; ++respBufferSize; // Device variable classification szHartResp[respBufferSize] = 0; ++respBufferSize; // Units code szHartResp[respBufferSize] = NOT_USED; ++respBufferSize; // Value szHartResp[respBufferSize] = 0x7f; ++respBufferSize; szHartResp[respBufferSize] = 0xa0; ++respBufferSize; szHartResp[respBufferSize] = 0; ++respBufferSize; szHartResp[respBufferSize] = 0; ++respBufferSize; // Status szHartResp[respBufferSize] = VAR_STATUS_BAD | LIM_STATUS_CONST; ++respBufferSize; break; } } // data time stamp copyLongToRespBuf(dataTimeStamp); } } /*! * \fn common_cmd_11() * \brief Process the HART command 11 : Transmit Unique ID if Tag matches */ void common_cmd_11(void) { if (!memcmp(&(szHartCmd[respBufferSize+1]), &(startUpDataLocalNv.TagName[0]), SHORT_TAG_SIZE)) { badTagFlag = FALSE; // the first part of the response is identical to command 0 common_cmd_0(); } else { // No response at all badTagFlag = TRUE; // rtsRcv(); // MH: Not necessary as in "Run to completion" we don't send partial messages // Get ready for a new command // MH substituted prepareToRxFrame(); initHartRxSm(); } } /*! * \fn common_cmd_12() * \brief Process the HART command 12 : Transmit MSG */ void common_cmd_12(void) { unsigned char respCode = (deviceBusyFlag) ? HART_DEVICE_BUSY : RESP_SUCCESS; if (respCode) { szHartResp[respBufferSize] = 3; // Byte count ++respBufferSize; szHartResp[respBufferSize] = 0; // Device Status high byte ++respBufferSize; szHartResp[respBufferSize] = (startUpDataLocalV.fromPrimary) ? startUpDataLocalNv.Primary_status : startUpDataLocalNv.Secondary_status; // Status byte ++respBufferSize; // Cmd-specific response code szHartResp[respBufferSize] = respCode; // Command-specific response code ++respBufferSize; } else { szHartResp[respBufferSize] = 26; // Byte count ++respBufferSize; szHartResp[respBufferSize] = 0; // Device Status high byte ++respBufferSize; szHartResp[respBufferSize] = (startUpDataLocalV.fromPrimary) ? startUpDataLocalNv.Primary_status : startUpDataLocalNv.Secondary_status; // Status byte ++respBufferSize; memcpy(&(szHartResp[respBufferSize]), &startUpDataLocalNv.HARTmsg, 24); respBufferSize += 24; } } /*! * \fn common_cmd_13() * \brief Process the HART command 13 : Transmit Tag, Descriptor, and date */ void common_cmd_13(void) { unsigned char respCode = (deviceBusyFlag) ? HART_DEVICE_BUSY : RESP_SUCCESS; if (respCode) { szHartResp[respBufferSize] = 3; // Byte count ++respBufferSize; szHartResp[respBufferSize] = 0; // Device Status high byte ++respBufferSize; szHartResp[respBufferSize] = (startUpDataLocalV.fromPrimary) ? startUpDataLocalNv.Primary_status : startUpDataLocalNv.Secondary_status; // Status byte ++respBufferSize; // Cmd-specific response code szHartResp[respBufferSize] = respCode; // Command-specific response code ++respBufferSize; } else { szHartResp[respBufferSize] = 23; // Byte count ++respBufferSize; szHartResp[respBufferSize] = 0; // Device Status high byte ++respBufferSize; szHartResp[respBufferSize] = (startUpDataLocalV.fromPrimary) ? startUpDataLocalNv.Primary_status : startUpDataLocalNv.Secondary_status; // Status byte ++respBufferSize; // Since the are store together, just write them out memcpy(&(szHartResp[respBufferSize]), &startUpDataLocalNv.TagName, 21); respBufferSize += 21; } } /*! * \fn common_cmd_14() * \brief Process the HART command 14 : Transmit PV sensor information */ void common_cmd_14(void) { float span = 0.0; unsigned char respCode = (deviceBusyFlag) ? HART_DEVICE_BUSY : RESP_SUCCESS; if (respCode) { szHartResp[respBufferSize] = 3; // Byte count ++respBufferSize; szHartResp[respBufferSize] = 0; // Device Status high byte ++respBufferSize; szHartResp[respBufferSize] = (startUpDataLocalV.fromPrimary) ? startUpDataLocalNv.Primary_status : startUpDataLocalNv.Secondary_status; // Status byte ++respBufferSize; // Cmd-specific response code szHartResp[respBufferSize] = respCode; // Command-specific response code ++respBufferSize; } else { szHartResp[respBufferSize] = 18; // Byte count ++respBufferSize; szHartResp[respBufferSize] = 0; // Device Status high byte ++respBufferSize; szHartResp[respBufferSize] = (startUpDataLocalV.fromPrimary) ? startUpDataLocalNv.Primary_status : startUpDataLocalNv.Secondary_status; // Status byte ++respBufferSize; // The transducer S/N is 0 szHartResp[respBufferSize] = 0; // Sensor S/N ++respBufferSize; szHartResp[respBufferSize] = 0; // Sensor S/N ++respBufferSize; szHartResp[respBufferSize] = 0; // Sensor S/N ++respBufferSize; // Transducer units are the PV units szHartResp[respBufferSize] = u9900Database.db.UnitsPrimaryVar; ++respBufferSize; // Now the High limit from the database copyFloatToRespBuf(u9900Database.db.LOOP_SET_HIGH_LIMIT.floatVal); // Now the low limit from the database copyFloatToRespBuf(u9900Database.db.LOOP_SET_LOW_LIMIT.floatVal); // the minimum span is 0 copyFloatToRespBuf(span); } } /*! * \fn common_cmd_15() * \brief Process the HART command 15 : Read Device information */ void common_cmd_15(void) { float damping = 0.0; unsigned char respCode = (deviceBusyFlag) ? HART_DEVICE_BUSY : RESP_SUCCESS; if (respCode) { szHartResp[respBufferSize] = 3; // Byte count ++respBufferSize; szHartResp[respBufferSize] = 0; // Device Status high byte ++respBufferSize; szHartResp[respBufferSize] = (startUpDataLocalV.fromPrimary) ? startUpDataLocalNv.Primary_status : startUpDataLocalNv.Secondary_status; // Status byte ++respBufferSize; // Cmd-specific response code szHartResp[respBufferSize] = respCode; // Command-specific response code ++respBufferSize; } else { szHartResp[respBufferSize] = 20; // Byte count ++respBufferSize; szHartResp[respBufferSize] = DEV_STATUS_HIGH_BYTE; // Device Status high byte ++respBufferSize; szHartResp[respBufferSize] = (startUpDataLocalV.fromPrimary) ? startUpDataLocalNv.Primary_status : startUpDataLocalNv.Secondary_status; // Status byte ++respBufferSize; // Alarm selection szHartResp[respBufferSize] = ALARM_CODE_LOOP_HIGH; ++respBufferSize; // Transfer function szHartResp[respBufferSize] = XFR_FUNCTION_NONE; ++respBufferSize; // Upper & lower range units from the DB szHartResp[respBufferSize] = u9900Database.db.UnitsPrimaryVar; ++respBufferSize; // Now the High limit from the database copyFloatToRespBuf(u9900Database.db.LOOP_SET_HIGH_LIMIT.floatVal); // Now the low limit from the database copyFloatToRespBuf(u9900Database.db.LOOP_SET_LOW_LIMIT.floatVal); // PV damping value copyFloatToRespBuf(damping); // Write protect code szHartResp[respBufferSize] = NO_WRITE_PROTECT; ++respBufferSize; // Reserved for now szHartResp[respBufferSize] = NOT_USED; ++respBufferSize; // Analog channel bits szHartResp[respBufferSize] = ANALOG_CHANNEL_FLAG; ++respBufferSize; } } /*! * \fn common_cmd_16() * \brief Process the HART command 16 : Transmit Final Assembly Number */ void common_cmd_16(void) { unsigned char respCode = (deviceBusyFlag) ? HART_DEVICE_BUSY : RESP_SUCCESS; if (respCode) { szHartResp[respBufferSize] = 3; // Byte count ++respBufferSize; szHartResp[respBufferSize] = 0; // Device Status high byte ++respBufferSize; szHartResp[respBufferSize] = (startUpDataLocalV.fromPrimary) ? startUpDataLocalNv.Primary_status : startUpDataLocalNv.Secondary_status; // Status byte ++respBufferSize; // Cmd-specific response code szHartResp[respBufferSize] = respCode; // Command-specific response code ++respBufferSize; } else { szHartResp[respBufferSize] = FINAL_ASSY_SIZE+2; // Byte count ++respBufferSize; szHartResp[respBufferSize] = 0; // Device Status high byte ++respBufferSize; szHartResp[respBufferSize] = (startUpDataLocalV.fromPrimary) ? startUpDataLocalNv.Primary_status : startUpDataLocalNv.Secondary_status; // Status byte ++respBufferSize; // Final Assembly memcpy(&(szHartResp[respBufferSize]), &startUpDataLocalNv.FinalAssy, FINAL_ASSY_SIZE); respBufferSize += FINAL_ASSY_SIZE; } } /*! * \fn common_cmd_17() * \brief Process the HART command 17 : Write MSG */ void common_cmd_17(void) { // First check to see if we have too few bytes unsigned char respCode = (HART_MSG_SIZE > hartDataCount) ? TOO_FEW_DATA_BYTES : RESP_SUCCESS; // If we have enough bytes, make sure the poll address is valid if (!respCode) { respCode = (deviceBusyFlag) ? HART_DEVICE_BUSY : RESP_SUCCESS; } // If we have a non-zero code, send back the error return if (respCode) { common_tx_error(respCode); } else // We can execute the command from here { // Set the change flags setPrimaryMasterChg(); setSecondaryMasterChg(); incrementConfigCount(); // Copy the data into the local structure memcpy(startUpDataLocalNv.HARTmsg, &(szHartCmd[respBufferSize+1]), HART_MSG_SIZE); // Set up to write RAM to FLASH updateNvRam = TRUE; // Build the response szHartResp[respBufferSize] = HART_MSG_SIZE+2; // Byte count ++respBufferSize; szHartResp[respBufferSize] = 0; // Device Status high byte ++respBufferSize; szHartResp[respBufferSize] = (startUpDataLocalV.fromPrimary) ? startUpDataLocalNv.Primary_status : startUpDataLocalNv.Secondary_status; // Status byte ++respBufferSize; // Write back the message memcpy(&(szHartResp[respBufferSize]), &startUpDataLocalNv.HARTmsg, HART_MSG_SIZE); respBufferSize += HART_MSG_SIZE; } } /*! * \fn common_cmd_18() * \brief Process the HART command 18 : Write tag, descriptor & date */ void common_cmd_18(void) { // First check to see if we have too few bytes unsigned char respCode = (TAG_DESCRIPTOR_DATE_SIZE > hartDataCount) ? TOO_FEW_DATA_BYTES : RESP_SUCCESS; // If we have enough bytes, make sure the poll address is valid if (!respCode) { respCode = (deviceBusyFlag) ? HART_DEVICE_BUSY : RESP_SUCCESS; } // If we have a non-zero code, send back the error return if (respCode) { common_tx_error(respCode); } else // We can execute the command from here { // Set the change flags setPrimaryMasterChg(); setSecondaryMasterChg(); incrementConfigCount(); // Copy the received string directly into the structure memcpy(&startUpDataLocalNv.TagName, &(szHartCmd[respBufferSize+1]), TAG_DESCRIPTOR_DATE_SIZE); // Set up to write RAM to FLASH updateNvRam = TRUE; // Build response szHartResp[respBufferSize] = TAG_DESCRIPTOR_DATE_SIZE+2; // Byte count ++respBufferSize; szHartResp[respBufferSize] = 0; // Device Status high byte ++respBufferSize; szHartResp[respBufferSize] = (startUpDataLocalV.fromPrimary) ? startUpDataLocalNv.Primary_status : startUpDataLocalNv.Secondary_status; // Status byte ++respBufferSize; // Parrot back what was written memcpy(&(szHartResp[respBufferSize]), &startUpDataLocalNv.TagName, TAG_DESCRIPTOR_DATE_SIZE); respBufferSize += TAG_DESCRIPTOR_DATE_SIZE; } } /*! * \fn common_cmd_19() * \brief Process the HART command 19 : Write final assembly number */ void common_cmd_19(void) { // First check to see if we have too few bytes unsigned char respCode = (FINAL_ASSY_SIZE > hartDataCount) ? TOO_FEW_DATA_BYTES : RESP_SUCCESS; // If we have enough bytes, make sure the poll address is valid if (!respCode) { respCode = (deviceBusyFlag) ? HART_DEVICE_BUSY : RESP_SUCCESS; } // If we have a non-zero code, send back the error return if (respCode) { common_tx_error(respCode); } else // We can execute the command from here { // Set the change flags setPrimaryMasterChg(); setSecondaryMasterChg(); incrementConfigCount(); // Copy the final assembly into the database memcpy(&startUpDataLocalNv.FinalAssy, &(szHartCmd[respBufferSize+1]), 3); // Set up to write RAM to FLASH updateNvRam = TRUE; // Build the response szHartResp[respBufferSize] = FINAL_ASSY_SIZE+2; // Byte count ++respBufferSize; szHartResp[respBufferSize] = 0; // Device Status high byte ++respBufferSize; szHartResp[respBufferSize] = (startUpDataLocalV.fromPrimary) ? startUpDataLocalNv.Primary_status : startUpDataLocalNv.Secondary_status; // Status byte ++respBufferSize; // Parrot back the final assy memcpy(&(szHartResp[respBufferSize]), &startUpDataLocalNv.FinalAssy, FINAL_ASSY_SIZE); respBufferSize += FINAL_ASSY_SIZE; } } /*! * \fn common_cmd_20() * \brief Process the HART command 20 : Read Long Tag */ void common_cmd_20(void) { unsigned char respCode = (deviceBusyFlag) ? HART_DEVICE_BUSY : RESP_SUCCESS; if (respCode) { szHartResp[respBufferSize] = 3; // Byte count ++respBufferSize; szHartResp[respBufferSize] = 0; // Device Status high byte ++respBufferSize; szHartResp[respBufferSize] = (startUpDataLocalV.fromPrimary) ? startUpDataLocalNv.Primary_status : startUpDataLocalNv.Secondary_status; // Status byte ++respBufferSize; // Cmd-specific response code szHartResp[respBufferSize] = respCode; // Command-specific response code ++respBufferSize; } else { szHartResp[respBufferSize] = LONG_TAG_SIZE + 2; // Byte count ++respBufferSize; szHartResp[respBufferSize] = 0; // Device Status high byte ++respBufferSize; szHartResp[respBufferSize] = (startUpDataLocalV.fromPrimary) ? startUpDataLocalNv.Primary_status : startUpDataLocalNv.Secondary_status; // Status byte ++respBufferSize; // Final Assembly memcpy(&(szHartResp[respBufferSize]), &startUpDataLocalNv.LongTag, LONG_TAG_SIZE); respBufferSize += LONG_TAG_SIZE; } } /*! * \fn common_cmd_21() * \brief Process the HART command 21 : Read unique ID associated w/ Long Tag */ void common_cmd_21(void) { if (!memcmp(&szHartCmd[respBufferSize+1], &startUpDataLocalNv.LongTag, LONG_TAG_SIZE)) { badTagFlag = FALSE; // the first part of the response is identical to command 0 common_cmd_0(); } else { // No response at all badTagFlag = TRUE; // rtsRcv(); // MH: Not necessary as in "Run to completion" we don't send partial messages // Get ready for a new command //MH substituted prepareToRxFrame(); initHartRxSm(); } } /*! * \fn common_cmd_22() * \brief Process the HART command 22 : Write Long Tag */ void common_cmd_22(void) { // First check to see if we have too few bytes unsigned char respCode = (LONG_TAG_SIZE > hartDataCount) ? TOO_FEW_DATA_BYTES : RESP_SUCCESS; // If we have enough bytes, make sure the poll address is valid if (!respCode) { respCode = (deviceBusyFlag) ? HART_DEVICE_BUSY : RESP_SUCCESS; } // If we have a non-zero code, send back the error return if (respCode) { common_tx_error(respCode); } else // We can execute the command from here { // Set the change flags setPrimaryMasterChg(); setSecondaryMasterChg(); incrementConfigCount(); // Copy the final assembly into the database memcpy(&startUpDataLocalNv.LongTag, &(szHartCmd[respBufferSize+1]), LONG_TAG_SIZE); // Set up to write RAM to FLASH updateNvRam = TRUE; // Build the response szHartResp[respBufferSize] = LONG_TAG_SIZE+2; // Byte count ++respBufferSize; szHartResp[respBufferSize] = 0; // Device Status high byte ++respBufferSize; szHartResp[respBufferSize] = (startUpDataLocalV.fromPrimary) ? startUpDataLocalNv.Primary_status : startUpDataLocalNv.Secondary_status; // Status byte ++respBufferSize; // Parrot back the final assy memcpy(&(szHartResp[respBufferSize]), &startUpDataLocalNv.LongTag, LONG_TAG_SIZE); respBufferSize += LONG_TAG_SIZE; } } #ifdef IMPLEMENT_RANGE_CMDS_35_36_37 /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: common_cmd_35() // // Description: // // Process the HART command 35 : Write Primary Variable Range Values // // Parameters: void // // Return Type: void // // Implementation notes: // // /////////////////////////////////////////////////////////////////////////////////////////// void common_cmd_35(void) { float upper, lower; unsigned char units; // Are we busy? unsigned char respCode = (deviceBusyFlag) ? HART_DEVICE_BUSY : RESP_SUCCESS; if (!respCode) { // Check for too few bytes sent if (9 > hartDataCount) { respCode = TOO_FEW_DATA_BYTES; } } // While there are several other possible response codes, the HART processor // does not have enough information to process them, so BUSY or SUCCESS are the // only possible choices if (respCode) { common_tx_error(respCode); } else { // extract the data from the commands if (longAddressFlag) { units = szHartCmd[LONG_DATA_OFFSET]; upper = decodeBufferFloat(&(szHartCmd[LONG_DATA_OFFSET+1])); lower = decodeBufferFloat(&(szHartCmd[LONG_DATA_OFFSET+5])); } else { units = szHartCmd[SHORT_DATA_OFFSET]; upper = decodeBufferFloat(&(szHartCmd[SHORT_DATA_OFFSET+1])); lower = decodeBufferFloat(&(szHartCmd[SHORT_DATA_OFFSET+5])); } // set up the request setBothRangeVals(upper, lower); // Now build the response // Now build the response buffer szHartResp[respBufferSize] = 11; ++respBufferSize; // Send status as usual szHartResp[respBufferSize] = 0; // Device Status high byte ++respBufferSize; szHartResp[respBufferSize] = (startUpDataLocalV.fromPrimary) ? startUpDataLocalNv.Primary_status : startUpDataLocalNv.Secondary_status; // Status byte ++respBufferSize; // parrot back the units szHartResp[respBufferSize] = units; // Device Status high byte ++respBufferSize; // Now parrot back the range values copyFloatToRespBuf(upper); copyFloatToRespBuf(lower); } } /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: common_cmd_36() // // Description: // // Process the HART command 36 : Set PV Upper Range Value // // Parameters: void // // Return Type: void // // Implementation notes: // // /////////////////////////////////////////////////////////////////////////////////////////// void common_cmd_36(void) { // Are we busy? unsigned char respCode = (deviceBusyFlag) ? HART_DEVICE_BUSY : RESP_SUCCESS; // While there are several other possible response codes, the HART processor // does not have enough information to process them, so BUSY or SUCCESS are the // only possible choices if (!respCode) { // execute setUpperRangeVal(); } if (respCode) { szHartResp[respBufferSize] = 3; // Byte count } else { szHartResp[respBufferSize] = 2; // Byte count } ++respBufferSize; szHartResp[respBufferSize] = 0; // Device Status high byte ++respBufferSize; szHartResp[respBufferSize] = (startUpDataLocalV.fromPrimary) ? startUpDataLocalNv.Primary_status : startUpDataLocalNv.Secondary_status; // Status byte ++respBufferSize; if (respCode) { // Cmd-specific response code szHartResp[respBufferSize] = respCode; // Command-specific response code ++respBufferSize; } } /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: common_cmd_37() // // Description: // // Process the HART command 37 : Set PV Lower Range Value // // Parameters: void // // Return Type: void // // Implementation notes: // // /////////////////////////////////////////////////////////////////////////////////////////// void common_cmd_37(void) { // Are we busy? unsigned char respCode = (deviceBusyFlag) ? HART_DEVICE_BUSY : RESP_SUCCESS; // While there are several other possible response codes, the HART processor // does not have enough information to process them, so BUSY or SUCCESS are the // only possible choices if (!respCode) { // execute setLowerRangeVal(); szHartResp[respBufferSize] = 2; // Byte count ++respBufferSize; szHartResp[respBufferSize] = 0; // Device Status high byte ++respBufferSize; szHartResp[respBufferSize] = (startUpDataLocalV.fromPrimary) ? startUpDataLocalNv.Primary_status : startUpDataLocalNv.Secondary_status; // Status byte ++respBufferSize; } else { common_tx_error(respCode); } } #endif /*! * \fn common_cmd_38() * \brief Process the HART command 38 : Reset Configuration Changed flag */ void common_cmd_38(void) { unsigned char respCode; U_SHORT_INT configCounter; // If there are no data bytes, we assume the master is not rev 7, and simply reset the // status bit // First check to see if we have too few bytes if (0 == hartDataCount) { // Clear the status bit (startUpDataLocalV.fromPrimary) ? clrPrimaryMasterChg() : clrSecondaryMasterChg(); // Build the response szHartResp[respBufferSize] = 4; // Byte count ++respBufferSize; szHartResp[respBufferSize] = 0; // Device Status high byte ++respBufferSize; szHartResp[respBufferSize] = (startUpDataLocalV.fromPrimary) ? startUpDataLocalNv.Primary_status : startUpDataLocalNv.Secondary_status; // Status byte ++respBufferSize; // Now send back the configuration changed counter configCounter.i = startUpDataLocalNv.configChangeCount; szHartResp[respBufferSize] = configCounter.b[1]; // Device Status high byte ++respBufferSize; szHartResp[respBufferSize] = configCounter.b[0]; // Device Status high byte ++respBufferSize; } else { configCounter.b[1] = szHartCmd[respBufferSize+1]; configCounter.b[0] = szHartCmd[respBufferSize+2]; // First check to see if we have too few bytes respCode = (CONFIG_COUNTER_SIZE > hartDataCount) ? TOO_FEW_DATA_BYTES : RESP_SUCCESS; // If we have enough bytes, make sure the poll address is valid if (!respCode) { respCode = (deviceBusyFlag) ? HART_DEVICE_BUSY : RESP_SUCCESS; } // Now check to see if the config counter sent matches the local count if (!respCode) { respCode = (configCounter.i != startUpDataLocalNv.configChangeCount) ? CONFIG_COUNTER_MISMATCH : RESP_SUCCESS; } // If we do not have a successful response code, send back a short reply, do // not execute the command if (respCode) { common_tx_error(respCode); } else { // execute the command (startUpDataLocalV.fromPrimary) ? clrPrimaryMasterChg() : clrSecondaryMasterChg(); // Build the response szHartResp[respBufferSize] = CONFIG_COUNTER_SIZE+2; // Byte count ++respBufferSize; szHartResp[respBufferSize] = 0; // Device Status high byte ++respBufferSize; szHartResp[respBufferSize] = (startUpDataLocalV.fromPrimary) ? startUpDataLocalNv.Primary_status : startUpDataLocalNv.Secondary_status; // Status byte ++respBufferSize; // Now send back the configuration changed counter configCounter.i = startUpDataLocalNv.configChangeCount; szHartResp[respBufferSize] = configCounter.b[1]; // Device Status high byte ++respBufferSize; szHartResp[respBufferSize] = configCounter.b[0]; // Device Status high byte ++respBufferSize; } } } /*! * \fn common_cmd_39() * \brief Process the HART command 39 : EPROM Control Burn/Restore (Deprecated) */ void common_cmd_39(void) { unsigned char burnCommand = szHartCmd[respBufferSize+1]; // First check to see if we have too few bytes unsigned char respCode = (1 > hartDataCount) ? TOO_FEW_DATA_BYTES : RESP_SUCCESS; // If we have enough bytes, make sure the poll address is valid if (!respCode) { respCode = (deviceBusyFlag) ? HART_DEVICE_BUSY : RESP_SUCCESS; } // if there is no response code, set up to execute the command if (!respCode) { // If the command data is 0, sync to RAM if (0 == burnCommand) { // Burn RAM -> FLASH cmdSyncToFlash = TRUE; } // if it is 1, sync to flash else if (1 == burnCommand) { // Refresh FLASH -> RAM cmdSyncToRam = TRUE; } else { // Invalid selection, do nothing respCode = INVALID_SELECTION; } } // If we have a non-zero code, send back the error return if (respCode) { common_tx_error(respCode); } else // We can execute the command from here { // Now build the response buffer szHartResp[respBufferSize] = 3; ++respBufferSize; // Send status as usual szHartResp[respBufferSize] = 0; // Device Status high byte ++respBufferSize; szHartResp[respBufferSize] = (startUpDataLocalV.fromPrimary) ? startUpDataLocalNv.Primary_status : startUpDataLocalNv.Secondary_status; // Status byte ++respBufferSize; // Parrot back the command byte szHartResp[respBufferSize] = burnCommand; ++respBufferSize; } } /*! * \fn common_cmd_40() * \brief Process the HART command 40 : Enter/Exit Fixed Current Mode */ void common_cmd_40 (void) { U_LONG_FLOAT cmdCurrent; // Are we busy? unsigned char respCode = (deviceBusyFlag) ? HART_DEVICE_BUSY : RESP_SUCCESS; // Is loop current signaling disabled? if (CURRENT_MODE_DISABLE == startUpDataLocalNv.currentMode) { respCode = LOOP_CURRENT_NOT_ACTIVE; } // Did we receive enough bytes? if (!respCode) { respCode = (4 > hartDataCount) ? TOO_FEW_DATA_BYTES : RESP_SUCCESS; } // Determine if the commanded value is too large or too small if (!respCode) { updateInProgress = TRUE; // decode the commanded current cmdCurrent.fVal = decodeBufferFloat(&(szHartCmd[respBufferSize+1])); // Save the current value of the loop for later, if needed if ((0.0 < cmdCurrent.fVal) && (LOOP_OPERATIONAL == loopMode)) { savedLoopCurrent = ma4_20; } // Set the loop current respCode = setFixedCurrentMode(cmdCurrent.fVal); } if (respCode) { // clear the update in progress flag updateInProgress = FALSE; updateRequestSent = FALSE; common_tx_error(respCode); } else { // Now store the command value so that the 9900 can be periodically // reminded if it is in fixed current state lastRequestedCurrentValue = cmdCurrent.fVal; if (0.0 == cmdCurrent.fVal) { clrPrimaryStatusBits(FD_STATUS_PV_ANALOG_FIXED); clrSecondaryStatusBits(FD_STATUS_PV_ANALOG_FIXED); } else { setPrimaryStatusBits(FD_STATUS_PV_ANALOG_FIXED); setSecondaryStatusBits(FD_STATUS_PV_ANALOG_FIXED); } // Now build the response szHartResp[respBufferSize] = 6; // Byte count ++respBufferSize; szHartResp[respBufferSize] = 0; // Device Status high byte ++respBufferSize; szHartResp[respBufferSize] = (startUpDataLocalV.fromPrimary) ? startUpDataLocalNv.Primary_status : startUpDataLocalNv.Secondary_status; // Status byte ++respBufferSize; // Copy in the requested loop current value or the saved value to the response and to // the reported loop variable if (0.0 == cmdCurrent.fVal) { copyFloatToRespBuf(savedLoopCurrent); reportingLoopCurrent = savedLoopCurrent; } else { copyFloatToRespBuf(cmdCurrent.fVal); reportingLoopCurrent = cmdCurrent.fVal; } } } /*! * \fn common_cmd_42() * \brief Process the HART command 42 : Perform Device Reset */ void common_cmd_42 (void) { // Are we busy? unsigned char respCode = (deviceBusyFlag) ? HART_DEVICE_BUSY : RESP_SUCCESS; // if we are not busy, set the reset flag if (respCode) { common_tx_error(respCode); } else { cmdReset = TRUE; szHartResp[respBufferSize] = 2; // Byte count ++respBufferSize; szHartResp[respBufferSize] = 0; // Device Status high byte ++respBufferSize; szHartResp[respBufferSize] = (startUpDataLocalV.fromPrimary) ? startUpDataLocalNv.Primary_status : startUpDataLocalNv.Secondary_status; // Status byte ++respBufferSize; } } /*! * \fn common_cmd_45() * \brief Process the HART command 45 : Trim Loop Current Zero * * 1/24/13 Resets the 9900 update message counter to remind of a current trim */ void common_cmd_45 (void) { U_LONG_FLOAT cmdCurrent; // Are we busy? unsigned char respCode = (deviceBusyFlag) ? HART_DEVICE_BUSY : RESP_SUCCESS; // MH - 1/24/13 Reset the 9900 reminder modeUpdateCount =0; // Is loop current signaling disabled? if (CURRENT_MODE_DISABLE == startUpDataLocalNv.currentMode) { respCode = LOOP_CURRENT_NOT_ACTIVE; } // Did we receive enough bytes? if (!respCode) { respCode = (4 > hartDataCount) ? TOO_FEW_DATA_BYTES : RESP_SUCCESS; } // Make sure the loop is set up correctly if ((!respCode) && (FALSE == setToMinValue)) { respCode = INCORRECT_LOOP_MODE; } // Determine if the commanded value is too large or too small if (!respCode) { updateInProgress = TRUE; cmdCurrent.fVal = decodeBufferFloat(&(szHartCmd[respBufferSize+1])); respCode = trimLoopCurrentZero(cmdCurrent.fVal); } if (respCode) { updateInProgress = FALSE; updateRequestSent = FALSE; common_tx_error(respCode); } else { reportingLoopCurrent = cmdCurrent.fVal; // Now build the response szHartResp[respBufferSize] = 6; // Byte count ++respBufferSize; szHartResp[respBufferSize] = 0; // Device Status high byte ++respBufferSize; szHartResp[respBufferSize] = (startUpDataLocalV.fromPrimary) ? startUpDataLocalNv.Primary_status : startUpDataLocalNv.Secondary_status; // Status byte ++respBufferSize; // Copy in the requested loop current value for the response. The 9900 will catch up later copyFloatToRespBuf(cmdCurrent.fVal); } } /*! * \fn common_cmd_46() * \brief Process the HART command 46 : Trim Loop Current Gain * 1/24/13 Resets the 9900 update message counter to remind of a current trim */ void common_cmd_46 (void) { U_LONG_FLOAT cmdCurrent; // Are we busy? unsigned char respCode = (deviceBusyFlag) ? HART_DEVICE_BUSY : RESP_SUCCESS; // Reset 9900 reminder modeUpdateCount =0; // Is loop current signaling disabled? if (CURRENT_MODE_DISABLE == startUpDataLocalNv.currentMode) { respCode = LOOP_CURRENT_NOT_ACTIVE; } // Did we receive enough bytes? if (!respCode) { respCode = (4 > hartDataCount) ? TOO_FEW_DATA_BYTES : RESP_SUCCESS; } // Make sure the loop is set up correctly if ((!respCode) && (FALSE == setToMaxValue)) { respCode = INCORRECT_LOOP_MODE; } // Try to execute the command if no errors so far if (!respCode) { updateInProgress = TRUE; cmdCurrent.fVal = decodeBufferFloat(&(szHartCmd[respBufferSize+1])); respCode = trimLoopCurrentGain(cmdCurrent.fVal); } if (respCode) { updateInProgress = FALSE; updateRequestSent = FALSE; common_tx_error(respCode); } else { // Set the reporting current value reportingLoopCurrent = cmdCurrent.fVal; // Now build the response szHartResp[respBufferSize] = 6; // Byte count ++respBufferSize; szHartResp[respBufferSize] = 0; // Device Status high byte ++respBufferSize; szHartResp[respBufferSize] = (startUpDataLocalV.fromPrimary) ? startUpDataLocalNv.Primary_status : startUpDataLocalNv.Secondary_status; // Status byte ++respBufferSize; // Copy in the requested loop current value for the response. The 9900 will catch up later copyFloatToRespBuf(cmdCurrent.fVal); } } /*! * \fn common_cmd_48() * \brief Process the HART command 48 : Transmit Additional Status */ void common_cmd_48(void) { unsigned char match = TRUE; if ((0 < hartDataCount) && (9 > hartDataCount)) { common_tx_error(TOO_FEW_DATA_BYTES); return; } // First, check to see if we have to clear the more status available bit. // This is only true if we have 9 or more request bytes if (9 <= hartDataCount) { // Were are only going to compare the first 9 bytes if (szHartCmd[respBufferSize+1] != startUpDataLocalV.DeviceSpecificStatus[0]) { match = FALSE; } if (szHartCmd[respBufferSize+2] != startUpDataLocalV.DeviceSpecificStatus[1]) { match = FALSE; } if (szHartCmd[respBufferSize+3] != startUpDataLocalV.DeviceSpecificStatus[2]) { match = FALSE; } if (szHartCmd[respBufferSize+4] != startUpDataLocalV.DeviceSpecificStatus[3]) { match = FALSE; } if (szHartCmd[respBufferSize+5] != startUpDataLocalV.DeviceSpecificStatus[4]) { match = FALSE; } if (szHartCmd[respBufferSize+6] != startUpDataLocalV.DeviceSpecificStatus[5]) { match = FALSE; } if (szHartCmd[respBufferSize+7] != startUpDataLocalV.extendFieldDevStatus) { match = FALSE; } if (szHartCmd[respBufferSize+8] != startUpDataLocalV.DeviceOpMode) { match = FALSE; } if (szHartCmd[respBufferSize+9] != startUpDataLocalV.StandardStatus0) { match = FALSE; } if (TRUE == match) { (startUpDataLocalV.fromPrimary) ? clrPrimaryMoreAvailable() : clrSecondaryMoreAvailable(); } } // Build the response szHartResp[respBufferSize] = 11; // Byte count ++respBufferSize; szHartResp[respBufferSize] = 0; // Device Status high byte ++respBufferSize; szHartResp[respBufferSize] = (startUpDataLocalV.fromPrimary) ? startUpDataLocalNv.Primary_status : startUpDataLocalNv.Secondary_status; // Status byte ++respBufferSize; // Device specific status memcpy(&szHartResp[respBufferSize], startUpDataLocalV.DeviceSpecificStatus, DEV_SPECIFIC_STATUS_SIZE); respBufferSize += DEV_SPECIFIC_STATUS_SIZE; // Extended device status szHartResp[respBufferSize] = startUpDataLocalV.extendFieldDevStatus; ++respBufferSize; // Device operating mode szHartResp[respBufferSize] = startUpDataLocalV.DeviceOpMode; ++respBufferSize; // standard status 0 szHartResp[respBufferSize] = startUpDataLocalV.StandardStatus0; ++respBufferSize; } /*! * \fn common_cmd_54() * \brief Process the HART command 54 : Read Device Variable Information */ void common_cmd_54 (void) { union { unsigned long i; unsigned char b[4]; } UpdateTime; UpdateTime.i = SENSOR_UPDATE_TIME; float span = 0.0; float damping = 0.0; unsigned char respCode = (deviceBusyFlag) ? HART_DEVICE_BUSY : RESP_SUCCESS; unsigned char requestedVariable = szHartCmd[respBufferSize+1]; // Did we receive enough bytes? if (!respCode) { respCode = (1 > hartDataCount) ? TOO_FEW_DATA_BYTES : RESP_SUCCESS; } // Now check to make sure the selection is valid if (!respCode) { switch (requestedVariable) { case DVC_PV: case DVC_SV: case DVC_PERCENT_RANGE: case DVC_LOOP_CURRENT: case DVC_PRIMARY_VARIABLE: case DVC_SECONDARY_VARIABLE: // Do not change the response code break; default: respCode = INVALID_SELECTION; break; } } if (respCode) { common_tx_error(respCode); } else { szHartResp[respBufferSize] = 29; // Byte count ++respBufferSize; szHartResp[respBufferSize] = 0; // Device Status high byte ++respBufferSize; szHartResp[respBufferSize] = (startUpDataLocalV.fromPrimary) ? startUpDataLocalNv.Primary_status : startUpDataLocalNv.Secondary_status; // Status byte ++respBufferSize; // Device Variable Code szHartResp[respBufferSize] = requestedVariable; ++respBufferSize; // The transducer S/N is 0 szHartResp[respBufferSize] = 0; // Sensor S/N ++respBufferSize; szHartResp[respBufferSize] = 0; // Sensor S/N ++respBufferSize; szHartResp[respBufferSize] = 0; // Sensor S/N ++respBufferSize; switch(requestedVariable) { case DVC_SV: case DVC_SECONDARY_VARIABLE: // Transducer units are the PV units szHartResp[respBufferSize] = (NOT_USED <= u9900Database.db.UnitsSecondaryVar) ? NOT_USED : u9900Database.db.UnitsSecondaryVar; ++respBufferSize; break; case DVC_PV: case DVC_PERCENT_RANGE: case DVC_LOOP_CURRENT: case DVC_PRIMARY_VARIABLE: default: // Transducer units are the PV units szHartResp[respBufferSize] = u9900Database.db.UnitsPrimaryVar; ++respBufferSize; break; } // Now the High limit from the database copyFloatToRespBuf(u9900Database.db.LOOP_SET_HIGH_LIMIT.floatVal); // Now the low limit from the database copyFloatToRespBuf(u9900Database.db.LOOP_SET_LOW_LIMIT.floatVal); // the damping is 0 copyFloatToRespBuf(damping); // the minimum span is 0 copyFloatToRespBuf(span); // device variable classification switch(requestedVariable) { case DVC_SV: case DVC_SECONDARY_VARIABLE: // SV units are not classified szHartResp[respBufferSize] = 0; ++respBufferSize; break; case DVC_PV: case DVC_PERCENT_RANGE: case DVC_LOOP_CURRENT: case DVC_PRIMARY_VARIABLE: default: // Transducer units are the PV units szHartResp[respBufferSize] = u9900Database.db.Hart_Dev_Var_Class; ++respBufferSize; break; } // device variable family szHartResp[respBufferSize] = NOT_USED; ++respBufferSize; // Update time period szHartResp[respBufferSize] = UpdateTime.b[3]; ++respBufferSize; szHartResp[respBufferSize] = UpdateTime.b[2]; ++respBufferSize; szHartResp[respBufferSize] = UpdateTime.b[1]; ++respBufferSize; szHartResp[respBufferSize] = UpdateTime.b[0]; ++respBufferSize; } } /*! * \fn common_cmd_57() * \brief Process the HART command 57 : Read Unit Tag, Descriptor, and Date (Deprecated) */ void common_cmd_57 (void) { // Function is identical to command 13, so just use it common_cmd_13(); } /*! * \fn common_cmd_58() * \brief Process the HART command 58 : Write Unit Tag, Descriptor, and Date (Deprecated) */ void common_cmd_58 (void) { // the code is identical to command 18, so just use it common_cmd_18(); } /*! * \fn common_cmd_110() * \brief Process the HART command 110 : Read All Dynamic Variables (Deprecated) */ void common_cmd_110 (void) { //unsigned char respCode = (updateDelay) ? UPDATE_FAILURE : RESP_SUCCESS; szHartResp[respBufferSize] = 12; // Byte count ++respBufferSize; szHartResp[respBufferSize] = 0; // Device Status high byte ++respBufferSize; szHartResp[respBufferSize] = (startUpDataLocalV.fromPrimary) ? startUpDataLocalNv.Primary_status : startUpDataLocalNv.Secondary_status; // Status byte ++respBufferSize; // Now the PV szHartResp[respBufferSize] = u9900Database.db.UnitsPrimaryVar; ++respBufferSize; copyFloatToRespBuf(PVvalue); // Now the SV szHartResp[respBufferSize] = u9900Database.db.UnitsSecondaryVar; ++respBufferSize; copyFloatToRespBuf(SVvalue); } /*! * \fn void common_tx_error(unsigned char respCode) * \brief Respond to the master with a response code * * \param respCode The response code to send * * Global respBufferSize indicates the position in the buffer\n * The response is built in a global buffer szHartResp[] , and respBufferSize is incremented to * point to next position on buffer. */ void common_tx_error(unsigned char respCode) { szHartResp[respBufferSize] = 2; // Byte count ++respBufferSize; szHartResp[respBufferSize] = respCode; // response code ++respBufferSize; szHartResp[respBufferSize] = (startUpDataLocalV.fromPrimary) ? startUpDataLocalNv.Primary_status : startUpDataLocalNv.Secondary_status; // primary or secondary status ++respBufferSize; } /*! * \fn void common_tx_comm_error(void) * \brief Responds to the Master with a communications error code * */ void common_tx_comm_error(void) { szHartResp[respBufferSize] = 2; // Byte count ++respBufferSize; szHartResp[respBufferSize] = COMM_ERROR; // Communication Error if (HartErrRegister & BUFFER_OVERFLOW) { szHartResp[respBufferSize] |= BOVF_ERROR; // Buffer Overflow Error ++respBufferSize; } if (HartErrRegister & RCV_BAD_LRC) { szHartResp[respBufferSize] |= LPAR_ERROR; // LRC Error ++respBufferSize; } if (HartErrRegister & RCV_PARITY_ERROR) { szHartResp[respBufferSize] |= VPAR_ERROR; // Parity Error ++respBufferSize; } if (HartErrRegister & RCV_FRAMING_ERROR) { szHartResp[respBufferSize] |= FRAM_ERROR; // Framing Error ++respBufferSize; } ++respBufferSize; szHartResp[respBufferSize] = 0; // status byte ++respBufferSize; } /*! * \fn mfr_cmd_219() * \brief Process the HART command 219 : Write device ID */ void mfr_cmd_219(void) { // First check to see if we have too few bytes unsigned char respCode = (FINAL_ASSY_SIZE > hartDataCount) ? TOO_FEW_DATA_BYTES : RESP_SUCCESS; // If we have enough bytes, make sure the poll address is valid if (!respCode) { respCode = (deviceBusyFlag) ? HART_DEVICE_BUSY : RESP_SUCCESS; } // If we have a non-zero code, send back the error return if (respCode) { common_tx_error(respCode); } else // We can execute the command from here { // Set the change flags setPrimaryMasterChg(); setSecondaryMasterChg(); incrementConfigCount(); // Copy the new Device ID to FLASH copyDeviceIdToFlash(&(szHartCmd[respBufferSize+1])); // Copy the final assembly into the database memcpy(&startUpDataLocalNv.DeviceID, &(szHartCmd[respBufferSize+1]), DEVICE_ID_SIZE); // Set up to write RAM to FLASH updateNvRam = TRUE; // Build the response szHartResp[respBufferSize] = DEVICE_ID_SIZE+2; // Byte count ++respBufferSize; szHartResp[respBufferSize] = 0; // Device Status high byte ++respBufferSize; szHartResp[respBufferSize] = (startUpDataLocalV.fromPrimary) ? startUpDataLocalNv.Primary_status : startUpDataLocalNv.Secondary_status; // Status byte ++respBufferSize; // Parrot back the final assy memcpy(&(szHartResp[respBufferSize]), &startUpDataLocalNv.DeviceID, DEVICE_ID_SIZE); respBufferSize += DEVICE_ID_SIZE; } } /*! * \fn mfr_cmd_220() * \brief Process the HART command 220 : Retrieve Error Counters */ void mfr_cmd_220(void) { // First check to see if we have too few bytes unsigned char respCode; respCode = (deviceBusyFlag) ? HART_DEVICE_BUSY : RESP_SUCCESS; // If we have a non-zero code, send back the error return if (respCode) { common_tx_error(respCode); } else // We can execute the command from here { // Build the response szHartResp[respBufferSize] = 2 + 24 + 38; // Byte count ++respBufferSize; // RC & Status szHartResp[respBufferSize] = 0; // Device Status high byte ++respBufferSize; szHartResp[respBufferSize] = (startUpDataLocalV.fromPrimary) ? startUpDataLocalNv.Primary_status : startUpDataLocalNv.Secondary_status; // Status byte ++respBufferSize; // Copy the number of messages ready to process copyLongToRespBuf(numMsgReadyToProcess); // Copy the number of messages ready to process copyLongToRespBuf(numMsgProcessed); // Copy the number of messages ready to process copyLongToRespBuf(numMsgUnableToProcess); // Copy the number of messages ready to process copyLongToRespBuf(xmtMsgCounter); // Copy the number of messages ready to process copyLongToRespBuf(errMsgCounter); // Copy the number of flash writes copyLongToRespBuf(flashWriteCount); // Now copy in the error counters from the startup data structure copyIntToRespBuf(startUpDataLocalV.errorCounter[0]); copyIntToRespBuf(startUpDataLocalV.errorCounter[1]); copyIntToRespBuf(startUpDataLocalV.errorCounter[2]); copyIntToRespBuf(startUpDataLocalV.errorCounter[3]); copyIntToRespBuf(startUpDataLocalV.errorCounter[4]); copyIntToRespBuf(startUpDataLocalV.errorCounter[5]); copyIntToRespBuf(startUpDataLocalV.errorCounter[6]); copyIntToRespBuf(startUpDataLocalV.errorCounter[7]); copyIntToRespBuf(startUpDataLocalV.errorCounter[8]); copyIntToRespBuf(startUpDataLocalV.errorCounter[9]); copyIntToRespBuf(startUpDataLocalV.errorCounter[10]); copyIntToRespBuf(startUpDataLocalV.errorCounter[11]); copyIntToRespBuf(startUpDataLocalV.errorCounter[12]); copyIntToRespBuf(startUpDataLocalV.errorCounter[13]); copyIntToRespBuf(startUpDataLocalV.errorCounter[14]); copyIntToRespBuf(startUpDataLocalV.errorCounter[15]); copyIntToRespBuf(startUpDataLocalV.errorCounter[16]); copyIntToRespBuf(startUpDataLocalV.errorCounter[17]); copyIntToRespBuf(startUpDataLocalV.errorCounter[18]); } } /*! * \fn mfr_cmd_221() * \brief Process the HART command 221 : Reset Error Counters */ void mfr_cmd_221(void) { // First check to see if we have too few bytes unsigned char respCode; int index; respCode = (deviceBusyFlag) ? HART_DEVICE_BUSY : RESP_SUCCESS; // If we have a non-zero code, send back the error return if (respCode) { common_tx_error(respCode); } else // We can execute the command from here { // Reset All the long counters to 0 numMsgReadyToProcess = 0; numMsgProcessed = 0; numMsgUnableToProcess = 0; xmtMsgCounter = 0; errMsgCounter = 0; flashWriteCount = 0; // reset the counters in the startup data to 0 for (index = 0; index < 19; ++index) { startUpDataLocalV.errorCounter[index] = 0; } // Now signal the fact the NVRAM haas to change //cmdSyncToFlash = TRUE; // Build the response szHartResp[respBufferSize] = 2 + 24 + 38; // Byte count ++respBufferSize; // RC & Status szHartResp[respBufferSize] = 0; // Device Status high byte ++respBufferSize; szHartResp[respBufferSize] = (startUpDataLocalV.fromPrimary) ? startUpDataLocalNv.Primary_status : startUpDataLocalNv.Secondary_status; // Status byte ++respBufferSize; // Copy the number of messages ready to process copyLongToRespBuf(numMsgReadyToProcess); // Copy the number of messages ready to process copyLongToRespBuf(numMsgProcessed); // Copy the number of messages ready to process copyLongToRespBuf(numMsgUnableToProcess); // Copy the number of messages ready to process copyLongToRespBuf(xmtMsgCounter); // Copy the number of messages ready to process copyLongToRespBuf(errMsgCounter); // Copy the number of flash writes copyLongToRespBuf(flashWriteCount); // Now copy in the error counters from the startup data structure copyIntToRespBuf(startUpDataLocalV.errorCounter[0]); copyIntToRespBuf(startUpDataLocalV.errorCounter[1]); copyIntToRespBuf(startUpDataLocalV.errorCounter[2]); copyIntToRespBuf(startUpDataLocalV.errorCounter[3]); copyIntToRespBuf(startUpDataLocalV.errorCounter[4]); copyIntToRespBuf(startUpDataLocalV.errorCounter[5]); copyIntToRespBuf(startUpDataLocalV.errorCounter[6]); copyIntToRespBuf(startUpDataLocalV.errorCounter[7]); copyIntToRespBuf(startUpDataLocalV.errorCounter[8]); copyIntToRespBuf(startUpDataLocalV.errorCounter[9]); copyIntToRespBuf(startUpDataLocalV.errorCounter[10]); copyIntToRespBuf(startUpDataLocalV.errorCounter[11]); copyIntToRespBuf(startUpDataLocalV.errorCounter[12]); copyIntToRespBuf(startUpDataLocalV.errorCounter[13]); copyIntToRespBuf(startUpDataLocalV.errorCounter[14]); copyIntToRespBuf(startUpDataLocalV.errorCounter[15]); copyIntToRespBuf(startUpDataLocalV.errorCounter[16]); copyIntToRespBuf(startUpDataLocalV.errorCounter[17]); copyIntToRespBuf(startUpDataLocalV.errorCounter[18]); } } /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: mfr_cmd_222() // // Description: // // Process the HART command 222 : Dump Nonvolatile memory // // Parameters: void // // Return Type: void // // Implementation notes: // This MFR-specific command is used to dump the NV memory. It is not // to be published in the DD // // /////////////////////////////////////////////////////////////////////////////////////////// /*! * \fn mfr_cmd_222() * \brief Process the HART command 222 : Dump Nonvolatile memory * This MFR-specific command is used to dump the NV memory. It is not to be published in the DD * */ void mfr_cmd_222(void) { // First check to see if we have too few bytes unsigned char respCode; unsigned char index; //unsigned char * pNvMem = VALID_SEGMENT_1; unsigned char * pNvMem = (unsigned char *)&startUpDataLocalNv; respCode = (deviceBusyFlag) ? HART_DEVICE_BUSY : RESP_SUCCESS; // If we have a non-zero code, send back the error return if (respCode) { common_tx_error(respCode); } else // We can execute the command from here { // Build the response szHartResp[respBufferSize] = 2 + sizeof(HART_STARTUP_DATA_NONVOLATILE) + 1; // Byte count ++respBufferSize; // RC & Status szHartResp[respBufferSize] = 0; // Device Status high byte ++respBufferSize; szHartResp[respBufferSize] = (startUpDataLocalV.fromPrimary) ? startUpDataLocalNv.Primary_status : startUpDataLocalNv.Secondary_status; // Status byte ++respBufferSize; // Now copy out the NV Flash byte by byte for (index = 0; index < sizeof(HART_STARTUP_DATA_NONVOLATILE); ++index) { szHartResp[respBufferSize] = *(pNvMem + index); // the NV memory ++respBufferSize; } // Send back the key from the current setting logic szHartResp[respBufferSize] = currentMsgSent; // last message sent ++respBufferSize; } } /*! * \fn float CalculatePercentRange(float upper, float lower, float value) * \brief Utility to calculate the passed value as a percent of range * * \param upper * \param lower * \param value - the current loop value * \return a float indicating the percent of range * */ float CalculatePercentRange(float upper, float lower, float value) { float percentRange = ((value - lower)/(upper - lower)) * 100.0; return percentRange; } <file_sep>#ifndef COMMON_H_CMD_H_ #define COMMON_H_CMD_H_ void common_cmd_0(void); void common_cmd_1(void); void common_cmd_2(void); void common_cmd_3(void); void common_cmd_6(void); void common_cmd_7(void); void common_cmd_8(void); void common_cmd_9(void); void common_cmd_11(void); void common_cmd_12(void); void common_cmd_13(void); void common_cmd_14(void); void common_cmd_15(void); void common_cmd_16(void); void common_cmd_17(void); void common_cmd_18(void); void common_cmd_19(void); void common_cmd_20(void); void common_cmd_21(void); void common_cmd_22(void); #ifdef IMPLEMENT_RANGE_CMDS_35_36_37 void common_cmd_35(void); void common_cmd_36(void); void common_cmd_37(void); #endif void common_cmd_38(void); void common_cmd_39(void); void common_cmd_40 (void); void common_cmd_42 (void); void common_cmd_43 (void); void common_cmd_45 (void); void common_cmd_46 (void); void common_cmd_48(void); void common_cmd_54 (void); void common_cmd_57 (void); void common_cmd_58 (void); void common_cmd_110 (void); void mfr_cmd_219(void); void mfr_cmd_220(void); void mfr_cmd_221(void); void mfr_cmd_222(void); void common_tx_error(unsigned char); void common_tx_comm_error(void); float CalculatePercentRange(float, float, float); extern unsigned char badTagFlag; #endif /*COMMON_H_CMD_H_*/ <file_sep>/*! * \file utilities_r3.c * \brief This module provides utility functions for the flash memory, and other miscellaneous functions * * Revision History: * Date Rev. Engineer Description * -------- ----- ------------ -------------- * 04/04/11 0 <NAME> Creation * * 04/07/11 0 Patel Add funcations * */ #include <msp430f5528.h> #include "define.h" #include "hardware.h" #include "utilities_r3.h" // Flash programming utilities. Shut off all interrupts and the // watchdog before calling any flash programming function to prevent // undesirable results // For now, only 4 segments (2048 bytes) are allocated for these operations. The // segments are 2-5 (addresses F800 - FBFF) /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: copyMainFlashToMem() // // Description: // // Copies the contents of a segment to main (RAM) memory. The pointer MUST point to a valid // main flash start address, and segSize MUST be an integral multiple of 512. The memory // reserved for the copy must be big enough to take the number of 512 byte segments // being copied. Returns TRUE if everything was OK, FALSE otherwise // // Parameters: // // unsigned char * flashPtr: pointer to the start of flash to be copied. // unsigned char * memPtr: pointer to the start of RAM to be copied to. // int segSize: the number of bytes (in multiples of 512) to be copied // // Return Type: int. // // Implementation notes: // // Checks to make sure the parameters are valid, then copies the contents of the flash // to the RAM memory. // /////////////////////////////////////////////////////////////////////////////////////////// int copyMainFlashToMem (unsigned char * flashPtr, unsigned char * memPtr, int segSize) { int okToCopy = FALSE; int success = FALSE; int iIdx; if ((MAIN_SEGMENT_SIZE > segSize) || ((4 * MAIN_SEGMENT_SIZE) < segSize) || (0 != (segSize % MAIN_SEGMENT_SIZE))) { return success; // just bail now } // Verify we have a valid segment pointer & that segSize doesn't overrun if ((VALID_SEGMENT_1 == flashPtr) && ((4 * MAIN_SEGMENT_SIZE) >= segSize)) { okToCopy = TRUE; } else if ((VALID_SEGMENT_2 == flashPtr) && ((3 * MAIN_SEGMENT_SIZE) >= segSize)) { okToCopy = TRUE; } else if ((VALID_SEGMENT_3 == flashPtr) && ((2 * MAIN_SEGMENT_SIZE) >= segSize)) { okToCopy = TRUE; } else if ((VALID_SEGMENT_4 == flashPtr) && ((1 * MAIN_SEGMENT_SIZE) >= segSize)) { okToCopy = TRUE; } if (TRUE == okToCopy) { stopWatchdog(); //MH OK // If we're here, it's a simple copy operation for (iIdx = 0; iIdx < segSize; ++iIdx) { *(memPtr + iIdx) = *(flashPtr + iIdx); } success = TRUE; startWatchdog(); // MH -> start should match the stopWatchdog() above, deprecated resetWatchdog();; } return success; } /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: copyMemToMainFlash() // // Description: // // Copies memory contents to previously erased flash. It takes a // pointer to the starting location in flash (does not need to be on a segment // boundary), a pointer to the memory to copy from, and the size of the memory // to copy. The flashPtr & memSize parms are checked to verify all the written // locations are in the 2K flash block. Returns TRUE if everything worked OK, // FALSE otherwise. Performs a byte write. // // Parameters: // // unsigned char * flashPtr: pointer to the start of flash to be copied to. // unsigned char * memPtr: pointer to the start of RAM to be copied. // int memSize: the number of bytes to be copied // // Return Type: int. // // Implementation notes: // // memSize does not have to be a multiple of 512 bytes. // NOTE: This function cannot be used to program VALID_SEGMENT_4, which has a special LOCK // bit, LOCKA!! // /////////////////////////////////////////////////////////////////////////////////////////// int copyMemToMainFlash (unsigned char * flashPtr, unsigned char * memPtr, int memSize) { int success = FALSE; int iIdx; unsigned char value = 0x55; // If we're out of bounds, bail early if (((unsigned char *)VALID_SEGMENT_1 > flashPtr) || (flashPtr + memSize) > INFO_MEMORY_END) { return success; } stopWatchdog(); // MH - OK _disable_interrupts(); // If we're here, the request is valid. FCTL3 = FWKEY; // Clear Lock bit // set up to write FCTL1 = FWKEY | WRT; for (iIdx = 0; iIdx < memSize; ++iIdx) { value = *(memPtr + iIdx); *(flashPtr + iIdx) = value; // Wait for the previous write to complete while (!(FCTL3 & WAIT)) { __no_operation(); } #if 0 // Timing - necessary?? for (i = 0; i < 100; ++i) { __no_operation(); } #endif } FCTL1 = FWKEY; // Turn off the WRT bit FCTL3 = FWKEY | LOCK; // Set Lock bit success = TRUE; startWatchdog(); // MH -> start should match the stopWatchdog() above, deprecated resetWatchdog();; _enable_interrupts(); return success; } /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: eraseMainSegment() // // Description: // // Erase individual main flash segments. Takes a pointer to the first segment to // erase and the total size in bytes to erase. The number of bytes to erase // MUST be and integral of the segment size, and the flash to be // erased MUST be in the valid area. All flash contents in the erased area will // be lost. // // Parameters: // // unsigned char * flashPtr: pointer to the start of flash to be erased. // int segSize: the number of bytes (in multiples of 128) to be erased // // Return Type: int. // // Implementation notes: // // Checks to make sure the parameters are valid, then erases the contents of the flash. // NOTE: This function cannot be used to erase VALID_SEGMENT_4, which has a special LOCK // bit, LOCKA!! // /////////////////////////////////////////////////////////////////////////////////////////// int eraseMainSegment(unsigned char * flashPtr, int segSize) { int okToErase = FALSE; int success = FALSE; int numSegsErased; int numSegmentsToErase = segSize / MAIN_SEGMENT_SIZE; if ((MAIN_SEGMENT_SIZE > segSize) || ((3 * MAIN_SEGMENT_SIZE) < segSize) || (0 != (segSize % MAIN_SEGMENT_SIZE))) { return success; // just bail now } // Verify we have a valid segment pointer & that segSize doesn't overrun if ((VALID_SEGMENT_1 == flashPtr) && ((3 * MAIN_SEGMENT_SIZE) >= segSize)) { okToErase = TRUE; } else if ((VALID_SEGMENT_2 == flashPtr) && ((2 * MAIN_SEGMENT_SIZE) >= segSize)) { okToErase = TRUE; } else if ((VALID_SEGMENT_3 == flashPtr) && ((1 * MAIN_SEGMENT_SIZE) >= segSize)) { okToErase = TRUE; } if (TRUE == okToErase) { _disable_interrupts(); // erase all segments stopWatchdog(); //MH OK for (numSegsErased = 0; numSegmentsToErase > numSegsErased; ++numSegsErased, flashPtr+=MAIN_SEGMENT_SIZE) { FCTL3 = FWKEY; // Clear Lock bit FCTL1 = FWKEY | ERASE; // Set Erase bit, don't allow interrupts *flashPtr = 0; // Dummy write to erase Flash seg // Wait until the BUSY bit clears while (FCTL3 & BUSY) { __no_operation(); } success = TRUE; } } FCTL3 = FWKEY | LOCK; // Set the lock bit startWatchdog(); // MH -> start should match the stopWatchdog() above, deprecated resetWatchdog();; _enable_interrupts(); return success; } /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: verifyFlashContents() // // Description: // // Verifies that the Flash and RAM memory contents are identical in the // specified range. Returns TRUE if everything is identical, FALSE otherwise // // Parameters: // // unsigned char * flashPtr: pointer to the start of flash to be checked. // unsigned char * memPtr: pointer to the start of RAM to be checked. // int segSize: the number of bytes to be copied // // Return Type: int. // // Implementation notes: // // The check size does not need to be a multiple of the segnment size. // /////////////////////////////////////////////////////////////////////////////////////////// int verifyFlashContents(unsigned char * flashPtr, unsigned char * memPtr, int memSize) { int ok = TRUE; int numBytesCompared = 0; stopWatchdog(); // MH - OK while ((TRUE == ok) && (numBytesCompared < memSize)) { if (*(flashPtr + numBytesCompared) == *(memPtr + numBytesCompared)) { ++numBytesCompared; } else { ok = FALSE; } } startWatchdog(); // MH -> start should match the stopWatchdog() above, deprecated resetWatchdog();; return ok; } /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: syncToRam() // // Description: // // Copies the contents from FLASH to main (RAM) memory. // // Parameters: // // unsigned char * flashPtr: pointer to the start of flash to be copied. // unsigned char * memPtr: pointer to the start of RAM to be copied to. // int segSize: the number of bytes to be copied // // Return Type: void. // // Implementation notes: // // Checks to make sure the parameters are valid, then copies the contents of the flash // to the RAM memory. // /////////////////////////////////////////////////////////////////////////////////////////// void syncToRam(unsigned char * flashPtr, unsigned char * memPtr, int memSize) { int idx; for (idx = 0; idx < memSize; ++idx) { *(memPtr+idx) = *(flashPtr+idx); } } /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: syncToRam() // // Description: // // Copies the contents from RAM to FLASH memory. // // Parameters: // // unsigned char * flashPtr: pointer to the start of flash to be copied to. // unsigned char * memPtr: pointer to the start of RAM to be copied from. // int segSize: the number of bytes to be copied // // Return Type: int - TRUE if the memory is in sync, FALSE otherwise. // // Implementation notes: // // Checks to make sure the parameters are valid, then copies the contents of the flash // to the FLASH memory. FLASH segments are erased first // /////////////////////////////////////////////////////////////////////////////////////////// #ifdef FORCE_FLASH_WRITE extern WORD testWriteFlash; extern unsigned char updateNvRam; #endif int syncToFlash(unsigned char * flashPtr, unsigned char * memPtr, int memSize) { // First see if there is a need to change by verifying the memory values int success = verifyFlashContents(flashPtr, memPtr, memSize); //// DEBUG == Simulate a Change in NV #ifdef FORCE_FLASH_WRITE if(testWriteFlash > 80) { testWriteFlash =0; updateNvRam = TRUE; success = FALSE; } #endif // If the verify worked, just reurn success now if (success) { return success; } // Calculate the number of segments to erase int numSegsToErase = calcNumSegments(memSize); // erase the flash eraseMainSegment(flashPtr, (numSegsToErase*MAIN_SEGMENT_SIZE)); // copy the RAM back in to FLASH copyMemToMainFlash(flashPtr, memPtr, memSize); // Verify that it worked (or not) success = verifyFlashContents(flashPtr, memPtr, memSize); // Reset the write timer to 0 so it starts counting up //flashWriteTimer = 0; return success; } /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: IntToFloat() // // Description: // // Converts an integer value to the IEEE754 32-bit floating-point equivalent // // Parameters: // // int iValue: the number to be converted. // // Return Type: float. // // Implementation notes: // // // /////////////////////////////////////////////////////////////////////////////////////////// float IntToFloat (int iValue) { union { float fValue; double dValue; } rtnVal; // I need to make sure the precision is not lost here. later rtnVal.dValue = (double)iValue; rtnVal.dValue /= 100.; rtnVal.fValue = (float)rtnVal.dValue; return rtnVal.fValue; } /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: calcNumSegments() // // Description: // // Calculates the number of contiguous FLASH segments to erase based upon data size // // Parameters: // // int memSize: the number of bytes to erase. // // Return Type: int - the number of segments to erase. // // Implementation notes: // // // /////////////////////////////////////////////////////////////////////////////////////////// int calcNumSegments (int memSize) { int numSegs = memSize / MAIN_SEGMENT_SIZE; int remainder = memSize % MAIN_SEGMENT_SIZE; // if there is a remainder, increment the number of segments numSegs += (remainder) ? 1 : 0; return numSegs; } <file_sep>/////////////////////////////////////////////////////////////////////////////////////////// // Copyright (C) AB Tech Solution LLC 2011 All Rights Reserved. // This code may not be copied without the express written consent of // AB Tech Solution LLC. // // // Client: GF // // // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY // KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // /////////////////////////////////////////////////////////////////////////////////////////// // // Header File Name: HartCommand.h // // Description: // // This module provides HART command interface. Functions are implemented in // the file, HartCommand.c // // Revision History: // Date Rev. Engineer Description // -------- ----- ------------ -------------- // 04/02/11 0 <NAME> Creation // // 04/07/11 0 patel Add funcations // /////////////////////////////////////////////////////////////////////////////////////////// #ifndef HARTCOMMAND_H_ #define HARTCOMMAND_H_ // Offsets #define CMD_SOF_OFFSET 0 #define CMD_ADDR_FIELD_OFFSET CMD_SOF_OFFSET #define CMD_LONG_ADDR_OFFSET CMD_ADDR_FIELD_OFFSET+5 #define CMD_SHORT_ADDR_OFFSET CMD_ADDR_FIELD_OFFSET+1 #define CMD_SHORT_CMD_OFFSET CMD_SHORT_ADDR_OFFSET #define CMD_LONG_CMD_OFFSET CMD_LONG_ADDR_OFFSET // Command values #define HART_CMD_0 0 #define HART_CMD_1 1 #define HART_CMD_2 2 #define HART_CMD_3 3 #define HART_CMD_6 6 #define HART_CMD_7 7 #define HART_CMD_8 8 #define HART_CMD_9 9 #define HART_CMD_11 11 #define HART_CMD_12 12 #define HART_CMD_13 13 #define HART_CMD_14 14 #define HART_CMD_15 15 #define HART_CMD_16 16 #define HART_CMD_17 17 #define HART_CMD_18 18 #define HART_CMD_19 19 #define HART_CMD_20 20 #define HART_CMD_21 21 #define HART_CMD_22 22 #define HART_CMD_35 35 #define HART_CMD_36 36 #define HART_CMD_37 37 #define HART_CMD_38 38 #define HART_CMD_39 39 #define HART_CMD_40 40 #define HART_CMD_42 42 #define HART_CMD_43 43 #define HART_CMD_45 45 #define HART_CMD_46 46 #define HART_CMD_48 48 #define HART_CMD_54 54 #define HART_CMD_57 57 #define HART_CMD_58 58 #define HART_CMD_110 110 #define HART_CMD_128 128 #define HART_CMD_129 129 #define HART_CMD_131 131 #define HART_CMD_135 135 #define HART_CMD_139 139 #define HART_CMD_140 140 #define HART_CMD_142 142 #define HART_CMD_143 143 #define HART_CMD_146 146 #define HART_CMD_147 147 #define HART_CMD_150 150 #define HART_CMD_160 160 #define HART_CMD_161 161 #define HART_CMD_162 162 #define HART_CMD_163 163 #define HART_CMD_164 164 #define HART_CMD_165 165 #define HART_CMD_219 219 #define HART_CMD_220 220 #define HART_CMD_221 221 #define HART_CMD_222 222 unsigned char processHartCommand (void); void executeCommand(void); #ifdef USE_MULTIPLE_SENSOR_COMMANDS // Prototypes of individual sensor command handlers void executeFlowCommand(void); void executeConductivityCommand(void); void executeLevelCommand(void); void executeMa4_20Command(void); void executeOrpCommand(void); void executePhCommand(void); void executePressureCommand(void); #endif void executeCmd0(void); void executeCmd11(void); void executeCmd21(void); void executeTxErr(unsigned char); void executeCommErr(void); #endif /*HARTCOMMAND_H_*/ <file_sep>// GF Hart Communication Module - code Rev 3. renew FW developing JOURNALING // 2/5/13 We found that the AC coupling cap C7 for the RTS needed to be increase to 0.1uF to provide enough charge to reliable turn ON the opto couplers. A single positive transaciton is needed to set the T-flip flop (Q =RTS = High) A init pulse is given as soon as micro jumps to main and another after setting the clock. // // 2/4/13 The RTS control signal is initialized with 500uS width pulses and High Drive Strenght at control pin // // 1/24/13 1) hostActive bit stays set when Hart master is connected (it toggled in previous version). It is cleared after HART_MASTER_DISCONNECTED_MS ms of removing the hart master - for now is 16 (2 Secs) 2) The reminder UPDATE_REMINDER_COUNT was changed from 20 to 8000 ( 8000 *0.15 sec = 20 min) and is reset every CMD 45/46 (adjust min current and gain) // 1/18/13 Added a test case comming from ULA038a. In this case we don't have a Hart Master sending cyclical messages. A timer of 1.5 secs (HART_CONFIG_CHANGE_SYNC_TICKS) forces the synchronization with flash // 1/17/13 Corrected Following Hart Comands: -Command 3. It sends the Dynamic Variables available ONLY (previous version interpreted different this command) -Command 8. Sends the correct Variable Classification for PV and SV. TV and QV remains same as previous SV classsification is obtained as follows: - If SV units = NOT_USED (250) thats the Classification we send - If PV Classification is not LEVEL, then we send TEMP as the SV class - If PV Class is level and then SV class is obtained from SV units - Kg or Lb SV Class is Volume per Mass - All other SV class is Volume per Volume Command 9 - functional the same, but removed all unnecesary comments // 1/15/13 Hart received character wit Uart Error (FE, PE, OE and BREAK) goes to the RxFifo. An evHartRxChar event is generated and the Receiver State machine decides what to do in the Hart Frame building. No noticeables side effects // 12/27/12 Previous version with No low Power endured all night. From 4:34PM to 10:34AM, 18hrs Examination found a race condition when testing for going to sleep - the evHsbRecComplete happens while the testing (calling a function IS_SYSTEM_EVENT for ery event) says no event, we go to sleep while the evHsbRecComplete happened. uC doesn't call the loop and goes to sleep. At the start of $I reception, it wakes-up and resumes the pending transmission. FIX: Condition for going to sleep must be atomic. Improvement. HSB activity has high traffic, we wake up and not going to sleep during the start of hsb listen slot. When Hsb Attention timer expires, I do a cleanup of RX- this: a)avoids a extra interrupt, b) clear status from previous // 12/27/12 It fails at same point Let's run it overnight without low power undef LOW_POWERMODE_ENABLED // 12/27/12 ** The extra char received after Hart finished transmission, is due the RTS-Modem interaction. It happens that the RX line stays an extra 3.2 mS after RTS has gone high. This is seen by uC as a RX char, sometimes with error - FIX: After the TX ends, in the ISR is perfomed a clean-up which basically sets the UCSWRST bit, leaving the UART as POR. ** HSB recovery The Error handler is done after the Hart has finished. Also we limit of 5 retries the attempts to reset port (Astro-Med storage) ** Flashing is being forced to every 10 secs Tests indicates that HSB losses communication (even with flash). Hooked all monitor and waiting to have an incident on 12/27/2012 @2:39PM // 12/26/12 1) Plan to Divide-and-conquer: found that it Fails even when flash is disabled start: 8AM failed: 8:36AM 2) Using Astro-Med I founds events in main loop: 2.1) event evHartRxChar -> this calls hartReceiver() and since was 'prepared' in the last rx loop, it init the Rcv State Machine 2.2) event evHartRcvReplyTimer -> creates the delay?? 2.3) but, why I receive an evHartRxChar event? There is a xtra character after LRC that generates a Hart RXChar event. Did the following to correct: a) evHsbRecComplete event has higher priority than evHartRxChar (and any other event) b) REPLY timer - Starts when hartReceiver is in LRC internal state (same as before) - It is not kicked (this is not a watchdog type) - It stops by itself at ISR when registering the evHartRcvReplyTimer,i.e. generates only ONE event per frame c) GAP timer - Starts when hartReceiver has receiver Preambles + STX (same as before) - kicked under ISR at every Hart recvd char - Stops when hartReceiver is in LRC internal state (same as before), but also - Sets a flag that doesn't allow the timer ISR to register an event and - event has been sent to loop, the flag skips the Gap error action // 12/21/12 GOALS for Today: - Timer for HSB counter starts when $H is detected at RxInterrupt - CCR1 is preset at 100mS -> This is the Flag that ends the Flash write slot time - (?) These are possible delays CCR1 Resets and Enables RXIE Start CCR2 1) First // 12/19/12 This version has the proper event priority // 12/20/12 This Commit version has evHsbRecComplete with lower priorty - HSB recovery reads UCA0RXBUF diables/enables RXIE in hope to recover port - TP3 has a toggle to see loop scan but i could not observe a fault // 12/20/12 - HSB recovers UART errors at ISR and has a supervisory to just start RXIE and get in sync - Only one timer for HSB - 140mS - HSB flashwrite slot is between TX ends and the hsbAttentionTimer (all under interrupts) - Test over night with FlashEnable (normal) - Optimization disabled - Low Power // 12/19/12 === GENERAL Start with the following HART Doesn't stop HSB HSB Doesn't stop HART Change the way HSB is received - - Reception made on ISR - Single timer (drop active-idle slots, too slow) - TXIE is always enabled - RXIE is always ON at start, once HSB syncs it is OFF at TX ends and enabled at hsbAttentionTimer timeout 1) HSB RECEIVER moved to ISR All chars are received under interrupt, no RxFifo 1.1 AT beginning RXIE is always ON 1.2 Detect a $H - Start hsbAttentionTimer and capture following Rx bytes 1.3 If Uart error (FE, PE, OE) just signals cancel this frame and RXIE=0 1.4 Capture until CR (or abort if exceed) - When CR detected, RXIE=0, SET_EVENT(evHsbRecComplete) NOTE: Latency to start response is 800uS --> Need to take care of UART UCOE error as Rx chars may arrive when flashing blocking 2) Main loop catches evHsbRecComplete 2.1 Process Command, which basicaly send-to-completion sz9900CmdBuffer[], Index is volatile WORD i9900CmdBuf // Command Buffer Index 3) HSB TRANSMIT ISR 3.1 Chain the next char in the response buffer sz9900CmdBuffer[] (uses TxFifo) 3.2 At completion it signals the flashWriteAllowedHsb to flash if required 4) hsbAttentionTimer ISR - Enables the RXIE = 1 5) Supervisory Recovery, - Purge andy pending TX and RX RXIE =1 All variables should be "volatile" // 12/18/12 Tested that HSB can't complete when flashing (FORCE_FLASH_WRITE. Still do not know if 475 commands to flash but will run overnight to see - Flag to to flash was changed to flashWriteAllowed. This flasg is set after HSB has completed, and in turn it will take another main loop cycle to write to flash, but all house cleaning is done before flashing. Tested to write to flash, after more testing try to save TAGS. - Watchdog clock assigned different in flash routines - Removed all previous functions and modified: start, stop and kick the Dog. // 12/17/12 Lost communication while flashing (need to know if 475 sends this command) THe variable flashWriteAllowed should be volatile // 12/17/12 - Add flag to reject gap error when reply timer already started - Add volatile modifier to sEvents[] and now compiler allows Optimization - Validate hsb buffer txmitt before sending responseSize <= MAX_9900_RESP_SIZE - Optimization level set to 2, speed (5) 12/15/12 Errors, 1) Hart Gap timer eventually gets trigger, even an answer is sent to Hart the event may indicate a conflict 2) HSB catchs an error code 3, it recovers but data is sent after $I. 3) After a long time, my guess is about 24 hrs, Hart stops working. Hart becomes irresponsive at that point ==>It is not caused by the 24hrs timestamp 12/11/12 Added a supervisory function to HSB - restarts serial port Found that after few hours of operation HSB is not communicating. There was no recovery - provided a reinitialization of serial port 12/11/12 Documenting Code - Several changes but *.HEX file has no change to 12/10/12 (test) 12/10/12 We go for LPM0 instead LPM1 in order to have FLL always stabilizing DCO Note that Icc is higher as FLLs wasn't working in previous SW (390uA), Measured Icc was in the range of 700uA (??) but I think we have a damaged board Rev. F 12/7/12 Previous commit (LPM1) was tested overnigth - Ran good For this commit Flash data in the proper slot - Prepare for a weekend test: 8 channels, two for signals: HSB and HART Some test points to detect faults - Power UP Reset - Hart Gap timer Idea is to have trigger point to catch errors in recorder 6) Testing LOW POWER MODE ACLK and SMCLK are monitored at Pins #define MONITOR_ACLK_SMCLK FLL always ON - No ON/OFF control LPM1 430uA ===> This is what will be installed on Production version LPM3 389uA FLL always OFF - No ON/OFF control LPM1 400uA LPM3 490uA (makes no sense, it may not be entering LPM3) No monitoring pins FLL always ON == Suggested by <NAME>. LPM1 370uA LPM3 370uA FLL always OFF LPM1 329uA LPM3 367uA (may not be entering) ===> Set testing Overnight in LPM1 FLL always ON 12/6/12 Completed following tasks for TESTING - Commits as necessary 1) dataTimeStamp reflects mS in one day (same as original code) 2) Flash writting stress protection FLASH_WRITE_MS 4000 logic 3) Return HSB Start HSB after Hart (ON sequence) Stop Hart if HSB stops (OFF sequence) Use TP11-> Gnd w 2K resistor, Note that this logic works only at powerup 4) WD clk source= ACLK, Timer Interval selected by WD_TIME_INTERVAL define (1 sec should be production) 5) Command 42 is not-supported but when received it completes a proper reply === In progress - Remove any debug left overs (TestPts, Clear oscillator fault in main) 6) Test Low Power 7) Logic for Flashing and testing - Evaluate Impact of Sillicon revs. E and rev F - Observe WD value @pre_init.c WDCTL = 0x6904 (this is the POR default) @main WDCTL = 0x6980 (this is the POR default) resetWatchdog() function in toggleRTSline kicks the WD only, need to HOLD or refresh WD afterward - Push to upstream - Move WDTIS_4 (1 sec) - Return FLL control loop startegy: FLL starts ON to get closer to calibrated Freq. Control ON/OFF during Idle/Active Slots - Verify that project has following settings: --silicon_version msp uses msp430 cpu --abi eabi uses eabi for aplication binary interface --code_model small 16b function pointers and 64K low memory --data_model small 16b data pointers and 64K low memory --stack_size 380 C compiler Optimizations OFF pre_init.c: WDTCTL = WDTPW + WDTHOLD; // Stop WDT Note: run-time stack over a pattern shows an unsage x43FE-x436A = x94 (224) bytes with HSB and HART Allocation is 380 (0x17C) bytes FFFE- 17C = 0x4282 (bottom) POR: 0x43FE main() 0x43BA endles loop:0x43BA -> Isr (random) 0x43A6 = Stack takes x14 (20) bytes to take Hart isr 12/5/12 - Solved Watchdog long reset (34min) - Watchdog wasn't disabled, trip time = 2^31/1,048,576 = 34min - WD tested setting for now is: WDTSSEL_1(ACLK), WDTIS_3 (16 sec), kicked every loop scan 12/4/12 -- Fixed confusing variable declarations on headers These global variables in merge.h were declared duplicated ==>> extern unsigned int flashWriteCount; BEWARE, it was long in Vijai ==>> extern long dataTimeStamp; 000029a2 dataTimeStamp MAP File addresses 000029a0 flashWriteCount <==== 000029a4 dataTimeStamp <==== 11/29/12 ==== REALLY HARD - disable LOW POWER MODE (to be able to use emulator) - Test trap (hart reply timer) - Run it for fe minutes It Fails to respond to Communiactor after 40mins ===> Run test Overnight with no HSB TEST_ALL_NIGHT ** Preparing code for testing ** -> Return from LPM3 to LPM1 -> Organize States to start/stop Hart and Hsb -> added pre_init as initialization got too high -> Trap all unused vectors 11/28/12 - Hart Alone works in Low Power Mode 1 and 3 (to return code to full see sections where HSB is removed as HART_ALONE_LPM) Code works - Solved BUG: From time to time, the GAP timer expires, canceling current transaction - kickRecTimer() was moved to Hart Rx ISR, it means that main loop may have some latency. - Ocasionally I got a Reply error, but no Hart RX chars in the 200mS boundary, isolated Char make it fail alone === KEEP observing ==> It means that the Gap timer can be used to restart the RX state machine, How to do it without causing a Fault???? Other bugs, Notice that there were unread chars in FIFO (hard to say, as Debugger intrudes with program), but handled same as Hsb: read while fifo non-empty Other: Added vectors for the unused non-maskable ISRs: SYSNMI_VECTOR (Vacant Memory Access, JTAG Mailbox), UNMI_VECTOR (Oscillator Fault, Flash Memory Access Violation) ******** - Hart and Hsb working together - No Low Power Mode yet - Removed old-style timers from code: incrementMainMsgTimer(), startMainMsgTimer(), stopMainMsgTimer(), init9900Timers() - Removed Hsb serial port control enableMainRcvIntr(), enableMainTxIntr(), 11/26/12 - A define TEST_LOW_POWERMODE to enable LowPower. - Hart fails at about 1:20 min:sec - FLL is ON only at Powerup - when CPU rev > "E" will enable always - Sections to save are out 11/15/12 Low Power Mode revisited 11/14/12 Save Flash after HART transaction & HSB idle Organize the System events. * When HART communication is stopped, databaseOk, updateMsgRcv and hartCommStarted are set to FALSE. * When 9900 polls, it will geta bad database status in reply. Db is built and this sets databaseOk TRUE. * Next update command from 9900 will: * The very first will set current mode and the comm9900Started to TRUE * If reestablish a HART stop condition, will require 20 updates to perform this operation it will get The flag is set to FALSE when to indicate that Hart has been stopped, // every system tick is polled to reestablished when Database is Ok again 11/13-12 Clean Code: - Those that didn't compiled because lack of scope on variables - Provide equivalent function incrementMainMsgTimer(void) == 10 sec time-out - Seems that CalculateDatabaseChecksum() is not used Functions to analyze: - Please note that hart_comm_started is also hart_comm_started - updateMsgRcvd = TRUE when an update message has been received from the 9900 and HART communications can begin - stopHartComm() function coded direclty on 11/12/12 - Hsb slot timer added with the following functions: start(preset), stop - Removed a BUG in putcUart(), this conflicted the hLoopBack.enable() function - Hart replies to 9900 Only missing so far is the first update command == I will do a commit as I think is wise to avoid so many edits w/o testings Next: -Parse the 9900 command and answer it -Enable RX and once in-sync, disable it during the Idle slot. // 11/9/12 Created a Branch - Where Hart and Hsb worked independenlty Create a TAG in history hsb_fetching Rename legacy project files to _r3 in order to track changes Edit: Move Variables to better scope main9900_r3.* // 11/6/12 Corrected generic inline functions: isRxEmpty, isRxFull, isTxEmpty, isTxFull in driverUart.h Tested with 79 chars (simulating) max Hsb packet (67) Need to workout more on Uart error handling, so far only the flags are set with no action taken // 11/5/12 Testing Hsb Port using single char in/out // 11/1/12 - 11/4/12 We will test LPM0 later - Move to HSB as schedule needs full functionallity first -Tested Hart messages that request saving data to Flash: Flash write 40mS, Transaction rate 500 , command_2 = 44*11/1200 +14 = 417. SIlent window = 80mS, margin 50% Commands that generate a write request: 6 Save Polling Address, 17 Write MSG, 18 Write tag, descriptor & date, 19 Write final assembly number, 22 Write Long Tag, 219 Write device ID // 10/31/12 Working in saving NV data to flash == Need to estimate last transaction time -if less than XX then save to flash // 10/30/12 - Analizing Hart command by functions: 0,11,21 = Idenitity - isAddressValid() moved to protocols.h, reduces scope of defines - rtsRcv() not needed (we don't send partial messages in run to completion) - Later write 18,19, Reset 42 Linker basic options -> ${ProjDirPath}/Debug/GFHartR3.map to aid in Linux/Windows context switch // 10/29/12 Corrected SendFrame Error // 10/23/12 DEBUG - Most of the time can't reply to cmd0 - Increase RX buffer to 8-> 16 == no help - Reply and Gap timers doubled == they are responding but make it longer no help Added hartcommandr3.x, common_h_cmd.* TEMP increase stack from 240 to 300 -- Still not working as I need to anlize how hartTransmitter() is initialized // 10/22/12 -Receiver State machine design complete -Need the processHartCommand() function defined in HartCommand.x // 10/18/12 - The original receiver works with Rx/Driver!! 1) Merging files from the original (trimmed) project 2) added files will have a "r3" suffix in its name: hartr3, utilitiesr3, main9900r3 3) create a contention fileset merge.x to incremental add files 4) Project Run-Time model options setting changed: --silicon_version msp uses msp430 cpu --abi eabi uses eabi for aplication binary interface --code_model small 16b function pointers and 64K low memory --data_model small 16b data pointers and 64K low memory GOAL is to =>> Validate a RX 475 communicator frame, RX a command and TX a response - copy files from \git\HartGitHub\HartFw3 project (win - cloned from GitHub) - marco/git/Hart/HartFw3 (linux) Compiler requires processHartCommand() need to add files - Rx Fifo stores received byte with status - Using events to enter main loop - define a version of hartReceiverSm() - Increase stack 200->240 emulator losses some calls to onlines - Cleanup protocols.x and call hartReceiverSm() from main. Establish interface - Basic Clock System prepared for LPM0 ACLK = XT1CLK = 32.768Khz external crystal MCLK = SMCLK = DCOCLKDIV= 1,058,576 - Testing Commit/pull from two machines - Testing the fifo/app using of Tx and Rx - Working in the driverUart - APP/ISR and define members/events to xmit a complete message - Debugginfg TxIsr and RxIsr System Timer is Disabled for Now Emulation won't work well - CHanged inlines - Not solved Set stack 160->200 - It worked => CCS doen't check stack. Need to estimate and test === Test with small Modem Board This - Tx and Rx interrupts always enabled - Add LoopBack enable() disable() isEnabled() handlers - Loopback is enabled before txsbuf is loaded (this makes Rx listen to all Txmited bytes) - bHalfDuplex -> bHwFlowControl changed names - TODO: Create a HW/SW timer EVENTS: ISR Receiver eHartRx eHartRxError Timer eRxGapError eHartReply ISR Transmitter opeSendResponse eResponseSent HartReceiverSm commands build, NewChar ==> reset ==> start over continue results validFrame ==> A valid message with my address, internal state to xtra data done ==> a valid message and at least one extra char received (1) error ==> Error found (1) busy ==> A receiver is in progress with no errors so far idle ==> Waitting for a valid preamble (1) Internal state changes to Idle state <file_sep>#ifndef HARDWARE_H_ #define HARDWARE_H_ /*! * \file hardware.h * \brief Provides the hardware interface for GF Hart implementation * * Software switches "define" are declared here. * * Created on: Sep 28, 2012 * \author: MH */ /************************************************************************* * $INCLUDES *************************************************************************/ #include "msp_port.h" /************************************************************************* * $DEFINES *************************************************************************/ // // Software Configuration Switch defines // Analying side effects 11/13/12 // // Always included code for (original project define) QUICK_START /*! * Compare current consumption on low power modes vs. active mode * * Used to compare current consumption in low power vs. active mode.\n * While developing SW sometimes is necessary to work always in Active mode as some silicon revisions * has emulator Errata. Production code should have this define */ #define LOW_POWERMODE_ENABLED /*! * Define how deep the microcontroller will sleep in low power * * Define the sleep depth: LPM0_bits to LPM3_bits.\n * Production code is LMP0 - MH 12/11/12 */ #define LPM_BITS LPM0_bits /*! * Silicon Rev. E has UCS10 errata * * We remove the impact of UCS10 by using ACLK to generate Hart Baud rate\r * Select ONE of the available clock sources for Hart UART: * - HART_UART_USES_ACLK * - HART_UART_USES_SMCLK * Production code uses ACLK * */ #define HART_UART_USES_ACLK //#define HART_UART_USES_SMCLK /* * WatchDog Time Interval * * WD uses ACLK (32K) and Time interval possible values are * WDTIS_3 16 Sec * WDTIS_4 1 Sec * WDTIS_5 0.25 Sec * WDTIS_6 0.0156 Sec * Production Code Time interval is WDTIS_4 = 1 Sec */ #define WD_TIME_INTERVAL WDTIS_4 /*! * Enable ACLK and SMCLK monitoring in pins * * During testing Clock jumps (silicon rev. E) we need to observe ACLK and SMCL; * may be removed from production code to save some power */ #define MONITOR_ACLK // #define MONITOR_SMCLK // // DISABLE_FLASH_WRTING // This define won't allow writing to Flash as writing to flash requires 40mS. // During some testing CPU availability sometimes I need to evaulate best time // to write. This define is only for debug //#define DISABLE_INTERNAL_FLASH_WRITE // // Trap all unused interrupts // undefine for production code #define TRAP_INTERRUPTS // Timers clock source are ACLK/8 = 32768/8 = 4096hz // Reload value is (mS -1)*4.096 // 8, 508, 8188 40956u Tick aprox 2mS, 125mS, 2 Sec, 10Sec #define SYSTEM_TICK_TPRESET 508 #define SYSTEM_TICK_MS 125 #define NUMBER_OF_MS_IN_24_HOURS 86400000 // Minimum time to wait between Flash writes (other conditions apply) // Time is in mS 0 to 65000 #define FLASH_WRITE_MS 2000 /* Change from 4000 to 2000 since less chance to catch a write */ /*! * Hart slave timers * * They behave like watchdog and are kicked everytime a char is received * - Inter-character GAP time for 2 chars @1200bps = 11* 2 * 4096 /1200 = 75 * - Slave reply time for 1.5 chars @1200bps = 11* 1.5 * 4096 /1200 = 57 * - Time out is measured from RX STOP bit + 1 Baud time + Timer preset * * Gap timer * - Start: when command message start delimiter is received * - Stop: at LRC command reception reaches (we don't care when extra char ends) * after receiving a Gap Time out notification, just after calling initHartRx extrnal prep * - Event Taken when hartFrameRcvd is false, i.e. avoid if there is a valid message to reply to * the event should notify the error and initHartRx state machine * * Reply Timer * - Start when receiver reaches LRC (we are going to reply to all complete messages, some may not be to us) * - Stop When the Reply event is taken * - Event hartFrameRcvd should be true */ #define GAP_TIMER_PRESET 82 /* 2 chars + 10% = 2.2* 9.1666 ~ 20mS or 82 counts THIS IS PRODUCTION SETTING */ // Follows test and comments //#define GAP_TIMER_PRESET 75 /* 18mS ~ 75 tested w 50mS~201 and hyperterminal */ (== ORIGINAL VALUE) //#define GAP_TIMER_PRESET 56 /* 13.5mS (1.5 chars) accelerate fault probability */ (PROBLM found, kickHartRecTimer to ISR) //#define GAP_TIMER_PRESET 38 /* 38~10 mS (1.1 chars) test functionality, (FUNCTIONALITY TESTED) with 39 (9.5) takes a long time to fail*/ #define REPLY_TIMER_PRESET 53 /* 14mS ~ 53, tested w 100mS~406 and hyperterminal */ /*! * High Speed Bus timer * This timer measures the start of a Hsb message $H and times out to receive next command * -Start when hsb receives $H * -At Time Out it stops the counter (MC=0) and Enables HSB Rx interrupt */ #define HSB_ATTENTION_CCR_PRESET 573 /* Set to 140mS Theoretically should be 150 - 2*0.512= 149mS*/ /*! * Flash Write slot- * Strategy is to not drop any Hart message. Hart will trigger a Flash write at the end of TX bit, * when RTS goes high. * Second condition is if HSB is in the IDLE slot. We are going to reduce the IDLE_SLOT, ideally by 40mS * which is the time to write flash. 150-40 = 110mS. With a 20% safety margin, IDLE is 88 mS * * */// 12/7/12 Flash WRITE // To obtain the //#define HSB_IDLE_SLOT 545 /* Theoretically should be 150mS less a safety margin give 133mSto be @middle */ //#define HSB_IDLE_SLOT 361 /* 88 mS, test if we drop a HSB message, WE are listening to last "part" of $R section */ //#define HSB_IDLE_SLOT 409 /* 100 mS, test if we drop a HSB message - SAVE is taken, listening 20 mS of $R section */ //#define HSB_IDLE_SLOT 450 /* 110 mS, test if we drop a HSB message - SAVE is taken, listening 7.6 mS of $R section */ #define HSB_IDLE_SLOT 492 /* 120mS - SAVE has higher probability to be taken sooner, May drop HSB message if syncFlash requires flashing */ /* * HSB_SEQUENCER * This define generates a delay to start Hart first and then HSB * */ //#define HSB_SEQUENCER /*! * Hart is started first and Hsb starts after following delay * ticks are x125mS */ #ifdef HSB_SEQUENCER #define HART_HSB_SEQUENCE_DELAY 12 /* 12 x 0.125 = 1.5 Sec */ #endif /*! * Hart is stopped if we are not able to communicate with 9900 * This is the way original code handled: * Timeout preset to Drop Hart comm when 9900 is not communicating (in 125ms ticks) */ #define MAX_9900_TIMEOUT 40 /* 40 x 125mS ticks = 5 secs */ /*! * Supervisory HSB watchdog * * If HSB doesn't receive messages, due a lost of sync, excessive errors, etc * It may result in a disabled receiver. This timer intends to re-init the serial * port RX interrupt after no sensing HSB acitvity * Ticks are in x125 mS ticks */ #define HSB_NO_ACTIVITY_TIMEOUT 9 /* Reinit HSB serial port after 9*0.125 = 1.125 SECS */ /*! * FORCE_FLASH_WRITE * This define simulates a change in NV memory such that flashing happens often * Used to debug flash writes as it introduces a 40mS delay */ // #define FORCE_FLASH_WRITE /* will let it run for weekend */ /*! * DEBUG_SIGN_MAINLOOP_TOGGLE * The main loop is toggled every time is take to measure its scan time. * This define signs the scan duration by toggling "event number" times TPx at the end of loop scan * Note: if event (shouldn't happen) is "evNull", evLastEvent toggles are used */ #define DEBUG_SIGN_MAINLOOP_TOGGLE //HICCUP #define NO_CURRENT_MESSAGE_SENT 0xF0 #define FIXED_CURRENT_MESSAGE_SENT 0xF1 #define LOOP_CURRENT_MESSAGE_SENT 0xF2 // Promote to Global as it is seen by driverUart 12/26/12 #define HART_PREAMBLE 0xFF /************************************************************************* * $GLOBAL PROTOTYPES *************************************************************************/ void INIT_set_Vcore(unsigned char); void INIT_SVS_supervisor(void); void initHardware(void); //!< Initialize Peripherals for the Hart Application //void stop_oscillator(); //!< Stops the CPU clock and go to sleep mode /************************************************************************* * $GLOBAL VARIABLES *************************************************************************/ extern volatile WORD SistemTick125mS; //HICCUP extern unsigned char currentMsgSent; /*! * bHartRecvFrameCompleted * This global indicates that a complete (until LRC) Hart frame has been received in the hartReceiver (main loop) * which runs outside the interrupt receiver. The flag is used to block a evHartRcvGapTimeout events */ extern volatile BOOLEAN bHartRecvFrameCompleted; /************************************************************************* * $INLINE FUNCTIONS *************************************************************************/ #if 0 //MH These function have given me so many troubles - just discard and rewrite proper ones startWatchdog(), stopWatchdog(), resetWatchdog() #endif /*! * kickWatchdog() * Reset WD internal counter */ inline void kickWatchdog(void) { WDTCTL = WDTPW | WDTCNTCL; } /*! * startWatchdog() * Assigns a predefined value to the WDTCTL: set to watchdog POR, clock source is ACLK * Time interval WD_TIME_INTERVAL is defined for porduction to WDTIS_4 (1 Sec @32KHz) */ inline void startWatchdog(void) { WDTCTL = WDTPW | WDTSSEL_1 | WDTCNTCL | WD_TIME_INTERVAL; // WD clk is ACLK and trips at 32K (1 secs) } /*! * stopWatchdog() * Stops the WD counter, this should be matched by a startWatchdog() on its context * We use the same clk source in order not to request a CLOCK change (and alter LPMx) */ inline void stopWatchdog(void) { WDTCTL = WDTPW | WDTHOLD | WDTSSEL_1 | WD_TIME_INTERVAL; // Sets the HOLD bit, WD is not operative } /*! * kickHartGapTimer() * Reset timer count register to zero * */ inline void kickHartGapTimer(void) //!< Kick the Hart DLL dog { HART_RCV_GAP_TIMER_CTL |= TACLR; // Count=0 } /*! * startGapTimerEvent() * Start Counting Up and generate an interrupt if reaches preset * */ inline void startGapTimerEvent(void) //!< Kick the Hart DLL dog { HART_RCV_GAP_TIMER_CTL |= MC_1; // Up mode } /*! * startReplyTimerEvent() * Start Counting Up and generate an interrupt if reaches preset * */ inline void startReplyTimerEvent(void) //!< Kick the Hart DLL dog { HART_RCV_REPLY_TIMER_CTL |= MC_1 ; // Up mode } /*! * startHsbAttentionTimer() * Start Counting Up to the initialized preset and generate an interrupt when done * \return As a side effect, it will generate and interrupt TIMER0_A0_VECTOR * */ inline void startHsbAttentionTimer() { HSB_ATTENTION_TIMER_CTL |= MC_1; // Count in Up mode } /*! * stopHsbAttentionTimer() * Stop the Timer from counting * */ inline void stopHsbAttentionTimer() //(typo error corrected) { HSB_ATTENTION_TIMER_CTL &= ~MC_3; // This makes MC_0 = stop counting } #endif /* HARDWARE_H_ */ <file_sep>/*! * \file errorHandler.c * \brief Trap unused interrupts * Created on: Nov 29, 2012 * \author: MH */ #include "hardware.h" #include <msp430f5528.h> // List of unused vectors // 63 is System Reset = Not trapped = /*! * System NMI 62 */ #pragma vector=SYSNMI_VECTOR __interrupt void _hart_SYSNMI_VECTOR(void) { #ifdef TRAP_INTERRUPTS while(1); #endif // A reti; is generated by compiler } /*! * User NMI 61 */ #pragma vector=UNMI_VECTOR __interrupt void _hart_UNMI_VECTOR(void) { #ifdef TRAP_INTERRUPTS while(1); #endif // A reti; is generated by compiler } /*! * Comp_B 60 */ #pragma vector=COMP_B_VECTOR __interrupt void _hart_COMP_B_VECTOR(void) { #ifdef TRAP_INTERRUPTS while(1); #endif // A reti; is generated by compiler } /*! * TB0 TB0CCR1 to TB0CCR6,TB0IFG 58 */ #pragma vector=TIMER0_B1_VECTOR __interrupt void _hart_TIMER0_B1_VECTOR(void) { #ifdef TRAP_INTERRUPTS while(1); #endif // A reti; is generated by compiler } /*! * Watchdog Timer_A Interval mode 57 */ #pragma vector=WDT_VECTOR __interrupt void _hart_WDT_VECTOR(void) { #ifdef TRAP_INTERRUPTS while(1); #endif // A reti; is generated by compiler } /*! * USCI_B0 Rec/Tra 55 */ #pragma vector=USCI_B0_VECTOR __interrupt void _hart_USCI_B0_VECTOR(void) { #ifdef TRAP_INTERRUPTS while(1); #endif // A reti; is generated by compiler } /*! * ADC12_A 54 */ #pragma vector=ADC12_VECTOR __interrupt void _hart_ADC12_VECTOR(void) { #ifdef TRAP_INTERRUPTS while(1); #endif // A reti; is generated by compiler } /*! * TA0 TA0CCR1 to TA0CCR4, TA0IFG 52 */ #pragma vector=TIMER0_A1_VECTOR __interrupt void _hart_TIMER0_A1_VECTOR(void) { #ifdef TRAP_INTERRUPTS while(1); #endif // A reti; is generated by compiler } /*! * USB_UBM USB interrupts 51 */ #pragma vector=USB_UBM_VECTOR __interrupt void _hart_USB_UBM_VECTOR(void) { #ifdef TRAP_INTERRUPTS while(1); #endif // A reti; is generated by compiler } /*! * DMA 50 */ #pragma vector=DMA_VECTOR __interrupt void _hart_DMA_VECTOR(void) { #ifdef TRAP_INTERRUPTS while(1); #endif // A reti; is generated by compiler } /*! * TA1 TA1CCR1 to TA1CCR2, TA1IFG (TA1IV)(1) (3) */ #pragma vector=TIMER1_A1_VECTOR __interrupt void _hart_TIMER1_A1_VECTOR(void) { #ifdef TRAP_INTERRUPTS while(1); #endif // A reti; is generated by compiler } /*! * I/O Port P1 47 */ #pragma vector=PORT1_VECTOR __interrupt void _hart_PORT1_VECTOR(void) { #ifdef TRAP_INTERRUPTS while(1); #endif // A reti; is generated by compiler } /*! * USCI_B1 45 */ #pragma vector=USCI_B1_VECTOR __interrupt void _hart_USCI_B1_VECTOR(void) { #ifdef TRAP_INTERRUPTS while(1); #endif // A reti; is generated by compiler } #if 0 // Timer A2 interrupt service routine for CC0, TA2CCR0 (44) // Hart slave response time #pragma vector=TIMER2_A0_VECTOR __interrupt void slaveReplyTimerISR(void) { #ifdef TRAP_INTERRUPTS while(1); #endif // A reti; is generated by compiler } #endif /*! * TA2 TA2CCR1 to TA2CCR2,TA2IFG 43 */ #pragma vector=TIMER2_A1_VECTOR __interrupt void _hart_TIMER2_A1_VECTOR(void) { #ifdef TRAP_INTERRUPTS while(1); #endif // A reti; is generated by compiler } <file_sep>/*! * \file hartcommand_r3.c * \brief This module provides the HART command interface * * Revision History: * Date Rev. Engineer Description * -------- ----- ------------ -------------- * 04/02/11 0 <NAME> Creation * * 04/07/11 0 patel Add funcations * */ #include <msp430f5528.h> #include "define.h" #include "hardware.h" #include "protocols.h" #include "hart_r3.h" #include "common_h_cmd_r3.h" #include "hartcommand_r3.h" // Did we get a broadcast address? int rcvBroadcastAddr = FALSE; extern HART_STARTUP_DATA_VOLATILE startUpDataLocalV; /*! * \function processHartCommand() * \brief Process the HART command, generate the response. * * Isr and Drivers store Hart command message in a global buffer szHartCommadn[]. This function * process the command (by creating a response) or prepares a error response * */ unsigned char processHartCommand (void) { unsigned char rtnVal = FALSE; // Make sure the CD interrupt is off so no new messages can be received numMsgProcessed++; if (hartFrameRcvd) { // Verify that the number of data bytes received is <= expected byte count if (expectedByteCnt > hartDataCount) { return rtnVal; } // Only proceed if the address is valid if (addressValid) { // If there is a short frame and the command is NOT 0, return if (!longAddressFlag &&(HART_CMD_0 != hartCommand)) { return rtnVal; } if (rcvLrcError || parityErr || overrunErr) { executeCommErr (); rtnVal = TRUE; } else { // Make sure I have a short address before processing cmd 0 if (!longAddressFlag) { if (HART_CMD_0 == hartCommand) { executeCmd0(); rtnVal = TRUE; } } else { if (rcvBroadcastAddr) { if (HART_CMD_11 == hartCommand) { executeCmd11(); rtnVal = (badTagFlag) ? FALSE : TRUE; badTagFlag = FALSE; } else if (HART_CMD_21 == hartCommand) { executeCmd21(); rtnVal = (badTagFlag) ? FALSE : TRUE; badTagFlag = FALSE; } else { executeTxErr(CMD_NOT_IMPLEMENTED); rtnVal = TRUE; } } else { executeCommand(); rtnVal = (badTagFlag) ? FALSE : TRUE; badTagFlag = FALSE; } } } } else { numMsgUnableToProcess++; } } else { numMsgUnableToProcess++; } return rtnVal; } /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: executeCommand() // // Description: // // Execute the HART command, generate the response. The function first checks to // see if the command goes to a common handler, or a sensor-specific one. // // Parameters: void // // Return Type: void // // Implementation notes: // This function steers the command to the correct handler based upon the // sensor type // /////////////////////////////////////////////////////////////////////////////////////////// void executeCommand(void) { // First, check to see if the command is a common command. If not, // then select the specific sensor handler switch(hartCommand) { case HART_CMD_0: common_cmd_0(); break; case HART_CMD_1: common_cmd_1(); break; case HART_CMD_2: common_cmd_2(); break; case HART_CMD_3: common_cmd_3(); break; case HART_CMD_6: common_cmd_6(); break; case HART_CMD_7: common_cmd_7(); break; case HART_CMD_8: common_cmd_8(); break; case HART_CMD_9: common_cmd_9(); break; case HART_CMD_11: common_cmd_11(); break; case HART_CMD_12: common_cmd_12(); break; case HART_CMD_13: common_cmd_13(); break; case HART_CMD_14: common_cmd_14(); break; case HART_CMD_15: common_cmd_15(); break; case HART_CMD_16: common_cmd_16(); break; case HART_CMD_17: common_cmd_17(); break; case HART_CMD_18: common_cmd_18(); break; case HART_CMD_19: common_cmd_19(); break; case HART_CMD_20: common_cmd_20(); break; case HART_CMD_21: common_cmd_21(); break; case HART_CMD_22: common_cmd_22(); break; #ifdef IMPLEMENT_RANGE_CMDS_35_36_37 case HART_CMD_35: common_cmd_35(); break; case HART_CMD_36: common_cmd_36(); break; case HART_CMD_37: common_cmd_37(); break; #endif case HART_CMD_38: common_cmd_38(); break; case HART_CMD_39: common_cmd_39(); break; case HART_CMD_40: common_cmd_40(); break; #if 0 case HART_CMD_42: // We don't support CMD_42 MH 12/6/12 common_cmd_42(); break; #endif #if 0 case HART_CMD_43: common_cmd_43(); break; #endif case HART_CMD_45: common_cmd_45(); break; case HART_CMD_46: common_cmd_46(); break; case HART_CMD_48: common_cmd_48(); break; case HART_CMD_54: common_cmd_54(); break; case HART_CMD_57: common_cmd_57(); break; case HART_CMD_58: common_cmd_58(); break; case HART_CMD_110: common_cmd_110(); break; case HART_CMD_219: mfr_cmd_219(); break; case HART_CMD_220: mfr_cmd_220(); break; case HART_CMD_221: mfr_cmd_221(); break; case HART_CMD_222: mfr_cmd_222(); break; // If it is not a common command, select the // handler based upon the sensor type default: #ifdef USE_MULTIPLE_SENSOR_COMMANDS switch(startUpDataLocalV.defaultSensorType) { case CONDUCTIVITY_TYPE: executeConductivityCommand(); break; case LEVEL_TYPE: executeLevelCommand(); break; case ORP_TYPE: executeOrpCommand(); break; case PH_TYPE: executePhCommand(); break; case PRESSURE_TYPE: executePressureCommand(); break; case MA4_20_TYPE: executeMa4_20Command(); break; case FLOW_TYPE: default: executeFlowCommand(); break; } #else common_tx_error(CMD_NOT_IMPLEMENTED); break; #endif } } /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: executeFlowCommand() // // Description: // // Execute the HART command, generate the response. // // Parameters: void // // Return Type: void // // Implementation notes: // // // /////////////////////////////////////////////////////////////////////////////////////////// void executeFlowCommand(void) { common_tx_error(CMD_NOT_IMPLEMENTED); } #ifdef USE_MULTIPLE_SENSOR_COMMANDS /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: executeConductivityCommand() // // Description: // // Execute the HART command, generate the response. // // Parameters: void // // Return Type: void // // Implementation notes: // // // /////////////////////////////////////////////////////////////////////////////////////////// void executeConductivityCommand(void) { common_tx_error(CMD_NOT_IMPLEMENTED); } /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: executeLevelCommand() // // Description: // // Execute the HART command, generate the response. // // Parameters: void // // Return Type: void // // Implementation notes: // // // /////////////////////////////////////////////////////////////////////////////////////////// void executeLevelCommand(void) { common_tx_error(CMD_NOT_IMPLEMENTED); } /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: executeMa4_20Command() // // Description: // // Execute the HART command, generate the response. // // Parameters: void // // Return Type: void // // Implementation notes: // // // /////////////////////////////////////////////////////////////////////////////////////////// void executeMa4_20Command(void) { common_tx_error(CMD_NOT_IMPLEMENTED); } /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: executeOrpCommand() // // Description: // // Execute the HART command, generate the response. // // Parameters: void // // Return Type: void // // Implementation notes: // // // /////////////////////////////////////////////////////////////////////////////////////////// void executeOrpCommand(void) { common_tx_error(CMD_NOT_IMPLEMENTED); } /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: executePhCommand() // // Description: // // Execute the HART command, generate the response. // // Parameters: void // // Return Type: void // // Implementation notes: // // // /////////////////////////////////////////////////////////////////////////////////////////// void executePhCommand(void) { common_tx_error(CMD_NOT_IMPLEMENTED); } /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: executePressureCommand() // // Description: // // Execute the HART command, generate the response. // // Parameters: void // // Return Type: void // // Implementation notes: // // // /////////////////////////////////////////////////////////////////////////////////////////// void executePressureCommand(void) { common_tx_error(CMD_NOT_IMPLEMENTED); } #endif /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: executeCmd0() // // Description: // // Execute the HART command 0, generate the response. // // Parameters: void // // Return Type: void // // Implementation notes: // // // /////////////////////////////////////////////////////////////////////////////////////////// void executeCmd0(void) { common_cmd_0(); } /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: executeCmd11() // // Description: // // Execute the appropriate HART command 11, generate the response. // // Parameters: void // // Return Type: void // // Implementation notes: // // // /////////////////////////////////////////////////////////////////////////////////////////// void executeCmd11(void) { common_cmd_11(); } /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: executeCmd21() // // Description: // // Execute the appropriate HART command 21, generate the response. // // Parameters: void // // Return Type: void // // Implementation notes: // // // /////////////////////////////////////////////////////////////////////////////////////////// void executeCmd21(void) { common_cmd_21(); } /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: executeTxErr() // // Description: // // Execute the HART tx err command, generate the response. // // Parameters: unsigned char error code // // Return Type: void // // Implementation notes: // // // /////////////////////////////////////////////////////////////////////////////////////////// void executeTxErr(unsigned char errCode) { common_tx_error(errCode); } /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: executeCommErr() // // Description: // // Execute the HART comm err command, generate the response. // // Parameters: void // // Return Type: void // // Implementation notes: // // // /////////////////////////////////////////////////////////////////////////////////////////// void executeCommErr(void) { common_tx_comm_error(); } <file_sep>/*! * \file hart_r3.c * \brief This module provides HART interface. * Created on: Sep 20, 2012 * \author: * Revision History: * Date Rev. Engineer Description * -------- ----- ------------ -------------- * 04/01/11 0 <NAME> Creation * 04/02/11 1 Patel Add funcations * */ /////////////////////////////////////////////////////////////////////////////////////////// // // Module Name: // // Functional Unit: // // Description: // // // // Exported Interfaces: // // hart.h - This interface file includes all exported interfaces // from this module. // // Document Reference(s): // // PDD-xxxx // // Implementation Notes: // // // // // /////////////////////////////////////////////////////////////////////////////////////////// //============================================================================== // INCLUDES //============================================================================== #include <msp430f5528.h> #include <string.h> #include "hardware.h" #include "protocols.h" #include "utilities_r3.h" #include "main9900_r3.h" #include "hart_r3.h" //============================================================================== // LOCAL DEFINES //============================================================================== //============================================================================== // LOCAL PROTOTYPES. //============================================================================== //============================================================================== // GLOBAL DATA //============================================================================== unsigned char updateNvRam; //!< A flag so NV ram is only updated in the main loop //============================================================================== // LOCAL DATA //============================================================================== //============================================================================== // FUNCTIONS //============================================================================== ///!MH NEED TO ORGANIZE VARIABLE & DEFINE SCOPES // The process variables float PVvalue = 0.0; float SVvalue = 0.0; float ma4_20 = 0.0; float savedLoopCurrent = 0.0; float reportingLoopCurrent = 0.0; // If the device is busy, we need to respond appropriately unsigned char deviceBusyFlag = FALSE; // Flags to indicate a HART command has been received unsigned char cmdSyncToRam = FALSE; unsigned char cmdSyncToFlash = FALSE; unsigned char cmdReset = FALSE; unsigned char doNotRespond = FALSE; // The programmed Device ID must be set in a different area of FLASH // and copied into the local data on initialization const unsigned char * pNvDevId = NV_DEVICE_ID_LOCATION; // The startup data HART_STARTUP_DATA_NONVOLATILE startUpDataLocalNv; HART_STARTUP_DATA_VOLATILE startUpDataLocalV; const HART_STARTUP_DATA_NONVOLATILE startUpDataFactoryNv = { //"+GF+ Signet 9900\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", // Name //FLOW_TYPE, // default sensor //FALSE, // from primary 0, // primary status 0, // secondary status //EXPANDED_DEV_TYPE, // expanded device type //XMIT_PREAMBLE_BYTES, // min M -> S preambles //HART_MAJ_REV, // HART rev //DEVICE_REVISION, // device revision //SOFTWARE_REVISION, // sw revision //HARDWARE_REVISION, // hw revision //SIGNAL_CODE, // physical signal code //FLAGS, // flags {0x00, 0x00, 0x01}, // default device ID //XMIT_PREAMBLE_BYTES, // min S -> M preambles //MAX_DEV_VARS, // Maximum device variables CURRENT_CONFIG_CNT, // configuration change counter //EXT_FLD_STATUS, // extended field device status GF_MFR_ID, // manufacturer ID //GF_MFR_ID, // private label distributor code //DEVICE_PROFILE, // Device Profile {0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF}, // Long tag is all '?' {0x20,0x33,0xcd,0x36,0x08,0x20}, // tag = "HCOMM " {0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF}, // tag descriptor - all '?' {1,1,0x64}, // date 0, // polling address {0x97,0x11,0x6B}, // final assembly = "9900395d" {0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF}, // HART message - all '?' //0, // Alert Status //0, // Error Status //{0,0,0,0,0,0}, // Device Specific Status //0, // Device Op Mode Status //0, // Std Status 0 CURRENT_MODE_ENABLE //, // Current Mode //{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0} // Error Counts }; const HART_STARTUP_DATA_VOLATILE startUpDataFactoryV = { "+GF+ Signet 9900\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", // Name FLOW_TYPE, // default sensor FALSE, // from primary //0, // primary status //0, // secondary status EXPANDED_DEV_TYPE, // expanded device type XMIT_PREAMBLE_BYTES, // min M -> S preambles HART_MAJ_REV, // HART rev DEVICE_REVISION, // device revision SOFTWARE_REVISION, // sw revision HARDWARE_REVISION, // hw revision SIGNAL_CODE, // physical signal code FLAGS, // flags //{0x00, 0x00, 0x01}, // default device ID XMIT_PREAMBLE_BYTES, // min S -> M preambles MAX_DEV_VARS, // Maximum device variables //CURRENT_CONFIG_CNT, // configuration change counter EXT_FLD_STATUS, // extended field device status //GF_MFR_ID, // manufacturer ID GF_MFR_ID, // private label distributor code DEVICE_PROFILE, // Device Profile //{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, // Long tag //{0x22,0x00,0xCF,0x34,0xD7,0xDF}, // tag //{0,0,0,0,0,0,0,0,0,0,0,0}, // tag descriptor //{1,1,0x64}, // date //0, // polling address //{0x00,0x00,0x01}, // final assembly //{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, // HART message //0, // Alert Status //0, // Error Status {0,0,0,0,0,0}, // Device Specific Status 0, // Device Op Mode Status 0, // Std Status 0 //CURRENT_MODE_ENABLE, // Current Mode {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0} // Error Counts }; void incrementConfigCount(void) { startUpDataLocalNv.configChangeCount++; // Set up to write RAM to FLASH updateNvRam = TRUE; } void setPrimaryMasterChg(void) { startUpDataLocalNv.Primary_status |= FD_STATUS_CONFIG_CHANGED; // Set up to write RAM to FLASH updateNvRam = TRUE; } void setSecondaryMasterChg(void) { startUpDataLocalNv.Secondary_status |= FD_STATUS_CONFIG_CHANGED; // Set up to write RAM to FLASH updateNvRam = TRUE; } void clrPrimaryMasterChg(void) { startUpDataLocalNv.Primary_status &= ~FD_STATUS_CONFIG_CHANGED; // Set up to write RAM to FLASH updateNvRam = TRUE; } void clrSecondaryMasterChg(void) { startUpDataLocalNv.Secondary_status &= ~FD_STATUS_CONFIG_CHANGED; // Set up to write RAM to FLASH updateNvRam = TRUE; } void setPrimaryStatusBits(unsigned char bits) { startUpDataLocalNv.Primary_status |= bits; // Set up to write RAM to FLASH updateNvRam = TRUE; } void setSecondaryStatusBits(unsigned char bits) { startUpDataLocalNv.Secondary_status |= bits; // Set up to write RAM to FLASH updateNvRam = TRUE; } void clrPrimaryStatusBits(unsigned char bits) { startUpDataLocalNv.Primary_status &= ~bits; // Set up to write RAM to FLASH updateNvRam = TRUE; } void clrSecondaryStatusBits(unsigned char bits) { startUpDataLocalNv.Secondary_status &= ~bits; // Set up to write RAM to FLASH updateNvRam = TRUE; } void syncNvRam(void) { // Set busy flag deviceBusyFlag = TRUE; syncToFlash(VALID_SEGMENT_1, ((unsigned char *)&startUpDataLocalNv), sizeof(HART_STARTUP_DATA_NONVOLATILE)); // clear busy flag deviceBusyFlag = FALSE; } void setPrimaryMoreAvailable(void) { startUpDataLocalNv.Primary_status |= FD_STATUS_MORE_STATUS_AVAIL; // Set up to write RAM to FLASH updateNvRam = TRUE; } void setSecondaryMoreAvailable(void) { startUpDataLocalNv.Secondary_status |= FD_STATUS_MORE_STATUS_AVAIL; // Set up to write RAM to FLASH updateNvRam = TRUE; } void clrPrimaryMoreAvailable(void) { startUpDataLocalNv.Primary_status &= ~FD_STATUS_MORE_STATUS_AVAIL; // Set up to write RAM to FLASH updateNvRam = TRUE; } void clrSecondaryMoreAvailable(void) { startUpDataLocalNv.Secondary_status &= ~FD_STATUS_MORE_STATUS_AVAIL; // Set up to write RAM to FLASH updateNvRam = TRUE; } // Utilities to copy ints and floats into the response buffer /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: copyLongToRespBuf() // // Description: // // Copies a long int value into the response buffer // // Parameters: // long - the number to copy // // Return Type: void // // Implementation notes: // The function increases respBufferSize appropriately // // /////////////////////////////////////////////////////////////////////////////////////////// void copyLongToRespBuf(long iVal) { U_LONG_INT temp; temp.i = iVal; // Copy in the number in backwards szHartResp[respBufferSize] = temp.b[3]; ++respBufferSize; szHartResp[respBufferSize] = temp.b[2]; ++respBufferSize; szHartResp[respBufferSize] = temp.b[1]; ++respBufferSize; szHartResp[respBufferSize] = temp.b[0]; ++respBufferSize; } /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: copyIntToRespBuf() // // Description: // // Copies a short int value into the response buffer // // Parameters: // int - the int number to copy // // Return Type: void // // Implementation notes: // The function increases respBufferSize appropriately // // /////////////////////////////////////////////////////////////////////////////////////////// void copyIntToRespBuf(int iVal) { U_SHORT_INT temp; temp.i = iVal; // Copy in the number in backwards szHartResp[respBufferSize] = temp.b[1]; ++respBufferSize; szHartResp[respBufferSize] = temp.b[0]; ++respBufferSize; } /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: copyFloatToRespBuf() // // Description: // // Copies a floating point value into the response buffer // // Parameters: // float - the floating point number to copy // // Return Type: void // // Implementation notes: // The function increases respBufferSize appropriately // // /////////////////////////////////////////////////////////////////////////////////////////// void copyFloatToRespBuf(float fVal) { U_LONG_FLOAT temp; temp.fVal = fVal; // Copy in the number in backwards szHartResp[respBufferSize] = temp.b[3]; ++respBufferSize; szHartResp[respBufferSize] = temp.b[2]; ++respBufferSize; szHartResp[respBufferSize] = temp.b[1]; ++respBufferSize; szHartResp[respBufferSize] = temp.b[0]; ++respBufferSize; } /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: decodeBufferFloat() // // Description: // // Decodes a floating point value from the command or response buffer // // Parameters: // unsigned char * pBuffer - the pointer to the first byte of the number to decode // // Return Type: float // // Implementation notes: // // /////////////////////////////////////////////////////////////////////////////////////////// float decodeBufferFloat(unsigned char * pBuffer) { U_LONG_FLOAT temp; temp.b[3] = *pBuffer; temp.b[2] = *(pBuffer+1); temp.b[1] = *(pBuffer+2); temp.b[0] = *(pBuffer+3); return temp.fVal; } /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: decodeBufferInt() // // Description: // // Decodes an integer value from the command or response buffer // // Parameters: // unsigned char * pBuffer - the pointer to the first byte of the number to decode // // Return Type: int // // Implementation notes: // // /////////////////////////////////////////////////////////////////////////////////////////// int decodeBufferInt(unsigned char * pBuffer) { U_SHORT_INT temp; temp.b[1] = *pBuffer; temp.b[0] = *(pBuffer+1); return temp.i; } /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: UpdateSensorType() // // Description: // // copies the 9900 downloades sensor type to the local startup data // // Parameters: void // // Return Type: void // // Implementation notes: // // /////////////////////////////////////////////////////////////////////////////////////////// void UpdateSensorType(void) { startUpDataLocalV.defaultSensorType = u9900Database.db.MEASUREMENT_TYPE; } /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: copyNvDeviceIdToRam() // // Description: // // Copies the NV Device ID to the local startup data if it is not 0xFFFFFF (erased). // Otherwise, the RAM value is left as-is // // Parameters: void // // Return Type: void // // Implementation notes: // // /////////////////////////////////////////////////////////////////////////////////////////// void copyNvDeviceIdToRam(void) { // Define the erased FLASH pattern //unsigned char erasedValue[DEVICE_ID_SIZE] = {0xFF, 0xFF, 0xFF}; //MH Initialization is wrong unsigned char erasedValue[DEVICE_ID_SIZE]; memset(erasedValue,0xFF,DEVICE_ID_SIZE); //MH erasedValue[0..DEVICE_ID_SIZE-1]= 0xFF // Only copy if the FLASH is NOT erased if (memcmp(pNvDevId, erasedValue, DEVICE_ID_SIZE)) { memcpy(startUpDataLocalNv.DeviceID, pNvDevId, DEVICE_ID_SIZE); } } /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: copyDeviceIdToFlash() // // Description: // // Copies the Device ID to the start of FLASH segment 3 // // Parameters: // // unsigned char * - pointer to the first byte of device ID // // Return Type: int - TRUE if the copy was successful, FALSE otherwise // // Implementation notes: // Erases segment 3 before copying, just in case the value is being changed // // /////////////////////////////////////////////////////////////////////////////////////////// int copyDeviceIdToFlash(unsigned char * pDeviceId) { int rtnFlag; // Erase segment 3 rtnFlag = eraseMainSegment(NV_DEVICE_ID_LOCATION, MAIN_SEGMENT_SIZE); // copy in the new value if (rtnFlag) { rtnFlag = copyMemToMainFlash(NV_DEVICE_ID_LOCATION, pDeviceId, DEVICE_ID_SIZE); } // check the new value against the supplied value, and return TRUE if it matches if (rtnFlag) { rtnFlag = verifyFlashContents(NV_DEVICE_ID_LOCATION, pDeviceId, DEVICE_ID_SIZE); } return rtnFlag; } /////////////////////////////////////////////////////////////////////////////////////////// // // Function Name: verifyDeviceId() // // Description: // // Checks to see if the Device ID is correct, and loads it if it isn't // // Parameters: void // // Return Type: void // // Implementation notes: // // /////////////////////////////////////////////////////////////////////////////////////////// void verifyDeviceId(void) { int numSegsToErase; // Make sure the FLASH device ID is programmed before proceeding // Define the erased FLASH pattern //unsigned char erasedValue[DEVICE_ID_SIZE] = {0xFF, 0xFF, 0xFF}; //MH Initialization is wrong unsigned char erasedValue[DEVICE_ID_SIZE]; memset(erasedValue,0xFF,DEVICE_ID_SIZE); //MH erasedValue[0..DEVICE_ID_SIZE-1]= 0xFF // Only continue if the FLASH is NOT erased if (memcmp(pNvDevId, erasedValue, DEVICE_ID_SIZE)) { // Now check to see if what is in FLASH and RAM are identical. Do nothing if // they're the same. if (memcmp(pNvDevId, startUpDataLocalNv.DeviceID, DEVICE_ID_SIZE)) { // Copy the correct ID into RAM copyNvDeviceIdToRam(); // Now make sure it is sync'd up: // erase the segment of FLASH so it can be reprogrammed numSegsToErase = calcNumSegments (sizeof(HART_STARTUP_DATA_NONVOLATILE)); eraseMainSegment(VALID_SEGMENT_1, (numSegsToErase*MAIN_SEGMENT_SIZE)); // Copy the local data into NV memory copyMemToMainFlash (VALID_SEGMENT_1, ((unsigned char *)&startUpDataLocalNv), sizeof(HART_STARTUP_DATA_NONVOLATILE)); } } } <file_sep>#ifndef HART_H_ #define HART_H_ /************************************************************************* * $INCLUDES *************************************************************************/ /************************************************************************* * $DEFINES *************************************************************************/ // Defines for certain Common Practice Commands //#define IMPLEMENT_RANGE_CMDS_35_36_37 // Initial fixed values of local data #define GF_MFR_ID 0x6055 #define EXPANDED_DEV_TYPE 0xE1B3 #define HART_MAJ_REV 7 #define DEVICE_REVISION 1 #define SOFTWARE_REVISION 1 #define HARDWARE_REVISION 1 #define SIGNAL_CODE 0 #define FLAGS 0x03 #define MAX_DEV_VARS 1 // Changed from 4 -> 1 per <NAME>. Only PV & SV #define CURRENT_CONFIG_CNT 0 #define EXT_FLD_STATUS 0 #define DEVICE_PROFILE 1 // HART Error Register Flags #define NO_HART_ERRORS 0x0000 #define RCV_PARITY_ERROR 0x0001 #define RCV_FRAMING_ERROR 0x0002 #define RCV_OVERRUN_ERROR 0x0004 #define RCV_BREAK_CHAR 0x0008 #define EXCESS_PREAMBLE 0x0010 #define INSUFFICIENT_PREAMBLE 0x0020 #define WRONG_ADDR 0x0040 #define UNSUPPORTED_CMD 0x0080 #define HART_TIMER_EXPIRED 0x0100 #define STX_ERROR 0x0200 #define RCV_BAD_BYTE_COUNT 0x0400 #define RCV_BAD_LRC 0x0800 #define BUFFER_OVERFLOW 0x1000 #define GAP_TIMER_EXPIRED 0x2000 #define EXTRA_CHAR_RCVD 0x4000 // HART Comm response error codes #define COMM_ERR 0x80 #define VERT_PAR_ERR 0x40 #define OVRRUN_ERR 0x20 #define FRM_ERR 0x10 #define LONG_PAR_ERR 0x08 #define BUFF_OVR_ERR 0x02 // Default Sensor types - from 9900 #define NOT_CONFIGURED 0x00 #define FLOW_TYPE 0x01 #define PH_TYPE 0x02 #define ORP_TYPE 0x03 #define CONDUCTIVITY_TYPE 0x04 #define PRESSURE_TYPE 0x05 #define LEVEL_TYPE 0x06 #define TEMPERATURE_TYPE 0x07 #define MA4_20_TYPE 0x08 #define SALINITY_TYPE 0x09 // Defines #define RESP_SOF_OFFSET 0 #define LONG_DATA_OFFSET 8 //RESP_LONG_COUNT_OFFSET+1 #define SHORT_DATA_OFFSET 4 // RESP_SHORT_COUNT_OFFSET+1 // Error Codes #define CMD_NOT_IMPLEMENTED 64 // Command not implemented #define UNIT_BUSY 32 // The device is busy #define SHORT_DATA 5 // not enough data received #define SELECTION_INVALID 2 // The selection is invalid // Other response codes #define NO_WRITE_PROTECT 251 // Write protect mode not available #define NOT_USED 250 // Alarm response codes for command 15 #define ALARM_CODE_LOOP_HIGH 0 #define ALARM_CODE_LOOP_LOW 1 #define ALARM_CODE_LOOP_HOLD 239 #define ALARM_CODE_LOOP_MFG 240 #define ALARM_CODE_LOOP_NONE 250 #define ALARM_CODE_LOOP_NULL 251 #define ALARM_CODE_LOOP_UNKN 252 //#define ANALOG_CHANNEL_FLAG 1 #define ANALOG_CHANNEL_FLAG 0 #define XFR_FUNCTION_NONE 0 #define DEV_STATUS_HIGH_BYTE 0 // Return ERR code #define COMM_ERROR 0x80 // Communications error #define VPAR_ERROR 0x40 // Vertical parity error #define OVRN_ERROR 0x20 // UART Character Overrun error #define FRAM_ERROR 0x10 // UART Character Framing error #define LPAR_ERROR 0x08 // Longitudinal parity error #define BOVF_ERROR 0x02 // Buffer overflow error // Unit codes #define PRESSURE_IN_PSI 6 #define CELSIUS 32 #define FARENHEIT 33 #define RANKIN 34 #define KELVIN 35 #define MILLIVOLTS 36 #define HERTZ 38 #define MILLIAMPS 39 #define MINUTES 50 #define SECONDS 51 #define HOURS 52 #define DAYS 53 #define PERCENT 57 #define VOLTS 58 #define DEGREES 143 #define RADIANS 144 // Command-specific response codes #define RESP_SUCCESS 0 #define INVALID_POLL_ADDR_SEL 2 #define INVALID_SELECTION 2 #define PASSED_PARM_TOO_LARGE 3 #define PASSED_PARM_TOO_SMALL 4 #define TOO_FEW_DATA_BYTES 5 #define DEV_SPECIFIC_CMD_ERR 6 #define IN_WRITE_PROTECT_MODE 7 #define UPDATE_FAILURE 8 #define SET_NEAREST_POSSIBLE 8 #define LOWER_RANGE_TOO_HIGH 9 #define INVALID_DATE_CODE 9 #define CONFIG_COUNTER_MISMATCH 9 #define INCORRECT_LOOP_MODE 9 #define APPL_PROCESS_TOO_HIGH 9 #define APPL_PROCESS_TOO_LOW 10 #define LOWER_RANGE_TOO_LOW 10 #define UPPER_RANGE_TOO_HIGH 11 #define LOOP_CURRENT_NOT_ACTIVE 11 #define IN_MULTIDROP_MODE 11 #define INVALID_MODE_SEL 12 #define UPPER_RANGE_TOO_LOW 12 #define DYN_VARS_RETURNED 14 #define NEW_LOWER_RANGE_PUSHED 14 #define SPAN_TOO_SMALL 14 #define ACCESS_RESTRICTED 16 #define INVALID_SPAN 29 #define CMD_RESP_TRUNCATED 30 #define HART_DEVICE_BUSY 32 // Current Modes (command 6 #define CURRENT_MODE_DISABLE 0 #define CURRENT_MODE_ENABLE 1 // Address field masks #define BURST_MODE_BIT 0x40 // Burst mode bit #define PRIMARY_MASTER 0x80 #define POLL_ADDR_MASK 0x3F #define EXT_DEV_TYPE_ADDR_MASK 0x3FFF // Lower status byte bit masks #define FD_STATUS_DEVICE_MALFUNCTION 0x80 #define FD_STATUS_CONFIG_CHANGED 0x40 #define FD_STATUS_COLD_START 0x20 #define FD_STATUS_MORE_STATUS_AVAIL 0x10 #define FD_STATUS_PV_ANALOG_FIXED 0x08 #define FD_STATUS_PV_ANALOG_SATURATED 0x04 #define FD_STATUS_SV_OUT_OF_LIMITS 0x02 #define FD_STATUS_PV_OUT_OF_LIMITS 0x01 /*! * Added user test case: * If no Hart Master sending cyclical frames we need to generate a timed event * to synchronize NV-ram. Define is in 125mS ticks */ #define HART_CONFIG_CHANGE_SYNC_TICKS 12 /*! * hostActive bit sent to 9900 needs to be: * 0 Hart Master is not present * 1 Set as soon as a Hart message is received * 1->0 After HOST_ACTIVE_TIMEOUT of no hart activity, bit is cleared * * Define is compared with x125mS ticks, 16 is 2 Secs */ #define HOST_ACTIVE_TIMEOUT 16 // Device Variable Codes #define DVC_PV 0 #define DVC_SV 1 #define DVC_BATTERY_LIFE 243 #define DVC_PERCENT_RANGE 244 #define DVC_LOOP_CURRENT 245 #define DVC_PRIMARY_VARIABLE 246 #define DVC_SECONDARY_VARIABLE 247 #define DVC_TERTIARY_VARIABLE 248 #define DVC_QUARTERNARY_VARIABLE 249 #define DVC_INVALID_SELECTION 255 // exported variables // The following structure is the HART startup information, which needs // to be stored in non-volatile memory #define NAME_SIZE 32 #define DEVICE_ID_SIZE 3 #define SHORT_TAG_SIZE 6 #define LONG_TAG_SIZE 32 #define DESCRIPTOR_SIZE 12 #define DATE_SIZE 3 #define FINAL_ASSY_SIZE 3 #define HART_MSG_SIZE 24 #define TAG_DESCRIPTOR_DATE_SIZE 21 #define CONFIG_COUNTER_SIZE 2 #define DEV_SPECIFIC_STATUS_SIZE 6 #define NV_DEVICE_ID_LOCATION VALID_SEGMENT_3 /* Extended device status 01 - maint req 02 - dev variable alert 04 - critical power fail Device op mode 0 - Reserved for now Std status 0 01 - simulation active 02 - NV mem defect 04 - vol mem defect 08 - watchdog reset executed 10 - voltage condition OO range 20 - envirnmental condition OOR 40 - hardware problem, */ // Values for Standard Status 0 #define SS0_SIMULATION_ACTIVE 0x01 #define SS0_NV_MEM_DEFECT 0x02 #define SS0_VOL_MEM_DEFECT 0x04 #define SS0_WATCHDOG_CALLED 0x08 #define SS0_VOLTAGE_OOR 0x10 #define SS0_ENVIRONMENT_OOR 0x20 #define SS0_HARDWARE_PROBLEM 0x40 // Variable Status Flags #define VAR_STATUS_GOOD 0xC0 #define VAR_STATUS_MAN_FIXED 0x80 #define VAR_STATUS_INACCURATE 0x40 #define VAR_STATUS_BAD 0x00 #define LIM_STATUS_CONST 0x30 #define LIM_STATUS_HIGH 0x20 #define LIM_STATUS_LOW 0x10 #define LIM_STATUS_NOT_LIMITED 0x00 /*! * The volatile section of local startup data * * This is the portion of local data that is always loaded with factory values * */ typedef struct stHartStartupV // HART 7 compliant { // The first member must be an unsigned char unsigned char myName [NAME_SIZE]; unsigned char defaultSensorType; int fromPrimary; //unsigned char Primary_status; //unsigned char Secondary_status; // The following members are used for command 0 unsigned int expandedDevType; unsigned char minPreamblesM2S; unsigned char majorHartRevision; unsigned char deviceRev; unsigned char swRev; unsigned char hwRev; // 5 bits only unsigned char physSignalCode; // 3 bits only unsigned char flags; //unsigned char DeviceID [DEVICE_ID_SIZE]; unsigned char minPreamblesS2M; unsigned char maxNumDevVars; //unsigned int configChangeCount; // Must be changed every revision!! unsigned char extendFieldDevStatus; //unsigned int ManufacturerIdCode; unsigned int PrivDistCode; unsigned char devProfile; //////////////////////////////////////////// //unsigned char LongTag [LONG_TAG_SIZE]; //unsigned char TagName [SHORT_TAG_SIZE]; //unsigned char Descriptor [DESCRIPTOR_SIZE]; //unsigned char Date[DATE_SIZE]; //unsigned char PollingAddress; //unsigned char FinalAssy [FINAL_ASSY_SIZE]; //////////////////////////////////////////// //unsigned char HARTmsg [HART_MSG_SIZE]; //unsigned char AlertStatus; //unsigned char ErrStatus; unsigned char DeviceSpecificStatus [DEV_SPECIFIC_STATUS_SIZE]; unsigned char DeviceOpMode; unsigned char StandardStatus0; //unsigned char currentMode; ///////////////////////////////////////////// unsigned int errorCounter[19]; } HART_STARTUP_DATA_VOLATILE; // Error Counter Indices: // Index 0 = the number of FRAMING errors // Index 1 = the number of PARITY errors // Index 2 = the number of OVERFLOW errors // Index 3 = the number of insufficient preambles // Index 4 = the number of excess preambles // Index 5 = the number of STX errors // Index 6 = the number of bad LRC // Index 7 = the number of bad byte errors // Index 8 = the number of cold starts // Index 9 = the number of commanded resets // Index 10 = the number of UNMI interrupts // Index 11 = the number of SYSNMI interrupts // Index 12 = the number of WDT interrupts // Index 13 = the number of bad addresses // Index 14 = the number of SOM overflows // Index 15 = the number of not my addresses // Index 16 = the number of errored byte counts // Index 17 = the number of received characters exceed the buffer // Index 18 = the number of fatal SOM characters /*! * The non-volatile section of local startup data * * This is the portion of local data that is loaded from flash. * Modifications are stored as necessary * */ typedef struct stHartStartupNV // HART 7 compliant { // The first member must be an unsigned char //unsigned char myName [NAME_SIZE]; //unsigned char defaultSensorType; //int fromPrimary; unsigned char Primary_status; unsigned char Secondary_status; // The following members are used for command 0 //unsigned int expandedDevType; //unsigned char minPreamblesM2S; //unsigned char majorHartRevision; //unsigned char deviceRev; //unsigned char swRev; //unsigned char hwRev; // 5 bits only //unsigned char physSignalCode; // 3 bits only //unsigned char flags; unsigned char DeviceID [DEVICE_ID_SIZE]; //unsigned char minPreamblesS2M; //unsigned char maxNumDevVars; unsigned int configChangeCount; // Must be changed every revision!! //unsigned char extendFieldDevStatus; unsigned int ManufacturerIdCode; //unsigned int PrivDistCode; //unsigned char devProfile; //////////////////////////////////////////// unsigned char LongTag [LONG_TAG_SIZE]; unsigned char TagName [SHORT_TAG_SIZE]; unsigned char Descriptor [DESCRIPTOR_SIZE]; unsigned char Date[DATE_SIZE]; unsigned char PollingAddress; unsigned char FinalAssy [FINAL_ASSY_SIZE]; //////////////////////////////////////////// unsigned char HARTmsg [HART_MSG_SIZE]; //unsigned char AlertStatus; //unsigned char ErrStatus; //unsigned char DeviceSpecificStatus [DEV_SPECIFIC_STATUS_SIZE]; //unsigned char DeviceOpMode; //unsigned char StandardStatus0; unsigned char currentMode; ///////////////////////////////////////////// //unsigned int errorCounter[19]; } HART_STARTUP_DATA_NONVOLATILE; /*! * Long-Float utility unions */ typedef union uLongFloat { float fVal; unsigned char b[4]; } U_LONG_FLOAT; /*! * Integer-Bytes utility unions */ typedef union uIntByte { int i; unsigned char b[2]; } U_SHORT_INT; /*! * Long-Bytes utility unions */ typedef union uLongByte { long i; unsigned char b[4]; } U_LONG_INT; /************************************************************************* * $GLOBAL PROTOTYPES *************************************************************************/ void incrementConfigCount(void); void setPrimaryMasterChg(void); void setSecondaryMasterChg(void); void clrPrimaryMasterChg(void); void clrSecondaryMasterChg(void); void setPrimaryMoreAvailable(void); void setSecondaryMoreAvailable(void); void clrPrimaryMoreAvailable(void); void clrSecondaryMoreAvailable(void); void setPrimaryStatusBits(unsigned char); void setSecondaryStatusBits(unsigned char); void clrPrimaryStatusBits(unsigned char); void clrSecondaryStatusBits(unsigned char); void syncNvRam(void); // The programmed Device ID must be set in a different area of FLASH // and copied into the local data on initialization void copyNvDeviceIdToRam(void); int copyDeviceIdToFlash(unsigned char *); void verifyDeviceId(void); // Utilities to copy ints and floats into the response buffer void copyIntToRespBuf(int); void copyLongToRespBuf(long); void copyFloatToRespBuf(float); float decodeBufferFloat(unsigned char *); int decodeBufferInt(unsigned char *); // void UpdateSensorType(void); /************************************************************************* * $GLOBAL VARIABLES *************************************************************************/ extern unsigned char updateNvRam; // A flag so NV ram is only updated in the main loop // Process variables extern float PVvalue; extern float SVvalue; extern float ma4_20; extern float savedLoopCurrent; extern float reportingLoopCurrent; extern HART_STARTUP_DATA_NONVOLATILE startUpDataLocalNv; extern const HART_STARTUP_DATA_NONVOLATILE startUpDataFactoryNv; extern HART_STARTUP_DATA_VOLATILE startUpDataLocalV; extern const HART_STARTUP_DATA_VOLATILE startUpDataFactoryV; extern const unsigned char * pNvDevId; // If the device is busy, we need to respond appropriately extern unsigned char deviceBusyFlag; // Flags to indicate a HART command has been received extern unsigned char cmdSyncToRam; extern unsigned char cmdSyncToFlash; extern unsigned char cmdReset; extern unsigned char doNotRespond; /************************************************************************* * $INLINE FUNCTIONS *************************************************************************/ #endif /*HART_H_*/ <file_sep>/*! * \file define.h * \brief Global types and defines for the project * * Created on: Sep 19, 2012 * Author: MH * */ #ifndef DEFINE_H_ #define DEFINE_H_ /* Type definitions */ typedef unsigned char BOOLEAN; //!< Provide a bool for C typedef unsigned char BYTE; //!< Provide a 8-bit unsigned typedef signed char SBYTE; //!< Provide a 8-bit signed typedef unsigned int WORD; //!< Provide a 16-bit unsigned typedef signed int SWORD; //!< Provide a 16-bit signed typedef unsigned long int LWORD; //!< Provide a 32-bit unsigned typedef signed long int SLWORD; //!< Provide a 32-bit signed // These typedefs are used for 9900 communications typedef unsigned char int8u; //!< Provide a 8-bit unsigned typedef unsigned int int16u; //!< Provide a 16-bit unsigned /*! * \union fp32 * A type that easy conversion of FP -> hex * */ typedef union { float floatVal; int8u byteVal[4]; // Allows easy conversion of FP -> hex } fp32; /*! * \struct stFuncCtrl * Structure enable, disable and get status of a given feature * */ typedef struct { void (*enable)(void); //!< Enable feature void (*disable)(void); //!< Disable feature BOOLEAN (*isEnabled)(void); //!< Request feature status } stFuncCtrl; /// @cond SKIP_COMMENTS /* Boolean definitions */ #define TRUE 1 #define FALSE 0 #define YES 1 #define NO 0 #define ON 1 #define OFF 0 /* Logical definitions */ #define AND && #define OR || #define NOT ! /* Bit-masking operations */ #define BIT_AND & #define BIT_OR | #define BIT_NOT ~ /// @endcond /* Bit operation on registers */ /*! * \fn SETB(p,m) * \brief Macro to set the indicated bit of word, byte * * \param p This is the variable to set bit to * \param m this is the mask indicating the bit to set * * The idea of the macro is that if a constant is used as p bit number, the implementation will generate an atomic OR * */ #define SETB(p,m) p |= m /*! * \fn CLEARB(p,m) * \brief Macro to clear the indicated bit of word, byte * * \param p This is the variable to clear the bit to * \param m this is the mask indicating the bit to be clear * * The idea of the macro is that if a constant is used as p bit number, the implementation will generate an atomic AND * */ #define CLEARB(p,m) p &= ~m /*! * \fn TOGGLEB(p,m) * \brief Macro to toggle the indicated bit of word, byte * * \param p This is the variable to toggle bit to * \param m this is the mask indicating the bit to toggle * * The idea of the macro is that if a constant is used as p bit number, the implementation will generate an atomic XOR * */ #define TOGGLEB(p,m) p ^= m /// @cond SKIP_COMMENTS /* Error values */ #define NO_ERROR 0 #define YES_ERROR 1 /* character defines */ #define BLANK 0x20 /* blank ASCII character */ #ifndef EOF #define EOF -1 #endif #define NEWLINE '\n' /* End of line terminator */ #ifndef NULL #define NULL (0L) #endif /// @endcond /* macro expressions */ /*! * \fn DIM(x) * \brief Macro to provide the DIMENSION (number of elements) of the array * * \param x Ia the array to be dimensioned * \return The number of elements in the array * * */ #define DIM(x) ((int)(sizeof(x) / sizeof(x[0]))) #define TBD ; /* flag to fix something */ #endif /* DEFINE_H_ */ <file_sep>/*! * \file msp_port.h * \brief Collect all MSP430F5528 defines related to Hart Board * \author MH * Created on: Sep 19, 2012 * */ #ifndef MSP_PORT_H_ #define MSP_PORT_H_ /************************************************************************* * $INCLUDES *************************************************************************/ #include <msp430f5528.h> #include "define.h" /************************************************************************* * $DEFINES *************************************************************************/ //#define HART_ICTL UCA1ICTL // A0 is the HSB UART //#define MAIN_CTL1 UCA0CTL1 //#define MAIN_BR0 UCA0BR0 //#define MAIN_BR1 UCA0BR1 //#define MAIN_MCTL UCA0MCTL //#define MAIN_IV UCA0IV //#define MAIN_IE UCA0IE //#define MAIN_IFG UCA0IFG //#define MAIN_STAT UCA0STAT //#define MAIN_CTLW0 UCA0CTLW0 //#define MAIN_BRW UCA0BRW //#define MAIN_ABCTL UCA0ABCTL //#define MAIN_IRCTL UCA0IRCTL //#define MAIN_IRTCTL UCA0IRTCTL //#define MAIN_IRRCTL UCA0IRRCTL //#define MAIN_ICTL UCA0ICTL ///////////// Hardware Pins //////////////// // Test Points #define TP_PORTOUT P1OUT #define TP_PORTDIR P1DIR #define TP1_MASK 0x10 #define TP2_MASK 0x20 #define TP3_MASK 0x40 #define TP4_MASK 0x80 // X1 Xtal #define XT1_PORTOUT P5OUT #define XT1_PORTDIR P5DIR #define XT1_PORTSEL P5SEL #define XT1_PORTREN P5REN #define XIN_MASK 0x10 #define XOUT_MASK 0x20 // Hart Uart #define HART_UART_PORTSEL P4SEL /*!< msp430 Hart port SEL */ #define HART_UART_PORTDIR P4DIR /*!< msp430 Hart port DIR */ #define HART_UART_PORTDS P4DS /*!< msp430 Hart port Drive strength DS */ #define HART_UART_TX_MASK 0x10 /*!< msp430 Hart port pin mask for TX */ #define HART_UART_RX_MASK 0x20 /*!< msp430 Hart port pin mask for RX */ // HArt Uart Tx control (RTS) line HI= Driver disable #define HART_UART_TXCTRL_PORTOUT P4OUT /*!< Hart msp430 TX driver port OUT */ #define HART_UART_TXCTRL_PORTSEL P4SEL /*!< Hart msp430 TX driver port SEL */ #define HART_UART_TXCTRL_PORTDIR P4DIR /*!< Hart msp430 TX driver port DIR */ #define HART_UART_TXCTRL_MASK 0x01 /*!< Hart msp430 TX driver pin port MASK */ #define HART_UART_TXCTRL_PORTDS P4DS /*!< Hart msp430 RTS Hi Drive Strength */ // High Speed Bus uses TA0 #define HSB_ATTENTION_TIMER_TR TA0R /*!< Hsb slot counter Value */ #define HSB_ATTENTION_TIMER_CTL TA0CTL /*!< Hsb slot Setup Register */ #define HSB_ATTENTION_TIMER_CCR TA0CCR0 /*!< Compare register CCR0 for Hsb slot time */ #define HSB_ATTENTION_TIMER_CCTL TA0CCTL0 /*!< CCTL0 control register for Hsb slot module */ // Use the CCR1 module of TA0 to reduce the WRITE TO FLASH opportunity #define HSB_ATTENTION_TIMER_FLASH_WR_DISABLE_CCR TA0CCR1 /*!< Time to end the Hsb flash write slot */ #define HSB_ATTENTION_TIMER_FLASH_WR_DISABLE_CCTL TA0CCTL1 /*!< Control for the capture module of Hsb Flash wr slot */ // Hart Receiver Dog timers // Reception GAP between chars uses TA1 #define HART_RCV_GAP_TIMER_TR TA1R /*!< Hart Gap timer count Value */ #define HART_RCV_GAP_TIMER_CTL TA1CTL /*!< Hart gap timer Setup Register */ #define HART_RCV_GAP_TIMER_CCR TA1CCR0 /*!< Hart compare register CCR0 for GAP time */ #define HART_RCV_GAP_TIMER_CCTL TA1CCTL0 /*!< CCTL0 control register for GAP module */ // Slave Reply uses TA2 #define HART_RCV_REPLY_TIMER_TR TA2R /*!< Hart Reply timer Count Value */ #define HART_RCV_REPLY_TIMER_CTL TA2CTL /*!< Hart Reply timer Setup Register */ #define HART_RCV_REPLY_TIMER_CCR TA2CCR0 /*!< Hart reply timer Compare register CCR0 */ #define HART_RCV_REPLY_TIMER_CCTL TA2CCTL0 /*!< Hart reply timer CCTL0 Control register */ // Definitions from msp430x.h not found in CCS #define P1OUT_ (0x0202u) /* Port 1 Output */ #define P2OUT_ (0x0203u) /* Port 2 Output */ #define P3OUT_ (0x0222u) /* Port 3 Output */ #define P4OUT_ (0x0223u) /* Port 4 Output */ #define STOP_WD() ( WDTCTL = WDTPW | WDTHOLD) /*! * Used to set/reset/test pin in a port using inlines * Dropped caus generated non-atomic functions * * */ typedef struct { int8u *port; int8u mask; } tIoPinPort; #endif /* MSP_PORT_H_ */
1a6981ce503ed11199eb5c79c3c83949511e4054
[ "C", "Text" ]
25
C
wayne2000/GFHart
dc5cdd328ed332fb23ff267897482a8f23895027
a0bfee3d465ced6dca4a7410d46cf5c04f0f9fef
refs/heads/master
<file_sep>// This file can be replaced during build by using the `fileReplacements` array. // `ng build ---prod` replaces `environment.ts` with `environment.prod.ts`. // The list of file replacements can be found in `angular.json`. export const environment = { production: false, api: { auth: '<KEY>', base: 'https://api.mysportsfeeds.com/v1.2/pull/nba/', active_players: '/active_players.json', team_standings: '/overall_team_standings.json' } }; /* * In development mode, to ignore zone related error stack frames such as * `zone.run`, `zoneDelegate.invokeTask` for easier debugging, you can * import the following file, but please comment it out in production mode * because it will have performance impact when throw error */ // import 'zone.js/dist/zone-error'; // Included with Angular CLI. <file_sep>import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { HttpClientModule } from '@angular/common/http'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { NbaModule } from './modules/nba/nba.module'; import { PlayersComponent } from './components/players/players.component'; import { TeamsComponent } from './components/teams/teams.component'; import { StandingsComponent } from './components/standings/standings.component'; import { NavbarComponent } from './components/navbar/navbar.component'; //material module import { MaterialModule } from './modules/material/material.module'; import { LayoutModule } from '@angular/cdk/layout'; import { MatToolbarModule, MatButtonModule, MatSidenavModule, MatIconModule, MatListModule, MatGridListModule, MatCardModule, MatMenuModule } from '@angular/material'; import { NavListComponent } from './components/nav-list/nav-list.component'; import { DashboardComponent } from './components/dashboard/dashboard.component'; import { FormsModule } from '@angular/forms'; @NgModule({ declarations: [ AppComponent, PlayersComponent, TeamsComponent, StandingsComponent, NavbarComponent, NavListComponent, DashboardComponent, ], imports: [ BrowserModule, AppRoutingModule, FormsModule, HttpClientModule, MaterialModule, LayoutModule, MatToolbarModule, MatButtonModule, MatSidenavModule, MatIconModule, MatListModule, MatGridListModule, MatCardModule, MatMenuModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { StandingsService } from './services/standings.service'; import { PlayersService } from './services/players.service'; import { DataModule } from 'src/app/modules/data/data.module'; @NgModule({ imports: [ CommonModule, DataModule ], declarations: [] }) export class NbaModule { } <file_sep>import { Component, OnInit } from '@angular/core'; import { PlayersService } from 'src/app/modules/nba/services/players.service'; @Component({ selector: 'app-players', templateUrl: './players.component.html', styleUrls: ['./players.component.css'] }) export class PlayersComponent implements OnInit { playerName : string; constructor(private playerService : PlayersService) { } ngOnInit() { } public search() { console.log('player: ' + this.playerName); // this.playerService.GetPlayersByYear('2017-2018', '?player=james') // .subscribe((players) => { // // console.log('players: ' + JSON.stringify(players)); // }); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { StandingsService } from '../../modules/nba/services/standings.service'; @Component({ selector: 'app-standings', templateUrl: './standings.component.html', styleUrls: ['./standings.component.css'] }) export class StandingsComponent implements OnInit { constructor(private standingsService : StandingsService) { } ngOnInit() { this.standingsService.GetStandingsByYear('2017-2018') .subscribe((standings) => { // console.log('standings: ' + JSON.stringify(standings)); }); } } <file_sep>import { Injectable } from '@angular/core'; import { HttpHeaders } from '@angular/common/http'; import { map, catchError } from 'rxjs/operators' import { Observable } from 'rxjs'; import { environment } from 'src/environments/environment'; import { ApiService } from 'src/app/modules/data/services/api.service'; @Injectable({ providedIn: 'root' }) export class StandingsService { constructor(private apiService : ApiService) { } public GetStandingsByYear(year: string) { //pass in enum of year return this.apiService.Get(year + environment.api.team_standings) .pipe(map(json => { return json; })); } } <file_sep>import { Component } from '@angular/core'; @Component({ selector: 'app-dashboard', templateUrl: './dashboard.component.html', styleUrls: ['./dashboard.component.css'] }) export class DashboardComponent { cards = [ { title: 'Favorite Players', cols: 2, rows: 1 }, { title: 'Favorite Teams', cols: 1, rows: 1 }, { title: 'Standings', cols: 1, rows: 2 }, { title: 'Some other basketball stuff', cols: 1, rows: 1 } ]; } <file_sep>import { Injectable } from '@angular/core'; import { HttpHeaders } from '@angular/common/http'; import { map, catchError } from 'rxjs/operators' import { Observable } from 'rxjs'; import { environment } from 'src/environments/environment'; import { ApiService } from 'src/app/modules/data/services/api.service'; @Injectable({ providedIn: 'root' }) export class PlayersService { constructor(private apiService : ApiService) { } public GetPlayersByYear(year: string, query: string) { //pass in enum of year var url = year + environment.api.active_players; if (query) url += query; return this.apiService.Get(url) .pipe(map(json => { return json; })); } } <file_sep>import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable, throwError } from 'rxjs'; import { map, catchError } from 'rxjs/operators' import { HttpHeaders } from '@angular/common/http'; import { environment } from 'src/environments/environment'; const API_URL = environment.api.base; @Injectable({ providedIn: 'root' }) export class ApiService { private headers : HttpHeaders; constructor(private http: HttpClient) { this.headers = new HttpHeaders(); this.headers = this.headers.append("Authorization", "Basic " + environment.api.auth); } public Get(endpoint: string) : Observable<any> { return this.http .get(API_URL + endpoint, { headers: this.headers }) .pipe(catchError(this.handleError)); } public Post(endpoint: string, data: any) : Observable<any> { return this.http.post(API_URL + endpoint, data) .pipe(catchError(this.handleError)); } //handle any error encounted while sending http request private handleError (error: Response | any) { console.error('ApiService::handleError', error); return throwError(error); } }
d16d413edb674fcb2e7d1459f22f0de4e1a4ebb1
[ "TypeScript" ]
9
TypeScript
kyle-morton/NBA-Jam
cb447b826a54a01c9b38dead158e193ed8d6f434
c9ac7a4af4bce0743b86085babfce6c9d859fc5f
refs/heads/master
<file_sep>import re # Set up file to parce fname = 'task.in' def readFile(fname): """Function for parcing and validating data from scepified file""" # Open file rof reading with open(fname, 'r') as f: content = f.readlines() amount = [] price = [] header = [] # Getting data from first line in file to get farmerQuantity and amountNeeded try: data = map(int, re.findall(r'\d+', content[0])) except ValueError as err: print(err.args) # Validating values of first line # 0 <= farmerQuantity <= 100 000 000 #0 <= amountNeeded <= 300 000 000 if data[0] <= 100000000 and data[0] >= 0 and data[1] <= 300000000 and data[1] >= 0: header.append(data) else: raise ValueError('Input values not in limited range') #Starting to parse next lines for line in content[1:]: try: data = map(int, re.findall(r'\d+', line)) except ValueError as err: print(err.args) # Validating values of next lines #0<= amount <= 300 000 000 #1 <= price <= 1 000 if data[0] <= 300000000 and data[0] >= 0 and data[1] <= 1000 and data[1] >= 1: amount .append(data[0]) price.append(data[1]) else: raise ValueError('Input values not in limited range') return amount, price, header # Get amount, price, farmerQuantity and amountNeeded amount, price, header = readFile(fname) farmerQuantity, amountNeeded = header[0] totalPrice = 0 if sum(amount) < amountNeeded: totalPrice = 0 else: while amountNeeded > 0: # Get index of min price minPriceIndex = price.index(min(price)) # Take last needed amount if amountNeeded < amount[minPriceIndex]: totalPrice += (price[minPriceIndex] * amountNeeded) break # Total price totalPrice += (price[minPriceIndex] * amount[minPriceIndex]) # Remove already used price del price[minPriceIndex] amountNeeded -= amount[minPriceIndex] # Create file task.out with received information msg = "Total price for {} milk bottles is - {}".format(header[0][1], totalPrice) with open('task.out', 'w') as file: file.write(msg)
c805823ba5359deccd92c7c4d16bcdfbdf06141c
[ "Python" ]
1
Python
Shpergl/Python_test_tasks
77ad472dfe440e2372687d71f7ac15daa9a6e762
7f69a4a43704f729cc01a89037716d416bd6724f
refs/heads/master
<file_sep>using NServiceBus.Logging; using RD.ConsumerService.CommandExample; using RD.ConsumerService.SagaExample.Events; using RD.Core.Messaging; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RD.ConsumerService.EventExample { public class PublishSagaCompleteEventHandler : BaseEventHandler<PublishSagaCompleteEvent> { static readonly ILog log = LogManager.GetLogger<PublishSagaCompleteEventHandler>(); public override Task Handle(PublishSagaCompleteEvent @event) { log.Info($"Saga Complete with id:{@event.Id}"); return Task.CompletedTask; } } } <file_sep>using RD.Core.Messaging; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RD.ConsumerService.CommandExample { public class ExampleService :BaseService, IExampleService { public ExampleService(IBus buse):base(buse) { } } public interface IExampleService:IBaseService { } public interface IBaseService { IBus Bus { get; } } public abstract class BaseService:IBaseService { public BaseService(IBus bus) { Bus = bus; } public IBus Bus { get; set; } } } <file_sep>using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using RD.ConsumerService.SagaExample.Events; using RD.Core.Messaging; using System; using System.Threading.Tasks; namespace RD.ConsumerService.SagaExample { public class NServiceBusSecret { public string EndpointHost { get; set; } public string DestinationEndpointHost { get; set; } public string RabbitConnectionInfo { get; set; } } class Program { static async Task Main(string[] args) { Console.WriteLine("Hello World!"); await CreateHostBuilder(args).RunConsoleAsync(); } public static IHostBuilder CreateHostBuilder(string[] args) { return Host .CreateDefaultBuilder(args) .ConfigureAppConfiguration((hostContext, builder) => { builder.AddUserSecrets<NServiceBusSecret>(); }) .ConfigureServices((hostContext,services)=> { var nserviceBusSecret= hostContext.Configuration.GetSection(typeof(NServiceBusSecret).Name).Get<NServiceBusSecret>(); services.AddNServiceBusPublisherEvent(nserviceBusSecret.EndpointHost, nserviceBusSecret.RabbitConnectionInfo, "mongodb://localhost:27017/SagaDB"); }); } } } <file_sep>using RD.Core.Messaging.Contracts.Commands; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace SagaNameSpace { public class SagaStartingCommand:BaseCommand { } } <file_sep>using RD.Core.Messaging.Contracts.Events; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace RD.ConsumerService.CommandExample { public class PublishCommandEvent : BaseEvent { public PublishCommandEvent() { Id = Guid.NewGuid(); } } } <file_sep>using NServiceBus; using NServiceBus.Logging; using RD.Core.Messaging; using RD.ConsumerService.CommandExample; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ShareNameSpace; namespace RD.ConsumerService.CommandExample { public class ConsumerServiceHandler : BaseCommandHandler<ClientPublishCommand> { static readonly ILog log = LogManager.GetLogger<ConsumerServiceHandler>(); static readonly Random random = new Random(); IExampleService _exampleService; public ConsumerServiceHandler(IExampleService exampleService) { _exampleService = exampleService; } public override Task Handle(ClientPublishCommand message)//, IMessageHandlerContext context) { log.Info($"Received ClientPublishCommand Id = {message.Id}"); var publishCommmandEvent = new PublishCommandEvent { Id = message.Id }; //log.Info($"Publishing OrderPlaced, OrderId = {message.Id}"); //return context.Publish(orderPlaced); // this.Bus.Publish(publishCommmandEvent).Wait(); return _exampleService.Bus.Publish(publishCommmandEvent); } } } <file_sep>using Microsoft.Extensions.DependencyInjection; using MongoDB.Driver; using NServiceBus; using NServiceBus.Transport.RabbitMQ; using RD.Core.Messaging; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace RD.Core.Messaging { public static class AddNServiceBusCollections { public static IServiceCollection AddNServiceBus(this IServiceCollection services,string endPoint,Dictionary<string,KeyValuePair<Type,string>> destionationEndpoints,string rabbitConnection,string mongoConfiguration) { AddNServiceBus(services, endPoint, endPointConfiguration => { var transporter = endPointConfiguration.UseTransport<RabbitMQTransport>(); transporter.UseConventionalRoutingTopology(); transporter.ConnectionString(rabbitConnection); var routing=transporter.Routing(); foreach (var typedic in destionationEndpoints) { routing.RouteToEndpoint(typedic.Value.Key.Assembly,typedic.Key, typedic.Value.Value); } },mongoConfiguration); return services; } public static IServiceCollection AddNServiceBusPublisherEvent(this IServiceCollection services,string publisherEndpoint,string rabbitConnectionString,string mongoConfiguration) { var endPointConfiguration= new EndpointConfiguration(publisherEndpoint); endPointConfiguration.EnableInstallers(); var transporter= endPointConfiguration.UseTransport<RabbitMQTransport>(); transporter.UseConventionalRoutingTopology(); transporter.ConnectionString(rabbitConnectionString); AddNServiceBus(services,publisherEndpoint,endPointConfigure=> { endPointConfigure.EnableInstallers(); endPointConfigure.UseTransport<RabbitMQTransport>() .UseConventionalRoutingTopology() .ConnectionString(rabbitConnectionString); },mongoConfiguration); return services; } static IServiceCollection AddNServiceBus(this IServiceCollection services,string endPoint,Action<EndpointConfiguration> configuration, string mongoConfiguration) { var endPointConfiguration = new EndpointConfiguration(endPoint); endPointConfiguration.EnableInstallers(); configuration(endPointConfiguration); if (!string.IsNullOrWhiteSpace(mongoConfiguration)) endPointConfiguration.UsePersistence<MongoPersistence>().MongoClient(new MongoClient(mongoConfiguration)).UseTransactions(false).DatabaseName("SagaDB"); else endPointConfiguration.UsePersistence<InMemoryPersistence>(); services.AddSingleton(endPointConfiguration); services.AddSingleton(new SessionAndConfigurationHolder(endPointConfiguration)); services.AddHostedService<NServiceBusService>(); services.AddSingleton(provider => { var management = provider.GetService<SessionAndConfigurationHolder>(); if (management.MessageSession != null) { return management.MessageSession; } var timeout = TimeSpan.FromSeconds(30); if (!SpinWait.SpinUntil(() => management.MessageSession != null || management.StartupException != null, timeout)) { throw new TimeoutException($"Unable to resolve the message session within '{timeout.ToString()}'. If you are trying to resolve the session within hosted services it is encouraged to use `Lazy<IMessageSession>` instead of `IMessageSession` directly"); } management.StartupException?.Throw(); return management.MessageSession; }); services.AddSingleton(provider => new Lazy<IMessageSession>(provider.GetService<IMessageSession>)); services.AddSingleton(provi => provi.GetService(typeof(IServiceProvider))); services.AddSingleton<IBus, Bus>(); return services; } } } <file_sep>using NServiceBus; using RD.Core.Messaging; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace RD.Core.Messaging { public class Bus : IBus { readonly IMessageSession _messageSession; public Bus(IMessageSession messageSession) { _messageSession = messageSession; } public async Task Publish(object message, PublishOptions options) { await _messageSession.Publish(message, options).ConfigureAwait(false); } public async Task Publish<T>(Action<T> messageConstructor, PublishOptions publishOptions) { await _messageSession.Publish<T>(messageConstructor, publishOptions).ConfigureAwait(false); } public async Task Send(object message, SendOptions options) { await _messageSession.Send(message, options).ConfigureAwait(false); } public async Task Send<T>(Action<T> messageConstructor, SendOptions options) { await _messageSession.Send<T>(messageConstructor, options).ConfigureAwait(false); } public Task Subscribe(Type eventType, SubscribeOptions options) { return _messageSession.Subscribe(eventType, options); } public Task Unsubscribe(Type eventType, UnsubscribeOptions options) { return _messageSession.Unsubscribe(eventType, options); } } } <file_sep>using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using NServiceBus; using RDNameSpace; using System; using System.Collections.Generic; using System.Dynamic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace RD.Core.Client.Controllers { [Route("/")] public class HomeController : Controller { static int messagesSent; private readonly ILogger<HomeController> _log; private readonly IMessageSession _messageSession; public HomeController(IMessageSession messageSession, ILogger<HomeController> logger) { _messageSession = messageSession; _log = logger; } [HttpGet] public IActionResult Index() { return View(); } [HttpGet] public async Task<ActionResult> GetPlace() { string orderId = Guid.NewGuid().ToString().Substring(0, 8); var command = new ClientPublishCommand(); await _messageSession.Send(command).ConfigureAwait(false); _log.LogInformation($"Sending PlaceOrder, OrderId = {orderId}"); dynamic model = new ExpandoObject(); model.OrderId = orderId; model.MessagesSent = Interlocked.Increment(ref messagesSent); return View(model); } } } <file_sep>using Microsoft.Extensions.Configuration; using NServiceBus; using RD.Core.Messaging.Contracts.Commands; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RD.Core.Messaging { public abstract class BaseCommandHandler<T>: IHandleMessages<T> where T:BaseCommand { IBus Bus { get; set; } public IMessageHandlerContext bus; public BaseCommandHandler() { } public abstract Task Handle(T command); public Task Handle(T message, IMessageHandlerContext context) { bus = context; Handle(message); return Task.CompletedTask; } } public abstract class BaseSagaHandler<T, U> : Saga<T>,IAmStartedByMessages<U> where T:ContainSagaData,new() where U:BaseCommand { public abstract Task Handle(U command); public Task Handle(U message,IMessageHandlerContext context) { Handle(message); return Task.CompletedTask; } public abstract void ConfigureSagaFinder(SagaPropertyMapper<T> mapper); protected override void ConfigureHowToFindSaga(IConfigureHowToFindSagaWithMessage sagaMessageFindingConfiguration) { base.ConfigureHowToFindSaga(sagaMessageFindingConfiguration); } protected override void ConfigureHowToFindSaga(SagaPropertyMapper<T> mapper) { ConfigureSagaFinder(mapper); } } public class SagaData : ContainSagaData { public SagaData() { CreationDate = DateTime.Now; } public DateTime CreationDate { get; set; } } } <file_sep> using RD.Core.Messaging.Contracts.Commands; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ShareNameSpace { public class ClientPublishCommand : BaseCommand { public ClientPublishCommand() { Id = Guid.NewGuid(); } } } <file_sep>using Microsoft.Extensions.Hosting; using NServiceBus; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; namespace RD.Core.Messaging { public class NServiceBusService : IHostedService { public NServiceBusService(SessionAndConfigurationHolder holder) { this.holder = holder; } public async Task StartAsync(CancellationToken cancellationToken) { try { endpoint = await Endpoint.Start(holder.EndpointConfiguration) .ConfigureAwait(false); } catch (Exception e) { holder.StartupException = ExceptionDispatchInfo.Capture(e); return; } holder.MessageSession = endpoint; } public async Task StopAsync(CancellationToken cancellationToken) { try { if (endpoint != null) { await endpoint.Stop() .ConfigureAwait(false); } } finally { holder.MessageSession = null; holder.StartupException = null; } } public readonly SessionAndConfigurationHolder holder; public IEndpointInstance endpoint; } public class SessionAndConfigurationHolder { public SessionAndConfigurationHolder(EndpointConfiguration endpointConfiguration) { EndpointConfiguration = endpointConfiguration; } public EndpointConfiguration EndpointConfiguration { get; } public IMessageSession MessageSession { get; internal set; } public ExceptionDispatchInfo StartupException { get; internal set; } } } <file_sep>using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using NServiceBus; using RD.Core.Messaging; using SagaNameSpace; using ShareNameSpace; using System; using System.Collections.Generic; using System.Dynamic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace RD.Core.API.Controllers { [ApiController] [Route("[controller]")] public class WeatherForecastController : ControllerBase { static int messagesSent; private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; private readonly ILogger<WeatherForecastController> _logger; private readonly IBus _bus; public WeatherForecastController(IBus bus, ILogger<WeatherForecastController> logger) { _logger = logger; _bus = bus; } [HttpGet] public IEnumerable<WeatherForecast> Get() { var rng = new Random(); return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = rng.Next(-20, 55), Summary = Summaries[rng.Next(Summaries.Length)] }) .ToArray(); } [HttpPost("sendCommand")] public async Task<ActionResult> SendCommand() { string orderId = Guid.NewGuid().ToString().Substring(0, 8); var command = new ClientPublishCommand(); await _bus.Send(command); _logger.LogInformation($"Sending PlaceOrder, OrderId = {orderId}"); dynamic model = new ExpandoObject(); model.OrderId = orderId; model.MessagesSent = Interlocked.Increment(ref messagesSent); return Ok(); } [HttpPost("fireWorkflow")] public async Task<ActionResult> FireWorkflow() { string orderId = Guid.NewGuid().ToString().Substring(0, 8); var command = new SagaStartingCommand(); command.Id = Guid.NewGuid(); await _bus.Send(command); _logger.LogInformation($"Sending PlaceOrder, OrderId = {orderId}"); dynamic model = new ExpandoObject(); model.OrderId = orderId; model.MessagesSent = Interlocked.Increment(ref messagesSent); return Ok(command.Id); } [HttpPost("completeWorkflow/{id}")] public async Task<ActionResult> CompleteWorkflow(Guid id) { string orderId = Guid.NewGuid().ToString().Substring(0, 8); var command = new SagaCompleteCommand(); command.Id =id; await _bus.Send(command); _logger.LogInformation($"Sending PlaceOrder, OrderId = {orderId}"); dynamic model = new ExpandoObject(); model.OrderId = orderId; model.MessagesSent = Interlocked.Increment(ref messagesSent); return Ok(); } } } <file_sep>using NServiceBus; using RD.ConsumerService.SagaExample.Events; using RD.ConsumerService.SagaExample.SagaFlow; using RD.Core.Messaging; using SagaNameSpace; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RD.ConsumerService.SagaExample { public class SagaWorkflowSampleHandler :BaseSagaHandler<SagaDataSample,SagaStartingCommand> ,IHandleMessages<SagaCompleteCommand> { public Task Handle(SagaCompleteCommand message, IMessageHandlerContext context) { MarkAsComplete(); var eventCommand= new PublishSagaCompleteEvent(); eventCommand.Id = message.Id; context.Publish(eventCommand).Wait(); return Task.CompletedTask; } public override Task Handle(SagaStartingCommand command) { return Task.CompletedTask; } public override void ConfigureSagaFinder(SagaPropertyMapper<SagaDataSample> mapper) { mapper.ConfigureMapping<SagaStartingCommand>(message => message.Id).ToSaga(sagaData => sagaData.SagaIdentifier); mapper.ConfigureMapping<SagaCompleteCommand>(message => message.Id).ToSaga(sagaData => sagaData.SagaIdentifier); } } } <file_sep>using NServiceBus; using RD.Core.Messaging.Contracts.Events; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RD.Core.Messaging { public abstract class BaseEventHandler<T>: IHandleMessages<T> where T : BaseEvent { IBus Bus { get; set; } public IMessageHandlerContext bus; public BaseEventHandler() { } public abstract Task Handle(T @event); public Task Handle(T message, IMessageHandlerContext context) { bus = context; Handle(message); return Task.CompletedTask; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace RD.Core.Client.Configuration { public class NServiceBusSecret { public string EndpointHost { get; set; } public string DestinationEndpointHost { get; set; } } } <file_sep>using NServiceBus; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RD.Core.Contract.Commands { public abstract class BaseCommand:Command,ICommand { } } <file_sep>using NServiceBus; using RD.Core.Messaging.Contracts.Commands; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RD.Core.Messaging.Contracts.Messages { public abstract class BaseMessage:Command,IMessage { } } <file_sep>using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.OpenApi.Models; using NServiceBus; using SagaNameSpace; using RD.Core.Messaging; using ShareNameSpace; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using RD.Core.API.Controllers; using System.Threading; namespace RD.Core.API { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { var nserviceBusSecret = Configuration.GetSection(typeof(NServiceBusSecret).Name) .Get<NServiceBusSecret>(); Dictionary<string, KeyValuePair<Type, string>> keyValuePairs = new Dictionary<string, KeyValuePair<Type, string>>(); keyValuePairs.Add("ShareNameSpace", new KeyValuePair<Type, string>(typeof(ClientPublishCommand), nserviceBusSecret.DestinationEndpointHost)); keyValuePairs.Add("SagaNameSpace",new KeyValuePair<Type, string>(typeof(SagaStartingCommand), nserviceBusSecret.SagaEndpointHost)); services.AddNServiceBus(nserviceBusSecret.EndpointHost,keyValuePairs,nserviceBusSecret.RabbitConnectionInfo, "mongodb://localhost:27017"); services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "RD.Core.API", Version = "v1" }); }); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "RD.Core.API v1")); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } } <file_sep>using NServiceBus; using RD.Core.Messaging.Contracts.Commands; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RD.Core.Messaging.Contracts.Events { public abstract class BaseEvent:Command, IEvent { } } <file_sep>using NServiceBus; using RD.Core.Messaging; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RD.ConsumerService.SagaExample.SagaFlow { public class SagaDataSample:SagaData { public Guid SagaIdentifier { get; set; } } } <file_sep>using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using NServiceBus; using RD.ConsumerService.CommandExample; using RD.Core.Messaging; using System; using System.Threading.Tasks; namespace RD.ConsumerService.EventExample { public class NServiceBusSecret { public string EndpointHost { get; set; } public string DestinationEndpointHost { get; set; } public string RabbitConnectionInfo { get; set; } } class Program { static async Task Main(string[] args) { Console.Title = "EventHandler"; await CreateHostBuilder(args).RunConsoleAsync(); } public static IHostBuilder CreateHostBuilder(string[] args) { return Host.CreateDefaultBuilder(args).ConfigureAppConfiguration((hostContext, builder) => { builder.AddUserSecrets<NServiceBusSecret>(); }) .ConfigureServices((hostContext, services) => { var nservisBusSecret = hostContext.Configuration.GetSection(typeof(NServiceBusSecret).Name).Get<NServiceBusSecret>(); services.AddNServiceBusPublisherEvent(nservisBusSecret.EndpointHost,nservisBusSecret.RabbitConnectionInfo, "mongodb://localhost:27017/SagaDB"); services.AddScoped<IBus, Bus>(); }); } } } <file_sep>using NServiceBus; using RD.Core.Contract.Commands; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RD.Core.Contract.Messages { public class BaseMessage:Command,IMessage { } } <file_sep>using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using MongoDB.Driver; using NServiceBus; using RD.Core.Messaging; using System; using System.Threading; using System.Threading.Tasks; namespace RD.ConsumerService.CommandExample { public class ServiceBusHosted : NServiceBusService { public ServiceBusHosted(SessionAndConfigurationHolder sessionAndConfigurationHolder):base(sessionAndConfigurationHolder) { } public async Task Start(CancellationToken cancellationToken) { IServiceCollection services = new ServiceCollection(); services.AddScoped<IBaseService, BaseService>(); services.AddScoped<IExampleService, ExampleService>(); var startedEndPoint= EndpointWithExternallyManagedContainer.Create(holder.EndpointConfiguration, (NServiceBus.ObjectBuilder.IConfigureComponents)services); var provider=services.BuildServiceProvider(); await startedEndPoint.Start(provider); } } public class NServiceBusSecret { public string EndpointHost { get; set; } public string DestinationEndpointHost { get; set; } public string RabbitConnectionInfo { get; set; } } class Program { static async Task Main(string[] args) { Console.Title = "CommandHanlder"; await CreateHostBuilder(args).RunConsoleAsync(); } public static IHostBuilder CreateHostBuilder(string[] args) { return Host.CreateDefaultBuilder(args) .ConfigureAppConfiguration((hostContext, builder) => { builder.AddUserSecrets<NServiceBusSecret>(); }) .ConfigureServices((hostContext, services) => { var nservisBusSecret = hostContext.Configuration.GetSection(typeof(NServiceBusSecret).Name).Get<NServiceBusSecret>(); services.AddScoped<IExampleService, ExampleService>(); var endPointConfiguration = new EndpointConfiguration(nservisBusSecret.EndpointHost); endPointConfiguration.EnableInstallers(); endPointConfiguration.UsePersistence<MongoPersistence>().MongoClient(new MongoClient("mongodb://localhost:27017")).UseTransactions(false).DatabaseName("SagaDB"); endPointConfiguration.UseTransport<RabbitMQTransport>() .UseConventionalRoutingTopology() .ConnectionString(nservisBusSecret.RabbitConnectionInfo); //hostContext.Contains(c => //{ // c.Register(Component.For<Lazy<IMessageSession>>().Instance(((IStartableEndpointWithExternallyManagedContainer)_endpoint).MessageSession).LifestyleSingleton()); // // Resolve service // _service = c.Resolve<MyService>(); //}); var statrEndpoint = EndpointWithExternallyManagedServiceProvider.Create(endPointConfiguration, services); services.AddSingleton(p => statrEndpoint.MessageSession.Value); services.AddSingleton<IBus, Bus>(); var provider = services.BuildServiceProvider(); statrEndpoint.Start(provider).Wait(); // services.AddNServiceBusPublisherEvent(nservisBusSecret.EndpointHost, nservisBusSecret.RabbitConnectionInfo, "mongodb://localhost:27017"); }); } } } <file_sep>using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using RD.Core.Messaging; using System; using System.Threading.Tasks; namespace Test.EventTesting.Consumer { public class NServiceBusSecret { public string EndpointHost { get; set; } public string DestinationEndpointHost { get; set; } public string RabbitConnectionInfo { get; set; } } class Program { static async Task Main(string[] args) { Console.Title = "EventHandler"; await CreateHostBuilder(args).RunConsoleAsync(); } public static IHostBuilder CreateHostBuilder(string[] args) { return Host.CreateDefaultBuilder(args).ConfigureAppConfiguration((hostContext, builder) => { builder.AddUserSecrets<NServiceBusSecret>(); }) .ConfigureServices((hostContext, services) => { var nservisBusSecret = hostContext.Configuration.GetSection(typeof(NServiceBusSecret).Name).Get<NServiceBusSecret>(); services.AddNServiceBusPublisherEvent(nservisBusSecret.EndpointHost, nservisBusSecret.RabbitConnectionInfo); services.AddScoped<IBus, Bus>(); }); } } } <file_sep>using NServiceBus; using NServiceBus.Logging; using RD.ConsumerService.CommandExample; using RD.Core.Messaging; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RD.ConsumerService.EventExample { public class PublishCommandEventHandler : BaseEventHandler<PublishCommandEvent> { static readonly ILog log = LogManager.GetLogger<PublishCommandEventHandler>(); public override Task Handle(PublishCommandEvent message) { log.Info($"Event Message Receipt in 444444:{message.Id}"); return Task.CompletedTask; } } } <file_sep>using NServiceBus; using RD.Core.Contract.Commands; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RD.Core.Contract.Events { public abstract class BaseEvent:Command, IEvent { } } <file_sep>using Microsoft.Extensions.DependencyInjection; using NServiceBus; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace RD.Core.Client.Configuration { public static class AddNServiceBusCollections { public static IServiceCollection AddNServiceBus(this IServiceCollection services, string endPoint, Action<EndpointConfiguration> configuration) { var endPointConfiguration = new EndpointConfiguration(endPoint); configuration(endPointConfiguration); services.AddNServiceBus(endPointConfiguration); return services; } static IServiceCollection AddNServiceBus(this IServiceCollection services, EndpointConfiguration configuration) { services.AddSingleton(configuration); services.AddSingleton(new SessionAndConfigurationHolder(configuration)); services.AddHostedService<NServiceBusService>(); services.AddSingleton(provider => { var management = provider.GetService<SessionAndConfigurationHolder>(); if (management.MessageSession != null) { return management.MessageSession; } var timeout = TimeSpan.FromSeconds(30); if (!SpinWait.SpinUntil(() => management.MessageSession != null || management.StartupException != null, timeout)) { throw new TimeoutException($"Unable to resolve the message session within '{timeout.ToString()}'. If you are trying to resolve the session within hosted services it is encouraged to use `Lazy<IMessageSession>` instead of `IMessageSession` directly"); } management.StartupException?.Throw(); return management.MessageSession; }); services.AddSingleton(provider => new Lazy<IMessageSession>(provider.GetService<IMessageSession>)); return services; } } } <file_sep>using System; namespace ResearchAndDevelopment { public class Class1 { } } <file_sep>namespace RD.ConsumerService.CommandExample { public interface IExampleService<Example> { } }<file_sep>using RD.Core.Contract.Commands; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace RDNameSpace { public class ClientPublishCommand : ICommand { public Guid Id { get ; set ; } public ClientPublishCommand() { Id = Guid.NewGuid(); } } } <file_sep>using NServiceBus; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RD.Core.Messaging { public interface IBus: IMessageSession { } } <file_sep>using RD.Core.Messaging.Contracts.Events; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RD.ConsumerService.SagaExample.Events { public class PublishSagaCompleteEvent:BaseEvent { } }
28edc43d63b901df1f4500ef0ffa96c7fff64da3
[ "C#" ]
33
C#
sms7182/RD.Core
bbba46c74cb2e253f41d43db4ca041b2a0ba9860
73c3b8ac9d243968b21fcec1e8cad7c58381bd69
refs/heads/master
<repo_name>EntryDSM/Shuck<file_sep>/Dockerfile FROM mhart/alpine-node:12 WORKDIR /usr/src/app COPY package*.json ./ RUN npm install COPY . . EXPOSE 20800 CMD ["npm", "start"] <file_sep>/docker-deploy.sh echo "$DOCKER_PASS" | docker login -u "$DOCKER_USER" --password-stdin registry.entrydsm.hs.kr PACKAGE_VERSION=$(cat package.json \ | grep version \ | head -1 \ | awk -F: '{ print $2 }' \ | sed 's/[",]//g' \ | tr -d '[[:space:]]') docker build -t registry.entrydsm.hs.kr/shuck:${PACKAGE_VERSION} . docker tag registry.entrydsm.hs.kr/shuck:${PACKAGE_VERSION} registry.entrydsm.hs.kr/shuck:latest docker push registry.entrydsm.hs.kr/shuck:${PACKAGE_VERSION} docker push registry.entrydsm.hs.kr/shuck:latest exit
de5ecc2fbeaff265256af9bf9c76625f38d6a0e2
[ "Dockerfile", "Shell" ]
2
Dockerfile
EntryDSM/Shuck
33d9f3614566dcb4eb9ad507e13b78986b1baa88
59ac994717cc8f98c6d8310bc6f30621e5bb5a86
refs/heads/master
<repo_name>jhutarek/marble-arch<file_sep>/arch-intents/src/main/java/cz/jhutarek/marble/arch/intents/domain/IntentController.kt package cz.jhutarek.marble.arch.intents.domain interface IntentController { fun browse(url: String) }<file_sep>/app-example/src/main/java/cz/jhutarek/marble/example/main/di/MainModule.kt package cz.jhutarek.marble.example.main.di import cz.jhutarek.marble.arch.navigation.device.AndroidNavigationController import cz.jhutarek.marble.arch.navigation.system.NavigationActivityDelegate import cz.jhutarek.marble.example.main.system.MainActivity import cz.jhutarek.marblearch.R import dagger.Module import dagger.Provides import dagger.android.ContributesAndroidInjector import javax.inject.Singleton @Module(includes = [MainModule.AbstractMainModule::class]) class MainModule { @Module interface AbstractMainModule { @ContributesAndroidInjector fun mainActivity(): MainActivity } @Provides @Singleton fun navigationActivityDelegate(navigationController: AndroidNavigationController) = NavigationActivityDelegate(navigationController, R.id.navigationHostFragment) }<file_sep>/arch-usecase/src/main/java/cz/jhutarek/marble/arch/usecase/domain/UseCase.kt package cz.jhutarek.marble.arch.usecase.domain interface UseCase<in I, out O> { operator fun invoke(input: I): O } <file_sep>/arch-repository/src/main/java/cz/jhutarek/marble/arch/repository/data/Source.kt package cz.jhutarek.marble.arch.repository.data import io.reactivex.Maybe @Deprecated("Do not use, will be changed or removed") interface Source<in Q : Any, D : Any> { fun request(query: Q): Maybe<D> }<file_sep>/arch-mvvm/src/main/java/cz/jhutarek/marble/arch/mvvm/system/MarbleFragment.kt package cz.jhutarek.marble.arch.mvvm.system import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.annotation.CallSuper import androidx.fragment.app.Fragment import com.jakewharton.rxrelay2.BehaviorRelay import cz.jhutarek.marble.arch.log.infrastructure.logD import cz.jhutarek.marble.arch.mvvm.model.State import cz.jhutarek.marble.arch.mvvm.presentation.ViewModel import dagger.android.support.AndroidSupportInjection import io.reactivex.Observable import io.reactivex.android.schedulers.AndroidSchedulers.mainThread import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.Disposable import io.reactivex.rxkotlin.withLatestFrom import javax.inject.Inject // TODO test // TODO extract common parts with MarbleActivity abstract class MarbleFragment<M : ViewModel<S>, S : State> : Fragment() { @Inject protected lateinit var viewModel: M protected abstract val layoutResId: Int private var statesDisposable: Disposable? = null private var viewsDisposable: CompositeDisposable? = null private val isUpdatingViewRelay = BehaviorRelay.createDefault(false) final override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? = inflater.inflate(layoutResId, container, false) final override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) onInitializeViews() } @CallSuper override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) AndroidSupportInjection.inject(this) logD("Fragment created") } @CallSuper override fun onStart() { super.onStart() logD("Bind views") viewsDisposable = CompositeDisposable(onBindViews()) logD("Bind states") statesDisposable = onBindStates( viewModel.states .distinctUntilChanged() .observeOn(mainThread()) ) } @CallSuper override fun onStop() { super.onStop() logD("Unbind states") statesDisposable?.dispose() statesDisposable = null logD("Unbind views") viewsDisposable?.clear() viewsDisposable = null } protected open fun onInitializeViews() {} protected open fun onBindStates(states: Observable<S>): Disposable = Observable.never<Unit>().subscribe() protected open fun onBindViews(): List<Disposable> = listOf() protected fun Observable<S>.subscribeForViews(onValue: (S) -> Unit): Disposable = subscribe { isUpdatingViewRelay.accept(true) onValue(it) isUpdatingViewRelay.accept(false) } protected fun <T> Observable<T>.subscribeForViewModel(onValue: M.(event: T) -> Unit): Disposable = this.withLatestFrom(isUpdatingViewRelay) { event, isUpdatingView -> Pair(event, isUpdatingView) } .filter { !it.second } .map { it.first } .subscribe { onValue(viewModel, it) } }<file_sep>/arch-repository/build.gradle apply plugin: 'java-library' apply plugin: 'kotlin' apply plugin: 'com.github.dcendents.android-maven' group = 'com.github.jhutarek.marble-arch' dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" api 'io.reactivex.rxjava2:rxjava:2.2.2' implementation 'com.jakewharton.rxrelay2:rxrelay:2.0.0' testImplementation project(':test-specs') testImplementation 'org.junit.jupiter:junit-jupiter-api:5.3.1' testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.3.1' testImplementation 'io.kotlintest:kotlintest-runner-junit5:3.1.10' testImplementation 'io.kotlintest:kotlintest-assertions:3.1.10' testImplementation 'io.mockk:mockk:1.8.12' } <file_sep>/app-example/src/main/java/cz/jhutarek/marble/example/main/di/MainComponent.kt package cz.jhutarek.marble.example.main.di import android.content.Context import cz.jhutarek.marble.arch.application.di.MarbleApplicationComponent import cz.jhutarek.marble.arch.navigation.di.NavigationModule import cz.jhutarek.marble.arch.resources.di.StringsModule import cz.jhutarek.marble.example.current.di.CurrentWeatherModule import cz.jhutarek.marble.example.overview.di.OverviewModule import cz.jhutarek.marble.example.settings.di.SettingsModule import dagger.BindsInstance import dagger.Component import dagger.android.AndroidInjectionModule import dagger.android.support.AndroidSupportInjectionModule import javax.inject.Singleton @Singleton @Component( modules = [ AndroidInjectionModule::class, AndroidSupportInjectionModule::class, MainModule::class, CurrentWeatherModule::class, OverviewModule::class, SettingsModule::class, StringsModule::class, NavigationModule::class ] ) interface MainComponent : MarbleApplicationComponent { @Component.Builder interface Builder { @BindsInstance fun applicationContext(context: Context): Builder fun build(): MainComponent } }<file_sep>/arch-navigation/src/main/java/cz/jhutarek/marble/arch/navigation/system/NavigationActivityDelegate.kt package cz.jhutarek.marble.arch.navigation.system import android.app.Activity import android.os.Bundle import androidx.navigation.NavController import androidx.navigation.NavOptions import androidx.navigation.findNavController import cz.jhutarek.marble.arch.log.infrastructure.logD import cz.jhutarek.marble.arch.navigation.device.AndroidNavigationController import cz.jhutarek.marble.arch.navigation.model.Destination.Type.* import io.reactivex.disposables.Disposable import javax.inject.Inject import javax.inject.Singleton // TODO test @Singleton class NavigationActivityDelegate @Inject constructor( private val navigationController: AndroidNavigationController, private val navigationHostResId: Int ) { private var destinationsDisposable: Disposable? = null private var systemNavigationListener: NavController.OnNavigatedListener? = null fun onSupportNavigateUp(activity: Activity) = activity.findNavController(navigationHostResId).navigateUp() fun onStart(activity: Activity) { logD("Bind navigation destinations") val systemNavigationController = activity.findNavController(navigationHostResId) destinationsDisposable = navigationController.observeDestinationRequests().subscribe { when (it.type) { PUSH_ON_TOP -> systemNavigationController.navigate(it.id) POP_TO_PREVIOUS_INSTANCE -> systemNavigationController.navigate( it.id, Bundle.EMPTY, NavOptions.Builder() .setPopUpTo(it.id, true) .build() ) POP_ALL_THEN_PUSH -> systemNavigationController.navigate( it.id, Bundle.EMPTY, NavOptions.Builder() .setPopUpTo(systemNavigationController.graph.startDestination, true) .build() ) } } NavController.OnNavigatedListener { _, destination -> navigationController.notifyNavigationExecuted(destination.id) } .also { systemNavigationListener = it } .let { systemNavigationController.addOnNavigatedListener(it) } } fun onStop(activity: Activity) { logD("Unbind navigation destinations") destinationsDisposable?.dispose() destinationsDisposable = null systemNavigationListener?.let { activity.findNavController(navigationHostResId).removeOnNavigatedListener(it) } systemNavigationListener = null } }<file_sep>/arch-keyboard/src/test/java/cz/jhutarek/marble/arch/keyboard/domain/KeyboardUseCaseTest.kt package cz.jhutarek.marble.arch.keyboard.domain import cz.jhutarek.marble.test.infrastructure.InstancePerClassStringSpec import io.mockk.mockk import io.mockk.verify internal class KeyboardUseCaseHideKeyboardTest : InstancePerClassStringSpec({ val controller = mockk<KeyboardController>(relaxUnitFun = true) val hideKeyboard = KeyboardUseCase.HideKeyboard(controller) "use case should delegate hide keyboard action to controller" { hideKeyboard(Unit) verify { controller.hideKeyboard() } } })<file_sep>/arch-mvvm/src/main/java/cz/jhutarek/marble/arch/mvvm/system/ViewExtensions.kt package cz.jhutarek.marble.arch.mvvm.system import android.widget.EditText // TODO test var EditText.textString: String? get() = text?.toString() set(value) { if (value != text?.toString()) { val nullableSelectionStart = selectionStart.takeIf { it >= 0 && it < value?.length ?: 0 } setText(value) nullableSelectionStart?.let { setSelection(it) } } }<file_sep>/arch-repository/src/main/java/cz/jhutarek/marble/arch/repository/domain/Data.kt package cz.jhutarek.marble.arch.repository.domain sealed class Data<out T : Any> { object Loading : Data<Nothing>() { override fun toString() = "Loading" } object Empty : Data<Nothing>() { override fun toString() = "Empty" } data class Loaded<out T : Any>(val value: T) : Data<T>() data class Error(val error: Throwable) : Data<Nothing>() }<file_sep>/app-example/src/main/java/cz/jhutarek/marble/example/current/system/CurrentWeatherFragment.kt package cz.jhutarek.marble.example.current.system import androidx.core.view.isVisible import cz.jhutarek.marble.arch.mvvm.system.MarbleFragment import cz.jhutarek.marble.example.current.presentation.CurrentWeatherViewModel import cz.jhutarek.marblearch.R import io.reactivex.Observable import kotlinx.android.synthetic.main.current__current_weather_fragment.* class CurrentWeatherFragment : MarbleFragment<CurrentWeatherViewModel, CurrentWeatherViewModel.State>() { override val layoutResId = R.layout.current__current_weather_fragment override fun onBindStates(states: Observable<CurrentWeatherViewModel.State>) = states.subscribeForViews { progressBar.isVisible = it.loadingVisible emptyMessage.isVisible = it.emptyVisible dataGroup.isVisible = it.dataVisible errorMessage.isVisible = it.errorVisible errorMessage.text = it.error icon.setImageResource(it.descriptionIcon) timestamp.text = it.timestamp location.text = it.location temperature.text = it.temperature pressure.text = it.pressure description.text = it.descriptionText additionalInfo.text = it.additionalInfo } }<file_sep>/arch-mvvm/src/main/java/cz/jhutarek/marble/arch/mvvm/presentation/ViewModel.kt package cz.jhutarek.marble.arch.mvvm.presentation import com.jakewharton.rxrelay2.BehaviorRelay import cz.jhutarek.marble.arch.log.infrastructure.logI import cz.jhutarek.marble.arch.mvvm.model.State import io.reactivex.Observable // TODO test abstract class ViewModel<S : State>(defaultState: S) { protected val statesRelay: BehaviorRelay<S> = BehaviorRelay.createDefault(defaultState) val states: Observable<S> = statesRelay.hide().doOnNext { logI("$it") } protected fun BehaviorRelay<S>.accept(updater: (S) -> S) { accept(updater(value)) } }<file_sep>/arch-resources/src/main/java/cz/jhutarek/marble/arch/resources/device/AndroidStringsController.kt package cz.jhutarek.marble.arch.resources.device import android.content.Context import cz.jhutarek.marble.arch.resources.domain.StringsController import javax.inject.Inject import javax.inject.Singleton @Singleton class AndroidStringsController @Inject constructor( private val context: Context ) : StringsController { override fun getString(resId: Int): String = context.getString(resId) }<file_sep>/app-example/src/test/java/cz/jhutarek/marble/example/current/presentation/CurrentWeatherViewModelTest.kt package cz.jhutarek.marble.example.current.presentation import cz.jhutarek.marble.arch.repository.model.LegacyData import cz.jhutarek.marble.arch.resources.domain.StringsUseCase import cz.jhutarek.marble.test.infrastructure.InstancePerClassStringSpec import cz.jhutarek.marble.example.current.domain.CurrentWeatherUseCase import cz.jhutarek.marble.example.current.model.CurrentWeather import cz.jhutarek.marble.example.current.model.CurrentWeather.DescriptionCode.* import cz.jhutarek.marble.example.current.presentation.CurrentWeatherViewModel.State import cz.jhutarek.marblearch.R import io.kotlintest.data.forall import io.kotlintest.tables.row import io.mockk.every import io.mockk.mockk import io.mockk.verify import io.reactivex.Observable import org.threeten.bp.ZoneId import org.threeten.bp.ZonedDateTime import org.threeten.bp.format.DateTimeFormatter internal class CurrentWeatherViewModelTest : InstancePerClassStringSpec({ val error = IllegalStateException("error") val currentWeather = CurrentWeather( ZonedDateTime.of(2018, 10, 10, 10, 10, 10, 10, ZoneId.systemDefault()), "location", 15.6, 123.4, "description", UNKNOWN, 21.0, 180.0, ZonedDateTime.of(2018, 9, 9, 9, 9, 9, 9, ZoneId.systemDefault()), ZonedDateTime.of(2018, 11, 11, 11, 11, 11, 11, ZoneId.systemDefault()) ) val errorString = "error string: %s" val temperatureString = "temperature string: %.2f" val pressureString = "pressure string: %.2f" val windSpeedString = "wind speed string: %.2f" val windDirectionString = "wind direction string: %.2f" val sunriseString = "sunrise string: %s" val sunsetString = "sunset string: %s" val additionalInfoSeparatorString = " | " val observeCurrentWeather = mockk<CurrentWeatherUseCase.Observe> { every { this@mockk(any()) } returns Observable.never<LegacyData<Unit, CurrentWeather>>() } val getString = mockk<StringsUseCase.GetString> { every { this@mockk(R.string.current__error) } returns errorString every { this@mockk(R.string.current__temperature) } returns temperatureString every { this@mockk(R.string.current__pressure) } returns pressureString every { this@mockk(R.string.current__wind_speed) } returns windSpeedString every { this@mockk(R.string.current__wind_direction) } returns windDirectionString every { this@mockk(R.string.current__sunrise) } returns sunriseString every { this@mockk(R.string.current__sunset) } returns sunsetString every { this@mockk(R.string.current__additional_info_separator) } returns additionalInfoSeparatorString } "view model should execute observe use case in constructor" { CurrentWeatherViewModel(observeCurrentWeather, getString) verify { observeCurrentWeather(Unit) } } "view model should map repository emissions to states" { forall( row( State( loadingVisible = false, emptyVisible = true, error = null, errorVisible = false, dataVisible = false, timestamp = null, location = null, temperature = null, pressure = null, descriptionText = null, additionalInfo = null ), LegacyData.Empty(Unit) ), row( State( loadingVisible = true, emptyVisible = false, error = null, errorVisible = false, dataVisible = false, timestamp = null, location = null, temperature = null, pressure = null, descriptionText = null, additionalInfo = null ), LegacyData.Loading(Unit) ), row( State( loadingVisible = false, emptyVisible = false, error = errorString.format(error.toString()), errorVisible = true, dataVisible = false, timestamp = null, location = null, temperature = null, pressure = null, descriptionText = null, additionalInfo = null ), LegacyData.Error(Unit, error) ), row( State( loadingVisible = false, emptyVisible = false, error = null, errorVisible = false, dataVisible = true, timestamp = currentWeather.timestamp?.format(DateTimeFormatter.ofPattern("dd. LLLL H:mm")), location = currentWeather.location, temperature = temperatureString.format(currentWeather.temperatureCelsius), pressure = pressureString.format(currentWeather.pressureMilliBar), descriptionText = currentWeather.descriptionText?.capitalize(), additionalInfo = listOf( windSpeedString.format(currentWeather.windSpeedKmph), windDirectionString.format(currentWeather.windDirectionDegrees), currentWeather.sunriseTimestamp?.format(DateTimeFormatter.ofPattern("H:mm"))?.let { sunriseString.format(it) }, currentWeather.sunsetTimestamp?.format(DateTimeFormatter.ofPattern("H:mm"))?.let { sunsetString.format(it) } ).joinToString(separator = additionalInfoSeparatorString) ), LegacyData.Loaded(Unit, currentWeather) ) ) { expectedState, data -> every { observeCurrentWeather(Unit) } returns Observable.just(data) CurrentWeatherViewModel(observeCurrentWeather, getString).states .test() .assertValue(expectedState) } } "view model should map description codes to icons" { forall( row(R.drawable.ic_clear, CLEAR), row(R.drawable.ic_fog, FOG), row(R.drawable.ic_few_clouds, FEW_CLOUDS), row(R.drawable.ic_scattered_clouds, SCATTERED_CLOUDS), row(R.drawable.ic_overcast_clouds, OVERCAST_CLOUDS), row(R.drawable.ic_drizzle, DRIZZLE), row(R.drawable.ic_light_rain, LIGHT_RAIN), row(R.drawable.ic_heavy_rain, HEAVY_RAIN), row(R.drawable.ic_snow, SNOW), row(R.drawable.ic_thunderstorm, THUNDERSTORM), row(R.drawable.ic_unknown, UNKNOWN) ) { expectedResId, descriptionCode -> every { observeCurrentWeather(Unit) } returns Observable.just(LegacyData.Loaded(Unit, currentWeather.copy(descriptionCode = descriptionCode))) CurrentWeatherViewModel(observeCurrentWeather, getString).states .test() .assertValue { it.descriptionIcon == expectedResId } } } })<file_sep>/README.md # marble-arch TODO ## Design notes - MVVM * Do not hide `Observable`s and other reactive types for more flexibility (user of the API might want to modify the stream before subscribing with our methods). * In lambdas, `it` should be "small" event or value, `this` should be "big" receiver like ViewModel. <file_sep>/arch-repository/src/main/java/cz/jhutarek/marble/arch/repository/domain/Repository.kt package cz.jhutarek.marble.arch.repository.domain import cz.jhutarek.marble.arch.repository.model.LegacyData import io.reactivex.Completable import io.reactivex.Observable @Deprecated("Do not use, will be changed or removed") interface Repository<Q : Any, D : Any> { fun observe(): Observable<LegacyData<Q, D>> fun load(query: Q) // TODO return Completable fun update(query: Q) // TODO return Completable fun clearCaches(query: Q? = null): Completable }<file_sep>/app-example/src/main/java/cz/jhutarek/marble/example/settings/system/SettingsFragment.kt package cz.jhutarek.marble.example.settings.system import cz.jhutarek.marble.arch.mvvm.system.MarbleFragment import cz.jhutarek.marble.example.settings.presentation.SettingsViewModel import cz.jhutarek.marblearch.R class SettingsFragment : MarbleFragment<SettingsViewModel, SettingsViewModel.State>() { override val layoutResId = R.layout.settings__settings_fragment }<file_sep>/arch-resources/src/test/java/cz/jhutarek/marble/arch/resources/device/AndroidStringsControllerTest.kt package cz.jhutarek.marble.arch.resources.device import android.content.Context import cz.jhutarek.marble.test.infrastructure.InstancePerClassStringSpec import io.kotlintest.shouldBe import io.mockk.every import io.mockk.mockk import io.mockk.verify internal class AndroidStringsControllerTest : InstancePerClassStringSpec({ val string = "any string" val resId = 123 val context = mockk<Context>() val controller = AndroidStringsController(context) "controller should invoke string method on context" { every { context.getString(any()) } returns string controller.getString(resId) verify { context.getString(resId) } } "controller should return string from context" { every { context.getString(any()) } returns string controller.getString(resId) shouldBe string } })<file_sep>/arch-repository/src/main/java/cz/jhutarek/marble/arch/repository/model/LegacyData.kt package cz.jhutarek.marble.arch.repository.model @Deprecated("Do not use, will be changed or removed") sealed class LegacyData<out Q : Any, out T : Any> { abstract val query: Q abstract fun <R : Any> mapQuery(mapper: (Q) -> R): LegacyData<R, T> // TODO test data class Loading<out Q : Any>(override val query: Q) : LegacyData<Q, Nothing>() { override fun <R : Any> mapQuery(mapper: (Q) -> R) = Loading(mapper(query)) } // TODO test data class Empty<out Q : Any>(override val query: Q) : LegacyData<Q, Nothing>() { override fun <R : Any> mapQuery(mapper: (Q) -> R) = Empty(mapper(query)) } // TODO test data class Loaded<out Q : Any, out T : Any>(override val query: Q, val value: T) : LegacyData<Q, T>() { override fun <R : Any> mapQuery(mapper: (Q) -> R) = Loaded(mapper(query), value) } // TODO test data class Error<out Q : Any>(override val query: Q, val error: Throwable) : LegacyData<Q, Nothing>() { override fun <R : Any> mapQuery(mapper: (Q) -> R) = Error(mapper(query), error) } }<file_sep>/arch-repository/src/main/java/cz/jhutarek/marble/arch/repository/data/Cache.kt package cz.jhutarek.marble.arch.repository.data import io.reactivex.Completable @Deprecated("Do not use, will be changed or removed") interface Cache<in Q : Any, D : Any> : Source<Q, D> { fun store(query: Q, data: D): Completable fun clear(query: Q? = null): Completable }<file_sep>/test-rx/src/main/java/cz/jhutarek/marble/test/infrastructure/RxTestListener.kt package cz.jhutarek.marble.test.infrastructure import io.kotlintest.Description import io.kotlintest.Spec import io.kotlintest.extensions.TestListener import io.reactivex.android.plugins.RxAndroidPlugins import io.reactivex.plugins.RxJavaPlugins import io.reactivex.schedulers.Schedulers object RxTestListener : TestListener { override fun beforeSpec(description: Description, spec: Spec) { RxJavaPlugins.setComputationSchedulerHandler { Schedulers.trampoline() } RxJavaPlugins.setIoSchedulerHandler { Schedulers.trampoline() } RxJavaPlugins.setSingleSchedulerHandler { Schedulers.trampoline() } RxAndroidPlugins.setMainThreadSchedulerHandler { Schedulers.trampoline() } } override fun afterSpec(description: Description, spec: Spec) { RxJavaPlugins.reset() RxAndroidPlugins.reset() } }<file_sep>/app-example/src/main/java/cz/jhutarek/marble/example/main/system/MainApplication.kt package cz.jhutarek.marble.example.main.system import com.jakewharton.threetenabp.AndroidThreeTen import cz.jhutarek.marble.arch.application.system.MarbleApplication import cz.jhutarek.marble.example.main.di.DaggerMainComponent import cz.jhutarek.marblearch.BuildConfig class MainApplication : MarbleApplication() { override val isDebug = BuildConfig.DEBUG override fun onCreateComponent() = DaggerMainComponent.builder() .applicationContext(applicationContext) .build() override fun onInitialize() { AndroidThreeTen.init(this) } }<file_sep>/arch-resources/src/main/java/cz/jhutarek/marble/arch/resources/domain/StringsController.kt package cz.jhutarek.marble.arch.resources.domain interface StringsController { fun getString(resId: Int): String }<file_sep>/app-example/src/main/java/cz/jhutarek/marble/example/main/system/MainActivity.kt package cz.jhutarek.marble.example.main.system import cz.jhutarek.marble.arch.mvvm.system.MarbleActivity import cz.jhutarek.marble.arch.navigation.system.NavigationActivityDelegate import cz.jhutarek.marble.example.main.presentation.MainViewModel import cz.jhutarek.marblearch.R import javax.inject.Inject class MainActivity : MarbleActivity<MainViewModel, MainViewModel.State>() { @Inject internal lateinit var navigationDelegate: NavigationActivityDelegate override val layoutResId = R.layout.main__main_activity override fun onStart() { super.onStart() navigationDelegate.onStart(this) } override fun onStop() { super.onStop() navigationDelegate.onStop(this) } override fun onSupportNavigateUp() = navigationDelegate.onSupportNavigateUp(this) } <file_sep>/test-specs/src/main/java/cz/jhutarek/marble/test/infrastructure/InstancePerClassStringSpec.kt package cz.jhutarek.marble.test.infrastructure import io.kotlintest.extensions.TestListener import io.kotlintest.specs.AbstractStringSpec import io.kotlintest.specs.StringSpec abstract class InstancePerClassStringSpec( spec: AbstractStringSpec.() -> Unit = {}, private val listeners: List<TestListener> = listOf() ) : StringSpec(spec) { final override fun isInstancePerTest() = true final override fun listeners() = listeners }<file_sep>/arch-log/src/main/java/cz/jhutarek/marble/arch/log/infrastructure/Logger.kt package cz.jhutarek.marble.arch.log.infrastructure import timber.log.Timber object Logger { private class TagPrefixDebugTree(private val tagPrefix: String) : Timber.DebugTree() { override fun log(priority: Int, tag: String?, message: String, throwable: Throwable?) = super.log(priority, tagPrefix + tag, message, throwable) } fun initialize(isDebug: Boolean, tagPrefix: String) { if (isDebug) Timber.plant(TagPrefixDebugTree(tagPrefix)) } } fun <T : Any> T.logD(message: String) = log(message) { Timber.d(it) } fun <T : Any> T.logI(message: String) = log(message) { Timber.i(it) } fun <T : Any> T.logW(message: String) = log(message) { Timber.w(it) } fun <T : Any> T.logE(message: String) = log(message) { Timber.e(it) } private fun <T : Any> T.log(message: String, block: (String) -> Unit) { Timber.tag(this::class.java.simpleName) block(message) }<file_sep>/app-example/src/main/java/cz/jhutarek/marble/example/current/data/CurrentWeatherMemoryCache.kt package cz.jhutarek.marble.example.current.data import cz.jhutarek.marble.arch.repository.data.Cache import cz.jhutarek.marble.example.current.domain.CurrentWeatherRepository import cz.jhutarek.marble.example.current.model.CurrentWeather import io.reactivex.Completable import io.reactivex.Maybe import org.threeten.bp.Duration import javax.inject.Inject import javax.inject.Singleton // TODO add system time device (controller + usecase) // TODO extract base classes // TODO test @Singleton class CurrentWeatherMemoryCache @Inject constructor() : Cache<CurrentWeatherRepository.Query, CurrentWeather> { private data class TimestampedCurrentWeather(val timestamp: Long, val currentWeather: CurrentWeather) private val timeToLive = Duration.ofSeconds(30) private val values = mutableMapOf<CurrentWeatherRepository.Query, TimestampedCurrentWeather>() override fun request(query: CurrentWeatherRepository.Query): Maybe<CurrentWeather> = Maybe.fromCallable<CurrentWeather> { values[query]?.let { if (Duration.ofMillis(it.timestamp).plus(timeToLive).minusMillis(System.currentTimeMillis()) > Duration.ZERO) { it.currentWeather } else { values.remove(query) null } } } override fun store(query: CurrentWeatherRepository.Query, data: CurrentWeather): Completable = Completable.fromAction { values[query] = TimestampedCurrentWeather(System.currentTimeMillis(), data) } override fun clear(query: CurrentWeatherRepository.Query?): Completable = Completable.fromAction { values.clear() } }<file_sep>/app-example/src/test/java/cz/jhutarek/marble/example/overview/presentation/OverviewViewModelTest.kt package cz.jhutarek.marble.example.overview.presentation import cz.jhutarek.marble.arch.navigation.domain.NavigationUseCase import cz.jhutarek.marble.arch.repository.model.LegacyData import cz.jhutarek.marble.test.infrastructure.InstancePerClassStringSpec import cz.jhutarek.marble.example.current.domain.CurrentWeatherUseCase import cz.jhutarek.marble.example.current.domain.CurrentWeatherUseCase.Load import cz.jhutarek.marble.example.current.model.CurrentWeather import cz.jhutarek.marblearch.R import io.kotlintest.data.forall import io.kotlintest.tables.row import io.mockk.every import io.mockk.mockk import io.mockk.verify import io.reactivex.Observable internal class OverviewViewModelTest : InstancePerClassStringSpec({ val location = "location" val currentWeather = mockk<CurrentWeather> { every { this@mockk.location } returns location } val error = IllegalStateException() val input = "any input" val observe = mockk<CurrentWeatherUseCase.Observe> { every { this@mockk(Unit) } returns Observable.never() } val loadCurrentWeather = mockk<CurrentWeatherUseCase.Load>(relaxUnitFun = true) val navigate = mockk<NavigationUseCase.Navigate>(relaxUnitFun = true) "view model should execute observe use case in constructor" { OverviewViewModel(observe, loadCurrentWeather, navigate) verify { observe(Unit) } } "view model should map observed data to refresh enabled state" { forall( row(true, LegacyData.Empty(Unit)), row(false, LegacyData.Loading(Unit)), row(true, LegacyData.Loaded(Unit, currentWeather)), row(true, LegacyData.Error(Unit, error)) ) { expectedEnabled, data -> every { observe(Unit) } returns Observable.just(data) OverviewViewModel(observe, loadCurrentWeather, navigate).states .test() .assertValueAt(0) { it.refreshEnabled == expectedEnabled } } } "view model should map observed data to input state when loaded" { every { observe(Unit) } returns Observable.just(LegacyData.Loaded(Unit, currentWeather)) OverviewViewModel(observe, loadCurrentWeather, navigate).states .test() .assertValueAt(0) { it.input == location } } "view model should execute load current weather use case on refresh with current input" { OverviewViewModel(observe, loadCurrentWeather, navigate).apply { setInput(input) refresh() } verify { loadCurrentWeather(Load.ByCity(input)) } } "view model should update input when set" { val viewModel = OverviewViewModel(observe, loadCurrentWeather, navigate) val testObserver = viewModel.states.test() viewModel.setInput(input) testObserver.assertValueAt(1) { it.input == input } } "view model should navigate to settings" { val viewModel = OverviewViewModel(observe, loadCurrentWeather, navigate) viewModel.showSettings() verify { navigate(R.id.navigation__settings) } } })<file_sep>/arch-navigation/src/main/java/cz/jhutarek/marble/arch/navigation/device/AndroidNavigationController.kt package cz.jhutarek.marble.arch.navigation.device import com.jakewharton.rxrelay2.PublishRelay import cz.jhutarek.marble.arch.log.infrastructure.logD import cz.jhutarek.marble.arch.log.infrastructure.logI import cz.jhutarek.marble.arch.navigation.domain.NavigationController import cz.jhutarek.marble.arch.navigation.model.Destination import io.reactivex.Observable import java.util.concurrent.TimeUnit.MILLISECONDS import javax.inject.Inject import javax.inject.Singleton @Singleton class AndroidNavigationController @Inject constructor( /** * Android NavController invokes its listener for every popped destination, however we don't want to listen to each of those changes * (we want just the "final", settled destination). * This delay is used to fine-tune the debounce limit after which we proclaim the destination to be settled. * Setting it too high will result in visible UI delay, setting it too low might cause unwanted emissions. */ private val destinationsDebounceLimitMillis: Long = 20 ) : NavigationController { private val destinationRequestsRelay = PublishRelay.create<Destination>() private val observeRelay = PublishRelay.create<Int>() fun observeDestinationRequests(): Observable<Destination> = destinationRequestsRelay.hide() override fun observe(): Observable<Int> = observeRelay .hide() .debounce(destinationsDebounceLimitMillis, MILLISECONDS) override fun navigate(destination: Destination) { logI("Navigate to: $destination") destinationRequestsRelay.accept(destination) } fun notifyNavigationExecuted(destinationId: Int) { logD("Notify navigation executed: $destinationId") observeRelay.accept(destinationId) } }<file_sep>/app-example/src/main/java/cz/jhutarek/marble/example/overview/presentation/OverviewViewModel.kt package cz.jhutarek.marble.example.overview.presentation import cz.jhutarek.marble.arch.log.infrastructure.logI import cz.jhutarek.marble.arch.mvvm.presentation.ViewModel import cz.jhutarek.marble.arch.navigation.domain.NavigationUseCase import cz.jhutarek.marble.arch.repository.model.LegacyData import cz.jhutarek.marble.example.current.domain.CurrentWeatherUseCase import cz.jhutarek.marble.example.current.domain.CurrentWeatherUseCase.Load.ByCity import cz.jhutarek.marblearch.R import javax.inject.Inject import javax.inject.Singleton import cz.jhutarek.marble.arch.mvvm.model.State as MarbleState @Singleton class OverviewViewModel @Inject constructor( observeCurrentWeather: CurrentWeatherUseCase.Observe, private val loadCurrentWeather: CurrentWeatherUseCase.Load, private val navigate: NavigationUseCase.Navigate ) : ViewModel<OverviewViewModel.State>(State()) { data class State( val input: String? = null, val refreshEnabled: Boolean = true ) : MarbleState init { observeCurrentWeather(Unit) .map { State( input = if (it is LegacyData.Loaded) it.value.location else statesRelay.value.input, refreshEnabled = it is LegacyData.Empty || it is LegacyData.Loaded || it is LegacyData.Error ) } .subscribe(statesRelay) } fun refresh() { logI("Refresh") loadCurrentWeather(ByCity(statesRelay.value.input.orEmpty())) } fun showSettings() { logI("Show settings") navigate(R.id.navigation__settings) } fun setInput(input: CharSequence) { logI("Input: $input") statesRelay.accept { it.copy(input = input.toString()) } } }<file_sep>/arch-keyboard/src/main/java/cz/jhutarek/marble/arch/keyboard/device/AndroidKeyboardController.kt package cz.jhutarek.marble.arch.keyboard.device import com.jakewharton.rxrelay2.PublishRelay import cz.jhutarek.marble.arch.keyboard.domain.KeyboardController import cz.jhutarek.marble.arch.log.infrastructure.logI import io.reactivex.Observable import javax.inject.Inject import javax.inject.Singleton @Singleton class AndroidKeyboardController @Inject constructor() : KeyboardController { private val keyboardHidesRelay = PublishRelay.create<Unit>() fun observeKeyboardHides(): Observable<Unit> = keyboardHidesRelay.hide() override fun hideKeyboard() { logI("Hide keyboard") keyboardHidesRelay.accept(Unit) } }<file_sep>/arch-mvvm/src/main/java/cz/jhutarek/marble/arch/mvvm/system/Mvvm.kt package cz.jhutarek.marble.arch.mvvm.system import android.os.Looper.getMainLooper import cz.jhutarek.marble.arch.log.infrastructure.logD import io.reactivex.android.plugins.RxAndroidPlugins import io.reactivex.android.schedulers.AndroidSchedulers object Mvvm { fun initialize() { // TODO confirm that this is working: https://medium.com/@sweers/rxandroids-new-async-api-4ab5b3ad3e93 RxAndroidPlugins.setInitMainThreadSchedulerHandler { AndroidSchedulers.from(getMainLooper(), true) } logD("Initialized MVVM") } }<file_sep>/arch-keyboard/src/main/java/cz/jhutarek/marble/arch/keyboard/domain/KeyboardController.kt package cz.jhutarek.marble.arch.keyboard.domain interface KeyboardController { fun hideKeyboard() }<file_sep>/arch-intents/build.gradle apply plugin: 'com.android.library' apply plugin: 'kotlin-android' apply plugin: 'com.github.dcendents.android-maven' apply plugin: 'de.mobilej.unmock' group = 'com.github.jhutarek.marble-arch' android { compileSdkVersion 28 defaultConfig { minSdkVersion 21 targetSdkVersion 28 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" api project(':arch-usecase') implementation project(':arch-log') implementation 'com.google.dagger:dagger:2.19' testImplementation project(':test-specs') testImplementation 'org.junit.jupiter:junit-jupiter-api:5.3.1' testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.3.1' testImplementation 'io.kotlintest:kotlintest-runner-junit5:3.1.10' testImplementation 'io.kotlintest:kotlintest-assertions:3.1.10' testImplementation 'io.mockk:mockk:1.8.12' unmock 'org.robolectric:android-all:4.3_r2-robolectric-0' } unMock { keepStartingWith "android.content." keep "android.view.CompatibilityInfoHolder" keep "android.net.Uri" keepStartingWith "libcore." keepAndRename "java.nio.charset.Charsets" to "xjava.nio.charset.Charsets" }<file_sep>/arch-keyboard/src/main/java/cz/jhutarek/marble/arch/keyboard/system/KeyboardActivityDelegate.kt package cz.jhutarek.marble.arch.keyboard.system import android.app.Activity import android.app.Activity.INPUT_METHOD_SERVICE import android.view.View import android.view.inputmethod.InputMethodManager import cz.jhutarek.marble.arch.keyboard.device.AndroidKeyboardController import cz.jhutarek.marble.arch.log.infrastructure.logD import io.reactivex.disposables.Disposable import javax.inject.Inject import javax.inject.Singleton @Singleton class KeyboardActivityDelegate @Inject constructor( private val androidKeyboardController: AndroidKeyboardController, private val rootViewResId: Int ) { private var keyboardHidesDisposable: Disposable? = null fun onStart(activity: Activity) { logD("Bind keyboard activity delegate") keyboardHidesDisposable = androidKeyboardController.observeKeyboardHides().subscribe { val inputMethodManager = activity.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager inputMethodManager.hideSoftInputFromWindow(activity.findViewById<View>(rootViewResId).windowToken, 0) } } fun onStop() { logD("Unbind keyboard activity delegate") keyboardHidesDisposable?.dispose() keyboardHidesDisposable = null } }<file_sep>/arch-repository/src/main/java/cz/jhutarek/marble/arch/repository/data/BaseRepository.kt package cz.jhutarek.marble.arch.repository.data import com.jakewharton.rxrelay2.PublishRelay import cz.jhutarek.marble.arch.repository.domain.Repository import cz.jhutarek.marble.arch.repository.model.LegacyData import io.reactivex.Completable import io.reactivex.Maybe import io.reactivex.Observable @Deprecated("Do not use, will be changed or removed") abstract class BaseRepository<Q : Any, D : Any>( source: Source<Q, D>, private vararg val caches: Cache<Q, D> ) : Repository<Q, D> { private data class IndexedResult<out D : Any>(val index: Int, val value: D) private val allSources = caches.toList() + source private val relay = PublishRelay.create<LegacyData<Q, D>>() final override fun observe(): Observable<LegacyData<Q, D>> = relay.hide().distinctUntilChanged() final override fun load(query: Q) { allSources .mapIndexed { index, source -> source.request(query) .map { result -> IndexedResult(index, result) } } .let { Maybe.concat(it) } .firstElement() .flatMap { storeValueInCaches(query, it) } .map { LegacyData.Loaded(query, it) as LegacyData<Q, D> } .toSingle(LegacyData.Empty(query)) .toObservable() .startWith(LegacyData.Loading(query)) .onErrorReturn { LegacyData.Error(query, it) } .subscribe(relay) } final override fun update(query: Q) { Completable.concat( listOf( clearCaches(query), Completable.fromAction { load(query) } ) ) .toObservable<LegacyData<Q, D>>() .startWith(LegacyData.Loading(query)) .onErrorReturn { LegacyData.Error(query, it) } .subscribe(relay) } final override fun clearCaches(query: Q?): Completable = Completable.merge(caches.map { it.clear(query) }) .toObservable<Unit>() .ignoreElements() private fun storeValueInCaches(query: Q, indexedResult: IndexedResult<D>): Maybe<D> = Completable.merge( allSources .take(indexedResult.index) .filterIsInstance<Cache<Q, D>>() .map { it.store(query, indexedResult.value) } ) .toSingle { indexedResult.value } .toMaybe() }<file_sep>/arch-resources/src/test/java/cz/jhutarek/marble/arch/resources/domain/StringsUseCaseTest.kt package cz.jhutarek.marble.arch.resources.domain import cz.jhutarek.marble.test.infrastructure.InstancePerClassStringSpec import io.kotlintest.shouldBe import io.mockk.every import io.mockk.mockk import io.mockk.verify internal class StringsUseCaseTest : InstancePerClassStringSpec({ val string = "any string" val resId = 123 val controller = mockk<StringsController> { every { getString(any()) } returns string } val getString = StringsUseCase.GetString(controller) "use case should invoke strings controller" { getString(resId) verify { controller.getString(123) } } "use case should return string from controller" { getString(resId) shouldBe string } })<file_sep>/arch-repository/src/main/java/cz/jhutarek/marble/arch/repository/model/DataObservableExtensions.kt package cz.jhutarek.marble.arch.repository.model import io.reactivex.Observable // TODO test @Deprecated("Do not use, will be changed or removed") fun <Q : Any, T : Any, R : Any> Observable<LegacyData<Q, T>>.mapQuery(mapper: (Q) -> R): Observable<LegacyData<R, T>> = map { it.mapQuery(mapper) }<file_sep>/arch-keyboard/src/test/java/cz/jhutarek/marble/arch/keyboard/device/AndroidKeyboardControllerTest.kt package cz.jhutarek.marble.arch.keyboard.device import cz.jhutarek.marble.test.infrastructure.InstancePerClassStringSpec internal class AndroidKeyboardControllerTest : InstancePerClassStringSpec({ val controller = AndroidKeyboardController() "observe hides should not have default value" { controller.observeKeyboardHides() .test() .assertNoValues() .assertNotComplete() } "observe hides should emit value after hide keyboard" { val testObserver = controller.observeKeyboardHides().test() controller.hideKeyboard() testObserver.assertValue(Unit) } })<file_sep>/arch-intents/src/main/java/cz/jhutarek/marble/arch/intents/domain/IntentUseCase.kt package cz.jhutarek.marble.arch.intents.domain import cz.jhutarek.marble.arch.usecase.domain.UseCase import javax.inject.Inject import javax.inject.Singleton sealed class IntentUseCase<in I, out O> : UseCase<I, O> { @Singleton class Browse @Inject constructor(private val intentController: IntentController) : IntentUseCase<String, Unit>() { override fun invoke(input: String) = intentController.browse(input) } } <file_sep>/arch-resources/src/main/java/cz/jhutarek/marble/arch/resources/di/StringsModule.kt package cz.jhutarek.marble.arch.resources.di import cz.jhutarek.marble.arch.resources.device.AndroidStringsController import cz.jhutarek.marble.arch.resources.domain.StringsController import dagger.Binds import dagger.Module @Module interface StringsModule { @Binds fun stringsController(controller: AndroidStringsController): StringsController }<file_sep>/arch-usecase/build.gradle apply plugin: 'java-library' apply plugin: 'kotlin' apply plugin: 'com.github.dcendents.android-maven' group = 'com.github.jhutarek.marble-arch' dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" api 'io.reactivex.rxjava2:rxjava:2.2.2' } <file_sep>/arch-keyboard/src/main/java/cz/jhutarek/marble/arch/keyboard/di/KeyboardModule.kt package cz.jhutarek.marble.arch.keyboard.di import cz.jhutarek.marble.arch.keyboard.device.AndroidKeyboardController import cz.jhutarek.marble.arch.keyboard.domain.KeyboardController import dagger.Binds import dagger.Module @Module interface KeyboardModule { @Binds fun keyboardController(androidKeyboardController: AndroidKeyboardController): KeyboardController }<file_sep>/app-example/src/test/java/cz/jhutarek/marble/example/current/domain/CurrentWeatherUseCaseTest.kt package cz.jhutarek.marble.example.current.domain import cz.jhutarek.marble.arch.repository.model.LegacyData import cz.jhutarek.marble.test.infrastructure.InstancePerClassStringSpec import cz.jhutarek.marble.example.current.domain.CurrentWeatherRepository.Query import cz.jhutarek.marble.example.current.domain.CurrentWeatherUseCase.Load import cz.jhutarek.marble.example.current.domain.CurrentWeatherUseCase.Observe import cz.jhutarek.marble.example.current.model.CurrentWeather import io.mockk.every import io.mockk.mockk import io.mockk.verify import io.reactivex.Observable internal class ObserveUseCaseTest : InstancePerClassStringSpec({ val repository = mockk<CurrentWeatherRepository>() val city = "any city" val repositoryData: LegacyData<CurrentWeatherRepository.Query, CurrentWeather> = LegacyData.Loading(Query(city)) val expectedMappedData = LegacyData.Loading(Unit) val observe = Observe(repository) "use case should execute observe on repository" { every { repository.observe() } returns Observable.never() observe(Unit) verify { repository.observe() } } "use case should return mapped observable from repository" { every { repository.observe() } returns Observable.just(repositoryData) observe(Unit) .test() .assertValue(expectedMappedData) } }) internal class LoadUseCaseTest : InstancePerClassStringSpec({ val repository = mockk<CurrentWeatherRepository>(relaxUnitFun = true) val byCity = Load.ByCity("any city") val load = Load(repository) "use case should execute load on repository" { load(byCity) verify { repository.load(Query(byCity.city)) } } })<file_sep>/arch-keyboard/src/main/java/cz/jhutarek/marble/arch/keyboard/domain/KeyboardUseCase.kt package cz.jhutarek.marble.arch.keyboard.domain import cz.jhutarek.marble.arch.usecase.domain.UseCase import javax.inject.Inject import javax.inject.Singleton sealed class KeyboardUseCase<in I, out O> : UseCase<I, O> { @Singleton class HideKeyboard @Inject constructor(private val keyboardController: KeyboardController) : KeyboardUseCase<Unit, Unit>() { override fun invoke(input: Unit) { keyboardController.hideKeyboard() } } }<file_sep>/app-example/src/main/java/cz/jhutarek/marble/example/settings/presentation/SettingsViewModel.kt package cz.jhutarek.marble.example.settings.presentation import cz.jhutarek.marble.arch.mvvm.presentation.ViewModel import javax.inject.Inject import javax.inject.Singleton import cz.jhutarek.marble.arch.mvvm.model.State as MarbleState @Singleton class SettingsViewModel @Inject constructor() : ViewModel<SettingsViewModel.State>(State()) { class State : MarbleState // TODO }<file_sep>/arch-navigation/src/test/java/cz/jhutarek/marble/arch/navigation/device/AndroidNavigationControllerTest.kt package cz.jhutarek.marble.arch.navigation.device import cz.jhutarek.marble.arch.navigation.model.Destination import cz.jhutarek.marble.arch.navigation.model.Destination.Type.POP_TO_PREVIOUS_INSTANCE import cz.jhutarek.marble.test.infrastructure.InstancePerClassStringSpec internal class AndroidNavigationControllerTest : InstancePerClassStringSpec({ val destinationId = 123 val destination = Destination(456, POP_TO_PREVIOUS_INSTANCE) val controller = AndroidNavigationController() "destination requests observable should have no default value after construction" { controller.observeDestinationRequests().test() .assertNoValues() .assertNotTerminated() } "destination requests observable should emit value passed to navigate" { val testObservable = controller.observeDestinationRequests().test() controller.navigate(destination) testObservable.assertValue(destination) } "observe observable should have no default value after construction" { controller.observe().test() .assertNoValues() .assertNotTerminated() } "observe observable should emit value passed to notify navigation executed" { val testObservable = controller.observe().test() controller.notifyNavigationExecuted(destinationId) testObservable .awaitCount(1) .assertValue(destinationId) } })<file_sep>/app-example/src/main/java/cz/jhutarek/marble/example/current/data/AndroidCurrentWeatherRepository.kt package cz.jhutarek.marble.example.current.data import cz.jhutarek.marble.arch.repository.data.BaseRepository import cz.jhutarek.marble.example.current.domain.CurrentWeatherRepository import cz.jhutarek.marble.example.current.model.CurrentWeather import javax.inject.Inject import javax.inject.Singleton @Singleton class AndroidCurrentWeatherRepository @Inject constructor( source: CurrentWeatherSource, cache: CurrentWeatherMemoryCache ) : BaseRepository<CurrentWeatherRepository.Query, CurrentWeather>( source, cache ), CurrentWeatherRepository<file_sep>/arch-mvvm/src/main/java/cz/jhutarek/marble/arch/mvvm/model/State.kt package cz.jhutarek.marble.arch.mvvm.model interface State<file_sep>/arch-intents/src/main/java/cz/jhutarek/marble/arch/intents/device/AndroidIntentController.kt package cz.jhutarek.marble.arch.intents.device import android.content.ActivityNotFoundException import android.content.Context import android.content.Intent import android.content.Intent.ACTION_VIEW import android.content.Intent.FLAG_ACTIVITY_NEW_TASK import android.net.Uri import cz.jhutarek.marble.arch.intents.domain.IntentController import cz.jhutarek.marble.arch.log.infrastructure.logE import cz.jhutarek.marble.arch.log.infrastructure.logI import javax.inject.Inject import javax.inject.Singleton @Singleton class AndroidIntentController @Inject constructor(private val context: Context) : IntentController { override fun browse(url: String) { logI("Browse: $url") try { Intent(ACTION_VIEW, Uri.parse(url)) .apply { addFlags(FLAG_ACTIVITY_NEW_TASK) } .let { context.startActivity(it) } } catch (e: ActivityNotFoundException) { logE("Activity not found for browse intent: $e") } } }<file_sep>/arch-navigation/src/main/java/cz/jhutarek/marble/arch/navigation/domain/NavigationUseCase.kt package cz.jhutarek.marble.arch.navigation.domain import cz.jhutarek.marble.arch.navigation.model.Destination import cz.jhutarek.marble.arch.usecase.domain.UseCase import io.reactivex.Observable import javax.inject.Inject import javax.inject.Singleton sealed class NavigationUseCase<in I, out O> : UseCase<I, O> { @Singleton class Navigate @Inject constructor(private val controller: NavigationController) : NavigationUseCase<Int, Unit>() { override fun invoke(input: Int) = controller.navigate(Destination(input)) operator fun invoke(id: Int, type: Destination.Type) = controller.navigate(Destination(id, type)) } @Singleton class Observe @Inject constructor(private val controller: NavigationController) : NavigationUseCase<Unit, Observable<Int>>() { override fun invoke(input: Unit): Observable<Int> = controller.observe() } }<file_sep>/app-example/src/main/java/cz/jhutarek/marble/example/overview/di/OverviewModule.kt package cz.jhutarek.marble.example.overview.di import cz.jhutarek.marble.example.overview.system.OverviewFragment import dagger.Module import dagger.android.ContributesAndroidInjector @Module interface OverviewModule { @ContributesAndroidInjector fun overviewFragment(): OverviewFragment }<file_sep>/arch-resources/src/main/java/cz/jhutarek/marble/arch/resources/domain/StringsUseCase.kt package cz.jhutarek.marble.arch.resources.domain import cz.jhutarek.marble.arch.usecase.domain.UseCase import javax.inject.Inject import javax.inject.Singleton sealed class StringsUseCase<in I, out O> : UseCase<I, O> { @Singleton class GetString @Inject constructor(private val controller: StringsController) : StringsUseCase<Int, String>() { override operator fun invoke(input: Int) = controller.getString(input) } }<file_sep>/arch-navigation/src/main/java/cz/jhutarek/marble/arch/navigation/di/NavigationModule.kt package cz.jhutarek.marble.arch.navigation.di import cz.jhutarek.marble.arch.navigation.device.AndroidNavigationController import cz.jhutarek.marble.arch.navigation.domain.NavigationController import dagger.Binds import dagger.Module @Module interface NavigationModule { @Binds fun navigationController(controller: AndroidNavigationController): NavigationController }<file_sep>/arch-application/src/main/java/cz/jhutarek/marble/arch/application/system/MarbleApplication.kt package cz.jhutarek.marble.arch.application.system import android.app.Activity import android.app.Application import android.app.Service import androidx.fragment.app.Fragment import com.squareup.leakcanary.LeakCanary import cz.jhutarek.marble.arch.application.di.MarbleApplicationComponent import cz.jhutarek.marble.arch.log.infrastructure.Logger import cz.jhutarek.marble.arch.log.infrastructure.logD import cz.jhutarek.marble.arch.mvvm.system.Mvvm import dagger.android.DispatchingAndroidInjector import dagger.android.HasActivityInjector import dagger.android.HasServiceInjector import dagger.android.support.HasSupportFragmentInjector import javax.inject.Inject // TODO test abstract class MarbleApplication : Application(), HasActivityInjector, HasSupportFragmentInjector, HasServiceInjector { @Inject internal lateinit var dispatchingActivityInjector: DispatchingAndroidInjector<Activity> @Inject internal lateinit var dispatchingFragmentInjector: DispatchingAndroidInjector<Fragment> @Inject internal lateinit var dispatchingServiceInjector: DispatchingAndroidInjector<Service> internal lateinit var component: MarbleApplicationComponent override fun onCreate() { super.onCreate() if (LeakCanary.isInAnalyzerProcess(this)) return LeakCanary.install(this) Logger.initialize(isDebug, logTag) Mvvm.initialize() onInitialize() component = onCreateComponent() .also { it.inject(this) } logD("Application created") } final override fun activityInjector() = dispatchingActivityInjector final override fun supportFragmentInjector() = dispatchingFragmentInjector final override fun serviceInjector() = dispatchingServiceInjector protected open fun onInitialize() {} protected abstract fun onCreateComponent(): MarbleApplicationComponent protected open val logTag = "*Mrbl:" protected abstract val isDebug: Boolean } <file_sep>/arch-navigation/src/main/java/cz/jhutarek/marble/arch/navigation/domain/NavigationController.kt package cz.jhutarek.marble.arch.navigation.domain import cz.jhutarek.marble.arch.navigation.model.Destination import io.reactivex.Observable interface NavigationController { fun observe(): Observable<Int> fun navigate(destination: Destination) }<file_sep>/arch-intents/src/test/java/cz/jhutarek/marble/arch/intents/domain/BrowseUseCaseTest.kt package cz.jhutarek.marble.arch.intents.domain import cz.jhutarek.marble.test.infrastructure.InstancePerClassStringSpec import io.mockk.mockk import io.mockk.verify internal class IntentUseCaseBrowseTest : InstancePerClassStringSpec({ val url = "url" val intentController = mockk<IntentController>(relaxUnitFun = true) val browse = IntentUseCase.Browse(intentController) "use case should delegate browse action to controller" { browse(url) verify { intentController.browse(url) } } })<file_sep>/app-example/src/main/java/cz/jhutarek/marble/example/settings/model/Settings.kt package cz.jhutarek.marble.example.settings.model data class Settings( val units: Units ) { enum class Units { METRIC, IMPERIAL } }<file_sep>/build.gradle buildscript { ext.kotlin_version = '1.3.20' repositories { google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.3.0' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" classpath 'com.github.dcendents:android-maven-gradle-plugin:2.1' classpath "de.mannodermaus.gradle.plugins:android-junit5:1.3.1.1" // workaround for https://issuetracker.google.com/issues/115738511 classpath 'com.android.tools.build.jetifier:jetifier-processor:1.0.0-beta02' classpath 'de.mobilej.unmock:UnMockPlugin:0.7.0' } } allprojects { repositories { google() jcenter() } tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all { sourceCompatibility = JavaVersion.VERSION_1_8 targetCompatibility = JavaVersion.VERSION_1_8 kotlinOptions { jvmTarget = '1.8' } } } task clean(type: Delete) { delete rootProject.buildDir } <file_sep>/app-example/src/main/java/cz/jhutarek/marble/example/current/domain/CurrentWeatherRepository.kt package cz.jhutarek.marble.example.current.domain import cz.jhutarek.marble.arch.repository.domain.Repository import cz.jhutarek.marble.example.current.model.CurrentWeather interface CurrentWeatherRepository : Repository<CurrentWeatherRepository.Query, CurrentWeather> { data class Query(val city: String) }<file_sep>/arch-intents/src/test/java/cz/jhutarek/marble/arch/intents/device/AndroidIntentControllerTest.kt package cz.jhutarek.marble.arch.intents.device import android.content.ActivityNotFoundException import android.content.Context import android.content.Intent import android.content.Intent.ACTION_VIEW import android.content.Intent.FLAG_ACTIVITY_NEW_TASK import android.net.Uri import cz.jhutarek.marble.test.infrastructure.InstancePerClassStringSpec import io.kotlintest.shouldBe import io.mockk.every import io.mockk.mockk import io.mockk.slot internal class AndroidIntentControllerTest : InstancePerClassStringSpec({ val url = "url" val context = mockk<Context>(relaxUnitFun = true) val controller = AndroidIntentController(context) "controller should try to open url in browser with correct settings" { val slot = slot<Intent>() every { context.startActivity(capture(slot)) } returns Unit controller.browse(url) with(slot.captured) { action shouldBe ACTION_VIEW data shouldBe Uri.parse(url) flags shouldBe FLAG_ACTIVITY_NEW_TASK } } "controller should swallow exception if there is no application to open url with" { every { context.startActivity(any()) } throws ActivityNotFoundException() controller.browse(url) } })<file_sep>/app-example/src/main/java/cz/jhutarek/marble/example/current/model/CurrentWeather.kt package cz.jhutarek.marble.example.current.model import org.threeten.bp.ZonedDateTime data class CurrentWeather( val timestamp: ZonedDateTime?, val location: String?, val temperatureCelsius: Double?, val pressureMilliBar: Double?, val descriptionText: String?, val descriptionCode: DescriptionCode, val windSpeedKmph: Double?, val windDirectionDegrees: Double?, val sunriseTimestamp: ZonedDateTime?, val sunsetTimestamp: ZonedDateTime? ) { enum class DescriptionCode { CLEAR, FOG, FEW_CLOUDS, SCATTERED_CLOUDS, OVERCAST_CLOUDS, DRIZZLE, LIGHT_RAIN, HEAVY_RAIN, SNOW, THUNDERSTORM, UNKNOWN } }<file_sep>/arch-navigation/src/main/java/cz/jhutarek/marble/arch/navigation/model/Destination.kt package cz.jhutarek.marble.arch.navigation.model data class Destination(val id: Int, val type: Type = Type.PUSH_ON_TOP) { enum class Type { PUSH_ON_TOP, POP_TO_PREVIOUS_INSTANCE, POP_ALL_THEN_PUSH } }<file_sep>/app-example/src/main/java/cz/jhutarek/marble/example/current/domain/CurrentWeatherUseCase.kt package cz.jhutarek.marble.example.current.domain import cz.jhutarek.marble.arch.repository.model.LegacyData import cz.jhutarek.marble.arch.repository.model.mapQuery import cz.jhutarek.marble.arch.usecase.domain.UseCase import cz.jhutarek.marble.example.current.domain.CurrentWeatherRepository.Query import cz.jhutarek.marble.example.current.model.CurrentWeather import io.reactivex.Observable import javax.inject.Inject import javax.inject.Singleton sealed class CurrentWeatherUseCase<in I, out O> : UseCase<I, O> { @Singleton class Observe @Inject constructor(private val repository: CurrentWeatherRepository) : CurrentWeatherUseCase<Unit, Observable<LegacyData<Unit, CurrentWeather>>>() { override operator fun invoke(input: Unit): Observable<LegacyData<Unit, CurrentWeather>> = repository.observe().mapQuery { Unit } } @Singleton class Load @Inject constructor(private val repository: CurrentWeatherRepository) : CurrentWeatherUseCase<Load.ByCity, Unit>() { data class ByCity(val city: String) override operator fun invoke(input: ByCity) = repository.load(Query(input.city)) } }<file_sep>/arch-intents/src/main/java/cz/jhutarek/marble/arch/intents/di/IntentModule.kt package cz.jhutarek.marble.arch.intents.di import cz.jhutarek.marble.arch.intents.device.AndroidIntentController import cz.jhutarek.marble.arch.intents.domain.IntentController import dagger.Binds import dagger.Module @Module interface IntentModule { @Binds fun intentController(controller: AndroidIntentController): IntentController }<file_sep>/app-example/src/main/java/cz/jhutarek/marble/example/current/data/CurrentWeatherSource.kt package cz.jhutarek.marble.example.current.data import com.squareup.moshi.Json import com.squareup.moshi.JsonClass import cz.jhutarek.marble.arch.log.infrastructure.logE import cz.jhutarek.marble.arch.log.infrastructure.logI import cz.jhutarek.marble.arch.repository.data.Source import cz.jhutarek.marble.example.current.domain.CurrentWeatherRepository import cz.jhutarek.marble.example.current.model.CurrentWeather import cz.jhutarek.marble.example.current.model.CurrentWeather.DescriptionCode.* import io.reactivex.Maybe import io.reactivex.schedulers.Schedulers.io import org.threeten.bp.Instant import org.threeten.bp.ZoneId import org.threeten.bp.ZonedDateTime import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.moshi.MoshiConverterFactory import retrofit2.http.GET import retrofit2.http.Query import javax.inject.Inject import javax.inject.Singleton // TODO test, move JSON parsing to separate class @Singleton class CurrentWeatherSource @Inject constructor() : Source<CurrentWeatherRepository.Query, CurrentWeather> { private companion object { const val BASE_URL = "https://api.openweathermap.org/data/2.5/" private const val API_KEY = "<KEY>" const val CURRENT_WEATHER_PATH = "weather" const val API_KEY_KEY = "APPID" const val CITY_KEY = "q" const val LANGUAGE_KEY = "lang" const val UNITS_KEY = "units" const val METRIC_UNITS = "metric" } private interface CurrentWeatherInterface { @GET(CURRENT_WEATHER_PATH) fun currentWeather( @Query(API_KEY_KEY) apiKey: String, @Query(CITY_KEY) city: String, @Query(LANGUAGE_KEY) language: String, @Query(UNITS_KEY) units: String ): Maybe<CurrentWeatherRemote> } @JsonClass(generateAdapter = true) data class CurrentWeatherRemote( @Json(name = "dt") val timestamp: Long? = null, @Json(name = "name") val location: String? = null, @Json(name = "main") val mainParameters: MainParameters?, @Json(name = "weather") val weatherDescriptions: List<WeatherDescription?>?, @Json(name = "wind") val wind: Wind?, @Json(name = "sys") val sun: Sun? ) { @JsonClass(generateAdapter = true) data class WeatherDescription( @Json(name = "id") val code: Int? = null, @Json(name = "main") val short: String? = null, @Json(name = "description") val long: String? = null ) @JsonClass(generateAdapter = true) data class MainParameters( @Json(name = "temp") val temperatureCelsius: Double? = null, @Json(name = "pressure") val pressureMilliBar: Double? = null ) @JsonClass(generateAdapter = true) data class Wind( @Json(name = "speed") val speedKmph: Double? = null, @Json(name = "deg") val directionDegrees: Double? = null ) @JsonClass(generateAdapter = true) data class Sun( @Json(name = "sunrise") val sunriseTimestamp: Long? = null, @Json(name = "sunset") val sunsetTimestamp: Long? = null ) } private val client by lazy { Retrofit.Builder() .baseUrl(BASE_URL) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(MoshiConverterFactory.create()) .build() .create(CurrentWeatherInterface::class.java) } override fun request(query: CurrentWeatherRepository.Query): Maybe<CurrentWeather> = client.currentWeather(API_KEY, query.city, "en", METRIC_UNITS) .map { CurrentWeather( timestamp = it.timestamp?.let { ZonedDateTime.ofInstant(Instant.ofEpochSecond(it), ZoneId.systemDefault()) }, location = it.location, temperatureCelsius = it.mainParameters?.temperatureCelsius, pressureMilliBar = it.mainParameters?.pressureMilliBar, descriptionText = it.weatherDescriptions?.first()?.long, descriptionCode = it.weatherDescriptions?.first()?.code?.toDescriptionCode() ?: UNKNOWN, windSpeedKmph = it.wind?.speedKmph, windDirectionDegrees = it.wind?.directionDegrees, sunriseTimestamp = it.sun?.sunriseTimestamp?.let { ZonedDateTime.ofInstant( Instant.ofEpochSecond(it), ZoneId.systemDefault() ) }, sunsetTimestamp = it.sun?.sunsetTimestamp?.let { ZonedDateTime.ofInstant( Instant.ofEpochSecond(it), ZoneId.systemDefault() ) } ) } .doOnSuccess { logI("Response: $it") } .doOnError { logE("Error: $it") } .doOnComplete { logI("No response") } .subscribeOn(io()) private fun Int.toDescriptionCode() = when (this) { in 200..299 -> THUNDERSTORM in 300..399 -> DRIZZLE in 500..504 -> LIGHT_RAIN in 511..599 -> HEAVY_RAIN in 600..699 -> SNOW in 700..799 -> FOG 800 -> CLEAR 801 -> FEW_CLOUDS 802 -> SCATTERED_CLOUDS in 803..804 -> OVERCAST_CLOUDS else -> UNKNOWN } }<file_sep>/app-example/src/main/java/cz/jhutarek/marble/example/overview/system/OverviewFragment.kt package cz.jhutarek.marble.example.overview.system import android.view.inputmethod.EditorInfo import com.jakewharton.rxbinding2.view.clicks import com.jakewharton.rxbinding2.widget.editorActions import com.jakewharton.rxbinding2.widget.textChanges import cz.jhutarek.marble.arch.mvvm.system.MarbleFragment import cz.jhutarek.marble.arch.mvvm.system.textString import cz.jhutarek.marble.example.overview.presentation.OverviewViewModel import cz.jhutarek.marblearch.R import io.reactivex.Observable import kotlinx.android.synthetic.main.overview__overview_fragment.* import java.util.concurrent.TimeUnit.MILLISECONDS class OverviewFragment : MarbleFragment<OverviewViewModel, OverviewViewModel.State>() { override val layoutResId = R.layout.overview__overview_fragment override fun onInitializeViews() { toolbar.inflateMenu(R.menu.overview__overview_menu) } override fun onBindViews() = listOf( toolbar.menu.findItem(R.id.refresh).clicks().subscribeForViewModel { refresh() }, toolbar.menu.findItem(R.id.settings).clicks().subscribeForViewModel { showSettings() }, input.textChanges().debounce(250, MILLISECONDS).subscribeForViewModel { setInput(it) }, input.editorActions().filter { it == EditorInfo.IME_ACTION_SEARCH }.subscribeForViewModel { refresh() } ) override fun onBindStates(states: Observable<OverviewViewModel.State>) = states.subscribeForViews { toolbar.menu.findItem(R.id.refresh).isEnabled = it.refreshEnabled input.textString = it.input } }<file_sep>/app-example/src/main/java/cz/jhutarek/marble/example/current/di/CurrentWeatherModule.kt package cz.jhutarek.marble.example.current.di import cz.jhutarek.marble.example.current.data.AndroidCurrentWeatherRepository import cz.jhutarek.marble.example.current.domain.CurrentWeatherRepository import cz.jhutarek.marble.example.current.system.CurrentWeatherFragment import dagger.Binds import dagger.Module import dagger.android.ContributesAndroidInjector @Module interface CurrentWeatherModule { @ContributesAndroidInjector fun currentWeatherFragment(): CurrentWeatherFragment @Binds fun currentWeatherRepository(androidCurrentWeatherRepository: AndroidCurrentWeatherRepository): CurrentWeatherRepository }<file_sep>/arch-repository/src/test/kotlin/cz/jhutarek/marble/arch/repository/data/BaseRepositoryTest.kt package cz.jhutarek.marble.arch.repository.data import cz.jhutarek.marble.arch.repository.data.BaseRepositoryTest.MockRepositoryBuilder.SourceResult.* import cz.jhutarek.marble.arch.repository.data.BaseRepositoryTest.MockRepositoryBuilder.SourceResult.Error.Companion.EXPECTED_ERROR import cz.jhutarek.marble.arch.repository.data.BaseRepositoryTest.MockRepositoryBuilder.SourceResult.Value.Companion.EXPECTED_VALUE import cz.jhutarek.marble.arch.repository.model.LegacyData import cz.jhutarek.marble.test.infrastructure.InstancePerClassStringSpec import io.kotlintest.data.forall import io.kotlintest.inspectors.forAll import io.kotlintest.tables.row import io.mockk.* import io.reactivex.Completable import io.reactivex.CompletableObserver import io.reactivex.Maybe import io.reactivex.MaybeObserver internal class BaseRepositoryTest : InstancePerClassStringSpec() { internal class MockRepositoryBuilder(allResults: List<SourceResult> = listOf(SourceResult.Whatever())) { val query = "query" internal sealed class SourceResult { abstract val maybeSpy: Maybe<String> class Whatever : SourceResult() { override val maybeSpy: Maybe<String> = spyk(Maybe.empty()) override fun toString() = "any" } class Empty : SourceResult() { override val maybeSpy: Maybe<String> = spyk(Maybe.empty()) override fun toString() = "empty" } data class Value(private val value: String = ANY_VALUE) : SourceResult() { companion object { const val ANY_VALUE = "any value" const val EXPECTED_VALUE = "expected value" } override val maybeSpy: Maybe<String> = spyk(Maybe.just(value)) override fun toString() = value } data class Error(private val error: Throwable = ANY_ERROR) : SourceResult() { companion object { val ANY_ERROR = IllegalStateException("any error") val EXPECTED_ERROR = IllegalStateException("expected error") } override val maybeSpy: Maybe<String> = spyk(Maybe.error(error)) override fun toString() = "$error" } } private val sourceResult = allResults.last() private val cacheResults = allResults.dropLast(1) private val sourceMock = mockk<Source<String, String>> { every { request(query) } returns sourceResult.maybeSpy } private val sourceResultSpy = sourceResult.maybeSpy val cacheClearSpies = List(cacheResults.size) { spyk(Completable.complete()) } val cacheMocks = cacheResults.mapIndexed { index, result -> mockk<Cache<String, String>> { every { request(query) } returns result.maybeSpy every { store(eq(query), any()) } returns Completable.complete() every { clear(query) } returns cacheClearSpies[index] } } private val cacheResultSpies = cacheResults.map { it.maybeSpy } val allMocks = cacheMocks + sourceMock val allResultSpies = cacheResultSpies + sourceResultSpy val repository = spyk(object : BaseRepository<String, String>(sourceMock, *cacheMocks.toTypedArray()) {}) } init { "repository should request each source when loaded" { forall( row(1), row(2), row(3), row(10) ) { sourceCount -> BaseRepositoryTest.MockRepositoryBuilder(List(sourceCount) { BaseRepositoryTest.MockRepositoryBuilder.SourceResult.Whatever() }) .run { clearMocks(*allMocks.toTypedArray(), answers = false) repository.load(query) allMocks.forAll { verify { it.request(query) } } } } } "repository should subscribe to sources until the first of them returns value" { forall( row(1, listOf(Empty())), row(1, listOf(Value())), row(1, listOf(Error())), row(1, listOf(Value(), Empty())), row(1, listOf(Value(), Value())), row(1, listOf(Value(), Value(), Value(), Empty(), Error(), Value())), row(2, listOf(Empty(), Empty())), row(2, listOf(Empty(), Value())), row(2, listOf(Empty(), Value(), Value(), Value())), row(5, listOf(Empty(), Empty(), Empty(), Empty(), Value(), Value(), Error())) ) { expectedSubscribedSources, allResults -> MockRepositoryBuilder(allResults).run { clearMocks(*allResultSpies.toTypedArray(), answers = false) repository.load(query) allResultSpies.take(expectedSubscribedSources).forAll { verify { it.subscribe(any<MaybeObserver<String>>()) } } allResultSpies.drop(expectedSubscribedSources).forAll { verify(inverse = true) { it.subscribe(any<MaybeObserver<String>>()) } } } } } "repository should emit loading first when loading" { MockRepositoryBuilder().run { val testObserver = repository.observe().test() repository.load(query) testObserver.assertValueAt(0, LegacyData.Loading(query)) } } "repository should emit value from first source that is not empty or error" { forall( row(listOf(Value(EXPECTED_VALUE))), row(listOf(Value(EXPECTED_VALUE), Empty())), row(listOf(Value(EXPECTED_VALUE), Value())), row(listOf(Value(EXPECTED_VALUE), Value(), Value(), Empty(), Error(), Value())), row(listOf(Empty(), Value(EXPECTED_VALUE))), row(listOf(Empty(), Value(EXPECTED_VALUE), Value(), Value())), row(listOf(Empty(), Empty(), Empty(), Empty(), Value(EXPECTED_VALUE), Value(), Error())) ) { allResults -> MockRepositoryBuilder(allResults).run { val testObserver = repository.observe().test() repository.load(query) testObserver.assertValueAt(1, LegacyData.Loaded(query, EXPECTED_VALUE)) } } } "repository should emit error from first source that is not empty or has value" { forall( row(listOf(Error(EXPECTED_ERROR))), row(listOf(Error(EXPECTED_ERROR), Empty())), row(listOf(Error(EXPECTED_ERROR), Error())), row(listOf(Error(EXPECTED_ERROR), Error(), Value(), Empty(), Error(), Value())), row(listOf(Empty(), Error(EXPECTED_ERROR))), row(listOf(Empty(), Error(EXPECTED_ERROR), Error(), Value())), row(listOf(Empty(), Empty(), Empty(), Empty(), Error(EXPECTED_ERROR), Value(), Error())) ) { allResults -> MockRepositoryBuilder(allResults).run { val testObserver = repository.observe().test() repository.load(query) testObserver.assertValueAt(1, LegacyData.Error(query, EXPECTED_ERROR)) } } } "repository should emit empty if all sources are empty" { forall( row(1), row(2), row(3), row(10) ) { sourceCount -> MockRepositoryBuilder(List(sourceCount) { Empty() }).run { val testObserver = repository.observe().test() repository.load(query) testObserver.assertValueAt(1, LegacyData.Empty(query)) } } } "repository should store value loaded from lower source in all higher caches" { forall( row(0, listOf(Empty())), row(0, listOf(Value())), row(0, listOf(Error())), row(0, listOf(Value(), Empty())), row(0, listOf(Value(), Value())), row(0, listOf(Empty(), Empty())), row(1, listOf(Empty(), Value(EXPECTED_VALUE))), row(2, listOf(Empty(), Empty(), Value(EXPECTED_VALUE), Empty(), Error(), Value())), row(4, listOf(Empty(), Empty(), Empty(), Empty(), Value(EXPECTED_VALUE), Value(), Error())) ) { expectedStoreCount, allResults -> MockRepositoryBuilder(allResults).run { clearMocks(*cacheMocks.toTypedArray(), answers = false) repository.load(query) cacheMocks.take(expectedStoreCount).forAll { verify { it.store(query, EXPECTED_VALUE) } } cacheMocks.drop(expectedStoreCount).forAll { verify(inverse = true) { it.store(query, any()) } } } } } "repository should emit error if cache emits error when storing value" { MockRepositoryBuilder(listOf(Empty(), Value())).run { every { cacheMocks[0].store(query, any()) } returns Completable.error(EXPECTED_ERROR) val testObserver = repository.observe().test() repository.load(query) testObserver.assertValueAt(1, LegacyData.Error(query, EXPECTED_ERROR)) } } "repository should subscribe to clear all caches" { MockRepositoryBuilder(listOf(Value(), Empty(), Empty())).run { repository.clearCaches(query).subscribe() cacheClearSpies.forAll { verify { it.subscribe(any<CompletableObserver>()) } } } } "repository should emit complete when all caches are successfully cleared" { MockRepositoryBuilder(listOf(Value(), Empty(), Empty())).run { repository.clearCaches(query) .test() .assertComplete() } } "repository should emit error when any cache is not successfully cleared" { MockRepositoryBuilder(listOf(Value(), Empty(), Empty())).run { every { cacheMocks[1].clear(query) } returns Completable.error(EXPECTED_ERROR) repository.clearCaches(query) .test() .assertError(EXPECTED_ERROR) } } "repository should emit loading on update" { MockRepositoryBuilder().run { val testObserver = repository.observe().test() repository.update(query) testObserver.assertValueAt(0, LegacyData.Loading(query)) } } "repository should clear all caches and load on update" { MockRepositoryBuilder().run { repository.update(query) verifyOrder { repository.clearCaches(query) repository.load(query) } } } "repository should emit error if caches are not successfully cleared on update" { MockRepositoryBuilder(listOf(Value(), Empty(), Empty())).run { every { cacheMocks[1].clear(query) } returns Completable.error(EXPECTED_ERROR) val testObserver = repository.observe().test() repository.update(query) testObserver.assertValueAt(1, LegacyData.Error(query, EXPECTED_ERROR)) } } } }<file_sep>/app-example/src/main/java/cz/jhutarek/marble/example/current/presentation/CurrentWeatherViewModel.kt package cz.jhutarek.marble.example.current.presentation import cz.jhutarek.marble.arch.mvvm.presentation.ViewModel import cz.jhutarek.marble.arch.repository.model.LegacyData import cz.jhutarek.marble.arch.resources.domain.StringsUseCase import cz.jhutarek.marble.example.current.domain.CurrentWeatherUseCase import cz.jhutarek.marble.example.current.model.CurrentWeather.DescriptionCode.* import cz.jhutarek.marblearch.R import org.threeten.bp.format.DateTimeFormatter import javax.inject.Inject import javax.inject.Singleton import cz.jhutarek.marble.arch.mvvm.model.State as MarbleState @Singleton class CurrentWeatherViewModel @Inject constructor( observeCurrentWeather: CurrentWeatherUseCase.Observe, getString: StringsUseCase.GetString ) : ViewModel<CurrentWeatherViewModel.State>(State()) { companion object { private val descriptionIconMap = mapOf( CLEAR to R.drawable.ic_clear, DRIZZLE to R.drawable.ic_drizzle, FEW_CLOUDS to R.drawable.ic_few_clouds, FOG to R.drawable.ic_fog, HEAVY_RAIN to R.drawable.ic_heavy_rain, LIGHT_RAIN to R.drawable.ic_light_rain, OVERCAST_CLOUDS to R.drawable.ic_overcast_clouds, SCATTERED_CLOUDS to R.drawable.ic_scattered_clouds, SNOW to R.drawable.ic_snow, THUNDERSTORM to R.drawable.ic_thunderstorm ).withDefault { R.drawable.ic_unknown } } data class State( val loadingVisible: Boolean = false, val emptyVisible: Boolean = false, val error: String? = null, val errorVisible: Boolean = false, val dataVisible: Boolean = false, val timestamp: String? = null, val location: String? = null, val temperature: String? = null, val pressure: String? = null, val descriptionText: String? = null, val descriptionIcon: Int = R.drawable.ic_unknown, val additionalInfo: String? = null ) : MarbleState init { observeCurrentWeather(Unit) .map { when (it) { is LegacyData.Empty -> { State( emptyVisible = true ) } is LegacyData.Loading -> { State( loadingVisible = true ) } is LegacyData.Loaded -> { State( dataVisible = true, timestamp = it.value.timestamp?.format(DateTimeFormatter.ofPattern("dd. LLLL H:mm")), location = it.value.location, temperature = it.value.temperatureCelsius?.let { getString(R.string.current__temperature).format(it) }, pressure = it.value.pressureMilliBar?.let { getString(R.string.current__pressure).format(it) }, descriptionText = it.value.descriptionText?.capitalize(), descriptionIcon = descriptionIconMap.getValue(it.value.descriptionCode), additionalInfo = listOfNotNull( it.value.windSpeedKmph?.let { getString(R.string.current__wind_speed).format(it) }, it.value.windDirectionDegrees?.let { getString(R.string.current__wind_direction).format(it) }, it.value.sunriseTimestamp?.format(DateTimeFormatter.ofPattern("H:mm"))?.let { getString(R.string.current__sunrise).format( it ) }, it.value.sunsetTimestamp?.format(DateTimeFormatter.ofPattern("H:mm"))?.let { getString(R.string.current__sunset).format( it ) } ).joinToString(separator = getString(R.string.current__additional_info_separator)) ) } is LegacyData.Error -> { State( errorVisible = true, error = it.error.toString().let { getString(R.string.current__error).format(it) } ) } } } .subscribe(statesRelay) } }<file_sep>/arch-application/src/main/java/cz/jhutarek/marble/arch/application/di/MarbleApplicationComponent.kt package cz.jhutarek.marble.arch.application.di import cz.jhutarek.marble.arch.application.system.MarbleApplication interface MarbleApplicationComponent { fun inject(marbleApplication: MarbleApplication) }<file_sep>/arch-navigation/src/test/java/cz/jhutarek/marble/arch/navigation/domain/NavigationUseCaseTest.kt package cz.jhutarek.marble.arch.navigation.domain import cz.jhutarek.marble.arch.navigation.model.Destination import cz.jhutarek.marble.arch.navigation.model.Destination.Type.POP_TO_PREVIOUS_INSTANCE import cz.jhutarek.marble.test.infrastructure.InstancePerClassStringSpec import io.mockk.every import io.mockk.mockk import io.mockk.verify import io.reactivex.Observable internal class NavigateUseCaseTest : InstancePerClassStringSpec({ val controller = mockk<NavigationController>(relaxUnitFun = true) val destinationId = 123 val destinationType = POP_TO_PREVIOUS_INSTANCE val navigate = NavigationUseCase.Navigate(controller) "use case should execute navigate on controller with default type" { navigate(destinationId) verify { controller.navigate(Destination(destinationId)) } } "use case should execute navigate on controller with given arguments" { navigate(destinationId, destinationType) verify { controller.navigate(Destination(destinationId, destinationType)) } } }) internal class ObserveUseCaseTest : InstancePerClassStringSpec({ val controller = mockk<NavigationController>() val destination = 456 val observe = NavigationUseCase.Observe(controller) "use case should execute observe on controller" { every { controller.observe() } returns Observable.never() observe(Unit) verify { controller.observe() } } "use case should destination from controller" { every { controller.observe() } returns Observable.just(destination) observe(Unit) .test() .assertValue(destination) } })<file_sep>/app-example/src/main/java/cz/jhutarek/marble/example/main/presentation/MainViewModel.kt package cz.jhutarek.marble.example.main.presentation import cz.jhutarek.marble.arch.mvvm.presentation.ViewModel import javax.inject.Inject import javax.inject.Singleton import cz.jhutarek.marble.arch.mvvm.model.State as MarbleState @Singleton class MainViewModel @Inject constructor() : ViewModel<MainViewModel.State>(State()) { class State : MarbleState }<file_sep>/app-example/src/main/java/cz/jhutarek/marble/example/settings/di/SettingsModule.kt package cz.jhutarek.marble.example.settings.di import cz.jhutarek.marble.example.settings.system.SettingsFragment import dagger.Module import dagger.android.ContributesAndroidInjector @Module interface SettingsModule { @ContributesAndroidInjector fun settingsFragment(): SettingsFragment }
8b7fe23a6fed6a54714aa30a9d6a14e4f9eab531
[ "Markdown", "Kotlin", "Gradle" ]
75
Kotlin
jhutarek/marble-arch
12f70cba1eb0877fac8d3f8a068c3fe5e08a2224
ce2ad44c6149bb01f4dc48c277233af9cb6145cf
refs/heads/master
<file_sep>from flask import Flask, abort, request, session, redirect, url_for, escape, request import os from random import randint import sqlite3 from base64 import b64encode from os import urandom import hashlib from send_email import * filename = "userdata.db" app = Flask(__name__) app.secret_key = b'' #a secret key to encrypt user sessions admin_email = "<EMAIL>" #a gmail email address admin_password = "<PASSWORD>" #a gmail email address password def init(): global filename exists = os.path.exists(filename) if exists: #check file isn't empty or corrupted with open(filename, "rb") as file: data = file.read() if data == b"": #file is empty init_db() else: init_db() def init_db(): global filename try: with open(filename, "w") as file: file.write("") connection = sqlite3.connect('userdata.db') c = connection.cursor() # Create table c.execute('''CREATE TABLE users (user_id INTEGER PRIMARY KEY, username varchar(32) NOT NULL, password varchar(128) NOT <PASSWORD>, salt varchar(128) NOT NULL, confirmation varchar(128) NOT NULL, email varchar(128) NOT NULL, timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL)''') # Save (commit) the changes connection.commit() except: init_db() @app.route("/") def index(): if logged_in(): try: username = session.get("username") return 'Ya boi '+username+' logged in<br><a href="/settings">Settings?</a><br><a href="/logout">Log out?</a>' except: body = '<a href="/login">Login?</a><br><a href="/register">Register?</a>' return body else: body = '<a href="/login">Login?</a><br><a href="/register">Register?</a>' return body @app.route("/login") def login(): body = '<form action="/login_post" method="post">Username: <input type="text" name="username"><br>Password: <input type="<PASSWORD>" name="password"><br><input type="submit" value="Submit"></form><br><a href="/">Home?</a><br><a href="/register">Register?</a>' #var = "".join([random_imgur() for i in range(1)]) return body @app.route("/register") def register(): body = '<form action="/register_post" method="post">Username: <input type="text" name="username"><br>Password: <input type="<PASSWORD>" name="password"><br>Confirm Password: <input type="<PASSWORD>" name="password_confirm"><br>Email: <input type="text" name="email"><br><input type="submit" value="Submit"></form><br><a href="/">Home?</a><br><a href="/login">Login?</a>' #var = "".join([random_imgur() for i in range(1)]) return body @app.route('/logout') def logout(): # remove the username from the session if it's there session.pop('username', None) return redirect(url_for('index')) @app.route('/login_post', methods=['POST']) def login_post(): if not request.form: abort(400) username = request.form.get('username') password = request.form.get('<PASSWORD>') connection = sqlite3.connect('userdata.db') try: c = connection.cursor() c.execute("SELECT password,salt FROM users WHERE username=?", [username]) rows = c.fetchall() if rows: try: hashed_password = rows[0][0] salt = rows[0][1] hashed_password_attempt = hash_password(password,salt) if hashed_password == hashed_password_attempt: #create cookie and redirect to secure pages session['username'] = username return redirect(url_for('index')) else: return "Incorrect Password<br><a href='/login'>Login?</a><br><a href='/'>Home?</a>" except: return "Error Logging In<br><a href='/login'>Login?</a><br><a href='/'>Home?</a>" else: return "User does not exist<br><a href='/register'>Register?</a><br><a href='/'>Home?</a>" except: return "Error<br><a href='/login'>Login?</a><br><a href='/'>Home?</a>" @app.route('/register_post', methods=['POST']) def register_post(): if not request.form: abort(400) salt = b64encode(os.urandom(96)).decode("utf-8") #the 96 bytes is 128 characters in base64 username = request.form.get('username') password = request.form.get('password') password_confirm = request.form.get('password_confirm') email = request.form.get('email') validation_code = b64encode(os.urandom(12)).decode("utf-8").replace("=","a").replace("+","b").replace("/","c") connection = sqlite3.connect('userdata.db') c = connection.cursor() c.execute("SELECT username FROM users WHERE username=?", [username]) rows = c.fetchall() if not rows: #username does not already exist if password == password_confirm: hashed_password = <PASSWORD>_password(password,salt) else: return "Passwords must match<br><a href='/register'>Register?</a><br><a href='/'>Home?</a>" # Insert a row of data try: c.execute("INSERT INTO users(username, password, salt, confirmation, email) VALUES (?,?,?,?,?)",[username,hashed_password,salt,validation_code,email]) # Save (commit) the changes connection.commit() connection.close() confirmation_link = "<a href='http://127.0.0.1:5000/confirm_email?cc="+validation_code+"&user="+username+"'>Click here to complete your registration.</a>" email_status = send_email(admin_email,admin_password,email,"Confirmation Email",confirmation_link) if email_status: return "Registered Successfully!<br><br>Please use the confirmation link in your email for full access (The email may be in your spam folder).<br><a href='/login'>Login?</a><br><a href='/'>Home?</a>" else: return "Registered mostly successfully!<br><br>The confirmation link failed to send to your email, for full access, change your email or retry the sending process when you log in.<br><a href='/login'>Login?</a><br><a href='/'>Home?</a>" except: connection.close() return "Registration Failed<br><a href='/register'>Register?</a><br><a href='/'>Home?</a>" else: return "Username is taken<br><a href='/register'>Register?</a><br><a href='/login'>Login?</a><br><a href='/'>Home?</a>" connection.close() return "Error<br><a href='/register'>Register?</a><br><a href='/'>Home?</a>" @app.route('/settings') def settings(): #if the email isn't confirmed, resend the email #ability to change the password and the email if logged_in(): resend_email = '' try: username = session.get("username") connection = sqlite3.connect('userdata.db') c = connection.cursor() c.execute("SELECT confirmation FROM users WHERE username=?", [username]) rows = c.fetchall() if rows: #the username does exist validation_code = rows[0][0] if validation_code != "y": #potentially bad as it reveals the users email is confirmed resend_email = '<br><a href="/resend_email">Resend Confirmation Email?</a>' else: pass else: return 'What in tarnation.' except: return 'Something went wrong.' return 'Ya logged in and on the settings page<br><a href="/">Home?</a>'+resend_email+'<br><a href="/logout">Log out?</a>' else: return redirect(url_for('index')) #todo #change email #change password #change username(?) #I forgot my password #I forgot my username #I forgot my email @app.route('/resend_email') def resend_email(): if 'username' in session: #now check the database if that is a real username try: username = session.get("username") connection = sqlite3.connect('userdata.db') c = connection.cursor() c.execute("SELECT confirmation,email FROM users WHERE username=?", [username]) rows = c.fetchall() if rows: #the username does exist validation_code = rows[0][0] email = rows[0][1] if validation_code == "y": #potentially bad as it reveals the users email is confirmed return "That email has already been confirmed." else: confirmation_link = "<a href='http://127.0.0.1:5000/confirm_email?cc="+validation_code+"&user="+username+"'>Click here to complete your registration.</a>" email_status = send_email(admin_email,admin_password,email,"Confirmation Email",confirmation_link) if email_status: return 'Email sent successfully.' else: return 'The email was not sent successfully.' else: return 'What in tarnation.' except: return 'Something went wrong.' else: return 'You must be logged in to do this.' @app.route("/confirm_email", methods={'GET'}) def confirm_email(): #have the code expire try: confirmation_code = request.args.get("cc") username = request.args.get("user") try: connection = sqlite3.connect('userdata.db') c = connection.cursor() c.execute("SELECT confirmation FROM users WHERE username=?", [username]) rows = c.fetchall() if rows: #the username does exist print(rows) confirmation_code_real = rows[0][0] if confirmation_code_real == "y": #potentially bad as it reveals the users email is confirmed return "That email has already been confirmed" elif confirmation_code_real == confirmation_code: #update the entry to be 'y' c.execute("UPDATE users SET confirmation=? WHERE username=?", ['y',username]) connection.commit() connection.close() return "Your email has been validated." else: return "Invalid Code." else: return "Invalid Username." except: return "Invalid Attempt." except: return "Invalid." #do a lookup to check if that confirmation code matches that username #if it do, redirect to homepage #else, go to a page to send a new confirmation code (when logged in) def logged_in(): if 'username' in session: #now check the database if that is a real username try: username = session.get("username") connection = sqlite3.connect('userdata.db') c = connection.cursor() c.execute("SELECT username FROM users WHERE username=?", [username]) rows = c.fetchall() if rows: #the username does exist return True else: return False except: return False else: return False def confirmation_email(): #maybe work on this later #get a validation code validation_code = b64encode(os.urandom(32)).decode("utf-8") print(validation_code) #store it in the db with the user #email the code with a link def hash_password(password,salt): salted_str = (password+salt).encode("utf-8") hashGen = hashlib.sha512() hashGen.update(salted_str) hashed_password = hashGen.hexdigest() return hashed_password init() app.run()
3c898a10912da4af929db1d85fa005ab031f7667
[ "Python" ]
1
Python
EL-S/FlaskSecureLogin
f87ced2a3c11610d38b9b909dd915ccd9f7f02e7
a87727f0b997ac065321ca6adc1a6a36c6aa5415
refs/heads/master
<file_sep>#include<stdio.h> #include<string.h> #include<stdlib.h> #include <math.h> char *fourMore=""; char *sixtLast=""; char *substring(char *string, int position, int length){ char *pointer; int c; pointer = malloc(length+1); if (pointer == NULL){ printf("aloc\n"); exit(1); } for (c = 0 ; c < length ; c++){ *(pointer+c) = *(string+position-1); string++; } *(pointer+c) = '\0'; return pointer; } char *smallFour(char *ptr){ if(*ptr == '.'){ return "....";} else if(*ptr == '*'){ return "****";} else if(*ptr == 'x'){ return "xxxx";} else if(*ptr == 'o'){ return "oooo";} else return "SmaF"; } char *twoMaker(char *ptr){ if(*ptr == '.'){ return "........";} else if(*ptr == '*'){ return "********";} else if(*ptr == 'x'){ return "xxxxxxxx";} else if(*ptr == 'o'){ return "oooooooo";} else if(*ptr == 'y'){ return "yyyyyyyy";} else if(*ptr == 'z'){ return "zzzzzzzz";} else if(*ptr == 't'){ return "tttttttt";} else if(*ptr == 'a'){ return "aaaaaaaa";} else if(*ptr == 'b'){ return "bbbbbbbb";} else if(*ptr == 'c'){ return "cccccccc";} else if(*ptr == 'd'){ return "dddddddd";} else return "twoM"; } char *bigFour(char *ptr){ if(*ptr == '.'){ return "................";} else if(*ptr == '*'){ return "****************";} else if(*ptr == 'x'){ return "xxxxxxxxxxxxxxxx";} else if(*ptr == 'o'){ return "oooooooooooooooo";} else if(*ptr == 'y'){ return "yyyyyyyyyyyyyyyy";} else if(*ptr == 'z'){ return "zzzzzzzzzzzzzzzz";} else if(*ptr == 't'){ return "tttttttttttttttt";} else if(*ptr == 'a'){ return "aaaaaaaaaaaaaaaa";} else if(*ptr == 'b'){ return "bbbbbbbbbbbbbbbb";} else if(*ptr == 'c'){ return "cccccccccccccccc";} else if(*ptr == 'd'){ return "dddddddddddddddd";} else return "bigF"; } char *regulator(char *ptr,int imp){ char *ret=""; if(strlen(ptr)==4) {ret= ptr;} else if(strlen(ptr)==1){ if(imp==0){ ret= smallFour(ptr);} else if(imp==1){ ret= bigFour(ptr);} } else if(strlen(ptr)==2){ ret= twoMaker(ptr); } else if(strlen(ptr)==5){ fourMore = smallFour(substring(ptr,5,strlen(ptr))); ret = substring(ptr,1,4); } else if(strlen(ptr)>5){ret = substring(ptr,1,4);} else ret= "regM"; return ret; } int squareCheck (int x){ float z= sqrt(x*4); if (z ==(int)z) return 1; else return 0; } int pluscheck(char *girdi){ int sel ; char *param ="++"; char *ptr = strstr(girdi, param); if (ptr != NULL){sel=1;} else{sel=0;} return sel; } int main(){ int quadNum = 0; int kareli=1; const int size = 500; char commands[]=""; char *girdi=(char *) malloc(size * sizeof(char)); scanf("%s",girdi); int important = pluscheck(girdi); //printf("%d\n",important); if(strlen(girdi)==1){ return printf("%s\n", girdi); }else { if(strlen(girdi)>5 && strlen(girdi)<=30){quadNum=4;} else if(strlen(girdi)>30 && strlen(girdi)<=50){quadNum=8;} else if(strlen(girdi)>50){quadNum=16;} char parameter[]="+"; char *ptr = strtok(girdi, parameter); char *command[size]; char *kuadBas[size]; while(ptr != NULL){ char *point = regulator(ptr,important); //printf("%s-------%lu----%s\n",ptr,strlen(ptr),point ); if(strlen(point)==4){ command[kareli-1]=malloc(4); strcpy(command[kareli-1],point); kareli++; }else if(strlen(point)==8){ char *kel = substring(point,5,strlen(point)); for(int i=0;i<2;i++){ command[kareli-1]=malloc(4); strcpy(command[kareli-1],kel); kareli++; } }else if(strlen(point)==16){ char *kel = substring(point,13,strlen(point)); for(int i=0;i<4;i++){ command[kareli-1]=malloc(4); strcpy(command[kareli-1],kel); kareli++; } important =0; }else {printf("mEWh");} ptr = strtok(NULL, parameter); } if(kareli>2){command[kareli-1]=malloc(4);strcpy(command[kareli-1],fourMore);} //sixtLast if(kareli==2){int i=0;printf("%c%c\n%c%c\n",command[i][0],command[i][1],command[i][3],command[i][2]);} if(quadNum==4){ for(int i=0;i<quadNum && kareli!=2;i++){ for(int j=0;j<quadNum/2 && i<quadNum/2;j++){ if(i%2==0){printf("%c%c",command[j][0],command[j][1]);} else {printf("%c%c",command[j][3],command[j][2]);} } for(int t=quadNum-1;t>=quadNum/2 && i>=quadNum/2;t--){ if(i%2==0){printf("%c%c",command[t][0],command[t][1]);} else {printf("%c%c",command[t][3],command[t][2]);} } printf("\n"); } } else if(quadNum==8){ int j=0; for(int i=0;i<quadNum/4 && kareli!=2;i++){ printf("%c%c%c%c%c%c%c%c\n",command[j][0],command[j][1],command[j+1][0],command[j+1][1],command[j+3][0],command[j+3][1],command[j+2][0],command[j+2][1]); printf("%c%c%c%c%c%c%c%c\n",command[j][3],command[j][2],command[j+1][3],command[j+1][2],command[j+3][3],command[j+3][2],command[j+2][3],command[j+2][2]); if(j!=kareli-2)j=j+4; } printf("%c%c%c%c%c%c%c%c\n",command[j+4][0],command[j+4][1],command[j+5][0],command[j+5][1],command[j][0],command[j][1],command[j+1][0],command[j+1][1]); printf("%c%c%c%c%c%c%c%c\n",command[j+4][3],command[j+4][2],command[j+5][3],command[j+5][2],command[j][3],command[j][2],command[j+1][3],command[j+1][2]); printf("%c%c%c%c%c%c%c%c\n",command[j+7][0],command[j+7][1],command[j+6][0],command[j+6][1],command[j+3][0],command[j+3][1],command[j+2][0],command[j+2][1]); printf("%c%c%c%c%c%c%c%c\n",command[j+7][3],command[j+7][2],command[j+6][3],command[j+6][2],command[j+3][3],command[j+3][2],command[j+2][3],command[j+2][2]); } else if(quadNum==16){ for(int i=0;i<64;i++){ printf("-----%d\n",i); printf("%c%c\n",command[i][0],command[i][1]); printf("%c%c\n",command[i][3],command[i][2]); } } free(girdi); return 0; } } <file_sep>objemake: gcc -o main PLhw3.c ./main
707c381eb595b42bdb7968019ab9cc4da1a9e6d3
[ "C", "Makefile" ]
2
C
egemenozdag/C-Quadtrees
7b181b4e73e2fcca5bed508d46ec8255495e4138
601ec17a2fd53addf106a3308968ba8f2dd9b50c
refs/heads/master
<repo_name>wky0913/finweb-online<file_sep>/data_analyzer.py # 为聚宽的文件引用功能而运行的代码############## import io, os, sys, types from IPython import get_ipython from nbformat import read from IPython.core.interactiveshell import InteractiveShell def find_notebook(fullname, path=None): """find a notebook, given its fully qualified name and an optional path This turns "foo.bar" into "foo/bar.ipynb" and tries turning "Foo_Bar" into "Foo Bar" if Foo_Bar does not exist. """ name = fullname.rsplit('.', 1)[-1] if not path: path = [''] for d in path: nb_path = os.path.join(d, name + ".ipynb") if os.path.isfile(nb_path): return nb_path # let import Notebook_Name find "Notebook Name.ipynb" nb_path = nb_path.replace("_", " ") if os.path.isfile(nb_path): return nb_path class NotebookLoader(object): """Module Loader for Jupyter Notebooks""" def __init__(self, path=None): self.shell = InteractiveShell.instance() self.path = path def load_module(self, fullname): """import a notebook as a module""" path = find_notebook(fullname, self.path) print ("importing Jupyter notebook from %s" % path) # load the notebook object with io.open(path, 'r', encoding='utf-8') as f: nb = read(f, 4) # create the module and add it to sys.modules # if name in sys.modules: # return sys.modules[name] mod = types.ModuleType(fullname) mod.__file__ = path mod.__loader__ = self mod.__dict__['get_ipython'] = get_ipython sys.modules[fullname] = mod # extra work to ensure that magics that would affect the user_ns # actually affect the notebook module's ns save_user_ns = self.shell.user_ns self.shell.user_ns = mod.__dict__ try: for cell in nb.cells: if cell.cell_type == 'code': # transform the input to executable Python code = self.shell.input_transformer_manager.transform_cell(cell.source) # run the code in themodule exec(code, mod.__dict__) finally: self.shell.user_ns = save_user_ns return mod class NotebookFinder(object): """Module finder that locates Jupyter Notebooks""" def __init__(self): self.loaders = {} def find_module(self, fullname, path=None): nb_path = find_notebook(fullname, path) if not nb_path: return key = path if path: # lists aren't hashable key = os.path.sep.join(path) if key not in self.loaders: self.loaders[key] = NotebookLoader(path) return self.loaders[key] sys.meta_path.append(NotebookFinder()) ######################################################### import numpy as np import pandas as pd import bisect import jqdata import datetime import os from data_loader import DataLoaderSingle from data_loader import DataLoader from config import TODAY, YESTDAY, SDATE, EDATE from config import DATES, FILEN, CODES #数据分析类:分析数据 #输入参数: ''' 输入参数: 1.dic:整体数据 2.code:要统计的指数 3.dates:分位差统计范围 4.date:分位差使用的估值日期 ''' class DataAnalyzerSingle(object): def __init__(self, dic, code, dates, date): df = dic[code] self.dates = dates self.df = df[df.index.isin(dates)] self.dls = DataLoaderSingle(code, date) def cal_single(self,df,word): val_q=list(df.quantile([ii/10 for ii in range(11)])) val_cur=eval('self.dls.get_'+word+'()') idx=bisect.bisect(val_q,val_cur) try: val_qt=10*(idx-(val_q[idx]-val_cur)/(val_q[idx]-val_q[idx-1])) except IndexError: val_qt=0 return val_qt def get_pe_fwc(self): df = self.df.ix[self.dates,'PE']; return self.cal_single(df, 'pe') def get_pb_fwc(self): df = self.df.ix[self.dates,'PB']; return self.cal_single(df, 'pb') def get_pee_fwc(self): df = self.df.ix[self.dates,'PEE']; return self.cal_single(df, 'pee') def get_pbe_fwc(self): df = self.df.ix[self.dates,'PBE']; return self.cal_single(df, 'pbe') def get_pem_fwc(self): df = self.df.ix[self.dates,'PEM']; return self.cal_single(df, 'pem') def get_pbm_fwc(self): df = self.df.ix[self.dates,'PBM']; return self.cal_single(df, 'pbm') class DataAnalyzer(object): def __init__(self, dic, codes, dates, date): self.dic = dic self.codes = codes self.dates = dates self.date = date def get_summary(self): columns=[u'名称',u'加权PE',u'分位点%',u'等权PE',u'分位点%',u'中位数PE',u'分位点%', u'加权PB',u'分位点%',u'等权PB',u'分位点%',u'中位数PB',u'分位点%'] df_summary=pd.DataFrame(index=[code for code in self.codes],columns=columns) for code in self.codes: dls = DataLoaderSingle(code, self.date) pe = dls.get_pe() pb = dls.get_pb() pee = dls.get_pee() pbe = dls.get_pbe() pem = dls.get_pem() pbm = dls.get_pbm() das = DataAnalyzerSingle(self.dic, code, self.dates, self.date) pe_qt=das.get_pe_fwc() pb_qt=das.get_pb_fwc() pee_qt=das.get_pee_fwc() pbe_qt=das.get_pbe_fwc() pem_qt=das.get_pem_fwc() pbm_qt=das.get_pbm_fwc() all_index=get_all_securities(['index']) index_name=all_index.ix[code].display_name df_summary.ix[code]=[index_name,\ '%.1f' % pe,'%.1f' % pe_qt,'%.1f' % pee,'%.1f' % pee_qt,\ '%.1f' % pem,'%.1f' % pem_qt,'%.1f' % pb,'%.1f' % pb_qt,\ '%.1f' % pbe,'%.1f' % pbe_qt,'%.1f' % pbm,'%.1f' % pbm_qt] return df_summary <file_sep>/file_operator.py # 为聚宽的文件引用功能而运行的代码############## import io, os, sys, types from IPython import get_ipython from nbformat import read from IPython.core.interactiveshell import InteractiveShell def find_notebook(fullname, path=None): """find a notebook, given its fully qualified name and an optional path This turns "foo.bar" into "foo/bar.ipynb" and tries turning "Foo_Bar" into "Foo Bar" if Foo_Bar does not exist. """ name = fullname.rsplit('.', 1)[-1] if not path: path = [''] for d in path: nb_path = os.path.join(d, name + ".ipynb") if os.path.isfile(nb_path): return nb_path # let import Notebook_Name find "Notebook Name.ipynb" nb_path = nb_path.replace("_", " ") if os.path.isfile(nb_path): return nb_path class NotebookLoader(object): """Module Loader for Jupyter Notebooks""" def __init__(self, path=None): self.shell = InteractiveShell.instance() self.path = path def load_module(self, fullname): """import a notebook as a module""" path = find_notebook(fullname, self.path) print ("importing Jupyter notebook from %s" % path) # load the notebook object with io.open(path, 'r', encoding='utf-8') as f: nb = read(f, 4) # create the module and add it to sys.modules # if name in sys.modules: # return sys.modules[name] mod = types.ModuleType(fullname) mod.__file__ = path mod.__loader__ = self mod.__dict__['get_ipython'] = get_ipython sys.modules[fullname] = mod # extra work to ensure that magics that would affect the user_ns # actually affect the notebook module's ns save_user_ns = self.shell.user_ns self.shell.user_ns = mod.__dict__ try: for cell in nb.cells: if cell.cell_type == 'code': # transform the input to executable Python code = self.shell.input_transformer_manager.transform_cell(cell.source) # run the code in themodule exec(code, mod.__dict__) finally: self.shell.user_ns = save_user_ns return mod class NotebookFinder(object): """Module finder that locates Jupyter Notebooks""" def __init__(self): self.loaders = {} def find_module(self, fullname, path=None): nb_path = find_notebook(fullname, path) if not nb_path: return key = path if path: # lists aren't hashable key = os.path.sep.join(path) if key not in self.loaders: self.loaders[key] = NotebookLoader(path) return self.loaders[key] sys.meta_path.append(NotebookFinder()) ######################################################### import numpy as np import pandas as pd import bisect import jqdata import datetime import os from data_loader import DataLoaderSingleCode from config import TODAY, YESTDAY, SDATE, EDATE from config import DATES, FILEN, CODES class FileOperator(object): def __init__(self,fileN,dic={}): self.dic = dic self.fileN = fileN def save_file(self, dic): try: writer=pd.ExcelWriter(self.fileN) for code in dic: df=dic[code] df.to_excel(writer,code) writer.save() writer.close() except Exception as e: print("[save_file]:Save file failed!") print(e) def read_file(self): try: if not os.path.exists(self.fileN): return {} info=pd.read_excel(self.fileN,'info') dic={} for code in list(set(CODES+list(info.ix[:,'code']))): if code in info['code'].values: dic[code]=pd.read_excel(self.fileN,code) dic['info'] = info return dic except FileNotFoundError: return {} def flush_file(self, dic, dates): # 获取要更新的日期 for code in dic: if code != 'info': old_dates=dic[code].index break old_dates = [d.date() for d in old_dates] new_dates=pd.Series(list(set(dates)-set(old_dates))).sort_index(ascending=True) # 更新旧指数中的日期数据 if not new_dates.empty: tmp={} for code in dic: if code != 'info': dlsc = DataLoaderSingleCode(code, new_dates) tmp[code] = dlsc.get_index_df() dic[code] = dic[code].reindex(index=[d.date() for d in dic[code].index]) dic[code] = pd.concat([dic[code],tmp[code]]).sort_index(ascending=True) # 增加旧dic中的指数 new_codes=set(CODES)-set(dic) info = {} display_name=[] codes = [] start_date = [] end_date = [] if new_codes: for code in new_codes: if code != 'info': dl = DataLoaderSingleCode(code, dates[:]) dic[code] = dl.get_index_df() raw_info = get_security_info(code) codes.append(raw_info.code) display_name.append(raw_info.display_name) start_date.append(raw_info.start_date) end_date.append(raw_info.end_date) info['code'] = codes info['display_name'] = display_name info['start_date'] = start_date info['end_date'] = end_date info=pd.DataFrame(info) dic['info']=pd.concat([dic['info'],info],axis=0,ignore_index=True) return dic <file_sep>/data_ploter.py #########为聚宽的文件引用功能而运行的代码############## import io, os, sys, types from IPython import get_ipython from nbformat import read from IPython.core.interactiveshell import InteractiveShell def find_notebook(fullname, path=None): """find a notebook, given its fully qualified name and an optional path This turns "foo.bar" into "foo/bar.ipynb" and tries turning "Foo_Bar" into "Foo Bar" if Foo_Bar does not exist. """ name = fullname.rsplit('.', 1)[-1] if not path: path = [''] for d in path: nb_path = os.path.join(d, name + ".ipynb") if os.path.isfile(nb_path): return nb_path # let import Notebook_Name find "Notebook Name.ipynb" nb_path = nb_path.replace("_", " ") if os.path.isfile(nb_path): return nb_path class NotebookLoader(object): """Module Loader for Jupyter Notebooks""" def __init__(self, path=None): self.shell = InteractiveShell.instance() self.path = path def load_module(self, fullname): """import a notebook as a module""" path = find_notebook(fullname, self.path) print ("importing Jupyter notebook from %s" % path) # load the notebook object with io.open(path, 'r', encoding='utf-8') as f: nb = read(f, 4) # create the module and add it to sys.modules # if name in sys.modules: # return sys.modules[name] mod = types.ModuleType(fullname) mod.__file__ = path mod.__loader__ = self mod.__dict__['get_ipython'] = get_ipython sys.modules[fullname] = mod # extra work to ensure that magics that would affect the user_ns # actually affect the notebook module's ns save_user_ns = self.shell.user_ns self.shell.user_ns = mod.__dict__ try: for cell in nb.cells: if cell.cell_type == 'code': # transform the input to executable Python code = self.shell.input_transformer_manager.transform_cell(cell.source) # run the code in themodule exec(code, mod.__dict__) finally: self.shell.user_ns = save_user_ns return mod class NotebookFinder(object): """Module finder that locates Jupyter Notebooks""" def __init__(self): self.loaders = {} def find_module(self, fullname, path=None): nb_path = find_notebook(fullname, path) if not nb_path: return key = path if path: # lists aren't hashable key = os.path.sep.join(path) if key not in self.loaders: self.loaders[key] = NotebookLoader(path) return self.loaders[key] sys.meta_path.append(NotebookFinder()) ######################################################### import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib.dates as mdate import bisect import jqdata import datetime import os from data_loader import DataLoaderSingle from data_loader import DataLoader from file_operator import FileOperator from data_analyzer import DataAnalyzer from config import TODAY, YESTDAY, SDATE, EDATE from config import DATES, FILEN, CODES class Ploter(object): def __init__(self, dic, code, dates, date, fig_type, method='pee'): self.dic = dic self.code = code self.dates = dates self.date = date self.fig_type = fig_type self.method = method df=self.dic[self.code] self.df = df[df.index.isin(self.dates)] def get_fig_name(self): df = self.dic['info'] return df[df['code']==self.code].display_name.iloc[0] def get_fig_cal_cur_val(self): return self.df.ix[self.date.date(),self.method.upper()] def get_fig_cal_price(self): cal_val = self.get_fig_cal_cur_val() cal_price = self.df['PRICE']*(cal_val/self.df[self.method.upper()]) return cal_price def display_single(self, fig_data): plt.figure(figsize=(15,8)) plt.title(fig_data['name']+fig_data['desc']) for d in fig_data['data']: #plt.plot(self.dates, d['data'], label=d['label']) plt.plot(d['data'].index, d['data'], label=d['label']) plt.legend() plt.grid(True) plt.show() ''' fig_data={ 'name':'中证500', 'desc':'中证500估值图', 'data':[{'data':[], 'label':u'指数'}, {'data':[], 'label':u'指数'}] } ''' class TdFigPloter(Ploter): def assemble_fig_data(self): data1 = {'data':self.df['PRICE'], 'label':u'指数' } data2 = {'data':self.get_fig_cal_price(), 'label':u'当前估值线' } fig_data={'name':self.get_fig_name(), 'desc':u'通道图', 'data':[data1,data2] } return fig_data def display(self): fig_data = self.assemble_fig_data() self.display_single(fig_data) class GzFigPloter(Ploter): def assemble_fig_data(self): data1 = {'data':self.df[self.method.upper()], 'label':self.method.upper() } data2 = {'data':pd.Series(self.get_fig_cal_cur_val(), index=self.df[self.method.upper()].index), 'label':u'当前'+self.method.upper() } fig_data={'name':self.get_fig_name(), 'desc':u'估值图', 'data':[data1,data2] } return fig_data def display(self): fig_data = self.assemble_fig_data() self.display_single(fig_data) <file_sep>/data_loader.py #########为聚宽的文件引用功能而运行的代码############## import io, os, sys, types from IPython import get_ipython from nbformat import read from IPython.core.interactiveshell import InteractiveShell def find_notebook(fullname, path=None): """find a notebook, given its fully qualified name and an optional path This turns "foo.bar" into "foo/bar.ipynb" and tries turning "Foo_Bar" into "Foo Bar" if Foo_Bar does not exist. """ name = fullname.rsplit('.', 1)[-1] if not path: path = [''] for d in path: nb_path = os.path.join(d, name + ".ipynb") if os.path.isfile(nb_path): return nb_path # let import Notebook_Name find "Notebook Name.ipynb" nb_path = nb_path.replace("_", " ") if os.path.isfile(nb_path): return nb_path class NotebookLoader(object): """Module Loader for Jupyter Notebooks""" def __init__(self, path=None): self.shell = InteractiveShell.instance() self.path = path def load_module(self, fullname): """import a notebook as a module""" path = find_notebook(fullname, self.path) print ("importing Jupyter notebook from %s" % path) # load the notebook object with io.open(path, 'r', encoding='utf-8') as f: nb = read(f, 4) # create the module and add it to sys.modules # if name in sys.modules: # return sys.modules[name] mod = types.ModuleType(fullname) mod.__file__ = path mod.__loader__ = self mod.__dict__['get_ipython'] = get_ipython sys.modules[fullname] = mod # extra work to ensure that magics that would affect the user_ns # actually affect the notebook module's ns save_user_ns = self.shell.user_ns self.shell.user_ns = mod.__dict__ try: for cell in nb.cells: if cell.cell_type == 'code': # transform the input to executable Python code = self.shell.input_transformer_manager.transform_cell(cell.source) # run the code in themodule exec(code, mod.__dict__) finally: self.shell.user_ns = save_user_ns return mod class NotebookFinder(object): """Module finder that locates Jupyter Notebooks""" def __init__(self): self.loaders = {} def find_module(self, fullname, path=None): nb_path = find_notebook(fullname, path) if not nb_path: return key = path if path: # lists aren't hashable key = os.path.sep.join(path) if key not in self.loaders: self.loaders[key] = NotebookLoader(path) return self.loaders[key] sys.meta_path.append(NotebookFinder()) ######################################################### import numpy as np import pandas as pd import bisect import jqdata import datetime import os from config import TODAY, YESTDAY, SDATE, EDATE from config import DATES, FILEN, CODES from operator import mod WORDS = ['price','pe','pb','pee','pbe','pem','pbm'] # 数据加载类:获取数据,初步整理 class DataLoaderSingle(object): def __init__(self,code,date): stocks=get_index_stocks(code, date) dfn=len(stocks) if dfn<=0: df=pd.DataFrame() q=query( valuation.market_cap,valuation.pe_ratio, valuation.pb_ratio, ).filter(valuation.code.in_(stocks)) df=get_fundamentals(q, date) df=df.fillna(0) self.stocks = get_index_stocks(code, date) self.df = df self.dfn = len(stocks) self.code = code self.date = date def get_pe(self): if self.df.empty: return float('NaN') sum_p=sum(self.df.market_cap) sum_e=sum(self.df.market_cap/self.df.pe_ratio) if sum_e > 0: pe=sum_p / sum_e else: pe=float('NaN') return pe def get_pb(self): if self.df.empty: return float('NaN') sum_p=sum(self.df.market_cap) sum_b=sum(self.df.market_cap/self.df.pb_ratio) pb=sum_p/sum_b return pb def get_pee(self): if self.df.empty: return float('NaN') pee=len(self.df)/sum([1/p if p>0 else 0 for p in self.df.pe_ratio]) return pee def get_pbe(self): if self.df.empty: return float('NaN') pbe=len(self.df)/sum([1/b if b>0 else 0 for b in self.df.pb_ratio]) return pbe def get_pem(self): if self.df.empty: return float('NaN') pes=list(self.df.pe_ratio);pes.sort() if mod(self.dfn,2)==0: pem=0.5*sum(pes[round(self.dfn/2-1):round(self.dfn/2+1)]) else: pem=pes[round((self.dfn-1)/2)] return pem def get_pbm(self): if self.df.empty: return float('NaN') pbs=list(self.df.pb_ratio);pbs.sort() if mod(self.dfn,2)==0: pbm=0.5*sum(pbs[round(self.dfn/2-1):round(self.dfn/2+1)]) else: pbm=pbs[round((self.dfn-1)/2)] return pbm def get_index_price(self): price = get_price(self.code, end_date=self.date, count=1, frequency='1d', fields=['close']) return price.ix[0,'close'] class DataLoaderSingleCode(object): def __init__(self, code, dates): s_date = get_all_securities(['index']).ix[code].start_date self.code = code self.dates = dates[dates>s_date] def get_pes(self): tmp = [] for date in self.dates: dls = DataLoaderSingle(self.code,date) tmp.append(dls.get_pe()) return pd.Series(tmp, index=self.dates) def get_pbs(self): tmp = [] for date in self.dates: dls = DataLoaderSingle(self.code,date) tmp.append(dls.get_pb()) return pd.Series(tmp, index=self.dates) def get_pees(self): tmp = [] for date in self.dates: dls = DataLoaderSingle(self.code,date) tmp.append(dls.get_pee()) return pd.Series(tmp, index=self.dates) def get_pbes(self): tmp = [] for date in self.dates: dls = DataLoaderSingle(self.code,date) tmp.append(dls.get_pbe()) return pd.Series(tmp, index=self.dates) def get_pems(self): tmp = [] for date in self.dates: dls = DataLoaderSingle(self.code,date) tmp.append(dls.get_pem()) return pd.Series(tmp, index=self.dates) def get_pbms(self): tmp = [] for date in self.dates: dls = DataLoaderSingle(self.code,date) tmp.append(dls.get_pbm()) return pd.Series(tmp, index=self.dates) def get_index_df(self): pes,pbs,pees,pbes,pems,pbms,prices = [],[],[],[],[],[],[] for date in self.dates: dls = DataLoaderSingle(self.code,date) pes.append(dls.get_pe()) pbs.append(dls.get_pb()) pees.append(dls.get_pee()) pbes.append(dls.get_pbe()) pems.append(dls.get_pem()) pbms.append(dls.get_pbm()) prices.append(dls.get_index_price()) df = pd.DataFrame(index=self.dates) for word in WORDS: df[word.upper()]=eval(word+'s') return df class DataLoader(object): def __init__(self, codes, dates): self.codes = codes self.dates = dates def get_index_dic(self): dic = {} info = {} display_name=[] codes = [] start_date = [] end_date = [] for code in self.codes: dl = DataLoaderSingleCode(code, self.dates) dic[code] = dl.get_index_df() raw_info = get_security_info(code) codes.append(raw_info.code) display_name.append(raw_info.display_name) start_date.append(raw_info.start_date) end_date.append(raw_info.end_date) info['code'] = codes info['display_name'] = display_name info['start_date'] = start_date info['end_date'] = end_date dic['info'] = pd.DataFrame(info) return dic
776eb1c19e117ae3864d2b5fa585cfad85a57af3
[ "Python" ]
4
Python
wky0913/finweb-online
3f3a18b626149a04181fc9d3bf69cdc633c0c4e1
2f7892cb9be520f6e9ac4c818db98898aec4cea9
refs/heads/master
<file_sep> /** * BreakingCipher * Decrypts text that is encrypted using one/two keys * @author (Aida) * @version (Jan,2016) */ import edu.duke.*; public class BreakingCipher { public int[] countLetters(String message){ String alph = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; int[] counts = new int[26]; for(int i=0; i < message.length(); i++){ char ch = Character.toUpperCase(message.charAt(i)); int index = alph.indexOf(ch); if(index != -1){ counts[index] +=1; } } return counts; } public int maxIndex(int[] frqes){ int maxInd = 0; for(int i=0; i < frqes.length; i++){ if(frqes[i] > frqes[maxInd]){ maxInd = i; } } return maxInd; } public String decrypt(String encrypted){ CaesarCipher cc = new CaesarCipher(); int[] freqs = countLetters(encrypted); int maxInd = maxIndex(freqs); int dkey = maxInd - 4; if(maxInd < 4){ dkey = 26 - (4-maxInd); }else{ dkey = maxInd - 4; } return cc.encrypt(encrypted, 26-dkey); } public void testDecrypt(){ FileResource fr = new FileResource(); CaesarCipher ciph = new CaesarCipher(); String encrypted = ciph.encrypt(fr.asString(), 15); String decrypted = decrypt(encrypted); System.out.println(decrypted); } public String halfOfString(String message, int start){ StringBuilder sb = new StringBuilder(message); String halfS = ""; for(int i = start; i < sb.length(); i+=2){ char curr = sb.charAt(i); halfS = halfS + curr; } return halfS; } public int getKey(String s){ int[] freq = countLetters(s); int maxI = maxIndex(freq); int dkey = maxI - 4; if(maxI < 4){ dkey = 26 - (4-maxI); } return dkey; } public String decryptTwoKeys(String encrypted){ CaesarCipher cc = new CaesarCipher(); String one = halfOfString(encrypted,0); String two = halfOfString(encrypted,1); int key1 = getKey(one); int key2 = getKey(two); System.out.println("key1 = " + key1 + " key2 = " + key2); return cc.encryptTwoKeys(encrypted, 26-key1, 26-key2); } public void testDecryptTwoKeys(){ FileResource fr = new FileResource(); CaesarCipher ciph = new CaesarCipher(); String encrypted = fr.asString();//ciph.encryptTwoKeys(fr.asString(), 23, 2); String decrypted = decryptTwoKeys(encrypted); System.out.println(decrypted); } } <file_sep># Few algorithmes in java. <file_sep>PROJECT TITLE: Manipulation of characters in a file. PURPOSE OF PROJECT:Practice work VERSION or DATE:Jan, 2016 HOW TO START THIS PROJECT: AUTHORS: USER INSTRUCTIONS: <file_sep> /** * CaesarCipherO class encrypts a message with one key * and also decrypts the same message. Implements OO concept. * * @author (Aida) * @version (Jan, 2016) */ public class CaesarCipherO { private String alphabet; private String shifted; private int mainKey; public CaesarCipherO(int key){ mainKey = key; alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; shifted = alphabet.substring(mainKey)+ alphabet.substring(0,mainKey); } public String encrypt(String input){ StringBuilder sb = new StringBuilder(input); for(int i=0; i < sb.length(); i++){ char ch = sb.charAt(i); if(Character.isUpperCase(ch) != true){ ch = Character.toUpperCase(ch); int idx = alphabet.indexOf(ch); if(idx != -1){ char Nch = shifted.charAt(idx); Nch = Character.toLowerCase(Nch); sb.setCharAt(i, Nch); } }else if(Character.isUpperCase(ch) == true){ int idx = alphabet.indexOf(ch); if(idx != -1){ char Nch = shifted.charAt(idx); sb.setCharAt(i, Nch); } } } return sb.toString(); } public String decrypt(String input){ CaesarCipherO cc = new CaesarCipherO(26-mainKey); return cc.encrypt(input); } }
8694d9d3ff476dd58950d6e78bace6ddeb4333dd
[ "Markdown", "Java", "Text" ]
4
Java
bittidesta/Java-exercise
7d8fb4e45c977b744573103604c15c7c8e1630e2
293eeb5228155d88f3742bcd4adca3529ca0fa69
refs/heads/master
<repo_name>MrSpahceman/GroupProject1<file_sep>/java.js //NOTES for reference: Goolge maps API key: <KEY> // Event listener for a button //$("#button-id").on("click", function() { $(document).ready(); console.log("I'm ready") navigator.geolocation.getCurrentPosition(function(position) { var lat = position.coords.latitude; var long = position.coords.longitude; console.log(lat, long); $("p").append(lat, long); // Storing our google API URL for refence to use var queryURL = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + lat + "," + long + "&key=<KEY>"; // Perfoming an AJAX GET request to our queryURL $.ajax({ url: queryURL, method: "GET" }) // After the data from the AJAX request comes back .done(function(response) { var county = ''; console.log("We have your location - muahaha") var results = response.results; //console.log(response); // Get County for (i = 0; i < results.length; i++) { if ((results[i].types.indexOf("administrative_area_level_2")) !== -1) { console.log(results[i].types); county = (results[i].address_components[0].long_name); //console.log(county); console.log("Ready"); county = county.replace(/\sCounty/gi, ""); county = county.replace(/\s/g, "-"); county = county.toLowerCase(); break; } } // Get Spitcast for County console.log("We know where you are: " + county); if (county.length) { var queryURL = "https://cors.io/?http://api.spitcast.com/api/county/spots/" + county $.ajax({ url: queryURL, method: "GET", dataType: 'json', }).done(function(response) { console.log('spitcast response'); console.log(response); // response = JSON.parse(response); //console.log(response[0].spot_name); for (i = 0; i < response.length; i++) { var spotNames = (response[i].spot_name); console.log(spotNames); } }); } else { console.log("Bad or Missing County"); } }); });
57ac66927d478e13f2914d420a1d5039080d60fe
[ "JavaScript" ]
1
JavaScript
MrSpahceman/GroupProject1
f05a3bb827f02c9ce4961da639d168c76118514f
b576752766516a576676843f625cb5bfdadd7725
refs/heads/master
<file_sep>package com.bokecc.filter; import com.alibaba.fastjson.JSON; import com.bokecc.config.PropertiesObtainConfig; import com.bokecc.constant.Constant; import com.bokecc.util.Base64Util; import lombok.extern.slf4j.Slf4j; import org.glassfish.jersey.server.ContainerRequest; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import java.io.IOException; import java.util.Arrays; import java.util.List; @Slf4j public class SwaggerAuthenticationFilter implements ContainerRequestFilter { private static final String AUTHORIZATION_PROPERTY = "Authorization"; private static final String ACTIVE = "spring.profiles.active"; private static final String ACTIVE_FLAG = "testing"; private static final String ACTIVE_FLAG_DEV = "dev"; private static final String AUTH_URL = "swagger.json"; @Override public void filter(ContainerRequestContext requestContext) throws IOException { ContainerRequest request = (ContainerRequest) requestContext.getRequest(); String url = request.getPath(false); if(!url.equals(AUTH_URL)){ return; } final MultivaluedMap<String, String> headers = requestContext.getHeaders(); final List<String> authorization = headers.get(AUTHORIZATION_PROPERTY); if(authorization == null || authorization.isEmpty()) { requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED) .header("WWW-Authenticate", "Basic realm=\"input username and password\"").build()); return; } log.debug(JSON.toJSONString(authorization)); if(!auth(authorization.get(0))){ requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED) .header("WWW-Authenticate", "Basic realm=\"input username and password\"") .entity("认证失败") .build()); return; } log.debug("通过"); } /** * 认证方法体 * @param authHeadValue 认证头的值 * @return true:通过;false:未通过 */ private boolean auth(String authHeadValue) throws IOException { String[] authArray = authHeadValue.split(" "); if(authArray.length < 2){ return false; } String[] userArray = Base64Util.decodeAsString(authArray[1]).split(":"); log.info(Arrays.toString(userArray)); if(userArray.length < 2){ return false; } String userName = userArray[0]; String pw = userArray[1]; String active = PropertiesObtainConfig.env.getProperty(ACTIVE); if (ACTIVE_FLAG.equals(active) || ACTIVE_FLAG_DEV.equals(active)) { return Constant.BASIC_AUTH_USER.equals(userName) && Constant.BASIC_AUTH_PW_TESTING.equals(pw); } return Constant.BASIC_AUTH_USER.equals(userName) && Constant.BASIC_AUTH_PW_ONLINE.equals(pw); } } <file_sep>package com.bokecc.entity.annotation; import org.springframework.stereotype.Component; import java.lang.annotation.*; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Component public @interface JerseyRest { } <file_sep>package com.bokecc.config; import com.bokecc.entity.annotation.JerseyRest; import com.bokecc.filter.JerseyResponseFilter; import com.bokecc.filter.SwaggerAuthenticationFilter; import io.swagger.jaxrs.listing.ApiListingResource; import io.swagger.jaxrs.listing.SwaggerSerializers; import org.glassfish.jersey.server.ResourceConfig; import io.swagger.jaxrs.config.BeanConfig; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Configuration; import org.glassfish.jersey.server.ServerProperties; import org.springframework.beans.factory.annotation.Autowired; import javax.ws.rs.ApplicationPath; import lombok.extern.slf4j.Slf4j; import java.util.Map; import javax.annotation.PostConstruct; @Configuration @Slf4j @ApplicationPath("/api") public class JerseyConfig extends ResourceConfig{ @Autowired private ApplicationContext applicationContext; public JerseyConfig() { } @PostConstruct private void init(){ this.register(GlobalExceptionHandler.class); this.register(JerseyResponseFilter.class); this.register(ViolationExceptionHandler.class); this.register(SwaggerAuthenticationFilter.class); property(ServerProperties.BV_SEND_ERROR_IN_RESPONSE, true); // 寻找所有JerseyRest注解的Resources Map<String, Object> resources = applicationContext.getBeansWithAnnotation(JerseyRest.class); if(resources.isEmpty()){ return; } resources.forEach((x, y) ->{ this.register(y.getClass()); }); // 配置Swagger文档 configureSwagger(); } private void configureSwagger() { // Available at localhost:port/swagger.json this.register(ApiListingResource.class); this.register(SwaggerSerializers.class); BeanConfig config = new BeanConfig(); config.setConfigId("eagle-eye"); config.setTitle("API 文档"); config.setSchemes(new String[] { "http"}); config.setBasePath("/api"); config.setResourcePackage("com.bokecc.resource"); config.setPrettyPrint(true); config.setScan(true); } } <file_sep>package com.bokecc; import com.baomidou.mybatisplus.plugins.PaginationInterceptor; import lombok.extern.slf4j.Slf4j; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.ServletComponentScan; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.web.client.RestTemplate; @Slf4j @EnableAsync @EnableCaching @EnableScheduling @SpringBootApplication(scanBasePackages={"com.bokecc"}) @EnableTransactionManagement @ServletComponentScan(basePackages = {"com.bokecc"}) public class Application implements CommandLineRunner { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Override public void run(String... args) throws Exception { log.info(":::#####################################################################"); log.info(":::congratulation to you! the application has started successfully!"); log.info(":::#####################################################################"); } } <file_sep>package com.bokecc.schedule; /** * @author: <NAME>(chufuying) * @date: 2020/1/9 * @version: 0.0.1 * @jdk: 1.8 * @email: <EMAIL> **/ public class TestJob { } <file_sep>package com.bokecc.resource; import com.bokecc.Application; import com.bokecc.model.User; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.PropertyNamingStrategy; import org.json.JSONObject; import org.junit.Assert; import org.junit.BeforeClass; 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.web.client.RestTemplateBuilder; import org.springframework.context.annotation.Bean; import org.springframework.http.*; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.client.RestTemplate; // SpringMVC测试Resource //@RunWith(SpringRunner.class) //表示在测试环境中运行 //@SpringBootTest(classes = Application.class) //public class UserResourceTest { // // @Autowired // private WebApplicationContext wac; // // private MockMvc mvc; // // private MockHttpSession session; // @Autowired // ObjectMapper mapper; // // @Before // public void setupMockMvc(){ // //初始化MockMvc对象 // mvc = MockMvcBuilders.webAppContextSetup(wac).build(); // } // // @Test // public void getUser() throws Exception{ // int id = 1; // String uri = "/api/user/" + id; // RequestBuilder request = MockMvcRequestBuilders.get(uri) // .contentType(MediaType.APPLICATION_JSON_UTF8) // .accept(MediaType.APPLICATION_JSON_UTF8); // // mvc.perform(request) // .andExpect(MockMvcResultMatchers.status().isOk()) // .andDo(MockMvcResultHandlers.print()); // } // // @Test // public void getUsers() throws Exception { // String uri = "/api/user"; // RequestBuilder request = MockMvcRequestBuilders.get(uri) // .contentType(MediaType.APPLICATION_JSON_UTF8) // .accept(MediaType.APPLICATION_JSON_UTF8); // // mvc.perform(request) // .andExpect(MockMvcResultMatchers.status().isOk()) // .andDo(MockMvcResultHandlers.print()); // } // // @Test // @Transactional // public void addUser() throws Exception{ // String uri = "/api/user"; // // User user = new User(); // user.setUserName("test"); // user.setUserId("1213"); // // jackjson序列化 // String json = mapper.writeValueAsString(user); // // RequestBuilder request = MockMvcRequestBuilders.post(uri) // .accept(MediaType.APPLICATION_JSON_UTF8) // .content(json.getBytes()); // // mvc.perform(request) // .andExpect(MockMvcResultMatchers.status().isOk()) // .andDo(MockMvcResultHandlers.print());; // } // // @Test // @Transactional // public void deleteUser() throws Exception{ // String uri = "/api/user/1"; // // RequestBuilder request = MockMvcRequestBuilders.delete(uri) // .accept(MediaType.APPLICATION_JSON_UTF8); // // mvc.perform(request) // .andExpect(MockMvcResultMatchers.status().isOk()) // .andDo(MockMvcResultHandlers.print());; // } //} //Jersey测试Resources @RunWith(SpringRunner.class) //表示在测试环境中运行 @SpringBootTest(classes = Application.class) public class UserResourceTest { private static final String server_name = "http://localhost:8080"; private static HttpHeaders headers; @Autowired ObjectMapper mapper; @Autowired private RestTemplate restTemplate; @Bean public RestTemplate restTemplate(RestTemplateBuilder builder){ return builder.build(); } @BeforeClass public static void setHeader(){ headers = new HttpHeaders(); MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8"); headers.setContentType(type); headers.add("Accept", MediaType.APPLICATION_JSON.toString()); } @Test public void getUser() throws Exception{ int id = 1; String url = server_name + "/api/user/1"; HttpEntity<String> httpEntity = new HttpEntity<String>(null, headers); ResponseEntity<User> response = restTemplate.getForEntity(url, User.class, httpEntity); Assert.assertEquals(response.getStatusCode(), HttpStatus.OK); User user = response.getBody(); Assert.assertNotNull(user); } @Test public void getUsers() throws Exception { String url = server_name + "/api/user"; HttpEntity<String> httpEntity = new HttpEntity<String>(null, headers); ResponseEntity<User[]> response = restTemplate.getForEntity(url, User[].class, httpEntity); Assert.assertEquals(response.getStatusCode(), HttpStatus.OK); User[] userList = response.getBody(); Assert.assertTrue(userList.length > 0); } @Test @Transactional public void addUser() throws Exception { String url = server_name + "/api/user"; User user = new User(); user.setUserName("test"); user.setUserId("1213"); // jackjson序列化 mapper.setPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CASE); String json = mapper.writeValueAsString(user); JSONObject userJSon = new JSONObject(); HttpEntity<String> httpEntity = new HttpEntity<String>(json, headers); ResponseEntity<String> response = restTemplate.postForEntity(url, httpEntity, String.class); Assert.assertEquals(response.getStatusCode(), HttpStatus.OK); Assert.assertNotNull(response); } @Test @Transactional public void updateUser() throws Exception { String url = server_name + "/api/user/" + 1; User user = new User(); user.setUserName("sss"); user.setUserId("1213"); // jackjson序列化 mapper.setPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CASE); String json = mapper.writeValueAsString(user); JSONObject userJSon = new JSONObject(); HttpEntity<String> httpEntity = new HttpEntity<String>(json, headers); ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.PUT, httpEntity, String.class); Assert.assertEquals(response.getStatusCode(), HttpStatus.OK); Assert.assertNotNull(response); } @Test @Transactional public void deleteUser() throws Exception{ String url = server_name + "/api/user/" + 1; // restTemplate.delete(url); ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.DELETE, null, String.class); Assert.assertEquals(response.getStatusCode(), HttpStatus.OK); } }<file_sep>spring boot mybatis-plus swagger jersey 接口文档访问 http://127.0.0.1:8080/index.html <file_sep>package com.bokecc.service; public interface ICommonService { }<file_sep>package com.bokecc.config; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationListener; import org.springframework.context.annotation.Configuration; import org.springframework.context.event.ContextRefreshedEvent; @Configuration public class SpringContextHolder implements ApplicationListener<ContextRefreshedEvent> { private static ApplicationContext applicationContext = null; private static Logger logger = LoggerFactory.getLogger(SpringContextHolder.class); /** * 取得存储在静态变量中的ApplicationContext. */ public static ApplicationContext getApplicationContext() { return applicationContext; } /** * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型. */ @SuppressWarnings("unchecked") public static <T> T getBean(String name) { return (T) applicationContext.getBean(name); } /** * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型. */ public static <T> T getBean(Class<T> requiredType) { return applicationContext.getBean(requiredType); } /** * 清除SpringContextHolder中的ApplicationContext为Null. */ public static void cleanHolder() { logger.debug("清除SpringContextHolder中的ApplicationContext:" + applicationContext); applicationContext = null; } @Override public void onApplicationEvent(ContextRefreshedEvent event) { logger.info("init thread..."); applicationContext = event.getApplicationContext(); } } <file_sep>package com.bokecc.config; import com.bokecc.supports.RestResponse; import com.bokecc.supports.CommonErrorCode; import lombok.extern.slf4j.Slf4j; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; /** * 全局异常处理 */ @Slf4j @Provider public class GlobalExceptionHandler implements ExceptionMapper<Exception> { @Override public Response toResponse(Exception exception) { log.error("未处理的异常!{}", exception.getClass().getName(), exception); String sb = exception.getClass().getSimpleName() + " --> " + exception.getMessage(); RestResponse res = new RestResponse(CommonErrorCode.UNKNOWN_ERROR.getCode(), sb, null); return Response.ok(res, MediaType.APPLICATION_JSON_TYPE).status(500).build(); } }
231c4c3795a79b94ce55023e489b7b1601b3262c
[ "Markdown", "Java" ]
10
Java
tmacjx/jerseydemo
890d8b68f461b47a51d10a4a0e37bdba26ce26b1
3c053da0e558553c90d782a926159169b73f7af6
refs/heads/master
<file_sep>def sqrt(number) sqrt_recursive(number, 0, number) end def sqrt_recursive(num, min_interval, max_interval) mid = (min_interval+max_interval)/2.round if mid**2 == num mid elsif mid**2 < num min_interval = mid+1 sqrt_recursive(num,min_interval,max_interval) else max_interval = mid-1 sqrt_recursive(num,min_interval,max_interval) end end <file_sep>require_relative './node.rb' require_relative './linked-list.rb' class Queue attr_accessor :storage def initialize @storage = LinkedList.new end def enqueue(element) @storage.add_at(0,element) end def dequeue @storage.remove_at(@storage.length-1) end def size @storage.size end def empty? return true unless size > 0 end end # @queue = Queue.new # @queue.enqueue(19) # @queue.enqueue(7) # @queue.enqueue(3) # @queue.enqueue(45) # puts @queue.storage.get_all # puts @queue.dequeue <file_sep>require_relative 'tree-node.rb' class BinaryTree attr_accessor :root def initialize(key) @root = Node.new(key) end def insert(key) # if key == 0 # return # end queue = [] queue.unshift(@root) until queue.empty? temp = queue.pop if temp.left.nil? temp.left = Node.new(key) break else queue.unshift(temp.left) if temp.right.nil? temp.right = Node.new(key) break else queue.unshift(temp.right) end end end end # FIXME: not working properly def delete(key) arr = [] arr.push(@root) temp_node = nil until arr.empty? temp_node = arr.pop if temp_node.key == key temp_node = nil return end unless temp_node.right.nil? if temp_node.right.key == key temp_node.right = nil return else arr.push(temp_node.right) end end unless temp_node.left.nil? if temp_node.left.key == key temp_node.left = nil return else arr.push(temp_node.left) end end end end # returns the biggest element from a tree def max level_order.max end # returns the smallest element from a tree def min level_order.min end # returns the tree height def tree_height tree_height_recursive(@root) end # DFS Inorder Traversal def print_in_order print_in_order_recursive(@root) end # level order array def level_order_arr arr = [] # this is the array that we will return to the user queue = [] # this is a temp array to iterate throught elements queue.unshift(@root) until queue.empty? tempNode = queue.pop arr.push(tempNode.key) queue.unshift(tempNode.left) unless tempNode.left.nil? queue.unshift(tempNode.right) unless tempNode.right.nil? end arr end # DFS Preorder Traversal def print_pre_order print_pre_order_recursive(@root) end # DFS Postorder Traversal def print_post_order print_post_order_recursive(@root) end # find the longest path on the tree def tree_diameter # FIXME: find_diameter_recursive(@root) end def is_bst? is_bst_recursive(@root, -(2**(0.size * 8 - 2)), (2**(0.size * 8 - 2) - 1)) end def is_height_balanced? is_balanced_recursive(@root) end private def is_balanced_recursive(root) return true if root.nil? left_height = tree_height_recursive(root.left) right_height = tree_height_recursive(root.right) if (left_height - right_height).abs <= 1 && is_balanced_recursive(root.left) && is_balanced_recursive(root.right) return true end false end def is_bst_recursive(root, min, max) # an empty tree is a bst return true if root.nil? # false if this node violates the min/max constraints */ return false if (root.key < min) || (root.key > max) if is_bst_recursive(root.left, min, root.key - 1) && is_bst_recursive(root.right, root.key + 1, max) return true else return false end end # Depth first traversal in order (Left,Root,Right) def print_in_order_recursive(node) return if node.nil? # first start on the left child print_in_order_recursive(node.left) # then print the data of the node print node.key.to_s + ' ' # now recur on the right child print_in_order_recursive(node.right) end # Depth first traversal pre order (Root,Left,Right) def print_pre_order_recursive(node) return if node.nil? # first print the data of the node print node.key.to_s + ' ' # then recur on the left sub tree print_pre_order_recursive(node.left) # then on the right subtree print_pre_order_recursive(node.right) end # Depth first traversal post order (Left,Right,Root) def print_post_order_recursive(node) return if node.nil? # first recur on the left sub-tree print_post_order_recursive(node.left) # then ocur on the right sub-tree print_post_order_recursive(node.right) print node.key.to_s + ' ' end # the recursive function to get tree height def tree_height_recursive(node) if node.nil? 0 else left_height = tree_height_recursive(node.left) right_height = tree_height_recursive(node.right) if left_height > right_height return left_height + 1 else return right_height + 1 end end end end # boilerplate code def array_to_tree(array, i) return nil if i >= array.length || array[i] == 0 node = Node.new(array[i]) node.left = array_to_tree(array, 2*i+1) node.right = array_to_tree(array, 2*i+2) node end tree = array_to_tree([1, 2, 0, 3, 4, 0, 0],0) tr = "hello" # p tree.root.key # p tree.level_order_arr # # p tree.is_height_balanced? <file_sep>class Node attr_accessor :key,:left,:right def initialize(key) @key = key @left = @right = nil end end def array_to_tree(array, start,ending) return nil if start > ending # new code midle = (start+ending)/2 node = Node.new(array[midle]) node.left = array_to_tree(array,start,midle-1) node.right = array_to_tree(array,midle+1,ending) node end def binary_search_tree(array) # your code here tree = array_to_tree([10, 12, 15, 7, 2, 23, 9, 14, 21],0,array.length-1) print_pre_order(tree); # smaller_than = [] # bigger_than = [] # array.each_index do |index| # if array[0] >= array[index] # smaller_than << array[index] # else # bigger_than << array[index] # end # end # binary_search_tree(bigger_than) # result = smaller_than + bigger_than # result = result[0..result.length-2] # result end def print_pre_order(node) if node == nil return end print node.key.to_s+" " print_pre_order(node.left) print_pre_order(node.right) end binary_search_tree([10, 12, 15, 7, 2, 23, 9, 14, 21]) # => 10 7 2 9 12 15 [14 23] 21 # => 10 7 2 9 12 15 [23 14] 21<file_sep># this is count sorting algorithm def count_sort(array) <file_sep>def sum(number) # Your code here number == 0 ? 0 : number + sum(number-1) end puts sum(4) puts sum(10)<file_sep>class Vertex attr_accessor :key,:src,:dest def initialize(key) @key = key @src = @dest = nil end end class Queue attr_accessor :storage def initialize @storage = Array.new end def enqueue(element) @storage.insert(0,element) end def poll @storage.pop end def size @storage.size end def empty? return true unless size > 0 end end class Graph attr_accessor :vertices, :adjList # initializing the graph with the number of vertices that we will have def initialize(v) @vertices = v @adjList = Array.new(v) # create a list for each vertex @adjList.each_index do |index| @adjList[index] = [] end end # adds an edge to a un directed graph def add_edge(src, dest) # add a edge to the head @adjList[src] << dest # since this graph is not directed we need to do the oposite also # @adjList[dest] << src end def is_component? visited = Array.new(@vertices, false) i = 0 counter = 0 while i < visited.length if !visited[i] depth_first_recursion(i, visited) counter += 1 end i += 1 end if counter > 1 return false else return true end end def self.hash_to_graph(_hash) gr = Graph.new(_hash.keys.size) _hash.each do |key, value| value.each do |element| gr.add_edge(key, element) end end gr end private # The recursive function used by DFS def depth_first_recursion(v, visited) # Mark the current node as visited and print it visited[v] = true # print v.to_s + ' ' head = @adjList[v] head.each_index do |index| n = head[index] depth_first_recursion(n, visited) unless visited[n] end end end def connected_graph?(graph) # write your code here gr = Graph.hash_to_graph(graph) gr.is_component? end puts connected_graph?( 0 => [2], 1 => [4], 2 => [0, 5, 3], 3 => [5, 2], 4 => [5, 1], 5 => [4, 2, 3] ) # => true puts connected_graph?( 0 => [1, 2], 1 => [0, 2], 2 => [0, 1, 3, 4, 5], 3 => [2, 4], 4 => [3, 2], 5 => [2] ) # => true <file_sep>def move(start,goal) ar=[1,2,3]-[start]-[goal] return "#{start}->#{ar[0]} #{start}->#{goal} #{ar[0]}->#{goal}" end puts move(1, 3) # => 1->2 1->3 2->3 puts move(2, 3) # => 2->1 2->3 1->3 puts move(1,2) # 1->3 1->2 3->2 puts move(2,1) # 2->3 2->1 3->1<file_sep>require_relative '../basic-data-structures/graphs/graph.rb' def bfs(graph) # write your code her gr = Graph.new(graph.keys.size) graph.each do |key, value| value.each do |element| gr.add_edge(key, element) end end gr.breadth_first_traverse(0) end p bfs(0 => [2], 1 => [4], 2 => [5, 0, 3], 3 => [2], 4 => [1, 5], 5 => [4, 2]) # => [0, 2, 5, 3, 4, 1] puts # bfs({0=>[1, 2], 1=>[0, 2], 2=>[0, 1, 3, 4, 5], 3=>[2, 4], 4=>[3, 2], 5=>[2]}) # => [0, 1, 2, 3, 4, 5] puts # bfs({0=>[1, 2], 1=>[0, 3, 4], 2=>[0, 5, 6], 3=>[1], 4=>[1], 5=>[2], 6=>[2]}) # => [0, 1, 2, 3, 4, 5, 6] puts # bfs({0=>[3], 1=>[2, 3], 2=>[4, 1], 3=>[1, 0], 4=>[2]}) # => [0, 3, 1, 2, 4] puts # bfs({0=>[1, 2], 1=>[0, 3, 4], 2=>[0, 5, 6], 3=>[1], 4=>[1, 5], 5=>[2, 4], 6=>[2]}) # => [0, 1, 2, 3, 4, 5, 6] <file_sep>require './node.rb' class List attr_accessor :head,:tail def add(number) new_node = Node.new(number) if @head==nil @head = new_node @head.next=@tail new_node.next else last_node = @head while last_node.next != nil last_node = last_node.next end last_node.next = new_node end end def get(index) current = @head for i in 0..index-1 current = current.next end return current.data end def get_all node = @head counter = 0 data = "" while node != nil data += "[#{counter}] => #{node.data} " node = node.next counter += 1 end return data end end # Bolierplate code # list = List.new # list.add(1) # list.add(15) # list.add(16) # puts list.get_all<file_sep>def insertion_sort(array) # write your code here i = 1 while i < array.length key = array[i] j = i-1 while j >= 0 && array[j] >= key array[j+1] = array[j] j -= 1 end array[j+1] = key puts array.join(' ') i+=1 end end arr = [12,11,13,5,6] print arr insertion_sort(arr)<file_sep>class Node attr_accessor :data, :next def initialize(data) @data = data end end<file_sep>class SlidingMax def find_max(arr,k) i = 0 start_index = 0 end_index = k max_numbers = '' while i <= arr.length if i >= k max_numbers += " "+ max(arr[start_index...end_index]).to_s start_index += 1 end_index += 1 end i += 1 end return max_numbers end private def max(arr) max = arr[0] arr.each_index do |i| if arr[i] > max max = arr[i] end end return max end end @max = SlidingMax.new arr = [1,3,5,7,9,2] k = 3 puts @max.find_max(arr,k) <file_sep>class Node attr_reader :data attr_accessor :left, :right def initialize(data) @data = data end end def array_to_tree(array, i) return nil if i >= array.length || array[i] == 0 node = Node.new(array[i]) node.left = array_to_tree(array, 2 * i + 1) node.right = array_to_tree(array, 2 * i + 2) node end def is_height_balanced?(root) return true if root.nil? left_height = tree_height(root.left) right_height = tree_height(root.right) if (left_height - right_height).abs <= 1 && is_height_balanced?(root.left) && is_height_balanced?(root.right) return true end false end def tree_height(node) if node.nil? 0 else left_height = tree_height(node.left) right_height = tree_height(node.right) if left_height > right_height return left_height + 1 else return right_height + 1 end end end def balanced_tree?(arr) # write your code here is_height_balanced?(array_to_tree(arr, 0)) end puts balanced_tree?([1, 2, 0, 3, 4, 0, 0]) # => false puts balanced_tree?([1, 2, 3, 4, 5, 6, 7]) # => true <file_sep>def search_tree?(tree) # create an empty stack stack = [] root = -(2**(0.size * 8 -2)) i = 0 while i <= tree.length-1 if tree[i] < root return false end while !stack.empty? && stack.last < tree[i] root = stack.pop end stack.push(tree[i]) i += 1 end return true end # puts search_tree?([10, 4, 12]) # => true puts search_tree?([10, 5, 7]) # => false<file_sep>require_relative '../basic-data-structures/graphs/graph.rb' def depth_first_search(graph) # write your code her gr = Graph.new(graph.keys.size) graph.each do |key, value| value.each do |element| gr.add_edge(key, element) end end gr.depth_first(0) end depth_first_search( 0 => [2], 1 => [4], 2 => [5, 0, 3], 3 => [2], 4 => [1, 5], 5 => [4, 2] ) # => [0, 2, 5, 4, 1, 3] <file_sep>require_relative './/node.rb' class LinkedList attr_accessor :head,:length def initialize @length = 0 end def size @length end def add(item) node = Node.new(item) if @head == nil @head = node @length += 1 else current_node = @head while current_node.next != nil current_node = current_node.next end current_node.next = node @length += 1 end end def add_at(index,item) node = Node.new(item) current_node = @head previus_node = nil current_index = 0 if index > @length return -1 end if index == 0 node.next = current_node @head = node @length += 1 return @head.data else while current_index < index current_index += 1 previus_node = current_node current_node = current_node.next end node.next = current_node previus_node.next = node @length += 1 return node.data end end # remove data based on index def remove_at(index) current_node = @head previus_node = nil current_index = 0 if index < 0 return -1 end if index == 0 @head = current_node.next @length -= 1 else while current_index < index current_index += 1 previus_node = current_node current_node = current_node.next end previus_node.next = current_node.next @length -= 1 end return current_node.data end # remove data def remove(data) current_node = @head if current_node.data == data @head = current_node.next @length -= 1 else while current_node.data != data previus_node = current_node current_node = current_node.next end previus_node.next = current_node.next @length -= 1 end return current_node.data end # returns the element based on index def element_at(index) puts "element_at #{index}" if index < 0 return -1 end if index == 0 current_node = @head if current_node != nil return current_node.data else return -1 end end current_node = @head counter = 0 while counter < index counter += 1 current_node = current_node.next end return current_node.data end # returns the node based on the data def get(data) current_node = @head if current_node.data == data return current_node end while current_node.data != data current_node = current_node.next end if current_node.data == data return current_node else return -1 end end def get_all node = @head counter = 0 data = "" while node != nil data += "[#{counter}] => #{node.data} " node = node.next counter += 1 end return data end end # Bolierplate code # @linked_list = LinkedList.new # @linked_list.add(1) # puts @linked_list.get_all # @linked_list.add_at(0,100) # puts @linked_list.get_all # @linked_list.remove_at(1) # puts @linked_list.get_all # @linked_list.add(22) # @linked_list.add(14) # @linked_list.add(56) # puts @linked_list.get_all # puts @linked_list.remove_at(1) # puts @linked_list.get_all # puts @linked_list.remove(56) # puts @linked_list.get_all <file_sep>require_relative './ee-node.rb' class BinarySearchTree attr_accessor :root def initialize(key=nil) if key != nil @root = Node.new(key) end end # searching for a key def search(key) # return root if its nil or has the same key if @root == nil or @root.key == key return @root end # value is greater than root's key if @root.key > key return search(@root.left,key) else # value is less than root's key return search(@root.right,key) end end # inserting a key into a tree def insert(key) @root = insert_recursive(@root,key) end # printing in depth first traversal Inorder def print_in_order print_in_order_recursive(@root) end # printing in depth first traversal pre order def print_pre_order print_pre_order_recursive(@root) end def delete_key(key) @root = delete_recursive(@root,key) end private # the recursive function to insert a new key into BST def insert_recursive(root,key) # if the root is empty then return a new tree if root == nil root = Node.new(key) return root end # Othervise recur down the tree if key < root.key root.left = insert_recursive(root.left,key) elsif key > root.key root.right = insert_recursive(root.right,key) end # return the unchanged node pointer return root end # the recursive function to print in order def print_in_order_recursive(root) if root != nil print_in_order_recursive(root.left) print root.key.to_s+" " print_in_order_recursive(root.right) end end # the recursive function to print pre order def print_pre_order_recursive(root) if root != nil print root.key.to_s+" " print_pre_order_recursive(root.left) print_pre_order_recursive(root.right) end end #the recursive function to delete a node def delete_recursive(root,key) # if the tree is empty if root == nil return nil end # otherwise recur down the tree if key < root.key root.left = delete_recursive(root.left,key) elsif key > root.key root.right = delete_recursive(root.right,key) else # if the key is the same as root key then this is the node # to be deleted if root.left == nil return root.right elsif root.right == nil return root.left end # get the smallest in right sub tree root.key = min_value(root.right) # delete the inorder successor root.right = delete_recursive(root.right,root.key) end return root end # find the smallest key in the sub tree def min_value(node) min = node.key while node.left != nil min = node.left.key node = node.left end return min end end # boiler plate code bst = BinarySearchTree.new(50) bst.insert(30) bst.insert(20) bst.insert(40) bst.insert(70) bst.insert(60) bst.insert(80) bst.print_in_order bst.delete_key(30) puts bst.print_in_order <file_sep>def exact_sum?(k,coins) len = coins.length subSum?(len,k,coins) end def subSum?(length,sum,ar_coins) if sum == 0 return true end if length == 0 and sum != 0 return false end # if last element is greater than sum ignore it if ar_coins[length-1] > sum return subSum?(length-1,sum,ar_coins) end if subSum?(length-1,sum-ar_coins[length-1],ar_coins) == true return true else return subSum?(length-1,sum,ar_coins) end end puts "#{exact_sum?(12, [1, 2, 3, 4, 5])}:true" # => true puts "#{exact_sum?(11, [1, 5, 9, 13])}:false" # => false puts "#{exact_sum?(50, [1, 3, 5, 37, 18, 5])}:true" # => true<file_sep>def transpose(string) while string.match(/gn/) string.gsub!("gn","ng") end string end<file_sep>## Ruby Data Structures And Algorithms * Mos popular data structures and algorithms implemented on ruby programming language. ## Data structures * Nodes * Lists * Linked Lists * Stack * Queue * Binary Tree * Binary Search Tree * Heap ## Algorithms challenges * MinStack * Sliding Maximum * Balanced Brackets * Transposition * Stacks or Recursion * Basic Recursion * Binary Search * Tower of Hanoi Part1 * Tower of Hanoi Part2 * Backtracking Recursion * Sum of left most tree * Binary Tree traversal (DFS Post Order Traversal) * Binary Search Tree traversals (DFS Pre Order Traversal) * How Tall is a tree ? ## Searching algorithms ## Sorting algoriths * CountSort * InsertionSort * QuickSort ## Libraries used * Rspec * Byebug <file_sep>require_relative '../basic-data-structures/stack.rb' class BalancedBrackets attr_accessor :stack def initialize @stack = Stack.new end def is_balanced?(string) # create the array string_arr = string.split('') string_arr.each_index do |i| if string_arr[i] == '{' or string_arr[i] == '(' or string_arr[i] == '[' @stack.push(string_arr[i]) end if string_arr[i] == '}' or string_arr[i] == ')' or string_arr[i] == ']' if @stack.size <= 0 return false elsif !is_match_pair?(@stack.pop,string_arr[i]) return false end end end if @stack.size <= 0 return true; else return false end end def is_match_pair?(left_pair,right_pair) if left_pair == '(' and right_pair == ')' return true elsif left_pair == '[' and right_pair == ']' return true elsif left_pair == '{' and right_pair == '}' return true else return false end end end @b = BalancedBrackets.new puts @b.is_balanced?("{}") puts @b.is_balanced?("{[()]}") puts @b.is_balanced?("(hello)[world]") puts @b.is_balanced?("[({}{}{})([])]") puts "------------" puts @b.is_balanced?("(hello - no ending )") puts @b.is_balanced?("([)] - The [ is improperly enclosed in the ().") puts @b.is_balanced?(")( - There's an ending ) without a ( before it.") <file_sep>def hanoi_steps(number_of_discs) # your code here tower(number_of_discs,1,3,2) end def tower(n,from,to,aux) if n == 1 print "#{n} -> #{to} " else tower(n-1,from,aux,to) print "#{from} -> #{to} " tower(n-1,aux,to,from) end end <file_sep># Implementation of Quicksort algorithm def quick_sort(array) sort(array,0,array.length-1) end # The main function that implements quicksort # arr --> the array to be sorted # low --> starting index # high --> ending index def sort(array,low,high) if low < high pi = partition_end(array,low,high) # recursively sort elements before and after partition sort(array,low,pi-1) sort(array,pi+1,high) end array end def partition_end(array,low,heigh) # seting the pivot point from the last element pivot = array[heigh] i = low-1 # index of smaller element j = low while j < heigh # now if the element at position j is smaller or equals to the pivot point # increment i and do a swap array[i] with array[j] if array[j] <= pivot i+=1 # swapping in ruby array[i],array[j] = array[j],array[i] end j+=1 end # swap arr[i+1] and array[heigh] or pivot array[i+1],array[heigh] = array[heigh],array[i+1] return i+1 end # bolerplate code array = [10,80,30,90,40,50,70] print array puts print quick_sort(array) puts <file_sep>def binary_tree_height(array_tree) sc = Math.log(array_tree.length+1)/Math.log(2) sc = sc.to_i sc = sc.ceil-1 return sc+1 end <file_sep>class Node attr_accessor :key,:left,:right def initialize(key) @key = key end end class BinaryTree attr_accessor :root def initialize(key) @root = Node.new(key) end def insert(key) if key == 0 return end queue = [] queue.unshift(@root) until queue.empty? temp = queue.pop() if temp.left.nil? temp.left = Node.new(key) break else queue.unshift(temp.left) if temp.right.nil? temp.right = Node.new(key) break else queue.unshift(temp.right) end end end end # returns the tree height def tree_height tree_height_recursive(@root) end def is_bst? is_bst_recursive(@root, -(2**(0.size * 8 - 2)), (2**(0.size * 8 - 2) - 1)) end private def is_bst_recursive(root, min, max) # an empty tree is a bst return true if root.nil? # false if this node violates the min/max constraints */ return false if (root.key < min) || (root.key > max) if is_bst_recursive(root.left, min, root.key - 1) && is_bst_recursive(root.right, root.key + 1, max) return true else return false end end # the recursive function to get tree height def tree_height_recursive(node) if node.nil? 0 else left_height = tree_height_recursive(node.left) right_height = tree_height_recursive(node.right) if left_height > right_height return left_height + 1 else return right_height + 1 end end end end def search_tree?(arr) tr = BinaryTree.new(arr.shift) arr.each do |item| tr.insert(item) end return tr.is_bst? end puts search_tree?([10, 4, 12]) # => true puts search_tree?([10, 5, 7]) # => false<file_sep>require_relative '../basic-data-structures/stack.rb' class MinStack attr_accessor :stack def initialize @stack = Stack.new end def push(element) @stack.push(element) end def min_element current_node = @stack.list.head min = current_node.data while current_node if current_node.data < min min = current_node.data end current_node = current_node.next end return min end end # BolierPlate Code # @min_stack = MinStack.new # @min_stack.push(100) # @min_stack.push(96) # @min_stack.push(97) # @min_stack.push(95) # @min_stack.push(98) # puts @min_stack.stack.list.get_all # puts "The smallest is: #{@min_stack.min_element}" # puts "--------------------------------" # @min_stack.push(94) # @min_stack.push(90) # @min_stack.push(92) # @min_stack.push(93) # @min_stack.push(89) # puts @min_stack.stack.list.get_all # puts "The smallest is: #{@min_stack.min_element}" # puts "--------------------------------" # @min_stack.push(50) # @min_stack.push(43) # @min_stack.push(27) # @min_stack.push(20) # puts @min_stack.stack.list.get_all # puts "The smallest is: #{@min_stack.min_element}" # puts "--------------------------------" # @min_stack.push(-1) # puts @min_stack.stack.list.get_all # puts "The smallest is: #{@min_stack.min_element}" # puts "--------------------------------" <file_sep>class Node attr_accessor :key,:left,:right def initialize(key) @key = key end end<file_sep>class Node attr_accessor :key, :left , :right def initialize(key) @key = key end end class BinarySearchTree attr_accessor :root,:value def initialize(key=nil) if key != nil @root = Node.new(key) end @value = '' end # inserting a key into a tree def insert(key) @root = insert_recursive(@root,key) end # printing in depth first traversal pre order def print_pre_order print_pre_order_recursive(@root) end private # the recursive function to insert a new key into BST def insert_recursive(root,key) # if the root is empty then return a new tree if root == nil root = Node.new(key) return root end # Othervise recur down the tree if key < root.key root.left = insert_recursive(root.left,key) elsif key > root.key root.right = insert_recursive(root.right,key) end # return the unchanged node pointer return root end # the recursive function to print pre order def print_pre_order_recursive(root) if root != nil # print root.key.to_s+" " @value += root.key.to_s+" " print_pre_order_recursive(root.left) print_pre_order_recursive(root.right) end return @value[0..@value.length-2] end end def binary_search_tree(array) # your code here # creating the instance and the root bst = BinarySearchTree.new(array[0]) array.unshift() array.each do |element| bst.insert(element) end # result = smaller_than + bigger_than # result = result[0..result.length-2] # result value = bst.print_pre_order return value end puts binary_search_tree([8, 3, 10, 1, 6, 14, 4, 7, 13]) # => 8 3 1 6 4 7 10 14 13<file_sep>require_relative './near-ds/node.rb' require_relative './near-ds/linked-list.rb' class Stack attr_accessor :list def initialize @list = LinkedList.new end def push(item) @list.add_at(0,item) end def pop @list.remove_at(0) end def peak @list.element_at(0) end def size @list.length end end # Bolierplate code # @stack = Stack.new # @stack.push(2) # @stack.push(12) # @stack.push(9) # @stack.push(87) # puts "size of stack #{@stack.size}" # puts "peaking into stack #{@stack.peak}" # puts "removing #{@stack.pop}" # puts "size of stack #{@stack.size}" # puts "peaking into stack #{@stack.peak}" # puts "removing #{@stack.pop}" # puts "size of stack #{@stack.size}" # puts "peaking into stack #{@stack.peak}" # puts "removing #{@stack.pop}" # puts "size of stack #{@stack.size}" # puts "peaking into stack #{@stack.peak}" # puts "removing #{@stack.pop}" # puts "size of stack #{@stack.size}" # puts "peaking into stack #{@stack.peak}" <file_sep>def leftmost_nodes_sum(array) # your code here sum = 0 i = 0 while i < array.length sum += array[i] i *= 2 i += 1 end sum end puts leftmost_nodes_sum([2, 7, 5, 2, 6, 0, 9]) # => 11 puts leftmost_nodes_sum([1, 7, 5, 2, 6, 0, 9, 3, 7, 5, 11, 0, 0, 4, 0]) # => 13 puts leftmost_nodes_sum([5, 3, 4, 11, 13, 15, 21, 10, 4, 7, 2, 8, 0, 9, 0]) # => 29<file_sep>require_relative('../basic-data-structures/trees/tree-node.rb') # The Adjacent list Graph class Graph attr_accessor :adjList,:edges,:vertices # initializing the graph with the number of vertices that we will have def initialize(v) @vertices = v @edges = 0 @adjList = Array.new(v) # create a list for each vertex @adjList.each_index do |index| @adjList[index] = [] end end def get_edges (@edges/2).to_i end def get_vertices @vertices end # adds an edge to a un directed graph def add_edge(src, dest) # add a edge to the head @adjList[src] << dest # since this graph is not directed we need to do the oposite also # @adjList[dest] << src @edges += 1 end def has_cycle? return true if (@edges / 2).to_i >= @vertices false end private def self.hash_to_graph(_hash) gr = Graph.new(_hash.keys.size) _hash.each do |key, value| value.each do |element| gr.add_edge(key, element) end end gr end end
61f444d6176eb8df1b5932872528a5f944f95454
[ "Markdown", "Ruby" ]
32
Ruby
azdrenymeri/data-structures
e073a210b04273a1a1859aa8c6bf1890eb720e5f
0f65939bd8ae1080415d1459150d0c6bd7603923
refs/heads/master
<repo_name>FrediBach/XC-Weeks<file_sep>/parse.php <!DOCTYPE html> <head> <meta charset="utf-8"> </head> <body> <?php die(); error_reporting(E_ALL); ini_set('display_errors', 1); $data = file_get_contents('100kflights-2016.html'); $doc = new DOMDocument(); $doc->loadHTML('<?xml encoding="UTF-8">' . $data); /* foreach ($doc->childNodes as $item){ foreach ($item->childNodes as $item1){ foreach ($item1->childNodes as $item2){ foreach ($item2->childNodes as $item3){ echo '.'; foreach ($item3->childNodes as $item4){ echo '-'; foreach ($item4->childNodes as $item5){ echo '!'; } } } } } } */ $flights = array(); foreach ($doc->getElementsByTagName('tr') as $tr) { //echo $tr->nodeValue . '<br />'; $row = array(); $nodes = array(); foreach ($tr->getElementsByTagName('td') as $td) { $row[] = $td->nodeValue; $nodes[] = $td; } $link = ''; foreach($nodes[2]->getElementsByTagName('a') as $link) { $link = $link->getAttribute('href'); } $split = explode('=', $link); $link = $split[1]; $split = explode('&', $link); $link = $split[0]; $split = explode(' ', $link); $lat = $split[0]; $lng = $split[1]; $datestr = substr($row[1], 0, 8); $date = new DateTime('20'.substr($datestr,6,2).'-'.substr($datestr,3,2).'-'.substr($datestr,0,2)); $week = (int)$date->format("W"); $month = $date->format("M"); preg_match("/\/([a-z]+):([a-z]+)\//", $link, $matches); $pilot = ''; if (isset($matches[2])) { $pilot = $matches[2]; } $data = array( 'date' => $datestr, 'week' => $week, 'month' => $month, 'country' => substr($row[2], 0, 2), 'takeoff' => substr($row[2], 2), 'distance' => (float)substr($row[4], 0, -3), 'points' => (float)substr($row[5], 0, -2), 'speed' => (float)$row[6], 'cert' => substr($row[7], 0, 1), 'lat' => (float)$lat, 'lng' => (float)$lng, 'pilot' => $pilot ); $flights[] = $data; //echo $data['date'].' - '.$data['week'].' - '.$data['month'].' - '.$data['country'].' - '.$data['takeoff'].' - '.$data['distance'].' - '.$data['points'].' - '.$data['speed'].' - '.$data['cert'].' - '.$data['lat'].' - '.$data['lng'].'<br />'; } echo count($flights); $weeks = array(); foreach($flights as $flight){ if (!isset($weeks[$flight['week']])){ $weeks[$flight['week']] = array(); } if (!isset($weeks[$flight['week']][$flight['country']])){ $weeks[$flight['week']][$flight['country']] = array('flights' => array(), 'cnt' => 0); } $weeks[$flight['week']][$flight['country']]['flights'][] = $flight; $weeks[$flight['week']][$flight['country']]['cnt']++; } ksort($weeks); function cntsort($item1,$item2) { if ($item1['cnt'] == $item2['cnt']) return 0; return ($item1['cnt'] < $item2['cnt']) ? 1 : -1; } foreach($weeks as $k => $v){ uasort($weeks[$k], 'cntsort'); } file_put_contents('100kflights-2016.json', json_encode($weeks)); echo '!'; <file_sep>/README.md # XC-Weeks The best weeks to fly XC paragliding all around the world <file_sep>/indexsource.php <!DOCTYPE html> <!-- (c) 2015 by <NAME> This is my dream season based on the collected data: 42-43: Bir (India) 2 weeks 44-47: Quixada (Brasil) 4 weeks 48-49: De Aar (South Africa) 2 weeks 50-52: Cornago (Australia) 3 weeks 1-4: Kerio View (Kenia) 4 weeks 5-8: Mt. Borah (Australia) 4 weeks 9-11: Bassano (Italy) 3 weeks 12: Fiesch (Switzerland) 1 week 13: Fanas (Switzerland) 1 week 14: Mornera (Switzerland) 1 week 15-17: Bir (India) 3 weeks 18-19: Fanas (Switzerland) 2 weeks 20-23: Fiesch (Switzerland) 3 weeks 24-25: Sorica (Slovenia) 2 weeks 26-27: Fiesch (Switzerland) 3 weeks 28-30: Piedrahita (Spain) 3 weeks 31-32: Fiesch (Switzerland) 2 weeks 33-34: Speikboden (Italy) 2 weeks 35-36: Stol (Slovenia) 2 weeks 37-40: Serrone (Italy) 4 weeks I'm sure I could fly 100 100ks with this schedule, but I would need at least three gliders ... and be sponsored by Voltaren. ;-) --> <head> <meta charset="utf-8"> <meta name="viewport" content="width=560"> <title>XC Weeks - The best weeks to fly 100k with a paraglider!</title> <style> body, html { margin: 0px; padding: 0px; } body { font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 14px; } img.logo { height: 88px; width: 88px; float: left; margin-right: 40px; margin-left: 35px; margin-top: 10px; margin-bottom: 10px; opacity: 0.7; } p { max-width: 900px; margin-top: 0px; margin-bottom: 8px; } a { color: #fff; } a:hover { text-decoration: none; } .highlighted { color: #fff; } .container { margin: 40px; margin-top: 20px; margin-bottom: 10px; position: relative; } .footer { float: right; } .monthselect { position: absolute; right: 0px; top: 0px; } h1 { margin-top: 0px; margin-bottom: 12px; font-size: 24px; font-family: 'Trebuchet MS','Lucida Grande','Lucida Sans Unicode','Lucida Sans',Tahoma,sans-serif; } .weeks { overflow: hidden; } .week { display: block; width: 474px; height: 418px; float: left; margin: 40px; margin-top: 20px; margin-right: 20px; padding: 4px; overflow: hidden; background: #fff; background: rgba(255,255,255,0.5); border-radius: 3px; -webkit-box-shadow: 0px 0px 20px 3px rgba(0,0,0,0.3); -moz-box-shadow: 0px 0px 20px 3px rgba(0,0,0,0.3); box-shadow: 0px 0px 20px 3px rgba(0,0,0,0.3); } .week .header { color: #000; padding-bottom: 4px; position: relative; } .week .header .rating { position: absolute; top: 0px; right: 0px; } .week .header .rating span { color: rgba(0,0,0,0.1); } .week .header .rating span.active { color: rgba(0,0,0,1); } .week .header .title { font-weight: 18px; font-weight: bold; } .week .header .weekrange { margin-left: 20px; font-size: 12px; } .countries { height: 150px; overflow: auto; } .week .country { padding: 4px; margin-bottom: 2px; margin-left: 2px; margin-right: 2px; position: relative; } .week .action { position: absolute; right: 7px; top: 7px; background: #333; color: #fff; border-radius: 2px; font-size: 10px; padding: 1px; padding-left: 4px; padding-right: 4px; padding-bottom: 2px; cursor: pointer; cursor: hand; -moz-user-select: -moz-none; -khtml-user-select: none; -webkit-user-select: none; -o-user-select: none; user-select: none; } .week .action:hover { background: #000; } .countryinfos { background: rgba(0,0,0,0.05); border-radius: 3px; padding: 2px; } .week .country .title { width: 55px; display: inline-block; } .week .meta { font-size: 11px; margin-left: 15px; color: #666; width: 55px; display: inline-block; } .week .meta.meta100ks { width: 70px; } .week .meta.meta200ks { width: 70px; } .week .meta.metascore { width: 40px; } .week .meta i { font-size: 14px; color: #145a9b; font-weight: bold; font-style: normal; } .week .country .takeoffs { margin-top: 4px; padding-top: 4px; line-height: 160%; display: none; } .week .country .takeoffs .takeoff { display: inline-block; cursor: pointer; cursor: hand; -moz-user-select: -moz-none; -khtml-user-select: none; -webkit-user-select: none; -o-user-select: none; user-select: none; } .week .country .takeoffs .takeoff:hover { text-decoration: underline; } .week .country .takeoffs .flights { color: #B72106; margin-left: 4px; margin-right: 10px; } .week .country .takeoffs a.info { background: rgba(110,79,51,0.8); padding-left: 5px; padding-right: 5px; text-decoration: none; font-size: 10px; line-height: 100%; border-radius: 5px; margin-right: 3px; vertical-align: 10%; font-weight: bold; } .week .country .takeoffs a.info:hover { background: rgba(0,0,0,1.0); } .heatmap { width: 472px; height: 235px; border: 1px #fff solid; border-radius: 4px; margin-bottom: 6px; -webkit-box-shadow: 0px 0px 5px 0px rgba(0,0,0,0.2); -moz-box-shadow: 0px 0px 5px 0px rgba(0,0,0,0.2); box-shadow: 0px 0px 5px 0px rgba(0,0,0,0.2); } body > canvas { position: fixed; top: 0px; bottom: 0px; z-index: -1; } .marker { color: #6e4f33; border-left: 1px rgba(110,79,51,0.8) dotted; border-bottom: 1px rgba(110,79,51,0.8) dotted; padding-left: 8px; padding-bottom: 0px; padding-top: 6px; border-bottom-left-radius: 6px; margin-left: -1px; margin-top: -1px; font-size: 10px; } .marker .text { -moz-text-shadow: 0 0 2px #fff; -webkit-text-shadow: 0 0 2px #fff; text-shadow: 0px 0px 2px #fff; } </style> <link href="http://xcweeks.com/favicon.ico" rel="icon" type="image/x-icon" /> </head> <body> <?php error_reporting(E_ALL); ini_set('display_errors', 1); $jsondata = array(); $jsondata[] = json_decode(file_get_contents('data/100kflights-2016.json')); $jsondata[] = json_decode(file_get_contents('data/100kflights-2015.json')); $jsondata[] = json_decode(file_get_contents('data/100kflights-2014.json')); $jsondata[] = json_decode(file_get_contents('data/100kflights-2013.json')); $jsondata[] = json_decode(file_get_contents('data/100kflights-2012.json')); $jsondata[] = json_decode(file_get_contents('data/100kflights-2011.json')); $jsondata[] = json_decode(file_get_contents('data/100kflights-2010.json')); $jsondata[] = json_decode(file_get_contents('data/100kflights-2009.json')); $data = new stdClass; foreach($jsondata as $jd){ foreach($jd as $week => $countries){ if (!isset($data->{$week})) $data->{$week} = new stdClass; foreach($countries as $country => $meta){ if (!isset($data->{$week}->{$country})){ $data->{$week}->{$country} = new stdClass; $data->{$week}->{$country}->cnt = 0; $data->{$week}->{$country}->flights = array(); } $data->{$week}->{$country}->flights = array_merge($data->{$week}->{$country}->flights, $meta->flights); } } } foreach($data as $week => $countries){ foreach($countries as $country => $meta){ $data->{$week}->{$country}->cnt = count($data->{$week}->{$country}->flights); } } echo '<div class="container">'; echo '<div class="monthselect"><select><option value="" selected>Full year</option><option value="Jan">January</option><option value="Feb">February</option><option value="Mar">March</option><option value="Apr">April</option><option value="May">May</option><option value="Jun">June</option><option value="Jul">July</option><option value="Aug">August</option><option value="Sep">September</option><option value="Oct">October</option><option value="Nov">November</option><option value="Dec">Dezember</option></select></div>'; echo '<img class="logo" src="xc-weeks-logo-4.svg" alt="XC Weeks" title="XC Weeks"><h1>The very best weeks to fly 100k with a paraglider?</h1>'; echo '<p>Ever wondered where to go if you want to fly as many 100k\'s in a year as possible? XC Weeks can help you. It shows you where and in which week you\'ll be able to fly 100km based on the top 25\'000 100km flights of the top ranked pilots in that category.</p>'; echo '<p><span class="highlighted">But take care, some of those places have really strong conditions in those weeks!</span></p>'; echo '</div>'; function getStartAndEndDate($week, $year){ $time = strtotime("1 January $year", time()); $day = date('w', $time); $time += ((7*$week)+1-$day)*24*3600; $return[0] = date('F j.', $time); $time += 6*24*3600; $return[1] = date('F j. Y', $time); return $return; } function getStartMonth($week, $year){ $time = strtotime("1 January $year", time()); $day = date('w', $time); $time += ((7*$week)+1-$day)*24*3600; return date('M', $time); } function getEndMonth($week, $year){ $time = strtotime("1 January $year", time()); $day = date('w', $time); $time += ((7*$week)+1-$day)*24*3600; $time += 6*24*3600; return date('M', $time); } function fixTakeoff($name){ $from = array( 'Roldanillo [...', 'Roldanillo pico', 'borah N', 'Kerio View H...', 'Kerio View S...', 'kerio view', 'Mt Borah South', 'Kerio View Sud', 'kerio', 'Kerio Süd', 'Mt. Borah W', 'zrezane Kerio View', 'South Kerio', 'roldanillo', 'greenacres ...', 'Greenacres west', 'Mt. Borah E', 'Mt. Borah Nor...', 'Picco, Rolda...', 'Mt. Bora', 'Mt. Borah (AU)', 'mt borah', 'Mt. Borah S', 'Roldanillo. ...', 'El Penon', 'Mt. Borahh', 'MT. Borah', 'Mt. Borah NE', 'Stella alpina', 'Bassano [da ...', 'serrone', 'garzetta', 'garzetta gemona', 'Gemona', 'bassano', 'dubbo', '<NAME>', 'Serrone 1', 'Bassano [Ant...', 'Bassano [Cas...', 'B<NAME>', 'Barrington 3...', 'Dubbo north', '<NAME>', '<NAME>', 'Landeck 1', 'Fiesch [Heimat]', 'Wildkogel 2', 'Serrone (IT)', 'marlens', 'Bassano - ta...', 'BASSANO', 'fanas', 'Fanas 2', 'fiesch', 'riederalp', 'Quixada', '<NAME>', 'Piedrahita', '<NAME>', 'Conargo North', 'Manilla', 'greenacres', 'DeAar', 'Pampoenfonte...', 'Roldanillo A...', 'Barrington\'s...', 'Barrington t...', 'quixada', 'quixada sant...', 'Quixadá Sant...', 'DeAar (ZA)', 'Mt. Borah N', 'Qixada', 'Quxada', 'Morada Nova ...', 'Mourada Nouva', 'Mt Borah', 'col rodella', 'K<NAME>', 'St. André [...', 'walts point', 'Walt\'s Point...', 'Walt\'s', 'Fiesch [Heim...', 'erzincan', 'Birstonas', 'Speikboden 2', 'Speikboden 1', '<NAME>', 'Fiesch [Galv...', 'Fiescheralp', 'piedrahita ', '<NAME> 1', 'Birštonas', '<NAME>', 'Fourneuby ', 'Shumen II', 'balea n', 'Balea Lac', 'Balea N', 'Jupiter, Utah', 'speikboden', 'Antholz 1', '<NAME>', '<NAME>', 'Niesen - S', 'defreggen', '<NAME>', '<NAME>', 'sorica', 'Michalkow', 'Cottbus-Nord', 'Cottbus - Nord', 'BALDY, ID', 'Bald mtn sun...', 'bald mtn sun...', 'la Breya', '<NAME> 2', 'Hohe Wand - Ost', 'všechov', 'Všechov - S...', 'King Mtn Idaho', 'King Mountai...', 'SantaRita do...', 'Kocs Csörl�...', 'Kalocsa - S', 'Roldanillo ', 'sfanta ana', 'grente', 'cesaro', 'Bassano [Pan...', 'Malý Pěč�...', 'Emberger Alm 3', 'balea lac', 'castelo de vide', 'corvatch', 'Flims Casson...', 'Mount 7', 'Mt 7 golden', 'Mt 7', 'Mt 7 (Golden)', 'Mt.7 Golden', 'Mt.7', 'MT7', 'Mt. 7', 'Mt.7-Golden, BC', 'MT 7', 'Mt7 Golden', 'Mount Seven ...', 'Mt-7 (Golden)', 'Mount 7 ', 'Mt. 7 Lookout', 'Golden', 'Willi XC Loo...', 'Mount Seven ', 'Mount Sevenn', 'golden', 'Goldenn', 'Lookout', 'Golden ', 'teton village', 'Teton villiage', 'jaragua', 'Jaragua', 'Jaraguá Goi...', '0', '<NAME>', 'Osser - Ostrý', '<NAME>', 'El Salto ', 'la Braya', 'Mackenzie Upper', 'Upper McKenzie', 'Upper Macken...', 'Upper MacKen...', 'Mt. Seven', 'Mt Seven', '<NAME>a�...', 'vale de amor...', '<NAME>', 'balea', 'jupiter', 'PORXOS', 'KOnchinka', 'riederalp (CH)', 'cavallaria f...', 'cavallaria', '<NAME>', 'Speikboden 3', '<NAME>', 'osterfelder', 'osterfelder ', 'Hochrieß', 'JARACUA', 'Galibier', 'Kozakov', 'Kalocsa - N', 'Larouco ', 'Larouco,PT', 'ROKH', 'rokh', 'pebble creek...', 'Porxos Xc', 'Porxos xc', 'Balea N.', 'Deglėnai', 'Milk Hill Wh...', 'la salle ', 'Lin<NAME> ...', 'Linhares 1', 'Olesnica', 'Mackenzie Lower', 'Mackenzie', 'Lower Macken...', 'Mckenzie', 'Mt7', 'Niesen - SW', '<NAME>', 'Breya', '<NAME>', '<NAME>', 'Bischling We...', 'Hebbronville...', 'Hebronville,...', 'Hebronnville...', 'Osterfelder ', 'Mt Mackenzie...', 'Lower Mackenzie', 'Lower MacKenzie', 'Koclířov -...', 'PLAN DE LA B...', 'Jupiter Peak', '<NAME>...', 'Belltall,ES', 'rokh NW', 'Upper MacKenzie', 'Mt 7 Golden BC', 'McKenzie ', '<NAME>', 'Schöckl SO', 'Wildkogel 1', '<NAME>', '<NAME>', 'antholz', 'wank', '<NAME>', ' <NAME>', '<NAME>', '<NAME>0', 'moosalp', 'Kössen 2', 'Seegrube SW', 'Col Rodella ...', 'COL DE L ARP...', 'fort du truc', 'oleśnica', '<NAME>', 'McKenzie - CA', '<NAME>', '<NAME>', 'Saint Hilaire 1', 'Mackenzie ', 'McKenzie upper', 'sunny peak', 'Feuerkogel N', 'Emberger', 'emberger alm', 'Bassano - Ta...', '<NAME>', '<NAME>', 'serpaton', 'les richards', 'Rokh 3angle', 'sf. ana', 'Sf Ana', 'sfânta ana', 'King mountain', 'Alliance S/W', 'Alliance E-W', 'Alliance E-W...', 'Galahad E-W', 'Galahad Tow ...', 'Galahad EW t...', 'Gallihad Tow', 'Galahad tow ...', 'rampa queralt', 'Rokh SE', 'gornergrat', 'Panarotta - ...', '<NAME>', 'Gresse-en-ve...', 'les Richards', 'Lower MacKen...', 'McKenzie Lau...', 'McKenzie low...', '<NAME>', '<NAME>', 'cornizzolo', 'Disentis Lai...', 'sta maria in...', 'jeufosse', 'Houeville', 'RAMPA QUERALT', '<NAME>', 'emberger', 'Embergeralm', 'meruz', 'Méru', 'Méruz', '<NAME>', 'sf ana ', 'sfanta ana ', 'Sfanta Ana', 'agostadero ', 'Ruederalp', '<NAME>', '<NAME>', 'loser', 'LOSER', '<NAME>', 'Meru', 'meruz', 'Les richards', 'luedingen', 'rampa Querelt', 'rampa Queralt', 'Všechov (CZ)', 'skrzetla', '<NAME>...', '<NAME>', '<NAME>', 'Saint Hilaire 2', '<NAME>', 'meruz ', 'Queralt ', 'POLSKA NOWA ...', '<NAME>', 'laveno', 'Turnthaler', 'Thurtaler', 'figuerasa', '<NAME>', 'montgellafrey ', '<NAME>', 'garzette', 'san giacomo', 'roldanillo. ...', 'Mt Borah Nor...', 'Nyaru ', 'South Kerio ...', 'takeoff sud', 'greeenacres ...', '<NAME>', 'Hay (north)', 'A<NAME>', 'rift Valley', 'Kerio view', 'Bor<NAME>', 'De aar', 'kerio View', 'Manilla Mt B...', 'borah', 'Mt Borah (Ma...', '<NAME>', 'Mt Borah Man...', 'Manilla, Aus...', 'Manilla SE', 'Mt Borah, Ma...', '<NAME>', 'Billing', 'Bir', 'Fiesch Kühb...', '<NAME> ...', 'billing', '<NAME>', 'jot pass', 'EGED', 'EGED /HU/', '<NAME>', 'MT Borah', 'iguala', 'RIEDERALP', 'Thurnthaler', 'Turntaler', 'WILDKOGEL', 'billing bir', 'Vsechov', 'Kobala (SI)', 'FANAS', 'Fanas ', '<NAME>', 'Klosters Got...', 'gotschna', 'ober<NAME>i', 'Schuls', 'Fiesch (CH)', 'helm', 'gemona', 'S.Giacomo(Fr)', 'Bassano Camp...', '<NAME>', '<NAME>', 'm.nudo', 'feltre', 'Schmitten', 'thurntaler', 'Turnthaler, AT', 'S<NAME>ur...', 'Greifenburg 12', 'Greifenburg ...', 'Emberg alm', 'Iguala (MX)', 'Birstonas', 'Manilla (AU)', 'DOLADA', 'rubbio', '<NAME>', 'SCHMITTEN..', '<NAME>m,', 'Mornera (Mon...', 'stelzerberg', 'Ladir', 'Fanas Eggli ...', 'OBERE WENGI', 'ober<NAME>', 'Gummen - Eng...', 'Eggli', 'Eggli (CH)', 'GANA', 'fiescheralp', 'gummen (brienz)', 'W-STEIN', 'hafelekar', 'SEEGRUBE', 'stoderzinken', '<NAME>', 'quaggione', 'hausstein', 'bisanne', 'Bissane', 'meruz ', 'STOL (SLO)', 'Kocs', 'krvavec', 'bir billing', 'Mszana 2', 'SIRIA', 'Bentelo Plus 4', 'fanas eggli', '<NAME>', 'Embergeralmiece', 'Embergerarme...', 'Gaißberg', '<NAME>', 'gastein', 'Gaisberg SW', 'juffing', '<NAME>', 'Oberauer', 'Oberauersbrunst', 'vértesszölős', 'Vértesszölös', 'Fistengrat', '<NAME>', 'monte nudo l...', 'wildkogel', 'cuarnan', 'm.cuarnan', 'schöckl SO', 'Birstonas', 'Ladir (CH)', '<NAME>', '<NAME>...', '<NAME>', 's<NAME>', 'rideralp', 'BIBERG', 'Emberg', '<NAME>', 'meruz ', 'Meruz ', 'Velký Lopen...', 'nyikom', 'valkininkai', '<NAME>', 'Falzes', 'falzen', 'falzes', '<NAME>', 'gsies', 'Gsies', 'Weissenstei', 'gummenalp', 'kalocsa', '<NAME>...', 'panarotta', '<NAME>', 'Seegrube!', 'ogassa', 'king mtn idaho', 'king mountain', 'Plus 4 - Ben...', 'mäggisseren', 'novegno', 'emberg alm', 'NIESEN', 'gummen', '<NAME>', 'aptenau', 'Trattberg Ab...', 'Trattberg/ A...', 'trattberg', 'Tbtenau Trat...', 'Trattberg (AT)', 'Qurnan Gemon...', '<NAME>', 'hochfelln', 'HOCHFELLN', 'Panenský T�...', 'montgirot', 'King Mtn. Idaho', 'Marbachegg T...', 'niesen', 'praticino', 'piedrahita', 'Cottbus_Nord', 'Plus4 - Bentelo', '<NAME>', '<NAME>...', 'les Rchards', 'denizli', 'Panukkale', 'weissenstein', 'Moosalp,CH', 'kobala', 'Soriza', 'Sorica, Sori...', 'GEMONA', 'Eged_track_p...', 'Toldijk XC M...', '<NAME>', 'súča', 'horna suča', 'Jaragua - BR', 'castelo', 'cottbus', 'karadag', 'mut', 'Kavoliai II', 'Heimatt', 'Heimat', 'HEIMATT', 'Weissenstein...', 'kapall', 'pena negra', 'Pena negra', 'Peña Negra ...', 'Piedrahita P...', 'Pena Negra S...', 'kocs', 'balea N', 'Balea sud', 'Jaragua-GO', 'ouro preto d...', 'Livigno - Ca...', 'peñanegra', 'Piedrahita (ES)', 'Peñanegra', 'Piedrahitab', 'Chelan', 'Eger-Eged', 'horna suca', 'Súča', 'inovec', 'Jaragua - Go', 'Jaragua - GO', 'poggio bustone', 'CORNIZZOLO', 'Speickboden', 'prada del mo...', 'quarnan gemona', '<NAME>', 'Pena', 'Jaraguá - GO', 'Pine Mtn', 'PineMtn', 'Queral', 'penya montan...', 'Rampa de Que...', 'Mt. 7 Golden', 'Moosalp aka ...', 'fiesch heimat', 'SORICA', 'csobanc', 'leonpolis', 'Peña Monta...', 'FIESCH', 'Flims Cassons', 'Cassonsgrat', 'Fiesch - Kü...', 'fiesch heimatt', 'Kueboden', '<NAME>', 'fiesch Heimat', 'Kuhboden', 'monte Grappa', 'Cima Grappa ...', 'cima grappa', 'Mt.Grappa', 'Speikboden, ...', 'Spikeboudn', 'Nove Sady', 'schmitten', 'Defreggen', 'Teton Villag...', 'Balea Lacut ...', 'Kühboden', 'Fiescheralp,...', 'Fiesch, Chü...', 'Slovenia Kobala', 'golm', 'Deffregen', 'Hearne, TX', 'Hearne, TX USA', 'hearne, TX USA', 'Jupiter Peak...', 'Skinny Ridge...', 'gardane rokh', 'Sfanta Ana', 'speickboden', 'Fiesch, Heimat', 'Fiescheralp ...', 'FIESCH SM1', 'Fiesch, Küe...', 'Fiesch garvela', 'Fiesch Kühe...', 'Seegrube (AT)', 'Defreggen', 'kobata', 'Bald Mountain', 'Bald Mountai...', 'Mount Baldy,...', 'Bald mtn. Su...', 'Michalków', 'Bisanne (Sig...', 'speikpoden', 'davos', 'birstonas', 'Birstonas', 'Ottawa, KS', 'Bald, Sun Va...', 'sopot (BG)', '<NAME>', 'corvatsch', '<NAME>', 'bald mtn. Su...', 'Balea S', 'Walts Point', 'Bir-Billing', 'Quixada Rampa', 'Mt Bakewell', 'Bakewell', 'Barr South', 'Quixada Sant...', 'De Aar ', 'de aar', 'Serra Talhad...', 'Serra Telhada', 'Serra Telhad...', 'de Aar', 'De Aar - Vos...', 'DeAar - Vosburg', 'Branvlei', 'Priska', 'Riacho das A...', 'Booligal, NSW', 'mirador de l...', 'mirador', 'Greenacres West', 'Barrington No.3', 'South Barrin...', 'Araripina Ai...', 'R<NAME>', 'Ivanhoe Airs...', 'Kakamas Airf...', 'porterville', 'kerio view h...' ); $to = array( 'Roldanillo', 'Roldanillo', 'Mt. Borah', 'Kerio View', 'Kerio View', 'Kerio View', 'Mt. Borah', 'Kerio View', 'Kerio View', 'Kerio View', 'Mt. Borah', 'Kerio View', 'Kerio View', 'Roldanillo', 'Greenacres', 'Greenacres', 'Mt. Borah', 'Mt. Borah', '<NAME>', 'Mt. Borah', 'Mt. Borah', 'Mt. Borah', 'Mt. Borah', 'Roldanillo', '<NAME>', 'Mt. Borah', 'Mt. Borah', 'Mt. Borah', '<NAME>', 'Bassano', 'Serrone', 'Gemona', 'Gemona', 'Gemona', 'Bassano', 'Dubbo', 'Gemona', 'Serrone', 'Bassano', 'Bassano', 'Barrington', 'Barrington', 'Dubbo', 'Fanas', 'Fiesch', 'Landeck', 'Fiesch', 'Wildkogel', 'Serrone', 'Marlens', 'Bassano', 'Bassano', 'Fanas', 'Fanas', 'Fiesch', 'Riederalp', 'Quixadá', 'Peña Negra', 'Peña Negra', 'Kobala', 'Conargo', 'Mt. Borah', 'Greenacres', 'De Aar', 'Pampoenfontein', 'Roldanillo', 'Barrington', 'Barrington', 'Quixadá', 'Quixadá', 'Quixadá', 'De Aar', 'Mt. Borah', 'Quixadá', 'Quixadá', 'Morada Nova', 'Morada Nova', 'Mt. Borah', '<NAME>', 'Stol', '<NAME>', '<NAME>', '<NAME>', 'Walt\'<NAME>', 'Fiesch', 'Erzincan', 'Birštonas', 'Speikboden', 'Speikboden', 'Fiesch', 'Fiesch', 'Fiesch', '<NAME>', '<NAME>', 'Birstonas', 'Queralt', 'Fourneuby', 'Shumen', 'Balea', 'Balea', 'Balea', 'Jupiter', 'Speikboden', 'Antholz', 'Fiesch', 'Fiesch', 'Niesen', 'Defreggen', 'Stol', 'Sorica', 'Sorica', 'Michalków', 'Cottbus', 'Cottbus', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', 'Všechov', 'Všechov', 'King Mountain', 'King Mountain', 'Santa Rita d...', 'Kocs Csörl...', 'Kalocsa', 'Roldanillo', '<NAME>', 'Grente', 'Cesarò', 'Bassano', 'Malý Pěč...', '<NAME>', 'Balea', 'Castelo de V...', '<NAME>', 'Cassons', 'Mount Seven', 'Mount Seven', 'Mount Seven', 'Mount Seven', 'Mount Seven', 'Mount Seven', 'Mount Seven', 'Mount Seven', 'Mount Seven', 'Mount Seven', 'Mount Seven', 'Mount Seven', 'Mount Seven', 'Mount Seven', 'Mount Seven', 'Mount Seven', 'Mount Seven', 'Mount Seven', 'Mount Seven', 'Mount Seven', 'Mount Seven', 'Mount Seven', 'Mount Seven', 'Teton Village', 'Teton Village', 'Jaraguá', 'Jaraguá', 'Jaraguá', 'Jaraguá', 'Černá Hora', 'Osser', 'Kruševo', 'El Salto', 'La Breya', 'McKenzie', 'McKenzie', 'McKenzie', 'McKenzie', 'Mount Seven', 'Mount Seven', 'Peña Monta...', 'Vale de Amor...', 'Vale de Amor...', 'Balea', 'Jupiter', 'Porxos', 'Konchinka', 'Riederalp', 'Cavallaria', 'Cavallaria', '<NAME>', 'Speikboden', 'Gaisberg', 'Osterfelder', 'Osterfelder', 'Hochries', 'Jaraguá', '<NAME>', 'Kozákov', 'Kalocsa', 'Larouco', 'Larouco', 'Rokh', 'Rokh', 'Pebble Creek...', 'Porxos', 'Porxos', 'Balea', 'Deglenai', '<NAME>', 'La Salle', 'Linhares', 'Linhares', 'Oleśnica', 'McKenzie', 'McKenzie', 'McKenzie', 'McKenzie', '<NAME>', 'Niesen', 'Fiesch', '<NAME>', 'Hinterrugg', 'Bischling', 'Bischling', 'Hebbronville', 'Hebbronville', 'Hebbronville', 'Osterfelder', 'McKenzie', 'McKenzie', 'McKenzie', 'Koclířov', 'Plan de la B...', 'Jupiter', 'Narli', 'Belltall', 'Rokh', 'McKenzie', '<NAME>', 'McKenzie', 'Montanchez', 'Schöckl', 'Wildkogel', '<NAME>', 'Bischling', 'Antholz', 'Wank', 'Borsk', 'Balea', 'Balea', 'Nara', 'Moosalp', 'Kössen', 'Seegrube', '<NAME>', 'Col de l\'Arp...', '<NAME>', 'Oleśnica', 'Rokh', 'McKenzie', 'Balea', 'Bassano', '<NAME>', 'McKenzie', 'McKenzie', '<NAME>', 'Feuerkogel', '<NAME>', '<NAME>', 'Bassano', 'Bassano', 'Cottbus', 'Serpaton', '<NAME>', 'Rokh', 'Sf. Ana', 'Sf. Ana', 'Sf. Ana', 'King Mountain', 'Alliance', 'Alliance', 'Alliance', 'Galahad', 'Galahad', 'Galahad', 'Galahad', 'Galahad', 'Queralt', 'Rokh', 'Gornergrat', 'Panarotta', '<NAME>', 'Gresse en Ve...', '<NAME>', 'McKenzie', 'McKenzie', 'McKenzie', 'Rosalind', 'Rosalind', 'Cornizzolo', '<NAME>', 'St<NAME>...', 'Jeufosse', 'Houéville', 'Queralt', 'Fanas', '<NAME>', '<NAME>', 'Meruz', 'Meruz', 'Meruz', 'Zlatník', 'Sf. Ana', 'Sf. Ana', 'Sf. Ana', 'agostadero', 'Riederalp', 'Antholz', 'Bassano', 'Loser', 'Loser', '<NAME>', 'Meruz', 'Meruz', '<NAME>', 'Lüdingen', 'Queralt', 'Queralt', 'Všechov', 'Skrzętla', '<NAME>', '<NAME>', '<NAME>', '<NAME>', 'Saint-Marcel', 'Meruz', 'Queralt', '<NAME> ...', 'Braunwald', 'Laveno', 'Thurntaler', 'Thurntaler', 'Figuerassa', 'Gemona', 'montgellafrey', 'Gemona', 'Gemona', '<NAME>', 'Roldanillo', 'Mt. Borah', 'Nyaru', 'Kerio View', 'Ker<NAME>', 'Greenacres', 'Nyaru', 'Hay', '<NAME>', 'Kerio View', 'Kerio View', 'Mt. Borah', '<NAME>', 'Kerio View', 'Mt. Borah', 'Mt. Borah', 'Mt. Borah', 'Mystic', 'Mt. Borah', 'Mt. Borah', 'Mt. Borah', 'Mt. Borah', 'Gemona', '<NAME>', '<NAME>', 'Fiesch', 'Marlens', '<NAME>', '<NAME>', '<NAME>', 'Eged', 'Eged', 'Bischling', '<NAME>', 'Iguala', 'Riederalp', 'Thurntaler', 'Thurntaler', 'Wildkogel', '<NAME>', 'Všechov', 'Kobala', 'Fanas', 'Fanas', 'Fiesch', 'Gotschna', 'Gotschna', '<NAME>', 'Scuol', 'Fiesch', 'Helm', 'Gemona', '<NAME>', 'Bassano', 'Laveno', 'Laveno', 'Laveno', 'Feltre', 'Schmittenhöhe', 'Thurntaler', 'Thurntaler', 'Thurntaler', 'Greifenburg', 'Greifenburg', '<NAME>', 'Iguala', 'Birštonas', 'Mt. Borah', '<NAME>', 'Rubbio', 'Rubbio', 'Schmittenhöhe', '<NAME>', 'Mornera', 'Stelserberg', 'Ladir', 'Fanas', '<NAME>', '<NAME>', 'Gummen', 'Fanas', 'Fanas', 'Gana', 'Fiesch', 'Gummen', 'Weissenstein', 'Hafelekar', 'Seegrube', 'Stoderzinken', 'Laveno', 'Quaggione', 'Hausstein', 'Bisanne', 'Bisanne', 'Meruz', 'Stol', '<NAME>rl...', 'Krvavec', '<NAME>', 'Mszana', 'Siria', 'Bentelo', 'Fanas', '<NAME>', '<NAME>', '<NAME>', 'Gaisberg', '<NAME>', 'Gastein', 'Gaisberg', 'Jufing', 'Grente', '<NAME>', '<NAME>', 'Vértesszőlős', 'Vértesszőlős', 'Fisetengrat', 'Gemona', 'Laveno', 'Wildkogel', 'Cuarnan', 'Cuarnan', 'Schöckl', 'Birštonas', 'Ladir', 'Gummen', 'Brunni', 'Stelserberg', 'Stelserberg', 'Riederalp', 'Biberg', '<NAME>', 'Schöckl', 'Meruz', '<NAME>', 'Nyikom', 'Valkininkai', 'Fanas', 'Pfalzen', 'Pfalzen', 'Pfalzen', 'Pfalzen', '<NAME>', '<NAME>', 'Weissenstein', 'Gummen', 'Kalocsa', '<NAME>', 'Panarotta', 'Panarotta', 'Seegrube', 'Ogassa', '<NAME>', 'King Mountain', 'Bentelo', 'Mäggisseren', 'Novegno', '<NAME>', 'Niesen', 'Gummen', 'Feuerkogel', 'Aptenau', 'Trattberg', 'Trattberg', 'Trattberg', 'Trattberg', 'Trattberg', 'Trattberg', 'Gemona', 'Gemona', 'Hochfelln', 'Hochfelln', '<NAME>...', 'Montgirot', '<NAME>', 'Marbachegg', 'Niesen', 'Praticino', '<NAME>', 'Cottbus', 'Bentelo', 'Feuerkogel', '<NAME>...', '<NAME>', 'Denizli', 'Pamukkale', 'Weissenstein', 'Moosalp', 'Kobala', 'Sorica', 'Sorica', 'Gemona', 'Eged', 'Toldijk', '<NAME>', '<NAME>a', 'Horná Súča', 'Jaraguá', '<NAME>', 'Cottbus', 'Karadag', 'Mut', 'Kavoliai', 'Fiesch', 'Fiesch', 'Fiesch', 'Weissenstein', 'Kapall', 'Peña Negra', 'Peña Negra', 'Peña Negra', 'Peña Negra', 'Peña Negra', 'Kocs Csörl...', 'Balea', 'Balea', 'Jaraguá', 'Ouro Preto D...', 'Livigno', 'Peña Negra', 'Peña Negra', 'Peña Negra', 'Peña Negra', 'Chelan Butte', 'Eged', 'Horná Súča', 'Horná Súča', 'Inovec', 'Jaraguá', 'Jaraguá', '<NAME>', 'Cornizzolo', 'Speikboden', 'Prada', 'Gemona', 'Feuerkogel', 'Peña Negra', 'Jaraguá', 'Pine Mt', 'Pine Mt', 'Queralt', 'Peña Negra', 'Queralt', 'Mount Seven', 'Moosalp', 'Fiesch', 'Sorica', 'Csobánc', 'Leonpolis', 'Peña Negra', 'Fiesch', 'Cassons', 'Cassons', 'Fiesch', 'Fiesch', 'Fiesch', 'Ayaş', 'Fiesch', 'Fiesch', 'Bassano', 'Bassano', 'Bassano', 'Bassano', 'Speikboden', 'Speikboden', 'Nové Sady', 'Schmittenhö...', 'Defereggen', 'Teton Village', 'Balea', 'Fiesch', 'Fiesch', 'Fiesch', 'Kobala', 'Golm', 'Defereggen', 'Hearne', 'Hearne', 'Hearne', 'Jupiter', '<NAME>', 'Rokh', '<NAME>', 'Speikboden', 'Fiesch', 'Fiesch', 'Fiesch', 'Fiesch', 'Fiesch', 'Fiesch', 'Seegrube', 'Defereggen', 'Kobala', '<NAME>', '<NAME>', '<NAME>', '<NAME>', 'Michałków', 'Bisanne', 'Speikboden', 'Davos', 'Birštonas', 'Birštonas', 'Ottawa', '<NAME>', 'Sopot', 'Mirandela', 'Corvatsch', 'Corvatsch', '<NAME>', 'Balea', '<NAME>', '<NAME>', 'Quixadá', '<NAME>', '<NAME>', 'Barrington', 'Quixadá', 'De Aar', 'De Aar', 'Serra Talhada', 'Serra Talhada', 'Serra Talhada', 'De Aar', 'De Aar', 'De Aar', 'Brandvlei', 'Prieska', 'Riacho des A...', 'Booligal', 'Mirador De L...', 'Mirador De L...', 'Greenacres', 'Barrington', 'Barrington', 'Araripina', 'Roldanillo', 'Ivanhoe', 'Kakamas', 'Porterville', '<NAME>' ); foreach($from as $k => $v){ if ($name == $v && isset($to[$k])){ return $to[$k]; } } return $name; } // Check 15 and further!!!! $takeoffinfos = array( array( 'takeoff' => '<NAME>', 'name' => '<NAME>', 'weeks' => array(23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39), 'url' => 'http://www.flypiedrahita.com/' ), array( 'takeoff' => 'Quixadá', 'name' => '<NAME>', 'weeks' => array(44,45,46), 'url' => 'http://flywithandy.com/' ), array( 'takeoff' => '<NAME>', 'name' => '<NAME>', 'weeks' => array(6), 'url' => 'http://flymanilla.com/' ), array( 'takeoff' => '<NAME>', 'name' => 'Parakros', 'weeks' => array(40,41,42,43,44,45,46,47,48), 'url' => 'http://parakros.com/' ), array( 'takeoff' => 'Sarangkot', 'name' => 'Parakros', 'weeks' => array(7,8,9,10), 'url' => 'http://parakros.com/' ), array( 'takeoff' => 'Ager', 'name' => '<NAME>', 'weeks' => array(37,38), 'url' => 'http://xtc-paragliding.com/' ), array( 'takeoff' => 'Gemona', 'name' => '<NAME>', 'weeks' => array(16,17,18,19,20,21,22,40), 'url' => 'http://xtc-paragliding.com/' ), array( 'takeoff' => 'Kobala', 'name' => '<NAME>', 'weeks' => array(28,29,30,31,32,33), 'url' => 'http://www.nicole-fedele.com/' ), array( 'takeoff' => 'Meduno', 'name' => '<NAME>', 'weeks' => array(28,29,30,31,32,33), 'url' => 'http://www.nicole-fedele.com/' ), array( 'country' => 'PT', 'name' => '<NAME>', 'weeks' => array(30,31,32,33,34,35,36,37,38,39,40), 'url' => 'http://www.paraglideportugal.com/' ), array( 'takeoff' => 'Bassano', 'name' => '<NAME>', 'weeks' => array(10,11,12,13,14,15,16,17,18), 'url' => 'http://www.austrianarena.com/' ), array( 'country' => 'IN', 'name' => '<NAME>', 'weeks' => array(14,15,16,17,18,19,41,42,43,44,45), 'url' => 'https://www.facebook.com/SkyDebu?pnref=story' ), array( 'takeoff' => 'Quixadá', 'name' => 'ThermikZone', 'weeks' => array(42,43,44), 'url' => 'http://www.termikzone.com/work/500km-xc-challenge/' ), array( 'takeoff' => 'Tacima', 'name' => 'ThermikZone', 'weeks' => array(41,42), 'url' => 'http://www.termikzone.com/work/tacima-brazil/' ), array( 'takeoff' => 'Quixadá', 'name' => 'ThermikZone', 'weeks' => array(43,44,45,46,47,48), 'url' => 'http://www.termikzone.com/work/quixada-brazil/' ), array( 'takeoff' => 'Jaraguá', 'name' => 'ThermikZone', 'weeks' => array(32), 'url' => 'http://www.termikzone.com/work/expedicao-xc-cerrado-jaragua-goias/' ), array( 'takeoff' => 'Ager', 'name' => '<NAME>', 'weeks' => array(32,33,34,35,36,37,38,39,40), 'url' => 'http://www.flywithxirli.com/' ), array( 'takeoff' => 'Sopot', 'name' => 'Rose Valley Lodge', 'weeks' => array(14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40), 'url' => 'http://www.rosevalleylodge.net/' ), array( 'takeoff' => 'Dobrostan', 'name' => '<NAME>', 'weeks' => array(14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40), 'url' => 'http://www.rosevalleylodge.net/' ) ); $countryweeks = array(); $weeks = array(); function cntsort($item1,$item2){ if ($item1['100ks'] == $item2['100ks']) return 0; return ($item1['100ks'] < $item2['100ks']) ? 1 : -1; } foreach($data as $week => $countries){ $first_value = reset($countries); $first_key = key($countries); $locations = array(); foreach($countries as $country => $meta){ $dates = array(); $max = 0; $twos = 0; foreach($meta->flights as $flight){ if ($flight->distance >= 200) $twos++; if ($flight->points > $max) $max = $flight->points; $dates[$flight->date] = true; } $score = round(count($dates) / 49 * 100); if (!isset($weeks[$week])){ $weeks[$week] = array( 'month' => $countries->{$first_key}->flights[0]->month, '100ks' => 0, 'countries' => array() ); } $weeks[$week]['100ks'] = $weeks[$week]['100ks'] + $meta->cnt; $weeks[$week]['countries'][$country] = array( '100ks' => $meta->cnt, '200ks' => $twos, 'score' => $score, 'max' => $max, 'takeoffs' => array() ); if (!isset($countryweeks[$country])){ $countryweeks[$country] = array(); for ($i=1;$i<=52;$i++){ if ($week == $i){ $countryweeks[$country][$i] = array('cnt' => $meta->cnt, 'score' => $score, 'max' => $max); } else { $countryweeks[$country][$i] = array('cnt' => 0, 'score' => 0, 'max' => 0); } } } else { $countryweeks[$country][$week] = array('cnt' => $meta->cnt, 'score' => $score, 'max' => $max); } uasort($weeks[$week]['countries'], 'cntsort'); $takeoffs = array(); $takeoffpos = array(); foreach($meta->flights as $flight){ $lockey = round($flight->lng,1).','.round($flight->lat,1); if (isset($locations[$lockey])){ $locations[$lockey]['count']++; } else { $locations[$lockey] = array( 'lat' => round($flight->lng,1), 'lng' => round($flight->lat,1), 'count' => 1 ); } if (!isset($takeoffs[fixTakeoff($flight->takeoff)])){ $takeoffs[fixTakeoff($flight->takeoff)] = 1; $takeoffpos[fixTakeoff($flight->takeoff)] = array('lat' => $flight->lat, 'lng' => $flight->lng); } else { $takeoffs[fixTakeoff($flight->takeoff)]++; } } arsort($takeoffs); foreach($takeoffs as $takeoff => $cnt){ $weeks[$week]['countries'][$country]['takeoffs'][] = array('name' => ucfirst($takeoff), 'flights' => $cnt, 'lat' => $takeoffpos[$takeoff]['lat'], 'lng' => $takeoffpos[$takeoff]['lng']); } } $coords = array(); $max = 0; foreach($locations as $loc){ if ($loc['count'] > $max) $max = $loc['count']; $coords[] = $loc; } $weeks[$week]['heatmapcoords'] = $coords; $weeks[$week]['heatmapmax'] = $max; } echo '<div class="weeks">'; foreach($weeks as $k => $week){ $year = (int)date("Y"); if ((int)date('W') > $k){ $weekrange = getStartAndEndDate(((int)$k)-1, $year+1); $startmonth = getStartMonth(((int)$k)-1, $year+1); $endmonth = getEndMonth(((int)$k)-1, $year+1); } else { $weekrange = getStartAndEndDate(((int)$k)-1, $year); $startmonth = getStartMonth(((int)$k)-1, $year); $endmonth = getEndMonth(((int)$k)-1, $year); } echo '<div class="week week_'.$k.' month_'.$startmonth.' month_'.$endmonth.'">'; echo '<div class="header">'; echo '<div class="rating">'; if ($week['100ks'] > 30){ echo '<span class="active">☆</span>'; } else { echo '<span>☆</span>'; } if ($week['100ks'] > 75){ echo '<span class="active">☆</span>'; } else { echo '<span>☆</span>'; } if ($week['100ks'] > 150){ echo '<span class="active">☆</span>'; } else { echo '<span>☆</span>'; } if ($week['100ks'] > 300){ echo '<span class="active">☆</span>'; } else { echo '<span>☆</span>'; } if ($week['100ks'] > 600){ echo '<span class="active">☆</span>'; } else { echo '<span>☆</span>'; } echo '</div>'; echo '<span class="title">Week '.$k.'</span>'; echo '<span class="weekrange">'.$weekrange[0].' to '.$weekrange[1].'</span>'; echo '</div>'; echo '<div class="heatmap" id="hm'.$k.'" data-max="'.$week['heatmapmax'].'" data-coords=\''.json_encode($week['heatmapcoords']).'\'></div>'; echo '<div class="countries">'; $biggest = array(); foreach($week['countries'] as $k2 => $country){ echo '<div class="country country_'.$k2.'">'; echo '<div class="action">show takeoffs</div>'; echo '<div class="countryinfos">'; echo '<span class="title"><img src="countries/'.strtolower($k2).'.png"> '.$k2.'</span>'; echo '<span class="meta meta100ks"><i>'.$country['100ks'].'</i> 100ks</span>'; echo '<span class="meta meta200ks"><i>'.$country['200ks'].'</i> 200ks</span>'; echo '<span class="meta metascore"><i>'.$country['score'].'</i> %</span>'; echo '<span class="meta metamax"><i>'.round($country['max']).'</i> p</span>'; echo '</div>'; echo '<div class="takeoffs">'; foreach($country['takeoffs'] as $k3 => $takeoff){ if (empty($biggest) || $biggest['flights'] < $takeoff['flights']){ $biggest = $takeoff; } foreach($takeoffinfos as $info){ if ( ( (isset($info['takeoff']) && $info['takeoff'] == $takeoff['name']) || (isset($info['country']) && $info['country'] == $k2) ) && in_array($k, $info['weeks']) ){ echo '<a class="info" href="'.$info['url'].'" target="_blank" title="'.$info['name'].'">i</a>'; } } echo '<div class="takeoff takeoff_'.$k3.'" data-lat="'.$takeoff['lat'].'" data-lng="'.$takeoff['lng'].'">'; echo '<span class="name">'.$takeoff['name'].'</span>'; echo '<span class="flights">'.$takeoff['flights'].'</span>'; echo '</div>'; } echo '</div>'; echo '</div>'; } $secondbiggest = array(); foreach($week['countries'] as $k2 => $country){ foreach($country['takeoffs'] as $k3 => $takeoff){ if ( (abs($biggest['lat']-$takeoff['lat']) > 30 || abs($biggest['lng']-$takeoff['lng']) > 30) && $biggest['name'] != $takeoff['name']){ if (empty($secondbiggest) || $secondbiggest['flights'] < $takeoff['flights']){ $secondbiggest = $takeoff; } } } } $thirdbiggest = array(); foreach($week['countries'] as $k2 => $country){ foreach($country['takeoffs'] as $k3 => $takeoff){ if ( (abs($biggest['lat']-$takeoff['lat']) > 30 || abs($biggest['lng']-$takeoff['lng']) > 30) && (abs($secondbiggest['lat']-$takeoff['lat']) > 30 || abs($secondbiggest['lng']-$takeoff['lng']) > 30) && $biggest['name'] != $takeoff['name'] && $secondbiggest['name'] != $takeoff['name']){ if (empty($thirdbiggest) || $thirdbiggest['flights'] < $takeoff['flights']){ $thirdbiggest = $takeoff; } } } } $fourthbiggest = array(); foreach($week['countries'] as $k2 => $country){ foreach($country['takeoffs'] as $k3 => $takeoff){ if ( (abs($biggest['lat']-$takeoff['lat']) > 30 || abs($biggest['lng']-$takeoff['lng']) > 30) && (abs($secondbiggest['lat']-$takeoff['lat']) > 30 || abs($secondbiggest['lng']-$takeoff['lng']) > 30) && (abs($thirdbiggest['lat']-$takeoff['lat']) > 30 || abs($thirdbiggest['lng']-$takeoff['lng']) > 30) && $biggest['name'] != $takeoff['name'] && $secondbiggest['name'] != $takeoff['name'] && $thirdbiggest['name'] != $takeoff['name']){ if (empty($fourthbiggest) || $fourthbiggest['flights'] < $takeoff['flights']){ $fourthbiggest = $takeoff; } } } } echo '<div class="biggest" data-cnt="'.$biggest['flights'].'" data-lat="'.$biggest['lat'].'" data-lng="'.$biggest['lng'].'" data-name="'.$biggest['name'].'"></div>'; if (!empty($secondbiggest)){ echo '<div class="secondbiggest" data-cnt="'.$secondbiggest['flights'].'" data-lat="'.$secondbiggest['lat'].'" data-lng="'.$secondbiggest['lng'].'" data-name="'.$secondbiggest['name'].'"></div>'; } if (!empty($thirdbiggest)){ echo '<div class="thirdbiggest" data-cnt="'.$thirdbiggest['flights'].'" data-lat="'.$thirdbiggest['lat'].'" data-lng="'.$thirdbiggest['lng'].'" data-name="'.$thirdbiggest['name'].'"></div>'; } if (!empty($fourthbiggest)){ echo '<div class="fourthbiggest" data-cnt="'.$fourthbiggest['flights'].'" data-lat="'.$fourthbiggest['lat'].'" data-lng="'.$fourthbiggest['lng'].'" data-name="'.$fourthbiggest['name'].'"></div>'; } echo '</div>'; echo '</div>'; } echo '</div>'; echo '<div class="countryweeks">'; foreach($countryweeks as $country => $weeks){ echo '<div class="country_'.$country.'" data-weeks=\''.json_encode($weeks).'\'></div>'; } echo '</div>'; ?> <div class="container footer"> <p>(c) 2015 by <a href="http://fredibach.ch/" target="blank"><NAME></a> - Data collected from <a href="http://xcontest.org/" target="blank">XContest</a></p> </div> <script type="text/javascript" src="js/jquery-1.10.2.min.js"></script> <script type="text/javascript" src="js/jquery.inview.min.js"></script> <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/trianglify/0.3.1/trianglify.min.js"></script> <script type="text/javascript" src="//maps.googleapis.com/maps/api/js?sensor=false"></script> <script type="text/javascript" src="js/richmarker.min.js"></script> <script type="text/javascript" src="js/heatmap.js"></script> <script type="text/javascript" src="js/gmaps-heatmap.js"></script> <script> var pattern = Trianglify({ x_colors: "RdBu", variance: "0.66", width: window.innerWidth, height: window.innerHeight, cell_size: 60 }); document.body.appendChild(pattern.canvas()); $('.action').on('click', function(){ $(this).parent().find('.takeoffs').slideToggle('fast'); }); $('.takeoff').on('click', function(){ window.open('http://www.xcontest.org/2015/world/en/flights-search/?filter%5Bpoint%5D='+$(this).attr('data-lat')+'+'+$(this).attr('data-lng')+'&filter%5Bradius%5D=5000&filter%5Bmode%5D=START&filter%5Bdate_mode%5D=dmy&filter%5Bdate%5D=&filter%5Bvalue_mode%5D=dst&filter%5Bmin_value_dst%5D=&filter%5Bcatg%5D=FAI3&filter%5Broute_types%5D=&filter%5Bavg%5D=&filter%5Bpilot%5D=&list%5Bsort%5D=pts&list%5Bdir%5D=down'); }); $('.monthselect select').on('change', function(){ var month = $(this).val(); if (month !== ''){ $('.week').hide(); $('.month_'+month).show(); $('.month_'+month).find('.heatmap').each(function(){ initMap($(this)); }); } else { $('.week').show(); } }); var loaded = {}; var initMap = function($el){ var id = $el.attr('id'); if (typeof loaded[id] == 'undefined' && $el.is(":visible")){ console.log('init id', id); loaded[id] = true; // map center var myLatlng = new google.maps.LatLng(8, 28); // map options, var myOptions = { zoom: 1, minZoom: 1, maxZoom: 1, center: myLatlng, disableDefaultUI: true }; // standard map var map = new google.maps.Map($el[0], myOptions); var datastr = $el.attr('data-coords'); var coords = $.parseJSON(datastr); var data = { 'max': Number($el.attr('data-max')), 'data': coords }; // heatmap layer var heatmap = new HeatmapOverlay(map, { // radius should be small ONLY if scaleRadius is true (or small radius is intended) "radius": 6, "maxOpacity": 1, "blur": 0.95, "backgroundColor": "rgba(218,200,155,0.4)", // scales the radius based on map zoom "scaleRadius": true, // if set to false the heatmap uses the global maximum for colorization // if activated: uses the data maximum within the current map boundaries // (there will always be a red spot with useLocalExtremas true) "useLocalExtrema": true, // which field name in your data represents the latitude - default "lat" latField: 'lat', // which field name in your data represents the longitude - default "lng" lngField: 'lng', // which field name in your data represents the data value - default "value" valueField: 'count' } ); try { heatmap.setData(data); } catch(err) {}; var $biggest = $el.parent().find('.biggest'); var markerpos = new google.maps.LatLng(Number($biggest.attr('data-lng')), Number($biggest.attr('data-lat'))); var marker = new RichMarker({ position: markerpos, map: map, flat: true, draggable: false, anchor: RichMarkerPosition.TOP_LEFT, content: '<div class="marker"><div class="text">'+$biggest.attr('data-name')+'</div></div>' }); var $secondbiggest = $el.parent().find('.secondbiggest'); if ($secondbiggest.length > 0 && (Number($biggest.attr('data-cnt')) / Number($secondbiggest.attr('data-cnt')) < 4 || $secondbiggest.attr('data-cnt') >= 9)){ var markerpos2 = new google.maps.LatLng(Number($secondbiggest.attr('data-lng')), Number($secondbiggest.attr('data-lat'))); var marker2 = new RichMarker({ position: markerpos2, map: map, flat: true, draggable: false, anchor: RichMarkerPosition.TOP_LEFT, content: '<div class="marker"><div class="text">'+$secondbiggest.attr('data-name')+'</div></div>' }); } var $thirdbiggest = $el.parent().find('.thirdbiggest'); if ($thirdbiggest.length > 0 && (Number($biggest.attr('data-cnt')) / Number($thirdbiggest.attr('data-cnt')) < 6 || $thirdbiggest.attr('data-cnt') >= 9)){ var markerpos3 = new google.maps.LatLng(Number($thirdbiggest.attr('data-lng')), Number($thirdbiggest.attr('data-lat'))); var marker2 = new RichMarker({ position: markerpos3, map: map, flat: true, draggable: false, anchor: RichMarkerPosition.TOP_LEFT, content: '<div class="marker"><div class="text">'+$thirdbiggest.attr('data-name')+'</div></div>' }); } var $fourthbiggest = $el.parent().find('.fourthbiggest'); if ($fourthbiggest.length > 0 && (Number($biggest.attr('data-cnt')) / Number($fourthbiggest.attr('data-cnt')) < 8 || $fourthbiggest.attr('data-cnt') >= 9)){ var markerpos4 = new google.maps.LatLng(Number($fourthbiggest.attr('data-lng')), Number($fourthbiggest.attr('data-lat'))); var marker2 = new RichMarker({ position: markerpos4, map: map, flat: true, draggable: false, anchor: RichMarkerPosition.TOP_LEFT, content: '<div class="marker"><div class="text">'+$fourthbiggest.attr('data-name')+'</div></div>' }); } } } $('.heatmap').bind( 'inview', function(event, isInView, visiblePartX, visiblePartY){ initMap($(this)); }); </script> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-68457619-1', 'auto'); ga('send', 'pageview'); </script> </body> </html> <file_sep>/bak/old1.php <!DOCTYPE html> <head> <meta charset="utf-8"> <style> body { font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 14px; } h1 { font-size: 18px; } table { width: 100%; } tr { background: #f8f8f8; margin-top: 4px; } th { padding: 4px; background: #333; color: #fff; text-align: left; } td { vertical-align: top; padding: 2px; padding-top: 4px; padding-left: 4px; padding-bottom: 0px; } td span { background: #E0DACD; border-radius: 3px; padding: 2px; padding-left: 5px; display: inline-block; margin-right: 8px; margin-bottom: 4px; } td span i { background: #fff; border-radius: 6px; padding: 2px; padding-left: 5px; padding-right: 5px; padding-bottom: 0px; margin: 1px; font-style: normal; font-size: 12px; line-height: 50%; } tr.spacer td { height: 1px; max-height: 1px; background: #bbb; padding: 0px; margin: 0px; overflow: hidden; } </style> </head> <body> <?php error_reporting(E_ALL); ini_set('display_errors', 1); $data = json_decode(file_get_contents('100kflights.json')); echo '<h1>Best 100k destinations for each week in a year</h1>'; echo '<p>Ever wondered where to go if you want to fly as many 100k\'s in a year as possible? This list can help you. It shows where and in which week you\'ll be able to fly 100km based on the top 5800 100km flights of the top ranked pilots in that category. But take care, some of those places have really strong conditions in those weeks! ;-)</p>'; echo '<table><thead><tr><th>Week</th><th>Month</th><th>Country</th><th>Flights</th><th>Takeoffs</th></tr></thead><tbody>'; foreach($data as $week => $countries){ $first_value = reset($countries); $first_key = key($countries); $c1 = 0; echo '<tr class="spacer"><td colspan="5"></td></tr>'; foreach($countries as $country => $meta){ if ($meta->cnt > 2){ $c1++; if ($c1 == 1){ echo '<tr><td>'.$week.'</td><td>'.$countries->{$first_key}->flights[0]->month.'</td>'; } else { echo '<tr><td>&nbsp;</td><td>&nbsp;</td>'; } echo '<td><img src="countries/'.strtolower($country).'.png"> '.$country.'</td><td>'.$meta->cnt.'</td><td>'; $takeoffs = array(); foreach($meta->flights as $flight){ if (!isset($takeoffs[$flight->takeoff])){ $takeoffs[$flight->takeoff] = 1; } else { $takeoffs[$flight->takeoff]++; } } arsort($takeoffs); foreach($takeoffs as $takeoff => $cnt){ echo '<span>'.$takeoff.' <i>'.$cnt.'</i></span>'; } echo '</td></tr>'; } } } echo '</tbody></table>'; ?> <p>(c) 2015 by <NAME> - Data collected from XContest</p> </body> </html> <file_sep>/test.php <?php $from = array( 'Roldanillo [...', 'Roldanillo pico', 'borah N', 'Kerio View H...', 'Kerio View S...', 'kerio view', 'Mt Borah South', 'Kerio View Sud', 'kerio', 'Kerio Süd', 'Mt. Borah W', 'zrezane Kerio View', 'South Kerio', 'roldanillo', 'greenacres ...', 'Greenacres west', 'Mt. Borah E', 'Mt. Borah Nor...', 'Picco, Rolda...', 'Mt. Bora', 'Mt. Borah (AU)', 'mt borah', 'Mt. Borah S', 'Roldanillo. ...', 'El Penon', 'Mt. Borahh', 'MT. Borah', 'Mt. Borah NE', 'Stella alpina', 'Bassano [da ...', 'serrone', 'garzetta', 'garzetta gemona', 'Gemona', 'bassano', 'dubbo', '<NAME>', 'Serrone 1', 'Bassano [Ant...', 'Bassano [Cas...', '<NAME>', 'Barrington 3...', 'Dubbo north', '<NAME>', '<NAME>', 'Landeck 1', 'Fiesch [Heimat]', 'Wildkogel 2', 'Serrone (IT)', 'marlens', 'Bassano - ta...', 'BASSANO', 'fanas', 'Fanas 2', 'fiesch', 'riederalp', 'Quixada', '<NAME>', 'Piedrahita', 'Tol<NAME>', 'Conargo North', 'Manilla', 'greenacres', 'DeAar', 'Pampoenfonte...', 'Roldanillo A...', 'Barrington\'s...', 'Barrington t...', 'quixada', 'quixada sant...', 'Quixadá Sant...', 'DeAar (ZA)', 'Mt. Borah N', 'Qixada', 'Quxada', 'Morada Nova ...', 'M<NAME>ouva', 'Mt Borah', 'col rodella', '<NAME>', 'St. André [...', 'walts point', 'Walt\'s Point...', 'Walt\'s', 'Fiesch [Heim...', 'erzincan', 'Birstonas', 'Speikboden 2', 'Speikboden 1', '<NAME>', 'Fiesch [Galv...', 'Fiescheralp', 'piedrahita ', '<NAME> 1', 'Birštonas', '<NAME>', 'Fourneuby ', 'Shumen II', 'balea n', 'B<NAME>', 'Balea N', 'Jupiter, Utah', 'speikboden', 'Antholz 1', '<NAME>', '<NAME>', 'Niesen - S', 'defreggen', '<NAME>', '<NAME>', 'sorica', 'Michalkow', 'Cottbus-Nord', 'Cottbus - Nord', 'BALDY, ID', 'Bald mtn sun...', 'bald mtn sun...', 'la Breya', 'Emberger Alm 2', 'Hohe Wand - Ost', 'všechov', 'Všechov - S...', 'King Mtn Idaho', 'King Mountai...', 'SantaRita do...', 'Kocs Csörl�...', 'Kalocsa - S', 'Roldanillo ', 'sfanta ana', 'grente', 'cesaro', 'Bassano [Pan...', 'Malý Pěč�...', 'Emberger Alm 3', 'balea lac', 'castelo de vide', 'corvatch', 'Flims Casson...', 'Mount 7', 'Mt 7 golden', 'Mt 7', 'Mt 7 (Golden)', 'Mt.7 Golden', 'Mt.7', 'MT7', 'Mt. 7', 'Mt.7-Golden, BC', 'MT 7', 'Mt7 Golden', 'Mount Seven ...', 'Mt-7 (Golden)', 'Mount 7 ', 'Mt. 7 Lookout', 'Golden', 'Willi XC Loo...', 'Mount Seven ', 'Mount Sevenn', 'golden', 'Goldenn', 'Lookout', 'Golden ', 'teton village', 'Teton villiage', 'jaragua', 'Jaragua', 'Jaraguá Goi...', '0', '<NAME>', 'Osser - Ostrý', 'K<NAME>', 'El Salto ', 'la Braya', 'Mackenzie Upper', 'Upper McKenzie', 'Upper Macken...', 'Upper MacKen...', 'Mt. Seven', 'Mt Seven', 'Peña Monta�...', 'vale de amor...', 'V<NAME>', 'balea', 'jupiter', 'PORXOS', 'KOnchinka', 'riederalp (CH)', 'cavallaria f...', 'cavallaria', '<NAME>', 'Speikboden 3', 'Gaisberg NO', 'osterfelder', 'osterfelder ', 'Hochrieß', 'JARACUA', 'Galibier', 'Kozakov', 'Kalocsa - N', 'Larouco ', 'Larouco,PT', 'ROKH', 'rokh', 'pebble creek...', 'Porxos Xc', 'Porxos xc', 'Balea N.', 'Deglėnai', 'Milk Hill Wh...', 'la salle ', 'Linhares da ...', 'Linhares 1', 'Olesnica', 'Mackenzie Lower', 'Mackenzie', 'Lower Macken...', 'Mckenzie', 'Mt7', 'Niesen - SW', '<NAME>', 'Breya', 'Hinterrugg W', 'Bischling Ost', 'Bischling We...', 'Hebbronville...', 'Hebronville,...', 'Hebronnville...', 'Osterfelder ', 'Mt Mackenzie...', 'Lower Mackenzie', 'Lower MacKenzie', 'Koclířov -...', 'PLAN DE LA B...', 'Jupiter Peak', 'Narlı, Kahr...', 'Belltall,ES', 'rokh NW', 'Upper MacKenzie', 'Mt 7 Golden BC', 'McKenzie ', '<NAME>', 'Schöckl SO', 'Wildkogel 1', '<NAME>', '<NAME>', 'antholz', 'wank', '<NAME>', ' <NAME>', '<NAME>', '<NAME>', 'moosalp', 'Kössen 2', 'Seegrube SW', 'Col Rodella ...', 'COL DE L ARP...', 'fort du truc', 'oleśnica', '<NAME>', 'McKenzie - CA', '<NAME>', '<NAME>', '<NAME> 1', 'Mackenzie ', 'McKenzie upper', 'sunny peak', '<NAME>', 'Emberger', 'emberger alm', 'Bassano - Ta...', '<NAME>', '<NAME>', 'serpaton', 'les richards', 'Rokh 3angle', 'sf. ana', 'Sf Ana', 'sfânta ana', 'King mountain', 'Alliance S/W', 'Alliance E-W', 'Alliance E-W...', 'Galahad E-W', 'Galahad Tow ...', 'Galahad EW t...', 'Gal<NAME>', 'Galahad tow ...', 'rampa queralt', 'Rokh SE', 'gornergrat', 'Panarotta - ...', 'Emberger alm', 'Gresse-en-ve...', 'les Richards', 'Lower MacKen...', 'McKenzie Lau...', 'McKenzie low...', '<NAME>-E', '<NAME>', 'cornizzolo', 'Disentis Lai...', 'sta maria in...', 'jeufosse', 'Houeville', '<NAME>', '<NAME>', 'emberger', 'Embergeralm', 'meruz', 'Méru', 'Méruz', '<NAME>', 'sf ana ', 'sfanta ana ', '<NAME>', 'agostadero ', 'Ruederalp', '<NAME>', '<NAME>', 'loser', 'LOSER', '<NAME>', 'Meru', 'meruz', '<NAME>', 'luedingen', '<NAME>', '<NAME>', 'Všechov (CZ)', 'skrzetla', '<NAME>...', '<NAME>', '<NAME>', '<NAME> 2', '<NAME>', 'meruz ', 'Queralt ', 'POLSKA NOWA ...', '<NAME>', 'laveno', 'Turnthaler', 'Thurtaler', 'figuerasa', '<NAME>', 'montgellafrey ', '<NAME>', 'garzette', 'san giacomo', 'roldanillo. ...', 'Mt Borah Nor...', 'Nyaru ', 'South Kerio ...', 'takeoff sud', 'greeenacres ...', '<NAME>', 'Hay (north)', '<NAME>', 'rift Valley', 'Kerio view', 'Borah W', 'De aar', 'kerio View', 'Manilla Mt B...', 'borah', 'Mt Borah (Ma...', 'Myst<NAME>', 'Mt Borah Man...', 'Manilla, Aus...', 'Manilla SE', 'Mt Borah, Ma...', '<NAME>', 'Billing', 'Bir', '<NAME>hb...', '<NAME> ...', 'billing', 'Prasher Lake', 'jot pass', 'EGED', 'EGED /HU/', '<NAME>', 'MT Borah', 'iguala', 'RIEDERALP', 'Thurnthaler', 'Turntaler', 'WILDKOGEL', 'billing bir', 'Vsechov', 'Kobala (SI)', 'FANAS', 'Fanas ', '<NAME>', '<NAME>...', 'gotschna', 'obere wengi', 'Schuls', 'Fiesch (CH)', 'helm', 'gemona', 'S.Giacomo(Fr)', '<NAME>...', 'm<NAME>', '<NAME>', 'm.nudo', 'feltre', 'Schmitten', 'thurntaler', 'Turnthaler, AT', '<NAME>...', 'Greifenburg 12', 'Greifenburg ...', '<NAME>', 'Iguala (MX)', 'Birstonas', 'Manilla (AU)', 'DOLADA', 'rubbio', '<NAME>', 'SCHMITTEN..', '<NAME>m,', 'Mornera (Mon...', 'stelzerberg', 'Ladir', 'Fanas Eggli ...', 'OBERE WENGI', 'obere Wengi', 'Gummen - Eng...', 'Eggli', 'Eggli (CH)', 'GANA', 'fiescheralp', 'gummen (brienz)', 'W-STEIN', 'hafelekar', 'SEEGRUBE', 'stoderzinken', '<NAME>', 'quaggione', 'hausstein', 'bisanne', 'Bissane', 'meruz ', 'STOL (SLO)', 'Kocs', 'krvavec', '<NAME>', 'Mszana 2', 'SIRIA', 'Bentelo Plus 4', 'fanas eggli', '<NAME>', 'Embergeralmiece', 'Embergerarme...', 'Gaißberg', '<NAME>', 'gastein', '<NAME>', 'juffing', '<NAME>', 'Oberauer', 'Oberauersbrunst', 'vértesszölős', 'Vértesszölös', 'Fistengrat', '<NAME>', 'monte nudo l...', 'wildkogel', 'cuarnan', 'm.cuarnan', 'schöckl SO', 'Birstonas', 'Ladir (CH)', '<NAME>', '<NAME>...', '<NAME>', '<NAME>', 'rideralp', 'BIBERG', 'Emberg', '<NAME>', 'meruz ', 'Meruz ', 'Velký Lopen...', 'nyikom', 'valkininkai', 'Fanas eggli', 'Falzes', 'falzen', 'falzes', 'Platten Pfalzen', 'gsies', 'Gsies', 'Weissenstei', 'gummenalp', 'kalocsa', '<NAME>...', 'panarotta', '<NAME>', 'Seegrube!', 'ogassa', 'king mtn idaho', 'king mountain', 'Plus 4 - Ben...', 'mäggisseren', 'novegno', 'emberg alm', 'NIESEN', 'gummen', '<NAME>', 'aptenau', 'Trattberg Ab...', 'Trattberg/ A...', 'trattberg', 'Tbtenau Trat...', 'Trattberg (AT)', '<NAME>...', '<NAME>', 'hochfelln', 'HOCHFELLN', '<NAME>�...', 'montgirot', 'King Mtn. Idaho', '<NAME>...', 'niesen', 'praticino', 'piedrahita', 'Cottbus_Nord', 'Plus4 - Bentelo', '<NAME>', '<NAME>...', '<NAME>', 'denizli', 'Panukkale', 'weissenstein', 'Moosalp,CH', 'kobala', 'Soriza', 'Sorica, Sori...', 'GEMONA', 'Eged_track_p...', 'Toldijk XC M...', '<NAME>', 'súča', '<NAME>', 'Jaragua - BR', 'castelo', 'cottbus', 'karadag', 'mut', '<NAME>', 'Heimatt', 'Heimat', 'HEIMATT', 'Weissenstein...', 'kapall', 'pena negra', 'Pena negra', 'Peña Negra ...', 'Piedrahita P...', 'Pena Negra S...', 'kocs', 'balea N', 'Balea sud', 'Jaragua-GO', 'ouro preto d...', 'Livigno - Ca...', 'peñanegra', 'Piedrahita (ES)', 'Peñanegra', 'Piedrahitab', 'Chelan', 'Eger-Eged', 'horna suca', 'Súča', 'inovec', 'Jaragua - Go', 'Jaragua - GO', 'poggio bustone', 'CORNIZZOLO', 'Speickboden', 'prada del mo...', 'quarnan gemona', '<NAME>', 'Pena', 'Jaraguá - GO', 'Pine Mtn', 'PineMtn', 'Queral', 'penya montan...', 'Rampa de Que...', 'Mt. 7 Golden', 'Moosalp aka ...', 'fiesch heimat', 'SORICA', 'csobanc', 'leonpolis', 'Peña Monta...', 'FIESCH', '<NAME>', 'Cassonsgrat', 'Fiesch - Kü...', 'fiesch heimatt', 'Kueboden', 'Ayas, Ankara', 'fiesch Heimat', 'Kuhboden', 'monte Grappa', 'Cima Grappa ...', 'cima grappa', 'Mt.Grappa', 'Speikboden, ...', 'Spikeboudn', 'Nove Sady', 'schmitten', 'Defreggen', 'Teton Villag...', 'Balea Lacut ...', 'Kühboden', 'Fiescheralp,...', 'Fiesch, Chü...', 'Slovenia Kobala', 'golm', 'Deffregen', 'Hearne, TX', 'Hearne, TX USA', 'hearne, TX USA', 'Jupiter Peak...', 'Skinny Ridge...', 'gardane rokh', 'Sfanta Ana', 'speickboden', 'Fiesch, Heimat', 'Fiescheralp ...', 'FIESCH SM1', 'Fiesch, Küe...', 'Fiesch garvela', 'Fiesch Kühe...', 'Seegrube (AT)', 'Defreggen', 'kobata', 'Bald Mountain', 'Bald Mountai...', 'Mount Baldy,...', 'Bald mtn. Su...', 'Michalków', 'Bisanne (Sig...', 'speikpoden', 'davos', 'birstonas', 'Birstonas', 'Ottawa, KS', 'Bald, Sun Va...', 'sopot (BG)', '<NAME>', 'corvatsch', '<NAME>', 'bald mtn. Su...', 'Balea S', 'Walts Point', 'Bir-Billing', 'Quixada Rampa', 'Mt Bakewell', 'Bakewell', 'Barr South', 'Quixada Sant...', 'De Aar ', 'de aar', 'Serra Talhad...', 'Serra Telhada', 'Serra Telhad...', 'de Aar', 'De Aar - Vos...', 'DeAar - Vosburg', 'Branvlei', 'Priska', 'Riacho das A...', 'Booligal, NSW', 'mirador de l...', 'mirador', 'Greenacres West', 'Barrington No.3', 'South Barrin...', 'Araripina Ai...', '<NAME>', 'Ivanhoe Airs...', 'Kakamas Airf...', 'porterville', 'kerio view h...' ); $to = array( 'Roldanillo', 'Roldanillo', 'Mt. Borah', 'Kerio View', 'Kerio View', 'Kerio View', 'Mt. Borah', 'Kerio View', 'Kerio View', 'Kerio View', 'Mt. Borah', 'Kerio View', 'Kerio View', 'Roldanillo', 'Greenacres', 'Greenacres', 'Mt. Borah', 'Mt. Borah', '<NAME>', 'Mt. Borah', 'Mt. Borah', 'Mt. Borah', 'Mt. Borah', 'Roldanillo', '<NAME>', 'Mt. Borah', 'Mt. Borah', 'Mt. Borah', '<NAME>', 'Bassano', 'Serrone', 'Gemona', 'Gemona', 'Gemona', 'Bassano', 'Dubbo', 'Gemona', 'Serrone', 'Bassano', 'Bassano', 'Barrington', 'Barrington', 'Dubbo', 'Fanas', 'Fiesch', 'Landeck', 'Fiesch', 'Wildkogel', 'Serrone', 'Marlens', 'Bassano', 'Bassano', 'Fanas', 'Fanas', 'Fiesch', 'Riederalp', 'Quixadá', 'Peña Negra', 'Peña Negra', 'Kobala', 'Conargo', 'Mt. Borah', 'Greenacres', 'De Aar', 'Pampoenfontein', 'Roldanillo', 'Barrington', 'Barrington', 'Quixadá', 'Quixadá', 'Quixadá', '<NAME>', 'Mt. Borah', 'Quixadá', 'Quixadá', '<NAME>', 'Morada Nova', 'Mt. Borah', '<NAME>', 'Stol', '<NAME>', '<NAME>', 'Walt\'<NAME>', 'Walt\'<NAME>', 'Fiesch', 'Erzincan', 'Birštonas', 'Speikboden', 'Speikboden', 'Fiesch', 'Fiesch', 'Fiesch', 'Peña Negra', '<NAME>', 'Birstonas', 'Queralt', 'Fourneuby', 'Shumen', 'Balea', 'Balea', 'Balea', 'Jupiter', 'Speikboden', 'Antholz', 'Fiesch', 'Fiesch', 'Niesen', 'Defreggen', 'Stol', 'Sorica', 'Sorica', 'Michalków', 'Cottbus', 'Cottbus', 'Mt. Baldy', 'Mt. Baldy', 'Mt. Baldy', '<NAME>', '<NAME>', '<NAME>', 'Všechov', 'Všechov', 'King Mountain', 'King Mountain', 'Santa Rita d...', 'Kocs Csörl...', 'Kalocsa', 'Roldanillo', '<NAME>', 'Grente', 'Cesarò', 'Bassano', 'Malý Pěč...', '<NAME>', 'Balea', 'Castelo de V...', '<NAME>', 'Cassons', 'Mount Seven', 'Mount Seven', 'Mount Seven', 'Mount Seven', 'Mount Seven', 'Mount Seven', 'Mount Seven', 'Mount Seven', 'Mount Seven', 'Mount Seven', 'Mount Seven', 'Mount Seven', 'Mount Seven', 'Mount Seven', 'Mount Seven', 'Mount Seven', 'Mount Seven', 'Mount Seven', 'Mount Seven', 'Mount Seven', 'Mount Seven', 'Mount Seven', 'Mount Seven', 'Teton Village', 'Teton Village', 'Jaraguá', 'Jaraguá', 'Jaraguá', 'Jaraguá', '<NAME>', 'Osser', 'Kruševo', 'El Salto', 'La Breya', 'McKenzie', 'McKenzie', 'McKenzie', 'McKenzie', 'Mount Seven', 'Mount Seven', 'Peña Monta...', 'Vale de Amor...', 'Vale de Amor...', 'Balea', 'Jupiter', 'Porxos', 'Konchinka', 'Riederalp', 'Cavallaria', 'Cavallaria', '<NAME>', 'Speikboden', 'Gaisberg', 'Osterfelder', 'Osterfelder', 'Hochries', 'Jaraguá', '<NAME>', 'Kozákov', 'Kalocsa', 'Larouco', 'Larouco', 'Rokh', 'Rokh', 'Pebble Creek...', 'Porxos', 'Porxos', 'Balea', 'Deglenai', '<NAME>', '<NAME>', 'Linhares', 'Linhares', 'Oleśnica', 'McKenzie', 'McKenzie', 'McKenzie', 'McKenzie', 'Mount Seven', 'Niesen', 'Fiesch', '<NAME>', 'Hinterrugg', 'Bischling', 'Bischling', 'Hebbronville', 'Hebbronville', 'Hebbronville', 'Osterfelder', 'McKenzie', 'McKenzie', 'McKenzie', 'Koclířov', 'Plan de la B...', 'Jupiter', 'Narli', 'Belltall', 'Rokh', 'McKenzie', 'Mount Seven', 'McKenzie', 'Montanchez', 'Schöckl', 'Wildkogel', '<NAME>', 'Bischling', 'Antholz', 'Wank', 'Borsk', 'Balea', 'Balea', 'Nara', 'Moosalp', 'Kössen', 'Seegrube', '<NAME>', '<NAME> l\'Arp...', '<NAME>', 'Oleśnica', 'Rokh', 'McKenzie', 'Balea', 'Bassano', '<NAME>', 'McKenzie', 'McKenzie', '<NAME>', 'Feuerkogel', '<NAME>', '<NAME>', 'Bassano', 'Bassano', 'Cottbus', 'Serpaton', '<NAME>', 'Rokh', 'Sf. Ana', 'Sf. Ana', 'Sf. Ana', 'King Mountain', 'Alliance', 'Alliance', 'Alliance', 'Galahad', 'Galahad', 'Galahad', 'Galahad', 'Galahad', 'Queralt', 'Rokh', 'Gornergrat', 'Panarotta', '<NAME>', 'Gresse en Ve...', '<NAME>', 'McKenzie', 'McKenzie', 'McKenzie', 'Rosalind', 'Rosalind', 'Cornizzolo', '<NAME>', '<NAME>...', 'Jeufosse', 'Houéville', 'Queralt', 'Fanas', '<NAME>', '<NAME>', 'Meruz', 'Meruz', 'Meruz', 'Zlatník', 'Sf. Ana', 'Sf. Ana', 'Sf. Ana', 'agostadero', 'Riederalp', 'Antholz', 'Bassano', 'Loser', 'Loser', '<NAME>ilaire', 'Meruz', 'Meruz', '<NAME>', 'Lüdingen', 'Queralt', 'Queralt', 'Všechov', 'Skrzętla', '<NAME>', '<NAME>', '<NAME>', '<NAME>', 'Saint-Marcel', 'Meruz', 'Queralt', '<NAME> ...', 'Braunwald', 'Laveno', 'Thurntaler', 'Thurntaler', 'Figuerassa', 'Gemona', 'montgellafrey', 'Gemona', 'Gemona', '<NAME>', 'Roldanillo', 'Mt. Borah', 'Nyaru', 'Kerio View', 'Kerio View', 'Greenacres', 'Nyaru', 'Hay', '<NAME>', 'Kerio View', 'Kerio View', 'Mt. Borah', '<NAME>', 'Kerio View', 'Mt. Borah', 'Mt. Borah', 'Mt. Borah', 'Mystic', 'Mt. Borah', 'Mt. Borah', 'Mt. Borah', 'Mt. Borah', 'Gemona', '<NAME>', '<NAME>', 'Fiesch', 'Marlens', 'Bir Billing', '<NAME>', '<NAME>', 'Eged', 'Eged', 'Bischling', 'Mt. Borah', 'Iguala', 'Riederalp', 'Thurntaler', 'Thurntaler', 'Wildkogel', '<NAME>', 'Všechov', 'Kobala', 'Fanas', 'Fanas', 'Fiesch', 'Gotschna', 'Gotschna', '<NAME>', 'Scuol', 'Fiesch', 'Helm', 'Gemona', '<NAME>', 'Bassano', 'Laveno', 'Laveno', 'Laveno', 'Feltre', 'Schmittenhöhe', 'Thurntaler', 'Thurntaler', 'Thurntaler', 'Greifenburg', 'Greifenburg', '<NAME>', 'Iguala', 'Birštonas', '<NAME>', '<NAME>', 'Rubbio', 'Rubbio', 'Schmittenhöhe', '<NAME>', 'Mornera', 'Stelserberg', 'Ladir', 'Fanas', '<NAME>', '<NAME>', 'Gummen', 'Fanas', 'Fanas', 'Gana', 'Fiesch', 'Gummen', 'Weissenstein', 'Hafelekar', 'Seegrube', 'Stoderzinken', 'Laveno', 'Quaggione', 'Hausstein', 'Bisanne', 'Bisanne', 'Meruz', 'Stol', 'Kocs Csörl...', 'Krvavec', '<NAME>', 'Mszana', 'Siria', 'Bentelo', 'Fanas', '<NAME>', '<NAME>', '<NAME>', 'Gaisberg', '<NAME>', 'Gastein', 'Gaisberg', 'Jufing', 'Grente', '<NAME>', '<NAME>', 'Vértesszőlős', 'Vértesszőlős', 'Fisetengrat', 'Gemona', 'Laveno', 'Wildkogel', 'Cuarnan', 'Cuarnan', 'Schöckl', 'Birštonas', 'Ladir', 'Gummen', 'Brunni', 'Stelserberg', 'Stelserberg', 'Riederalp', 'Biberg', '<NAME>', 'Schöckl', 'Meruz', '<NAME>', 'Nyikom', 'Valkininkai', 'Fanas', 'Pfalzen', 'Pfalzen', 'Pfalzen', 'Pfalzen', '<NAME>', '<NAME>', 'Weissenstein', 'Gummen', 'Kalocsa', '<NAME>', 'Panarotta', 'Panarotta', 'Seegrube', 'Ogassa', 'King Mountain', 'King Mountain', 'Bentelo', 'Mäggisseren', 'Novegno', '<NAME>', 'Niesen', 'Gummen', 'Feuerkogel', 'Aptenau', 'Trattberg', 'Trattberg', 'Trattberg', 'Trattberg', 'Trattberg', 'Trattberg', 'Gemona', 'Gemona', 'Hochfelln', 'Hochfelln', '<NAME>...', 'Montgirot', 'King Mountain', 'Marbachegg', 'Niesen', 'Praticino', 'Peña Negra', 'Cottbus', 'Bentelo', 'Feuerkogel', '<NAME>...', '<NAME>', 'Denizli', 'Pamukkale', 'Weissenstein', 'Moosalp', 'Kobala', 'Sorica', 'Sorica', 'Gemona', 'Eged', 'Toldijk', 'Horná Súča', 'Horná Súča', 'Horná Súča', 'Jaraguá', '<NAME>', 'Cottbus', 'Karadag', 'Mut', 'Kavoliai', 'Fiesch', 'Fiesch', 'Fiesch', 'Weissenstein', 'Kapall', 'Peña Negra', 'Peña Negra', 'Peña Negra', 'Peña Negra', 'Peña Negra', 'Kocs Csörl...', 'Balea', 'Balea', 'Jaraguá', 'Ouro Preto D...', 'Livigno', 'Peña Negra', 'Peña Negra', 'Peña Negra', 'Peña Negra', '<NAME>', 'Eged', 'Horná Súča', 'Horná Súča', 'Inovec', 'Jaraguá', 'Jaraguá', '<NAME>', 'Cornizzolo', 'Speikboden', 'Prada', 'Gemona', 'Feuerkogel', 'Peña Negra', 'Jaraguá', 'Pine Mt', 'Pine Mt', 'Queralt', 'Peña Negra', 'Queralt', 'Mount Seven', 'Moosalp', 'Fiesch', 'Sorica', 'Csobánc', 'Leonpolis', '<NAME>', 'Fiesch', 'Cassons', 'Cassons', 'Fiesch', 'Fiesch', 'Fiesch', 'Ayaş', 'Fiesch', 'Fiesch', 'Bassano', 'Bassano', 'Bassano', 'Bassano', 'Speikboden', 'Speikboden', 'Nové Sady', 'Schmittenhö...', 'Defereggen', 'Teton Village', 'Balea', 'Fiesch', 'Fiesch', 'Fiesch', 'Kobala', 'Golm', 'Defereggen', 'Hearne', 'Hearne', 'Hearne', 'Jupiter', 'Skinny Ridge', 'Rokh', '<NAME>', 'Speikboden', 'Fiesch', 'Fiesch', 'Fiesch', 'Fiesch', 'Fiesch', 'Fiesch', 'Seegrube', 'Defereggen', 'Kobala', 'Mt. Baldy', 'Mt. Baldy', 'Mt. Baldy', 'Mt. Baldy', 'Michałków', 'Bisanne', 'Speikboden', 'Davos', 'Birštonas', 'Birštonas', 'Ottawa', 'Mt. Baldy', 'Sopot', 'Mirandela', 'Corvatsch', 'Corvatsch', 'Mt. Baldy', 'Balea', 'Walt\'<NAME>', '<NAME>', 'Quixadá', 'Mt. Bakewell', 'Mt. Bakewell', 'Barrington', 'Quixadá', 'De Aar', 'De Aar', 'Serra Talhada', 'Serra Talhada', 'Serra Talhada', 'De Aar', 'De Aar', 'De Aar', 'Brandvlei', 'Prieska', 'Riacho des A...', 'Booligal', 'Mirador De L...', 'Mirador De L...', 'Greenacres', 'Barrington', 'Barrington', 'Araripina', 'Roldanillo', 'Ivanhoe', 'Kakamas', 'Porterville', '<NAME>' ); foreach($from as $k => $v){ echo $v.' -> '.$to[$k].'<br />'; }<file_sep>/bak/old2.php <!DOCTYPE html> <head> <meta charset="utf-8"> <meta name="viewport" content="initial-scale=1.0, user-scalable=no" /> <title>XComp - 100k weeks</title> <style> body { font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 14px; } h1 { font-size: 18px; } table { width: 100%; } tr { background: #f8f8f8; margin-top: 4px; } th { padding: 4px; background: #333; color: #fff; text-align: left; } td { vertical-align: top; padding: 2px; padding-top: 4px; padding-left: 4px; padding-bottom: 0px; } td span { background: #E0DACD; border-radius: 3px; padding: 2px; padding-left: 5px; display: inline-block; margin-right: 8px; margin-bottom: 4px; } td span i { background: #fff; border-radius: 6px; padding: 2px; padding-left: 5px; padding-right: 5px; padding-bottom: 0px; margin: 1px; font-style: normal; font-size: 12px; line-height: 50%; } tr.spacer td { height: 1px; max-height: 1px; background: #bbb; padding: 0px; margin: 0px; overflow: hidden; } .map { position: absolute; right: 2px; bottom: 10px; width: 250px; height: 125px; border: 2px #000 solid; } </style> </head> <body> <?php error_reporting(E_ALL); ini_set('display_errors', 1); $data = json_decode(file_get_contents('100kflights.json')); echo '<h1>Best 100k destinations for each week in a year</h1>'; echo '<p>Ever wondered where to go if you want to fly as many 100k\'s in a year as possible? This list can help you. It shows where and in which week you\'ll be able to fly 100km based on the top 5800 100km flights of the top ranked pilots in that category. But take care, some of those places have really strong conditions in those weeks! ;-)</p>'; echo '<table><thead><tr><th>Week</th><th>Month</th><th>Country</th><th>Flights</th><th>Takeoffs</th><th width="250">Heatmap</th></tr></thead><tbody>'; foreach($data as $week => $countries){ $first_value = reset($countries); $first_key = key($countries); $c1 = 0; $locations = array(); echo '<tr class="spacer"><td colspan="6"></td></tr>'; foreach($countries as $country => $meta){ if ($meta->cnt > 2){ $c1++; if ($c1 == 1){ echo '<tr><td>'.$week.'</td><td>'.$countries->{$first_key}->flights[0]->month.'</td>'; } else { echo '<tr><td>&nbsp;</td><td>&nbsp;</td>'; } echo '<td><img src="countries/'.strtolower($country).'.png"> '.$country.'</td><td>'.$meta->cnt.'</td><td>'; $takeoffs = array(); foreach($meta->flights as $flight){ $lockey = round($flight->lng,1).','.round($flight->lat,1); if (isset($locations[$lockey])){ $locations[$lockey]['count']++; } else { $locations[$lockey] = array( 'lat' => round($flight->lng,1), 'lng' => round($flight->lat,1), 'count' => 1 ); } if (!isset($takeoffs[$flight->takeoff])){ $takeoffs[$flight->takeoff] = 1; } else { $takeoffs[$flight->takeoff]++; } } arsort($takeoffs); foreach($takeoffs as $takeoff => $cnt){ echo '<span>'.$takeoff.' <i>'.$cnt.'</i></span>'; } echo '</td><td width="250">&nbsp;</td></tr>'; } } while ($c1 < 6){ $c1++; echo '<tr><td colspan="6">&nbsp;</td></tr>'; } $coords = array(); $max = 0; foreach($locations as $loc){ if ($loc['count'] > $max) $max = $loc['count']; $coords[] = $loc; } echo '<tr><td colspan="6" style="position:relative"><div class="map" data-max="'.$max.'" data-coords=\''.json_encode($coords).'\'></div></td></tr>'; } echo '</tbody></table>'; ?> <p>(c) 2015 by <NAME> - Data collected from XContest</p> <script type="text/javascript" src="js/jquery-1.10.2.min.js"></script> <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script> <script type="text/javascript" src="js/heatmap.js"></script> <script type="text/javascript" src="js/gmaps-heatmap.js"></script> <script> var cnt = 0; $('.map').each( function(){ cnt++; if (cnt <= 3 || 1 == 1){ // map center var myLatlng = new google.maps.LatLng(12, 22); // map options, var myOptions = { zoom: 0, center: myLatlng, disableDefaultUI: true }; // standard map var map = new google.maps.Map($(this)[0], myOptions); var datastr = $(this).attr('data-coords'); var coords = $.parseJSON(datastr); var data = { 'max': Number($(this).attr('data-max')), 'data': coords }; // heatmap layer var heatmap = new HeatmapOverlay(map, { // radius should be small ONLY if scaleRadius is true (or small radius is intended) "radius": 10, "maxOpacity": 1, // scales the radius based on map zoom "scaleRadius": true, // if set to false the heatmap uses the global maximum for colorization // if activated: uses the data maximum within the current map boundaries // (there will always be a red spot with useLocalExtremas true) "useLocalExtrema": true, // which field name in your data represents the latitude - default "lat" latField: 'lat', // which field name in your data represents the longitude - default "lng" lngField: 'lng', // which field name in your data represents the data value - default "value" valueField: 'count' } ); heatmap.setData(data); } }); </script> </body> </html> <file_sep>/bak/old7.php <!DOCTYPE html> <head> <meta charset="utf-8"> <meta name="viewport" content="initial-scale=1.0, user-scalable=no" /> <title>XC Weeks - The best weeks to fly 100k with a paraglider!</title> <style> body, html { margin: 0px; padding: 0px; } body { font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 14px; } .container { margin: 40px; margin-bottom: 10px; position: relative; } .monthselect { position: absolute; right: 0px; top: 0px; } h1 { margin-top: 0px; font-size: 24px; font-family: 'Trebuchet MS','Lucida Grande','Lucida Sans Unicode','Lucida Sans',Tahoma,sans-serif; } .weeks { overflow: hidden; } .week { display: block; width: 474px; height: 418px; float: left; margin: 40px; margin-top: 20px; margin-right: 20px; padding: 4px; overflow: hidden; background: #fff; background: rgba(255,255,255,0.5); border-radius: 3px; -webkit-box-shadow: 0px 0px 20px 3px rgba(0,0,0,0.3); -moz-box-shadow: 0px 0px 20px 3px rgba(0,0,0,0.3); box-shadow: 0px 0px 20px 3px rgba(0,0,0,0.3); } .week .header { color: #000; padding-bottom: 4px; position: relative; } .week .header .rating { position: absolute; top: 0px; right: 0px; } .week .header .rating span { color: rgba(0,0,0,0.1); } .week .header .rating span.active { color: rgba(0,0,0,1); } .week .header .title { font-weight: 18px; font-weight: bold; } .week .header .weekrange { margin-left: 20px; font-size: 12px; } .countries { height: 150px; overflow: auto; } .week .country { padding: 4px; margin-bottom: 2px; margin-left: 2px; margin-right: 2px; position: relative; } .week .action { position: absolute; right: 7px; top: 7px; background: #333; color: #fff; border-radius: 2px; font-size: 10px; padding: 1px; padding-left: 4px; padding-right: 4px; padding-bottom: 2px; cursor: pointer; cursor: hand; -moz-user-select: -moz-none; -khtml-user-select: none; -webkit-user-select: none; -o-user-select: none; user-select: none; } .week .action:hover { background: #000; } .countryinfos { background: rgba(0,0,0,0.05); border-radius: 3px; padding: 2px; } .week .country .title { width: 55px; display: inline-block; } .week .meta { font-size: 11px; margin-left: 15px; color: #666; width: 55px; display: inline-block; } .week .meta.meta100ks { width: 70px; } .week .meta.metascore { width: 40px; } .week .meta i { font-size: 14px; color: #145a9b; font-weight: bold; font-style: normal; } .week .country .takeoffs { margin-top: 4px; padding-top: 4px; line-height: 160%; display: none; } .week .country .takeoffs .takeoff { display: inline-block; cursor: pointer; cursor: hand; -moz-user-select: -moz-none; -khtml-user-select: none; -webkit-user-select: none; -o-user-select: none; user-select: none; } .week .country .takeoffs .takeoff:hover { text-decoration: underline; } .week .country .takeoffs .flights { color: #B72106; margin-left: 4px; margin-right: 10px; } .heatmap { width: 472px; height: 235px; border: 1px #fff solid; border-radius: 4px; margin-bottom: 6px; -webkit-box-shadow: 0px 0px 5px 0px rgba(0,0,0,0.2); -moz-box-shadow: 0px 0px 5px 0px rgba(0,0,0,0.2); box-shadow: 0px 0px 5px 0px rgba(0,0,0,0.2); } body > canvas { position: fixed; top: 0px; bottom: 0px; z-index: -1; } </style> </head> <body> <?php error_reporting(E_ALL); ini_set('display_errors', 1); $data1 = json_decode(file_get_contents('data/100kflights-2015.json')); $data2 = json_decode(file_get_contents('data/100kflights-2014.json')); $data3 = json_decode(file_get_contents('data/100kflights-2013.json')); $data4 = json_decode(file_get_contents('data/100kflights-2010-2012.json')); $data = new stdClass; foreach($data1 as $week => $countries){ if (!isset($data->{$week})) $data->{$week} = new stdClass; foreach($countries as $country => $meta){ if (!isset($data->{$week}->{$country})){ $data->{$week}->{$country} = new stdClass; $data->{$week}->{$country}->cnt = 0; $data->{$week}->{$country}->flights = array(); } $data->{$week}->{$country}->flights = array_merge($data->{$week}->{$country}->flights, $meta->flights); } } foreach($data2 as $week => $countries){ if (!isset($data->{$week})) $data->{$week} = new stdClass; foreach($countries as $country => $meta){ if (!isset($data->{$week}->{$country})){ $data->{$week}->{$country} = new stdClass; $data->{$week}->{$country}->cnt = 0; $data->{$week}->{$country}->flights = array(); } $data->{$week}->{$country}->flights = array_merge($data->{$week}->{$country}->flights, $meta->flights); } } foreach($data3 as $week => $countries){ if (!isset($data->{$week})) $data->{$week} = new stdClass; foreach($countries as $country => $meta){ if (!isset($data->{$week}->{$country})){ $data->{$week}->{$country} = new stdClass; $data->{$week}->{$country}->cnt = 0; $data->{$week}->{$country}->flights = array(); } $data->{$week}->{$country}->flights = array_merge($data->{$week}->{$country}->flights, $meta->flights); } } foreach($data4 as $week => $countries){ if (!isset($data->{$week})) $data->{$week} = new stdClass; foreach($countries as $country => $meta){ if (!isset($data->{$week}->{$country})){ $data->{$week}->{$country} = new stdClass; $data->{$week}->{$country}->cnt = 0; $data->{$week}->{$country}->flights = array(); } $data->{$week}->{$country}->flights = array_merge($data->{$week}->{$country}->flights, $meta->flights); } } foreach($data as $week => $countries){ foreach($countries as $country => $meta){ $data->{$week}->{$country}->cnt = count($data->{$week}->{$country}->flights); } } echo '<div class="container">'; echo '<div class="monthselect"><select><option value="" selected>Full year</option><option value="Jan">January</option><option value="Feb">February</option><option value="Mar">March</option><option value="Apr">April</option><option value="May">May</option><option value="Jun">June</option><option value="Jul">July</option><option value="Aug">August</option><option value="Sep">September</option><option value="Oct">October</option><option value="Nov">November</option><option value="Dez">Dezember</option></select></div>'; echo '<h1>XC Weeks - The best weeks to fly 100k with a paraglider!</h1>'; echo '<p>Ever wondered where to go if you want to fly as many 100k\'s in a year as possible? This list can help you. It shows where and in which week you\'ll be able to fly 100km based on the top 15\'000 100km flights of the top ranked pilots in that category. But take care, some of those places have really strong conditions in those weeks! ;-)</p>'; echo '</div>'; function getStartAndEndDate($week, $year){ $time = strtotime("1 January $year", time()); $day = date('w', $time); $time += ((7*$week)+1-$day)*24*3600; $return[0] = date('F j.', $time); $time += 6*24*3600; $return[1] = date('F j. Y', $time); return $return; } function getStartMonth($week, $year){ $time = strtotime("1 January $year", time()); $day = date('w', $time); $time += ((7*$week)+1-$day)*24*3600; return date('M', $time); } function getEndMonth($week, $year){ $time = strtotime("1 January $year", time()); $day = date('w', $time); $time += ((7*$week)+1-$day)*24*3600; $time += 6*24*3600; return date('M', $time); } function fixTakeoff($name){ $from = array( 'Roldanillo [...', 'Roldanillo pico', 'borah N', 'Kerio View H...', 'Kerio View S...', 'kerio view', 'Mt Borah South', 'Kerio View Sud', 'kerio', 'Kerio Süd', 'Mt. Borah W', 'zrezane Kerio View', 'South Kerio', 'roldanillo', 'greenacres ...', 'Greenacres west', 'Mt. Borah E', 'Mt. Borah Nor...', 'Picco, Rolda...', 'Mt. Bora', 'Mt. Borah (AU)', 'mt borah', 'Mt. Borah S', 'Roldanillo. ...', 'El Penon', 'Mt. Borahh', 'MT. Borah', 'Mt. Borah NE', 'Stella alpina', 'Bassano [da ...', 'serrone', 'garzetta', 'garzetta gemona', 'Gemona', 'bassano', 'dubbo', '<NAME>', 'Serrone 1', 'Bassano [Ant...', 'Bassano [Cas...', '<NAME>', 'Barrington 3...', 'Dubbo north', '<NAME>', '<NAME>', 'Landeck 1', 'Fiesch [Heimat]', 'Wildkogel 2', 'Serrone (IT)', 'marlens', 'Bassano - ta...', 'BASSANO', 'fanas', 'Fanas 2', 'fiesch', 'riederalp' ); $to = array( 'Roldanillo', 'Roldanillo', 'Mt. Borah', 'Kerio View', 'Kerio View', 'Kerio View', 'Mt. Borah', 'Kerio View', 'Kerio View', 'Kerio View', 'Mt. Borah', 'Kerio View', 'Kerio View', 'Roldanillo', 'Greenacres', 'Greenacres', 'Mt. Borah', 'Mt. Borah', '<NAME>', 'Mt. Borah', 'Mt. Borah', 'Mt. Borah', 'Mt. Borah', 'Roldanillo', '<NAME>', 'Mt. Borah', 'Mt. Borah', 'Mt. Borah', '<NAME>', 'Bassano', 'Serrone', '<NAME>', '<NAME>', '<NAME>', 'Bassano', 'Dubbo', '<NAME>', 'Serrone', 'Bassano', 'Bassano', 'Barrington', 'Barrington', 'Dubbo', 'Fanas', 'Fiesch', 'Landeck', 'Fiesch', 'Wildkogel', 'Serrone', 'Marlens', 'Bassano', 'Bassano', 'Fanas', 'Fanas', 'Fiesch', 'Riederalp' ); return str_replace($from, $to, $name); } $weeks = array(); function cntsort($item1,$item2){ if ($item1['100ks'] == $item2['100ks']) return 0; return ($item1['100ks'] < $item2['100ks']) ? 1 : -1; } foreach($data as $week => $countries){ $first_value = reset($countries); $first_key = key($countries); $locations = array(); foreach($countries as $country => $meta){ $dates = array(); $max = 0; $twos = 0; foreach($meta->flights as $flight){ if ($flight->distance >= 200) $twos++; if ($flight->points > $max) $max = $flight->points; $dates[$flight->date] = true; } $score = round(count($dates) / 35 * 100); if (!isset($weeks[$week])){ $weeks[$week] = array( 'month' => $countries->{$first_key}->flights[0]->month, '100ks' => 0, 'countries' => array() ); } $weeks[$week]['100ks'] = $weeks[$week]['100ks'] + $meta->cnt; $weeks[$week]['countries'][$country] = array( '100ks' => $meta->cnt, '200ks' => $twos, 'score' => $score, 'max' => $max, 'takeoffs' => array() ); uasort($weeks[$week]['countries'], 'cntsort'); $takeoffs = array(); $takeoffpos = array(); foreach($meta->flights as $flight){ $lockey = round($flight->lng,1).','.round($flight->lat,1); if (isset($locations[$lockey])){ $locations[$lockey]['count']++; } else { $locations[$lockey] = array( 'lat' => round($flight->lng,1), 'lng' => round($flight->lat,1), 'count' => 1 ); } if (!isset($takeoffs[fixTakeoff($flight->takeoff)])){ $takeoffs[fixTakeoff($flight->takeoff)] = 1; $takeoffpos[fixTakeoff($flight->takeoff)] = array('lat' => $flight->lat, 'lng' => $flight->lng); } else { $takeoffs[fixTakeoff($flight->takeoff)]++; } } arsort($takeoffs); foreach($takeoffs as $takeoff => $cnt){ $weeks[$week]['countries'][$country]['takeoffs'][] = array('name' => $takeoff, 'flights' => $cnt, 'lat' => $takeoffpos[$takeoff]['lat'], 'lng' => $takeoffpos[$takeoff]['lng']); } } $coords = array(); $max = 0; foreach($locations as $loc){ if ($loc['count'] > $max) $max = $loc['count']; $coords[] = $loc; } $weeks[$week]['heatmapcoords'] = $coords; $weeks[$week]['heatmapmax'] = $max; } echo '<div class="weeks">'; foreach($weeks as $k => $week){ $year = (int)date("Y"); if ((int)date('W') > $k){ $weekrange = getStartAndEndDate(((int)$k)-1, $year+1); $startmonth = getStartMonth(((int)$k)-1, $year+1); $endmonth = getEndMonth(((int)$k)-1, $year+1); } else { $weekrange = getStartAndEndDate(((int)$k)-1, $year); $startmonth = getStartMonth(((int)$k)-1, $year); $endmonth = getEndMonth(((int)$k)-1, $year); } echo '<div class="week week_'.$k.' month_'.$startmonth.' month_'.$endmonth.'">'; echo '<div class="header">'; echo '<div class="rating">'; if ($week['100ks'] > 30){ echo '<span class="active">☆</span>'; } else { echo '<span>☆</span>'; } if ($week['100ks'] > 75){ echo '<span class="active">☆</span>'; } else { echo '<span>☆</span>'; } if ($week['100ks'] > 150){ echo '<span class="active">☆</span>'; } else { echo '<span>☆</span>'; } if ($week['100ks'] > 300){ echo '<span class="active">☆</span>'; } else { echo '<span>☆</span>'; } if ($week['100ks'] > 600){ echo '<span class="active">☆</span>'; } else { echo '<span>☆</span>'; } echo '</div>'; echo '<span class="title">Week '.$k.'</span>'; echo '<span class="weekrange">'.$weekrange[0].' to '.$weekrange[1].'</span>'; echo '</div>'; echo '<div class="heatmap" data-max="'.$week['heatmapmax'].'" data-coords=\''.json_encode($week['heatmapcoords']).'\'></div>'; echo '<div class="countries">'; foreach($week['countries'] as $k2 => $country){ echo '<div class="country country_'.$k2.'">'; echo '<div class="action">show takeoffs</div>'; echo '<div class="countryinfos">'; echo '<span class="title"><img src="countries/'.strtolower($k2).'.png"> '.$k2.'</span>'; echo '<span class="meta meta100ks"><i>'.$country['100ks'].'</i> 100ks</span>'; echo '<span class="meta meta200ks"><i>'.$country['200ks'].'</i> 200ks</span>'; echo '<span class="meta metascore"><i>'.$country['score'].'</i> %</span>'; echo '<span class="meta metamax"><i>'.round($country['max']).'</i> p</span>'; echo '</div>'; echo '<div class="takeoffs">'; foreach($country['takeoffs'] as $k3 => $takeoff){ echo '<div class="takeoff takeoff_'.$k3.'" data-lat="'.$takeoff['lat'].'" data-lng="'.$takeoff['lng'].'">'; echo '<span class="name">'.$takeoff['name'].'</span>'; echo '<span class="flights">'.$takeoff['flights'].'</span>'; echo '</div>'; } echo '</div>'; echo '</div>'; } echo '</div>'; echo '</div>'; } echo '</div>'; ?> <div class="container"> <p>(c) 2015 by <NAME> - Data collected from XContest</p> </div> <script type="text/javascript" src="js/jquery-1.10.2.min.js"></script> <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/trianglify/0.3.1/trianglify.min.js"></script> <script type="text/javascript" src="//maps.googleapis.com/maps/api/js?sensor=false"></script> <script type="text/javascript" src="js/heatmap.js"></script> <script type="text/javascript" src="js/gmaps-heatmap.js"></script> <script> var pattern = Trianglify({ x_colors: "RdBu", variance: "0.66", width: window.innerWidth, height: window.innerHeight, cell_size: 60 }); document.body.appendChild(pattern.canvas()); $('.action').on('click', function(){ $(this).parent().find('.takeoffs').slideToggle('fast'); }); $('.takeoff').on('click', function(){ window.open('http://www.xcontest.org/2015/world/en/flights-search/?filter%5Bpoint%5D='+$(this).attr('data-lat')+'+'+$(this).attr('data-lng')+'&filter%5Bradius%5D=5000&filter%5Bmode%5D=START&filter%5Bdate_mode%5D=dmy&filter%5Bdate%5D=&filter%5Bvalue_mode%5D=dst&filter%5Bmin_value_dst%5D=&filter%5Bcatg%5D=FAI3&filter%5Broute_types%5D=&filter%5Bavg%5D=&filter%5Bpilot%5D=&list%5Bsort%5D=pts&list%5Bdir%5D=down'); }); $('.monthselect select').on('change', function(){ var month = $(this).val(); if (month !== ''){ $('.week').hide(); $('.month_'+month).show(); } else { $('.week').show(); } }); var cnt = 0; $('.heatmap').each( function(){ cnt++; if (cnt <= 3 || 1 == 1){ // map center var myLatlng = new google.maps.LatLng(12, 22); // map options, var myOptions = { zoom: 1, minZoom: 1, maxZoom: 1, center: myLatlng, disableDefaultUI: true }; // standard map var map = new google.maps.Map($(this)[0], myOptions); var datastr = $(this).attr('data-coords'); var coords = $.parseJSON(datastr); var data = { 'max': Number($(this).attr('data-max')), 'data': coords }; // heatmap layer var heatmap = new HeatmapOverlay(map, { // radius should be small ONLY if scaleRadius is true (or small radius is intended) "radius": 6, "maxOpacity": 1, "blur": 0.95, "backgroundColor": "rgba(218,200,155,0.4)", // scales the radius based on map zoom "scaleRadius": true, // if set to false the heatmap uses the global maximum for colorization // if activated: uses the data maximum within the current map boundaries // (there will always be a red spot with useLocalExtremas true) "useLocalExtrema": true, // which field name in your data represents the latitude - default "lat" latField: 'lat', // which field name in your data represents the longitude - default "lng" lngField: 'lng', // which field name in your data represents the data value - default "value" valueField: 'count' } ); heatmap.setData(data); } }); </script> </body> </html>
aef3140d6030fafb93f246b4ce1fe596d77fb4d2
[ "Markdown", "PHP" ]
7
PHP
FrediBach/XC-Weeks
07ca49a9f7858c4e1f449d63a936bb0579579713
80ad6b25df5295cc1b3ae673f58a1eec117f6bed
refs/heads/master
<repo_name>vldavid/escuelajs-reto-04<file_sep>/src/index.js const orders = (time, product, table) => { console.log(`### Orden: ${product} para ${table}`); return new Promise((resolve, reject) => { setTimeout(() => { resolve(`=== Pedido servido: ${product}, tiempo de preparación ${time}ms para la ${table}`); }, time); }); } const menu = { hamburger: 'Combo Hamburguesa', hotdog: 'Combo Hot Dogs', pizza: 'Combo Pizza', }; const table = ['Mesa 1', 'Mesa 2', 'Mesa 3', 'Mesa 4', 'Mesa 5']; function randomTime() { var min = 1, max = 8; var rand = Math.floor(Math.random() * (max - min + 1) + min); return rand * 1000; } const waiter = () => { orders(randomTime(), `${menu.hamburger}`, table[3]) .then((res) => console.log(res)) .catch((err) => console.error(err)); }; waiter(); const waiter2 = () => { orders(randomTime(), `${menu.hotdog}`, table[0]) .then((res) => { console.log(res); orders(randomTime(), `${menu.hotdog}`, table[2]) .then((res) => console.log(res)) .catch((err) => console.error(err)); }) .catch((err) => console.error(err)); }; waiter2(); async function waiter3() { try{ let promiseTable2 = new Promise((resolve, reject) => { resolve(orders(randomTime(), `${menu.pizza}`, table[1])); }); let result = await promiseTable2; console.log(result); } catch(err){ console.log('ERROR ORDEN MESA 2'); } } waiter3();
e9cde7569b525c35c3d5bae77792932f2ed801fa
[ "JavaScript" ]
1
JavaScript
vldavid/escuelajs-reto-04
6e0bdb79523a1bc493117f6bc2dcbbe42dcdda29
87531890a7c9607487f155a3f6658081857dc4f9
refs/heads/main
<repo_name>jeet-shah/traveleasy-h<file_sep>/screens/PantCatalogue.js import React from 'react'; import { Text, View,Image,TouchableOpacity, } from 'react-native'; import MyHeader from '../component/MyHeader'; import {styles} from '../component/Styles'; import DropDownPicker from 'react-native-dropdown-picker'; import firebase from 'firebase'; import db from '../config'; export default class PantCatalgue extends React.Component{ constructor(props){ super(props) this.state={ name:this.props.navigation.getParam('details')['name'], image:this.props.navigation.getParam('details')['avatar_url'], subtitle:this.props.navigation.getParam('details')['subtitle'], count:0, size:'42', userID:firebase.auth().currentUser.email, } } render(){ return( <View style={styles.container}> <View style={{marginTop:180,width:370}}> <MyHeader title={this.state.name} navigation={this.props.navigation} /> </View> <View style={{height:300}}> </View> <Text style={{marginTop:20,fontWeight:'bold'}}> {this.state.subtitle} </Text> <View style={{flexDirection:'row',marginTop:20,marginBottom:425}}> <DropDownPicker items={[ {label: '42', value: '42',selected:true}, {label: '44', value: '44'}, {label: '46', value: '46'} ]} containerStyle={{height: 40}} onChangeItem={item => this.setState({size:item.label})} placeholder="Size" style={{width:80}} dropDownStyle={{width:100}} /> <TouchableOpacity onPress={()=>{ if(this.state.count === 0){ this.setState({count:0}) }else{ this.setState({count:this.state.count-1}) } }} style={{backgroundColor:'white',width:40,marginLeft:20}}> <Text style={{fontSize:20}}>-</Text> </TouchableOpacity> <Text style={{fontSize:20}}> {this.state.count} </Text> <TouchableOpacity onPress={()=>{this.setState({count:this.state.count+1})}} style={{backgroundColor:'white'}}> <Text style={{fontSize:20,width:40}}>+</Text> </TouchableOpacity> <TouchableOpacity style={{marginTop:20,backgroundColor:'white',marginLeft:10}} onPress={()=>{ db.collection('Cart').doc(this.state.userID).collection('Pant').add({ "PantName":this.state.name, "PantQuantity":this.state.count, "PantSize":this.state.size, "userID":this.state.userID }) }}> <Text> Add To Cart </Text> </TouchableOpacity> </View> </View> ) } }
52dec24c9f769ae97bd748f90a0b8940c53b2587
[ "JavaScript" ]
1
JavaScript
jeet-shah/traveleasy-h
9a31f9d4f4bdcef0c4695a4df4f583b74b5a092c
f31658569269e797de1988c9963452c5b0d2d33b
refs/heads/master
<file_sep>var serverUrl = "server/"; function ajaxCall(service, callback, theData, async) { if (async === undefined) { async = true; } var params = { url: serverUrl + service, contentType: "application/json; charset=utf-8", type: "POST", data: theData, dataType: "json", success: callback, async: async }; $.ajax(params); } function executeSparql(callback, data, async) { ajaxCall("sparql", callback, data, async); } function getChilds(node, callback, async) { executeSparql(callback, node, async); } <file_sep>/** * */ package sim.visualization.server; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.net.URL; import java.util.HashSet; import java.util.Set; import org.apache.log4j.Logger; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.ontoware.aifbcommons.collection.ClosableIterator; import org.ontoware.rdf2go.model.Model; import org.ontoware.rdf2go.model.QueryResultTable; import org.ontoware.rdf2go.model.QueryRow; import org.ontoware.rdf2go.model.node.Node; import org.ontoware.rdf2go.model.node.URI; import org.ontoware.rdf2go.vocabulary.OWL; import org.openrdf.rdf2go.RepositoryModel; import org.openrdf.repository.http.HTTPRepository; import org.restlet.data.Status; import org.restlet.ext.json.JsonRepresentation; import org.restlet.representation.Representation; import org.restlet.resource.Post; import org.restlet.resource.ResourceException; import org.restlet.resource.ServerResource; /** * @author valer * */ public class SparqlResource extends ServerResource { public static final Logger logger = Logger.getLogger(SparqlResource.class); private static final int CLUSTER_SIZE = 8; private static final String ONTOLOGY_URI = "http://www.larkc.eu/ontologies/IMOntology.rdf#"; private int getClusterDepth(int count) { int aCount = count, depth = 0; do { aCount = aCount / CLUSTER_SIZE; depth++; } while (aCount > CLUSTER_SIZE); return depth; } private JSONObject createClusterNode(String clusterEntity, String nodeName, String linkName, int from, int to) throws JSONException { JSONObject cluster = new JSONObject(); cluster.put("name", nodeName); cluster.put("clusterEntity", clusterEntity == null ? nodeName : clusterEntity); cluster.put("type", "cluster"); cluster.put("label", (from + 1) + ".." + to); cluster.put("from", from); cluster.put("to", to); JSONObject obj = new JSONObject(); obj.put("node", cluster); if (linkName != null) { JSONObject link = new JSONObject(); link.put("name", linkName); link.put("label", ""); obj.put("link", link); } return obj; } @Post("json") public Representation post(Representation entity) throws ResourceException { try { String nodeName = null; String nodeType = null; String clusterEntity = null; int clusterFrom = 0; int clusterTo = 0; if (entity != null) { String text = entity.getText(); JsonRepresentation represent = new JsonRepresentation(text); JSONObject jsonObject = represent.getJsonObject(); nodeName = jsonObject.getString("name"); nodeType = jsonObject.getString("type"); if (nodeType.equals("cluster")) { clusterEntity = jsonObject.getString("clusterEntity"); clusterFrom = jsonObject.getInt("from"); clusterTo = jsonObject.getInt("to"); } System.out.println(nodeName); } else { //nodes(null); //int count = nodesCount(null); //System.out.print(count); } //JSONObject json = jsonobject.getJSONObject("request"); getResponse().setStatus(Status.SUCCESS_ACCEPTED); JSONObject data = nodes(nodeName, clusterEntity, clusterFrom, clusterTo - clusterFrom); Representation rep = new JsonRepresentation(data); getResponse().setStatus(Status.SUCCESS_OK); return rep; } catch (Exception e) { getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); } return null; } /* select distinct ?x ?date where { ?x rdf:type sim:WallClockTime . ?x sim:hasTimeStamp ?date . } order by desc (?date) limit 10 */ private static final String ROOT_QUERY_ID = "root"; private static final String NODE_QUERY_ID = "node"; private String readFile(URL url) { StringBuilder content = new StringBuilder(); BufferedReader br; try { br = new BufferedReader(new FileReader(new File(url.toURI()))); } catch (Exception e) { logger.error(e.getMessage(), e); throw new RuntimeException(e.getMessage(), e); } String line = null; try { while((line = br.readLine()) != null) { content.append(line + "\n"); } br.close(); } catch (IOException e) { logger.error(e.getMessage(), e); throw new RuntimeException(e.getMessage(), e); } return content.toString(); } private String getQuery(String queryId, String parentNode, int offset, int limit) { StringBuilder query = new StringBuilder(); query.append(readFile(this.getClass().getResource("/prefixes.sparql"))); query.append(readFile(this.getClass().getResource("/" + queryId + ".sparql"))); replaceParameters(query, "$parentNode$", parentNode); if (offset > -1) { query.append("offset " + String.valueOf(offset) + "\n"); query.append("limit " + String.valueOf(limit) + "\n"); } return query.toString(); } private void replaceParameters(StringBuilder query, String parameterName, String value) { int start = -1; while (true) { start = query.indexOf(parameterName, start); if (start == -1) { break; } int end = start + parameterName.length(); query.replace(query.indexOf("$parentNode$"), end, "<" + value + ">"); } } public int countQueryRows(ClosableIterator<QueryRow> queryRows) { int count = 0; Set<String> subjects = new HashSet<String>(); while (queryRows.hasNext()) { QueryRow qr = queryRows.next(); String subject = qr.getValue("subject").toString(); if (!subjects.contains(subject)) { count++; subjects.add(subject); } } return count; } private QueryResultTable getQueryResultTable(Model model, String parentNode, int offset, int limit) { String queryId = null; if (parentNode.equals("ROOT_NODE_ID")) { queryId = ROOT_QUERY_ID; } else { queryId = NODE_QUERY_ID; } QueryResultTable qrt = model.sparqlSelect(getQuery(queryId, parentNode, offset, limit)); return qrt; } public int nodesCount(String parentNode) { Model model = openModel(); ClosableIterator<QueryRow> queryRows = getQueryResultTable(model, parentNode, -1, -1).iterator(); int count = countQueryRows(queryRows); model.close(); return count; } public JSONObject nodes(String parentNode, String clusterEntity, int offset, int count) { Model model = openModel(); if (clusterEntity == null) { count = nodesCount(parentNode); } if (count <= CLUSTER_SIZE) { JSONObject childs; try { String node = clusterEntity != null ? clusterEntity : parentNode; childs = getChildsJSON(getQueryResultTable(model, node, offset, count), parentNode); } catch (JSONException e) { logger.error(e.getMessage(), e); throw new RuntimeException(e.getMessage(), e); } finally { model.close(); } return childs; } clusterEntity = clusterEntity != null ? clusterEntity : parentNode; int depth = getClusterDepth(count); JSONArray jsonArray = new JSONArray(); int clusterSize = (int) Math.pow(CLUSTER_SIZE, depth); int clustersCount = count / clusterSize; int clustersRest = count % clusterSize; if (clustersRest > 0) { clustersCount++; } for (int i = 0; i < clustersCount; i++) { int from = offset + (i * clusterSize); int to = offset + (((clustersRest > 0) && (i == clustersCount - 1)) ? (from + clustersRest) : ((i + 1) * clusterSize)); String clusterName = clusterEntity + "-C_" + from + "_" + to; try { jsonArray.put(createClusterNode(clusterEntity, clusterName, clusterName + "L", from, to)); } catch (JSONException e) { logger.error(e.getMessage(), e); throw new RuntimeException(e.getMessage(), e); } } JSONObject jsonObject = new JSONObject(); try { jsonObject.put("node", parentNode); jsonObject.put("childs", jsonArray); } catch (JSONException e) { logger.error(e.getMessage(), e); throw new RuntimeException(e.getMessage(), e); } return jsonObject; } private Model openModel() { Model model = new RepositoryModel(new HTTPRepository("http://127.0.0.1:8080/openrdf-sesame", "sim")); model.open(); return model; } private JSONObject getChildsJSON(QueryResultTable queryResultTable, String parentNode) throws JSONException { if (queryResultTable.getVariables().size() != 3) { logger.error("The query must return exactly three variables!"); throw new RuntimeException("The query must return exactly three variables!"); } JSONArray jsonArray = new JSONArray(); ClosableIterator<QueryRow> queryRows = queryResultTable.iterator(); Set<String> subjects = new HashSet<String>(); while (queryRows.hasNext()) { QueryRow qr = queryRows.next(); Node subject = qr.getValue("subject"); Node type = qr.getValue("type"); Node predicate = qr.getValue("predicate"); if (!(subject instanceof URI)) { logger.error("the return types must pe URI!"); throw new RuntimeException("the return types must pe URI!"); } if (subjects.contains(subject.toString())) { continue; //the predicate must be different, save it on the links name } subjects.add(subject.toString()); URI valueURI = subject.asURI(); URI typeURI = type.asURI(); URI predicateURI = predicate.asURI(); jsonArray.put(createNode(valueURI, typeURI, predicateURI)); } JSONObject jsonObject = new JSONObject(); jsonObject.put("node", parentNode); jsonObject.put("childs", jsonArray); return jsonObject; } private JSONObject createNode(URI subjectURI, URI typeURI, URI predicateURI) throws JSONException { JSONObject node = new JSONObject(); node.put("name", subjectURI.toString()); node.put("type", typeURI.equals(OWL.Class) ? "class" : typeURI.equals(OWL.ObjectProperty) ? "objectProperty" : typeURI.equals(OWL.DatatypeProperty) ? "datatypeProperty" : "entity"); node.put("label", subjectURI.toString().replace(ONTOLOGY_URI, "")); JSONObject obj = new JSONObject(); obj.put("node", node); String linkName = predicateURI.toString(); if (linkName != null) { JSONObject link = new JSONObject(); link.put("name", linkName); link.put("label", linkName); obj.put("link", link); } return obj; } } /* ask { ?x rdf:type sim:TotalSystemFreeMemory . ?x ?z ?y . ?z rdfs:range xsd:dateTime . } [12:19:33 PM] Mihai Chezan: ask { ?x rdf:type sim:TotalSystemFreeMemory . ?x ?z ?y . ?y rdfs:range xsd:dateTime . } [12:21:16 PM] Mihai Chezan: ask { ?x rdf:type sim:TotalSystemFreeMemory . ?x ?z ?y . ?z rdfs:range xsd:dateTime . } [12:23:41 PM] Mihai Chezan: select ?z where { ?x rdf:type sim:TotalSystemFreeMemory . ?x ?z ?y . ?z rdfs:range xsd:dateTime . } limit 1 offset 1 [12:25:59 PM] Mihai Chezan: select ?x where { ?x rdf:type sim:TotalSystemFreeMemory . } limit 1 offset 1 */
d72fc8c10436330b718e5df6f6b907398132991b
[ "JavaScript", "Java" ]
2
JavaScript
valer-roman/sim-visualization
6dae2cec45f165197c994866171167483cf48b92
7a7e14881b7a71d84a1be1098456e490a0c8e1fc
refs/heads/master
<file_sep>// // LikesTableViewCell.swift // AIScribe // // Created by <NAME> on 5/19/18. // Copyright © 2018 RT. All rights reserved. // import UIKit class LikesTableViewCell: UITableViewCell { @IBOutlet weak var itemLbl: UILabel! @IBOutlet weak var likeBtn: UIButton! @IBOutlet weak var dislikeBtn: UIButton! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } } <file_sep>// // FacebookSignInManager.swift // Brunch Bunch // // Created by <NAME> on 3/20/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit import FBSDKLoginKit class FacebookSignInManager: NSObject { typealias LoginCompletionBlock = (Dictionary<String, AnyObject>?, NSError?) -> Void //MARK:- Public functions class func basicInfoWithCompletionHandler(_ fromViewController:AnyObject, onCompletion: @escaping LoginCompletionBlock) -> Void { //Check internet connection if no internet connection then return self.getBaicInfoWithCompletionHandler(fromViewController) { (dataDictionary:Dictionary<String, AnyObject>?, error: NSError?) -> Void in onCompletion(dataDictionary, error) } } class func logoutFromFacebook() { FBSDKLoginManager().logOut() FBSDKAccessToken.setCurrent(nil) FBSDKProfile.setCurrent(nil) } //MARK:- Private functions class fileprivate func getBaicInfoWithCompletionHandler(_ fromViewController:AnyObject, onCompletion: @escaping LoginCompletionBlock) -> Void { let permissionDictionary = [ "fields" : "id,name,first_name,last_name,gender,email,birthday,picture.type(large)", //"locale" : "en_US" ] if FBSDKAccessToken.current() != nil { FBSDKGraphRequest(graphPath: "/me", parameters: permissionDictionary) .start(completionHandler: { (connection, result, error) in if error == nil { onCompletion(result as? Dictionary<String, AnyObject>, nil) } else { onCompletion(nil, error as NSError?) } }) } else { FBSDKLoginManager().logIn(withReadPermissions: ["email", "public_profile", "user_photos"], from: fromViewController as! UIViewController, handler: { (result, error) -> Void in if error != nil { FBSDKLoginManager().logOut() if let error = error as NSError? { let errorDetails = [NSLocalizedDescriptionKey : "Processing Error. Please try again!"] let customError = NSError(domain: "Error!", code: error.code, userInfo: errorDetails) onCompletion(nil, customError) } else { onCompletion(nil, error as NSError?) } } else if (result?.isCancelled)! { FBSDKLoginManager().logOut() let errorDetails = [NSLocalizedDescriptionKey : "Request cancelled!"] let customError = NSError(domain: "Request cancelled!", code: 1001, userInfo: errorDetails) onCompletion(nil, customError) } else { let pictureRequest = FBSDKGraphRequest(graphPath: "me", parameters: permissionDictionary) let _ = pictureRequest?.start(completionHandler: { (connection, result, error) -> Void in if error == nil { onCompletion(result as? Dictionary<String, AnyObject>, nil) } else { onCompletion(nil, error as NSError?) } }) } }) } } } <file_sep>// // MenuViewController.swift // AKSwiftSlideMenu // // Created by Ashish on 21/09/15. // Copyright (c) 2015 Kode. All rights reserved. // import UIKit import AWSS3 protocol SlideMenuDelegate { func slideMenuItemSelectedAtIndex(_ index : Int32) } class MenuViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { let appDelegate = UIApplication.shared.delegate as! AppDelegate @IBOutlet weak var nameLbl: UILabel! @IBOutlet weak var userIV: UIImageView! @IBOutlet weak var premiumBtn: UIButton! var lastId : String? @IBAction func closeMenu(_ sender: Any) { } @IBAction func goPremium(_ sender: Any) { self.openViewControllerBasedOnIdentifier("Premium") delegate?.slideMenuItemSelectedAtIndex(6) } /** * Array to display menu options */ @IBOutlet var tblMenuOptions : UITableView! /** * Transparent button to hide menu */ @IBOutlet var btnCloseMenuOverlay : UIButton! /** * Array containing menu options */ var arrayMenuOptions = [Dictionary<String,String>]() /** * Menu button which was tapped to display the menu */ var btnMenu : UIButton! /** * Delegate of the MenuVC */ var delegate : SlideMenuDelegate? override func viewDidLoad() { super.viewDidLoad() lastId = "tab controller" tblMenuOptions.separatorColor = .clear tblMenuOptions.tableFooterView = UIView() if appDelegate.userImage != nil { userIV.image = appDelegate.userImage } else if appDelegate.profileImg != nil && appDelegate.profileImg != "" { downloadImage(imagename: appDelegate.profileImg!) } else { appDelegate.userImage = UIImage(named: "profile-icon") userIV.image = appDelegate.userImage } if appDelegate.firstname != nil && appDelegate.lastname != nil { nameLbl.text = "\(appDelegate.firstname!) \(appDelegate.lastname!)" } else { nameLbl.text = "" } if appDelegate.fullVersion == true { premiumBtn.isHidden = true } NotificationCenter.default.addObserver( self, selector: #selector(appUpgradeNotification), name: NSNotification.Name(rawValue: "appUpgraded"), object: nil) } @objc func appUpgradeNotification (notification: NSNotification) { print("upgrade app UI") premiumBtn.isHidden = true tblMenuOptions.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) updateArrayMenuOptions() } func updateArrayMenuOptions(){ arrayMenuOptions.append(["title":"My Files","subtitle":"View your transcribed files.", "icon":"PlayIcon"]) arrayMenuOptions.append(["title":"My Corpora","subtitle":"Creating a corpus allows you to expand the vocabulary of your transcription service.", "icon":"PlayIcon"]) arrayMenuOptions.append(["title":"My Account","subtitle":"Edit your profile, password, preferences and more.", "icon":"PlayIcon"]) arrayMenuOptions.append(["title":"Logout", "subtitle":"", "icon":"PlayIcon"]) tblMenuOptions.reloadData() } @IBAction func onCloseMenuClick(_ button:UIButton!){ //self.tabBarController?.tabBar.isHidden = true btnMenu.tag = 0 if (self.delegate != nil) { var index = Int32(button.tag) if(button == self.btnCloseMenuOverlay) { index = -1 } if appDelegate.fullVersion == false { if index == 3 || index == 4 { return } } delegate?.slideMenuItemSelectedAtIndex(index) } UIView.animate(withDuration: 0.3, animations: { () -> Void in self.view.frame = CGRect(x: -UIScreen.main.bounds.size.width, y: 0, width: UIScreen.main.bounds.size.width,height: UIScreen.main.bounds.size.height) self.view.layoutIfNeeded() self.view.backgroundColor = UIColor.clear }, completion: { (finished) -> Void in self.view.removeFromSuperview() self.removeFromParentViewController() }) } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 75 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // old slider logic let btn = UIButton(type: UIButtonType.custom) btn.tag = indexPath.row self.onCloseMenuClick(btn) //NotificationCenter.default.post(name: Notification.Name("closeNav"), object: indexPath.row) //new slider logic //newLogic(indexPath.row) } func newLogic (index : Int) { switch(index){ case 0: print("Home1") self.openViewControllerBasedOnIdentifier("tab controller") break case 1: print("edit profile") self.openViewControllerBasedOnIdentifier("My Account") break case 2: print("manage friends") self.openViewControllerBasedOnIdentifier("My Friends") break case 3: print("manage groups") self.openViewControllerBasedOnIdentifier("My Groups") break case 4: print("manage family") self.openViewControllerBasedOnIdentifier("Manage Family") break case 5: print("logout") NotificationCenter.default.post(name: Notification.Name("Logout"), object: nil) break default: print("default\n", terminator: "") } } func openViewControllerBasedOnIdentifier(_ strIdentifier:String){ let destViewController : UIViewController = self.storyboard!.instantiateViewController(withIdentifier: strIdentifier) let topViewController : UIViewController = self.navigationController!.topViewController! if (lastId == destViewController.restorationIdentifier!){ print("Same VC") } else { lastId = strIdentifier self.navigationController!.pushViewController(destViewController, animated: true) self.view.removeFromSuperview() self.removeFromParentViewController() } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cellMenu")! as! MenuTableViewCell cell.selectionStyle = UITableViewCellSelectionStyle.none cell.layoutMargins = UIEdgeInsets.zero cell.preservesSuperviewLayoutMargins = false //cell.backgroundColor = UIColor.clear let lblTitle : UILabel = cell.contentView.viewWithTag(101) as! UILabel let lblTitle2 : UILabel = cell.contentView.viewWithTag(102) as! UILabel let lockIV : UIImageView = cell.contentView.viewWithTag(103) as! UIImageView //let imgIcon : UIImageView = cell.contentView.viewWithTag(100) as! UIImageView //imgIcon.image = UIImage(named: arrayMenuOptions[indexPath.row]["icon"]!) lblTitle.text = arrayMenuOptions[indexPath.row]["title"]! lblTitle2.text = arrayMenuOptions[indexPath.row]["subtitle"]! if indexPath.row == 5 { //cell.subheaderBottomPadding.constant = 0 cell.subheaderHeight.constant = 5 } if appDelegate.fullVersion == false { if indexPath.row == 3 || indexPath.row == 4 { lockIV.isHidden = false } else { lockIV.isHidden = true } } else { lockIV.isHidden = true } return cell } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return arrayMenuOptions.count } func numberOfSections(in tableView: UITableView) -> Int { return 1; } func downloadImage (imagename : String) { if appDelegate.downloadImages == true { let s3BucketName = "shotgraph1224/aiscribe" let downloadFilePath = (NSTemporaryDirectory() as NSString).appendingPathComponent(imagename) let downloadingFileURL = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(imagename) // Set the logging to verbose so we can see in the debug console what is happening //AWSLogger.default().logLevel = .none let downloadRequest = AWSS3TransferManagerDownloadRequest() downloadRequest?.bucket = s3BucketName downloadRequest?.key = imagename downloadRequest?.downloadingFileURL = downloadingFileURL let transferManager = AWSS3TransferManager.default() //[[transferManager download:downloadRequest] continueWithExecutor:[AWSExecutor mainThreadExecutor] withBlock:^id(AWSTask *task) { transferManager.download(downloadRequest!).continueWith(executor: AWSExecutor.mainThread(), block: ({ (task: AWSTask!) -> AWSTask<AnyObject>? in DispatchQueue.main.async(execute: { if task.error != nil { print("AWS Error downloading image") print(task.error.debugDescription) } else { //print("AWS download successful") var downloadOutput = AWSS3TransferManagerDownloadOutput() downloadOutput = task.result! as? AWSS3TransferManagerDownloadOutput print("downloadOutput photo: \(downloadOutput)"); print("downloadFilePath photo: \(downloadFilePath)"); let image = UIImage(contentsOfFile: downloadFilePath) self.userIV.image = image self.appDelegate.userImage = image } //println("test") }) return nil })) } else { self.userIV.image = UIImage.init(named: "profile-icon") } } } <file_sep>// // MyCorpora.swift // AIScribe // // Created by <NAME> on 6/8/19. // Copyright © 2019 RT. All rights reserved. // import UIKit class MyCorpora: BaseViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate { let appDelegate = UIApplication.shared.delegate as! AppDelegate var itemArray = [CorpusItem]() var currentItemArray = [CorpusItem]() private let refreshControl = UIRefreshControl() @IBOutlet weak var search: UISearchBar! @IBOutlet weak var activityView: UIActivityIndicatorView! @IBOutlet weak var menuBtn: UIButton! @IBOutlet weak var statusView: UIView! var did : String? var modelList = NSMutableArray() var selectedCorpus: CorpusItem? @IBOutlet weak var modelsTable: UITableView! override func viewDidLoad() { super.viewDidLoad() menuBtn.addTarget(self, action: #selector(BaseViewController.onSlideMenuButtonPressed(_:)), for: UIControlEvents.touchUpInside) self.statusView.isHidden = true modelsTable.tableFooterView = UIView() modelsTable.dataSource = self modelsTable.delegate = self search.delegate = self refreshControl.addTarget(self, action: #selector(manualRefresh(_:)), for: .valueChanged) if #available(iOS 10.0, *) { modelsTable.refreshControl = refreshControl } else { modelsTable.addSubview(refreshControl) } getCorpora() activityView.startAnimating() let keyboardDoneButtonView = UIToolbar() keyboardDoneButtonView.sizeToFit() let doneButton = UIBarButtonItem(title: "Done", style: .bordered, target: self, action: #selector(self.doneClicked)) keyboardDoneButtonView.items = [doneButton] search?.inputAccessoryView = keyboardDoneButtonView // Do any additional setup after loading the view. NotificationCenter.default.addObserver( self, selector: #selector(refreshCorporaNotification), name: NSNotification.Name(rawValue: "refreshCorpora"), object: nil) } @objc private func manualRefresh(_ sender: Any) { refreshCorporaControl() } func refreshCorporaControl() { itemArray.removeAll() getCorpora() } @objc func doneClicked(sender: UIButton!) { self.view.endEditing(true) } @objc func refreshCorporaNotification (notification: NSNotification) { print("refreshCorporaNotification") itemArray.removeAll() getCorpora() } func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { currentItemArray = itemArray.filter({ item -> Bool in switch searchBar.selectedScopeButtonIndex { case 0: if searchText.isEmpty { return true } return item.filename.lowercased().contains(searchText.lowercased()) || item.modelname.lowercased().contains(searchText.lowercased()) || item.content.lowercased().contains(searchText.lowercased()) || item.status.lowercased().contains(searchText.lowercased()) default: return false } }) modelsTable.reloadData() } func getCorpora() { print("getCorpora") let dataString = "corporaData" let urlString = "\(appDelegate.serverDestination!)getCorpusJSON.php" let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" let paramString = "uid=\(appDelegate.userid!)&mobile=true&devStatus=\(appDelegate.devStage!)" print("urlString: \(urlString)") print("paramString: \(paramString)") request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let session = URLSession.shared session.dataTask(with: request) {data, response, err in do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary print("files jsonResult: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary if dataDict[dataString]! is NSNull { print("no data") DispatchQueue.main.sync(execute: { self.statusView.isHidden = false self.activityView.isHidden = true self.activityView.stopAnimating() self.refreshControl.endRefreshing() //self.noResultsMain.isHidden = false }) //self.statusLbl.isHidden = false } else { let uploadData : NSMutableArray = (dataDict[dataString]! as! NSArray).mutableCopy() as! NSMutableArray if (uploadData.count > 0) { //let list = uploadData as! NSMutableArray for ob in uploadData { let dict = ob as! NSDictionary //self.modelList.add(dict) self.itemArray.append(CorpusItem(filename: dict.object(forKey: "filename") as! String, cpid: dict.object(forKey: "cpid") as! String, mid: dict.object(forKey: "mid") as! String, cid: dict.object(forKey: "cid") as! String, modelname: dict.object(forKey: "modelname") as! String, content: dict.object(forKey: "content") as! String, status: dict.object(forKey: "status") as! String)) } self.currentItemArray = self.itemArray DispatchQueue.main.sync(execute: { self.activityView.isHidden = true self.statusView.isHidden = true self.activityView.stopAnimating() self.modelsTable.reloadData() self.refreshControl.endRefreshing() }) } else { DispatchQueue.main.sync(execute: { self.statusView.isHidden = false self.activityView.isHidden = true self.activityView.stopAnimating() self.refreshControl.endRefreshing() //self.noResultsMain.isHidden = false }) } } } catch let err as NSError { print("error: \(err.description)") } }.resume() } // MARK: Tableview func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 44 } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = Bundle.main.loadNibNamed("FileHeaderCell", owner: self, options: nil)?.first as! FileHeaderCell headerView.headerLbl.text = "MY CORPORA" headerView.headerLbl.textColor = appDelegate.gray51 let font1 = UIFont.init(name: "Avenir-Heavy", size: 16.0) headerView.headerLbl.font = font1 headerView.leadingWidth.constant = 20 return headerView } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { selectedCorpus = currentItemArray[indexPath.row] //did = selectedCorpus!.cpid self.performSegue(withIdentifier: "EditCorpus", sender: self) } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 140 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.currentItemArray.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell")! let dict = currentItemArray[(indexPath as NSIndexPath).row] cell.selectionStyle = .none let v0 = cell.viewWithTag(1) as! UILabel let v1 = cell.viewWithTag(2) as! UILabel let v2 = cell.viewWithTag(3) as! UIButton let v3 = cell.viewWithTag(4) as! UILabel //let v3 = cell.viewWithTag(4) as! UIButton let v4 = cell.viewWithTag(5) as! UILabel let first30 = String(dict.content.prefix(30)) v0.text = "\(dict.filename).txt" v1.text = "Content: \(first30)..." v3.text = "Model: \(dict.modelname)" v4.text = "Status: \(dict.status)" v2.restorationIdentifier = "\(indexPath.row)" //v3.restorationIdentifier = "\(indexPath.row)" return cell } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "EditCorpus" { let destination = segue.destination as! EditCorpus destination.selectedCorpus = selectedCorpus } } } class CorpusItem { let filename: String let cpid: String let mid: String let cid: String let modelname: String let content: String let status: String init(filename: String, cpid: String, mid: String, cid: String, modelname: String, content: String, status: String) { self.filename = filename self.cpid = cpid self.mid = mid self.cid = cid self.modelname = modelname self.content = content self.status = status } } <file_sep>// // BasicProfileInfo.swift // AIScribe // // Created by <NAME> on 5/19/18. // Copyright © 2018 RT. All rights reserved. // import UIKit class BasicProfileInfo: UIViewController, UITextFieldDelegate { let appDelegate = UIApplication.shared.delegate as! AppDelegate let prefs = UserDefaults.standard @IBOutlet weak var activityView: UIActivityIndicatorView! @IBOutlet weak var pregnantBtn: UIButton! @IBOutlet weak var breastfeedingBtn: UIButton! @IBOutlet weak var submitBtn: UIButton! @IBOutlet weak var pregnantView: UIView! @IBOutlet weak var instructionsLbl: UILabel! @IBOutlet weak var genderSegment: UISegmentedControl! var isPregnant : Bool? var isBreastfeeding : Bool? @IBOutlet weak var fullnameLbl: UILabel! @IBOutlet weak var fullnameTxt: UITextField! @IBOutlet weak var dobLbl: UILabel! @IBOutlet weak var dobTxt: UITextField! @IBOutlet weak var dobTxtTopPadding: NSLayoutConstraint! @IBOutlet weak var fullnameTxtTopPadding: NSLayoutConstraint! @IBOutlet weak var dobPicker: UIDatePicker! @IBOutlet weak var dateView: UIView! var selectedDate : String? override func viewDidLoad() { super.viewDidLoad() appDelegate.signingUp = true isPregnant = false isBreastfeeding = false activityView.isHidden = true dateView.isHidden = true dobTxtTopPadding.constant = 0 //fullnameTxtTopPadding.constant = 0 //years in days * seconds in a day let d = Date(timeInterval: -6570*86400, since: NSDate() as Date) //dobPicker.setDate(NSDate() as Date, animated: false) dobPicker.setDate(d, animated: false) pregnantView.isHidden = true fullnameLbl.isHidden = true dobLbl.isHidden = true let attributedString = NSMutableAttributedString(string: "* You can change this from your Account Settings", attributes: [ .font: UIFont(name: "Avenir-Book", size: 12.0)!, .foregroundColor: appDelegate.crWarmGray ]) attributedString.addAttribute(.font, value: UIFont(name: "Avenir-Heavy", size: 12.0)!, range: NSRange(location: 32, length: 16)) instructionsLbl.attributedText = attributedString let btnItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.done, target: self, action: #selector(dismissKeyboard)) let numberToolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 50)) numberToolbar.backgroundColor = UIColor.darkGray numberToolbar.barStyle = UIBarStyle.default numberToolbar.tintColor = UIColor.black numberToolbar.items = [ UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil), btnItem] numberToolbar.sizeToFit() fullnameTxt.inputAccessoryView = numberToolbar dobTxt.inputAccessoryView = numberToolbar //debug() } func debug() { fullnameTxt.text = "\(appDelegate.randomString(length: 5)) \(appDelegate.randomString(length: 5))" selectDate() } @objc func dismissKeyboard () { self.view.endEditing(true) } func selectDate () { selectedDate = appDelegate.convertDateToSQLDate(date: dobPicker.date) let df = DateFormatter() df.dateFormat = "MM/d/yy" let displayString = df.string(from: dobPicker.date) dobTxt.text = displayString dateView.isHidden = true // if editingIndex == 0 // { // heightTxt.text = "\(selectedFoot!) ft, \(selectedInch!) in" // } // else if editingIndex == 1 // { heightWeightPicker.isHidden = false // // weightTxt.text = "\(selectedWeight!) lbs" // } // else // { // dobLbl.isHidden = false // // selectedDateString = appDelegate.convertDateToSQLDate(date: dobPicker.date) // selectedDate = dobPicker.date // // let df = DateFormatter() // df.dateFormat = "MM/d/yy" // // let displayString = df.string(from: dobPicker.date) // // dobTxt.text = displayString // pickersView.isHidden = true // } } @IBAction func selectPicker(_ sender: Any) { selectDate() } @IBAction func showDatePopup(_ sender: Any) { dismissKeyboard() dateView.isHidden = false } @IBAction func selectCusines(_ sender: Any) { //self.performSegue(withIdentifier: "SelectCuisines", sender: self) if fullnameTxt.text == "" { self.showBasicAlert(string: "Please Enter Full Name") return } if dobTxt.text == "" { self.showBasicAlert(string: "Please Enter Date of Birth") return } uploadUserData() } func showBasicAlert(string:String) { let alert = UIAlertController(title: nil, message: string, preferredStyle: UIAlertControllerStyle.alert) self.present(alert, animated: true, completion: nil) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in switch action.style { case .default: print("default") case .cancel: print("cancel") case .destructive: print("destructive") } })) } @IBAction func selectDate(_ sender: Any) { selectedDate = appDelegate.convertDateToSQLDate(date: dobPicker.date) appDelegate.dob = selectedDate let df = DateFormatter() df.dateFormat = "MM/d/yy" let displayString = df.string(from: dobPicker.date) dobTxt.text = displayString dateView.isHidden = true } @IBAction func managePregnant(_ sender: Any) { if isPregnant == true { pregnantBtn.setBackgroundImage(UIImage.init(named: "unselected"), for: .normal) isPregnant = false } else { pregnantBtn.setBackgroundImage(UIImage.init(named: "selected"), for: .normal) isPregnant = true } } @IBAction func manageBreastfeeding(_ sender: Any) { if isBreastfeeding == true { breastfeedingBtn.setBackgroundImage(UIImage.init(named: "unselected"), for: .normal) isBreastfeeding = false } else { breastfeedingBtn.setBackgroundImage(UIImage.init(named: "selected"), for: .normal) isBreastfeeding = true } } @IBAction func manageGender(_ sender: Any) { if genderSegment.selectedSegmentIndex != 0 { pregnantView.isHidden = false } else { pregnantView.isHidden = true } } func textFieldDidEndEditing(_ textField: UITextField) { if textField.restorationIdentifier == "fullname" && textField.text != "" { fullnameLbl.isHidden = false //usernameLblHeight.constant = 18 //fullnameTxtTopPadding.constant = 0 } else if textField.restorationIdentifier == "dob" && textField.text != "" { dobLbl.isHidden = false //emailLblHeight.constant = 18 dobTxtTopPadding.constant = 5 } } func uploadUserData() { submitBtn.isEnabled = false activityView.isHidden = false activityView.startAnimating() print("uploadUserData") let urlString = "\(appDelegate.serverDestination!)updateProfile.php" print("urlString: \(urlString)") let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" let paramString = "fullname=\(fullnameTxt.text!)&dob=\(selectedDate!)&gender=\(genderSegment.selectedSegmentIndex)&isbreastfeeding=\(isBreastfeeding!)&ispregnant=\(isPregnant!)&basicprofile=true&uid=\(appDelegate.userid!)&devStatus=\(appDelegate.devStage!)&mobile=true" print("paramString: \(paramString)") request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let session = URLSession.shared session.dataTask(with: request) {data, response, err in do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary print("add user jsonResult: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary if dataDict["userData"]! is NSNull { print("no user") } else { let userDict : NSDictionary = dataDict["userData"] as! NSDictionary let status : String = userDict["status"] as! String print("status: \(status)") if (status == "basic info saved") { let name = self.fullnameTxt.text let nameParts = name?.split(separator: " ") if nameParts!.count > 1 { self.appDelegate.firstname = String(nameParts![0]) self.appDelegate.lastname = String(nameParts![1]) } else { self.appDelegate.firstname = String(nameParts![0]) self.appDelegate.lastname = "" } self.prefs.setValue(self.appDelegate.firstname, forKey: "firstname") self.prefs.setValue(self.appDelegate.lastname, forKey: "lastname") self.prefs.synchronize() DispatchQueue.main.sync(execute: { self.activityView.isHidden = true self.activityView.stopAnimating() self.performSegue(withIdentifier: "SelectCuisines", sender: self) }) } else { DispatchQueue.main.sync(execute: { self.activityView.isHidden = true self.activityView.stopAnimating() self.submitBtn.isEnabled = true self.submitBtn.alpha = 1 //self.showBasicAlert(string: status) }) } } } catch let err as NSError { print("error: \(err.description)") } }.resume() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } <file_sep>// // Transcribe.swift // AIScribe // // Created by <NAME> on 5/24/19. // Copyright © 2019 RT. All rights reserved. // import UIKit import MobileCoreServices import Alamofire import AVFoundation class Transcribe: BaseViewController, UIPickerViewDelegate, UIPickerViewDataSource { @IBOutlet weak var filenameLbl: UILabel! var languageList = NSMutableArray() var modelsList = NSMutableArray() @IBOutlet weak var filenameLblHeight: NSLayoutConstraint! let appDelegate = UIApplication.shared.delegate as! AppDelegate var sandboxURL : URL? var selectedLanguage : NSDictionary? var selectedModel : NSDictionary? var selectedCode : String? var hasFile: Bool? @IBOutlet weak var activityView: UIActivityIndicatorView! @IBOutlet weak var menuBtn: UIButton! @IBOutlet weak var fileBtn: UIButton! @IBOutlet weak var languageBtn: UIButton! @IBOutlet weak var transcribeBtn: UIButton! @IBOutlet weak var languagePicker: UIPickerView! @IBOutlet weak var languagePopup: UIView! var cost : Float? @IBOutlet weak var modelsBtn: UIButton! @IBOutlet weak var modelsBtnHeight: NSLayoutConstraint! var showingLanguage : Bool? var cid : String? var selectedLang : String? var selectedModelName : String? @IBOutlet weak var customModelTopPadding: NSLayoutConstraint! override func viewDidLoad() { super.viewDidLoad() let tb : TabController = self.parent as! TabController menuBtn.addTarget(self, action: #selector(tb.onSlideMenuButtonPressed(_:)), for: UIControlEvents.touchUpInside) activityView.isHidden = true languagePicker.delegate = self languagePicker.dataSource = self filenameLbl.text = "" languagePopup.isHidden = true filenameLblHeight.constant = 0 transcribeBtn.isEnabled = false modelsBtn.isHidden = true modelsBtnHeight.constant = 0 customModelTopPadding.constant = 0 cid = "" getLanguages() NotificationCenter.default.addObserver( self, selector: #selector(hideTranscribePickerNotification), name: NSNotification.Name(rawValue: "hideTranscribePicker"), object: nil) NotificationCenter.default.addObserver( self, selector: #selector(resetTranscriptionNotification), name: NSNotification.Name(rawValue: "resetTranscription"), object: nil) NotificationCenter.default.addObserver( self, selector: #selector(hideTranscriptionActivityViewNotification), name: NSNotification.Name(rawValue: "hideTranscriptionActivityView"), object: nil) } @objc func hideTranscriptionActivityViewNotification (notification: NSNotification) { print("hideTranscriptionActivityViewNotification") activityView.stopAnimating() activityView.isHidden = true resetFields() } @objc func resetTranscriptionNotification (notification: NSNotification) { resetFields() } func resetFields() { print("reset transcription defaults") activityView.stopAnimating() activityView.isHidden = true //file = nil languagePicker.selectRow(0, inComponent: 0, animated: false) filenameLbl.text = "" languagePopup.isHidden = true filenameLblHeight.constant = 0 transcribeBtn.isEnabled = false modelsBtn.isEnabled = true languageBtn.isEnabled = true fileBtn.isEnabled = true languageBtn.setTitle("Choose audio language...", for: .normal) languageBtn.backgroundColor = UIColor.init(red: 214/255.0, green: 217/255.0, blue: 217/255.0, alpha: 1.0) transcribeBtn.backgroundColor = appDelegate.gray74 transcribeBtn.setTitle("TRANSCRIBE", for: .normal) selectedCode = nil self.modelsBtn.isHidden = true self.modelsBtnHeight.constant = 0 self.customModelTopPadding.constant = 0 self.cid = nil self.selectedModel = nil self.modelsBtn.setTitle("Custom models...", for: .normal) } @objc func hideTranscribePickerNotification (notification: NSNotification) { print("hideTranscribePickerNotification") languagePopup.isHidden = true } @IBAction func showPopup(_ sender: Any) { let btn = sender as! UIButton if btn.restorationIdentifier == "languageBtn" { showingLanguage = true if selectedLanguage == nil { selectedLanguage = languageList[0] as? NSDictionary } else { let ind = self.languageList.index(of: selectedLanguage!) languagePicker.selectRow(ind, inComponent: 0, animated: false) } } else { showingLanguage = false if selectedModel == nil { selectedModel = modelsList[0] as? NSDictionary languagePicker.selectRow(0, inComponent: 0, animated: false) } else { let ind = self.modelsList.index(of: selectedModel!) languagePicker.selectRow(ind, inComponent: 0, animated: false) } } languagePicker.reloadAllComponents() languagePopup.isHidden = false } @IBAction func transcribeFile(_ sender: Any) { print("transcribe file") activityView.startAnimating() activityView.isHidden = false transcribeBtn.isEnabled = false modelsBtn.isEnabled = false languageBtn.isEnabled = false fileBtn.isEnabled = false transcribeBtn.setTitle("TRANSCRIBING", for: .normal) initTransribeAF() } @IBAction func selectLanguage(_ sender: Any) { if showingLanguage == true { if selectedLanguage == nil { selectedLanguage = languageList[0] as? NSDictionary } selectedCode = selectedLanguage?.object(forKey: "code") as? String selectedLang = selectedLanguage?.object(forKey: "modelname") as? String languageBtn.setTitle(selectedLang, for: .normal) validateForm() getLanguageModels() } else { cid = selectedModel?.object(forKey: "cid") as? String selectedModelName = selectedModel?.object(forKey: "modelname") as? String modelsBtn.setTitle(selectedModelName, for: .normal) print("cid: \(cid!)") } languagePopup.isHidden = true } func validateForm() { if selectedLanguage != nil && hasFile == true { transcribeBtn.backgroundColor = appDelegate.crGreen transcribeBtn.isEnabled = true } else { transcribeBtn.backgroundColor = appDelegate.gray74 transcribeBtn.isEnabled = false } } @IBAction func openFile(_ sender: Any) { let docPicker = UIDocumentPickerViewController(documentTypes: [kUTTypeMP3 as String, kUTTypeWaveformAudio as String, kUTTypeAudio as String], in: .import) docPicker.delegate = self docPicker.allowsMultipleSelection = false present(docPicker, animated: true, completion: nil) } // MARK: Webservice func getLanguageModels() { modelsList.removeAllObjects() print("getLanguageModels") let dataString = "modelsData" let urlString = "\(appDelegate.serverDestination!)getLanguageModelsJSON.php" let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" let paramString = "uid=\(appDelegate.userid!)&code=\(selectedCode!)&mobile=true&devStatus=\(appDelegate.devStage!)" print("urlString: \(urlString)") print("paramString: \(paramString)") request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let session = URLSession.shared session.dataTask(with: request) {data, response, err in do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary print("models jsonResult: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary if dataDict[dataString]! is NSNull { print("no data") DispatchQueue.main.sync(execute: { self.modelsBtn.isHidden = true self.modelsBtnHeight.constant = 0 self.customModelTopPadding.constant = 0 self.cid = nil self.selectedModel = nil self.modelsBtn.setTitle("Custom models...", for: .normal) }) } else { let uploadData = (dataDict[dataString]! as! NSArray).mutableCopy() as! NSMutableArray if (uploadData.count > 0) { //let list = uploadData as! NSMutableArray for ob in uploadData { let dict = ob as! NSDictionary self.modelsList.add(dict) } self.selectedModel = self.modelsList[0] as? NSDictionary DispatchQueue.main.sync(execute: { self.activityView.isHidden = true self.activityView.stopAnimating() if self.modelsList.count > 0 { self.modelsBtn.isHidden = false self.modelsBtnHeight.constant = 35 self.customModelTopPadding.constant = 8 } else { self.modelsBtn.isHidden = true self.modelsBtnHeight.constant = 0 self.customModelTopPadding.constant = 0 } //self.languagePicker.reloadAllComponents() }) } else { DispatchQueue.main.sync(execute: { //self.noResultsMain.isHidden = false }) } } } catch let err as NSError { print("error: \(err.description)") } }.resume() } func getLanguages() { print("getLanguages") let dataString = "languageData" let urlString = "\(appDelegate.serverDestination!)getLanguagesJSON.php" let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" let paramString = "uid=\(appDelegate.userid!)&mobile=true&devStatus=\(appDelegate.devStage!)" print("urlString: \(urlString)") //print("paramString: \(paramString)") request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let session = URLSession.shared session.dataTask(with: request) {data, response, err in do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary print("files jsonResult: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary if dataDict[dataString]! is NSNull { print("no data") DispatchQueue.main.sync(execute: { //self.noResultsMain.isHidden = false }) //self.statusLbl.isHidden = false } else { let uploadData = (dataDict[dataString]! as! NSArray).mutableCopy() as! NSMutableArray if (uploadData.count > 0) { //let list = uploadData as! NSMutableArray for ob in uploadData { let dict = ob as! NSDictionary self.languageList.add(dict) } DispatchQueue.main.sync(execute: { self.selectedLanguage = self.languageList[0] as? NSDictionary self.selectedCode = self.selectedLanguage?.object(forKey: "code") as? String self.getLanguageModels() self.activityView.isHidden = true self.activityView.stopAnimating() self.languagePicker.reloadAllComponents() }) } else { DispatchQueue.main.sync(execute: { //self.noResultsMain.isHidden = false }) } } } catch let err as NSError { print("error: \(err.description)") } }.resume() } func initTransribeAF () { let language = self.selectedLanguage?.object(forKey: "code") as! String if cid == nil { cid = "" } let params = [ "uid": appDelegate.userid, "language": language, "estimatedCost": "\(self.cost!)", "cid": cid!, "mobile": "true" ] Alamofire.upload( multipartFormData: { multipartFormData in multipartFormData.append(self.sandboxURL!, withName: "file") for (key, value) in params { multipartFormData.append((value?.data(using: String.Encoding.utf8)!)!, withName: key) } }, to: "http://localhost:8888/aiscribe/initTranscribeJSON.php", encodingCompletion: { encodingResult in switch encodingResult { case .success(let upload, _, _): upload.responseJSON { response in print("response: \(response)") if let JSON = response.result.value { //print("JSON: \(JSON)") let dataDict : NSDictionary = JSON as! NSDictionary let data = dataDict.object(forKey: "data") as! NSDictionary let transcribeData = data.object(forKey: "transcribeData") as! NSDictionary let status = transcribeData.object(forKey: "status") as! String if status == "document saved" { let did = transcribeData.object(forKey: "did") as! String let file = NSMutableDictionary() file.setValue(did, forKey: "did") file.setValue("Pending", forKey: "status") file.setValue(self.sandboxURL!.lastPathComponent, forKey: "filename") file.setValue("today", forKey: "date") file.setValue(self.sandboxURL!, forKey: "url") NotificationCenter.default.post(name: Notification.Name("transcriptionStarted"), object: file) self.tabBarController?.selectedIndex = 0 } else { self.activityView.isHidden = true self.activityView.stopAnimating() self.transcribeBtn.isEnabled = true self.transcribeBtn.backgroundColor = self.appDelegate.crGreen self.transcribeBtn.setTitle("TRANSCRIBE", for: .normal) let alert = UIAlertController(title: nil, message: status, preferredStyle: UIAlertControllerStyle.alert) self.present(alert, animated: true, completion: nil) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in switch action.style{ case .default: print("default") case .cancel: print("cancel") case .destructive: print("destructive") } })) } } } case .failure(let encodingError): print(encodingError) } } ) } func sendDoc2 () { // var parameters: Parameters = [ // "ingredients": "newIngredientOptions", // "userid": "", // "recipeid": "recipeID", // "servings": "servingSize" // ] Alamofire.upload( multipartFormData: { multipartFormData in multipartFormData.append(self.sandboxURL!, withName: "file") }, to: "http://localhost:8888/aiscribe/getFileLengthAF.php", encodingCompletion: { encodingResult in switch encodingResult { case .success(let upload, _, _): upload.responseJSON { response in print("response: \(response)") if let JSON = response.result.value { //print("JSON: \(JSON)") let dataDict : NSDictionary = JSON as! NSDictionary let len = dataDict.object(forKey: "len") self.cost = dataDict.object(forKey: "estimatedCost") as? Float print("len: \(len!)") self.hasFile = true self.filenameLblHeight.constant = 50 let cd = String(format: "%.2f", self.cost!) self.filenameLbl.text = "\(self.sandboxURL!.lastPathComponent)\n Estimated Cost: $\(cd)" self.validateForm() } //debugPrint(response) } case .failure(let encodingError): print(encodingError) } } ) //https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#uploading-data-to-a-server } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ } extension Transcribe : UIDocumentPickerDelegate { func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) { guard let selectedURL = urls.first else { return } let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! sandboxURL = dir.appendingPathComponent(selectedURL.lastPathComponent) if FileManager.default.fileExists(atPath: sandboxURL!.path) { print("do nothin") print("sandboxURL: \(sandboxURL!)") print("selectedURL: \(selectedURL)") print("ext: \(sandboxURL!.pathExtension)") print("filename: \(sandboxURL!.lastPathComponent)") if sandboxURL!.pathExtension == "mp3" || sandboxURL!.pathExtension == "wav" || sandboxURL!.pathExtension == "flac" { filenameLblHeight.constant = 50 filenameLbl.text = sandboxURL!.lastPathComponent //sendDoc2() // let item = AVPlayerItem(url: sandboxURL!) // // let player = AVPlayer(playerItem: item) // let duration = player.currentItem?.duration.seconds let asset = AVURLAsset(url: sandboxURL!, options: nil) let audioDuration = asset.duration let audioDurationSeconds = CMTimeGetSeconds(audioDuration) //print("duration: \(duration)") print("audioDurationSeconds: \(audioDurationSeconds)") let costPerSecond = 0.02/60; let markup = 0.5; let markupTotal = (costPerSecond * markup) + costPerSecond //console.log("costPerSecond: " + costPerSecond); //console.log("markupTotal: " + markupTotal); var estimatedCost = Double(Int(audioDurationSeconds)) * Double(markupTotal) //console.log("estimatedCost: " + estimatedCost.toFixed(2)); if(estimatedCost < 1) { estimatedCost = 1.0 } self.cost = Float(estimatedCost) let cd = String(format: "%.2f", self.cost!) self.hasFile = true self.filenameLblHeight.constant = 50 self.filenameLbl.text = "\(self.sandboxURL!.lastPathComponent)\n Estimated Cost: $\(cd)" self.validateForm() } else { let alert = UIAlertController(title: nil, message: "Invalid file type", preferredStyle: UIAlertControllerStyle.alert) self.present(alert, animated: true, completion: nil) alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { action in switch action.style{ case .default: print("default") case .cancel: print("cancel") case .destructive: print("destructive") } })) } } else { do { try FileManager.default.copyItem(at: selectedURL, to: sandboxURL!) print("copied!") } catch { print("Error: \(error)") } } } // MARK: Pickerview func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { if showingLanguage == true { return languageList.count } else { return modelsList.count } } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { if showingLanguage == true { selectedLanguage = languageList[row] as? NSDictionary } else { selectedModel = modelsList[row] as? NSDictionary } //currentPhaseInd = row } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { var lang : NSDictionary? if showingLanguage == true { lang = languageList[row] as? NSDictionary } else { lang = modelsList[row] as? NSDictionary } var model = lang!.object(forKey: "modelname") as? String model = model!.replacingOccurrences(of: "- Narrowband", with: "") return model } } <file_sep>// // MyAccount.swift // AIScribe // // Created by DTO MacBook11 on 11/15/18. // Copyright © 2018 RT. All rights reserved. // import UIKit import AWSS3 class MyAccount: BaseViewController, UITableViewDataSource, UITableViewDelegate { let appDelegate = UIApplication.shared.delegate as! AppDelegate var prefsList = [NSDictionary]()//["Diet", "Nutrition Goals", "Notifications"] var moreList = [NSDictionary]()//["About Us", "Recommend App", "Feedback", "Legal Information"] @IBOutlet weak var accountTable: UITableView! @IBOutlet weak var menuBtn: UIButton! override func viewDidLoad() { super.viewDidLoad() accountTable.delegate = self accountTable.dataSource = self accountTable.tableFooterView = UIView() accountTable.separatorStyle = .none menuBtn.addTarget(self, action: #selector(BaseViewController.onSlideMenuButtonPressed(_:)), for: UIControlEvents.touchUpInside) // let tb : TabController = self.parent as! TabController // // menuBtn.addTarget(self, action: #selector(tb.onSlideMenuButtonPressed(_:)), for: UIControlEvents.touchUpInside) // prefsList.append(["title":"Diet", "icon":"diet"]) // prefsList.append(["title":"Nutrition Goals", "icon":"nutrition-goals"]) // prefsList.append(["title":"Notifications", "icon":"notifications"]) //moreList.append(["title":"About Us", "icon":"about-us"]) //moreList.append(["title":"Recommend App", "icon":"recommend-app"]) moreList.append(["title":"Feedback", "icon":"feedback"]) //moreList.append(["title":"Legal Information", "icon":"legal"]) accountTable.reloadData() } // MARK: Tableview Methods func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if section == 1 || section == 2 { return 44 } else { return 0 } } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if section == 1 || section == 2 { let headerView = Bundle.main.loadNibNamed("MemberHeaderCell", owner: self, options: nil)?.first as! MemberHeaderCell if section == 1 { headerView.headerLbl.text = "MORE" } // else // { // headerView.headerLbl.text = "MORE" // } headerView.headerLbl.textColor = appDelegate.gray51 let font1 = UIFont.init(name: "Avenir-Heavy", size: 16.0) headerView.headerLbl.font = font1 headerView.leadingWidth.constant = 20 return headerView } else { return nil } } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.row == 0 && indexPath.section == 0 { return 88 } else { return 62 } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell : UITableViewCell? //print("indexPath.row: \(indexPath.row) indexPath.section: \(indexPath.section)") if indexPath.section == 0 { cell = tableView.dequeueReusableCell(withIdentifier: "cell1")! let lblTitle = cell?.contentView.viewWithTag(1) as! UILabel //lblTitle.text = "\(appDelegate.firstname!) \(appDelegate.lastname!)" lblTitle.text = "\(appDelegate.username!)" // if indexPath.row == 0 // { // cell = tableView.dequeueReusableCell(withIdentifier: "cell1")! // // let lblTitle = cell?.contentView.viewWithTag(1) as! UILabel // // //lblTitle.text = "\(appDelegate.firstname!) \(appDelegate.lastname!)" // lblTitle.text = "\(appDelegate.username!)" // //// let imgIcon = cell?.contentView.viewWithTag(0) as! UIImageView //// imgIcon.image = appDelegate.userImage // } // else // { // cell = tableView.dequeueReusableCell(withIdentifier: "cell2")! // } } // else if indexPath.section == 1 { // // cell = tableView.dequeueReusableCell(withIdentifier: "cell3")! // // let lblTitle = cell?.contentView.viewWithTag(1) as! UILabel // let imgIcon = cell?.contentView.viewWithTag(0) as! UIImageView // let separator = cell?.contentView.viewWithTag(3) as! UIView // // lblTitle.text = prefsList[indexPath.row].object(forKey: "title") as? String // imgIcon.image = UIImage.init(named: prefsList[indexPath.row].object(forKey: "icon") as! String) // // if indexPath.row == 2 // { // separator.isHidden = true // } // } else { cell = tableView.dequeueReusableCell(withIdentifier: "cell3")! let lblTitle = cell?.contentView.viewWithTag(1) as! UILabel let imgIcon = cell?.contentView.viewWithTag(0) as! UIImageView let separator = cell?.contentView.viewWithTag(3) as! UIView lblTitle.text = moreList[indexPath.row].object(forKey: "title") as? String imgIcon.image = UIImage.init(named: moreList[indexPath.row].object(forKey: "icon") as! String) if indexPath.row == 3 { separator.isHidden = true } } cell?.selectionStyle = UITableViewCellSelectionStyle.none return cell! } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.row == 0 && indexPath.section == 0 { self.performSegue(withIdentifier: "EditProfile", sender: nil) } // else if indexPath.row == 0 && indexPath.section == 1 // { // self.performSegue(withIdentifier: "EditDiet", sender: nil) // } // else if indexPath.row == 1 && indexPath.section == 1 // { // self.performSegue(withIdentifier: "NutritionGoals", sender: nil) // } // else if indexPath.row == 2 && indexPath.section == 1 // { // self.performSegue(withIdentifier: "Notifications", sender: nil) // } // else if indexPath.row == 0 && indexPath.section == 1 // { // self.performSegue(withIdentifier: "AboutUs", sender: nil) // } // else if indexPath.row == 0 && indexPath.section == 1 // { // self.performSegue(withIdentifier: "RecommendApp", sender: nil) // } else if indexPath.row == 0 && indexPath.section == 1 { self.performSegue(withIdentifier: "Feedback", sender: nil) } // else if indexPath.row == 3 && indexPath.section == 1 // { // self.performSegue(withIdentifier: "Terms", sender: nil) // } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { //return 2 return 1 } // else if section == 1 // { // return prefsList.count // } else { return moreList.count } } func numberOfSections(in tableView: UITableView) -> Int { return 2; } func downloadImage (imagename : String, iv: UIImageView) { if appDelegate.downloadImages == true { let s3BucketName = "shotgraph1224/aiscribe" let downloadFilePath = (NSTemporaryDirectory() as NSString).appendingPathComponent(imagename) let downloadingFileURL = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(imagename) // Set the logging to verbose so we can see in the debug console what is happening //AWSLogger.default().logLevel = .none let downloadRequest = AWSS3TransferManagerDownloadRequest() downloadRequest?.bucket = s3BucketName downloadRequest?.key = imagename downloadRequest?.downloadingFileURL = downloadingFileURL let transferManager = AWSS3TransferManager.default() //[[transferManager download:downloadRequest] continueWithExecutor:[AWSExecutor mainThreadExecutor] withBlock:^id(AWSTask *task) { transferManager.download(downloadRequest!).continueWith(executor: AWSExecutor.mainThread(), block: ({ (task: AWSTask!) -> AWSTask<AnyObject>? in DispatchQueue.main.async(execute: { if task.error != nil { print("AWS Error downloading image") print(task.error.debugDescription) } else { //print("AWS download successful") var downloadOutput = AWSS3TransferManagerDownloadOutput() downloadOutput = task.result! as? AWSS3TransferManagerDownloadOutput print("downloadOutput photo: \(downloadOutput)"); print("downloadFilePath photo: \(downloadFilePath)"); let image = UIImage(contentsOfFile: downloadFilePath) iv.image = image } //println("test") }) return nil })) } else { iv.image = UIImage.init(named: "profile-icon") } } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. if segue.identifier == "EditProfile" { let destination = segue.destination as! EditProfile //destination.newFamilyMemberID = newFamilyMemberID destination.isEditing = true } } } <file_sep>// // ViewController.swift // AIScribe // // Created by <NAME> on 5/18/18. // Copyright © 2018 RT. All rights reserved. // import UIKit class ViewController: UIViewController { let appDelegate = UIApplication.shared.delegate as! AppDelegate let prefs = UserDefaults.standard @IBOutlet weak var iconIV: UIImageView! var pageInd : Int = 0 var pageDescriptions = ["Transcribe, Like Magic","Translate 20+ Languages!","For Any Industry"] var pageTitles = ["Upload audio files and get searchable, editable transcripts in minutes.","Translate audio or upload files to communicate with your customers in their own language.","Transcribe from microphone audio to analyzing hours of recordings from your call center."] var images = [UIImage.init(named: "transcription-landing"),UIImage.init(named: "translation-landing"),UIImage.init(named: "industry-landing")] @IBOutlet weak var titleLbl: UILabel! @IBOutlet weak var descriptionLbl: UILabel! @IBOutlet weak var btn1: UIButton! @IBOutlet weak var btn2: UIButton! @IBOutlet weak var btn3: UIButton! @IBOutlet weak var iconHeight: NSLayoutConstraint! @IBOutlet weak var iconWidth: NSLayoutConstraint! override func viewDidLoad() { super.viewDidLoad() if prefs.string(forKey: "onboarded") != nil { performSegue(withIdentifier: "loginSignupLoad", sender: nil) } titleLbl.text = pageDescriptions[0] descriptionLbl.text = pageTitles[0] UIApplication.shared.applicationIconBadgeNumber = 0 let leftSwipe = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipes(_:))) let rightSwipe = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipes(_:))) leftSwipe.direction = .left rightSwipe.direction = .right view.addGestureRecognizer(leftSwipe) view.addGestureRecognizer(rightSwipe) } @objc func handleSwipes(_ sender:UISwipeGestureRecognizer) { if (sender.direction == .left) { print("Swipe Left") if pageInd > 0 { pageInd -= 1 } } if (sender.direction == .right) { print("Swipe Right") if pageInd == 2 { self.prefs.setValue("yes" , forKey: "onboarded") self.prefs.synchronize() performSegue(withIdentifier: "loginSignup", sender: nil) } else { pageInd += 1 } } print("pageInd: \(pageInd)") manageTurn() } func manageTurn () { titleLbl.text = pageDescriptions[pageInd] descriptionLbl.text = pageTitles[pageInd] var theColor : UIColor? if pageInd == 0 { theColor = appDelegate.crGreen3 btn1.setBackgroundImage(UIImage.init(named: "white-circle"), for: .normal) btn2.setBackgroundImage(UIImage.init(named: "black-circle"), for: .normal) btn3.setBackgroundImage(UIImage.init(named: "black-circle"), for: .normal) } else if pageInd == 1 { theColor = appDelegate.crLightBlue btn1.setBackgroundImage(UIImage.init(named: "black-circle"), for: .normal) btn2.setBackgroundImage(UIImage.init(named: "white-circle"), for: .normal) btn3.setBackgroundImage(UIImage.init(named: "black-circle"), for: .normal) } else { theColor = appDelegate.gray74 btn1.setBackgroundImage(UIImage.init(named: "black-circle"), for: .normal) btn2.setBackgroundImage(UIImage.init(named: "black-circle"), for: .normal) btn3.setBackgroundImage(UIImage.init(named: "white-circle"), for: .normal) } iconIV.image = images[pageInd] UIView.animate(withDuration: 0.5, delay: 0.0, options: [.transitionCrossDissolve, .allowAnimatedContent], animations: { self.view.backgroundColor = theColor }) } @IBAction func showPage(_ sender: Any) { let btn : UIButton = sender as! UIButton pageInd = Int(btn.restorationIdentifier!)! titleLbl.text = pageDescriptions[pageInd] descriptionLbl.text = pageTitles[pageInd] manageTurn() } @IBAction func skipOnboarding(_ sender: Any) { self.prefs.setValue("yes" , forKey: "onboarded") self.prefs.synchronize() performSegue(withIdentifier: "loginSignup", sender: nil) } @IBAction func nextPage(_ sender: Any) { print("pageInd: \(pageInd)") if pageInd == 2 { self.prefs.setValue("yes" , forKey: "onboarded") self.prefs.synchronize() performSegue(withIdentifier: "loginSignup", sender: nil) } else { pageInd += 1 manageTurn() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } public extension UIDevice { static let modelName: String = { var systemInfo = utsname() uname(&systemInfo) let machineMirror = Mirror(reflecting: systemInfo.machine) let identifier = machineMirror.children.reduce("") { identifier, element in guard let value = element.value as? Int8, value != 0 else { return identifier } return identifier + String(UnicodeScalar(UInt8(value))) } func mapToDevice(identifier: String) -> String { // swiftlint:disable:this cyclomatic_complexity #if os(iOS) switch identifier { case "iPod5,1": return "iPod Touch 5" case "iPod7,1": return "iPod Touch 6" case "iPhone3,1", "iPhone3,2", "iPhone3,3": return "iPhone 4" case "iPhone4,1": return "iPhone 4s" case "iPhone5,1", "iPhone5,2": return "iPhone 5" case "iPhone5,3", "iPhone5,4": return "iPhone 5c" case "iPhone6,1", "iPhone6,2": return "iPhone 5s" case "iPhone7,2": return "iPhone 6" case "iPhone7,1": return "iPhone 6 Plus" case "iPhone8,1": return "iPhone 6s" case "iPhone8,2": return "iPhone 6s Plus" case "iPhone9,1", "iPhone9,3": return "iPhone 7" case "iPhone9,2", "iPhone9,4": return "iPhone 7 Plus" case "iPhone8,4": return "iPhone SE" case "iPhone10,1", "iPhone10,4": return "iPhone 8" case "iPhone10,2", "iPhone10,5": return "iPhone 8 Plus" case "iPhone10,3", "iPhone10,6": return "iPhone X" case "iPhone11,2": return "iPhone XS" case "iPhone11,4", "iPhone11,6": return "iPhone XS Max" case "iPhone11,8": return "iPhone XR" case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return "iPad 2" case "iPad3,1", "iPad3,2", "iPad3,3": return "iPad 3" case "iPad3,4", "iPad3,5", "iPad3,6": return "iPad 4" case "iPad4,1", "iPad4,2", "iPad4,3": return "iPad Air" case "iPad5,3", "iPad5,4": return "iPad Air 2" case "iPad6,11", "iPad6,12": return "iPad 5" case "iPad7,5", "iPad7,6": return "iPad 6" case "iPad2,5", "iPad2,6", "iPad2,7": return "iPad Mini" case "iPad4,4", "iPad4,5", "iPad4,6": return "iPad Mini 2" case "iPad4,7", "iPad4,8", "iPad4,9": return "iPad Mini 3" case "iPad5,1", "iPad5,2": return "iPad Mini 4" case "iPad6,3", "iPad6,4": return "iPad Pro 9.7 Inch" case "iPad6,7", "iPad6,8": return "iPad Pro 12.9 Inch" case "iPad7,1", "iPad7,2": return "iPad Pro 12.9 Inch 2. Generation" case "iPad7,3", "iPad7,4": return "iPad Pro 10.5 Inch" case "AppleTV5,3": return "Apple TV" case "AppleTV6,2": return "Apple TV 4K" case "AudioAccessory1,1": return "HomePod" case "i386", "x86_64": return "Simulator \(mapToDevice(identifier: ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] ?? "iOS"))" default: return identifier } #elseif os(tvOS) switch identifier { case "AppleTV5,3": return "Apple TV 4" case "AppleTV6,2": return "Apple TV 4K" case "i386", "x86_64": return "Simulator \(mapToDevice(identifier: ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] ?? "tvOS"))" default: return identifier } #endif } return mapToDevice(identifier: identifier) }() } <file_sep>// // AppDelegate.swift // AIScribe // // Created by <NAME> on 5/18/18. // Copyright © 2018 RT. All rights reserved. // import UIKit import CoreData import Foundation import SystemConfiguration import AWSS3 import AWSCognito import FBSDKCoreKit //import GooglePlaces import FacebookCore import FacebookLogin import Stripe import UserNotifications import HockeySDK @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var crGray : UIColor = UIColor.init(red: 91.0/255.0, green: 92.0/255.0, blue: 89.0/255.0, alpha: 1.0) var crOrange : UIColor = UIColor.init(red: 229.0/255.0, green: 89.0/255.0, blue: 52.0/255.0, alpha: 1.0) var crOrange2 : UIColor = UIColor.init(red: 250.0/255.0, green: 121.0/255.0, blue: 33.0/255.0, alpha: 1.0) var crOrange3 : UIColor = UIColor.init(red: 219.0/255.0, green: 107.0/255.0, blue: 29.0/255.0, alpha: 1.0) var crWarmGray : UIColor = UIColor.init(red: 155.0/255.0, green: 155.0/255.0, blue: 155.0/255.0, alpha: 1.0) var crLightBlue : UIColor = UIColor.init(red: 91/255.0, green: 192/255.0, blue: 235/255.0, alpha: 1.0) var crGreen : UIColor = UIColor.init(red: 134/255.0, green: 183/255.0, blue: 24/255.0, alpha: 1.0) var crGreen2 : UIColor = UIColor.init(red: 155/255.0, green: 197/255.0, blue: 61/255.0, alpha: 1.0) var crGreen3 : UIColor = UIColor.init(red: 156/255.0, green: 195/255.0, blue: 72/255.0, alpha: 1.0) var gray51 : UIColor = UIColor.init(red: 51/255.0, green: 51/255.0, blue: 51/255.0, alpha: 1.0) var gray180 : UIColor = UIColor.init(red: 180/255.0, green: 180/255.0, blue: 180/255.0, alpha: 1.0) var tomato : UIColor = UIColor.init(red: 229/255.0, green: 89/255.0, blue: 52/255.0, alpha: 1.0) var whitefive : UIColor = UIColor.init(red: 247/255.0, green: 247/255.0, blue: 247/255.0, alpha: 1.0) var gray74 : UIColor = UIColor.init(red: 74.0/255.0, green: 74.0/255.0, blue: 74.0/255.0, alpha: 1.0) var blue56 : UIColor = UIColor.init(red: 56/255.0, green: 216/255.0, blue: 212/255.0, alpha: 1.0) var serverDestination : String? var userid : String! var genuserid : String! var loggedIn : Bool? var profileImg : String? var fbID : String? var firstname: String! var lastname: String! var city: String! var state: String! var country: String! var zip: String! var email: String! var username: String! var mobile: String! var password: String! var referralCode: String! var userImagename: String! var birthday: String! var credits: String! var gender: Int! var userImage : UIImage? var debug : Bool? var lat: String! var lng: String! var fullVersion : Bool? var initLoaded : Bool = false var cloudVersion : Int = 0 var isAuthenticated : Bool? var usertype : String? var deviceid : String? var devicetoken : String? var viewMessageIdentifier = "VIEW_MESSAGE" var messageCategoryIdentifier = "MESSAGE_CATEGORY" var pushMessageUserID : String? var isFBLogin : Bool? var isTwitterLogin : Bool? var notificationsSetting : Int = 0 let prefs = UserDefaults.standard var isAddingFamily : Bool? var signingUp : Bool? var devStage : String? var downloadImages : Bool? var dob : String? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { fullVersion = true downloadImages = true //$(SWIFT_MODULE_NAME)-Swift.h //TestFairy.begin("ec963cd05b830146b2cf9039a57ee8bf80b07863") debug = true #if (arch(i386) || arch(x86_64)) && os(iOS) //print("simulator") #else //print("not simulator") debug = false; #endif //debug = false; //userid = "1" //debug = false devStage = "prod" if debug == true { serverDestination = "http://localhost:8888/aiscribe/" } else { serverDestination = "http://192.168.127.12/" } if prefs.integer(forKey: "notifications") != nil { notificationsSetting = prefs.integer(forKey: "notifications") } registerForPushNotifications() //GMSPlacesClient.provideAPIKey("<KEY>") UNUserNotificationCenter.current().delegate = self initAWS() //initPayments() initHockey() AppEventsLogger.activate(application) return FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions) } func initPayments () { STPPaymentConfiguration.shared().publishableKey = "pk_test_6pRNASCoBOKtIshFeQd4XMUh" STPPaymentConfiguration.shared().appleMerchantIdentifier = "your apple merchant identifier" } func initHockey () { BITHockeyManager.shared().configure(withIdentifier: "a8ac9f9fa8ef463dac8cfd8740c6dad2") BITHockeyManager.shared().start() BITHockeyManager.shared().authenticator.authenticateInstallation() } func registerForPushNotifications() { UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in print("Permission granted: \(granted)") guard granted else { return } // 1 let viewAction = UNNotificationAction(identifier: self.viewMessageIdentifier, title: "View", options: [.foreground]) // 2 let messageCategory = UNNotificationCategory(identifier: self.messageCategoryIdentifier, actions: [viewAction], intentIdentifiers: [], options: []) // 3 UNUserNotificationCenter.current().setNotificationCategories([messageCategory]) self.getNotificationSettings() } } func getNotificationSettings() { UNUserNotificationCenter.current().getNotificationSettings { (settings) in print("Notification settings: \(settings)") guard settings.authorizationStatus == .authorized else { return } UIApplication.shared.registerForRemoteNotifications() } } func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { let tokenParts = deviceToken.map { data -> String in return String(format: "%02.2hhx", data) } devicetoken = tokenParts.joined() print("Device Token: \(devicetoken!)") if userid != nil { //NotificationCenter.default.post(name: Notification.Name("updateToken"), object: nil) } } func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { print("Failed to register: \(error)") } func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool { return FBSDKApplicationDelegate.sharedInstance().application(application, open: url as URL!, sourceApplication: sourceApplication, annotation: annotation) } func initAWS () { let credentialsProvider = AWSCognitoCredentialsProvider(regionType:.USEast2, identityPoolId:"us-east-2:81c9384e-b1e7-4a25-b9dc-5bbd9fb2971d") let configuration = AWSServiceConfiguration(region:.USEast2, credentialsProvider:credentialsProvider) AWSServiceManager.default().defaultServiceConfiguration = configuration } func checkNull (param: AnyObject) -> AnyObject { if param.isMember(of: NSNull.self) { return "" as AnyObject } else { return param as AnyObject } } func randomString(length: Int) -> String { let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" let len = UInt32(letters.length) var randomString = "" for _ in 0 ..< length { let rand = arc4random_uniform(len) var nextChar = letters.character(at: Int(rand)) randomString += NSString(characters: &nextChar, length: 1) as String } return randomString } func currentTime (date : Date) -> String { let inputFormatter = DateFormatter() //var dateNow = NSDate() inputFormatter.dateFormat = "hh:mm a" let theLoggedInTokenTimestampDateEpochSeconds = date.timeIntervalSince1970 let timeInt = Int(theLoggedInTokenTimestampDateEpochSeconds) //NSLog(@"timeInt now: %d",timeInt); let dateNow = Date.init(timeIntervalSinceReferenceDate: TimeInterval(timeInt)) //NSLog(@"date: %@",[inputFormatter stringFromDate:dateNow]); let s = inputFormatter.string(from: dateNow as Date) return s; } func convertSQLDateTime (origDate : String) -> String { let inputFormatter = DateFormatter() //var dateNow = NSDate() inputFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" let d : Date = inputFormatter.date(from: origDate)! let df = DateFormatter() df.dateFormat = "MM/d/yy hh:mm a" let cv : String = df.string(from: d) return cv; } func convertSQLDateTimeProfile (origDate : String) -> String { let inputFormatter = DateFormatter() //var dateNow = NSDate() inputFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" let d : Date = inputFormatter.date(from: origDate)! let df = DateFormatter() df.dateFormat = "MM/d/yy" let cv : String = df.string(from: d) return cv; } func formatMessageDate (date : Date) -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MM/dd/yyyy hh:mm a" let selectedDate = dateFormatter.string(from: Date()) return selectedDate; } func formatMessageDate1 (date : Date, format: String) -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = format let selectedDate = dateFormatter.string(from: date) return selectedDate; } func convertDateToSQLTime (date : Date) -> String { let inputFormatter = DateFormatter() inputFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" let selectedDate = inputFormatter.string(from: date) return selectedDate } func convertDateToSQLDate (date : Date) -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" let selectedDate = dateFormatter.string(from: date) return selectedDate } func validateDate(date:String)->Bool { let dateFormatterGet = DateFormatter() dateFormatterGet.dateFormat = "MM/yyyy" let someDate = date if dateFormatterGet.date(from: someDate) != nil { let calendar = Calendar.current let year = calendar.component(.year, from: dateFormatterGet.date(from: someDate)!) print("valid: \(year)") return true } else { print("invalid") return false } } func isInternetAvailable() -> Bool { var zeroAddress = sockaddr_in() zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { zeroSockAddress in SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress) } } var flags = SCNetworkReachabilityFlags() if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) { return false } let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0 let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0 return (isReachable && !needsConnection) } func randomStringWithLength (len : Int) -> NSString { let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" let randomString : NSMutableString = NSMutableString(capacity: len) for i : Int in 0 ..< len { let length = UInt32 (letters.length) let rand = arc4random_uniform(length) randomString.appendFormat("%C", letters.character(at: Int(rand))) } return randomString } func isStringAnInt(string: String) -> Bool { return Int(string) != nil || Float(string) != nil } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "AIScribe") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } } extension AppDelegate: UNUserNotificationCenterDelegate { func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { // 1 let userInfo = response.notification.request.content.userInfo let aps = userInfo["aps"] as! [String: AnyObject] if aps["category"]! as! String == messageCategoryIdentifier { pushMessageUserID = aps["body"]! as? String print("pushMessageUserID: \(pushMessageUserID!)") NotificationCenter.default.post(name: NSNotification.Name(rawValue: "returnHome"), object: nil) NotificationCenter.default.post(name: Notification.Name("goToMessages"), object: nil) } completionHandler() } } <file_sep>// // MenuTableViewCell.swift // AIScribe // // Created by <NAME> on 4/5/19. // Copyright © 2019 RT. All rights reserved. // import UIKit class MenuTableViewCell: UITableViewCell { @IBOutlet weak var subheaderBottomPadding: NSLayoutConstraint! @IBOutlet weak var subheaderHeight: NSLayoutConstraint! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } } <file_sep>// // TranslationResult.swift // AIScribe // // Created by <NAME> on 5/24/19. // Copyright © 2019 RT. All rights reserved. // import UIKit import Alamofire class TranslationResult: UIViewController, UITextFieldDelegate, UIWebViewDelegate { let appDelegate = UIApplication.shared.delegate as! AppDelegate @IBOutlet weak var activityView: UIActivityIndicatorView! @IBOutlet weak var headerLbl: UILabel! @IBOutlet weak var filenameLbl: UILabel! @IBOutlet weak var transcriptionTV: UITextView! @IBOutlet weak var outputLbl: UILabel! @IBOutlet weak var saveBtn: UIButton! var did : String? var filename: String? var lang: String? var translationid: String? var selectedFile: NSDictionary? var textChanged:Bool? @IBOutlet weak var cancelBtn: UIButton! var currentValue: String? @IBOutlet weak var previewView: UIView! var webView: UIWebView? var displayLanguage : String? override func viewDidLoad() { super.viewDidLoad() previewView.isHidden = true if selectedFile?.object(forKey: "translation") as? String != nil { activityView.isHidden = true activityView.stopAnimating() let res = selectedFile!.object(forKey: "translation") as! String self.transcriptionTV.text = res self.filenameLbl.text = self.filename self.outputLbl.text = "Output Language: \(displayLanguage!)" NotificationCenter.default.post(name: Notification.Name("resetTranslation"), object: nil) cancelBtn.isHidden = true saveBtn.setTitle("Done", for: .normal) } else { activityView.startAnimating() getData() } let keyboardDoneButtonView = UIToolbar() keyboardDoneButtonView.sizeToFit() let doneButton = UIBarButtonItem(title: "Done", style: .bordered, target: self, action: #selector(self.doneClicked)) keyboardDoneButtonView.items = [doneButton] transcriptionTV.textContainerInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) transcriptionTV?.inputAccessoryView = keyboardDoneButtonView } func textFieldDidBeginEditing(_ textField: UITextField) { currentValue = textField.text } func textFieldDidEndEditing(_ textField: UITextField, reason: UITextFieldDidEndEditingReason) { if textField.text != currentValue { print("text changed") textChanged = true currentValue = textField.text } } @objc func doneClicked(sender: UIButton!) { self.view.endEditing(true) } @IBAction func updateTranscription(_ sender: Any) { if textChanged == true { updateTranslation() } else { dismiss() } } func getData() { print("getData") let dataString = "translationData" let urlString = "\(appDelegate.serverDestination!)getTranslationJSON.php" let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" translationid = selectedFile?.object(forKey: "translationid") as? String lang = selectedFile?.object(forKey: "language") as? String let paramString = "did=\(did!)&lang=\(lang!)&translationid=\(translationid!)&mobile=true&devStatus=\(appDelegate.devStage!)" print("urlString: \(urlString)") print("paramString: \(paramString)") request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let session = URLSession.shared session.dataTask(with: request) {data, response, err in do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary print("translation jsonResult: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary if dataDict[dataString]! is NSNull { print("no data") DispatchQueue.main.sync(execute: { //self.noResultsMain.isHidden = false }) //self.statusLbl.isHidden = false } else { let uploadData = dataDict[dataString] as! NSDictionary var res = uploadData.object(forKey: "translation") as! String self.displayLanguage = uploadData.object(forKey: "displayLanguage") as? String res = res.replacingOccurrences(of: "\\'", with: "'") DispatchQueue.main.sync(execute: { self.activityView.isHidden = true self.activityView.stopAnimating() self.transcriptionTV.text = res self.filenameLbl.text = self.filename self.outputLbl.text = "Output Language: \(self.displayLanguage!)" }) } } catch let err as NSError { print("error: \(err.description)") } }.resume() } func updateTranslation() { print("getData") let dataString = "translationData" let urlString = "\(appDelegate.serverDestination!)update-translation.php" let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" translationid = selectedFile?.object(forKey: "translationid") as? String let paramString = "translation=\(transcriptionTV.text!)&translationid=\(translationid!)&mobile=true&devStatus=\(appDelegate.devStage!)" print("urlString: \(urlString)") print("paramString: \(paramString)") request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let session = URLSession.shared session.dataTask(with: request) {data, response, err in do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary print("translation jsonResult: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary if dataDict[dataString]! is NSNull { print("no data") DispatchQueue.main.sync(execute: { //self.noResultsMain.isHidden = false }) //self.statusLbl.isHidden = false } else { let uploadData = dataDict[dataString] as! NSDictionary let status = uploadData.object(forKey: "status") as! String DispatchQueue.main.sync(execute: { if status == "Translation updated successfully" { let alert = UIAlertController(title: nil, message: status, preferredStyle: UIAlertControllerStyle.alert) self.present(alert, animated: true, completion: nil) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in switch action.style{ case .default: print("default") self.dismiss() case .cancel: print("cancel") case .destructive: print("destructive") } })) } }) } } catch let err as NSError { print("error: \(err.description)") } }.resume() } func createDoc() { print("createDoc") let dataString = "docData" let urlString = "\(appDelegate.serverDestination!)phpword/createDocJSON.php" let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" let str = filename?.split(separator: ".") let paramString = "filename=\(str![0])&lang=\(displayLanguage!)&input=\(transcriptionTV.text!)&mobile=true&devStatus=\(appDelegate.devStage!)" print("urlString: \(urlString)") print("paramString: \(paramString)") request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let session = URLSession.shared session.dataTask(with: request) {data, response, err in do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary print("docx jsonResult: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary if dataDict[dataString]! is NSNull { print("no data") DispatchQueue.main.sync(execute: { }) //self.statusLbl.isHidden = false } else { let uploadData = dataDict[dataString]! as! NSDictionary if (uploadData != nil) { //let list = uploadData as! NSMutableArray let status = uploadData.object(forKey: "status") as! String DispatchQueue.main.sync(execute: { self.activityView.isHidden = true self.activityView.stopAnimating() if status == "docx created successfully" { //download file let utilityQueue = DispatchQueue.global(qos: .utility) Alamofire.download("\(self.appDelegate.serverDestination!)\(self.filename!).docx") .downloadProgress(queue: utilityQueue) { progress in print("Download Progress: \(progress.fractionCompleted)") if(progress.fractionCompleted == 1.0) { print("done") DispatchQueue.main.sync(execute: { let appName = "ms-word" let appScheme = "/(appName)://app" //let appUrl = URL(string: appScheme) let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] //let url : NSString = "ms-word:ofv|u|https://www.dropbox.com/s/xxxxxx/new.docx?dl=0|p|xxxxxx|z|yes|a|App" as NSString let url : NSString = "\(appName):ofe|u|\(documentsPath)/\(self.filename!).docx|z|yes|a|App" as NSString let urlStr : NSString = url.addingPercentEscapes(using: String.Encoding.utf8.rawValue)! as NSString let searchURL : NSURL = NSURL(string: urlStr as String)! //UIApplication.shared.openURL(searchURL as URL) //if UIApplication.shared.canOpenURL(appUrl! as URL) if UIApplication.shared.canOpenURL(searchURL as URL) { print("App installed") UIApplication.shared.open(searchURL as URL) } else { print("App not installed") let alert = UIAlertController(title: nil, message: "You currently don't have an app installed to open Word files.", preferredStyle: UIAlertControllerStyle.alert) self.present(alert, animated: true, completion: nil) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in switch action.style{ case .default: print("default") case .cancel: print("cancel") case .destructive: print("destructive") } })) } }) } } .responseData { response in if let data = response.result.value { print("data: \(data)") } } } }) } else { DispatchQueue.main.sync(execute: { //self.noResultsMain.isHidden = false }) } } } catch let err as NSError { print("error: \(err.description)") } }.resume() //https://stackoverflow.com/questions/46251025/how-to-edit-and-save-microsoft-word-document-in-ios-stored-in-local-directory //https://docs.microsoft.com/en-us/office/client-developer/office-uri-schemes // } // MARK: File management func createPDF() { let html = "<b>\(self.filename!)</i></b><p>\(displayLanguage!)</p> <p>\(transcriptionTV.text!)</p>" let fmt = UIMarkupTextPrintFormatter(markupText: html) // 2. Assign print formatter to UIPrintPageRenderer let render = UIPrintPageRenderer() render.addPrintFormatter(fmt, startingAtPageAt: 0) // 3. Assign paperRect and printableRect let page = CGRect(x: 0, y: 0, width: 595.2, height: 841.8) // A4, 72 dpi let printable = page.insetBy(dx: 0, dy: 0) render.setValue(NSValue(cgRect: page), forKey: "paperRect") render.setValue(NSValue(cgRect: printable), forKey: "printableRect") // 4. Create PDF context and draw let pdfData = NSMutableData() UIGraphicsBeginPDFContextToData(pdfData, .zero, nil) for i in 1...render.numberOfPages { UIGraphicsBeginPDFPage(); let bounds = UIGraphicsGetPDFContextBounds() render.drawPage(at: i - 1, in: bounds) } UIGraphicsEndPDFContext(); // 5. Save PDF file let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] pdfData.write(toFile: "\(documentsPath)/\(filename!).pdf", atomically: true) loadPDF(filename: filename!) } func loadPDF(filename: String) { let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] let url = URL(fileURLWithPath: documentsPath, isDirectory: true).appendingPathComponent(filename).appendingPathExtension("pdf") let urlRequest = URLRequest(url: url) webView = UIWebView(frame: CGRect.init(x: 0, y: 55, width: view.frame.width, height: view.frame.height-55)) webView!.delegate = self previewView.addSubview(webView!) previewView.isHidden = false webView!.loadRequest(urlRequest) let alert = UIAlertController(title: nil, message: "PDF successfully saved to your files.", preferredStyle: UIAlertControllerStyle.alert) self.present(alert, animated: true, completion: nil) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in switch action.style{ case .default: print("default") case .cancel: print("cancel") case .destructive: print("destructive") } })) } func createTxt() { var filePath = "" // Fine documents directory on device let dirs : [String] = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.allDomainsMask, true) if dirs.count > 0 { let dir = dirs[0] //documents directory filePath = dir.appending("/" + filename! + ".txt") print("Local path = \(filePath)") } else { print("Could not find local directory to store file") return } // Set the contents let fileContentToWrite = "\(displayLanguage!)\n\n\(transcriptionTV.text!)" do { // Write contents to file try fileContentToWrite.write(toFile: filePath, atomically: false, encoding: String.Encoding.utf8) print("file saved") loadTXT(filename: filename!) let alert = UIAlertController(title: nil, message: "Text file successfully saved to your files.", preferredStyle: UIAlertControllerStyle.alert) self.present(alert, animated: true, completion: nil) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in switch action.style{ case .default: print("default") case .cancel: print("cancel") case .destructive: print("destructive") } })) } catch let error as NSError { print("An error took place: \(error)") } //http://swiftdeveloperblog.com/code-examples/read-and-write-string-into-a-text-file/ } func loadTXT(filename: String) { let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] let url = URL(fileURLWithPath: documentsPath, isDirectory: true).appendingPathComponent(filename).appendingPathExtension("pdf") let urlRequest = URLRequest(url: url) webView = UIWebView(frame: CGRect.init(x: 0, y: 55, width: view.frame.width, height: view.frame.height-55)) webView!.delegate = self previewView.addSubview(webView!) previewView.isHidden = false webView!.loadRequest(urlRequest) } func loadWordFile(file:String) { let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] let url = URL(fileURLWithPath: documentsPath, isDirectory: true).appendingPathComponent(file).appendingPathExtension("docx") let urlRequest = URLRequest(url: url) webView = UIWebView(frame: CGRect.init(x: 0, y: 55, width: view.frame.width, height: view.frame.height-55)) webView!.delegate = self previewView.addSubview(webView!) previewView.isHidden = false webView!.loadRequest(urlRequest) let alert = UIAlertController(title: nil, message: "Word doc successfully saved to your files.", preferredStyle: UIAlertControllerStyle.alert) self.present(alert, animated: true, completion: nil) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in switch action.style{ case .default: print("default") case .cancel: print("cancel") case .destructive: print("destructive") } })) } // MARK: Webview Delegate func webViewDidStartLoad(_ webView: UIWebView) { print("webview start load") } func webViewDidFinishLoad(_ webView: UIWebView) { print("webview finish load") } func webView(_ webView: UIWebView, didFailLoadWithError error: Error) { print("webview fail") } // MARK: Actions @IBAction func closePreview(_ sender: Any) { previewView.isHidden = true } @IBAction func createPDF(_ sender: Any) { createPDF() } @IBAction func createTXT(_ sender: Any) { createTxt() } @IBAction func createDOC(_ sender: Any) { createDoc() } @IBAction func cancel(_ sender: Any) { dismiss() } func dismiss() { self.navigationController?.popViewController(animated: true) self.dismiss(animated: true, completion: nil) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "TranslationOptions" { let destination = segue.destination as! TranslationOptions destination.did = did destination.filename = filename } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ } <file_sep>// // MyFiles.swift // AIScribe // // Created by <NAME> on 5/24/19. // Copyright © 2019 RT. All rights reserved. // import UIKit import Alamofire class MyFiles: BaseViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate { let appDelegate = UIApplication.shared.delegate as! AppDelegate var itemArray = [FileItem]() var currentItemArray = [FileItem]() @IBOutlet weak var search: UISearchBar! @IBOutlet weak var activityView: UIActivityIndicatorView! @IBOutlet weak var activityViewBottom: UIActivityIndicatorView! @IBOutlet weak var menuBtn: UIButton! var did : String? var fileList = NSMutableArray() var selectedFile: FileItem? private let refreshControl = UIRefreshControl() @IBOutlet weak var statusView: UIView! @IBOutlet weak var filesTable: UITableView! override func viewDidLoad() { super.viewDidLoad() search.delegate = self activityViewBottom.isHidden = true let tb : TabController = self.parent as! TabController menuBtn.addTarget(self, action: #selector(tb.onSlideMenuButtonPressed(_:)), for: UIControlEvents.touchUpInside) filesTable.tableFooterView = UIView() filesTable.dataSource = self filesTable.delegate = self statusView.isHidden = true getFiles() activityView.startAnimating() // Do any additional setup after loading the view. refreshControl.addTarget(self, action: #selector(refreshWeekData(_:)), for: .valueChanged) if #available(iOS 10.0, *) { filesTable.refreshControl = refreshControl } else { filesTable.addSubview(refreshControl) } let keyboardDoneButtonView = UIToolbar() keyboardDoneButtonView.sizeToFit() let doneButton = UIBarButtonItem(title: "Done", style: .bordered, target: self, action: #selector(self.doneClicked)) keyboardDoneButtonView.items = [doneButton] search?.inputAccessoryView = keyboardDoneButtonView NotificationCenter.default.addObserver( self, selector: #selector(refreshFilesNotification), name: NSNotification.Name(rawValue: "refreshFiles"), object: nil) NotificationCenter.default.addObserver( self, selector: #selector(transcriptionStartedNotification), name: NSNotification.Name(rawValue: "transcriptionStarted"), object: nil) } override func viewDidAppear(_ animated: Bool) { UIApplication.shared.applicationIconBadgeNumber = 0 } func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { currentItemArray = itemArray.filter({ item -> Bool in switch searchBar.selectedScopeButtonIndex { case 0: if searchText.isEmpty { return true } return item.filename.lowercased().contains(searchText.lowercased()) || item.status.lowercased().contains(searchText.lowercased()) default: return false } }) filesTable.reloadData() } @objc func doneClicked(sender: UIButton!) { self.view.endEditing(true) } @objc private func refreshWeekData(_ sender: Any) { refreshFiles() } func refreshFiles() { itemArray.removeAll() getFiles() } @objc func transcriptionStartedNotification (notification: NSNotification) { let dict = notification.object as! NSDictionary fileList.add(dict) filesTable.reloadData() //NotificationCenter.default.post(name: Notification.Name("resetTranscription"), object: nil) startProcessing(dict: dict) } @objc func refreshFilesNotification (notification: NSNotification) { print("refreshFilesNotification") refreshFiles() } func startProcessing (dict:NSDictionary) { print("startProcessing") activityViewBottom.startAnimating() activityViewBottom.isHidden = false let dataString = "transcribeData" let urlString = "\(appDelegate.serverDestination!)IBM-speech-to-text.php" let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" let filename = dict.object(forKey: "filename") as? String let did = dict.object(forKey: "did") as? String let paramString = "uid=\(appDelegate.userid!)&filename=\(filename!)&did=\(did!)&mobile=true&devStatus=\(appDelegate.devStage!)" print("urlString: \(urlString)") print("paramString: \(paramString)") request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let session = URLSession.shared session.dataTask(with: request) {data, response, err in do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary print("transcribe jsonResult: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary if dataDict[dataString]! is NSNull { print("no data") DispatchQueue.main.sync(execute: { self.activityViewBottom.isHidden = true self.activityViewBottom.stopAnimating() self.showBasicAlert(string: "Transcription unsuccessful") //self.noResultsMain.isHidden = false }) //self.statusLbl.isHidden = false } else { let uploadData = dataDict[dataString]! as! NSDictionary if (uploadData != nil) { let status = uploadData.object(forKey: "status") as! String print("status: \(status)") DispatchQueue.main.sync(execute: { self.activityViewBottom.isHidden = true self.activityViewBottom.stopAnimating() if status.contains("transcription completed") { self.refreshFiles() NotificationCenter.default.post(name: Notification.Name("resetTranscription"), object: nil) } else { self.showBasicAlert(string: status) } }) } else { DispatchQueue.main.sync(execute: { //self.noResultsMain.isHidden = false self.activityViewBottom.isHidden = true self.activityViewBottom.stopAnimating() self.showBasicAlert(string: "Transcription unsuccessful") }) } } } catch let err as NSError { print("error: \(err.description)") } }.resume() } func showBasicAlert(string:String) { let alert = UIAlertController(title: nil, message: string, preferredStyle: UIAlertControllerStyle.alert) self.present(alert, animated: true, completion: nil) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in switch action.style { case .default: print("default") case .cancel: print("cancel") case .destructive: print("destructive") } })) } func getFiles() { print("getFiles") let dataString = "filesData" let urlString = "\(appDelegate.serverDestination!)getFilesJSON.php" let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" let paramString = "uid=\(appDelegate.userid!)&mobile=true&devStatus=\(appDelegate.devStage!)" print("urlString: \(urlString)") print("paramString: \(paramString)") request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let session = URLSession.shared session.dataTask(with: request) {data, response, err in do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary print("files jsonResult: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary if dataDict[dataString]! is NSNull { print("no data") DispatchQueue.main.sync(execute: { self.statusView.isHidden = false self.activityView.isHidden = true self.activityView.stopAnimating() self.refreshControl.endRefreshing() //self.noResultsMain.isHidden = false }) } else { let uploadData : NSMutableArray = (dataDict[dataString]! as! NSArray).mutableCopy() as! NSMutableArray if (uploadData.count > 0) { for ob in uploadData { let dict = ob as! NSDictionary self.itemArray.append(FileItem(filename: dict.object(forKey: "filename") as! String, status: dict.object(forKey: "status") as! String, did: dict.object(forKey: "did") as! String, date: dict.object(forKey: "datecreated") as! String)) } self.currentItemArray = self.itemArray DispatchQueue.main.sync(execute: { self.activityView.isHidden = true self.activityView.stopAnimating() self.filesTable.reloadData() self.refreshControl.endRefreshing() }) } else { DispatchQueue.main.sync(execute: { self.refreshControl.endRefreshing() //self.noResultsMain.isHidden = false }) } } } catch let err as NSError { print("error: \(err.description)") } }.resume() } // MARK: Tableview func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 44 } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = Bundle.main.loadNibNamed("FileHeaderCell", owner: self, options: nil)?.first as! FileHeaderCell headerView.headerLbl.text = "MY FILES" headerView.headerLbl.textColor = appDelegate.gray51 let font1 = UIFont.init(name: "Avenir-Heavy", size: 16.0) headerView.headerLbl.font = font1 headerView.leadingWidth.constant = 20 return headerView } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // let dict = fileList[(indexPath as NSIndexPath).row] as! NSDictionary // // did = dict.object(forKey: "did") as! String selectedFile = currentItemArray[indexPath.row] did = selectedFile?.did self.performSegue(withIdentifier: "EditTranscription", sender: self) } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 90 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.currentItemArray.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell")! if currentItemArray.count > 0 { let dict = currentItemArray[(indexPath as NSIndexPath).row] cell.selectionStyle = .none let v0 = cell.viewWithTag(1) as! UILabel let v1 = cell.viewWithTag(2) as! UILabel let v2 = cell.viewWithTag(3) as! UIButton //let v3 = cell.viewWithTag(4) as! UIButton let v4 = cell.viewWithTag(5) as! UILabel v0.text = dict.filename v1.text = dict.status v4.text = dict.date // let transcription = dict.object(forKey: "transcription") as? String // let translations = dict.object(forKey: "translations") as? String // //v2.setTitle(transcription, for: .normal) //v3.setTitle(translations, for: .normal) // if translations == "create" // { // v3.addTarget(self, action: #selector(self.createTranslation(_:)), for: UIControlEvents.touchUpInside) // } // else // { // v3.addTarget(self, action: #selector(self.viewTranslations(_:)), for: UIControlEvents.touchUpInside) // } v2.restorationIdentifier = "\(indexPath.row)" //v3.restorationIdentifier = "\(indexPath.row)" } return cell } @IBAction func viewTranscription(_ sender: Any) { let btn = sender as! UIButton let ind = Int(btn.restorationIdentifier!) selectedFile = currentItemArray[ind!] did = selectedFile?.did self.performSegue(withIdentifier: "EditTranscription", sender: self) } @IBAction func createTranslation(_ sender: Any) { let btn = sender as! UIButton let ind = Int(btn.restorationIdentifier!) selectedFile = currentItemArray[ind!] did = selectedFile?.did self.performSegue(withIdentifier: "CreateTranslation", sender: self) } @IBAction func viewTranslations(_ sender: Any) { let btn = sender as! UIButton let ind = Int(btn.restorationIdentifier!) selectedFile = currentItemArray[ind!] did = selectedFile?.did self.performSegue(withIdentifier: "ViewTranslations", sender: self) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "EditTranscription" { let destination = segue.destination as! TranscriptionResult destination.did = did } else if segue.identifier == "ViewTranslations" { let destination = segue.destination as! DocumentTranslations destination.did = did destination.filename = selectedFile?.filename } } } class FileItem { let filename: String let status: String let did: String let date: String init(filename: String, status: String, did: String, date: String) { self.filename = filename self.status = status self.did = did self.date = date } } <file_sep>// // Feedback.swift // AIScribe // // Created by <NAME> on 3/9/19. // Copyright © 2019 RT. All rights reserved. // import UIKit class Feedback: UIViewController, UITextViewDelegate { let appDelegate = UIApplication.shared.delegate as! AppDelegate @IBOutlet weak var activityView: UIActivityIndicatorView! @IBOutlet weak var textTV: UITextView! @IBOutlet weak var submitBtn: UIButton! override func viewDidLoad() { super.viewDidLoad() activityView.isHidden = true textTV.delegate = self textTV.text = "Please give us your feedback" // Do any additional setup after loading the view. let keyboardDoneButtonView = UIToolbar() keyboardDoneButtonView.sizeToFit() let doneButton = UIBarButtonItem(title: "Done", style: .bordered, target: self, action: #selector(self.doneClicked)) keyboardDoneButtonView.items = [doneButton] textTV?.inputAccessoryView = keyboardDoneButtonView textTV?.textContainerInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) //debug() } func sendFeedback() { self.view.endEditing(true) submitBtn.isEnabled = false submitBtn.backgroundColor = appDelegate.crWarmGray activityView.isHidden = false activityView.startAnimating() print("sendFeedback") let urlString = "\(appDelegate.serverDestination!)addFeedback.php" print("urlString: \(urlString)") let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" let paramString = "feedback=\(textTV.text!)&uid=\(appDelegate.userid!)&devStatus=\(appDelegate.devStage!)&mobile=true" print("paramString: \(paramString)") request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let session = URLSession.shared session.dataTask(with: request) {data, response, err in do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary print("add user jsonResult: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary if dataDict["feedbackData"]! is NSNull { print("no data") self.activityView.isHidden = true self.activityView.stopAnimating() self.submitBtn.isEnabled = true self.submitBtn.alpha = 1 } else { let userDict : NSDictionary = dataDict["feedbackData"] as! NSDictionary let status : String = userDict["status"] as! String print("status: \(status)") if (status == "feedback saved") { DispatchQueue.main.sync(execute: { self.activityView.isHidden = true self.activityView.stopAnimating() // self.submitBtn.isEnabled = true // self.submitBtn.alpha = 1 let alert = UIAlertController(title: nil, message: "Thank you for your feedback!", preferredStyle: UIAlertControllerStyle.alert) self.present(alert, animated: true, completion: nil) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in switch action.style{ case .default: self.dismiss() case .cancel: print("cancel") case .destructive: print("destructive") } })) }) } else { DispatchQueue.main.sync(execute: { self.activityView.isHidden = true self.activityView.stopAnimating() self.submitBtn.isEnabled = true self.submitBtn.alpha = 1 }) } } } catch let err as NSError { print("error: \(err.description)") } }.resume() } func dismiss() { self.navigationController?.popViewController(animated: true) dismiss(animated: true, completion: nil) } @objc func doneClicked(sender: UIButton!) { self.view.endEditing(true) if textTV.text != "" { submitBtn.isEnabled = true submitBtn.backgroundColor = appDelegate.crLightBlue } } func textViewDidBeginEditing(_ textView: UITextView) { if textView.text == "Please give us your feedback" { textView.text = "" } } func textViewDidEndEditing(_ textView: UITextView) { if textView.text == "" { textView.text = "Please give us your feedback" } } @IBAction func submit() { if textTV.text != "" && textTV.text != "Please give us your feedback" { sendFeedback() } else { showBasicAlert(string: "Please enter feedback") } } @IBAction func cancel() { self.navigationController?.popViewController(animated: true) self.dismiss(animated: true, completion: nil) } func showBasicAlert(string:String) { let alert = UIAlertController(title: nil, message: string, preferredStyle: UIAlertControllerStyle.alert) self.present(alert, animated: true, completion: nil) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in switch action.style { case .default: print("default") case .cancel: print("cancel") case .destructive: print("destructive") } })) } } <file_sep>// // EditCorpus.swift // AIScribe // // Created by <NAME> on 6/27/19. // Copyright © 2019 RT. All rights reserved. // import UIKit class EditCorpus: UIViewController, UITextViewDelegate { let appDelegate = UIApplication.shared.delegate as! AppDelegate @IBOutlet weak var activityView: UIActivityIndicatorView! var selectedCorpus : CorpusItem? @IBOutlet weak var transcriptionTV: UITextView! @IBOutlet weak var saveBtn: UIButton! @IBOutlet weak var modelNameTxt: UITextField! @IBOutlet weak var headerLbl: UILabel! @IBOutlet weak var modelNameLbl: UILabel! @IBOutlet weak var modelLblHeight: NSLayoutConstraint! @IBOutlet weak var statusTxt: UITextField! var status : String? @IBOutlet weak var infoIcon: UIButton! var statusTimer : Timer? var refreshCount : Int = 0 var timerStarted : Bool? override func viewDidLoad() { super.viewDidLoad() infoIcon.isHidden = true activityView.isHidden = true modelNameTxt.isEnabled = false modelNameTxt.text = selectedCorpus?.filename transcriptionTV.text = selectedCorpus?.content transcriptionTV.delegate = self transcriptionTV.textContainerInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) let keyboardDoneButtonView = UIToolbar() keyboardDoneButtonView.sizeToFit() let doneButton = UIBarButtonItem(title: "Done", style: .bordered, target: self, action: #selector(self.doneClicked)) keyboardDoneButtonView.items = [doneButton] transcriptionTV?.inputAccessoryView = keyboardDoneButtonView getCorpusInfo() } override func viewDidLayoutSubviews() { transcriptionTV?.scrollRangeToVisible(NSMakeRange(0, 0)) } @objc func doneClicked(sender: UIButton!) { dismissKeyboard() } func dismissKeyboard () { self.view.endEditing(true) } // MARK: Webservice func getCorpusInfo() { print("getCorpusInfo") let dataString = "corpusData" let urlString = "\(appDelegate.serverDestination!)IBM-corpus-info.php" let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" let paramString = "uid=\(appDelegate.userid!)&cid=\(selectedCorpus!.cid)&mobile=true&devStatus=\(appDelegate.devStage!)" print("urlString: \(urlString)") print("paramString: \(paramString)") request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let session = URLSession.shared session.dataTask(with: request) {data, response, err in do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary print("corpus info jsonResult: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary if dataDict[dataString]! is NSNull { print("no data") DispatchQueue.main.sync(execute: { self.showBasicAlert(string: "Error retreiving corpus info.") //self.noResultsMain.isHidden = false }) } else { let uploadData = dataDict[dataString]! as! NSDictionary if (uploadData != nil) { //self.status = uploadData.object(forKey: "status") as? String DispatchQueue.main.sync(execute: { self.status = uploadData.object(forKey: "status") as? String self.infoIcon.isHidden = false if (self.status == "being_processed") { //start status refresh timer if self.timerStarted != true { self.statusTimer = Timer.scheduledTimer(timeInterval: 10.0, target: self, selector: #selector(self.refreshStatus), userInfo: nil, repeats: true) self.timerStarted = true } } else { print("stop refresh timer") self.statusTimer?.invalidate() self.timerStarted = false NotificationCenter.default.post(name: Notification.Name("refreshCorpora"), object: nil) } var displayText = "" if self.status == "analyzed" { displayText = "Analyzed" } else if self.status == "being_processed" { displayText = "Being processed" } else { displayText = "Undetermined" } self.infoIcon.isHidden = false self.statusTxt.text = displayText }) } else { DispatchQueue.main.sync(execute: { //self.noResultsMain.isHidden = false self.showBasicAlert(string: "Error retreiving corpus info.") }) } } } catch let err as NSError { print("error: \(err.description)") } }.resume() } @objc func refreshStatus () { refreshCount += 1 if refreshCount <= 20 { getCorpusInfo() } else { statusTimer?.invalidate() timerStarted = false } } func showBasicAlert(string:String) { let alert = UIAlertController(title: nil, message: string, preferredStyle: UIAlertControllerStyle.alert) self.present(alert, animated: true, completion: nil) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in switch action.style { case .default: print("default") case .cancel: print("cancel") case .destructive: print("destructive") } })) } func updateCorpus () { print("updateCorpus") let dataString = "corpusData" let urlString = "\(appDelegate.serverDestination!)IBM-create-corpus.php" let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" let paramString = "uid=\(appDelegate.userid!)&filename=\(selectedCorpus!.filename)&cpid=\(selectedCorpus!.cpid)&cid=\(selectedCorpus!.cid)&content=\(transcriptionTV.text!)&mobile=true&devStatus=\(appDelegate.devStage!)" print("urlString: \(urlString)") print("paramString: \(paramString)") request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let session = URLSession.shared session.dataTask(with: request) {data, response, err in do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary print("corpus update jsonResult: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary if dataDict[dataString]! is NSNull { print("no data") DispatchQueue.main.sync(execute: { self.activityView.isHidden = true self.activityView.stopAnimating() //self.noResultsMain.isHidden = false }) //self.statusLbl.isHidden = false } else { let uploadData = dataDict[dataString]! as! NSDictionary if (uploadData != nil) { let status = uploadData.object(forKey: "status") as! String print("status: \(status)") DispatchQueue.main.sync(execute: { if status == "corpus updated successfully" { //self.refreshFiles() self.activityView.isHidden = true self.activityView.stopAnimating() NotificationCenter.default.post(name: Notification.Name("refreshCorpora"), object: nil) let alert = UIAlertController(title: "Corpus Updated Sucessfully", message: "Custom model \(self.selectedCorpus!.modelname) needs to be retrained after new corpus data is analyzed.", preferredStyle: UIAlertControllerStyle.alert) self.present(alert, animated: true, completion: nil) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in switch action.style{ case .default: print("default") self.dismiss() case .cancel: print("cancel") case .destructive: print("destructive") } })) } else { self.saveBtn.isEnabled = true self.activityView.isHidden = true self.activityView.stopAnimating() let alert = UIAlertController(title: "Upload Error", message: status, preferredStyle: UIAlertControllerStyle.alert) self.present(alert, animated: true, completion: nil) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in switch action.style{ case .default: print("default") case .cancel: print("cancel") case .destructive: print("destructive") } })) } }) } else { DispatchQueue.main.sync(execute: { self.activityView.isHidden = true self.activityView.stopAnimating() //self.noResultsMain.isHidden = false }) } } } catch let err as NSError { print("error: \(err.description)") } }.resume() } func updateCorpus1 () { print("updateCorpus") let dataString = "corpusData" let urlString = "\(appDelegate.serverDestination!)IBM-update-corpus.php" let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" let paramString = "uid=\(appDelegate.userid!)&filename=\(selectedCorpus!.filename)&cpid=\(selectedCorpus!.cpid)&content=\(transcriptionTV.text!)&mobile=true&devStatus=\(appDelegate.devStage!)" print("urlString: \(urlString)") print("paramString: \(paramString)") request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let session = URLSession.shared session.dataTask(with: request) {data, response, err in do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary print("corpus update jsonResult: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary if dataDict[dataString]! is NSNull { print("no data") DispatchQueue.main.sync(execute: { self.activityView.isHidden = true self.activityView.stopAnimating() //self.noResultsMain.isHidden = false }) //self.statusLbl.isHidden = false } else { let uploadData = dataDict[dataString]! as! NSDictionary if (uploadData != nil) { let status = uploadData.object(forKey: "status") as! String print("status: \(status)") DispatchQueue.main.sync(execute: { if status == "corpus update successful" { //self.refreshFiles() self.activityView.isHidden = true self.activityView.stopAnimating() NotificationCenter.default.post(name: Notification.Name("refreshCorpora"), object: nil) let alert = UIAlertController(title: nil, message: "Corpus Updated Sucessfully", preferredStyle: UIAlertControllerStyle.alert) self.present(alert, animated: true, completion: nil) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in switch action.style{ case .default: print("default") self.dismiss() case .cancel: print("cancel") case .destructive: print("destructive") } })) } else { self.saveBtn.isEnabled = true self.activityView.isHidden = true self.activityView.stopAnimating() let alert = UIAlertController(title: "Upload Error", message: status, preferredStyle: UIAlertControllerStyle.alert) self.present(alert, animated: true, completion: nil) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in switch action.style{ case .default: print("default") case .cancel: print("cancel") case .destructive: print("destructive") } })) } }) } else { DispatchQueue.main.sync(execute: { self.activityView.isHidden = true self.activityView.stopAnimating() //self.noResultsMain.isHidden = false }) } } } catch let err as NSError { print("error: \(err.description)") } }.resume() } func textViewDidEndEditing(_ textView: UITextView) { validateForm() } func validateForm() { if transcriptionTV.text != "" { saveBtn.backgroundColor = appDelegate.crLightBlue saveBtn.isEnabled = true } else { saveBtn.backgroundColor = appDelegate.gray74 saveBtn.isEnabled = false } } @IBAction func showStatusInfo(_ sender: Any) { if (status == "being_processed") { status = "Being Processed indicates that the service is still analyzing the corpus. The service cannot accept requests to add new corpora or words, or to train the custom model, until its analysis is complete." } else if (status == "undetermined") { status = "Undetermined indicates that the service encountered an error while processing the corpus. The information that is returned for the corpus includes an error message that offers guidance for correcting the error." } else { status = "Analyzed indicates that the service successfully analyzed the corpus. The custom model can be trained with data from the corpus." } let alert = UIAlertController(title: nil, message: status, preferredStyle: UIAlertControllerStyle.alert) self.present(alert, animated: true, completion: nil) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in switch action.style{ case .default: print("default") case .cancel: print("cancel") case .destructive: print("destructive") } })) } @IBAction func updateFile(_ sender: Any) { saveBtn.backgroundColor = appDelegate.gray74 saveBtn.isEnabled = false activityView.isHidden = false activityView.startAnimating() updateCorpus() } @IBAction func cancel(_ sender: Any) { dismissKeyboard() dismiss() } func dismiss() { self.navigationController?.popViewController(animated: true) self.dismiss(animated: true, completion: nil) } } extension String { func capitalizingFirstLetter() -> String { return prefix(1).capitalized + dropFirst() } mutating func capitalizeFirstLetter() { self = self.capitalizingFirstLetter() } } <file_sep>// // EditProfile.swift // AIScribe // // Created by <NAME> on 11/6/18. // Copyright © 2018 RT. All rights reserved. // import UIKit import AWSS3 class EditProfile: BaseViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate { let appDelegate = UIApplication.shared.delegate as! AppDelegate let prefs = UserDefaults.standard @IBOutlet weak var activityView: UIActivityIndicatorView! @IBOutlet weak var submitBtn: UIButton! @IBOutlet weak var backBtn: UIButton! @IBOutlet weak var instructionsLbl: UILabel! @IBOutlet weak var usernameLbl: UILabel! @IBOutlet weak var usernameTxt: UITextField! @IBOutlet weak var creditsLbl: UILabel! @IBOutlet weak var passwordLbl: UILabel! @IBOutlet weak var passwordTxt: UITextField! @IBOutlet weak var firstnameLbl: UILabel! @IBOutlet weak var lastnameLbl: UILabel! @IBOutlet weak var firstnameTxt: UITextField! @IBOutlet weak var lastnameTxt: UITextField! @IBOutlet weak var emailLbl: UILabel! @IBOutlet weak var emailTxt: UITextField! @IBOutlet weak var dobTxtTopPadding: NSLayoutConstraint! @IBOutlet weak var fullnameTxtTopPadding: NSLayoutConstraint! @IBOutlet weak var lastnameTopPadding: NSLayoutConstraint! @IBOutlet weak var firstnameTopPadding: NSLayoutConstraint! @IBOutlet weak var imageIV : UIImageView! var selectedDate : String? var imagePicker : UIImagePickerController! var selectedImage : UIImage? var statusImageCache = [String:UIImage]() var inviteList : String? var uploadImageName : String? @IBOutlet weak var profileBtn: UIButton! var validateFields : [UITextField]? @IBOutlet weak var contentSV: UIScrollView! override func viewDidLoad() { super.viewDidLoad() activityView.isHidden = true dobTxtTopPadding.constant = 0 validateFields = [firstnameTxt,lastnameTxt, emailTxt, passwordTxt,usernameTxt] // if appDelegate.userImage != nil // { // profileBtn.setBackgroundImage(appDelegate.userImage, for: .normal) // } // else if appDelegate.profileImg != "" // { // downloadImage(imagename: appDelegate.profileImg!) // } creditsLbl.text = "$\(self.appDelegate.credits!)" getProfileInfo() //years in days * seconds in a day //let d = Date(timeInterval: -6570*86400, since: NSDate() as Date) //dobPicker.setDate(NSDate() as Date, animated: false) usernameLbl.isHidden = false firstnameLbl.isHidden = true lastnameLbl.isHidden = true emailLbl.isHidden = true passwordLbl.isHidden = true usernameTxt.isUserInteractionEnabled = false // let v = UIView.init(frame: CGRect.init(x: 0, y: profileBtn.frame.height-25, width: 300, height: 50)) // v.backgroundColor = .white // v.isUserInteractionEnabled = false // // profileBtn.addSubview(v) // let attributedString = NSMutableAttributedString(string: "* You can change this from your Account Settings", attributes: [ // .font: UIFont(name: "Avenir-Book", size: 12.0)!, // .foregroundColor: appDelegate.crWarmGray // ]) // attributedString.addAttribute(.font, value: UIFont(name: "Avenir-Heavy", size: 12.0)!, range: NSRange(location: 32, length: 16)) //instructionsLbl.attributedText = attributedString let btnItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.done, target: self, action: #selector(dismissKeyboard)) let numberToolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 50)) numberToolbar.backgroundColor = UIColor.darkGray numberToolbar.barStyle = UIBarStyle.default numberToolbar.tintColor = UIColor.black numberToolbar.items = [ UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil), btnItem] numberToolbar.sizeToFit() emailTxt.inputAccessoryView = numberToolbar passwordTxt.inputAccessoryView = numberToolbar usernameTxt.inputAccessoryView = numberToolbar firstnameTxt.inputAccessoryView = numberToolbar lastnameTxt.inputAccessoryView = numberToolbar NotificationCenter.default.addObserver( self, selector: #selector(updateCreditsNotification), name: NSNotification.Name(rawValue: "updateCredits"), object: nil) } @objc func updateCreditsNotification (notification: NSNotification) { let credits = notification.object as! String creditsLbl.text = "$\(credits)" contentSV.scrollRectToVisible(CGRect.init(x: 0, y: lastnameTxt.frame.origin.y, width: contentSV.frame.width, height: contentSV.frame.height), animated: false) } override func viewDidLayoutSubviews() { contentSV.contentSize = CGSize.init(width: contentSV.frame.width, height: 1000) } @objc func dismissKeyboard () { self.view.endEditing(true) } // MARK: Actions @IBAction func goBack(_ sender: Any) { self.navigationController?.popViewController(animated: true) dismiss(animated: true, completion: nil) } @IBAction func saveInfo(_ sender: Any) { for field in validateFields! { if field.text == "" { self.showBasicAlert(string: "Please enter \(field.restorationIdentifier)") return } } self.uploadUserData() } func showBasicAlert(string:String) { let alert = UIAlertController(title: nil, message: string, preferredStyle: UIAlertControllerStyle.alert) self.present(alert, animated: true, completion: nil) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in switch action.style { case .default: print("default") case .cancel: print("cancel") case .destructive: print("destructive") } })) } @IBAction func selectPhoto(_ sender: Any) { let alert = UIAlertController(title: nil, message: "Change your profile picture", preferredStyle: UIAlertControllerStyle.alert) self.present(alert, animated: true, completion: nil) alert.addAction(UIAlertAction(title: "Open Photo Library", style: .default, handler: { action in switch action.style{ case .default: print("default") self.choosePhoto() case .cancel: print("cancel") case .destructive: print("destructive") } })) alert.addAction(UIAlertAction(title: "Take a Photo", style: .default, handler: { action in switch action.style{ case .default: print("default") self.takePhoto() case .cancel: print("cancel") case .destructive: print("destructive") } })) alert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { action in switch action.style{ case .default: print("default") case .cancel: print("cancel") case .destructive: print("destructive") } })) } // MARK: Image Picker func takePhoto () { if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) { imagePicker = UIImagePickerController() imagePicker.delegate = self as? UIImagePickerControllerDelegate & UINavigationControllerDelegate imagePicker.sourceType = UIImagePickerControllerSourceType.camera; imagePicker.allowsEditing = false self.present(imagePicker, animated: true, completion: nil) } } func choosePhoto () { if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary) { imagePicker = UIImagePickerController() imagePicker.delegate = self as? UIImagePickerControllerDelegate & UINavigationControllerDelegate imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary; imagePicker.allowsEditing = true self.present(imagePicker, animated: true, completion: nil) } } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { print("cancel") } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { print("did pick") selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage imageIV.image = selectedImage self.dismiss(animated: true, completion: { self.uploadS3() //self.uploadToServer(name:"registration-\(self.appDelegate.userid!)") }); } // MARK: Web service func uploadS3 () { if appDelegate.profileImg == "" { uploadImageName = "\(appDelegate.randomString(length: 10)).jpeg" } else { uploadImageName = appDelegate.profileImg } let image = selectedImage! let fileManager = FileManager.default let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent(uploadImageName!) let imageData = UIImageJPEGRepresentation(image, 0) fileManager.createFile(atPath: path as String, contents: imageData, attributes: nil) let fileUrl = NSURL(fileURLWithPath: path) print("upload") let transferManager = AWSS3TransferManager.default() let uploadRequest = AWSS3TransferManagerUploadRequest() uploadRequest?.bucket = "shotgraph1224/aiscribe" uploadRequest!.key = uploadImageName uploadRequest?.body = fileUrl as URL uploadRequest?.contentType = "image/jpeg" uploadRequest?.acl = AWSS3ObjectCannedACL.publicReadWrite; transferManager.upload(uploadRequest!).continueWith(executor: AWSExecutor.mainThread(), block: { (task:AWSTask<AnyObject>) -> Any? in if let error = task.error as NSError? { if error.domain == AWSS3TransferManagerErrorDomain, let code = AWSS3TransferManagerErrorType(rawValue: error.code) { switch code { case .cancelled, .paused: break default: print("Error uploading 1: \(uploadRequest?.key!) Error: \(error)") } } else { print("Error uploading: \(uploadRequest?.key!) Code: \(error.code) Error: \(error)") } return nil } //let uploadOutput = task.result print("Upload complete for: \(uploadRequest!.key!)") //self.updateUserImage() return nil }) } func getProfileInfo () { print("getProfileInfo") let urlString = "\(appDelegate.serverDestination!)getProfileInfo.php" print("urlString: \(urlString)") let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" let paramString = "uid=\(appDelegate.userid!)&devStatus=\(appDelegate.devStage!)&mobile=true&devStatus=\(appDelegate.devStage!)" print("paramString: \(paramString)") request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let session = URLSession.shared session.dataTask(with: request) {data, response, err in do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary print("profile jsonResult: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary if dataDict["profileData"]! is NSNull { print("no user") } else { let uploadData : NSDictionary = dataDict["profileData"] as! NSDictionary let firstname = uploadData.object(forKey: "firstname") as? String let lastname = uploadData.object(forKey: "lastname") as? String let email = uploadData.object(forKey: "email") as? String let password = uploadData.object(forKey: "password") as? String let username = uploadData.object(forKey: "username") as? String //let credits = uploadData.object(forKey: "credits") as? String DispatchQueue.main.sync(execute: { self.firstnameLbl.isHidden = false self.lastnameLbl.isHidden = false self.emailLbl.isHidden = false self.passwordLbl.isHidden = false self.firstnameTxt.text = "\(firstname!)" self.lastnameTxt.text = "\(lastname!)" self.emailTxt.text = "\(email!)" self.passwordTxt.text = "\(password!)" self.usernameTxt.text = "\(username!)" //self.creditsLbl.text = "$\(self.appDelegate.credits!)" self.emailTxt.text = uploadData.object(forKey: "email") as? String }) } } catch let err as NSError { print("error: \(err.description)") } }.resume() } func updateUserImage () { print("updateUserImage") let urlString = "\(appDelegate.serverDestination!)updateProfileImage.php" print("urlString: \(urlString)") let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" let paramString = "uid=\(appDelegate.userid!)&userimage=\(uploadImageName!)&devStatus=\(appDelegate.devStage!)&mobile=true" print("paramString: \(paramString)") request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let session = URLSession.shared session.dataTask(with: request) {data, response, err in do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary print("image jsonResult: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary if dataDict["userImageData"]! is NSNull { print("no user") } else { let userDict : NSDictionary = dataDict["userImageData"] as! NSDictionary let status : String = userDict["status"] as! String print("status: \(status)") if (status == "profile image saved") { } else { DispatchQueue.main.sync(execute: { self.showBasicAlert(string: "Profile image not saved. Please check your internet connection.") }) } } } catch let err as NSError { print("error: \(err.description)") } }.resume() } func uploadUserData() { submitBtn.isEnabled = false activityView.isHidden = false activityView.startAnimating() print("uploadUserData") let urlString = "\(appDelegate.serverDestination!)updateProfile.php" print("urlString: \(urlString)") let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" var paramString = "firstname=\(firstnameTxt.text!)&lastname=\(lastnameTxt.text!)&email=\(emailTxt.text!)&password=\(<PASSWORD>!)&uid=\(appDelegate.userid!)&devStatus=\(appDelegate.devStage!)&mobile=true" if self.isEditing == true { paramString = "\(paramString)&updating=true" } else { paramString = "\(paramString)&basicprofile=true" } //paramString = "\(paramString)&basicprofile=true" print("paramString: \(paramString)") request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let session = URLSession.shared session.dataTask(with: request) {data, response, err in do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary print("add user jsonResult: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary if dataDict["userData"]! is NSNull { print("no user") } else { let userDict : NSDictionary = dataDict["userData"] as! NSDictionary let status : String = userDict["status"] as! String print("status: \(status)") if (status == "profile updated") { DispatchQueue.main.sync(execute: { self.activityView.isHidden = true self.activityView.stopAnimating() self.appDelegate.firstname = self.firstnameTxt.text! self.appDelegate.lastname = self.lastnameTxt.text! self.appDelegate.email = self.emailTxt.text! self.appDelegate.password = <PASSWORD>! if self.appDelegate.firstname != nil { self.prefs.setValue(self.appDelegate.firstname , forKey: "firstname") } if self.appDelegate.lastname != nil { self.prefs.setValue(self.appDelegate.lastname , forKey: "lastname") } if self.appDelegate.email != nil { self.prefs.setValue(self.appDelegate.email , forKey: "email") } if self.appDelegate.password != nil { self.prefs.setValue(self.appDelegate.password , forKey: "<PASSWORD>") } self.prefs.synchronize() self.showBasicAlert(string: "Profile updated") }) } else { DispatchQueue.main.sync(execute: { self.activityView.isHidden = true self.activityView.stopAnimating() self.submitBtn.isEnabled = true self.submitBtn.alpha = 1 self.showBasicAlert(string: status) }) } } } catch let err as NSError { print("error: \(err.description)") } }.resume() } // MARK: Textfield Delegate func textFieldDidEndEditing(_ textField: UITextField) { if textField.restorationIdentifier == "firstname" && textField.text != "" { firstnameLbl.isHidden = false } else if textField.restorationIdentifier == "lastname" && textField.text != "" { lastnameLbl.isHidden = false dobTxtTopPadding.constant = 5 } } func downloadImage (imagename : String) { if appDelegate.downloadImages == true { let s3BucketName = "shotgraph1224/aiscribe" let downloadFilePath = (NSTemporaryDirectory() as NSString).appendingPathComponent(imagename) let downloadingFileURL = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(imagename) // Set the logging to verbose so we can see in the debug console what is happening //AWSLogger.default().logLevel = .none let downloadRequest = AWSS3TransferManagerDownloadRequest() downloadRequest?.bucket = s3BucketName downloadRequest?.key = imagename downloadRequest?.downloadingFileURL = downloadingFileURL let transferManager = AWSS3TransferManager.default() //[[transferManager download:downloadRequest] continueWithExecutor:[AWSExecutor mainThreadExecutor] withBlock:^id(AWSTask *task) { transferManager.download(downloadRequest!).continueWith(executor: AWSExecutor.mainThread(), block: ({ (task: AWSTask!) -> AWSTask<AnyObject>? in DispatchQueue.main.async(execute: { if task.error != nil { print("AWS Error downloading image") print(task.error.debugDescription) } else { //print("AWS download successful") var downloadOutput = AWSS3TransferManagerDownloadOutput() downloadOutput = task.result! as? AWSS3TransferManagerDownloadOutput print("downloadOutput photo: \(downloadOutput)"); print("downloadFilePath photo: \(downloadFilePath)"); let image = UIImage(contentsOfFile: downloadFilePath) self.imageIV.image = image self.appDelegate.userImage = image } //println("test") }) return nil })) } else { self.imageIV.image = UIImage.init(named: "profile-icon") } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { self.view.endEditing(true) } } extension String { func sqlToDate(withFormat format: String = "yyyy-MM-dd 00:00:00") -> Date { let dateFormatter = DateFormatter() dateFormatter.dateFormat = format guard let date = dateFormatter.date(from: self) else { preconditionFailure("Take a look to your format") } return date } } <file_sep>// // MyCustomModels.swift // AIScribe // // Created by <NAME> on 5/24/19. // Copyright © 2019 RT. All rights reserved. // import UIKit class MyCustomModels: BaseViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate { let appDelegate = UIApplication.shared.delegate as! AppDelegate var itemArray = [ModelItem]() var currentItemArray = [ModelItem]() private let refreshControl = UIRefreshControl() @IBOutlet weak var search: UISearchBar! @IBOutlet weak var activityView: UIActivityIndicatorView! @IBOutlet weak var menuBtn: UIButton! @IBOutlet weak var statusView: UIView! var did : String? var modelList = NSMutableArray() var selectedModel: ModelItem? @IBOutlet weak var modelsTable: UITableView! var initLoaded : Bool? override func viewDidLoad() { super.viewDidLoad() let tb : TabController = self.parent as! TabController menuBtn.addTarget(self, action: #selector(tb.onSlideMenuButtonPressed(_:)), for: UIControlEvents.touchUpInside) self.statusView.isHidden = true modelsTable.tableFooterView = UIView() modelsTable.dataSource = self modelsTable.delegate = self search.delegate = self getModels() activityView.startAnimating() refreshControl.addTarget(self, action: #selector(refreshData(_:)), for: .valueChanged) if #available(iOS 10.0, *) { modelsTable.refreshControl = refreshControl } else { modelsTable.addSubview(refreshControl) } let keyboardDoneButtonView = UIToolbar() keyboardDoneButtonView.sizeToFit() let doneButton = UIBarButtonItem(title: "Done", style: .bordered, target: self, action: #selector(self.doneClicked)) keyboardDoneButtonView.items = [doneButton] search?.inputAccessoryView = keyboardDoneButtonView NotificationCenter.default.addObserver( self, selector: #selector(refreshModelsNotification), name: NSNotification.Name(rawValue: "refreshCustomModels"), object: nil) } override func viewWillAppear(_ animated: Bool) { if initLoaded == true { print("viewWillAppear initLoaded") refreshFiles() } } @objc private func refreshData(_ sender: Any) { refreshFiles() } func refreshFiles() { itemArray.removeAll() getModels() } @objc func doneClicked(sender: UIButton!) { self.view.endEditing(true) } func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { currentItemArray = itemArray.filter({ item -> Bool in switch searchBar.selectedScopeButtonIndex { case 0: if searchText.isEmpty { return true } return item.modelname.lowercased().contains(searchText.lowercased()) || item.modeldescription.lowercased().contains(searchText.lowercased()) || item.basename1.lowercased().contains(searchText.lowercased()) || item.status.lowercased().contains(searchText.lowercased()) default: return false } }) modelsTable.reloadData() } @objc func refreshModelsNotification (notification: NSNotification) { print("refreshModelsNotification") refreshFiles() } func getModels() { print("getModels") let dataString = "modelsData" let urlString = "\(appDelegate.serverDestination!)getModelsJSON.php" let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" let paramString = "uid=\(appDelegate.userid!)&mobile=true&devStatus=\(appDelegate.devStage!)" print("urlString: \(urlString)") print("paramString: \(paramString)") request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let session = URLSession.shared session.dataTask(with: request) {data, response, err in do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary print("files jsonResult: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary if dataDict[dataString]! is NSNull { print("no data") DispatchQueue.main.sync(execute: { self.statusView.isHidden = false self.activityView.isHidden = true self.activityView.stopAnimating() self.refreshControl.endRefreshing() //self.noResultsMain.isHidden = false }) //self.statusLbl.isHidden = false } else { let uploadData : NSMutableArray = (dataDict[dataString]! as! NSArray).mutableCopy() as! NSMutableArray if (uploadData.count > 0) { //let list = uploadData as! NSMutableArray for ob in uploadData { let dict = ob as! NSDictionary self.itemArray.append(ModelItem(modelname: dict.object(forKey: "modelname") as! String, modeldescription: dict.object(forKey: "modeldescription") as! String, basename1: dict.object(forKey: "basename1") as! String, mid: dict.object(forKey: "mid") as! String, cid: dict.object(forKey: "cid") as! String, status: dict.object(forKey: "status") as! String)) } self.currentItemArray = self.itemArray DispatchQueue.main.sync(execute: { self.activityView.isHidden = true self.statusView.isHidden = true self.activityView.stopAnimating() self.modelsTable.reloadData() self.refreshControl.endRefreshing() self.initLoaded = true }) } else { DispatchQueue.main.sync(execute: { self.statusView.isHidden = false self.refreshControl.endRefreshing() //self.noResultsMain.isHidden = false }) } } } catch let err as NSError { print("error: \(err.description)") } }.resume() } // MARK: Tableview func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 44 } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = Bundle.main.loadNibNamed("FileHeaderCell", owner: self, options: nil)?.first as! FileHeaderCell headerView.headerLbl.text = "MY MODELS" headerView.headerLbl.textColor = appDelegate.gray51 let font1 = UIFont.init(name: "Avenir-Heavy", size: 16.0) headerView.headerLbl.font = font1 headerView.leadingWidth.constant = 20 return headerView } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { selectedModel = currentItemArray[indexPath.row] self.performSegue(withIdentifier: "EditModel", sender: self) } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 140 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.currentItemArray.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell")! let dict = currentItemArray[(indexPath as NSIndexPath).row] cell.selectionStyle = .none let v0 = cell.viewWithTag(1) as! UILabel let v1 = cell.viewWithTag(2) as! UILabel let v2 = cell.viewWithTag(3) as! UIButton let v3 = cell.viewWithTag(4) as! UILabel let v4 = cell.viewWithTag(5) as! UILabel //let v3 = cell.viewWithTag(4) as! UIButton //let v4 = cell.viewWithTag(5) as! UILabel v0.text = dict.modelname v1.text = "Description: \(dict.modeldescription)" v3.text = "Language: \(dict.basename1)" v4.text = "Status: \(dict.status)" v2.restorationIdentifier = "\(indexPath.row)" //v3.restorationIdentifier = "\(indexPath.row)" return cell } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "EditModel" { let destination = segue.destination as! EditCustomModel destination.selectedModel = selectedModel } } } class ModelItem { let modelname: String let modeldescription: String let basename1: String let mid: String let cid: String let status: String init(modelname: String, modeldescription: String, basename1: String, mid: String, cid: String, status: String) { self.modelname = modelname self.modeldescription = modeldescription self.basename1 = basename1 self.mid = mid self.cid = cid self.status = status } } <file_sep>// // CuisinesCollectionviewCell.swift // AIScribe // // Created by <NAME> on 5/19/18. // Copyright © 2018 RT. All rights reserved. // import UIKit class CuisinesCollectionviewCell: UICollectionViewCell { //@IBOutlet weak var cuisineBtn: UIButton! @IBOutlet weak var cuisineLbl: UILabel! @IBOutlet weak var iconIV: UIImageView! } <file_sep>// // RecipeView.swift // AIScribe // // Created by <NAME> on 5/20/18. // Copyright © 2018 RT. All rights reserved. // import UIKit class RecipeView: UIView { @IBOutlet weak var recipeIV: UIImageView! @IBOutlet weak var starsIV: UIImageView! @IBOutlet weak var headerLbl: UILabel! @IBOutlet weak var infoLbl: UILabel! @IBOutlet weak var sourceLbl: UILabel! @IBOutlet weak var favoriteBtn: UIButton! var isFavorite : Bool? // class func instanceFromNib() -> UIView { // return UINib(nibName: "RecipeView", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! UIView // } class func createMyClassView() -> RecipeView { let myClassNib = UINib(nibName: "RecipeView", bundle: nil) return myClassNib.instantiate(withOwner: nil, options: nil)[0] as! RecipeView } @IBAction func manageFavorite(_ sender: Any) { if isFavorite == true { favoriteBtn.setBackgroundImage(UIImage.init(named: "addToFavorites"), for: .normal) isFavorite = false } else { favoriteBtn.setBackgroundImage(UIImage.init(named: "favorite"), for: .normal) isFavorite = true } } /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ } <file_sep># Uncomment the next line to define a global platform for your project # platform :ios, '9.0' target 'AIScribe' do # Comment the next line if you're not using Swift and don't want to use dynamic frameworks use_frameworks! # Pods for AIScribe target 'AIScribeTests' do inherit! :search_paths # Pods for testing end target 'AIScribeUITests' do inherit! :search_paths # Pods for testing end end pod 'AFNetworking', '~> 3.0' pod 'Alamofire', '~> 4.4' pod 'TestFairy' pod 'AWSAutoScaling' pod 'AWSCloudWatch' pod 'AWSCognito' pod 'AWSCognitoIdentityProvider' pod 'AWSDynamoDB' pod 'AWSEC2' pod 'AWSElasticLoadBalancing' pod 'AWSIoT' pod 'AWSKinesis' pod 'AWSLambda' pod 'AWSMachineLearning' pod 'AWSMobileAnalytics' pod 'AWSS3' pod 'AWSSES' pod 'AWSSimpleDB' pod 'AWSSNS' pod 'AWSSQS' pod 'FacebookCore' pod 'FacebookLogin' pod 'LinkedinSwift', '~> 1.6.2' pod 'SwiftyJSON', git: 'https://github.com/BaiduHiDeviOS/SwiftyJSON.git', branch: 'swift3' pod 'Stripe' pod 'AZTabBar' pod 'HockeySDK' <file_sep>// // DocumentTranslations.swift // AIScribe // // Created by <NAME> on 5/27/19. // Copyright © 2019 RT. All rights reserved. // import UIKit class DocumentTranslations: UIViewController, UITableViewDelegate, UITableViewDataSource { let appDelegate = UIApplication.shared.delegate as! AppDelegate @IBOutlet weak var activityView: UIActivityIndicatorView! @IBOutlet weak var menuBtn: UIButton! @IBOutlet weak var filenameLbl: UILabel! var did : String? var filename: String? var translationsList = NSMutableArray() var selectedFile: NSDictionary? @IBOutlet weak var translationTable: UITableView! override func viewDidLoad() { super.viewDidLoad() translationTable.tableFooterView = UIView() translationTable.dataSource = self translationTable.delegate = self filenameLbl.text = filename activityView.startAnimating() getTranslations() // Do any additional setup after loading the view. NotificationCenter.default.addObserver( self, selector: #selector(refreshTranslationsNotification), name: NSNotification.Name(rawValue: "refreshTranslations"), object: nil) } @objc func refreshTranslationsNotification (notification: NSNotification) { print("handle") translationsList.removeAllObjects() getTranslations() } func getTranslations() { print("getTranslations") let dataString = "translationData" let urlString = "\(appDelegate.serverDestination!)documentTranslationsJSON.php" let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" let paramString = "did=\(did!)&mobile=true&devStatus=\(appDelegate.devStage!)" print("urlString: \(urlString)") //print("paramString: \(paramString)") request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let session = URLSession.shared session.dataTask(with: request) {data, response, err in do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary print("translations jsonResult: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary if dataDict[dataString]! is NSNull { print("no data") DispatchQueue.main.sync(execute: { //self.noResultsMain.isHidden = false }) //self.statusLbl.isHidden = false } else { let uploadData : NSMutableArray = (dataDict[dataString]! as! NSArray).mutableCopy() as! NSMutableArray if (uploadData.count > 0) { //let list = uploadData as! NSMutableArray for ob in uploadData { let dict = ob as! NSDictionary self.translationsList.add(dict) } DispatchQueue.main.sync(execute: { self.activityView.isHidden = true self.activityView.stopAnimating() self.translationTable.reloadData() }) } else { DispatchQueue.main.sync(execute: { //self.noResultsMain.isHidden = false }) } } } catch let err as NSError { print("error: \(err.description)") } }.resume() } // MARK: Tableview func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // let dict = translationsList[(indexPath as NSIndexPath).row] as! NSDictionary // // did = dict.object(forKey: "did") as! String } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 75 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.translationsList.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell")! let dict = translationsList[(indexPath as NSIndexPath).row] as! NSDictionary cell.selectionStyle = .none let v0 = cell.viewWithTag(1) as! UILabel let v1 = cell.viewWithTag(2) as! UILabel let v2 = cell.viewWithTag(3) as! UIButton v0.text = dict.object(forKey: "displayLang") as? String v1.text = dict.object(forKey: "language") as? String //v2.setTitle(dict.object(forKey: "transcription") as? String, for: .normal) //v3.setTitle(dict.object(forKey: "translations") as? String, for: .normal) v2.restorationIdentifier = "\(indexPath.row)" return cell } @IBAction func viewTranslation(_ sender: Any) { let btn = sender as! UIButton let ind = Int(btn.restorationIdentifier!) selectedFile = translationsList[ind!] as? NSDictionary did = selectedFile!.object(forKey: "did") as? String self.performSegue(withIdentifier: "EditTranslation", sender: self) } @IBAction func cancel(_ sender: Any) { self.navigationController?.popViewController(animated: true) self.dismiss(animated: true, completion: nil) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "EditTranslation" { let destination = segue.destination as! TranslationResult destination.did = did destination.filename = filename destination.selectedFile = selectedFile } } } <file_sep>// // ForgotPassword.swift // AIScribe // // Created by <NAME> on 5/18/18. // Copyright © 2018 RT. All rights reserved. // import UIKit class ForgotPassword: UIViewController, UITextFieldDelegate { let appDelegate = UIApplication.shared.delegate as! AppDelegate @IBOutlet weak var emailTxt: UITextField! @IBOutlet weak var submitBtn: UIButton! @IBOutlet weak var activityView: UIActivityIndicatorView! override func viewDidLoad() { super.viewDidLoad() activityView.isHidden = true emailTxt.delegate = self submitBtn.isEnabled = false submitBtn.backgroundColor = appDelegate.crWarmGray submitBtn.layer.cornerRadius = submitBtn.frame.width/2 let keyboardDoneButtonView = UIToolbar() keyboardDoneButtonView.sizeToFit() let doneButton = UIBarButtonItem(title: "Done", style: .bordered, target: self, action: #selector(self.doneClicked)) keyboardDoneButtonView.items = [doneButton] emailTxt?.inputAccessoryView = keyboardDoneButtonView //debug() } @IBAction func goBack(_ sender: Any) { self.navigationController?.popViewController(animated: true) dismiss(animated: true, completion: nil) } func debug () { emailTxt?.text = "<EMAIL>" submitBtn.isEnabled = true submitBtn.backgroundColor = appDelegate.crLightBlue } @objc func doneClicked(sender: UIButton!) { self.view.endEditing(true) if emailTxt.text != "" { submitBtn.isEnabled = true submitBtn.backgroundColor = appDelegate.crLightBlue } } func sendPasswordRequest() { NotificationCenter.default.post(name: Notification.Name("showResetInstructions"), object: nil) for controller in self.navigationController!.viewControllers as Array { if controller.isKind(of: Login.self) { self.navigationController!.popToViewController(controller, animated: true) break } } } func textFieldDidEndEditing(_ textField: UITextField, reason: UITextFieldDidEndEditingReason) { if emailTxt.text != "" { submitBtn.isEnabled = true submitBtn.backgroundColor = appDelegate.crLightBlue } } @IBAction func sendRequest(_ sender: Any) { if emailTxt.text != "" { activityView.isHidden = false activityView.startAnimating() let urlString = "\(appDelegate.serverDestination!)passwordRequestJSON.php" print("urlString: \(urlString)") let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" let paramString = "email=\(emailTxt.text!)&devStatus=\(appDelegate.devStage!)&mobile=true&devStatus=\(appDelegate.devStage!)" request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) //print("decryptParam: \(paramString)") let session = URLSession.shared session.dataTask(with: request) {data, response, err in //print("Entered the completionHandler: \(response)") //var err: NSError? do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary print("passwordRequestData: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary //print("dataDict: \(dataDict)") let uploadData : NSDictionary = dataDict.object(forKey: "passwordRequestData") as! NSDictionary let status = uploadData.object(forKey: "status") as? String DispatchQueue.main.sync(execute: { if status != nil && status == "Password request sent" { self.sendPasswordRequest() } else { DispatchQueue.main.sync(execute: { self.activityView.stopAnimating() self.activityView.isHidden = true let alert = UIAlertController(title: "Password Request Error", message: status, preferredStyle: UIAlertControllerStyle.alert) self.present(alert, animated: true, completion: nil) alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { action in switch action.style{ case .default: print("default") case .cancel: print("cancel") case .destructive: print("destructive") } })) }) } }) } catch let err as NSError { print("error: \(err.description)") } }.resume() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } <file_sep>// // AccountConfirmation.swift // AIScribe // // Created by <NAME> on 5/18/18. // Copyright © 2018 RT. All rights reserved. // import UIKit class AccountConfirmation: UIViewController { let appDelegate = UIApplication.shared.delegate as! AppDelegate @IBOutlet weak var statusLbl: UILabel! @IBOutlet weak var instructionsLbl: UILabel! override func viewDidLoad() { super.viewDidLoad() let attributedString = NSMutableAttributedString(string: "We’ve emailed a verification link to \(appDelegate.email!). Click on the link in the email to finish setting up your account.", attributes: [ .font: UIFont(name: "Avenir-Book", size: 16.0)!, .foregroundColor: appDelegate.crGray ]) attributedString.addAttributes([ .font: UIFont(name: "Avenir-Medium", size: 16.0)!, .foregroundColor: UIColor.black ], range: NSRange(location: 37, length: appDelegate.email!.characters.count)) instructionsLbl.attributedText = attributedString let attributedString2 = NSMutableAttributedString(string: "Did not receive verification link? Resend email.", attributes: [ .font: UIFont(name: "Avenir-Book", size: 14.0)!, .foregroundColor: UIColor.gray ]) attributedString2.addAttributes([ .font: UIFont(name: "Avenir-Medium", size: 14.0)!, .foregroundColor: appDelegate.crLightBlue ], range: NSRange(location: 35, length: 12)) statusLbl.attributedText = attributedString2 } @IBAction func returnLogin(_ sender: Any) { for controller in self.navigationController!.viewControllers as Array { if controller.isKind(of: Login.self) { self.navigationController!.popToViewController(controller, animated: true) break } } } // override func viewDidAppear(_ animated: Bool) { // // print("viewDidAppear") // } // // override func viewWillAppear(_ animated: Bool) { // // print("viewWillAppear") // } func checkConfirmation() { let urlString = "\(appDelegate.serverDestination!)checkConfirmation.php" print("urlString: \(urlString)") let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" let paramString = "uid=\(appDelegate.userid!)&devStatus=\(appDelegate.devStage!)&mobile=true" print("paramString: \(paramString)") request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let session = URLSession.shared session.dataTask(with: request) {data, response, err in do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary print("confirmation check jsonResult: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary if dataDict["userData"]! is NSNull { print("no user") } else { let userDict : NSDictionary = dataDict["userData"] as! NSDictionary let status : String = userDict["status"] as! String print("status: \(status)") if (status == "account confirmed") { DispatchQueue.main.sync(execute: { self.performSegue(withIdentifier: "AddInfo", sender: self) }) } else { DispatchQueue.main.sync(execute: { }) } } } catch let err as NSError { print("error: \(err.description)") } }.resume() } @IBAction func resendEmail(_ sender: Any) { let urlString = "\(appDelegate.serverDestination!)resendEmail.php" print("urlString: \(urlString)") let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" let paramString = "email=\(appDelegate.email!)&devStatus=\(appDelegate.devStage!)&mobile=true" print("paramString: \(paramString)") request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let session = URLSession.shared session.dataTask(with: request) {data, response, err in do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary print("resend email jsonResult: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary if dataDict["emailData"]! is NSNull { print("no user") } else { let userDict : NSDictionary = dataDict["emailData"] as! NSDictionary let status : String = userDict["status"] as! String print("status: \(status)") if (status == "email sent") { DispatchQueue.main.sync(execute: { self.showBasicAlert(string: "Email has been resent to \(self.appDelegate.email!)") }) } else { DispatchQueue.main.sync(execute: { self.showBasicAlert(string: "Request could not be completed. Please check your internet connection.") }) } } } catch let err as NSError { print("error: \(err.description)") } }.resume() } func showBasicAlert(string:String) { let alert = UIAlertController(title: nil, message: string, preferredStyle: UIAlertControllerStyle.alert) self.present(alert, animated: true, completion: nil) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in switch action.style { case .default: print("default") case .cancel: print("cancel") case .destructive: print("destructive") } })) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } <file_sep>// // InviteFriends.swift // AIScribe // // Created by <NAME> on 8/24/18. // Copyright © 2018 RT. All rights reserved. // import UIKit import Contacts import FBSDKLoginKit import FBSDKCoreKit import Social import MessageUI class InviteFriends: UIViewController, UITableViewDelegate, UITableViewDataSource, FBSDKLoginButtonDelegate, MFMessageComposeViewControllerDelegate { let appDelegate = UIApplication.shared.delegate as! AppDelegate var inviteList = [NSDictionary]() var facebookList = [NSDictionary]() var selectedPhoneList = [String]() var selectedEmailList = [String]() //var contactsList = [NSDictionary]() var contactsList = [CNContact]() var selectedInviteList = [NSDictionary]() var selectedFacebookList = [NSDictionary]() //var selectedContactsList = [NSDictionary]() var selectedContactsList = [CNContact]() var inviteMode : Int? var item : NSDictionary? var item1 : CNContact? @IBOutlet weak var requestsTable: UITableView! @IBOutlet weak var separatorView: UIView! @IBOutlet weak var nameTxt: UITextField! @IBOutlet weak var emailLbl: UILabel! @IBOutlet weak var instructionLbl: UILabel! @IBOutlet weak var micBtn: UIButton! @IBOutlet weak var instructionHeight: NSLayoutConstraint! var dict2 : [String : AnyObject]? @IBOutlet weak var activityView: UIActivityIndicatorView! @IBOutlet weak var sendBtn: UIButton! var emailsStr : String? var phonesStr : String? override func viewDidLoad() { super.viewDidLoad() inviteMode = 0 requestsTable.dataSource = self requestsTable.delegate = self requestsTable.tableFooterView = UIView() instructionHeight.constant = 0 separatorView.isHidden = true micBtn.isHidden = false emailLbl.isHidden = true activityView.isHidden = true sendBtn.backgroundColor = appDelegate.crWarmGray sendBtn.isEnabled = false // if FBSDKAccessToken.current() != nil { // // print("has logged into FB") // // getFBFriends() // } //debug() let btnItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.done, target: self, action: #selector(dismissKeyboard)) let numberToolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 50)) numberToolbar.backgroundColor = UIColor.darkGray numberToolbar.barStyle = UIBarStyle.default numberToolbar.tintColor = UIColor.black numberToolbar.items = [ UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil), btnItem] numberToolbar.sizeToFit() nameTxt.inputAccessoryView = numberToolbar getContacts() //getFBFriends() // if FBSDKAccessToken.current() != nil { // // print("has logged into FB") // // self.logUserData() // } // Do any additional setup after loading the view. } // func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) { // // print("logged in") // } // // func loginButtonDidLogOut(_ loginButton: FBSDKLoginButton!) { // // print("logged out") // } // MARK: Actions func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) { print("logged in") } func loginButtonDidLogOut(_ loginButton: FBSDKLoginButton!) { print("logged out") } func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) { print("result: \(result)") if let error = error { print(error.localizedDescription) return } //self.logUserData() } @IBAction func loginFB(_ sender: Any) { //http://www.oodlestechnologies.com/blogs/How-To-Integrate-Facebook-iOS-Application-In-swift-4 // FacebookSignInManager.basicInfoWithCompletionHandler(self) { (dataDictionary:Dictionary<String, AnyObject>?, error:NSError?) -> Void in // // print("dataDictionary: \(dataDictionary!)") // // self.appDelegate.firstname = dataDictionary!["first_name"] as! String // self.appDelegate.lastname = dataDictionary!["last_name"] as! String // self.appDelegate.email = dataDictionary!["email"] as! String // self.appDelegate.fbID = dataDictionary!["id"] as? String // let pic = dataDictionary!["picture"] as! NSDictionary // let data = pic["data"] as! NSDictionary //// //// self.appDelegate.profileImg = data["url"] as? String // } // let fbLoginManager : FBSDKLoginManager = FBSDKLoginManager() // // fbLoginManager.logIn(withReadPermissions: ["email"], from: self) { (result, error) in // // if (error == nil){ // // let fbloginresult : FBSDKLoginManagerLoginResult = result! // if fbloginresult.grantedPermissions != nil { // if(fbloginresult.grantedPermissions.contains("email")) { // // if((FBSDKAccessToken.current()) != nil){ // // FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email"]).start(completionHandler: { (connection, result, error) -> Void in // if (error == nil){ // self.dict2 = result as! [String : AnyObject] // // //print(result!) // print("dict: \(self.dict2)") // // self.getFBFriends() // } // }) // } // } // } // } // } } var inviteVals : [String:String]? @IBAction func sendInvites(_ sender: Any) { emailsStr = (selectedEmailList.map{String($0)}).joined(separator: ",") phonesStr = (selectedPhoneList.map{String($0)}).joined(separator: ",") print("emailsStr: \(emailsStr!)") print("phonesStr: \(phonesStr!)") inviteVals = ["emailsStr" : emailsStr!, "phonesStr" : phonesStr!, "inviteMode" : "2"] //NotificationCenter.default.post(name: Notification.Name("invitesSentNotification"), object: dict) if selectedPhoneList.count > 0 { sendSMS() } else { sendInvites() } } func sendEmailInvites() { //emailsStr = "" print("sendEmailInvites") let dataString = "emailInvitesData" let urlString = "\(appDelegate.serverDestination!)sendEmailInvites.php" let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" let paramString = "uid=\(appDelegate.userid!)&emailsStr=\(emailsStr!)&devStatus=\(appDelegate.devStage!)&mobile=true" print("urlString: \(urlString)") print("paramString: \(paramString)") request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let session = URLSession.shared session.dataTask(with: request) {data, response, err in do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary print("friend requests jsonResult: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary if dataDict[dataString]! is NSNull { print("no data") DispatchQueue.main.sync(execute: { //self.recipeStatusTV.isHidden = false }) } else { let uploadData : NSDictionary = dataDict[dataString]! as! NSDictionary print("uploadData: \(uploadData)") let status = uploadData.object(forKey: "status") as! String var isSaved = false //to do if status == "email invites sent" { isSaved = true } DispatchQueue.main.sync(execute: { }) } } catch let err as NSError { print("error: \(err.description)") } }.resume() } @IBAction func cancel(_ sender: Any) { self.navigationController?.popViewController(animated: true) self.dismiss(animated: true, completion: nil) } @IBAction func selectItem(_ sender: Any) { let btn = sender as! UIButton manageButton(btn: btn) } @IBAction func changeInviteMode(_ sender: Any) { let btn = sender as? UIButton inviteMode = Int((btn?.restorationIdentifier!)!) if inviteMode != 2 { instructionHeight.constant = 0 separatorView.isHidden = true micBtn.isHidden = false emailLbl.isHidden = true nameTxt.borderStyle = .roundedRect nameTxt.placeholder = "Search in Friends" } else { separatorView.isHidden = false instructionHeight.constant = 58 micBtn.isHidden = true emailLbl.isHidden = false nameTxt.borderStyle = .none nameTxt.placeholder = "enter email (eg. <EMAIL>)" } requestsTable.reloadData() } func cellUpdateBtn (btn: UIButton) { let ind = Int(btn.restorationIdentifier!) if inviteMode == 0 { item = facebookList[ind!] if selectedFacebookList.contains(item!) { btn.setBackgroundImage(#imageLiteral(resourceName: "checkGreen"), for: .normal) //replace with check } else { btn.setBackgroundImage(#imageLiteral(resourceName: "plus-normal"), for: .normal) } } else if inviteMode == 1 { item1 = contactsList[ind!] // if selectedContactsList.contains(item1!) // { // btn.setBackgroundImage(#imageLiteral(resourceName: "checkGreen"), for: .normal) //replace with check // } // else // { // btn.setBackgroundImage(#imageLiteral(resourceName: "plus-normal"), for: .normal) // } var ind = 0 var hasPhone = false for phone in selectedPhoneList { if let phone1 = item1?.phoneNumbers[0] { if phone1.value.stringValue == phone { hasPhone = true } } ind += 1 } ind = 0 var hasEmail = false for email in selectedEmailList { if let email1 = item1?.emailAddresses[0] { if email1.value as String == email { hasEmail = true } } ind += 1 } if hasPhone == false && hasEmail == false { btn.setBackgroundImage(#imageLiteral(resourceName: "light"), for: .normal) } else { btn.setBackgroundImage(#imageLiteral(resourceName: "checkGreen"), for: .normal) } } else { item = inviteList[ind!] if selectedInviteList.contains(item!) { btn.setBackgroundImage(#imageLiteral(resourceName: "checkGreen"), for: .normal) //replace with check } else { btn.setBackgroundImage(#imageLiteral(resourceName: "plus-normal"), for: .normal) } } } func manageButton (btn: UIButton) { let ind = Int(btn.restorationIdentifier!) if inviteMode == 0 { item = facebookList[ind!] if selectedFacebookList.contains(item!) { let ind2 = selectedFacebookList.index(of: item!) btn.setBackgroundImage(#imageLiteral(resourceName: "plus-normal"), for: .normal) //replace with check selectedFacebookList.remove(at: ind2!) self.disableSendBtn() } else { btn.setBackgroundImage(#imageLiteral(resourceName: "checkGreen"), for: .normal) //replace with check selectedFacebookList.append(item!) } } else if inviteMode == 1 { item1 = contactsList[ind!] //disable button and remove selected contact if selectedContactsList.contains(item1!) { let ind2 = selectedContactsList.index(of: item1!) btn.setBackgroundImage(#imageLiteral(resourceName: "plus-normal"), for: .normal) //replace with check selectedContactsList.remove(at: ind2!) self.disableSendBtn() //remove selected phone number if (item1?.phoneNumbers.count)! > 0 { var ind = 0 for phone in selectedPhoneList { if let phone1 = self.item1?.phoneNumbers[0] { if phone1.value.stringValue == phone { self.selectedPhoneList.remove(at: ind) print("remove phone") } } ind += 1 } } //remove selected email if (item1?.emailAddresses.count)! > 0 { var ind = 0 for email in selectedEmailList { if let email1 = self.item1?.emailAddresses[0] { if email1.value as String == email { self.selectedEmailList.remove(at: ind) print("remove email") } } ind += 1 } } } else { //add contact // if contact.phoneNumbers.count > 0 { // self.txtP1.text = (contact.phoneNumbers[0].value as! CNPhoneNumber).valueForKey("digits") as? String // } else { // self.txtP1.text = "" // } let alert = UIAlertController(title: "Share Contact", message: "Please select", preferredStyle: UIAlertControllerStyle.alert) self.present(alert, animated: true, completion: nil) if (item1?.phoneNumbers.count)! > 0 { alert.addAction(UIAlertAction(title: "Phone", style: .default, handler: { action in switch action.style{ case .default: print("default") btn.setBackgroundImage(#imageLiteral(resourceName: "checkGreen"), for: .normal) //replace with check self.selectedContactsList.append(self.item1!) if let phone = self.item1?.phoneNumbers[0] { print("phone: \(phone.value.stringValue)") self.selectedPhoneList.append(phone.value.stringValue as String) self.enableSendBtn() } else { print("na phone") } case .cancel: print("cancel") case .destructive: print("destructive") } })) } if (item1?.emailAddresses.count)! > 0 { alert.addAction(UIAlertAction(title: "Email", style: .default, handler: { action in switch action.style{ case .default: print("default") btn.setBackgroundImage(#imageLiteral(resourceName: "checkGreen"), for: .normal) //replace with check self.selectedContactsList.append(self.item1!) if let email = self.item1?.emailAddresses[0] { print("email: \(email.value)") self.selectedEmailList.append(email.value as String) self.enableSendBtn() } case .cancel: print("cancel") case .destructive: print("destructive") } })) } alert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { action in switch action.style{ case .default: print("default") case .cancel: print("cancel") case .destructive: print("destructive") } })) } print("selectedContactsList: \(selectedContactsList.count)") } else { item = inviteList[ind!] if selectedInviteList.contains(item!) { let ind2 = selectedInviteList.index(of: item!) btn.setBackgroundImage(#imageLiteral(resourceName: "plus-normal"), for: .normal) //replace with check selectedInviteList.remove(at: ind2!) self.disableSendBtn() } else { btn.setBackgroundImage(#imageLiteral(resourceName: "checkGreen"), for: .normal) //replace with check selectedInviteList.append(item!) } } } func sendSMS () { if (MFMessageComposeViewController.canSendText()) { let controller = MFMessageComposeViewController() controller.body = "Download Chewsrite at http://aiscribelink.com and use my signup code: \(self.appDelegate.referralCode!)..." //controller.recipients = [phoneNumber.text] controller.messageComposeDelegate = self controller.recipients = selectedPhoneList self.present(controller, animated: true, completion: nil) } else { // show failure alert selectedPhoneList.removeAll() requestsTable.reloadData() let alert = UIAlertController(title: nil, message: "Texting is not allowed on this device.", preferredStyle: UIAlertControllerStyle.alert) self.present(alert, animated: true, completion: nil) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in switch action.style{ case .default: print("default") if self.selectedEmailList.count > 0 { self.sendInvites() } case .cancel: print("cancel") case .destructive: print("destructive") } })) } } // MARK: Text Delegate func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { print("message UI dismiss with error") controller.dismiss(animated: true) } func messageComposeViewController(_ controller: MFMessageComposeViewController, didFinishWith result: MessageComposeResult) { print("message UI dismiss") controller.dismiss(animated: true) if selectedEmailList.count > 0 { sendInvites() } } func enableSendBtn () { sendBtn.backgroundColor = appDelegate.crLightBlue sendBtn.isEnabled = true } func disableSendBtn () { if selectedFacebookList.count == 0 && selectedContactsList.count == 0 && selectedEmailList.count == 0 { sendBtn.backgroundColor = appDelegate.crWarmGray sendBtn.isEnabled = false } } // MARK: Query func getFBFriends () { let params = ["fields": "id, first_name, last_name, name, email, picture"] let graphRequest = FBSDKGraphRequest(graphPath: "/me/friends", parameters: params) let connection = FBSDKGraphRequestConnection() connection.add(graphRequest, completionHandler: { (connection, result, error) in if error == nil { if let userData = result as? [String:Any] { print("friends: \(userData)") } } else { print("Error Getting Friends \(error)"); } }) connection.start() } func getContacts () { let contactStore = CNContactStore() let keysToFetch = [CNContactFormatter.descriptorForRequiredKeys(for: .fullName), CNContactPhoneNumbersKey, CNContactEmailAddressesKey] as [Any] // The container means // that the source the contacts from, such as Exchange and iCloud var allContainers: [CNContainer] = [] do { allContainers = try contactStore.containers(matching: nil) } catch { print("Error fetching containers") } //var contacts: [CNContact] = [] // Loop the containers for container in allContainers { let fetchPredicate = CNContact.predicateForContactsInContainer(withIdentifier: container.identifier) do { let containerResults = try contactStore.unifiedContacts(matching: fetchPredicate, keysToFetch: keysToFetch as! [CNKeyDescriptor]) // Put them into "contacts" self.contactsList.append(contentsOf: containerResults) //print("containerResults: \(containerResults)\n") } catch { print("Error fetching results for container") } } for contact in contactsList { //print("contact: \(contact.givenName) \(contact.familyName)") } } @objc func dismissKeyboard () { var dict : NSMutableDictionary? if inviteMode == 2 { if nameTxt.text != "" { dict = ["friendname" : nameTxt.text!,"serving" : "2 oz", "active" : true] inviteList.append(dict!) selectedInviteList.append(dict!) selectedEmailList.append(nameTxt.text!) nameTxt.text = "" self.enableSendBtn() } } else { //self.selectedEmailList.append(email as String) } requestsTable.reloadData() self.view.endEditing(true) } func sendInvites() { print("sendInvites") let dataString = "inviteData" let urlString = "\(appDelegate.serverDestination!)sendInvites.php" let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" let paramString = "uid=\(appDelegate.userid!)&emails=\(emailsStr!)&phones=\(phonesStr!)&inviteMode=\(inviteMode!)&devStatus=\(appDelegate.devStage!)&mobile=true" print("urlString: \(urlString)") print("paramString: \(paramString)") request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let session = URLSession.shared session.dataTask(with: request) {data, response, err in do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary //print("recipes jsonResult: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary if dataDict[dataString]! is NSNull { print("no data") DispatchQueue.main.sync(execute: { // self.activityView.stopAnimating() // self.activityView.isHidden = true }) } else { let uploadData : NSDictionary = dataDict[dataString]! as! NSDictionary print("uploadData: \(uploadData)") let status = uploadData.object(forKey: "status") as! String var isSaved = false if status == "invites sent" { isSaved = true } DispatchQueue.main.sync(execute: { if isSaved == true { //let dict = ["emailsStr" : self.emailsStr!, "phonesStr" : self.phonesStr!] self.handleSave() } else { print("save error") let alert = UIAlertController(title: nil, message: "Save Error", preferredStyle: UIAlertControllerStyle.alert) self.present(alert, animated: true, completion: nil) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in switch action.style{ case .default: print("default") case .cancel: print("cancel") case .destructive: print("destructive") } })) } }) } } catch let err as NSError { print("error: \(err.description)") } }.resume() } func handleSave() { NotificationCenter.default.post(name: Notification.Name("invitesSentNotification"), object: inviteVals) self.navigationController?.popViewController(animated: true) self.dismiss(animated: true, completion: nil) } func debug () { var dict : NSMutableDictionary = ["friendname" : "<NAME>","serving" : "1 oz", "active" : false] facebookList.append(dict) dict = ["friendname" : "<NAME>","serving" : "2 oz", "active" : false] facebookList.append(dict) // dict = ["friendname" : "<NAME>","serving" : "2 oz", "active" : false] // contactsList.append(dict) // // dict = ["friendname" : "<NAME>","serving" : "2 oz", "active" : false] // contactsList.append(dict) dict = ["friendname" : "<EMAIL>","serving" : "2 oz", "active" : false] inviteList.append(dict) dict = ["friendname" : "<EMAIL>","serving" : "2 oz", "active" : false] inviteList.append(dict) requestsTable.reloadData() } // MARK: Tableview func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if inviteMode == 0 { return self.facebookList.count } else if inviteMode == 1 { return self.contactsList.count } else { return self.inviteList.count } } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 44 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: "cell")! as! FriendRequestCell var dict : NSDictionary? var dict1 : CNContact? var friendname = "" if inviteMode == 0 { dict = self.facebookList[(indexPath as NSIndexPath).row] as NSDictionary friendname = dict?.object(forKey: "friendname") as! String } else if inviteMode == 1 { cell = tableView.dequeueReusableCell(withIdentifier: "cell1")! as! FriendRequestCell dict1 = self.contactsList[(indexPath as NSIndexPath).row] as CNContact // var ind = 0 // var hasPhone = false // // for phone in selectedPhoneList // { // if let phone1 = dict1?.phoneNumbers[0] // { // if phone1.value.stringValue == phone // { // hasPhone = true // } // } // // ind += 1 // } // // ind = 0 // // var hasEmail = false // // for email in selectedEmailList // { // if let email1 = self.item1?.emailAddresses[0] // { // if email1.value as String == email // { // hasEmail = true // } // } // // ind += 1 // } // // if hasPhone == false && hasEmail == false // { // cell.requestBtn.setBackgroundImage(#imageLiteral(resourceName: "light"), for: .normal) // } // else // { // cell.requestBtn.setBackgroundImage(#imageLiteral(resourceName: "checkGreen"), for: .normal) // } // var hasEmail = false // // if let a = dict1?.emailAddresses[0].value { // // hasEmail = true // } // // var hasPhone = false // // if let b = dict1?.phoneNumbers[0].value.stringValue { // // hasPhone = true // } // if !selectedEmailList.contains(dict1?.emailAddresses[0].value as String) && !selectedPhoneList.contains(dict1?.phoneNumbers[0].value.stringValue as String) // { // cell.requestBtn.setBackgroundImage(#imageLiteral(resourceName: "light"), for: .normal) // } // else // { // cell.requestBtn.setBackgroundImage(#imageLiteral(resourceName: "checkGreen"), for: .normal) // } //cell.requestBtn.setBackgroundImage(#imageLiteral(resourceName: "light"), for: .normal) let fn = dict1?.givenName let ln = dict1?.familyName // if let phone = dict1?.phoneNumbers[0] // { // print("phone: \(phone.value.stringValue)") // } // else // { // print("na phone") // } // if let email = dict1?.emailAddresses[0] // { // print("email: \(email.value)") // } // else // { // print("na email") // } friendname = "\(fn!) \(ln!)" } else { dict = self.inviteList[(indexPath as NSIndexPath).row] as NSDictionary friendname = dict?.object(forKey: "friendname") as! String } if inviteMode == 0 { cell.friendIV.image = UIImage.init(named: (dict?.object(forKey: "friendname") as? String)!) cell.friendIV.image = #imageLiteral(resourceName: "risotto") } else if inviteMode == 2 { cell = tableView.dequeueReusableCell(withIdentifier: "cell1")! as! FriendRequestCell if dict?.object(forKey: "active") as! Bool == true { cell.requestBtn.setBackgroundImage(#imageLiteral(resourceName: "checkGreen"), for: .normal) } else { cell.requestBtn.setBackgroundImage(#imageLiteral(resourceName: "light"), for: .normal) } //cell.friendIV.image = nil } cell.selectionStyle = .none cell.nameLbl.text = friendname cell.requestBtn.restorationIdentifier = "\(indexPath.row)" cell.requestBtn.addTarget(self, action: #selector(self.selectItem(_:)), for: UIControlEvents.touchUpInside) cellUpdateBtn(btn: cell.requestBtn) return cell } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } <file_sep>// // AccountPreferences.swift // AIScribe // // Created by <NAME> on 1/2/19. // Copyright © 2019 RT. All rights reserved. // import UIKit class AccountPreferences: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate,UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource { let appDelegate = UIApplication.shared.delegate as! AppDelegate @IBOutlet weak var headerLbl: UILabel! @IBOutlet weak var cuisineCV: UICollectionView! var cuisines = [NSDictionary]() var selectedCuisines = [NSDictionary]() @IBOutlet weak var activityView: UIActivityIndicatorView! @IBOutlet weak var submitBtn: UIButton! var newFamilyMemberID : Int? var concerns = [NSDictionary]() var selectedConcerns = [NSDictionary]() @IBOutlet weak var otherTxt: UITextField! //likes dislikes var likedItems = NSMutableArray() var dislikedItems = NSMutableArray() var category : String? var selectedList = NSMutableArray() var currentButtons = [UIButton]() var scrollButtons = [UIButton]() var buttonUnderscores = [UIView]() var fruitsList = NSMutableArray() var vegList = NSMutableArray() var meatList = NSMutableArray() var seafoodList = NSMutableArray() var dairyList = NSMutableArray() var nutsList = NSMutableArray() @IBOutlet weak var likesTable: UITableView! @IBOutlet weak var buttonScrollview: UIScrollView! @IBOutlet weak var buttonView: UIView! @IBOutlet weak var likesView: UIView! var viewIndex : Int = 0 // MARK: viewDidLoad override func viewDidLoad() { //appDelegate.userid = "24" super.viewDidLoad() cuisineCV.delegate = self cuisineCV.dataSource = self likesView.isHidden = true cuisineCV.isHidden = false //otherTxt.isHidden = true activityView.isHidden = true //appDelegate.userid = "1" getCuisines() //populate() getAllConcerns() //getConcerns() getLikesDislikes() //query user added concerns //print("frame size: \(self.view.frame.width)") // var fontSize : CGFloat = 16.0 // // if self.view.frame.width <= 320 // { // fontSize = 14.0 // } // let attributedString = NSMutableAttributedString(string: "Step 2: Let us know your dietery concerns", attributes: [ // .font: UIFont(name: "Avenir-Medium", size: fontSize)!, // .foregroundColor: UIColor.white // ]) // attributedString.addAttribute(.font, value: UIFont(name: "Avenir-Book", size: fontSize)!, range: NSRange(location: 0, length: 7)) // // headerLbl.attributedText = attributedString let btnItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.done, target: self, action: #selector(dismissKeyboard)) let numberToolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 50)) numberToolbar.backgroundColor = UIColor.darkGray numberToolbar.barStyle = UIBarStyle.default numberToolbar.tintColor = UIColor.black numberToolbar.items = [ UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil), btnItem] numberToolbar.sizeToFit() NotificationCenter.default.addObserver(self, selector: #selector(refeshConcerns), name: NSNotification.Name(rawValue: "refeshConcerns"), object: nil) //likes dislikes getIngredients() //selectedList = fruitsList category = "0" activityView.isHidden = true likesTable.delegate = self likesTable.dataSource = self likesTable.tableFooterView = UIView() // v2.isHidden = true // v3.isHidden = true // v4.isHidden = true // v5.isHidden = true // v6.isHidden = true //print("frame size: \(self.view.frame.width)") // var fontSize : CGFloat = 16.0 // // if self.view.frame.width <= 320 // { // fontSize = 14.0 // } // // let attributedString = NSMutableAttributedString(string: "Step 3: Let us know your likes & dislikes", attributes: [ // .font: UIFont(name: "Avenir-Medium", size: fontSize)!, // .foregroundColor: UIColor.white // ]) // attributedString.addAttribute(.font, value: UIFont(name: "Avenir-Light", size: fontSize)!, range: NSRange(location: 0, length: 7)) // // headerLbl.attributedText = attributedString //buttonView.isHidden = true populateButtonView() NotificationCenter.default.addObserver(self, selector: #selector(refreshIngredients), name: NSNotification.Name(rawValue: "refreshIngredients"), object: nil) } // MARK: Actions @IBAction func updateView(_ sender: Any) { let seg = sender as! UISegmentedControl viewIndex = seg.selectedSegmentIndex if viewIndex == 0 || viewIndex == 1 { cuisineCV.reloadData() cuisineCV.isHidden = false likesView.isHidden = true } else { cuisineCV.isHidden = true likesView.isHidden = false } } @IBAction func savePreferences(_ sender: Any) { } @objc func dismissKeyboard () { self.view.endEditing(true) } @IBAction func uploadData(_ sender: Any) { uploadAllData() } @objc func refreshIngredients (notification: NSNotification) { let newItems = notification.object as! [NSDictionary] //add new cats for dict in newItems { let ingredientID = dict.object(forKey: "ingredientid") as! String let dict = ["ingredient" : dict.object(forKey: "ingredient") as! String,"ingredientid": ingredientID,"categoryid": dict.object(forKey: "categoryid") as! String] as NSDictionary likedItems.add("\(ingredientID)-up") if dict.object(forKey: "categoryid") as! String == "1" { self.fruitsList.add(dict) } else if dict.object(forKey: "categoryid") as! String == "2" { self.vegList.add(dict) } else if dict.object(forKey: "categoryid") as! String == "3" { self.meatList.add(dict) } else if dict.object(forKey: "categoryid") as! String == "4" { self.seafoodList.add(dict) } else if dict.object(forKey: "categoryid") as! String == "5" { self.dairyList.add(dict) } else if dict.object(forKey: "categoryid") as! String == "6" { self.nutsList.add(dict) } //ind += 1 self.selectedList.add(dict) } self.likesTable.reloadData() } @IBAction func showOptions(_ sender: Any) { let btn = sender as! UIButton let ind = Int(btn.accessibilityIdentifier!) var i = 0 for view in buttonUnderscores { if i == ind { view.isHidden = false } else { view.isHidden = true } i += 1 } if btn.restorationIdentifier == "b1" { // v1.isHidden = false // v2.isHidden = true // v3.isHidden = true // v4.isHidden = true // v5.isHidden = true // v6.isHidden = true selectedList = fruitsList category = "0" } else if btn.restorationIdentifier == "b2" { // v1.isHidden = true // v2.isHidden = false // v3.isHidden = true // v4.isHidden = true // v5.isHidden = true // v6.isHidden = true selectedList = vegList category = "1" } else if btn.restorationIdentifier == "b3" { // v1.isHidden = true // v2.isHidden = true // v3.isHidden = false // v4.isHidden = true // v5.isHidden = true // v6.isHidden = true selectedList = meatList category = "2" } else if btn.restorationIdentifier == "b4" { // v1.isHidden = true // v2.isHidden = true // v3.isHidden = true // v4.isHidden = false // v5.isHidden = true // v6.isHidden = true selectedList = seafoodList category = "3" } else if btn.restorationIdentifier == "b5" { // v1.isHidden = true // v2.isHidden = true // v3.isHidden = true // v4.isHidden = true // v5.isHidden = false // v6.isHidden = true selectedList = dairyList category = "4" } else if btn.restorationIdentifier == "b6" { // v1.isHidden = true // v2.isHidden = true // v3.isHidden = true // v4.isHidden = true // v5.isHidden = true // v6.isHidden = false selectedList = nutsList category = "5" } currentButtons.removeAll() likesTable.reloadData() } // MARK: Webservice func getAllConcerns() { //displayItems.removeAll() print("getAllConcerns") let dataString = "concernsData" let urlString = "\(appDelegate.serverDestination!)getAllConcerns.php" let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" //appDelegate.userid = "22" let paramString = "devStatus=\(appDelegate.devStage!)&mobile=true" print("urlString: \(urlString)") print("paramString: \(paramString)") request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let session = URLSession.shared session.dataTask(with: request) {data, response, err in do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary print("concerns jsonResult: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary if dataDict[dataString]! is NSNull { print("no data") DispatchQueue.main.sync(execute: { //self.recipeStatusTV.isHidden = false self.cuisineCV.reloadData() }) } else { let uploadData : NSMutableArray = (dataDict[dataString]! as! NSArray).mutableCopy() as! NSMutableArray let recipes1 = uploadData as! [NSDictionary] var hasData = false if (recipes1.count > 0) { hasData = true for dict2 in recipes1 { let name = dict2.object(forKey: "concernname" as String)! let image = dict2.object(forKey: "imageblue" as String)! let image2 = dict2.object(forKey: "imagewhite" as String)! let concernid = dict2.object(forKey: "concernid" as String)! self.concerns.append( ["name" : name, "image" : UIImage.init(named: image as! String)!, "image2" : UIImage.init(named: image2 as! String)!,"concernid": concernid]) } DispatchQueue.main.sync(execute: { if hasData == true { self.cuisineCV.reloadData() if self.newFamilyMemberID == nil && self.appDelegate.signingUp != true { self.getUserConcerns() } } else { print("no data") //self.noResultsMain.isHidden = false self.cuisineCV.reloadData() } }) } else { DispatchQueue.main.sync(execute: { self.cuisineCV.reloadData() //self.noResultsMain.isHidden = false }) } } } catch let err as NSError { print("error: \(err.description)") } }.resume() } func getCuisines() { print("getCuisines") let dataString = "cuisineData" let dataString2 = "favoriteData" let urlString = "\(appDelegate.serverDestination!)getCuisinesProfile.php" let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" let paramString = "register=true&devStatus=\(appDelegate.devStage!)&uid=\(appDelegate.userid!)&mobile=true" print("urlString: \(urlString)") print("paramString: \(paramString)") request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let session = URLSession.shared session.dataTask(with: request) {data, response, err in do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary //print("cuisines jsonResult: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary if dataDict[dataString]! is NSNull { print("no data") DispatchQueue.main.sync(execute: { self.cuisineCV.isHidden = true //self.recipeStatusTV.isHidden = false }) } else { // parse cuisines let uploadData = dataDict[dataString]! as! NSDictionary let list1 = (uploadData["cuisines"]! as! NSArray).mutableCopy() as! NSMutableArray let cuisines1 = list1 as! [NSDictionary] var hasData = false if (cuisines1.count > 0) { hasData = true for dict in cuisines1 { let dict2 = dict.mutableCopy() as! NSMutableDictionary self.cuisines.append(dict2) } //parse favorites let uploadData2 = dataDict[dataString2]! as! NSDictionary let list = (uploadData2["favorites"]! as! NSArray).mutableCopy() as! NSMutableArray let favorites1 = list as! [String] var ind = 0 for _ in self.cuisines { let dict3 = self.cuisines[ind] as NSDictionary let cuisineid = dict3.object(forKey: "cuisineid") as! String if favorites1.contains(cuisineid) { self.selectedCuisines.append(dict3) } ind += 1 } DispatchQueue.main.sync(execute: { if hasData == true { self.cuisineCV.reloadData() } else { print("no data") self.cuisineCV.isHidden = true //self.noResultsMain.isHidden = false } }) } else { DispatchQueue.main.sync(execute: { //self.noResultsMain.isHidden = false }) } } } catch let err as NSError { print("error: \(err.description)") } }.resume() } func getUserConcerns() { //displayItems.removeAll() print("getConcerns") let dataString = "concernsData" let urlString = "\(appDelegate.serverDestination!)getDietaryConcerns.php" let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" let paramString = "uid=\(appDelegate.userid!)&devStatus=\(appDelegate.devStage!)&mobile=true" print("urlString: \(urlString)") print("paramString: \(paramString)") request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let session = URLSession.shared session.dataTask(with: request) {data, response, err in do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary print("concerns jsonResult: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary if dataDict[dataString]! is NSNull { print("no data") DispatchQueue.main.sync(execute: { //self.recipeStatusTV.isHidden = false }) } else { let uploadData : NSMutableArray = (dataDict[dataString]! as! NSArray).mutableCopy() as! NSMutableArray let recipes1 = uploadData as! [String] var hasData = false if (recipes1.count > 0) { hasData = true var ind = 0 for _ in self.concerns { let dict3 = self.concerns[ind] as NSDictionary let concernid = dict3.object(forKey: "concernid") as! String if recipes1.contains(concernid) { self.selectedConcerns.append(dict3) } ind += 1 } DispatchQueue.main.sync(execute: { if hasData == true { //self.cuisineCV.reloadData() //self.recipeStatusTV.text = "You currently have no recipes." //self.updateDisplayList() //self.cuisineCV.reloadData() } else { print("no data") //self.noResultsMain.isHidden = false } }) } else { DispatchQueue.main.sync(execute: { //self.noResultsMain.isHidden = false }) } } } catch let err as NSError { print("error: \(err.description)") } }.resume() } func getLikesDislikes() { //displayItems.removeAll() print("getLikesDislikes") let dataString = "likesData" let urlString = "\(appDelegate.serverDestination!)getUserFoodLikesProfile.php" let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" let paramString = "uid=\(appDelegate.userid!)&devStatus=\(appDelegate.devStage!)&mobile=true" print("urlString: \(urlString)") print("paramString: \(paramString)") request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let session = URLSession.shared session.dataTask(with: request) {data, response, err in do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary print("likes jsonResult: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary if dataDict[dataString]! is NSNull { print("no data") DispatchQueue.main.sync(execute: { //self.recipeStatusTV.isHidden = false }) } else { let uploadData = dataDict[dataString]! as! NSDictionary //var hasData = true let likes = uploadData.object(forKey: "likes") as! String let dislikes = uploadData.object(forKey: "dislikes") as! String let likesArr = likes.split(separator: ",") let dislikesArr = dislikes.split(separator: ",") for str in likesArr { self.likedItems.add("\(str)-up") } for str in dislikesArr { self.dislikedItems.add("\(str)-down") } //print("likedItems: \(self.likedItems)") // DispatchQueue.main.sync(execute: { // // if hasData == true // { // //self.cuisineCV.reloadData() // //self.recipeStatusTV.text = "You currently have no recipes." // //self.updateDisplayList() // } // else // { // print("no data") // // //self.noResultsMain.isHidden = false // } // }) } } catch let err as NSError { print("error: \(err.description)") } }.resume() } func uploadLikesUserData() { submitBtn.isEnabled = false activityView.isHidden = false activityView.startAnimating() print("uploadUserData") var likesString = "" var dislikesString = "" if likedItems.count > 0 { var cuisineids = "" var i = 0 for a in likedItems { if i == 0 { //cuisineids = (a.object(forKey: "concernid") as? String)! cuisineids = a as! String } else { //cuisineids = "\(cuisineids),\(a.object(forKey: "concernid") as! String)" cuisineids = "\(cuisineids),\(a as! String)" } i += 1 } likesString = "\(cuisineids)" } if dislikedItems.count > 0 { var cuisineids = "" var i = 0 for a in dislikedItems { if i == 0 { //cuisineids = (a.object(forKey: "concernid") as? String)! cuisineids = a as! String } else { //cuisineids = "\(cuisineids),\(a.object(forKey: "concernid") as! String)" cuisineids = "\(cuisineids),\(a as! String)" } i += 1 } dislikesString = "\(cuisineids)" } let urlString = "\(appDelegate.serverDestination!)manageUserFoodLikes.php" print("urlString: \(urlString)") let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" likesString = likesString.replacingOccurrences(of: "-up", with: "", options: .literal, range: nil) dislikesString = dislikesString.replacingOccurrences(of: "-down", with: "", options: .literal, range: nil) print("likesString: \(likesString)") print("dislikesString: \(dislikesString)") var paramString = "" if newFamilyMemberID != nil { paramString = "likes=\(likesString)&dislikes=\(dislikesString)&familyid=\(newFamilyMemberID!)&devStatus=\(appDelegate.devStage!)&mobile=true" } else { paramString = "likes=\(likesString)&dislikes=\(dislikesString)&uid=\(appDelegate.userid!)&devStatus=\(appDelegate.devStage!)&mobile=true" } print("paramString: \(paramString)") request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let session = URLSession.shared session.dataTask(with: request) {data, response, err in do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary print("likes jsonResult: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary if dataDict["likesData"]! is NSNull { print("no user") self.activityView.isHidden = true self.activityView.stopAnimating() self.submitBtn.isEnabled = true self.submitBtn.alpha = 1 self.showBasicAlert(string: "no data") } else { let userDict : NSDictionary = dataDict["likesData"] as! NSDictionary let status : String = userDict["status"] as! String print("status: \(status)") if status == "likes saved" || status == "likes updated" { DispatchQueue.main.sync(execute: { self.activityView.isHidden = true self.activityView.stopAnimating() self.submitBtn.isEnabled = true self.submitBtn.alpha = 1 if (self.self.appDelegate.signingUp == true) { self.performSegue(withIdentifier: "NutritionalGoals", sender: self) } else { self.showBasicAlert(string: "Likes/Dislikes Updated") } }) } else { DispatchQueue.main.sync(execute: { self.activityView.isHidden = true self.activityView.stopAnimating() self.submitBtn.isEnabled = true self.submitBtn.alpha = 1 self.showBasicAlert(string: status) }) } } } catch let err as NSError { print("error: \(err.description)") } }.resume() } func getIngredients() { print("getIngredients") let dataString = "ingredientData" let urlString = "\(appDelegate.serverDestination!)getAllIngredients.php" let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" let paramString = "" print("urlString: \(urlString)") //print("paramString: \(paramString)") request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let session = URLSession.shared session.dataTask(with: request) {data, response, err in do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary print("ingredients jsonResult: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary if dataDict[dataString]! is NSNull { print("no data") DispatchQueue.main.sync(execute: { //self.noResultsMain.isHidden = false }) //self.statusLbl.isHidden = false } else { let uploadData : NSMutableArray = (dataDict[dataString]! as! NSArray).mutableCopy() as! NSMutableArray if (uploadData.count > 0) { let list = uploadData as! NSMutableArray for ob in list { let dict = ob as! NSDictionary // var fruitsList = NSMutableArray() // var vegList = NSMutableArray() // var meatList = NSMutableArray() // var seafoodList = NSMutableArray() // var dairyList = NSMutableArray() // var nutsList = NSMutableArray() if dict.object(forKey: "categoryid") as! String == "1" { self.fruitsList.add(dict) } else if dict.object(forKey: "categoryid") as! String == "2" { self.vegList.add(dict) } else if dict.object(forKey: "categoryid") as! String == "3" { self.meatList.add(dict) } else if dict.object(forKey: "categoryid") as! String == "4" { self.seafoodList.add(dict) } else if dict.object(forKey: "categoryid") as! String == "5" { self.dairyList.add(dict) } else if dict.object(forKey: "categoryid") as! String == "6" { self.nutsList.add(dict) } // else if dict.object(forKey: "categoryid") as! String == "7" // { // fruitsList.add(dict) // } // else if dict.object(forKey: "categoryid") as! String == "8" // { // fruitsList.add(dict) // } // else if dict.object(forKey: "categoryid") as! String == "9" // { // fruitsList.add(dict) // } // else if dict.object(forKey: "categoryid") as! String == "10" // { // fruitsList.add(dict) // } } self.selectedList = self.fruitsList DispatchQueue.main.sync(execute: { self.likesTable.reloadData() }) } else { DispatchQueue.main.sync(execute: { //self.noResultsMain.isHidden = false }) } } } catch let err as NSError { print("error: \(err.description)") } }.resume() } @objc func refeshConcerns (notification: NSNotification) { let newConcerns = notification.object as! [NSDictionary] //add new cats var ind = concerns.count-1 concerns.remove(at: ind) for dict in newConcerns { let dict1 = ["name" : dict.object(forKey: "name") as! String, "image" : UIImage.init(named: "customWhite")!, "image2" : UIImage.init(named: "customWhite")!,"concernid": dict.object(forKey: "concernid") as! String] as [String : Any] concerns.append(dict1 as NSDictionary) selectedConcerns.append(dict1 as NSDictionary) ind += 1 } concerns.append( ["name" : "Other", "image" : UIImage.init(named: "add")!, "image2" : UIImage.init(named: "add")!,"concernid": ind]) cuisineCV.reloadData() } func uploadAllData () { var cuisineString = "" if selectedCuisines.count > 0 { var cuisineids = "" var i = 0 for a in selectedCuisines { if i == 0 { cuisineids = (a.object(forKey: "cuisineid") as? String)! } else { cuisineids = "\(cuisineids),\(a.object(forKey: "cuisineid") as! String)" } i += 1 } cuisineString = "\(cuisineids)" } var concernString = "" if selectedConcerns.count > 0 { var concernids = [String]() //var i = 0 for a in selectedConcerns { concernids.append((a.object(forKey: "concernid") as? String)!) // if i == 0 // { // concernids = (a.object(forKey: "concernid") as? String)! // } // else // { // concernids = "\(concernids),\(a.object(forKey: "concernid") as! String)" // } // // i += 1 } concernString = "\(concernids.joined(separator: ","))" } var likesString = "" var dislikesString = "" if likedItems.count > 0 { // var cuisineids = "" // var i = 0 var cuisineids = [String]() for a in likedItems { cuisineids.append(a as! String) // if i == 0 // { // //cuisineids = (a.object(forKey: "concernid") as? String)! // // cuisineids = a as! String // } // else // { // //cuisineids = "\(cuisineids),\(a.object(forKey: "concernid") as! String)" // cuisineids = "\(cuisineids),\(a as! String)" // } // // i += 1 } //likesString = "\(cuisineids)" likesString = "\(cuisineids.joined(separator: ","))" } if dislikedItems.count > 0 { var cuisineids = [String]() // var cuisineids = "" // var i = 0 for a in dislikedItems { cuisineids.append(a as! String) // if i == 0 // { // //cuisineids = (a.object(forKey: "concernid") as? String)! // // cuisineids = a as! String // } // else // { // //cuisineids = "\(cuisineids),\(a.object(forKey: "concernid") as! String)" // cuisineids = "\(cuisineids),\(a as! String)" // } // // i += 1 } //dislikesString = "\(cuisineids)" dislikesString = "\(cuisineids.joined(separator: ","))" } if concernString == "" { concernString = "8,23" } let urlString = "\(appDelegate.serverDestination!)manageUserAccountPrefsData.php" print("urlString: \(urlString)") let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" likesString = likesString.replacingOccurrences(of: "-up", with: "", options: .literal, range: nil) dislikesString = dislikesString.replacingOccurrences(of: "-down", with: "", options: .literal, range: nil) print("likesString: \(likesString)") print("dislikesString: \(dislikesString)") let paramString = "likes=\(likesString)&dislikes=\(dislikesString)&concerns=\(concernString)&cuisines=\(cuisineString)&uid=\(appDelegate.userid!)&devStatus=\(appDelegate.devStage!)&mobile=true" // if newFamilyMemberID != nil // { // paramString = "likes=\(likesString)&dislikes=\(dislikesString)&concernString=\(concernString)&cuisineString=\(cuisineString)&familyid=\(newFamilyMemberID!)&devStatus=\(appDelegate.devStage!)" // } // else // { // paramString = "likes=\(likesString)&dislikes=\(dislikesString)&concerns=\(concernString)&cuisines=\(cuisineString)&uid=\(appDelegate.userid!)&devStatus=\(appDelegate.devStage!)" // } print("paramString: \(paramString)") request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let session = URLSession.shared session.dataTask(with: request) {data, response, err in do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary print("prefsData jsonResult: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary if dataDict["prefsData"]! is NSNull { print("no user") self.activityView.isHidden = true self.activityView.stopAnimating() self.submitBtn.isEnabled = true self.submitBtn.alpha = 1 self.showBasicAlert(string: "no data") } else { let userDict : NSDictionary = dataDict["prefsData"] as! NSDictionary let status : String = userDict["status"] as! String print("status: \(status)") if status == "3" { DispatchQueue.main.sync(execute: { self.activityView.isHidden = true self.activityView.stopAnimating() // self.submitBtn.isEnabled = true // self.submitBtn.alpha = 1 self.showBasicAlert(string: "Dietary Preferences Updated") }) } else { DispatchQueue.main.sync(execute: { self.activityView.isHidden = true self.activityView.stopAnimating() self.submitBtn.isEnabled = true self.submitBtn.alpha = 1 //self.showBasicAlert(string: status) }) } } } catch let err as NSError { print("error: \(err.description)") } }.resume() } func uploadConcerns() { submitBtn.isEnabled = false activityView.isHidden = false activityView.startAnimating() print("uploadConcerns") var concernString = "" if selectedConcerns.count > 0 { var concernids = "" var i = 0 for a in selectedConcerns { if i == 0 { concernids = (a.object(forKey: "concernid") as? String)! } else { concernids = "\(concernids),\(a.object(forKey: "concernid") as! String)" } i += 1 } concernString = "\(concernids)" } let urlString = "\(appDelegate.serverDestination!)manageDietaryConcerns.php" print("urlString: \(urlString)") let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" var paramString = "" if newFamilyMemberID != nil { paramString = "selections=\(concernString)&familyid=\(newFamilyMemberID!)&devStatus=\(appDelegate.devStage!)&mobile=true" } else { paramString = "selections=\(concernString)&uid=\(appDelegate.userid!)&devStatus=\(appDelegate.devStage!)&mobile=true" } print("paramString: \(paramString)") request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let session = URLSession.shared session.dataTask(with: request) {data, response, err in do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary print("cuisines jsonResult: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary if dataDict["favoriteData"]! is NSNull { print("no user") self.activityView.isHidden = true self.activityView.stopAnimating() self.submitBtn.isEnabled = true self.submitBtn.alpha = 1 self.showBasicAlert(string: "no data") } else { let userDict : NSDictionary = dataDict["favoriteData"] as! NSDictionary let status : String = userDict["status"] as! String print("status: \(status)") if status == "user dietary concerns saved" || status == "user dietary concerns saved" || status == "user dietary concerns updated" { DispatchQueue.main.sync(execute: { self.activityView.isHidden = true self.activityView.stopAnimating() self.submitBtn.isEnabled = true self.submitBtn.alpha = 1 if (self.self.appDelegate.signingUp == true) { self.performSegue(withIdentifier: "LikesDislikes", sender: self) } else { self.showBasicAlert(string: "Dietary Concerns Updated") } }) } else { DispatchQueue.main.sync(execute: { self.activityView.isHidden = true self.activityView.stopAnimating() self.submitBtn.isEnabled = true self.submitBtn.alpha = 1 //self.showBasicAlert(string: status) }) } } } catch let err as NSError { print("error: \(err.description)") } }.resume() } func uploadCuisines() { submitBtn.isEnabled = false activityView.isHidden = false activityView.startAnimating() print("uploadCuisines") var cuisineString = "" if selectedCuisines.count > 0 { var cuisineids = "" var i = 0 for a in selectedCuisines { if i == 0 { cuisineids = (a.object(forKey: "cuisineid") as? String)! } else { cuisineids = "\(cuisineids),\(a.object(forKey: "cuisineid") as! String)" } i += 1 } cuisineString = "\(cuisineids)" } let urlString = "\(appDelegate.serverDestination!)manageFavoriteCuisines.php" print("urlString: \(urlString)") let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" var paramString = "" if newFamilyMemberID != nil { paramString = "selections=\(cuisineString)&familyid=\(newFamilyMemberID!)&devStatus=\(appDelegate.devStage!)&mobile=true" } else { paramString = "selections=\(cuisineString)&uid=\(appDelegate.userid!)&devStatus=\(appDelegate.devStage!)&mobile=true" } print("paramString: \(paramString)") request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let session = URLSession.shared session.dataTask(with: request) {data, response, err in do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary print("cuisines jsonResult: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary if dataDict["favoriteData"]! is NSNull { print("no user") } else { let userDict : NSDictionary = dataDict["favoriteData"] as! NSDictionary let status : String = userDict["status"] as! String print("status: \(status)") if (status == "usercuisines saved" || status == "usercuisines updated") { DispatchQueue.main.sync(execute: { self.activityView.isHidden = true self.activityView.stopAnimating() self.submitBtn.isEnabled = true self.submitBtn.alpha = 1 if (self.self.appDelegate.signingUp == true) { self.performSegue(withIdentifier: "DietaryConcerns", sender: self) } else { self.showBasicAlert(string: "Cusines Updated") } }) } else { DispatchQueue.main.sync(execute: { self.activityView.isHidden = true self.activityView.stopAnimating() self.submitBtn.isEnabled = true self.submitBtn.alpha = 1 //self.showBasicAlert(string: status) }) } } } catch let err as NSError { print("error: \(err.description)") } }.resume() } func uploadLikesDislikes() { submitBtn.isEnabled = false activityView.isHidden = false activityView.startAnimating() print("uploadUserData") var likesString = "" var dislikesString = "" if likedItems.count > 0 { var cuisineids = "" var i = 0 for a in likedItems { if i == 0 { //cuisineids = (a.object(forKey: "concernid") as? String)! cuisineids = a as! String } else { //cuisineids = "\(cuisineids),\(a.object(forKey: "concernid") as! String)" cuisineids = "\(cuisineids),\(a as! String)" } i += 1 } likesString = "\(cuisineids)" } if dislikedItems.count > 0 { var cuisineids = "" var i = 0 for a in dislikedItems { if i == 0 { //cuisineids = (a.object(forKey: "concernid") as? String)! cuisineids = a as! String } else { //cuisineids = "\(cuisineids),\(a.object(forKey: "concernid") as! String)" cuisineids = "\(cuisineids),\(a as! String)" } i += 1 } dislikesString = "\(cuisineids)" } let urlString = "\(appDelegate.serverDestination!)manageUserFoodLikes.php" print("urlString: \(urlString)") let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" likesString = likesString.replacingOccurrences(of: "-up", with: "", options: .literal, range: nil) dislikesString = dislikesString.replacingOccurrences(of: "-down", with: "", options: .literal, range: nil) print("likesString: \(likesString)") print("dislikesString: \(dislikesString)") var paramString = "" if newFamilyMemberID != nil { paramString = "likes=\(likesString)&dislikes=\(dislikesString)&familyid=\(newFamilyMemberID!)&devStatus=\(appDelegate.devStage!)&mobile=true" } else { paramString = "likes=\(likesString)&dislikes=\(dislikesString)&uid=\(appDelegate.userid!)&devStatus=\(appDelegate.devStage!)&mobile=true" } print("paramString: \(paramString)") request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let session = URLSession.shared session.dataTask(with: request) {data, response, err in do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary print("likes jsonResult: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary if dataDict["likesData"]! is NSNull { print("no user") self.activityView.isHidden = true self.activityView.stopAnimating() self.submitBtn.isEnabled = true self.submitBtn.alpha = 1 self.showBasicAlert(string: "no data") } else { let userDict : NSDictionary = dataDict["likesData"] as! NSDictionary let status : String = userDict["status"] as! String print("status: \(status)") if status == "likes saved" || status == "likes updated" { DispatchQueue.main.sync(execute: { self.activityView.isHidden = true self.activityView.stopAnimating() self.submitBtn.isEnabled = true self.submitBtn.alpha = 1 if (self.self.appDelegate.signingUp == true) { self.performSegue(withIdentifier: "NutritionalGoals", sender: self) } else { self.showBasicAlert(string: "Likes/Dislikes Updated") } }) } else { DispatchQueue.main.sync(execute: { self.activityView.isHidden = true self.activityView.stopAnimating() self.submitBtn.isEnabled = true self.submitBtn.alpha = 1 self.showBasicAlert(string: status) }) } } } catch let err as NSError { print("error: \(err.description)") } }.resume() } // MARK: - UICollectionViewDataSource, UICollectionViewDelegate methods func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let kWhateverHeightYouWant = 190 return CGSize.init(width: 600, height: CGFloat(kWhateverHeightYouWant)) } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if viewIndex == 0 { return self.cuisines.count } else { return self.concerns.count } } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if viewIndex == 0 { let dict = self.cuisines[indexPath.row] as! NSDictionary //let id = dict.object(forKey: "cuisineid") as! String let name = dict.object(forKey: "cuisinename") as! String let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as? CuisinesCollectionviewCell cell?.cuisineLbl.text = name if selectedCuisines.contains(dict) { cell?.cuisineLbl.backgroundColor = appDelegate.crLightBlue cell?.cuisineLbl.textColor = UIColor.white } else { cell?.cuisineLbl.backgroundColor = UIColor.white cell?.cuisineLbl.textColor = appDelegate.crLightBlue } cell?.cuisineLbl.layer.borderWidth = 1.0 cell?.cuisineLbl.layer.borderColor = appDelegate.crLightBlue.cgColor cell?.cuisineLbl.layer.cornerRadius = 4.0 //cell?.statusLbl.isHidden = true return cell! } else { let dict = self.concerns[indexPath.row] let string = dict.object(forKey: "name") as! String let img = dict.object(forKey: "image") as! UIImage let img2 = dict.object(forKey: "image2") as! UIImage let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell2", for: indexPath) as? CuisinesCollectionviewCell cell?.cuisineLbl.text = string cell?.iconIV.image = img if selectedConcerns.contains(dict) { cell?.backgroundColor = appDelegate.crLightBlue cell?.cuisineLbl.textColor = UIColor.white cell?.iconIV.image = img2 } else { cell?.backgroundColor = UIColor.white cell?.cuisineLbl.textColor = appDelegate.crLightBlue } cell?.layer.borderWidth = 1.0 cell?.layer.borderColor = appDelegate.crLightBlue.cgColor cell?.layer.cornerRadius = 4.0 return cell! } } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if viewIndex == 0 { let dict = self.cuisines[indexPath.row] as! NSDictionary //let id = dict.object(forKey: "cuisineid") as! String // let name = dict.object(forKey: "cuisinename") as! String // // print("cuisinename: \(name)") if selectedCuisines.contains(dict) { let ind = selectedCuisines.firstIndex(of: dict) selectedCuisines.remove(at: ind!) } else { selectedCuisines.append(dict) } print("selectedCuisines: \(selectedCuisines)") cuisineCV.reloadData() } else { if indexPath.row == concerns.count-1 { performSegue(withIdentifier: "AddConcern", sender: nil) } else { let dict = self.concerns[indexPath.row] //let id = dict.object(forKey: "cuisineid") as! String // let name = dict.object(forKey: "cuisinename") as! String // // print("cuisinename: \(name)") if selectedConcerns.contains(dict) { let ind = selectedConcerns.firstIndex(of: dict) selectedConcerns.remove(at: ind!) } else { selectedConcerns.append(dict) } print("selectedConcerns: \(selectedConcerns)") cuisineCV.reloadData() } } } // MARK: Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { } @IBAction func goBack(_ sender: Any) { self.navigationController?.popViewController(animated: true) dismiss(animated: true, completion: nil) } func populateButtonView () { var xPos = 0 let lbls = ["Fruits","Vegetables","Meat","Seafood","Dairy","Nuts, Beans &\nOther Protein"] var width = 65 for i : Int in 0 ..< lbls.count { if i == 5 { width = 80 } else { width = 65 } let doneButton3 = UIButton(frame: CGRect(x: xPos, y: 0, width: width, height: 34)) doneButton3.setTitle(lbls[i], for: .normal) doneButton3.addTarget(self, action: #selector(self.showOptions(_:)), for: UIControlEvents.touchUpInside) doneButton3.restorationIdentifier = "b\(i+1)" doneButton3.accessibilityIdentifier = String(i) buttonScrollview.addSubview(doneButton3) let f = UIFont(name: "Avenir-Book", size: 12.0) doneButton3.titleLabel?.font = f doneButton3.titleLabel?.numberOfLines = 0 doneButton3.setTitleColor(appDelegate.crLightBlue, for: .normal) let view = UIButton(frame: CGRect(x: xPos, y: 36, width: width, height: 2)) view.backgroundColor = appDelegate.crLightBlue buttonScrollview.addSubview(view) buttonUnderscores.append(view) if i > 0 { view.isHidden = true } xPos = xPos + width } buttonScrollview.contentSize = CGSize.init(width: lbls.count*75, height: 42) } // MARK: Tableview func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.selectedList.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell : LikesTableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell")! as! LikesTableViewCell let dict = self.selectedList[(indexPath as NSIndexPath).row] as! NSDictionary let id = dict.object(forKey: "ingredientid") as? String var val = dict.object(forKey: "ingredient") as? String val = val!.replacingOccurrences(of: "\"", with: "", options: .literal, range: nil) val = val!.replacingOccurrences(of: "/", with: "", options: .literal, range: nil) val = val!.replacingOccurrences(of: "\\u2019", with: "'", options: .literal, range: nil) cell.likeBtn?.setBackgroundImage(UIImage.init(named: "gray-up"), for: .normal) cell.dislikeBtn.setBackgroundImage(UIImage.init(named: "gray"), for: .normal) cell.itemLbl?.text = val! cell.selectionStyle = .none let likeRestVal = "\(id!)-up" let dislikeRestVal = "\(id!)-down" cell.likeBtn?.restorationIdentifier = likeRestVal cell.dislikeBtn?.restorationIdentifier = dislikeRestVal if likedItems.contains(likeRestVal) { cell.likeBtn?.setBackgroundImage(UIImage.init(named: "green"), for: .normal) } else if dislikedItems.contains(dislikeRestVal) { cell.dislikeBtn?.setBackgroundImage(UIImage.init(named: "red"), for: .normal) } cell.likeBtn?.addTarget(self, action: #selector(self.likeItem(_:)), for: UIControlEvents.touchUpInside) cell.dislikeBtn?.addTarget(self, action: #selector(self.dislikeItem(_:)), for: UIControlEvents.touchUpInside) currentButtons.append(cell.likeBtn) currentButtons.append(cell.dislikeBtn) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { //println("You selected cell #\(indexPath.row)!") //selectedIem = self.items[(indexPath as NSIndexPath).row] //self.performSegue(withIdentifier: "GoToCategoryCards", sender: self) } @objc func likeItem(_ sender : UIButton) { let btn = sender as UIButton let val = btn.restorationIdentifier if likedItems.contains(val!) { likedItems.remove(val!) btn.setBackgroundImage(UIImage.init(named: "gray-up"), for: .normal) } else { likedItems.add(val!) btn.setBackgroundImage(UIImage.init(named: "green"), for: .normal) if dislikedItems.contains(val!) { dislikedItems.remove(val!) } let prefix = val?.split(separator: "-") for btn1 in self.currentButtons { if btn1.restorationIdentifier == "\(prefix![0])-down" { //print("set to gray") dislikedItems.remove("\(prefix![0])-down") btn1.setBackgroundImage(UIImage.init(named: "gray"), for: .normal) } } } print("likedItems: \(likedItems)") print("dislikedItems: \(dislikedItems)") } @objc func dislikeItem(_ sender : UIButton) { let btn = sender as UIButton let val = btn.restorationIdentifier if dislikedItems.contains(val!) { dislikedItems.remove(val!) btn.setBackgroundImage(UIImage.init(named: "gray"), for: .normal) } else { dislikedItems.add(val!) btn.setBackgroundImage(UIImage.init(named: "red"), for: .normal) if likedItems.contains(val!) { likedItems.remove(val!) } let prefix = val?.split(separator: "-") for btn1 in self.currentButtons { if btn1.restorationIdentifier == "\(prefix![0])-up" { likedItems.remove("\(prefix![0])-up") //print("set to gray") btn1.setBackgroundImage(UIImage.init(named: "gray-up"), for: .normal) } } } print("likedItems: \(likedItems)") print("dislikedItems: \(dislikedItems)") } func showBasicAlert(string:String) { let alert = UIAlertController(title: nil, message: string, preferredStyle: UIAlertControllerStyle.alert) self.present(alert, animated: true, completion: nil) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in switch action.style { case .default: print("default") case .cancel: print("cancel") case .destructive: print("destructive") } })) } func populate () { concerns.append( ["name" : "Diabetic", "image" : UIImage.init(named: "noSugarBlue")!, "image2" : UIImage.init(named: "noSugarWhite")!,"concernid": "1"]) concerns.append( ["name" : "Dairy Allergy", "image" : UIImage.init(named: "dairyAllergyBlue")!, "image2" : UIImage.init(named: "dairyAllergyWhite")!,"concernid": "2"]) concerns.append( ["name" : "Egg Allergy", "image" : UIImage.init(named: "eggAllergyBlue")!, "image2" : UIImage.init(named: "eggAllergyWhite")!,"concernid": "3"]) concerns.append( ["name" : "Fish Allergy", "image" : UIImage.init(named: "fishAllergyBlue")!, "image2" : UIImage.init(named: "fishAllergyWhite")!,"concernid": "4"]) concerns.append( ["name" : "Flexitarian", "image" : UIImage.init(named: "flexitarianBlue")!, "image2" : UIImage.init(named: "flexitarianWhite")!,"concernid": "5"]) concerns.append( ["name" : "Gluten Intolerance", "image" : UIImage.init(named: "glutenIntoleranceBlue")!, "image2" : UIImage.init(named: "glutenIntoleranceWhite")!,"concernid": "6"]) concerns.append( ["name" : "Halal", "image" : UIImage.init(named: "halalBlue")!, "image2" : UIImage.init(named: "halalWhite")!,"concernid": "7"]) concerns.append( ["name" : "Heart Healthy", "image" : UIImage.init(named: "heartHealthyBlue")!, "image2" : UIImage.init(named: "heartHealthyWhite")!,"concernid": "8"]) concerns.append( ["name" : "Keto", "image" : UIImage.init(named: "ketoBlue")!, "image2" : UIImage.init(named: "ketoWhite")!,"concernid": "9"]) concerns.append( ["name" : "Kosher", "image" : UIImage.init(named: "kosherBlue")!, "image2" : UIImage.init(named: "kosherWhite")!,"concernid": "10"]) concerns.append( ["name" : "Lacto Vegitarian", "image" : UIImage.init(named: "lactoVegetarianBlue")!, "image2" : UIImage.init(named: "lactoVegetarianWhite")!,"concernid": "11"]) concerns.append( ["name" : "Lactose Intolerant", "image" : UIImage.init(named: "lactoseIntoleranceBlue")!, "image2" : UIImage.init(named: "lactoseIntoleranceWhite")!,"concernid": "12"]) concerns.append( ["name" : "Low Carb", "image" : UIImage.init(named: "lowCarbBlue")!, "image2" : UIImage.init(named: "lowCarbWhite")!,"concernid": "13"]) concerns.append( ["name" : "Low Fat", "image" : UIImage.init(named: "lowFatBlue")!, "image2" : UIImage.init(named: "lowFatWhite")!,"concernid": "14"]) concerns.append( ["name" : "Low Sodium", "image" : UIImage.init(named: "lowSodiumBlue")!, "image2" : UIImage.init(named: "lowSodiumWhite")!,"concernid": "15"]) concerns.append( ["name" : "Low Sugar", "image" : UIImage.init(named: "lowSugarBlue")!, "image2" : UIImage.init(named: "lowSugarWhite")!,"concernid": "16"]) concerns.append( ["name" : "Ovo Vegetarian", "image" : UIImage.init(named: "ovoVegetarianBlue")!, "image2" : UIImage.init(named: "ovoVegetarianWhite")!,"concernid": "17"]) concerns.append( ["name" : "Paleo", "image" : UIImage.init(named: "paleoBlue")!, "image2" : UIImage.init(named: "paleoWhite")!,"concernid": ""]) concerns.append( ["name" : "Peanut Allergy", "image" : UIImage.init(named: "peanutAllergyBlue")!, "image2" : UIImage.init(named: "peanutAllergyWhite")!,"concernid": "18"]) concerns.append( ["name" : "Pescetarian", "image" : UIImage.init(named: "pescetarianBlue")!, "image2" : UIImage.init(named: "pescetarianWhite")!,"concernid": "19"]) concerns.append( ["name" : "Shellfish Allergy", "image" : UIImage.init(named: "shellfishAllergyBlue")!, "image2" : UIImage.init(named: "shellfishAllergyWhite")!,"concernid": "20"]) concerns.append( ["name" : "Soy Allergy", "image" : UIImage.init(named: "soyAllergyBlue")!, "image2" : UIImage.init(named: "soyAllergyWhite")!,"concernid": "21"]) concerns.append( ["name" : "Vegan", "image" : UIImage.init(named: "veganBlue")!, "image2" : UIImage.init(named: "veganWhite")!,"concernid": ""]) concerns.append( ["name" : "Vegetarian", "image" : UIImage.init(named: "vegetarianBlue")!, "image2" : UIImage.init(named: "vegetarianWhite")!,"concernid": "22"]) concerns.append( ["name" : "Wheat Allergy", "image" : UIImage.init(named: "wheatAllergyBlue")!, "image2" : UIImage.init(named: "wheatAllergyWhite")!,"concernid": "23"]) concerns.append( ["name" : "Other", "image" : UIImage.init(named: "add")!, "image2" : UIImage.init(named: "add")!,"concernid": "24"]) cuisineCV.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } <file_sep>// // RecipeSearch.swift // AIScribe // // Created by <NAME> on 6/8/18. // Copyright © 2018 RT. All rights reserved. // import UIKit class RecipeSearch: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate { let appDelegate = UIApplication.shared.delegate as! AppDelegate @IBOutlet weak var headerLbl: UILabel! @IBOutlet weak var recipeCV: UICollectionView! var recipes = [NSDictionary]() override func viewDidLoad() { super.viewDidLoad() recipeCV.delegate = self recipeCV.dataSource = self // cuisines.add("Afgan") // cuisines.add("American") // cuisines.add("Argentinian") // cuisines.add("Belgian") // cuisines.add("Brazilian") // cuisines.add("Cajun") //debug() //recipeCV.reloadData() } func debug () { var dict : NSMutableDictionary = ["recipename" : "Pistachio-Crusted Chicken and Quinoa Salad", "category" : "","source" : "Hello Fresh","preptime" : "40 mins","calories" : "400","imagename" : "pistachio"] recipes.append(dict) dict = ["recipename" : "Mixed Mushroom Risotto", "category" : "1","source" : "Blue Apron","preptime" : "60 mins","calories" : "300","imagename" : "risotto"] recipes.append(dict) dict = ["recipename" : "Smoky Beluga Lentils", "category" : "2","source" : "Blue Apron","preptime" : "20 mins","calories" : "350","imagename" : "lentils"] recipes.append(dict) recipeCV.reloadData() } @IBAction func next(_ sender: Any) {} // MARK: - UICollectionViewDataSource, UICollectionViewDelegate methods func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let kWhateverHeightYouWant = 190 return CGSize.init(width: 600, height: CGFloat(kWhateverHeightYouWant)) } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.recipes.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { //chanage cell width to 40% of screen let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as? RecipesCollectionViewCell let dict = recipes[indexPath.row] cell?.frame.size = CGSize.init(width: recipeCV.frame.width * 0.5, height: 292) //Randall. check this cell?.recipeIV.image = UIImage.init(named: (dict.object(forKey: "imagename") as? String)!) cell?.headerLbl.text = dict.object(forKey: "recipename") as? String cell?.infoLbl.text = "\(dict.object(forKey: "preptime") as! String) • \(dict.object(forKey: "calories") as! String)" let attributedString = NSMutableAttributedString(string: "Source: \((dict.object(forKey: "source") as? String)!)", attributes: [ .font: UIFont(name: "Avenir-Book", size: 13.0)!, .foregroundColor: appDelegate.crGray ]) attributedString.addAttribute(.font, value: UIFont(name: "Avenir-Heavy", size: 13.0)!, range: NSRange(location: 0, length: 7)) cell?.sourceLbl.attributedText = attributedString // if selectedCuisines.contains(string) // { // cell?.cuisineLbl.backgroundColor = appDelegate.crLightBlue // cell?.cuisineLbl.textColor = UIColor.white // } // else // { // cell?.cuisineLbl.backgroundColor = UIColor.white // cell?.cuisineLbl.textColor = appDelegate.crLightBlue // } //cell?.statusLbl.isHidden = true return cell! } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let recipe = recipes[indexPath.row] print("recipe: \(recipe)") // if selectedCuisines.contains(cuisine) // { // selectedCuisines.remove(cuisine) // } // else // { // selectedCuisines.add(cuisine) // } //print("selectedCuisines: \(selectedCuisines)") recipeCV.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } <file_sep>// // RecipesCollectionViewCell.swift // AIScribe // // Created by <NAME> on 6/8/18. // Copyright © 2018 RT. All rights reserved. // import UIKit class RecipesCollectionViewCell: UICollectionViewCell { @IBOutlet weak var recipeIV: UIImageView! @IBOutlet weak var starsIV: UIImageView! @IBOutlet weak var headerLbl: UILabel! @IBOutlet weak var infoLbl: UILabel! @IBOutlet weak var sourceLbl: UILabel! @IBOutlet weak var favoriteBtn: UIButton! var isFavorite : Bool? @IBOutlet weak var videoBtn: UIButton! var videoURL: String! } <file_sep>// // FilterSearch.swift // AIScribe // // Created by <NAME> on 6/8/18. // Copyright © 2018 RT. All rights reserved. // import UIKit class FilterSearch: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UITableViewDelegate, UITableViewDataSource{ let appDelegate = UIApplication.shared.delegate as! AppDelegate @IBOutlet weak var dietFilterView: UIView! var diets = [NSDictionary]() var selectedDiets = NSMutableArray() var meals = [NSDictionary]() var selectedMeals = NSMutableArray() var selectedCuisines = NSMutableArray() var selectedIngredients = NSMutableArray() var currentItemArray = NSMutableArray() var ingredients = [NSDictionary]() var cuisines = [NSDictionary]() @IBOutlet weak var cuisineCV: UICollectionView! @IBOutlet weak var mealsCV: UICollectionView! var selectedCategory : String? @IBOutlet weak var afghanBtn: UIButton! @IBOutlet weak var americanBtn: UIButton! @IBOutlet weak var argentinianBtn: UIButton! @IBOutlet weak var vegBtn: UIButton! @IBOutlet weak var chickenBtn: UIButton! @IBOutlet weak var pastaBtn: UIButton! var cuisineButtons = [UIButton]() var ingredientButtons = [UIButton]() @IBOutlet weak var dietHeight: NSLayoutConstraint! @IBOutlet weak var dietViewHeight: NSLayoutConstraint! @IBOutlet weak var cuisineTable: UITableView! @IBOutlet weak var ingredientTable: UITableView! @IBOutlet weak var cuisineHeight: NSLayoutConstraint! @IBOutlet weak var ingredientHeight: NSLayoutConstraint! @IBOutlet weak var sv: UIScrollView! @IBOutlet weak var svContentView: UIView! @IBOutlet weak var resultsLbl: UILabel! @IBOutlet weak var resultsView: UIView! @IBOutlet weak var resultsBtn: UIButton! var resultsCount : Int? // MARK: - viewDidLoad override func viewDidLoad() { super.viewDidLoad() // cuisineButtons = [afghanBtn,americanBtn,argentinianBtn] // ingredientButtons = [vegBtn,chickenBtn,pastaBtn] cuisineCV.delegate = self cuisineCV.dataSource = self mealsCV.delegate = self mealsCV.dataSource = self cuisineTable.delegate = self cuisineTable.dataSource = self // ingredientTable.delegate = self // ingredientTable.dataSource = self cuisineTable.tableFooterView = UIView() //ingredientTable.tableFooterView = UIView() cuisineTable.separatorStyle = .none //ingredientTable.separatorStyle = .none resultsView.isHidden = true resultsLbl.isHidden = true resultsBtn.isHidden = true resultsCount = selectedCuisines.count + selectedIngredients.count + selectedMeals.count + selectedDiets.count if resultsCount! > 0 { resultsLbl.text = "\(resultsCount!) results" resultsView.isHidden = false resultsLbl.isHidden = false resultsBtn.isHidden = false } //debug() //populateFields() getCuisines() getMeals() //getDiets() getAllConcerns() NotificationCenter.default.addObserver( self, selector: #selector(updateFilterNotification), name: NSNotification.Name(rawValue: "updateFilter"), object: nil) } override func viewDidAppear(_ animated: Bool) { // sv.contentSize = CGSize.init(width: sv.frame.width, height: 1500) // svContentView.setNeedsLayout() //svContentView.updateConstraints() //svContentView.needsUpdateConstraints() //svContentView.setNeedsLayout() //svContentView.frame = CGRect.init(x:0, y:0, width: sv.frame.width, height: 2500) //svContentView.setNeedsDisplay() } func populateFields () { for btn in cuisineButtons { if selectedCuisines.contains(btn.restorationIdentifier!) { //btn.backgroundColor = .red btn.setBackgroundImage(UIImage.init(named: "selected"), for: .normal) } else { //btn.backgroundColor = .gray btn.setBackgroundImage(UIImage.init(named: "unselected"), for: .normal) } } for btn in ingredientButtons { if selectedIngredients.contains(btn.restorationIdentifier!) { btn.setBackgroundImage(UIImage.init(named: "selected"), for: .normal) //btn.backgroundColor = .red } else { btn.setBackgroundImage(UIImage.init(named: "unselected"), for: .normal) //btn.backgroundColor = .gray } } } // MARK: - Notifications @objc func updateFilterNotification (notification: NSNotification) { print("port: \(notification.object)") if selectedCategory == "Diets" { selectedDiets = notification.object as! NSMutableArray cuisineCV.reloadData() } else if selectedCategory == "Cuisines" { selectedCuisines = notification.object as! NSMutableArray for btn in cuisineButtons { if selectedCuisines.contains(btn.restorationIdentifier!) { btn.setBackgroundImage(UIImage.init(named: "selected"), for: .normal) //btn.setBackgroundImage(UIImage.init(named: "<#T##String#>"), for: .normal) } else { //btn.backgroundColor = .gray btn.setBackgroundImage(UIImage.init(named: "unselected"), for: .normal) } } } else if selectedCategory == "Ingredients" { selectedIngredients = notification.object as! NSMutableArray for btn in ingredientButtons { if selectedIngredients.contains(btn.restorationIdentifier!) { //btn.backgroundColor = .red btn.setBackgroundImage(UIImage.init(named: "selected"), for: .normal) } else { //btn.backgroundColor = .gray btn.setBackgroundImage(UIImage.init(named: "unselected"), for: .normal) } } } else if selectedCategory == "Meals" { selectedMeals = notification.object as! NSMutableArray mealsCV.reloadData() } } // MARK: - Actions @IBAction func clearResults(_ sender: Any) { resultsLbl.text = "" resultsView.isHidden = true resultsLbl.isHidden = true resultsBtn.isHidden = true selectedCuisines.removeAllObjects() selectedIngredients.removeAllObjects() selectedMeals.removeAllObjects() selectedDiets.removeAllObjects() cuisineTable.reloadData() cuisineCV.reloadData() mealsCV.reloadData() } @IBAction func selectMealOption(_ sender: Any) { let btn = sender as! UIButton if selectedMeals.contains(btn.restorationIdentifier!) { btn.setBackgroundImage(UIImage.init(named: "unselected"), for: .normal) //btn.backgroundColor = .gray selectedMeals.remove(btn.restorationIdentifier!) } else { btn.setBackgroundImage(UIImage.init(named: "selected"), for: .normal) //btn.backgroundColor = .red selectedMeals.add(btn.restorationIdentifier!) } } @IBAction func selectCuisineOption(_ sender: Any) { let btn = sender as! UIButton if selectedCuisines.contains(btn.restorationIdentifier!) { //btn.backgroundColor = .gray btn.setBackgroundImage(UIImage.init(named: "unselected"), for: .normal) selectedCuisines.remove(btn.restorationIdentifier!) } else { btn.setBackgroundImage(UIImage.init(named: "selected"), for: .normal) //btn.backgroundColor = .red selectedCuisines.add(btn.restorationIdentifier!) } } @IBAction func selectIngredientOption(_ sender: Any) { let btn = sender as! UIButton if selectedIngredients.contains(btn.restorationIdentifier!) { btn.setBackgroundImage(UIImage.init(named: "unselected"), for: .normal) //btn.backgroundColor = .gray selectedIngredients.remove(btn.restorationIdentifier!) } else { btn.setBackgroundImage(UIImage.init(named: "selected"), for: .normal) //btn.backgroundColor = .red selectedIngredients.add(btn.restorationIdentifier!) } } @IBAction func viewMoreCuisine(_ sender: Any) { let btn = sender as! UIButton selectedCategory = btn.restorationIdentifier! performSegue(withIdentifier: "ShowMore", sender: nil) } @IBAction func viewMoreIngredients(_ sender: Any) { let btn = sender as! UIButton selectedCategory = btn.restorationIdentifier! performSegue(withIdentifier: "ShowMore", sender: nil) } @IBAction func viewMoreDiet(_ sender: Any) { let btn = sender as! UIButton selectedCategory = btn.restorationIdentifier! if dietHeight.constant == 800 { dietHeight.constant = 170 btn.setTitle("+ MORE DIET", for: .normal) } else { dietHeight.constant = 800 btn.setTitle("- LESS DIET", for: .normal) } //performSegue(withIdentifier: "ShowMore", sender: nil) } @IBAction func moreCuisine(_ sender: Any) { let btn = sender as! UIButton let newHeight = CGFloat(cuisines.count * 30) if cuisineHeight.constant == newHeight { cuisineHeight.constant = 170 btn.setTitle("+ MORE CUISINE", for: .normal) } else { cuisineHeight.constant = newHeight btn.setTitle("- LESS CUISINE", for: .normal) } } @IBAction func moreIngredients(_ sender: Any) { ingredientHeight.constant = 1000 } @IBAction func applyFilters(_ sender: Any) { let dict : NSDictionary = ["selectedMeals" : selectedMeals, "selectedIngredients" : selectedIngredients, "selectedCuisines" : selectedCuisines, "selectedDiets" : selectedDiets] NotificationCenter.default.post(name: Notification.Name("applyFilters"), object: dict) self.navigationController?.popViewController(animated: true) self.dismiss(animated: true, completion: nil) } @IBAction func cancel(_ sender: Any) { self.navigationController?.popViewController(animated: true) self.dismiss(animated: true, completion: nil) } // MARK: - Collectionview func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let kWhateverHeightYouWant = 190 return CGSize.init(width: 600, height: CGFloat(kWhateverHeightYouWant)) } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if collectionView.restorationIdentifier == "diet" { return self.diets.count } else { return self.meals.count } } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as? CuisinesCollectionviewCell var theDict : NSDictionary? var id = "" if collectionView.restorationIdentifier == "diet" { theDict = self.diets[indexPath.row] id = theDict?.object(forKey: "concernid") as! String } else { theDict = self.meals[indexPath.row] id = theDict?.object(forKey: "mealid") as! String } let string = theDict?.object(forKey: "name") as! String let img = theDict?.object(forKey: "image") as! UIImage let img2 = theDict?.object(forKey: "image2") as! UIImage cell?.cuisineLbl.text = string cell?.iconIV.image = img if collectionView.restorationIdentifier == "diet" { if selectedDiets.contains(id) { cell?.backgroundColor = appDelegate.crLightBlue cell?.cuisineLbl.textColor = UIColor.white cell?.iconIV.image = img2 } else { cell?.backgroundColor = UIColor.white cell?.cuisineLbl.textColor = appDelegate.crLightBlue } } else { if selectedMeals.contains(id) { cell?.backgroundColor = appDelegate.crLightBlue cell?.cuisineLbl.textColor = UIColor.white cell?.iconIV.image = img2 } else { cell?.backgroundColor = UIColor.white cell?.cuisineLbl.textColor = appDelegate.crLightBlue } } cell?.layer.borderWidth = 1.0 cell?.layer.borderColor = appDelegate.crLightBlue.cgColor cell?.layer.cornerRadius = 4.0 return cell! } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if collectionView.restorationIdentifier == "diet" { let dietDict = diets[indexPath.row] as NSDictionary let dietid = dietDict.object(forKey: "concernid") as! String print("dietid: \(dietid)") if selectedDiets.contains(dietid) { selectedDiets.remove(dietid) } else { selectedDiets.add(dietid) } print("selectedDiets: \(selectedDiets)") cuisineCV.reloadData() } else { let mealDict = meals[indexPath.row] as NSDictionary let mealid = mealDict.object(forKey: "mealid") as! String print("meal: \(mealid)") if selectedMeals.contains(mealid) { selectedMeals.remove(mealid) } else { selectedMeals.add(mealid) } print("selectedMeals: \(selectedMeals)") mealsCV.reloadData() } } // MARK: - Data func debug () { diets.append( ["name" : "Diabetic", "image" : UIImage.init(named: "noSugarBlue")!, "image2" : UIImage.init(named: "noSugarWhite")!]) diets.append( ["name" : "Dairy Allergy", "image" : UIImage.init(named: "dairyAllergyBlue")!, "image2" : UIImage.init(named: "dairyAllergyWhite")!]) diets.append( ["name" : "Egg Allergy", "image" : UIImage.init(named: "eggAllergyBlue")!, "image2" : UIImage.init(named: "eggAllergyWhite")!]) diets.append( ["name" : "Fish Allergy", "image" : UIImage.init(named: "fishAllergyBlue")!, "image2" : UIImage.init(named: "fishAllergyWhite")!]) diets.append( ["name" : "Flexitarian", "image" : UIImage.init(named: "flexitarianBlue")!, "image2" : UIImage.init(named: "flexitarianWhite")!]) diets.append( ["name" : "Gluten Intolerance", "image" : UIImage.init(named: "glutenIntoleranceBlue")!, "image2" : UIImage.init(named: "glutenIntoleranceWhite")!]) meals.append( ["name" : "Breakfast", "image" : UIImage.init(named: "noSugarBlue")!, "image2" : UIImage.init(named: "noSugarWhite")!]) meals.append( ["name" : "Lunch", "image" : UIImage.init(named: "dairyAllergyBlue")!, "image2" : UIImage.init(named: "dairyAllergyWhite")!]) meals.append( ["name" : "Snack", "image" : UIImage.init(named: "eggAllergyBlue")!, "image2" : UIImage.init(named: "eggAllergyWhite")!]) meals.append( ["name" : "Dinner", "image" : UIImage.init(named: "fishAllergyBlue")!, "image2" : UIImage.init(named: "fishAllergyWhite")!]) meals.append( ["name" : "Dessert", "image" : UIImage.init(named: "flexitarianBlue")!, "image2" : UIImage.init(named: "flexitarianWhite")!]) cuisines.append( ["name" : "Afgan", "id" : "1"]) ingredients.append( ["name" : "Vegetables", "id" : "1"]) // diets.append( ["name" : "Halal", "image" : UIImage.init(named: "halalBlue")!, "image2" : UIImage.init(named: "halalWhite")!]) // diets.append( ["name" : "Heart Healthy", "image" : UIImage.init(named: "heartHealthyBlue")!, "image2" : UIImage.init(named: "heartHealthyWhite")!]) // diets.append( ["name" : "Keto", "image" : UIImage.init(named: "ketoBlue")!, "image2" : UIImage.init(named: "ketoWhite")!]) // diets.append( ["name" : "Kosher", "image" : UIImage.init(named: "kosherBlue")!, "image2" : UIImage.init(named: "kosherWhite")!]) // diets.append( ["name" : "Lacto Vegitarian", "image" : UIImage.init(named: "lactoVegetarianBlue")!, "image2" : UIImage.init(named: "lactoVegetarianWhite")!]) // diets.append( ["name" : "Lactose Intolerant", "image" : UIImage.init(named: "lactoseIntoleranceBlue")!, "image2" : UIImage.init(named: "lactoseIntoleranceWhite")!]) // diets.append( ["name" : "Low Carb", "image" : UIImage.init(named: "lowCarbBlue")!, "image2" : UIImage.init(named: "lowCarbWhite")!]) // diets.append( ["name" : "Low Fat", "image" : UIImage.init(named: "lowFatBlue")!, "image2" : UIImage.init(named: "lowFatWhite")!]) // diets.append( ["name" : "Low Sodium", "image" : UIImage.init(named: "lowSodiumBlue")!, "image2" : UIImage.init(named: "lowSodiumWhite")!]) // diets.append( ["name" : "Low Sugar", "image" : UIImage.init(named: "lowSugarBlue")!, "image2" : UIImage.init(named: "lowSugarWhite")!]) // diets.append( ["name" : "Ovo Vegetarian", "image" : UIImage.init(named: "ovoVegetarianBlue")!, "image2" : UIImage.init(named: "ovoVegetarianWhite")!]) // diets.append( ["name" : "Paleo", "image" : UIImage.init(named: "paleoBlue")!, "image2" : UIImage.init(named: "paleoWhite")!]) // diets.append( ["name" : "Peanut Allergy", "image" : UIImage.init(named: "peanutAllergyBlue")!, "image2" : UIImage.init(named: "peanutAllergyWhite")!]) // diets.append( ["name" : "Pescetarian", "image" : UIImage.init(named: "pescetarianBlue")!, "image2" : UIImage.init(named: "pescetarianWhite")!]) // diets.append( ["name" : "Shellfish Allergy", "image" : UIImage.init(named: "shellfishAllergyBlue")!, "image2" : UIImage.init(named: "shellfishAllergyWhite")!]) // diets.append( ["name" : "Soy Allergy", "image" : UIImage.init(named: "soyAllergyBlue")!, "image2" : UIImage.init(named: "soyAllergyWhite")!]) // diets.append( ["name" : "Vegan", "image" : UIImage.init(named: "veganBlue")!, "image2" : UIImage.init(named: "veganWhite")!]) // diets.append( ["name" : "Vegetarian", "image" : UIImage.init(named: "vegetarianBlue")!, "image2" : UIImage.init(named: "vegetarianWhite")!]) // diets.append( ["name" : "<NAME>", "image" : UIImage.init(named: "wheatAllergyBlue")!, "image2" : UIImage.init(named: "wheatAllergyWhite")!]) cuisineCV.reloadData() mealsCV.reloadData() ingredientTable.reloadData() cuisineTable.reloadData() } func getAllConcerns() { //displayItems.removeAll() print("getAllConcerns") let dataString = "concernsData" let urlString = "\(appDelegate.serverDestination!)getAllConcerns.php" let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" //appDelegate.userid = "22" let paramString = "devStatus=\(appDelegate.devStage!)&mobile=true" print("urlString: \(urlString)") print("paramString: \(paramString)") request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let session = URLSession.shared session.dataTask(with: request) {data, response, err in do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary print("concerns jsonResult: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary if dataDict[dataString]! is NSNull { print("no data") DispatchQueue.main.sync(execute: { //self.recipeStatusTV.isHidden = false self.cuisineCV.reloadData() }) } else { let uploadData : NSMutableArray = (dataDict[dataString]! as! NSArray).mutableCopy() as! NSMutableArray let recipes1 = uploadData as! [NSDictionary] var hasData = false if (recipes1.count > 0) { hasData = true for dict2 in recipes1 { let name = dict2.object(forKey: "concernname" as String)! let image = dict2.object(forKey: "imageblue" as String)! let image2 = dict2.object(forKey: "imagewhite" as String)! let concernid = dict2.object(forKey: "concernid" as String)! self.diets.append( ["name" : name, "image" : UIImage.init(named: image as! String)!, "image2" : UIImage.init(named: image2 as! String)!,"concernid": concernid]) } DispatchQueue.main.sync(execute: { if hasData == true { self.cuisineCV.reloadData() } else { print("no data") //self.noResultsMain.isHidden = false self.cuisineCV.reloadData() } }) } else { DispatchQueue.main.sync(execute: { self.cuisineCV.reloadData() //self.noResultsMain.isHidden = false }) } } } catch let err as NSError { print("error: \(err.description)") } }.resume() } func getDiets () { diets.append( ["name" : "Diabetic", "image" : UIImage.init(named: "noSugarBlue")!, "image2" : UIImage.init(named: "noSugarWhite")!,"concernid": "1"]) diets.append( ["name" : "Dairy Allergy", "image" : UIImage.init(named: "dairyAllergyBlue")!, "image2" : UIImage.init(named: "dairyAllergyWhite")!,"concernid": "2"]) diets.append( ["name" : "Egg Allergy", "image" : UIImage.init(named: "eggAllergyBlue")!, "image2" : UIImage.init(named: "eggAllergyWhite")!,"concernid": "3"]) diets.append( ["name" : "Fish Allergy", "image" : UIImage.init(named: "fishAllergyBlue")!, "image2" : UIImage.init(named: "fishAllergyWhite")!,"concernid": "4"]) diets.append( ["name" : "Flexitarian", "image" : UIImage.init(named: "flexitarianBlue")!, "image2" : UIImage.init(named: "flexitarianWhite")!,"concernid": "5"]) diets.append( ["name" : "Gluten Intolerance", "image" : UIImage.init(named: "glutenIntoleranceBlue")!, "image2" : UIImage.init(named: "glutenIntoleranceWhite")!,"concernid": "6"]) diets.append( ["name" : "Halal", "image" : UIImage.init(named: "halalBlue")!, "image2" : UIImage.init(named: "halalWhite")!,"concernid": "7"]) diets.append( ["name" : "Heart Healthy", "image" : UIImage.init(named: "heartHealthyBlue")!, "image2" : UIImage.init(named: "heartHealthyWhite")!,"concernid": "8"]) diets.append( ["name" : "Keto", "image" : UIImage.init(named: "ketoBlue")!, "image2" : UIImage.init(named: "ketoWhite")!,"concernid": "9"]) diets.append( ["name" : "Kosher", "image" : UIImage.init(named: "kosherBlue")!, "image2" : UIImage.init(named: "kosherWhite")!,"concernid": "10"]) diets.append( ["name" : "Lacto Vegitarian", "image" : UIImage.init(named: "lactoVegetarianBlue")!, "image2" : UIImage.init(named: "lactoVegetarianWhite")!,"concernid": "11"]) diets.append( ["name" : "Lactose Intolerant", "image" : UIImage.init(named: "lactoseIntoleranceBlue")!, "image2" : UIImage.init(named: "lactoseIntoleranceWhite")!,"concernid": "12"]) diets.append( ["name" : "<NAME>", "image" : UIImage.init(named: "lowCarbBlue")!, "image2" : UIImage.init(named: "lowCarbWhite")!,"concernid": "13"]) diets.append( ["name" : "Low Fat", "image" : UIImage.init(named: "lowFatBlue")!, "image2" : UIImage.init(named: "lowFatWhite")!,"concernid": "14"]) diets.append( ["name" : "Low Sodium", "image" : UIImage.init(named: "lowSodiumBlue")!, "image2" : UIImage.init(named: "lowSodiumWhite")!,"concernid": "15"]) diets.append( ["name" : "Low Sugar", "image" : UIImage.init(named: "lowSugarBlue")!, "image2" : UIImage.init(named: "lowSugarWhite")!,"concernid": "16"]) diets.append( ["name" : "Ovo Vegetarian", "image" : UIImage.init(named: "ovoVegetarianBlue")!, "image2" : UIImage.init(named: "ovoVegetarianWhite")!,"concernid": "17"]) diets.append( ["name" : "Paleo", "image" : UIImage.init(named: "paleoBlue")!, "image2" : UIImage.init(named: "paleoWhite")!,"concernid": ""]) diets.append( ["name" : "Peanut Allergy", "image" : UIImage.init(named: "peanutAllergyBlue")!, "image2" : UIImage.init(named: "peanutAllergyWhite")!,"concernid": "18"]) diets.append( ["name" : "Pescetarian", "image" : UIImage.init(named: "pescetarianBlue")!, "image2" : UIImage.init(named: "pescetarianWhite")!,"concernid": "19"]) diets.append( ["name" : "Shellfish Allergy", "image" : UIImage.init(named: "shellfishAllergyBlue")!, "image2" : UIImage.init(named: "shellfishAllergyWhite")!,"concernid": "20"]) diets.append( ["name" : "Soy Allergy", "image" : UIImage.init(named: "soyAllergyBlue")!, "image2" : UIImage.init(named: "soyAllergyWhite")!,"concernid": "21"]) diets.append( ["name" : "Vegan", "image" : UIImage.init(named: "veganBlue")!, "image2" : UIImage.init(named: "veganWhite")!,"concernid": ""]) diets.append( ["name" : "Vegetarian", "image" : UIImage.init(named: "vegetarianBlue")!, "image2" : UIImage.init(named: "vegetarianWhite")!,"concernid": "22"]) diets.append( ["name" : "Wheat Allergy", "image" : UIImage.init(named: "wheatAllergyBlue")!, "image2" : UIImage.init(named: "wheatAllergyWhite")!,"concernid": "23"]) diets.append( ["name" : "Other", "image" : UIImage.init(named: "add")!, "image2" : UIImage.init(named: "add")!,"concernid": "24"]) cuisineCV.reloadData() } func getMeals() { meals.append( ["name" : "Breakfast", "image" : UIImage.init(named: "noSugarBlue")!, "image2" : UIImage.init(named: "noSugarWhite")!,"mealid" : "1"]) meals.append( ["name" : "Lunch", "image" : UIImage.init(named: "dairyAllergyBlue")!, "image2" : UIImage.init(named: "dairyAllergyWhite")!,"mealid" : "2"]) meals.append( ["name" : "Snack", "image" : UIImage.init(named: "eggAllergyBlue")!, "image2" : UIImage.init(named: "eggAllergyWhite")!,"mealid" : "3"]) meals.append( ["name" : "Dinner", "image" : UIImage.init(named: "fishAllergyBlue")!, "image2" : UIImage.init(named: "fishAllergyWhite")!,"mealid" : "4"]) meals.append( ["name" : "Dessert", "image" : UIImage.init(named: "flexitarianBlue")!, "image2" : UIImage.init(named: "flexitarianWhite")!,"mealid" : "5"]) mealsCV.reloadData() } // MARK: - Webservice func getCuisines() { print("getMyCuisines") let dataString = "cuisineData" let urlString = "\(appDelegate.serverDestination!)getCuisines.php" let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" let paramString = "register=true&devStatus=\(appDelegate.devStage!)&mobile=true" print("urlString: \(urlString)") print("paramString: \(paramString)") request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let session = URLSession.shared session.dataTask(with: request) {data, response, err in do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary print("cuisines jsonResult: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary if dataDict[dataString]! is NSNull { print("no data") DispatchQueue.main.sync(execute: { self.cuisineCV.isHidden = true //self.recipeStatusTV.isHidden = false }) } else { let uploadData : NSMutableArray = (dataDict[dataString]! as! NSArray).mutableCopy() as! NSMutableArray self.cuisines = uploadData as! [NSDictionary] var hasData = false if (self.cuisines.count > 0) { hasData = true // for dict in recipes1 // { // let dict2 = dict.mutableCopy() as! NSMutableDictionary // // self.cuisines.add(dict2) // } DispatchQueue.main.sync(execute: { if hasData == true { self.cuisineTable.reloadData() } else { print("no data") self.cuisineCV.isHidden = true //self.noResultsMain.isHidden = false } }) } else { DispatchQueue.main.sync(execute: { //self.noResultsMain.isHidden = false }) } } } catch let err as NSError { print("error: \(err.description)") } }.resume() } // MARK: Tableview func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if (editingStyle == UITableViewCellEditingStyle.delete) { // handle delete (by removing the data from your array and updating the tableview) // removeObject = currentItemArray[indexPath.row] // // currentItemArray.remove(at: indexPath.row) // itemArray.removeAll(where: { $0.signalid == removeObject?.signalid }) // // tableView.deleteRows(at: [indexPath], with: .fade) // // removeSignal() } } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 30 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if tableView.restorationIdentifier == "ingredients" { return self.ingredients.count } else { return self.cuisines.count } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell")! as! FriendRequestCell cell.selectionStyle = .none if tableView.restorationIdentifier == "ingredients" { let dict = ingredients[(indexPath as NSIndexPath).row] let symbol = dict.object(forKey: "name") as! String cell.nameLbl!.text = symbol if selectedIngredients.contains(dict) { cell.friendIV.image = UIImage.init(named: "selected") } else { cell.friendIV.image = UIImage.init(named: "unselected") } } else { let dict = cuisines[(indexPath as NSIndexPath).row] let symbol = dict.object(forKey: "cuisinename") as! String let cuisineid = dict.object(forKey: "cuisineid") as! String cell.nameLbl!.text = symbol if selectedCuisines.contains(cuisineid) { cell.friendIV.image = UIImage.init(named: "selected") } else { cell.friendIV.image = UIImage.init(named: "unselected") } } return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if tableView.restorationIdentifier == "ingredients" { let dict = ingredients[(indexPath as NSIndexPath).row] if selectedIngredients.contains(dict) { selectedIngredients.remove(dict) } else { selectedIngredients.add(dict) } ingredientTable.reloadData() } else { let dict = cuisines[(indexPath as NSIndexPath).row] let cuisineid = dict.object(forKey: "cuisineid") as! String if selectedCuisines.contains(cuisineid) { selectedCuisines.remove(cuisineid) } else { selectedCuisines.add(cuisineid) } print("selectedCuisines: \(selectedCuisines)") cuisineTable.reloadData() } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "ShowMore" { let destination = segue.destination as! ShowMoreFilterOptions destination.category = selectedCategory destination.selectedCuisines = selectedCuisines destination.selectedIngredients = selectedIngredients destination.selectedMeals = selectedMeals destination.selectedDiets = selectedDiets } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } <file_sep>// // CreateCustomModel.swift // AIScribe // // Created by <NAME> on 7/22/19. // Copyright © 2019 RT. All rights reserved. // import UIKit class CreateCustomModel: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate, UITextViewDelegate { let appDelegate = UIApplication.shared.delegate as! AppDelegate var selectedModel: ModelItem? var languageList = NSMutableArray() var selectedLanguage : NSDictionary? var selectedCode : String? @IBOutlet weak var activityView: UIActivityIndicatorView! @IBOutlet weak var modelNameTxt: UITextField! @IBOutlet weak var languageTxt: UITextField! @IBOutlet weak var transcriptionTV: UITextView! @IBOutlet weak var saveBtn: UIButton! @IBOutlet weak var showPopupBtn: UIButton! @IBOutlet weak var headerLbl: UILabel! @IBOutlet weak var languagePicker: UIPickerView! @IBOutlet weak var languagePopup: UIView! @IBOutlet weak var modelNameLbl: UILabel! @IBOutlet weak var modelLblHeight: NSLayoutConstraint! @IBOutlet weak var languageLbl: UILabel! @IBOutlet weak var languageLblHeight: NSLayoutConstraint! @IBOutlet weak var descriptionTxt: UITextField! @IBOutlet weak var statusTxt: UITextField! @IBOutlet weak var corpusTxt: UITextField! @IBOutlet weak var transcriptionsTxt: UITextField! @IBOutlet weak var trainBtn: UIButton! override func viewDidLoad() { super.viewDidLoad() self.activityView.isHidden = true //saveBtn.isHidden = true //trainBtn.isHidden = true modelNameTxt.delegate = self languageTxt.delegate = self transcriptionTV.delegate = self modelNameTxt.restorationIdentifier = "modelname" languagePicker.delegate = self languagePicker.delegate = self languagePopup.isHidden = true saveBtn.isEnabled = false saveBtn.backgroundColor = appDelegate.gray74 headerLbl.text = "Create Custom Model" transcriptionTV.text = "Model Description" modelNameLbl.isHidden = true languageLbl.isHidden = true languageLblHeight.constant = 0 modelLblHeight.constant = 0 let keyboardDoneButtonView = UIToolbar() keyboardDoneButtonView.sizeToFit() let doneButton = UIBarButtonItem(title: "Done", style: .bordered, target: self, action: #selector(self.doneClicked)) keyboardDoneButtonView.items = [doneButton] transcriptionTV.textContainerInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) transcriptionTV?.inputAccessoryView = keyboardDoneButtonView modelNameTxt?.inputAccessoryView = keyboardDoneButtonView getLanguages() validate() } func validate() { if modelNameTxt.text != "" && languageTxt.text != "" { saveBtn.isEnabled = true saveBtn.backgroundColor = appDelegate.crLightBlue } } func textFieldDidEndEditing(_ textField: UITextField) { if textField.restorationIdentifier == "modelname" { modelNameLbl.isHidden = false modelLblHeight.constant = 18 validate() } } func textViewDidBeginEditing(_ textView: UITextView) { if textView.text == "Model Description" { textView.text = "" } } func textViewDidEndEditing(_ textView: UITextView) { if textView.text == "" { textView.text = "Model Description" } } @IBAction func showPopup(_ sender: Any) { dismissKeyboard() languagePopup.isHidden = false } @IBAction func selectLanguage(_ sender: Any) { selectedCode = selectedLanguage?.object(forKey: "code") as? String let selectedLang = selectedLanguage?.object(forKey: "modelname") as? String languageTxt.text = selectedLang!.replacingOccurrences(of: "- Narrowband", with: "") languagePopup.isHidden = true languageLbl.isHidden = false languageLblHeight.constant = 18 validate() } @objc func doneClicked(sender: UIButton!) { dismissKeyboard() } func dismissKeyboard() { self.view.endEditing(true) } @IBAction func cancel(_ sender: Any) { dismissKeyboard() self.navigationController?.popViewController(animated: true) self.dismiss(animated: true, completion: nil) } @IBAction func trainModel(_ sender: Any) { print("train model") trainBtn.isEnabled = false self.activityView.isHidden = false self.activityView.startAnimating() trainModel() } @IBAction func updateModel(_ sender: Any) { saveBtn.isEnabled = false self.activityView.isHidden = false self.activityView.startAnimating() if (selectedModel != nil) { updateModel() } else { createModel() } } func getLanguages() { print("getLanguages") let dataString = "languageData" let urlString = "\(appDelegate.serverDestination!)getLanguagesJSON.php" let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" let paramString = "uid=\(appDelegate.userid!)&mobile=true&devStatus=\(appDelegate.devStage!)" print("urlString: \(urlString)") //print("paramString: \(paramString)") request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let session = URLSession.shared session.dataTask(with: request) {data, response, err in do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary print("files jsonResult: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary if dataDict[dataString]! is NSNull { print("no data") DispatchQueue.main.sync(execute: { //self.noResultsMain.isHidden = false }) } else { let uploadData = (dataDict[dataString]! as! NSArray).mutableCopy() as! NSMutableArray if (uploadData.count > 0) { //let list = uploadData as! NSMutableArray for ob in uploadData { let dict = ob as! NSDictionary self.languageList.add(dict) } DispatchQueue.main.sync(execute: { self.selectedLanguage = self.languageList[0] as? NSDictionary self.languagePicker.reloadAllComponents() }) } else { DispatchQueue.main.sync(execute: { //self.noResultsMain.isHidden = false }) } } } catch let err as NSError { print("error: \(err.description)") } }.resume() } func getModelInfo() { print("getModelInfo") let dataString = "modelData" let urlString = "\(appDelegate.serverDestination!)IBM-model-info.php" let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" let paramString = "uid=\(appDelegate.userid!)&cid=\(selectedModel!.cid)&mobile=true&devStatus=\(appDelegate.devStage!)" print("urlString: \(urlString)") print("paramString: \(paramString)") request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let session = URLSession.shared session.dataTask(with: request) {data, response, err in do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary print("model info jsonResult: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary if dataDict[dataString]! is NSNull { print("no data") DispatchQueue.main.sync(execute: { //self.noResultsMain.isHidden = false }) } else { let uploadData = dataDict[dataString]! as! NSDictionary if (uploadData != nil) { //self.status = uploadData.object(forKey: "status") as? String DispatchQueue.main.sync(execute: { var status = uploadData.object(forKey: "status") as? String if status == "ready" { self.trainBtn.isHidden = false status = "\(status!) - train" } if (status != "available" && status != "ready" && status != "failed") { //start timer } self.statusTxt.text = status self.corpusTxt.text = uploadData.object(forKey: "corpusfile") as? String self.transcriptionsTxt.text = uploadData.object(forKey: "transcriptions") as? String }) } else { DispatchQueue.main.sync(execute: { //self.noResultsMain.isHidden = false }) } } } catch let err as NSError { print("error: \(err.description)") } }.resume() } func createModel() { print("createModel") let dataString = "modelData" let urlString = "\(appDelegate.serverDestination!)IBM-create-model.php" let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" var modelDescription = "" if transcriptionTV.text != "" { modelDescription = transcriptionTV.text } let paramString = "modeldescription=\(modelDescription)&modelname=\(modelNameTxt.text!)&modelLanguage=\(selectedCode!)&uid=\(appDelegate.userid!)&mobile=true&devStatus=\(appDelegate.devStage!)" print("urlString: \(urlString)") print("paramString: \(paramString)") request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let session = URLSession.shared session.dataTask(with: request) {data, response, err in do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary print("create model jsonResult: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary if dataDict[dataString]! is NSNull { print("no data") DispatchQueue.main.sync(execute: { //self.noResultsMain.isHidden = false }) //self.statusLbl.isHidden = false } else { let uploadData = dataDict[dataString] as! NSDictionary let status = uploadData.object(forKey: "status") as! String DispatchQueue.main.sync(execute: { self.activityView.isHidden = true self.activityView.stopAnimating() if status == "model created successfully" { NotificationCenter.default.post(name: Notification.Name("refreshCustomModels"), object: nil) let alert = UIAlertController(title: nil, message: "Model Created Successfully", preferredStyle: UIAlertControllerStyle.alert) self.present(alert, animated: true, completion: nil) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in switch action.style{ case .default: print("default") self.navigationController?.popViewController(animated: true) case .cancel: print("cancel") case .destructive: print("destructive") } })) } }) } } catch let err as NSError { print("error: \(err.description)") } }.resume() } func updateModel() { print("updateModel") let dataString = "modelData" let urlString = "\(appDelegate.serverDestination!)editModelJSON.php" let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" let mid = selectedModel?.mid //let paramString = "modeldescription=\(transcriptionTV.text!)&modelname=\(modelNameTxt.text!)&mid=\(selectedModel?.mid)" let paramString = "modeldescription=\(transcriptionTV.text!)&mid=\(mid!)&mobile=true&devStatus=\(appDelegate.devStage!)" print("urlString: \(urlString)") print("paramString: \(paramString)") request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let session = URLSession.shared session.dataTask(with: request) {data, response, err in do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary print("model jsonResult: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary if dataDict[dataString]! is NSNull { print("no data") DispatchQueue.main.sync(execute: { //self.noResultsMain.isHidden = false }) //self.statusLbl.isHidden = false } else { let uploadData = dataDict[dataString] as! NSDictionary let status = uploadData.object(forKey: "status") as! String DispatchQueue.main.sync(execute: { if status == "model update successful" { NotificationCenter.default.post(name: Notification.Name("refreshCustomModels"), object: nil) let alert = UIAlertController(title: nil, message: "Model Saved", preferredStyle: UIAlertControllerStyle.alert) self.present(alert, animated: true, completion: nil) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in switch action.style{ case .default: print("default") self.navigationController?.popViewController(animated: true) case .cancel: print("cancel") case .destructive: print("destructive") } })) } }) } } catch let err as NSError { print("error: \(err.description)") } }.resume() } func trainModel() { print("trainModel") let dataString = "modelData" let urlString = "\(appDelegate.serverDestination!)IBM-train-model.php" let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" let paramString = "cid=\(selectedModel!.cid)&mobile=true&devStatus=\(appDelegate.devStage!)" print("urlString: \(urlString)") print("paramString: \(paramString)") request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let session = URLSession.shared session.dataTask(with: request) {data, response, err in do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary print("model jsonResult: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary if dataDict[dataString]! is NSNull { print("no data") DispatchQueue.main.sync(execute: { //self.noResultsMain.isHidden = false }) //self.statusLbl.isHidden = false } else { let uploadData = dataDict[dataString] as! NSDictionary let status = uploadData.object(forKey: "status") as! String DispatchQueue.main.sync(execute: { self.activityView.isHidden = true self.activityView.stopAnimating() if status == "Model training started successfully" { NotificationCenter.default.post(name: Notification.Name("refreshCustomModels"), object: nil) let alert = UIAlertController(title: nil, message: status, preferredStyle: UIAlertControllerStyle.alert) self.present(alert, animated: true, completion: nil) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in switch action.style{ case .default: print("default") self.navigationController?.popViewController(animated: true) case .cancel: print("cancel") case .destructive: print("destructive") } })) } }) } } catch let err as NSError { print("error: \(err.description)") } }.resume() } } extension CreateCustomModel : UIDocumentPickerDelegate { // MARK: Pickerview func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return languageList.count } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { selectedLanguage = languageList[row] as? NSDictionary } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { let lang = languageList[row] as! NSDictionary var model = lang.object(forKey: "modelname") as? String model = model!.replacingOccurrences(of: "- Narrowband", with: "") return model } } <file_sep>// // FriendRequestCell.swift // AIScribe // // Created by <NAME> on 8/23/18. // Copyright © 2018 RT. All rights reserved. // import UIKit class FriendRequestCell: UITableViewCell { @IBOutlet weak var nameLbl: UILabel! @IBOutlet weak var requestBtn: UIButton! @IBOutlet weak var friendIV: UIImageView! @IBOutlet weak var requestIV: UIImageView! } <file_sep>// // ForgotPasswordConfirmation.swift // ChewsRite // // Created by <NAME> on 5/18/18. // Copyright © 2018 RT. All rights reserved. // import UIKit class ForgotPasswordConfirmation: UIViewController { let appDelegate = UIApplication.shared.delegate as! AppDelegate @IBOutlet weak var instructionsLbl: UILabel! override func viewDidLoad() { super.viewDidLoad() let attributedString = NSMutableAttributedString(string: "Instructions to reset your password have been sent to your email <EMAIL>. Please check your inbox to continue.", attributes: [ .font: UIFont(name: "Avenir-Light", size: 14.0)!, .foregroundColor: appDelegate.crGray ]) attributedString.addAttribute(.font, value: UIFont(name: "Avenir-Medium", size: 14.0)!, range: NSRange(location: 65, length: 25)) attributedString.addAttribute(.font, value: UIFont(name: "Avenir-Book", size: 14.0)!, range: NSRange(location: 91, length: 36)) instructionsLbl.attributedText = attributedString } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } <file_sep>// // GoPremium.swift // AIScribe // // Created by <NAME> on 3/24/19. // Copyright © 2019 RT. All rights reserved. // import UIKit class GoPremium: BaseViewController { let appDelegate = UIApplication.shared.delegate as! AppDelegate @IBOutlet weak var activityView: UIActivityIndicatorView! @IBOutlet weak var submitBtn: UIButton! @IBOutlet weak var menuBtn: UIButton! override func viewDidLoad() { super.viewDidLoad() activityView.isHidden = true menuBtn.addTarget(self, action: #selector(BaseViewController.onSlideMenuButtonPressed(_:)), for: UIControlEvents.touchUpInside) } @IBAction func goPremium(_ sender: Any) { submitBtn.isEnabled = false submitBtn.backgroundColor = appDelegate.crWarmGray activityView.isHidden = false activityView.startAnimating() upgrade() } func upgrade () { activityView.isHidden = true activityView.stopAnimating() let debug = true if debug == false { updateUpgrade() } else { appDelegate.fullVersion = true //randall to do //save upgraded state in defaults and on server NotificationCenter.default.post(name: Notification.Name("appUpgraded"), object: nil) slideMenuItemSelectedAtIndex(0) } } func updateUpgrade() { print("updateUpgrade") let dataString = "groceryItemsData" let urlString = "\(appDelegate.serverDestination!)manageSingleGroceryItem.php" let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" let paramString = "uid=\(appDelegate.userid!)&selection=\(1)&devStatus=\(appDelegate.devStage!)" print("urlString: \(urlString)") print("paramString: \(paramString)") request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let session = URLSession.shared session.dataTask(with: request) {data, response, err in do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary print("grocery jsonResult: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary if dataDict[dataString]! is NSNull { print("no data") DispatchQueue.main.sync(execute: { //self.noResultsMain.isHidden = false }) } else { let uploadData : NSDictionary = dataDict[dataString]! as! NSDictionary let status = uploadData.object(forKey: "status") as! String var isSaved = false if status == "grocery items updated" || status == "grocery item added" || status == "substitution added" || status == "substitution removed" || status == "substitution updated" { isSaved = true } DispatchQueue.main.sync(execute: { if isSaved == true { NotificationCenter.default.post(name: Notification.Name("appUpgraded"), object: nil) self.slideMenuItemSelectedAtIndex(0) } }) } } catch let err as NSError { print("error: \(err.description)") } }.resume() } @IBAction func done(_ sender: Any) { self.navigationController?.popViewController(animated: true) dismiss(animated: true, completion: nil) } } <file_sep>// // BuyCredits.swift // AIScribe // // Created by <NAME> on 6/9/19. // Copyright © 2019 RT. All rights reserved. // import UIKit class BuyCredits: UIViewController, UITextFieldDelegate, UINavigationControllerDelegate { let appDelegate = UIApplication.shared.delegate as! AppDelegate let prefs = UserDefaults.standard @IBOutlet weak var activityView: UIActivityIndicatorView! @IBOutlet weak var submitBtn: UIButton! @IBOutlet weak var backBtn: UIButton! @IBOutlet weak var creditsLbl: UILabel! @IBOutlet weak var creditsTxt: UITextField! @IBOutlet weak var firstnameLbl: UILabel! @IBOutlet weak var lastnameLbl: UILabel! @IBOutlet weak var firstnameTxt: UITextField! @IBOutlet weak var lastnameTxt: UITextField! @IBOutlet weak var cardnoLbl: UILabel! @IBOutlet weak var cardnoTxt: UITextField! @IBOutlet weak var addressLbl: UILabel! @IBOutlet weak var addressTxt: UITextField! @IBOutlet weak var cityLbl: UILabel! @IBOutlet weak var cityTxt: UITextField! @IBOutlet weak var stateLbl: UILabel! @IBOutlet weak var stateTxt: UITextField! @IBOutlet weak var zipLbl: UILabel! @IBOutlet weak var zipTxt: UITextField! @IBOutlet weak var countryLbl: UILabel! @IBOutlet weak var countryTxt: UITextField! @IBOutlet weak var expLbl: UILabel! @IBOutlet weak var expTxt: UITextField! @IBOutlet weak var ccvLbl: UILabel! @IBOutlet weak var ccvTxt: UITextField! @IBOutlet weak var lastnameTopPadding: NSLayoutConstraint! @IBOutlet weak var firstnameTopPadding: NSLayoutConstraint! @IBOutlet weak var cardNoPadding: NSLayoutConstraint! @IBOutlet weak var addressPadding: NSLayoutConstraint! @IBOutlet weak var cityPadding: NSLayoutConstraint! @IBOutlet weak var zipPadding: NSLayoutConstraint! @IBOutlet weak var statePadding: NSLayoutConstraint! @IBOutlet weak var countryPadding: NSLayoutConstraint! @IBOutlet weak var expPadding: NSLayoutConstraint! @IBOutlet weak var ccvPadding: NSLayoutConstraint! @IBOutlet weak var creditsPadding: NSLayoutConstraint! var validateFields : [UITextField]? @IBOutlet weak var contentSV: UIScrollView! override func viewDidLoad() { super.viewDidLoad() activityView.isHidden = true firstnameTopPadding.constant = 0 lastnameTopPadding.constant = 0 firstnameTopPadding.constant = 0 cardNoPadding.constant = 0 addressPadding.constant = 0 cityPadding.constant = 0 zipPadding.constant = 0 statePadding.constant = 0 countryPadding.constant = 0 expPadding.constant = 0 ccvPadding.constant = 0 //creditsPadding.constant = 0 validateFields = [creditsTxt,firstnameTxt,lastnameTxt, cardnoTxt,addressTxt,cityTxt,stateTxt,zipTxt,countryTxt,expTxt ,ccvTxt] creditsLbl.isHidden = true firstnameLbl.isHidden = true lastnameLbl.isHidden = true cardnoLbl.isHidden = true addressLbl.isHidden = true cityLbl.isHidden = true stateLbl.isHidden = true zipLbl.isHidden = true countryLbl.isHidden = true expLbl.isHidden = true ccvLbl.isHidden = true expTxt.placeholder = "expiration (12/2019)" let btnItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.done, target: self, action: #selector(dismissKeyboard)) let numberToolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 50)) numberToolbar.backgroundColor = UIColor.darkGray numberToolbar.barStyle = UIBarStyle.default numberToolbar.tintColor = UIColor.black numberToolbar.items = [ UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil), btnItem] numberToolbar.sizeToFit() creditsTxt.delegate = self firstnameTxt.delegate = self lastnameTxt.delegate = self cardnoTxt.delegate = self ccvTxt.delegate = self expTxt.delegate = self addressTxt.delegate = self cityTxt.delegate = self stateTxt.delegate = self zipTxt.delegate = self countryTxt.delegate = self creditsTxt.inputAccessoryView = numberToolbar firstnameTxt.inputAccessoryView = numberToolbar lastnameTxt.inputAccessoryView = numberToolbar cardnoTxt.inputAccessoryView = numberToolbar ccvTxt.inputAccessoryView = numberToolbar expTxt.inputAccessoryView = numberToolbar addressTxt.inputAccessoryView = numberToolbar cityTxt.inputAccessoryView = numberToolbar stateTxt.inputAccessoryView = numberToolbar zipTxt.inputAccessoryView = numberToolbar countryTxt.inputAccessoryView = numberToolbar creditsTxt.keyboardType = .decimalPad cardnoTxt.keyboardType = .numberPad ccvTxt.keyboardType = .numberPad zipTxt.keyboardType = .numberPad creditsLbl.isHidden = false creditsTxt.text = "10.00" //debugVals() } func debugVals () { firstnameTopPadding.constant = 22 lastnameTopPadding.constant = 22 cardNoPadding.constant = 22 addressPadding.constant = 22 cityPadding.constant = 22 zipPadding.constant = 22 statePadding.constant = 22 countryPadding.constant = 22 expPadding.constant = 22 ccvPadding.constant = 22 creditsLbl.isHidden = false firstnameLbl.isHidden = false lastnameLbl.isHidden = false cardnoLbl.isHidden = false addressLbl.isHidden = false cityLbl.isHidden = false stateLbl.isHidden = false zipLbl.isHidden = false countryLbl.isHidden = false expLbl.isHidden = false ccvLbl.isHidden = false } override func viewDidLayoutSubviews() { contentSV.contentSize = CGSize.init(width: contentSV.frame.width, height: 1400) } // MARK: Actions @IBAction func goBack(_ sender: Any) { dismiss() } func dismiss() { self.navigationController?.popViewController(animated: true) dismiss(animated: true, completion: nil) } @IBAction func submitPayment(_ sender: Any) { for txt in validateFields! { if txt.text == "" { self.showBasicAlert(string: "Please enter \(txt.restorationIdentifier!)") return } } submitPayment() } func showBasicAlert(string:String) { let alert = UIAlertController(title: nil, message: string, preferredStyle: UIAlertControllerStyle.alert) self.present(alert, animated: true, completion: nil) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in switch action.style { case .default: print("default") case .cancel: print("cancel") case .destructive: print("destructive") } })) } // MARK: Web service func submitPayment() { submitBtn.isEnabled = false submitBtn.backgroundColor = appDelegate.gray74 activityView.isHidden = false activityView.startAnimating() print("submitPayment") let dataString = "paymentData" let urlString = "\(appDelegate.serverDestination!)buyCreditsJSON.php" print("urlString: \(urlString)") let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" let paramString = "credits=\(creditsTxt.text!)&firstname=\(firstnameTxt.text!)&lastname=\(lastnameTxt.text!)&card_number=\(cardnoTxt.text!)&cvc_number=\(ccvTxt.text!)&exp=\(expTxt.text!)&address=\(addressTxt.text!)&city=\(cityTxt.text!)&state=\(stateTxt.text!)&zip=\(zipTxt.text!)&country=\(countryTxt.text!)&uid=\(appDelegate.userid!)&devStatus=\(appDelegate.devStage!)&mobile=true" //paramString = "\(paramString)&basicprofile=true" print("paramString: \(paramString)") request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let session = URLSession.shared session.dataTask(with: request) {data, response, err in do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary print("payment jsonResult: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary if dataDict[dataString]! is NSNull { print("no payment") self.activityView.isHidden = true self.activityView.stopAnimating() self.submitBtn.isEnabled = true self.submitBtn.alpha = 1 self.submitBtn.backgroundColor = self.appDelegate.crLightBlue } else { let userDict : NSDictionary = dataDict[dataString] as! NSDictionary let status : String = userDict["status"] as! String self.appDelegate.credits = userDict["credits"] as? String print("status: \(status)") if (status == "payment successful") { DispatchQueue.main.sync(execute: { self.activityView.isHidden = true self.activityView.stopAnimating() NotificationCenter.default.post(name: Notification.Name("updateCredits"), object: self.appDelegate.credits) let alert = UIAlertController(title: nil, message: "Payment Successful", preferredStyle: UIAlertControllerStyle.alert) self.present(alert, animated: true, completion: nil) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in switch action.style{ case .default: print("default") self.dismiss() case .cancel: print("cancel") case .destructive: print("destructive") } })) }) } else { DispatchQueue.main.sync(execute: { self.activityView.isHidden = true self.activityView.stopAnimating() self.submitBtn.isEnabled = true self.submitBtn.alpha = 1 self.submitBtn.backgroundColor = self.appDelegate.crLightBlue self.showBasicAlert(string: status) }) } } } catch let err as NSError { print("error: \(err.description)") self.activityView.isHidden = true self.activityView.stopAnimating() self.submitBtn.isEnabled = true self.submitBtn.alpha = 1 self.submitBtn.backgroundColor = self.appDelegate.crLightBlue } }.resume() } // MARK: Textfield Delegate func textFieldDidEndEditing(_ textField: UITextField, reason: UITextFieldDidEndEditingReason) { if textField.restorationIdentifier == "First Name" && textField.text != "" { firstnameLbl.isHidden = false firstnameTopPadding.constant = 22 } else if textField.restorationIdentifier == "Last Name" && textField.text != "" { lastnameLbl.isHidden = false lastnameTopPadding.constant = 22 } else if textField.restorationIdentifier == "Card No" && textField.text != "" { // add length condition cardnoLbl.isHidden = false cardNoPadding.constant = 22 } else if textField.restorationIdentifier == "Address" && textField.text != "" { addressLbl.isHidden = false addressPadding.constant = 22 } else if textField.restorationIdentifier == "City" && textField.text != "" { cityLbl.isHidden = false cityPadding.constant = 22 } else if textField.restorationIdentifier == "State" && textField.text != "" { stateLbl.isHidden = false statePadding.constant = 22 } else if textField.restorationIdentifier == "Zip" && textField.text != "" { zipLbl.isHidden = false zipPadding.constant = 22 } else if textField.restorationIdentifier == "Country" && textField.text != "" { countryLbl.isHidden = false countryPadding.constant = 22 } else if textField.restorationIdentifier == "Expiration Date" && textField.text != "" { expPadding.constant = 22 expLbl.isHidden = false if appDelegate.validateDate(date: textField.text!) { } else { textField.text = "" //expPadding.constant = 0 let alert = UIAlertController(title: nil, message: "Invalid Expiration Date", preferredStyle: UIAlertControllerStyle.alert) self.present(alert, animated: true, completion: nil) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in switch action.style{ case .default: print("default") case .cancel: print("cancel") case .destructive: print("destructive") } })) } } else if textField.restorationIdentifier == "CCV" && textField.text != "" { ccvLbl.isHidden = false ccvPadding.constant = 22 } else if textField.restorationIdentifier == "Credits" && textField.text != "" { // add format condition if ((textField.text?.doubleValue) != nil) { creditsLbl.isHidden = false creditsPadding.constant = 22 } else { creditsLbl.isHidden = true creditsPadding.constant = 0 textField.text = "5.00" } } } // MARK: - Navigation @objc func dismissKeyboard () { self.view.endEditing(true) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension String { struct NumFormatter { static let instance = NumberFormatter() } var doubleValue: Double? { return NumFormatter.instance.number(from: self)?.doubleValue } var integerValue: Int? { return NumFormatter.instance.number(from: self)?.intValue } } <file_sep> // // Notifications.swift // AIScribe // // Created by DTO MacBook11 on 11/15/18. // Copyright © 2018 RT. All rights reserved. // import UIKit class Notifications: UIViewController, UITableViewDelegate, UITableViewDataSource { let appDelegate = UIApplication.shared.delegate as! AppDelegate @IBOutlet weak var statusView: UIView! @IBOutlet weak var statusLbl: UILabel! @IBOutlet weak var optionsTable: UITableView! var optionsList = [NSDictionary]() var selectedItems = [NSDictionary]() var prefsString : String? @IBOutlet weak var statusViewHeight: NSLayoutConstraint! override func viewDidLoad() { super.viewDidLoad() optionsTable.delegate = self optionsTable.dataSource = self optionsTable.tableFooterView = UIView() optionsList.append(["title":"I receive a new friend request", "optionid":0]) optionsList.append(["title":"A user accepts my friend invite", "optionid":1]) optionsList.append(["title":"Someone adds a review on my recipe", "optionid":2]) optionsList.append(["title":"Someone adds a review on a recipe I have reviewed", "optionid":3]) optionsList.append(["title":"Someone adds a recipe to my Group", "optionid":4]) optionsList.append(["title":"A friend invites me to a Group", "optionid":5]) optionsList.append(["title":"A Group I am a member of has been deleted", "optionid":6]) optionsList.append(["title":"Someone invites me to view their Meal Plan", "optionid":7]) let attributedString = NSMutableAttributedString(string: "Notifications are currently disabled for AIScribe. To receive notifications, go to Settings.", attributes: [ .font: UIFont(name: "Avenir-Light", size: 14.0)!, .foregroundColor: UIColor(white: 74.0 / 255.0, alpha: 1.0) ]) attributedString.addAttributes([ .font: UIFont(name: "Avenir-Heavy", size: 14.0)!, .foregroundColor: appDelegate.tomato ], range: NSRange(location: 84, length: 8)) statusLbl.attributedText = attributedString statusViewHeight.constant = 0 statusView.isHidden = true //getNotificationPrefs() optionsTable.reloadData() } @IBAction func disableAll(_ sender: Any) { if statusViewHeight.constant == 0 { statusViewHeight.constant = 68 statusView.isHidden = false selectedItems.removeAll() } else { statusViewHeight.constant = 0 statusView.isHidden = true } optionsTable.reloadData() } @IBAction func save(_ sender: Any) { updatePrefs() } @IBAction func goBack(_ sender: Any) { dismiss() } func dismiss () { self.navigationController?.popViewController(animated: true) dismiss(animated: true, completion: nil) } func getNotificationPrefs() { let urlString = "\(appDelegate.serverDestination!)notificationPrefs.php" print("getNotificationPrefs: \(urlString)") let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" //UIDevice.current.identifierForVendor!.uuidString let paramString = "uid=\(appDelegate.userid!)&devStatus=\(appDelegate.devStage!)&mobile=true" request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) print("paramString: \(paramString)") let session = URLSession.shared session.dataTask(with: request) {data, response, err in //print("Entered the completionHandler: \(response)") //var err: NSError? do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary //print("loginData: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary let uploadData : NSDictionary = dataDict.object(forKey: "prefsData") as! NSDictionary print("prefsData: \(uploadData)") if (uploadData != nil) { self.prefsString = uploadData.object(forKey: "prefs") as? String let arr = self.prefsString?.split(separator: ",") var arr2 = [String]() for a in arr! { arr2.append(String(a)) } for option in self.optionsList { if arr2.contains(option.object(forKey: "optionid") as! String) { self.selectedItems.append(option) } } DispatchQueue.main.sync(execute: { if self.optionsList.count > 0 { self.statusViewHeight.constant = 68 self.statusView.isHidden = false } self.optionsTable.reloadData() }) } else { self.showBasicAlert(string: "Please check your internet connection.") } } catch let err as NSError { print("error: \(err.description)") DispatchQueue.main.sync(execute: { self.showBasicAlert(string: "Please check your internet connection.") }) } }.resume() } func updatePrefs() { //submitBtn.isEnabled = false // activityView.isHidden = false // activityView.startAnimating() print("uploadUserData") let urlString = "\(appDelegate.serverDestination!)notificationPrefs.php" print("urlString: \(urlString)") let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" var selectedOptions = "" if selectedItems.count > 0 { var optionids = "" var i = 0 for a in selectedItems { if i == 0 { optionids = (a.object(forKey: "optionid") as? String)! } else { optionids = "\(selectedOptions),\(a.object(forKey: "optionid") as! String)" } i += 1 } selectedOptions = "\(optionids)" } let paramString = "\(selectedOptions)&update=true&uid=\(appDelegate.userid!)&devStatus=\(appDelegate.devStage!)&mobile=true" print("paramString: \(paramString)") request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let session = URLSession.shared session.dataTask(with: request) {data, response, err in do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary print("add user jsonResult: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary if dataDict["prefsData"]! is NSNull { print("no user") } else { let userDict : NSDictionary = dataDict["prefsData"] as! NSDictionary let status : String = userDict["status"] as! String print("status: \(status)") if (status == "prefs saved") { DispatchQueue.main.sync(execute: { // self.activityView.isHidden = true // self.activityView.stopAnimating() //self.showBasicAlert(string: "Prefs saved.") self.dismiss() }) } else { DispatchQueue.main.sync(execute: { // self.activityView.isHidden = true // self.activityView.stopAnimating() // // self.submitBtn.isEnabled = true // self.submitBtn.alpha = 1 self.showBasicAlert(string: "Please check internet connection.") }) } } } catch let err as NSError { print("error: \(err.description)") } }.resume() } func showBasicAlert(string:String) { let alert = UIAlertController(title: nil, message: string, preferredStyle: UIAlertControllerStyle.alert) self.present(alert, animated: true, completion: nil) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in switch action.style { case .default: print("default") case .cancel: print("cancel") case .destructive: print("destructive") } })) } // MARK: Tableview func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if statusViewHeight.constant == 0 { let item = optionsList[indexPath.row] if (selectedItems.contains(item)) { // found let ind = selectedItems.firstIndex(of: (item)) selectedItems.remove(at: ind!) } else { // not selectedItems.append(item) } optionsTable.reloadData() } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.optionsList.count } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.section == 0 { return 74 } else { return 42 } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.row == 0 { let cell = tableView.dequeueReusableCell(withIdentifier: "cell")! as? GroceryRecipeListCell return cell! } else { let cell = tableView.dequeueReusableCell(withIdentifier: "cell1")! as? NotificationOptionCell let dict = self.optionsList[(indexPath as NSIndexPath).row] let title = dict.object(forKey: "title") as! String print("title: \(title)") cell!.selectionStyle = .none cell!.optionLbl.text = title //cell.selectBtn.restorationIdentifier = "\(indexPath.row)" //cell.selectBtn.addTarget(self, action: #selector(self.selectItem(_:)), for: UIControlEvents.touchUpInside) if (selectedItems.contains(dict)) { // found cell!.optionIV.image = UIImage.init(named: "checkGreen") } else { // not cell!.optionIV.image = UIImage.init(named: "unselected-1") } return cell! } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ } <file_sep>// // TranslationList.swift // AIScribe // // Created by <NAME> on 5/25/19. // Copyright © 2019 RT. All rights reserved. // import UIKit class TranslationOptions: UIViewController, UITableViewDelegate, UITableViewDataSource { var did : String? @IBOutlet weak var activityView: UIActivityIndicatorView! let appDelegate = UIApplication.shared.delegate as! AppDelegate var languageList = NSMutableArray() var selectedLanguages = NSMutableArray() var selectedDisplayLanguages = NSMutableArray() var filename: String? var content : String? @IBOutlet weak var languageTable: UITableView! @IBOutlet weak var submitBtn: UIButton! override func viewDidLoad() { super.viewDidLoad() activityView.startAnimating() languageTable.tableFooterView = UIView() languageTable.dataSource = self languageTable.delegate = self submitBtn.backgroundColor = appDelegate.crWarmGray submitBtn.isEnabled = false getLanguages() // Do any additional setup after loading the view. } func getLanguages() { print("getLanguages") let dataString = "languageData" let urlString = "\(appDelegate.serverDestination!)getLanguages.php" let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" let paramString = "mobile=true&did=\(did!)&devStatus=\(appDelegate.devStage!)" print("urlString: \(urlString)") print("paramString: \(paramString)") request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let session = URLSession.shared session.dataTask(with: request) {data, response, err in do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary print("languages jsonResult: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary if dataDict[dataString]! is NSNull { print("no data") DispatchQueue.main.sync(execute: { //self.noResultsMain.isHidden = false }) //self.statusLbl.isHidden = false } else { let uploadData : NSMutableArray = (dataDict[dataString]! as! NSArray).mutableCopy() as! NSMutableArray if (uploadData.count > 0) { //let list = uploadData as! NSMutableArray for ob in uploadData { let dict = ob as! NSDictionary self.languageList.add(dict) } DispatchQueue.main.sync(execute: { self.activityView.isHidden = true self.activityView.stopAnimating() self.languageTable.reloadData() }) } else { DispatchQueue.main.sync(execute: { //self.noResultsMain.isHidden = false }) } } } catch let err as NSError { print("error: \(err.description)") } }.resume() } // MARK: Tableview func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // let dict = fileList[(indexPath as NSIndexPath).row] as! NSDictionary // // did = dict.object(forKey: "did") as! String } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if (editingStyle == UITableViewCellEditingStyle.delete) { // handle delete (by removing the data from your array and updating the tableview) // removeObject = currentItemArray[indexPath.row] // // currentItemArray.remove(at: indexPath.row) // itemArray.removeAll(where: { $0.signalid == removeObject?.signalid }) // // tableView.deleteRows(at: [indexPath], with: .fade) // // removeSignal() } } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 65 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.languageList.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell")! cell.selectionStyle = .none let dict = languageList[(indexPath as NSIndexPath).row] as! NSDictionary //cell.textLabel?.text = dict.object(forKey: "filename") as? String let v0 = cell.viewWithTag(1) as! UILabel let v2 = cell.viewWithTag(2) as! UIButton let code = dict.object(forKey: "code") as? String let translated = dict.object(forKey: "translated") as? Int let displayName = dict.object(forKey: "displayname") as? String v0.text = displayName v2.restorationIdentifier = "\(code!)" v2.accessibilityHint = displayName if translated == 1 { v2.isEnabled = false v2.alpha = 0.5 v2.setBackgroundImage(UIImage.init(named: "selected"), for: .normal) //v2.backgroundColor = .lightGray } else { v2.isEnabled = true v2.alpha = 1.0 v2.setBackgroundImage(UIImage.init(named: "unselected"), for: .normal) //v2.backgroundColor = .clear } //let rating = dict.object(forKey: "rating") as! String // if indexPath.row % 2 == 0 // { // cell.backgroundColor = appDelegate.whitefive // } // else // { // cell.backgroundColor = .white // } return cell } @IBAction func manageCode(_ sender: Any) { let btn = sender as! UIButton let code = btn.restorationIdentifier! let dl = btn.accessibilityHint! if selectedLanguages.contains(code) { selectedLanguages.remove(code) selectedDisplayLanguages.remove(dl) btn.setBackgroundImage(UIImage.init(named: "unselected"), for: .normal) } else { selectedLanguages.add(code) selectedDisplayLanguages.add(dl) btn.setBackgroundImage(UIImage.init(named: "selected"), for: .normal) } if selectedLanguages.count > 0 { submitBtn.isEnabled = true submitBtn.backgroundColor = appDelegate.crLightBlue } else { submitBtn.isEnabled = false submitBtn.backgroundColor = appDelegate.crWarmGray } print("selectedDisplayLanguages: \(selectedDisplayLanguages)") //languageTable.reloadData() } // MARK: - Navigation @IBAction func cancel(_ sender: Any) { self.navigationController?.popViewController(animated: true) self.dismiss(animated: true, completion: nil) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "ConfirmTranslations" { let destination = segue.destination as! ConfirmTranslations destination.did = did destination.content = content destination.selectedLanguages = selectedLanguages destination.selectedDisplayLanguages = selectedDisplayLanguages destination.filename = filename } } } <file_sep>// // TagsCollectionViewCell.swift // AIScribe // // Created by <NAME> on 6/15/18. // Copyright © 2018 RT. All rights reserved. // import UIKit class TagsCollectionViewCell: UICollectionViewCell { @IBOutlet weak var tagLbl: UILabel! @IBOutlet weak var leadingConstraint: NSLayoutConstraint! @IBOutlet weak var trailingConstraint: NSLayoutConstraint! } <file_sep>// // ConfirmTranslations.swift // AIScribe // // Created by <NAME> on 5/26/19. // Copyright © 2019 RT. All rights reserved. // import UIKit class ConfirmTranslations: UIViewController, UITableViewDelegate, UITableViewDataSource { let appDelegate = UIApplication.shared.delegate as! AppDelegate var did : String? var filename: String? var displayStrings = [String]() var processInd : Int = 0 var content : String? var languageList = NSMutableArray() var selectedLanguages = NSMutableArray() var selectedDisplayLanguages = NSMutableArray() var selectedDisplayLanguages2 = NSMutableArray() @IBOutlet weak var creditsLbl: UILabel! @IBOutlet weak var subtotalLbl: UILabel! @IBOutlet weak var activityView: UIActivityIndicatorView! @IBOutlet weak var filenameLbl: UILabel! @IBOutlet weak var languageTable: UITableView! @IBOutlet weak var submitBtn: UIButton! var subtotal : String? override func viewDidLoad() { super.viewDidLoad() selectedDisplayLanguages2 = selectedDisplayLanguages activityView.isHidden = true languageTable.tableFooterView = UIView() languageTable.dataSource = self languageTable.delegate = self filenameLbl.text = "Translate File: \(filename!)" creditsLbl.text = "Remaining Credits: $\(self.appDelegate.credits!)" for lang in selectedDisplayLanguages { displayStrings.append("English->\(lang as! String)") } getCost() languageTable.reloadData() } func getCost () { let len1 = content!.count var rate = 0.0 //$0.02 USD /THOUSAND CHAR //$0.10 USD /THOUSAND CHAR (custom) let chars = ceil( Double(len1 / 1000) ) * 1000 let custom = false if ( custom ) { rate = 0.10; } else { rate = 0.02; } let markup = 5.0; let cost = ( chars / 1000 ) * rate var total = ( cost * markup ) + cost if ( total < 1 ) { total = 1; } total = Double(selectedDisplayLanguages.count) * total subtotalLbl.text = "Subtotal: $\(String(format: "%.2f", total))" } // MARK: Tableview func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // let dict = fileList[(indexPath as NSIndexPath).row] as! NSDictionary // // did = dict.object(forKey: "did") as! String } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 65 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.selectedLanguages.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell")! cell.selectionStyle = .none let str = "\(displayStrings[(indexPath as NSIndexPath).row])" let dict = str //cell.textLabel?.text = dict.object(forKey: "filename") as? String let v0 = cell.viewWithTag(1) as! UILabel //let code = dict.object(forKey: "code") as? String v0.text = dict return cell } // MARK: Web service func startProcessing () { print("startProcessing") let dataString = "translateData" let urlString = "\(appDelegate.serverDestination!)IBM-translate-bulk2.php" let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" let currentLang = selectedLanguages[processInd] let currentDisplayLang = selectedDisplayLanguages[processInd] let paramString = "uid=\(appDelegate.userid!)&language=\(currentLang)&displayLanguage=\(currentDisplayLang)&did=\(did!)&mobile=true&devStatus=\(appDelegate.devStage!)" print("urlString: \(urlString)") print("paramString: \(paramString)") let str = "\(self.displayStrings[self.processInd]) - Processing" self.displayStrings[self.processInd] = str self.languageTable.reloadData() request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let session = URLSession.shared session.dataTask(with: request) {data, response, err in do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary print("bulk translation jsonResult: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary if dataDict[dataString]! is NSNull { print("no data") DispatchQueue.main.sync(execute: { self.activityView.isHidden = true self.activityView.stopAnimating() self.showBasicAlert(string: "Translation unsuccessful") }) } else { let uploadData = dataDict[dataString]! as! NSDictionary if (uploadData != nil) { //let status = uploadData.object(forKey: "status") as! String let translationid = uploadData.object(forKey: "translationid") as! String print("translationid: \(translationid)") var str = self.displayStrings[self.processInd].replacingOccurrences(of: " - Processing", with: "") if translationid != "none" { str = "\(str) - Processed" } else { str = "\(str) - Failed" } DispatchQueue.main.sync(execute: { self.displayStrings[self.processInd] = str self.languageTable.reloadData() self.processInd += 1 if self.processInd < self.selectedLanguages.count { print("process next language") self.startProcessing() } else { print("end of language list") self.activityView.stopAnimating() self.activityView.isHidden = true NotificationCenter.default.post(name: Notification.Name("refreshTranslations1"), object: nil) let alert = UIAlertController(title: nil, message: "Translations completed", preferredStyle: UIAlertControllerStyle.alert) self.present(alert, animated: true, completion: nil) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in switch action.style{ case .default: print("default") self.returnToTranscription() case .cancel: print("cancel") case .destructive: print("destructive") } })) } }) } else { DispatchQueue.main.sync(execute: { self.activityView.isHidden = true self.activityView.stopAnimating() self.showBasicAlert(string: "Translation unsuccessful") }) } } } catch let err as NSError { print("error: \(err.description)") } }.resume() } func returnToTranscription() { NotificationCenter.default.post(name: Notification.Name("refreshTranslations"), object: nil) for controller in self.navigationController!.viewControllers as Array { if controller.isKind(of: TranscriptionResult.self) { self.navigationController!.popToViewController(controller, animated: true) break } } } // MARK: Actions @IBAction func submitOrder(_ sender: Any) { print("submit order") activityView.startAnimating() activityView.isHidden = false submitBtn.isEnabled = false submitBtn.backgroundColor = appDelegate.gray74 startProcessing() } @IBAction func cancel(_ sender: Any) { selectedDisplayLanguages = selectedDisplayLanguages2 dismiss() } func dismiss() { self.navigationController?.popViewController(animated: true) self.dismiss(animated: true, completion: nil) } func showBasicAlert(string:String) { let alert = UIAlertController(title: nil, message: string, preferredStyle: UIAlertControllerStyle.alert) self.present(alert, animated: true, completion: nil) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in switch action.style { case .default: print("default") case .cancel: print("cancel") case .destructive: print("destructive") } })) } } <file_sep>// // ShowMoreFilterOptions.swift // AIScribe // // Created by <NAME> on 6/8/18. // Copyright © 2018 RT. All rights reserved. // import UIKit class ShowMoreFilterOptions: UIViewController, UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource { let appDelegate = UIApplication.shared.delegate as! AppDelegate @IBOutlet weak var activityView: UIActivityIndicatorView! @IBOutlet weak var headerLbl: UILabel! @IBOutlet weak var otherTxt: UITextField! var category : String? var isUpdating: Bool? //var labelList = ["Calories"] // var dietsList = ["Diabetic","Dairy Allergy"] // var cuisinesList = ["American"] // var ingredientsList = ["Vegetables"] var mealLabelList = NSMutableArray() var dietLabelList = NSMutableArray() var ingredientLabelList = NSMutableArray() var cuisineLabelList = NSMutableArray() var selectedLabelList : NSMutableArray? var selectedList : NSMutableArray? var selectedDiets : NSMutableArray? var selectedMeals : NSMutableArray? var selectedCuisines : NSMutableArray? var selectedIngredients : NSMutableArray? @IBOutlet weak var likesTable: UITableView! var numberToolbar : UIToolbar? @IBOutlet weak var submitBtn: UIButton! override func viewDidLoad() { super.viewDidLoad() likesTable.delegate = self likesTable.dataSource = self activityView.isHidden = true likesTable.allowsMultipleSelection = true dietLabelList.add("Diabetic") dietLabelList.add("Dairy Allergy") dietLabelList.add("Egg Allergy") dietLabelList.add("Fish Allergy") dietLabelList.add("Flexitarian") dietLabelList.add("Gluten Intolerance") mealLabelList.add("Breakfast") mealLabelList.add("Lunch") mealLabelList.add("Snack") mealLabelList.add("Dinner") mealLabelList.add("Dessert") cuisineLabelList.add("Afghan") cuisineLabelList.add("American") cuisineLabelList.add("Argentinian") ingredientLabelList.add("Vegatables") ingredientLabelList.add("Chicken") ingredientLabelList.add("Pasta") // let attributedString = NSMutableAttributedString(string: "More Options", attributes: [ // .font: UIFont(name: "Avenir-Medium", size: 16.0)!, // .foregroundColor: UIColor.white // ]) // attributedString.addAttribute(.font, value: UIFont(name: "Avenir-Light", size: 16.0)!, range: NSRange(location: 0, length: 7)) // // headerLbl.attributedText = attributedString if category == "Diets" { selectedList = selectedDiets! selectedLabelList = dietLabelList headerLbl.text = "Diet Options" } else if category == "Cuisines" { selectedList = selectedCuisines! selectedLabelList = cuisineLabelList headerLbl.text = "Cuisine Options" } else if category == "Ingredients" { selectedList = selectedIngredients! selectedLabelList = ingredientLabelList headerLbl.text = "Ingredient Options" } else if category == "Meals" { selectedList = selectedMeals! selectedLabelList = mealLabelList headerLbl.text = "Meal Options" } likesTable.tableFooterView = UIView() likesTable.reloadData() } @objc func dismissKeyboard () { self.view.endEditing(true) } @IBAction func cancel(_ sender: Any) { self.dismiss(animated: true, completion: nil) } @IBAction func submitOptions(_ sender: Any) { NotificationCenter.default.post(name: Notification.Name("updateFilter"), object: self.selectedList) self.dismiss(animated: true, completion: nil) } @IBAction func next(_ sender: Any) { // submitBtn.isEnabled = false // self.submitBtn.alpha = 0.5 // // var paramString = "category=\(category!)&uid=\(appDelegate.userid!)" // // for field in fields // { // let val = field.restorationIdentifier?.replacingOccurrences(of: " ", with: "", options: .literal, range: nil) // // paramString = "\(paramString)&\(val!)=\(field.text!)" // } // // print("vars: \(paramString)") // // activityView.isHidden = false // activityView.startAnimating() // // let urlString = "\(appDelegate.serverDestination!)addNutritionGoals.php" // // print("urlString: \(urlString)") // // let url = URL(string: urlString) // var request = URLRequest(url: url!) // // request.httpMethod = "POST" // // request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) // // let session = URLSession.shared // // session.dataTask(with: request) {data, response, err in // // //print("Entered the completionHandler: \(response)") // // //var err: NSError? // // do { // // let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary // // print("goalsData: \(jsonResult)") // // let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary // // //print("dataDict: \(dataDict)") // // let uploadData : NSDictionary = dataDict.object(forKey: "goalsData") as! NSDictionary // // if (uploadData != nil) // { // let status = uploadData.object(forKey: "status") as? String // // if (status == "goals info saved") // { // DispatchQueue.main.sync(execute: { // // self.activityView.isHidden = true // self.activityView.stopAnimating() // // self.submitBtn.isEnabled = true // self.submitBtn.alpha = 1 // // self.performSegue(withIdentifier: "login", sender: self) // }) // } // else // { // DispatchQueue.main.sync(execute: { // // self.activityView.isHidden = true // self.activityView.stopAnimating() // // self.submitBtn.isEnabled = true // self.submitBtn.alpha = 1 // // self.showBasicAlert(string: status!) // }) // } // } // else // { // //data not returned // } // } // catch let err as NSError // { // print("error: \(err.description)") // } // // }.resume() } func showBasicAlert(string:String) { let alert = UIAlertController(title: nil, message: string, preferredStyle: UIAlertControllerStyle.alert) self.present(alert, animated: true, completion: nil) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in switch action.style { case .default: print("default") case .cancel: print("cancel") case .destructive: print("destructive") } })) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.selectedLabelList!.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell : GoalsTableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell")! as! GoalsTableViewCell let val = self.selectedLabelList![(indexPath as NSIndexPath).row] print("val: \(val)") cell.itemLbl?.text = val as? String if (selectedList?.contains(val))! { //cell.setSelected(true, animated: false) tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none) } return cell } func textFieldDidEndEditing(_ textField: UITextField, reason: UITextFieldDidEndEditingReason) { print("tf: \(textField.restorationIdentifier!) \(textField.text!)") // let dict : NSDictionary = ["field" : textField.restorationIdentifier!, "val" : textField.text!] // // // savedVals.add(dict) } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let item = selectedLabelList![indexPath.row] if (!(selectedList?.contains(item))!) { selectedList?.add(item) } print("selectedList: \(selectedList)") } func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { let item = selectedLabelList![indexPath.row] if (selectedList?.contains(item))! { selectedList?.remove(item) } print("selectedList: \(selectedList)") } func textFieldDidEndEditing(_ textField: UITextField) { // if textField.restorationIdentifier == "other" && textField.text != "" // { // cuisines.add(otherTxt.text!) // otherTxt.text = "" // cuisineCV.reloadData() // } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // if segue.identifier == "AddIngredients" // { // let destination = segue.destination as! AddIngredients // destination.category = category // } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } <file_sep>// // UploadCorpus.swift // AIScribe // // Created by <NAME> on 6/27/19. // Copyright © 2019 RT. All rights reserved. // import UIKit import MobileCoreServices import Alamofire import AVFoundation class UploadCorpus: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource { let appDelegate = UIApplication.shared.delegate as! AppDelegate var sandboxURL : URL? var selectedModel : ModelItem? var cid : String? var hasFile: Bool? var languageList = NSMutableArray() var cost : String? var file : NSDictionary? @IBOutlet weak var filenameLbl: UILabel! @IBOutlet weak var filenameLblHeight: NSLayoutConstraint! @IBOutlet weak var activityView: UIActivityIndicatorView! @IBOutlet weak var menuBtn: UIButton! @IBOutlet weak var languageBtn: UIButton! @IBOutlet weak var transcribeBtn: UIButton! @IBOutlet weak var languagePicker: UIPickerView! @IBOutlet weak var languagePopup: UIView! var itemArray = [ModelItem]() var currentItemArray = [ModelItem]() override func viewDidLoad() { super.viewDidLoad() activityView.isHidden = true languagePicker.delegate = self languagePicker.dataSource = self filenameLbl.text = "" languagePopup.isHidden = true filenameLblHeight.constant = 0 transcribeBtn.isEnabled = false getModels() NotificationCenter.default.addObserver( self, selector: #selector(hideCorpusPickerNotification), name: NSNotification.Name(rawValue: "hideCorpusPicker"), object: nil) NotificationCenter.default.addObserver( self, selector: #selector(resetCorpusNotification), name: NSNotification.Name(rawValue: "resetCorpus"), object: nil) } // MARK: Notifications @objc func resetCorpusNotification (notification: NSNotification) { print("reset corpus defaults") file = nil languagePicker.selectRow(0, inComponent: 0, animated: false) filenameLbl.text = "" languagePopup.isHidden = true filenameLblHeight.constant = 0 transcribeBtn.isEnabled = false languageBtn.setTitle("Choose model...", for: .normal) languageBtn.backgroundColor = UIColor.init(red: 214/255.0, green: 217/255.0, blue: 217/255.0, alpha: 1.0) transcribeBtn.backgroundColor = appDelegate.gray74 transcribeBtn.setTitle("UPLOAD", for: .normal) cid = nil } @objc func hideCorpusPickerNotification (notification: NSNotification) { print("hideCorpusPickerNotification") languagePopup.isHidden = true } // MARK: Actions @IBAction func showPopup(_ sender: Any) { if selectedModel == nil { selectedModel = currentItemArray[0] } languagePopup.isHidden = false } @IBAction func uploadFile(_ sender: Any) { print("upload file") activityView.startAnimating() activityView.isHidden = false transcribeBtn.isEnabled = false transcribeBtn.setTitle("UPLOADING", for: .normal) initUpload() } @IBAction func selectLanguage(_ sender: Any) { cid = selectedModel?.cid languageBtn.setTitle(selectedModel?.modelname, for: .normal) languagePopup.isHidden = true validateForm() } func validateForm() { if selectedModel != nil && hasFile == true { transcribeBtn.backgroundColor = appDelegate.crGreen transcribeBtn.isEnabled = true } } @IBAction func openFile(_ sender: Any) { let docPicker = UIDocumentPickerViewController(documentTypes: [kUTTypeText as String], in: .import) docPicker.delegate = self docPicker.allowsMultipleSelection = false present(docPicker, animated: true, completion: nil) } @IBAction func cancel(_ sender: Any) { dismiss() } func dismiss() { self.navigationController?.popViewController(animated: true) self.dismiss(animated: true, completion: nil) } // MARK: Webservice func getModels() { print("getModels") let dataString = "modelsData" let urlString = "\(appDelegate.serverDestination!)getModelsJSON.php" let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" let paramString = "uid=\(appDelegate.userid!)&mobile=true&devStatus=\(appDelegate.devStage!)" print("urlString: \(urlString)") //print("paramString: \(paramString)") request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let session = URLSession.shared session.dataTask(with: request) {data, response, err in do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary print("files jsonResult: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary if dataDict[dataString]! is NSNull { print("no data") DispatchQueue.main.sync(execute: { // self.statusView.isHidden = false // self.refreshControl.endRefreshing() //self.noResultsMain.isHidden = false }) //self.statusLbl.isHidden = false } else { let uploadData : NSMutableArray = (dataDict[dataString]! as! NSArray).mutableCopy() as! NSMutableArray if (uploadData.count > 0) { //let list = uploadData as! NSMutableArray for ob in uploadData { let dict = ob as! NSDictionary self.itemArray.append(ModelItem(modelname: dict.object(forKey: "modelname") as! String, modeldescription: dict.object(forKey: "modeldescription") as! String, basename1: dict.object(forKey: "basename1") as! String, mid: dict.object(forKey: "mid") as! String, cid: dict.object(forKey: "cid") as! String, status: dict.object(forKey: "status") as! String)) } self.currentItemArray = self.itemArray DispatchQueue.main.sync(execute: { self.languagePicker.reloadAllComponents() // self.activityView.isHidden = true // self.statusView.isHidden = true // self.activityView.stopAnimating() // self.modelsTable.reloadData() // self.refreshControl.endRefreshing() }) } else { DispatchQueue.main.sync(execute: { // self.statusView.isHidden = false // self.refreshControl.endRefreshing() //self.noResultsMain.isHidden = false }) } } } catch let err as NSError { print("error: \(err.description)") } }.resume() } func initUpload () { print("ext: \(sandboxURL!.pathExtension)") print("filename: \(sandboxURL!.lastPathComponent)") let params = [ "userid": appDelegate.userid, "cid": cid!, "filename": sandboxURL!.lastPathComponent, "mobile": "true" ] Alamofire.upload( multipartFormData: { multipartFormData in multipartFormData.append(self.sandboxURL!, withName: "file") for (key, value) in params { multipartFormData.append((value?.data(using: String.Encoding.utf8)!)!, withName: key) } }, to: "http://localhost:8888/aiscribe/IBM-create-corpus.php", encodingCompletion: { encodingResult in switch encodingResult { case .success(let upload, _, _): upload.responseJSON { response in print("response: \(response)") if let JSON = response.result.value { //print("JSON: \(JSON)") let dataDict : NSDictionary = JSON as! NSDictionary let data = dataDict.object(forKey: "data") as! NSDictionary let corpusData = data.object(forKey: "corpusData") as! NSDictionary let status = corpusData.object(forKey: "status") as! String if status == "corpus created successfully" { self.activityView.isHidden = true self.activityView.stopAnimating() NotificationCenter.default.post(name: Notification.Name("refreshCorpora"), object: nil) let alert = UIAlertController(title: nil, message: "Corpus Uploaded Sucessfully", preferredStyle: UIAlertControllerStyle.alert) self.present(alert, animated: true, completion: nil) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in switch action.style{ case .default: print("default") self.dismiss() case .cancel: print("cancel") case .destructive: print("destructive") } })) } else { //handle error self.transcribeBtn.isEnabled = true let alert = UIAlertController(title: "Upload Error", message: status, preferredStyle: UIAlertControllerStyle.alert) self.present(alert, animated: true, completion: nil) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in switch action.style{ case .default: print("default") case .cancel: print("cancel") case .destructive: print("destructive") } })) } } //debugPrint(response) } case .failure(let encodingError): print(encodingError) } }) } } extension UploadCorpus : UIDocumentPickerDelegate { func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) { guard let selectedURL = urls.first else { return } let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! sandboxURL = dir.appendingPathComponent(selectedURL.lastPathComponent) if FileManager.default.fileExists(atPath: sandboxURL!.path) { //print("do nothin") print("sandboxURL: \(sandboxURL!)") print("selectedURL: \(selectedURL)") print("ext: \(sandboxURL!.pathExtension)") print("filename: \(sandboxURL!.lastPathComponent)") if sandboxURL!.pathExtension == "txt" { filenameLblHeight.constant = 21 filenameLbl.text = sandboxURL!.lastPathComponent self.hasFile = true self.validateForm() } else { let alert = UIAlertController(title: nil, message: "Invalid file type", preferredStyle: UIAlertControllerStyle.alert) self.present(alert, animated: true, completion: nil) alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { action in switch action.style{ case .default: print("default") case .cancel: print("cancel") case .destructive: print("destructive") } })) } } else { do { try FileManager.default.copyItem(at: selectedURL, to: sandboxURL!) print("copied!") } catch { print("Error: \(error)") } } } // MARK: Pickerview func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return currentItemArray.count } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { selectedModel = currentItemArray[row] } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { let lang = currentItemArray[row] let model = lang.modelname return model } } <file_sep>// // Login.swift // AIScribe // // Created by <NAME> on 5/18/18. // Copyright © 2018 RT. All rights reserved. // import UIKit import CoreLocation import AVFoundation import FBSDKLoginKit import FBSDKCoreKit import LocalAuthentication class Login: UIViewController, UITextFieldDelegate, CLLocationManagerDelegate { let appDelegate = UIApplication.shared.delegate as! AppDelegate @IBOutlet weak var usernameLbl: UILabel! @IBOutlet weak var usernameTxt: UITextField! @IBOutlet weak var passwordLbl: UILabel! @IBOutlet weak var passwordTxt: UITextField! @IBOutlet weak var emailLbl: UILabel! @IBOutlet weak var emailTxt: UITextField! @IBOutlet weak var forgotPasswordBtn: UIButton! @IBOutlet weak var submitBtn: UIButton! @IBOutlet weak var showSignupBtn: UIButton! @IBOutlet weak var loginBtn: UIButton! @IBOutlet weak var emailUnderscoreView: UIView! @IBOutlet weak var usernameLblHeight: NSLayoutConstraint! @IBOutlet weak var emailUnderscoreHeight: NSLayoutConstraint! @IBOutlet weak var emailLblHeight: NSLayoutConstraint! @IBOutlet weak var passwordLblHeight: NSLayoutConstraint! @IBOutlet weak var emailTxtHeight: NSLayoutConstraint! @IBOutlet weak var emailTxtTopPadding: NSLayoutConstraint! @IBOutlet weak var passwordLblTopPadding: NSLayoutConstraint! @IBOutlet weak var passwordTxtTopPadding: NSLayoutConstraint! @IBOutlet weak var emailLblTopPadding: NSLayoutConstraint! @IBOutlet weak var socialViewPaddingTop: NSLayoutConstraint! @IBOutlet weak var instructionsLblPaddingToop: NSLayoutConstraint! @IBOutlet weak var instructionsLbl: UILabel! @IBOutlet weak var activityView: UIActivityIndicatorView! @IBOutlet weak var socialView: UIView! var basicInfoCompleted : String? var accountConfirmed : String? var status : String? let prefs = UserDefaults.standard var inputList = NSMutableArray() var locationManager: CLLocationManager = CLLocationManager() var startLocation: CLLocation! var isLoggingIn : Bool? var dict : [String : AnyObject]? var isNewUser : Bool = false var hasAccount : Bool? var usingFB : Bool? var signupInputs : [UITextField]? var loginpInputs : [UITextField]? @IBOutlet weak var instructionsLblHeight: NSLayoutConstraint! @IBOutlet weak var sv: UIScrollView! @IBOutlet weak var touchIDBtn: UIButton! var touchIDAlert: UIAlertController? @IBOutlet weak var viewPasswordBtn: UIButton! override func viewDidLoad() { super.viewDidLoad() signupInputs = [usernameTxt, emailTxt, passwordTxt] loginpInputs = [usernameTxt, passwordTxt] usernameTxt.delegate = self emailTxt.delegate = self passwordTxt.delegate = self usernameLbl.isHidden = true emailLbl.isHidden = true passwordLbl.isHidden = true //instructionsLbl.isHidden = true touchIDBtn.isHidden = true usernameLblHeight.constant = 0 emailLblHeight.constant = 0 passwordLblHeight.constant = 0 //socialViewPaddingTop.constant = 0 instructionsLblPaddingToop.constant = 0 //instructionsLblHeight.constant = 0 instructionsLbl.text = "" submitBtn.isEnabled = false submitBtn.backgroundColor = appDelegate.crWarmGray submitBtn.layer.cornerRadius = submitBtn.frame.width/2 let btnItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.done, target: self, action: #selector(dismissKeyboard)) let numberToolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 50)) numberToolbar.backgroundColor = UIColor.darkGray numberToolbar.barStyle = UIBarStyle.default numberToolbar.tintColor = UIColor.black numberToolbar.items = [ UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil), btnItem] numberToolbar.sizeToFit() usernameTxt.inputAccessoryView = numberToolbar emailTxt.inputAccessoryView = numberToolbar passwordTxt.inputAccessoryView = numberToolbar NotificationCenter.default.addObserver(self, selector: #selector(showResetInstructions), name: NSNotification.Name(rawValue: "showResetInstructions"), object: nil) initStuff() //debug() showLogin() } override func viewWillDisappear(_ animated: Bool) { NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil) } override func viewDidAppear(_ animated: Bool) { NotificationCenter.default.addObserver(self, selector: #selector(Login.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(Login.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil) let modelName = UIDevice.modelName if modelName.contains("iPhone 5") { sv.frame = CGRect.init(x: 0, y: sv.frame.origin.y, width: view.frame.width, height: sv.frame.height) sv.contentSize = CGSize.init(width: view.frame.width, height: 700) sv.layoutSubviews() } } func initStuff() { //http://blogs.innovationm.com/linkedin-integration-in-swift-3-0/ print(self.appDelegate.formatMessageDate(date: Date())) //print(self.view.frame.height) // if self.view.frame.height < 600 // { // loginHeight.constant = 35 // membershipHeight.constant = 35 // fbTopMargin.constant = 0 // fbHeight.constant = 25 // loginTypeHeight.constant = 35 // passwordTopMargin.constant = 5 // } if FBSDKAccessToken.current() != nil { print("has logged into FB") self.logUserData() } if prefs.string(forKey: "fbid") != nil { appDelegate.fbID = prefs.string(forKey: "fbid") // appDelegate.firstname = prefs.string(forKey: "firstname") // appDelegate.lastname = prefs.string(forKey: "lastname") // appDelegate.email = prefs.string(forKey: "email") // appDelegate.profileImg = prefs.string(forKey: "profileImg") // appDelegate.referralCode = prefs.string(forKey: "code") } activityView.isHidden = true inputList = [emailTxt,passwordTxt] locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.delegate = self locationManager.requestWhenInUseAuthorization() locationManager.startUpdatingLocation() startLocation = nil if prefs.string(forKey: "cloudVersion") != nil { appDelegate.cloudVersion = Int(prefs.string(forKey: "cloudVersion")!)! } if prefs.string(forKey: "upgraded") != nil || prefs.bool(forKey: "nonConsumablePurchaseMade") { appDelegate.fullVersion = true } let attributedString = NSMutableAttributedString(string: "LOGIN", attributes: [ .font: UIFont(name: "Avenir-Book", size: 20.0)!, .foregroundColor: UIColor.white ]) loginBtn.setAttributedTitle(attributedString, for: .normal) let attributedString2 = NSMutableAttributedString(string: "SIGNUP", attributes: [ .font: UIFont(name: "Avenir-Heavy", size: 20.0)!, .foregroundColor: UIColor.white ]) showSignupBtn.setAttributedTitle(attributedString2, for: .normal) NotificationCenter.default.addObserver(self, selector: #selector(logout1), name: NSNotification.Name(rawValue: "Logout"), object: nil) print("login full: \(appDelegate.fullVersion!)") //listFiles2() //makeVideoOverlay() //listFilesFromDocumentsFolder() NotificationCenter.default.addObserver( self, selector: #selector(udpateTokenNotification), name: NSNotification.Name(rawValue: "updateToken"), object: nil) let myContext = LAContext() var authError: NSError? //check for touchID funcitonality if myContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &authError) { if let username = prefs.string(forKey: "username"), let _ = prefs.string(forKey: "<PASSWORD>") { usernameTxt.text = username //print("show touch ID buttun") //touchIDBtn.isHidden = false promptTouchID() } } else { //check auto login // prefs.removeObject(forKey: "username") // prefs.removeObject(forKey: "<PASSWORD>") // // prefs.synchronize() if checkAutoLogin() == true { performSegue(withIdentifier: "AutoLogin", sender: nil) } else { print("no") } } } // MARK: Notifications @objc func keyboardWillShow(notification: NSNotification) { if ((notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue) != nil { if self.view.frame.origin.y == 0 { print("go up") //self.view.frame.origin.y -= keyboardSize.height self.view.frame.origin.y -= 200 } else { print("other") } } } @objc func keyboardWillHide(notification: NSNotification) { if self.view.frame.origin.y != 0 { print("reset") self.view.frame.origin.y = 0 } else { print("other 2") } } func validateInputs () { if isLoggingIn == true { for input in loginpInputs! { if input.text == "" { submitBtn.isEnabled = false submitBtn.backgroundColor = appDelegate.crWarmGray return } } } else { for input in signupInputs! { if input.text == "" { submitBtn.isEnabled = false submitBtn.backgroundColor = appDelegate.crWarmGray return } } } submitBtn.isEnabled = true submitBtn.backgroundColor = appDelegate.crLightBlue } @objc func showResetInstructions (notification: NSNotification) { let attributedString = NSMutableAttributedString(string: "Instructions to reset your password have been sent to your email <EMAIL>. Please check your inbox to continue.", attributes: [ .font: UIFont(name: "Avenir-Light", size: 14.0)!, .foregroundColor: appDelegate.crGray ]) attributedString.addAttribute(.font, value: UIFont(name: "Avenir-Medium", size: 14.0)!, range: NSRange(location: 65, length: 25)) attributedString.addAttribute(.font, value: UIFont(name: "Avenir-Book", size: 14.0)!, range: NSRange(location: 91, length: 36)) instructionsLbl.attributedText = attributedString socialViewPaddingTop.constant = 20 instructionsLbl.isHidden = false instructionsLblPaddingToop.constant = 20 instructionsLblHeight.constant = 57 } func checkFBCreds() { activityView.isHidden = false activityView.startAnimating() let urlString = "\(appDelegate.serverDestination!)getFBCredentials.php" print("urlString: \(urlString)") let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" let paramString = "fbid=\(self.appDelegate.fbID!)&devStatus=\(appDelegate.devStage!)" request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) print("login decryptParam: \(paramString)") let session = URLSession.shared session.dataTask(with: request) {data, response, err in //print("Entered the completionHandler: \(response)") //var err: NSError? do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary //print("loginData: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary print("dataDict: \(dataDict)") let uploadData : NSDictionary = dataDict.object(forKey: "loginData") as! NSDictionary self.status = uploadData.object(forKey: "status") as? String if self.status != nil && self.status == "Logged in" { // self.appDelegate.firstname = uploadData.object(forKey: "firstname") as? String // self.appDelegate.lastname = uploadData.object(forKey: "lastname") as? String self.appDelegate.email = uploadData.object(forKey: "email") as? String // self.appDelegate.city = uploadData.object(forKey: "city") as? String // self.appDelegate.state = uploadData.object(forKey: "state") as? String // self.appDelegate.zip = uploadData.object(forKey: "zip") as? String // self.appDelegate.country = uploadData.object(forKey: "country") as? String // self.appDelegate.mobile = uploadData.object(forKey: "phone") as? String self.appDelegate.userid = uploadData.object(forKey: "userid") as? String self.appDelegate.genuserid = uploadData.object(forKey: "genuserid") as? String // self.accountConfirmed = uploadData.object(forKey: "accountConfirmed") as? String // self.paymentConfirmed = uploadData.object(forKey: "paymentConfirmed") as? String self.appDelegate.usertype = uploadData.object(forKey: "usertype") as? String if uploadData.object(forKey: "code") as? String != nil { self.appDelegate.referralCode = uploadData.object(forKey: "code") as? String } else { self.appDelegate.referralCode = "undefined" } // self.prefs.setValue(self.appDelegate.firstname , forKey: "firstname") // self.prefs.setValue(self.appDelegate.lastname , forKey: "lastname") // self.prefs.setValue(self.appDelegate.email , forKey: "email") // self.prefs.setValue(self.appDelegate.username , forKey: "username") //NotificationCenter.default.post(name: Notification.Name("reloadMenu"), object: nil) print("login usertype: \(self.appDelegate.usertype!)") print("login userid: \(self.appDelegate.userid!)") print("login genuserid: \(self.appDelegate.genuserid!)") } DispatchQueue.main.sync(execute: { self.activityView.isHidden = true self.activityView.stopAnimating() if self.status != nil && self.status == "Logged in" { self.isNewUser = false Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(self.loggedIn), userInfo: nil, repeats: false) } else { print("invalid") self.showBasicAlert(string: self.status!) } }) } catch let err as NSError { print("error: \(err.description)") DispatchQueue.main.sync(execute: { self.activityView.stopAnimating() self.activityView.isHidden = true let alert = UIAlertController(title: "Login Error", message: err.description, preferredStyle: UIAlertControllerStyle.alert) self.present(alert, animated: true, completion: nil) alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { action in switch action.style{ case .default: print("default") case .cancel: print("cancel") case .destructive: print("destructive") } })) }) } }.resume() } func logUserData() { //get saved user data } // MARK: Authentication func login(username: String, password : String?) { submitBtn.isEnabled = false submitBtn.backgroundColor = appDelegate.crWarmGray activityView.isHidden = false activityView.startAnimating() let urlString = "\(appDelegate.serverDestination!)loginJSON.php" print("urlString: \(urlString)") let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" //UIDevice.current.identifierForVendor!.uuidString let paramString = "username=\(usernameTxt.text!)&password=\(<PASSWORD>Txt.text!)&devStatus=\(appDelegate.devStage!)" request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) print("login decryptParam: \(paramString)") let session = URLSession.shared session.dataTask(with: request) {data, response, err in //print("Entered the completionHandler: \(response)") //var err: NSError? do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary print("jsonResult: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary print("login dataDict: \(dataDict)") let uploadData = dataDict.object(forKey: "loginData") as! NSDictionary if (uploadData != nil) { self.status = uploadData.object(forKey: "status") as? String if self.status != nil && self.status == "Logged in" { self.appDelegate.firstname = uploadData.object(forKey: "firstname") as? String self.appDelegate.lastname = uploadData.object(forKey: "lastname") as? String self.appDelegate.username = uploadData.object(forKey: "username") as? String self.appDelegate.email = uploadData.object(forKey: "email") as? String // self.appDelegate.city = uploadData.object(forKey: "city") as? String // self.appDelegate.state = uploadData.object(forKey: "state") as? String // self.appDelegate.zip = uploadData.object(forKey: "zip") as? String // self.appDelegate.country = uploadData.object(forKey: "country") as? String // self.appDelegate.mobile = uploadData.object(forKey: "phone") as? String self.appDelegate.userid = uploadData.object(forKey: "userid") as? String self.appDelegate.genuserid = uploadData.object(forKey: "genuserid") as? String self.appDelegate.profileImg = uploadData.object(forKey: "userimage") as? String self.appDelegate.dob = uploadData.object(forKey: "dob") as? String self.accountConfirmed = uploadData.object(forKey: "accountconfirmed") as? String self.appDelegate.credits = uploadData.object(forKey: "credits") as? String self.basicInfoCompleted = uploadData.object(forKey: "basicinfocompleted") as? String // appDelegate.paymentConfirmed = uploadData.object(forKey: "paymentConfirmed") as? String self.appDelegate.usertype = uploadData.object(forKey: "usertype") as? String if uploadData.object(forKey: "code") as? String != nil { self.appDelegate.referralCode = uploadData.object(forKey: "code") as? String } else { self.appDelegate.referralCode = "undefined" } if self.appDelegate.devicetoken != nil { self.updateDeviceToken() } // if uploadData.object(forKey: "gender") as? String != nil // { // self.appDelegate.gender = Int((uploadData.object(forKey: "gender") as? String)!) // } //NotificationCenter.default.post(name: Notification.Name("reloadMenu"), object: nil) print("login usertype: \(self.appDelegate.usertype!)") print("login userid: \(self.appDelegate.userid!)") print("login genuserid: \(self.appDelegate.genuserid!)") } DispatchQueue.main.sync(execute: { if self.status != nil && self.status == "Logged in" { Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(self.loggedIn), userInfo: nil, repeats: false) } else { print("invalid") //self.logout () self.submitBtn.backgroundColor = self.appDelegate.crLightBlue self.submitBtn.isEnabled = true self.activityView.isHidden = true self.activityView.stopAnimating() self.showBasicAlert(string: self.status!) } }) } } catch let err as NSError { print("error: \(err.description)") DispatchQueue.main.sync(execute: { self.activityView.stopAnimating() self.activityView.isHidden = true self.submitBtn.backgroundColor = self.appDelegate.crLightBlue self.submitBtn.isEnabled = true let alert = UIAlertController(title: "Login Error", message: err.description, preferredStyle: UIAlertControllerStyle.alert) self.present(alert, animated: true, completion: nil) alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { action in switch action.style{ case .default: print("default") case .cancel: print("cancel") case .destructive: print("destructive") } })) }) } }.resume() } @objc func loggedIn () { activityView.isHidden = true activityView.stopAnimating() appDelegate.loggedIn = true appDelegate.password = <PASSWORD> // if self.appDelegate.firstname != nil { // self.prefs.setValue(self.appDelegate.firstname , forKey: "firstname") // } // if self.appDelegate.lastname != nil { // self.prefs.setValue(self.appDelegate.lastname , forKey: "lastname") // } if self.appDelegate.username != nil { self.prefs.setValue(self.appDelegate.username , forKey: "username") } if self.appDelegate.email != nil { self.prefs.setValue(self.appDelegate.email , forKey: "email") } if self.appDelegate.password != nil { self.prefs.setValue(self.appDelegate.password , forKey: "<PASSWORD>") } if self.appDelegate.credits != nil { self.prefs.setValue(self.appDelegate.credits , forKey: "credits") } // if self.appDelegate.city != nil { // self.prefs.setValue(self.appDelegate.city , forKey: "city") // } // if self.appDelegate.state != nil { // self.prefs.setValue(self.appDelegate.state , forKey: "state") // } // if self.appDelegate.zip != nil { // self.prefs.setValue(self.appDelegate.zip , forKey: "zip") // } // if self.appDelegate.country != nil { // self.prefs.setValue(self.appDelegate.country , forKey: "country") // } // if self.appDelegate.mobile != nil { // self.prefs.setValue(self.appDelegate.mobile , forKey: "mobile") // } if self.appDelegate.userid != nil { self.prefs.setValue(self.appDelegate.userid , forKey: "userid") } if self.appDelegate.genuserid != nil { self.prefs.setValue(self.appDelegate.genuserid , forKey: "genuserid") } if self.appDelegate.profileImg != nil { self.prefs.setValue(self.appDelegate.profileImg , forKey: "profileImg") } if self.appDelegate.referralCode != nil { self.prefs.setValue(self.appDelegate.referralCode , forKey: "referralCode") } //appDelegate.paymentConfirmed = prefs.string(forKey: "paymentConfirmed") if self.appDelegate.usertype != nil { self.prefs.setValue(self.appDelegate.usertype , forKey: "usertype") } // if self.appDelegate.dob != nil { // self.prefs.setValue(self.appDelegate.dob , forKey: "dob") // } // // if self.appDelegate.gender != nil { // self.prefs.setValue(self.appDelegate.gender , forKey: "gender") // } prefs.synchronize() self.view.endEditing(true) self.isNewUser = false // if accountConfirmed == "1" && basicInfoCompleted == "1" // { // self.performSegue(withIdentifier: "login", sender: self) // } // else // { // self.performSegue(withIdentifier: "AddInfo", sender: self) // } self.performSegue(withIdentifier: "login", sender: self) } func checkAutoLogin ()-> Bool { if let username = prefs.string(forKey: "username"), let _ = prefs.string(forKey: "password"), let userid = prefs.string(forKey: "userid") { usernameTxt.text = username //passwordTxt.text = <PASSWORD> //login(username: username,password: <PASSWORD>) // prefs.setValue("aport.png", forKey: "profileImg") // prefs.setValue("a", forKey: "firstname") // prefs.setValue("port", forKey: "lastname") // // prefs.synchronize() if prefs.string(forKey: "genuserid") != nil { self.appDelegate.genuserid = prefs.string(forKey: "genuserid") } if prefs.string(forKey: "usertype") != nil { self.appDelegate.usertype = prefs.string(forKey: "usertype") } if prefs.string(forKey: "credits") != nil { self.appDelegate.credits = prefs.string(forKey: "credits") } if prefs.string(forKey: "firstname") != nil { self.appDelegate.firstname = prefs.string(forKey: "firstname") } if prefs.string(forKey: "lastname") != nil { self.appDelegate.lastname = prefs.string(forKey: "lastname") } if prefs.string(forKey: "username") != nil { self.appDelegate.username = prefs.string(forKey: "username") } if prefs.string(forKey: "email") != nil { self.appDelegate.email = prefs.string(forKey: "email") } // if prefs.string(forKey: "city") != nil // { // self.appDelegate.city = prefs.string(forKey: "city") // } // if prefs.string(forKey: "state") != nil // { // self.appDelegate.state = prefs.string(forKey: "state") // } // if prefs.string(forKey: "zip") != nil // { // self.appDelegate.zip = prefs.string(forKey: "zip") // } // if prefs.string(forKey: "country") != nil // { // self.appDelegate.country = prefs.string(forKey: "country") // } // if prefs.string(forKey: "mobile") != nil // { // self.appDelegate.mobile = prefs.string(forKey: "mobile") // } if prefs.string(forKey: "userid") != nil { self.appDelegate.userid = userid } if prefs.string(forKey: "profileImg") != nil { self.appDelegate.profileImg = prefs.string(forKey: "profileImg") } if prefs.string(forKey: "accountConfirmed") != nil { self.accountConfirmed = prefs.string(forKey: "accountconfirmed") } if prefs.string(forKey: "basicInfoCompleted") != nil { self.basicInfoCompleted = prefs.string(forKey: "basicinfocompleted") } // appDelegate.paymentConfirmed = prefs.string(forKey: "paymentConfirmed") if prefs.string(forKey: "usertype") != nil { self.appDelegate.usertype = prefs.string(forKey: "usertype") } if prefs.string(forKey: "referralCode") != nil { self.appDelegate.referralCode = prefs.string(forKey: "referralCode") } else { self.appDelegate.referralCode = "undefined" } if self.appDelegate.devicetoken != nil { self.updateDeviceToken() } print("userid: \(appDelegate.userid!)") //print("genuserid: \(appDelegate.genuserid!)") return true } return false } @objc func udpateTokenNotification (notification: NSNotification) { updateDeviceToken() } func debug () { //logout() //usernameTxt.text = "ridley1224b" //emailTxt.text = "<EMAIL>" // usernameTxt.text = "aport2" // emailTxt.text = "<EMAIL>" let randomEmail = appDelegate.randomString(length: 5) usernameTxt.text = randomEmail emailTxt.text = "\(randomEmail)<EMAIL>" usernameTxt.text = "aport" emailTxt.text = "<EMAIL>" passwordTxt.text = "<PASSWORD>" let modelName = UIDevice.modelName if appDelegate.debug == false && !modelName.contains("Simulator") && modelName.contains("iPad") { usernameTxt.text = "crichardson" emailTxt.text = "<EMAIL>" passwordTxt.text = "<PASSWORD>" } else if appDelegate.debug == false && !modelName.contains("Simulator") && modelName.contains("iPhone") { usernameTxt.text = "acosta" emailTxt.text = "<EMAIL>" passwordTxt.text = "<PASSWORD>" } usernameTxt.text = "ridley1224" emailTxt.text = "<EMAIL>" passwordTxt.text = "<PASSWORD>" usernameTxt.text = "ridleytech" emailTxt.text = "<EMAIL>" passwordTxt.text = "<PASSWORD>" // usernameTxt.text = "avamaxwell" // emailTxt.text = "<EMAIL>" // passwordTxt.text = "<PASSWORD>" // if modelName.contains("iPhone 5") // { //// sv.frame = CGRect.init(x: 0, y: sv.frame.origin.y, width: view.frame.width, height: sv.frame.height) //// sv.contentSize = CGSize.init(width: view.frame.width, height: 1300) // } usernameLbl.isHidden = false usernameLblHeight.constant = 18 emailLbl.isHidden = false emailLblHeight.constant = 18 passwordLbl.isHidden = false passwordLblHeight.constant = 18 submitBtn.isEnabled = true loginBtn.isEnabled = true //submitBtn.backgroundColor = appDelegate.crLightBlue submitBtn.backgroundColor = appDelegate.crLightBlue } func listFiles2() { let filemgr = FileManager.default let dirPaths = filemgr.urls(for: .documentDirectory, in: .userDomainMask) //let docsURL = dirPaths[0] let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first print("documentsDirectory: \(documentsDirectory)") do { let filelist = try filemgr.contentsOfDirectory(atPath: "/") for filename in filelist { print("filename: \(filename)") } } catch let error { print("Error: \(error.localizedDescription)") } } func listFilesFromDocumentsFolder() { print("list files") let filemgr = FileManager.default let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first do { let directoryContents = try FileManager.default.contentsOfDirectory(at: documentsDirectory!, includingPropertiesForKeys: nil, options: []) for i in 0 ..< directoryContents.count { let obj = directoryContents[i] as URL print("file: \(obj)") try! filemgr.removeItem(at: obj) } } catch { print("Could not search for urls of files in documents directory: \(error)") } } @objc func logout1 (notification : NSNotification) { print("logout notification") logout() } func logout () { self.appDelegate.initLoaded = false self.appDelegate.loggedIn = false // prefs.removeObject(forKey: "firstname") // prefs.removeObject(forKey: "lastname") prefs.removeObject(forKey: "username") prefs.removeObject(forKey: "<PASSWORD>") prefs.removeObject(forKey: "email") // prefs.removeObject(forKey: "city") // prefs.removeObject(forKey: "state") // prefs.removeObject(forKey: "zip") // prefs.removeObject(forKey: "country") // prefs.removeObject(forKey: "mobile") prefs.removeObject(forKey: "userid") prefs.removeObject(forKey: "genuserid") prefs.removeObject(forKey: "profileImg") prefs.removeObject(forKey: "referralCode") prefs.removeObject(forKey: "basicInfoCompleted") prefs.removeObject(forKey: "accountConfirmed") prefs.removeObject(forKey: "credits") prefs.removeObject(forKey: "cloudVersion") prefs.removeObject(forKey: "upgraded") prefs.removeObject(forKey: "nonConsumablePurchaseMade") // // appDelegate.fullVersion = nil prefs.synchronize() // appDelegate.firstname = nil // appDelegate.lastname = nil appDelegate.username = nil appDelegate.email = nil // appDelegate.city = nil // appDelegate.state = nil // appDelegate.zip = nil // appDelegate.country = nil // appDelegate.mobile = nil appDelegate.userid = nil appDelegate.genuserid = nil appDelegate.profileImg = nil appDelegate.referralCode = nil emailTxt.text = "" usernameTxt.text = "" passwordTxt.text = "" validateInputs() //self.navigationController?.popToRootViewController(animated: true) for controller in self.navigationController!.viewControllers as Array { if controller.isKind(of: Login.self) { self.navigationController!.popToViewController(controller, animated: true) break } } } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { //print("didUpdateLocations") let latestLocation: CLLocation = locations[locations.count - 1] if startLocation == nil { startLocation = latestLocation } //let distanceBetween: CLLocationDistance = latestLocation.distance(from: startLocation) appDelegate.lat = "\(latestLocation.coordinate.latitude)" appDelegate.lng = "\(latestLocation.coordinate.longitude)" } // MARK: Actions @IBAction func showPassword(_ sender: Any) { if passwordTxt.isSecureTextEntry { passwordTxt.isSecureTextEntry = false viewPasswordBtn.setBackgroundImage(UIImage.init(named: "orange-closed"), for: .normal) } else { passwordTxt.isSecureTextEntry = true viewPasswordBtn.setBackgroundImage(UIImage.init(named: "orange-open"), for: .normal) } } @IBAction func touchIdAction(_ sender: UIButton) { promptTouchID() } func promptTouchID () { //https://medium.com/anantha-krishnan-k-g/how-to-add-faceid-touchid-using-swift-4-a220db360bf4 let myContext = LAContext() let myLocalizedReasonString = "Login with Touch ID" var authError: NSError? if #available(iOS 8.0, macOS 10.12.1, *) { if myContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &authError) { myContext.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: myLocalizedReasonString) { success, evaluateError in DispatchQueue.main.async { if success { // User authenticated successfully, take appropriate action //self.successLabel.text = "Awesome!!... User authenticated successfully" print("Awesome!!... User authenticated successfully") // self.touchIDAlert = UIAlertController(title: nil, message: "User authenticated successfully", preferredStyle: UIAlertControllerStyle.alert) // // self.present(self.touchIDAlert!, animated: true, completion: nil) self.activityView.startAnimating() self.activityView.isHidden = false Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: #selector(self.touchIDLogin), userInfo: nil, repeats: false) } else { // User did not authenticate successfully, look at error and take appropriate action //self.successLabel.text = "Sorry!!... User did not authenticate successfully" print("Sorry!!... User did not authenticate successfully") self.showBasicAlert(string: "User did not authenticate successfully") } } } } else { // Could not evaluate policy; look at authError and present an appropriate message to user //successLabel.text = "Sorry!!.. Could not evaluate policy." print("Ooops!!.. This feature is not supported.") } } else { // Fallback on earlier versions print("Sorry!!.. Could not evaluate policy.") //successLabel.text = "Ooops!!.. This feature is not supported." } } @objc func touchIDLogin() { self.touchIDAlert?.dismiss(animated: true, completion: nil) if self.checkAutoLogin() == true { self.performSegue(withIdentifier: "AutoLogin", sender: nil) } else { print("no") } } @objc func doneClicked(sender: UIButton!) { self.view.endEditing(true) validateInputs() } @IBAction func createAccount(_ sender: Any) { isNewUser = true // if showingRestaurant == true // { // self.performSegue(withIdentifier: "CreateVenueProfile", sender: self) // } // else // { // self.performSegue(withIdentifier: "CreateGuestProfile", sender: self) // } } @IBAction func login(_ sender: Any) { dismissKeyboard() if appDelegate.isInternetAvailable() || appDelegate.debug == true { for i : Int in 0 ..< (inputList.count) { let textField = inputList[i] as! UITextField if textField.text == "" { showBasicAlert(string:textField.restorationIdentifier!) return } } login(username: usernameTxt.text!,password: <PASSWORD>) } else { self.showBasicAlert(string: "Please check your internet connection") } } func showBasicAlert(string:String) { let alert = UIAlertController(title: nil, message: string, preferredStyle: UIAlertControllerStyle.alert) self.present(alert, animated: true, completion: nil) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in switch action.style { case .default: print("default") case .cancel: print("cancel") case .destructive: print("destructive") } })) } @IBAction func loginFB(_ sender: Any) { //http://www.oodlestechnologies.com/blogs/How-To-Integrate-Facebook-iOS-Application-In-swift-4 FacebookSignInManager.basicInfoWithCompletionHandler(self) { (dataDictionary:Dictionary<String, AnyObject>?, error:NSError?) -> Void in if dataDictionary != nil { print("dataDictionary: \(dataDictionary!)") self.appDelegate.firstname = dataDictionary!["first_name"] as? String self.appDelegate.lastname = dataDictionary!["last_name"] as? String self.appDelegate.email = dataDictionary!["email"] as? String self.appDelegate.fbID = dataDictionary!["id"] as? String let pic = dataDictionary!["picture"] as! NSDictionary let data = pic["data"] as! NSDictionary self.appDelegate.profileImg = data["url"] as? String self.appDelegate.isAuthenticated = true self.prefs.setValue(self.appDelegate.fbID , forKey: "fbid") self.prefs.setValue(self.appDelegate.profileImg , forKey: "profileImg") self.checkFBCreds() } } } @IBAction func loginTwitter(_ sender: Any) { } @IBAction func loginEmail(_ sender: Any) { } @IBAction func showLogin(_ sender: Any) { showLogin() } func showLogin () { isLoggingIn = true emailLbl.isHidden = true emailTxt.isHidden = true emailUnderscoreView.isHidden = true emailTxtHeight.constant = 0 emailLblHeight.constant = 0 emailUnderscoreHeight.constant = 0 emailTxtTopPadding.constant = 0 passwordTxtTopPadding.constant = 0 passwordLblTopPadding.constant = 0 let attributedString = NSMutableAttributedString(string: "LOGIN", attributes: [ .font: UIFont(name: "Avenir-Heavy", size: 20.0)!, .foregroundColor: UIColor.white ]) loginBtn.setAttributedTitle(attributedString, for: .normal) let attributedString2 = NSMutableAttributedString(string: "SIGNUP", attributes: [ .font: UIFont(name: "Avenir-Book", size: 20.0)!, .foregroundColor: UIColor.white ]) showSignupBtn.setAttributedTitle(attributedString2, for: .normal) if usernameTxt.text != "" { usernameLbl.isHidden = false usernameLblHeight.constant = 18 } if passwordTxt.text != "" { passwordLbl.isHidden = false passwordLblHeight.constant = 18 } validateInputs() } @IBAction func showSignup(_ sender: Any) { showSignup() } func showSignup() { isLoggingIn = false usernameLblHeight.constant = 0 emailLblHeight.constant = 0 passwordLblHeight.constant = 0 emailTxt.isHidden = false emailUnderscoreView.isHidden = false emailTxtHeight.constant = 30 //emailLblHeight.constant = 18 emailUnderscoreHeight.constant = 1 emailTxtTopPadding.constant = 5 passwordTxtTopPadding.constant = 5 passwordLblTopPadding.constant = 20 let attributedString = NSMutableAttributedString(string: "LOGIN", attributes: [ .font: UIFont(name: "Avenir-Book", size: 20.0)!, .foregroundColor: UIColor.white ]) loginBtn.setAttributedTitle(attributedString, for: .normal) let attributedString2 = NSMutableAttributedString(string: "SIGNUP", attributes: [ .font: UIFont(name: "Avenir-Heavy", size: 20.0)!, .foregroundColor: UIColor.white ]) showSignupBtn.setAttributedTitle(attributedString2, for: .normal) if usernameTxt.text != "" { usernameLbl.isHidden = false usernameLblHeight.constant = 18 } if emailTxt.text != "" { emailLbl.isHidden = false emailLblHeight.constant = 18 } if passwordTxt.text != "" { passwordLbl.isHidden = false passwordLblHeight.constant = 18 } validateInputs() } @IBAction func clearEmail(_ sender: Any) { emailTxt.text = "" } @IBAction func submit(_ sender: Any) { dismissKeyboard() if isLoggingIn == true { login(username: usernameTxt.text!,password: <PASSWORD>) } else { uploadUserData() } } func updateDeviceToken() { let urlString = "\(appDelegate.serverDestination!)updateToken.php" print("device token urlString: \(urlString)") let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" //UIDevice.current.identifierForVendor!.uuidString let paramString = "uid=\(appDelegate.userid!)&deviceid=\(appDelegate.devicetoken!)&devStatus=\(appDelegate.devStage!)" request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) print("update token param: \(paramString)") let session = URLSession.shared session.dataTask(with: request) {data, response, err in //print("Entered the completionHandler: \(response)") //var err: NSError? do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary //print("loginData: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary print("dataDict: \(dataDict)") let uploadData : NSDictionary = dataDict.object(forKey: "tokenData") as! NSDictionary if (uploadData != nil) { self.status = uploadData.object(forKey: "status") as? String DispatchQueue.main.sync(execute: { }) } } catch let err as NSError { print("error: \(err.description)") DispatchQueue.main.sync(execute: { }) } }.resume() } //MARK: Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "CreateGuestProfile" { // let destination = segue.destination as! MyProfileViewController // destination.isNewUser = isNewUser // // if usingFB == false // { // appDelegate.firstname = nil // appDelegate.lastname = nil // appDelegate.email = nil // } // // usingFB = false } } @IBAction func goBack(_ sender: Any) { self.navigationController?.popViewController(animated: true) } @objc func dismissKeyboard () { self.view.endEditing(true) } // MARK: Textfield func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool{ let disallowedCharacterSet = NSCharacterSet() let maxLength = 35 let currentString: NSString = textField.text! as NSString var result = true let replacementStringIsLegal = string.rangeOfCharacter(from: disallowedCharacterSet as CharacterSet) == nil let newString: NSString = currentString.replacingCharacters(in: range, with: string) as NSString if newString.length <= maxLength { result = replacementStringIsLegal } else { result = false } validateInputs() //return newString.length <= maxLength return result } func textFieldDidEndEditing(_ textField: UITextField) { if textField.restorationIdentifier == "username" && textField.text != "" { usernameLbl.isHidden = false usernameLblHeight.constant = 18 } else if textField.restorationIdentifier == "email" && textField.text != "" { emailLbl.isHidden = false emailLblHeight.constant = 18 } else if textField.restorationIdentifier == "password" && textField.text != "" { passwordLbl.isHidden = false passwordLblHeight.constant = 18 } validateInputs() } func isValidEmail(emailID:String) -> Bool { let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}" let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx) return emailTest.evaluate(with: emailID) } func uploadUserData() { if !isValidEmail(emailID: emailTxt.text!) { showBasicAlert(string: "Please enter a valid email address") return } submitBtn.isEnabled = false activityView.isHidden = false activityView.startAnimating() print("uploadUserData") let urlString = "\(appDelegate.serverDestination!)updateProfile.php" print("urlString: \(urlString)") let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" var paramString = "email=\(emailTxt.text!)&username=\(usernameTxt.text!)&password=\(<PASSWORD>!)&deviceid=\(UIDevice.current.identifierForVendor!.uuidString)&signup=true&devStatus=\(appDelegate.devStage!)&code=\(appDelegate.randomString(length: 5))" if let string = appDelegate.fbID, !string.isEmpty { /* string is not blank */ print("fbID not blank. update") paramString = "\(paramString)&fbid=\(appDelegate.fbID!)&devStatus=\(appDelegate.devStage!)" } print("paramString: \(paramString)") request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let session = URLSession.shared session.dataTask(with: request) {data, response, err in do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary print("add user jsonResult: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary if dataDict["userData"]! is NSNull { print("no user") DispatchQueue.main.sync(execute: { self.showError(status: "error") }) } else { let userDict : NSDictionary = dataDict["userData"] as! NSDictionary let status : String = userDict["status"] as! String print("status: \(status)") if (status == "user saved" || status == "user updated") { DispatchQueue.main.sync(execute: { self.activityView.isHidden = true self.activityView.stopAnimating() self.submitBtn.isEnabled = true //self.submitBtn.alpha = 1 self.submitBtn.backgroundColor = self.appDelegate.crLightBlue self.loginBtn.isEnabled = true self.loginBtn.alpha = 1 if (status == "user saved") { let userid : NSNumber = userDict["userid"] as! NSNumber self.appDelegate.userid = "\(userid)" self.isNewUser = true self.appDelegate.email = self.emailTxt.text! } self.prefs.setValue(self.usernameTxt.text! , forKey: "username") self.prefs.setValue(self.emailTxt.text! , forKey: "email") self.prefs.setValue(self.passwordTxt.text! , forKey: "<PASSWORD>") self.prefs.synchronize() if self.isNewUser == true { self.dismissKeyboard() self.usernameTxt.text = "" self.emailTxt.text = "" self.passwordTxt.text = "" self.performSegue(withIdentifier: "signupConfirmation", sender: self) } }) } else { DispatchQueue.main.sync(execute: { self.showError(status: status) }) } } } catch let err as NSError { print("error: \(err.description)") } }.resume() } func showError (status: String) { self.activityView.isHidden = true self.activityView.stopAnimating() self.submitBtn.isEnabled = true //self.submitBtn.alpha = 1 self.loginBtn.isEnabled = true self.loginBtn.alpha = 1 self.submitBtn.backgroundColor = self.appDelegate.crLightBlue self.showBasicAlert(string: status) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } <file_sep>// // TranscriptionResult.swift // AIScribe // // Created by <NAME> on 5/24/19. // Copyright © 2019 RT. All rights reserved. // import UIKit import Alamofire class TranscriptionResult: UIViewController, UITableViewDelegate, UITableViewDataSource, UIWebViewDelegate { let appDelegate = UIApplication.shared.delegate as! AppDelegate var did : String? @IBOutlet weak var confidenceLbl: UILabel! @IBOutlet weak var headerLbl: UILabel! @IBOutlet weak var activityView: UIActivityIndicatorView! @IBOutlet weak var filenameLbl: UILabel! @IBOutlet weak var transcriptionTV: UITextView! var filename: String? @IBOutlet weak var saveBtn: UIButton! @IBOutlet weak var translationsView: UIView! var translationsList = NSMutableArray() var selectedFile: NSDictionary? @IBOutlet weak var translationTable: UITableView! @IBOutlet weak var previewView: UIView! var webView: UIWebView? var content : String? override func viewDidLoad() { super.viewDidLoad() self.confidenceLbl.text = "" activityView.startAnimating() translationsView.isHidden = true // Do any additional setup after loading the view. translationTable.tableFooterView = UIView() translationTable.dataSource = self translationTable.delegate = self previewView.isHidden = true transcriptionTV.textContainerInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) filenameLbl.text = filename getTranscriptionData() getTranslations() let keyboardDoneButtonView = UIToolbar() keyboardDoneButtonView.sizeToFit() let doneButton = UIBarButtonItem(title: "Done", style: .bordered, target: self, action: #selector(self.doneClicked)) keyboardDoneButtonView.items = [doneButton] transcriptionTV?.inputAccessoryView = keyboardDoneButtonView // Do any additional setup after loading the view. NotificationCenter.default.addObserver( self, selector: #selector(refreshTranslationsNotification1), name: NSNotification.Name(rawValue: "refreshTranslations1"), object: nil) } // MARK: Notifications @objc func refreshTranslationsNotification1 (notification: NSNotification) { print("handle") translationsList.removeAllObjects() getTranslations() } // MARK: Webservice func getTranslations() { print("getTranslations") let dataString = "translationData" let urlString = "\(appDelegate.serverDestination!)documentTranslationsJSON.php" let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" let paramString = "did=\(did!)&mobile=true&devStatus=\(appDelegate.devStage!)" print("urlString: \(urlString)") print("paramString: \(paramString)") request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let session = URLSession.shared session.dataTask(with: request) {data, response, err in do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary print("translations jsonResult: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary if dataDict[dataString]! is NSNull { print("no data") DispatchQueue.main.sync(execute: { self.translationsView.isHidden = false }) //self.statusLbl.isHidden = false } else { let uploadData : NSMutableArray = (dataDict[dataString]! as! NSArray).mutableCopy() as! NSMutableArray if (uploadData.count > 0) { //let list = uploadData as! NSMutableArray for ob in uploadData { let dict = ob as! NSDictionary self.translationsList.add(dict) } DispatchQueue.main.sync(execute: { self.activityView.isHidden = true self.activityView.stopAnimating() self.translationTable.reloadData() }) } else { DispatchQueue.main.sync(execute: { self.translationsView.isHidden = false //self.noResultsMain.isHidden = false }) } } } catch let err as NSError { print("error: \(err.description)") } }.resume() } func getTranscriptionData() { print("getTranscriptionData") let dataString = "transcriptionData" let urlString = "\(appDelegate.serverDestination!)transcriptionDataJSON.php" let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" let paramString = "did=\(did!)&mobile=true&devStatus=\(appDelegate.devStage!)" print("urlString: \(urlString)") print("paramString: \(paramString)") request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let session = URLSession.shared session.dataTask(with: request) {data, response, err in do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary print("transcription jsonResult: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary if dataDict[dataString]! is NSNull { print("no data") DispatchQueue.main.sync(execute: { //self.noResultsMain.isHidden = false }) } else { let uploadData = dataDict[dataString] as! NSDictionary self.content = uploadData.object(forKey: "response") as! String self.filename = uploadData.object(forKey: "filename") as? String let documentconfidence = uploadData.object(forKey: "documentconfidence") as? String DispatchQueue.main.sync(execute: { self.activityView.isHidden = true self.activityView.stopAnimating() self.transcriptionTV.text = self.content self.filenameLbl.text = self.filename if documentconfidence != "" { self.confidenceLbl.text = "Transcription Confidence: \(documentconfidence!)%" } else { self.confidenceLbl.text = "" } }) } } catch let err as NSError { print("error: \(err.description)") } }.resume() } func createDoc() { print("createDoc") let dataString = "docData" let urlString = "\(appDelegate.serverDestination!)/phpword/createDocJSON.php" let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" let str = filename?.split(separator: ".") let paramString = "filename=\(str![0])&input=\(transcriptionTV.text!)&mobile=true&devStatus=\(appDelegate.devStage!)" print("urlString: \(urlString)") print("paramString: \(paramString)") request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let session = URLSession.shared session.dataTask(with: request) {data, response, err in do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary print("docx jsonResult: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary if dataDict[dataString]! is NSNull { print("no data") DispatchQueue.main.sync(execute: { }) //self.statusLbl.isHidden = false } else { let uploadData = dataDict[dataString]! as! NSDictionary if (uploadData != nil) { //let list = uploadData as! NSMutableArray let status = uploadData.object(forKey: "status") as! String DispatchQueue.main.sync(execute: { self.activityView.isHidden = true self.activityView.stopAnimating() if status == "docx created successfully" { //download file let utilityQueue = DispatchQueue.global(qos: .utility) Alamofire.download("\(self.appDelegate.serverDestination!)\(self.filename!).docx") .downloadProgress(queue: utilityQueue) { progress in print("Download Progress: \(progress.fractionCompleted)") if(progress.fractionCompleted == 1.0) { print("done") DispatchQueue.main.sync(execute: { let appName = "ms-word" let appScheme = "/(appName)://app" //let appUrl = URL(string: appScheme) let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] //let url : NSString = "ms-word:ofv|u|https://www.dropbox.com/s/xxxxxx/new.docx?dl=0|p|xxxxxx|z|yes|a|App" as NSString let url : NSString = "\(appName):ofe|u|\(documentsPath)/\(self.filename!).docx|z|yes|a|App" as NSString let urlStr : NSString = url.addingPercentEscapes(using: String.Encoding.utf8.rawValue)! as NSString let searchURL : NSURL = NSURL(string: urlStr as String)! //UIApplication.shared.openURL(searchURL as URL) //if UIApplication.shared.canOpenURL(appUrl! as URL) if UIApplication.shared.canOpenURL(searchURL as URL) { print("App installed") UIApplication.shared.open(searchURL as URL) } else { print("App not installed") let alert = UIAlertController(title: nil, message: "Word doc successfully saved to your files.", preferredStyle: UIAlertControllerStyle.alert) self.present(alert, animated: true, completion: nil) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in switch action.style{ case .default: print("default") case .cancel: print("cancel") case .destructive: print("destructive") } })) } }) } } .responseData { response in if let data = response.result.value { print("data: \(data)") } } } }) } else { DispatchQueue.main.sync(execute: { //self.noResultsMain.isHidden = false }) } } } catch let err as NSError { print("error: \(err.description)") } }.resume() //https://stackoverflow.com/questions/46251025/how-to-edit-and-save-microsoft-word-document-in-ios-stored-in-local-directory //https://docs.microsoft.com/en-us/office/client-developer/office-uri-schemes // } // MARK: Tableview func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 44 } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = Bundle.main.loadNibNamed("FileHeaderCell", owner: self, options: nil)?.first as! FileHeaderCell headerView.headerLbl.text = "TRANSLATIONS" headerView.headerLbl.textColor = appDelegate.gray51 let font1 = UIFont.init(name: "Avenir-Heavy", size: 16.0) headerView.headerLbl.font = font1 headerView.leadingWidth.constant = 20 return headerView } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // let dict = translationsList[(indexPath as NSIndexPath).row] as! NSDictionary // // did = dict.object(forKey: "did") as! String } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 75 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.translationsList.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell")! let dict = translationsList[(indexPath as NSIndexPath).row] as! NSDictionary cell.selectionStyle = .none let v0 = cell.viewWithTag(1) as! UILabel let v1 = cell.viewWithTag(2) as! UILabel let v2 = cell.viewWithTag(3) as! UIButton v0.text = dict.object(forKey: "displayLang") as? String //v1.text = dict.object(forKey: "language") as? String v1.text = "" //v2.setTitle(dict.object(forKey: "transcription") as? String, for: .normal) //v3.setTitle(dict.object(forKey: "translations") as? String, for: .normal) v2.restorationIdentifier = "\(indexPath.row)" return cell } // MARK: File management func createPDF() { let html = "<b>\(self.filename!)</i></b> <p>\(transcriptionTV.text!)</p>" let fmt = UIMarkupTextPrintFormatter(markupText: html) // 2. Assign print formatter to UIPrintPageRenderer let render = UIPrintPageRenderer() render.addPrintFormatter(fmt, startingAtPageAt: 0) // 3. Assign paperRect and printableRect let page = CGRect(x: 0, y: 0, width: 595.2, height: 841.8) // A4, 72 dpi let printable = page.insetBy(dx: 0, dy: 0) render.setValue(NSValue(cgRect: page), forKey: "paperRect") render.setValue(NSValue(cgRect: printable), forKey: "printableRect") // 4. Create PDF context and draw let pdfData = NSMutableData() UIGraphicsBeginPDFContextToData(pdfData, .zero, nil) for i in 1...render.numberOfPages { UIGraphicsBeginPDFPage(); let bounds = UIGraphicsGetPDFContextBounds() render.drawPage(at: i - 1, in: bounds) } UIGraphicsEndPDFContext(); // 5. Save PDF file let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] pdfData.write(toFile: "\(documentsPath)/\(filename!).pdf", atomically: true) loadPDF(filename: filename!) } func loadPDF(filename: String) { let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] let url = URL(fileURLWithPath: documentsPath, isDirectory: true).appendingPathComponent(filename).appendingPathExtension("pdf") let urlRequest = URLRequest(url: url) webView = UIWebView(frame: CGRect.init(x: 0, y: 55, width: view.frame.width, height: view.frame.height-55)) webView!.delegate = self previewView.addSubview(webView!) previewView.isHidden = false webView!.loadRequest(urlRequest) let alert = UIAlertController(title: nil, message: "PDF successfully saved to your files.", preferredStyle: UIAlertControllerStyle.alert) self.present(alert, animated: true, completion: nil) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in switch action.style{ case .default: print("default") case .cancel: print("cancel") case .destructive: print("destructive") } })) } func createTxt() { var filePath = "" // Fine documents directory on device let dirs : [String] = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.allDomainsMask, true) if dirs.count > 0 { let dir = dirs[0] //documents directory filePath = dir.appending("/" + filename! + ".txt") print("Local path = \(filePath)") } else { print("Could not find local directory to store file") return } // Set the contents let fileContentToWrite = transcriptionTV.text! do { // Write contents to file try fileContentToWrite.write(toFile: filePath, atomically: false, encoding: String.Encoding.utf8) print("file saved") loadTXT(filename: filename!) let alert = UIAlertController(title: nil, message: "Text file successfully saved to your files.", preferredStyle: UIAlertControllerStyle.alert) self.present(alert, animated: true, completion: nil) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in switch action.style{ case .default: print("default") case .cancel: print("cancel") case .destructive: print("destructive") } })) } catch let error as NSError { print("An error took place: \(error)") } //http://swiftdeveloperblog.com/code-examples/read-and-write-string-into-a-text-file/ } func loadTXT(filename: String) { let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] let url = URL(fileURLWithPath: documentsPath, isDirectory: true).appendingPathComponent(filename).appendingPathExtension("pdf") let urlRequest = URLRequest(url: url) webView = UIWebView(frame: CGRect.init(x: 0, y: 55, width: view.frame.width, height: view.frame.height-55)) webView!.delegate = self previewView.addSubview(webView!) previewView.isHidden = false webView!.loadRequest(urlRequest) } func loadWordFile(file:String) { let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] let url = URL(fileURLWithPath: documentsPath, isDirectory: true).appendingPathComponent(file).appendingPathExtension("docx") let urlRequest = URLRequest(url: url) webView = UIWebView(frame: CGRect.init(x: 0, y: 55, width: view.frame.width, height: view.frame.height-55)) webView!.delegate = self previewView.addSubview(webView!) previewView.isHidden = false webView!.loadRequest(urlRequest) let alert = UIAlertController(title: nil, message: "Word doc successfully saved to your files.", preferredStyle: UIAlertControllerStyle.alert) self.present(alert, animated: true, completion: nil) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in switch action.style{ case .default: print("default") case .cancel: print("cancel") case .destructive: print("destructive") } })) } // MARK: Webview Delegate func webViewDidStartLoad(_ webView: UIWebView) { print("webview start load") } func webViewDidFinishLoad(_ webView: UIWebView) { print("webview finish load") } func webView(_ webView: UIWebView, didFailLoadWithError error: Error) { print("webview fail") } // MARK: Actions @IBAction func closePreview(_ sender: Any) { previewView.isHidden = true } @objc func doneClicked(sender: UIButton!) { self.view.endEditing(true) } @IBAction func createPDF(_ sender: Any) { createPDF() } @IBAction func createTXT(_ sender: Any) { createTxt() } @IBAction func createDOC(_ sender: Any) { createDoc() } @IBAction func viewTranslation(_ sender: Any) { let btn = sender as! UIButton let ind = Int(btn.restorationIdentifier!) selectedFile = translationsList[ind!] as? NSDictionary did = selectedFile!.object(forKey: "did") as? String self.performSegue(withIdentifier: "EditTranslation", sender: self) } @IBAction func updateTranscription(_ sender: Any) { } @IBAction func cancel(_ sender: Any) { self.navigationController?.popViewController(animated: true) self.dismiss(animated: true, completion: nil) } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "TranslationOptions" { let destination = segue.destination as! TranslationOptions destination.did = did destination.filename = filename destination.content = content } else if segue.identifier == "EditTranslation" { let destination = segue.destination as! TranslationResult destination.did = did destination.filename = filename destination.selectedFile = selectedFile } } } <file_sep>// // AboutUs.swift // AIScribe // // Created by <NAME> on 3/9/19. // Copyright © 2019 RT. All rights reserved. // import UIKit class AboutUs: UIViewController { @IBOutlet weak var textTV: UITextView! override func viewDidLoad() { super.viewDidLoad() textTV.text = "AIScribe is your on-the-go resource for all things healthy eating. No matter what your family's dietary restrictions, or how busy life gets, our mobile meal and menu app facilitates nutritious food choices so you can feel good about what you serve at your table." // Do any additional setup after loading the view. } @IBAction func cancel() { self.navigationController?.popViewController(animated: true) self.dismiss(animated: true, completion: nil) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ } <file_sep>// // Translate.swift // AIScribe // // Created by <NAME> on 5/24/19. // Copyright © 2019 RT. All rights reserved. // import UIKit import MobileCoreServices import Alamofire import AVFoundation class Translate: BaseViewController, UIPickerViewDelegate, UIPickerViewDataSource { let appDelegate = UIApplication.shared.delegate as! AppDelegate var sandboxURL : URL? var selectedLanguage : NSDictionary? var selectedCode : String? var hasFile: Bool? var languageList = NSMutableArray() var cost : Float? var file : NSDictionary? @IBOutlet weak var fileBtn: UIButton! @IBOutlet weak var filenameLbl: UILabel! @IBOutlet weak var filenameLblHeight: NSLayoutConstraint! @IBOutlet weak var activityView: UIActivityIndicatorView! @IBOutlet weak var menuBtn: UIButton! @IBOutlet weak var languageBtn: UIButton! @IBOutlet weak var transcribeBtn: UIButton! @IBOutlet weak var languagePicker: UIPickerView! @IBOutlet weak var languagePopup: UIView! override func viewDidLoad() { super.viewDidLoad() languageBtn.setTitle("Choose output language...", for: .normal) let tb : TabController = self.parent as! TabController menuBtn.addTarget(self, action: #selector(tb.onSlideMenuButtonPressed(_:)), for: UIControlEvents.touchUpInside) activityView.isHidden = true languagePicker.delegate = self languagePicker.dataSource = self filenameLbl.text = "" languagePopup.isHidden = true filenameLblHeight.constant = 0 transcribeBtn.isEnabled = false getLanguages() NotificationCenter.default.addObserver( self, selector: #selector(hideTranscribePickerNotification), name: NSNotification.Name(rawValue: "hideTranscribePicker"), object: nil) NotificationCenter.default.addObserver( self, selector: #selector(resetTranslationNotification), name: NSNotification.Name(rawValue: "resetTranslation"), object: nil) } @objc func resetTranslationNotification (notification: NSNotification) { print("reset translation defaults") file = nil languagePicker.selectRow(0, inComponent: 0, animated: false) filenameLbl.text = "" languagePopup.isHidden = true filenameLblHeight.constant = 0 transcribeBtn.isEnabled = false languageBtn.setTitle("Choose output language...", for: .normal) languageBtn.backgroundColor = UIColor.init(red: 214/255.0, green: 217/255.0, blue: 217/255.0, alpha: 1.0) transcribeBtn.backgroundColor = appDelegate.gray74 transcribeBtn.setTitle("TRANSLATE", for: .normal) selectedCode = nil } @objc func hideTranscribePickerNotification (notification: NSNotification) { print("hideTranscribePickerNotification") languagePopup.isHidden = true } @IBAction func showPopup(_ sender: Any) { if selectedLanguage == nil { selectedLanguage = languageList[0] as! NSDictionary } languagePopup.isHidden = false } @IBAction func translateFile(_ sender: Any) { print("translate file") activityView.startAnimating() activityView.isHidden = false transcribeBtn.isEnabled = false fileBtn.isEnabled = false languageBtn.isEnabled = false transcribeBtn.setTitle("TRANSLATING", for: .normal) initTranslate() } @IBAction func selectLanguage(_ sender: Any) { selectedCode = selectedLanguage?.object(forKey: "code") as? String let selectedLang = selectedLanguage?.object(forKey: "displayname") as? String languageBtn.setTitle(selectedLang, for: .normal) languagePopup.isHidden = true validateForm() } func validateForm() { if selectedLanguage != nil && hasFile == true { transcribeBtn.backgroundColor = appDelegate.crGreen transcribeBtn.isEnabled = true } } @IBAction func openFile(_ sender: Any) { let docPicker = UIDocumentPickerViewController(documentTypes: [kUTTypeText as String], in: .import) //let docPicker = UIDocumentPickerViewController(documentTypes: [kUTTypeText as String, kUTTypePDF as String], in: .import) docPicker.delegate = self docPicker.allowsMultipleSelection = false present(docPicker, animated: true, completion: nil) } // MARK: Webservice func getLanguages() { print("getLanguages") let dataString = "languageData" let urlString = "\(appDelegate.serverDestination!)getLanguages.php" let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" let paramString = "mobile=true&devStatus=\(appDelegate.devStage!)" print("urlString: \(urlString)") print("paramString: \(paramString)") request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let session = URLSession.shared session.dataTask(with: request) {data, response, err in do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary print("languages jsonResult: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary if dataDict[dataString]! is NSNull { print("no data") DispatchQueue.main.sync(execute: { //self.noResultsMain.isHidden = false }) //self.statusLbl.isHidden = false } else { let uploadData : NSMutableArray = (dataDict[dataString]! as! NSArray).mutableCopy() as! NSMutableArray if (uploadData.count > 0) { //let list = uploadData as! NSMutableArray for ob in uploadData { let dict = ob as! NSDictionary self.languageList.add(dict) } DispatchQueue.main.sync(execute: { self.activityView.isHidden = true self.activityView.stopAnimating() self.languagePicker.reloadAllComponents() }) } else { DispatchQueue.main.sync(execute: { //self.noResultsMain.isHidden = false }) } } } catch let err as NSError { print("error: \(err.description)") } }.resume() } func initTranslate() { print("initTranslate") let dataString = "translateData" let urlString = "\(appDelegate.serverDestination!)IBM-translate.php" let url = URL(string: urlString) var request = URLRequest(url: url!) request.httpMethod = "POST" let language = self.selectedLanguage?.object(forKey: "code") as! String // let params = [ // "userid": appDelegate.userid, // "language": language, // "estimatedCost": self.cost!, // "displayLang": selectedLanguage?.object(forKey: "displayname") as? String, // "fileName": sandboxURL!.lastPathComponent, // "fileType": sandboxURL!.pathExtension, // "mobile": "true" // ] let displayLanguage = selectedLanguage?.object(forKey: "displayname") as? String let paramString = "uid=\(appDelegate.userid!)&fileName=\(sandboxURL!.lastPathComponent)&fileType=\(sandboxURL!.pathExtension)&displayLanguage=\(displayLanguage!)&language=\(language)&estimatedCost=\(self.cost!)&mobile=true&devStatus=\(appDelegate.devStage!)" print("urlString: \(urlString)") print("paramString: \(paramString)") request.httpBody = paramString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let session = URLSession.shared session.dataTask(with: request) {data, response, err in do { let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary print("transcribeData jsonResult: \(jsonResult)") let dataDict : NSDictionary = jsonResult.object(forKey: "data") as! NSDictionary if dataDict[dataString]! is NSNull { print("no data") DispatchQueue.main.sync(execute: { self.activityView.isHidden = true self.activityView.stopAnimating() //self.noResultsMain.isHidden = false }) //self.statusLbl.isHidden = false } else { let transcribeData = dataDict[dataString]! as! NSDictionary if (transcribeData != nil) { DispatchQueue.main.sync(execute: { if transcribeData.object(forKey: "translationid") != nil { let translationid = transcribeData.object(forKey: "translationid") as! String let translation = transcribeData.object(forKey: "translation") as! String let did = transcribeData.object(forKey: "did") as! String self.file = NSMutableDictionary() self.file!.setValue(translation, forKey: "translation") self.file!.setValue(translationid, forKey: "translationid") self.file!.setValue(did, forKey: "did") self.file!.setValue(self.selectedLanguage?.object(forKey: "displayname") as? String, forKey: "displayLanguage") self.activityView.isHidden = true self.activityView.stopAnimating() self.fileBtn.isEnabled = true self.languageBtn.isEnabled = true NotificationCenter.default.post(name: Notification.Name("refreshFiles"), object: nil) self.performSegue(withIdentifier: "EditTranslation", sender: nil) } else { let status = transcribeData.object(forKey: "status") as! String self.activityView.isHidden = true self.activityView.stopAnimating() self.fileBtn.isEnabled = true self.languageBtn.isEnabled = true self.transcribeBtn.isEnabled = true self.transcribeBtn.backgroundColor = self.appDelegate.crGreen self.transcribeBtn.setTitle("TRANSLATE", for: .normal) let alert = UIAlertController(title: nil, message: status, preferredStyle: UIAlertControllerStyle.alert) self.present(alert, animated: true, completion: nil) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in switch action.style{ case .default: print("default") case .cancel: print("cancel") case .destructive: print("destructive") } })) } }) } else { DispatchQueue.main.sync(execute: { self.activityView.isHidden = true self.activityView.stopAnimating() //self.noResultsMain.isHidden = false }) } } } catch let err as NSError { print("error: \(err.description)") } }.resume() } func initTranslateAF () { let language = self.selectedLanguage?.object(forKey: "code") as! String print("ext: \(sandboxURL!.pathExtension)") print("filename: \(sandboxURL!.lastPathComponent)") let params = [ "userid": appDelegate.userid, "language": language, "estimatedCost": "\(self.cost!)", "displayLang": selectedLanguage?.object(forKey: "displayname") as? String, "fileName": sandboxURL!.lastPathComponent, "fileType": sandboxURL!.pathExtension, "mobile": "true" ] Alamofire.upload( multipartFormData: { multipartFormData in multipartFormData.append(self.sandboxURL!, withName: "file") for (key, value) in params { multipartFormData.append((value?.data(using: String.Encoding.utf8)!)!, withName: key) } }, to: "http://localhost:8888/aiscribe/IBM-translate.php", encodingCompletion: { encodingResult in switch encodingResult { case .success(let upload, _, _): upload.responseJSON { response in print("response: \(response)") if let JSON = response.result.value { //print("JSON: \(JSON)") let dataDict : NSDictionary = JSON as! NSDictionary let data = dataDict.object(forKey: "data") as! NSDictionary let transcribeData = data.object(forKey: "translateData") as! NSDictionary let translationid = transcribeData.object(forKey: "translationid") as! String if translationid != "none" { let translation = transcribeData.object(forKey: "translation") as! String let did = transcribeData.object(forKey: "did") as! String self.file = NSMutableDictionary() self.file!.setValue(translation, forKey: "translation") self.file!.setValue(translationid, forKey: "translationid") self.file!.setValue(did, forKey: "did") self.file!.setValue(self.selectedLanguage?.object(forKey: "displayname") as? String, forKey: "displayLang") self.performSegue(withIdentifier: "EditTranslation", sender: nil) } } //debugPrint(response) } case .failure(let encodingError): print(encodingError) } } ) } func getWordCount () { let params = [ "mobile": "true" ] Alamofire.upload( multipartFormData: { multipartFormData in multipartFormData.append(self.sandboxURL!, withName: "file") for (key, value) in params { multipartFormData.append((value.data(using: String.Encoding.utf8)!), withName: key) } }, to: "http://localhost:8888/aiscribe/getWordCountAF.php", encodingCompletion: { encodingResult in switch encodingResult { case .success(let upload, _, _): upload.responseJSON { response in print("response: \(response)") if let JSON = response.result.value { //print("JSON: \(JSON)") let dataDict : NSDictionary = JSON as! NSDictionary let data = dataDict.object(forKey: "data") as! NSDictionary let wordData = data.object(forKey: "wordData") as! NSDictionary //let len = dataDict.object(forKey: "len") let costS = wordData.object(forKey: "total") as? Double self.cost = Float(costS!) //print("len: \(len!)") self.hasFile = true self.filenameLblHeight.constant = 50 let cd = String(format: "%.2f", self.cost!) self.filenameLbl.text = "\(self.sandboxURL!.lastPathComponent)\n Estimated Cost: $\(cd)" self.validateForm() } //debugPrint(response) } case .failure(let encodingError): print(encodingError) } } ) //https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#uploading-data-to-a-server } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "EditTranslation" { let destination = segue.destination as! TranslationResult destination.selectedFile = file } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ } extension Translate : UIDocumentPickerDelegate { func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) { guard let selectedURL = urls.first else { return } let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! sandboxURL = dir.appendingPathComponent(selectedURL.lastPathComponent) if FileManager.default.fileExists(atPath: sandboxURL!.path) { print("do nothin") print("sandboxURL: \(sandboxURL!)") print("selectedURL: \(selectedURL)") print("ext: \(sandboxURL!.pathExtension)") print("filename: \(sandboxURL!.lastPathComponent)") // if sandboxURL!.pathExtension == "pdf" || sandboxURL!.pathExtension == "txt" || sandboxURL!.pathExtension == "doc" // { if sandboxURL!.pathExtension == "txt" || sandboxURL!.pathExtension == "doc" { filenameLblHeight.constant = 50 //filenameLbl.text = sandboxURL!.lastPathComponent getWordCount() // self.hasFile = true // self.filenameLblHeight.constant = 50 // self.filenameLbl.text = "\(self.sandboxURL!.lastPathComponent)\n Estimated Cost: \(self.cost!)" // // self.validateForm() } else { let alert = UIAlertController(title: nil, message: "Invalid file type", preferredStyle: UIAlertControllerStyle.alert) self.present(alert, animated: true, completion: nil) alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { action in switch action.style{ case .default: print("default") case .cancel: print("cancel") case .destructive: print("destructive") } })) } } else { do { try FileManager.default.copyItem(at: selectedURL, to: sandboxURL!) print("copied!") } catch { print("Error: \(error)") } } } // MARK: Pickerview func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return languageList.count } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { selectedLanguage = languageList[row] as? NSDictionary } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { let lang = languageList[row] as! NSDictionary let model = lang.object(forKey: "displayname") as? String return model } }
e74cbcdd8d7141722e2fd45c95c6b9aa45227f6d
[ "Swift", "Ruby" ]
42
Swift
ridleytech/aiscribe-ios
82f19bfc61ebd286cc91c82b388a1ba79528032c
a45fd0a52dbefee715a2f6e471165a9717f11c2d
refs/heads/main
<file_sep># Wish Them All ## Wish your dearest and closest ones on their birthday using this Birthday Assistant!<file_sep>from functions import * if __name__ == '__main__': while True: if checkBirthday(): wish() break<file_sep># pip install pandas # pip install openpyxl # pip install datetime # pip install regex # pip install smtplib import pandas as pd from datetime import datetime import re import smtplib from keys import * # check if anyone has their birthday today def checkBirthday(): data = pd.read_excel(r'birthday sheet.xlsx') df = pd.DataFrame(data) Name = df['Name'].tolist() Email = df['Email'].tolist() Birthdate = df['Birthdate (DD-MM-YYYY)'].tolist() # populating the data to a list for easy referencing later all_data = [] for name,email,birthdate in zip(Name,Email,Birthdate): all_data.append([name,email,birthdate]) # print(all_data) # date and time right now now = datetime.today().strftime("%m-%d") #print(formatted_date) # checking if the birthdate matches with today's date for i in all_data: individualBirthdate = str(i[2]) # formatting the date using the regex library pattern = re.compile(r"(\d{4})-(\d{2})-(\d{2})") results = re.search(pattern, individualBirthdate) # grouping the date and the month of his/her birthdate date = f"{results.group(2)}-{results.group(3)}" # return names, email's of people who have their birthday today wishThem = [] if date == now: wishThem.append([i[0],i[1]]) return wishThem def wish(): birthdays = checkBirthday() # send a birthday email to every person in the list for i in range(len(birthdays)): with smtplib.SMTP('smtp.gmail.com', 587) as smtp: smtp.ehlo() smtp.starttls() smtp.ehlo() smtp.login(EMAIL_ADDRESS,PASSWORD) msg = f''' Happy Birthday {birthdays[i][0]}! - Sent via Anish's programmed assistant. Thank you! '''.encode('utf-8') smtp.sendmail(EMAIL_ADDRESS, birthdays[i][1], msg)
a9e4322af7a7e6423ed88a52a03a4f2ff0553663
[ "Markdown", "Python" ]
3
Markdown
anishdhandore/Wish-Them-All
d41299f6b814f2c613e9f4d5399453f0c8d96fd0
2fb24845f34bc2703f73e1d3f937b707df8195c2
refs/heads/master
<file_sep>/* DS1621.cpp - Arduino library for Maxim DS1621 Digital Thermometer this library is free software: you can redistribute it and/or modify it. THIS SOFTWARE IS PROVIDED IN AN "AS IS" CONDITION WITHOUT ANY WARRANTIES Thermostat functions not yet implemented */ #include "LIS302DL.h" #include <Wire.h> LIS302DL::LIS302DL(short addr,long speed){ TWBR=speed; Wire.begin(); _addr=addr; } LIS302DL::LIS302DL(short addr){ Wire.begin(); _addr=addr; } uint8_t LIS302DL::readRegister(uint8_t reg){ uint8_t r; Wire.beginTransmission(_addr); Wire.write(reg); // register to read Wire.endTransmission(); Wire.requestFrom(_addr,1); // read a byte r = Wire.read(); return r; } void LIS302DL::writeRegister(uint8_t reg,uint8_t val) { Wire.beginTransmission(_addr); Wire.write(reg); Wire.write(val); Wire.endTransmission(); delay(10); } float LIS302DL::readX(){ float x; char _x; _x=readRegister(_X); x=_x*0.018; return(x); } float LIS302DL::readY(){ float y; char _y; _y=readRegister(_Y); y=_y*0.018; return(y); } float LIS302DL::readZ(){ float z; char _z; _z=readRegister(_Z); z=_z*0.018; return(z); } void LIS302DL::xOn(){ _ctrl_reg1_buff|=_X_ON; writeRegister(_CTRL_REG1,_ctrl_reg1_buff); } void LIS302DL::xOff(){ _ctrl_reg1_buff &=_X_OFF; writeRegister(_CTRL_REG1,_ctrl_reg1_buff); } void LIS302DL::yOn(){ _ctrl_reg1_buff|=_Y_ON; writeRegister(_CTRL_REG1,_ctrl_reg1_buff); } void LIS302DL::yOff(){ _ctrl_reg1_buff &=_Y_OFF; writeRegister(_CTRL_REG1,_ctrl_reg1_buff); } void LIS302DL::zOn(){ _ctrl_reg1_buff|=_Z_ON; writeRegister(_CTRL_REG1,_ctrl_reg1_buff); } void LIS302DL::zOff(){ _ctrl_reg1_buff &=_Z_OFF; writeRegister(_CTRL_REG1,_ctrl_reg1_buff); } void LIS302DL::highSpeed(){ _ctrl_reg1_buff|=_HIGH_SPEED; writeRegister(_CTRL_REG1,_ctrl_reg1_buff); } void LIS302DL::lowSpeed(){ _ctrl_reg1_buff &=_LOW_SPEED; writeRegister(_CTRL_REG1,_ctrl_reg1_buff); } void LIS302DL::fullRange(){ _ctrl_reg1_buff|=_FULL_RANGE; writeRegister(_CTRL_REG1,_ctrl_reg1_buff); } void LIS302DL::highSens(){ _ctrl_reg1_buff &=_HIGH_SENS; writeRegister(_CTRL_REG1,_ctrl_reg1_buff); } void LIS302DL::turnOn(){ _ctrl_reg1_buff|=_ON; writeRegister(_CTRL_REG1,_ctrl_reg1_buff); } void LIS302DL::turnOff(){ _ctrl_reg1_buff &=_OFF; writeRegister(_CTRL_REG1,_ctrl_reg1_buff); }<file_sep>#include "LIS302DL.h" #include "Wire.h" LIS302DL sens(0x1c,40000);//inizialize LIS302DL and Wire (i2c slave address,i2c speed) float z; void setup() { Serial.begin(19200); sens.turnOn();//turn on the device sens.zOn();//turn on z axes sens.highSpeed();//output data rate 400hz } void loop() { z=sens.readZ(); delay(3); Serial.println(z); } <file_sep>/* LIS302DL.h - Arduino library for Maxim DS1621 Digital Thermometer this library is free software: you can redistribute it and/or modify it. THIS SOFTWARE IS PROVIDED IN AN "AS IS" CONDITION WITHOUT ANY WARRANTIES Thermostat functions not yet implemented */ #ifndef LIS302DL_H #define LIS302DL_H #include "Arduino.h" class LIS302DL{ static const uint8_t _X = 0x29; static const uint8_t _Y = 0x2b; static const uint8_t _Z = 0x2d; static const uint8_t _CTRL_REG1=0x20; static const uint8_t _ON = 0x40; static const uint8_t _X_ON = 0x01; static const uint8_t _Y_ON = 0x02; static const uint8_t _Z_ON = 0x04; static const uint8_t _HIGH_SPEED= 0x80; static const uint8_t _FULL_RANGE= 0x20;// static const uint8_t _OFF = 0xBF; static const uint8_t _X_OFF = 0xFE; static const uint8_t _Y_OFF = 0xFD; static const uint8_t _Z_OFF = 0xFB; static const uint8_t _LOW_SPEED= 0x7F; static const uint8_t _HIGH_SENS= 0xDF; uint8_t _ctrl_reg1_buff; void writeRegister(uint8_t reg,uint8_t val); uint8_t readRegister(uint8_t reg); short _addr; public: LIS302DL(short addr,long speed);//Object constructor (i2c slave address,i2c speed) 40000=400Khz LIS302DL(short addr); void zOn();//turn on z axes void zOff();//turn off z axes void yOn();//turn on y axes void yOff();//turn off y axes void xOn();//turn on x axes void xOff();//turn off x axes void turnOn(); void turnOff(); float readX();//read x axes float readY();//read y axes float readZ();//read z axes void highSpeed();//output data rate 400hz void lowSpeed();//output data rate 100hz void fullRange();//±9.2g range sensitivity 72 mg/digit void highSens();//±2.3g range sensitivity 18 mg/digit }; #endif
152064aafdb6d3b11dfd0aa9848544ece1acbf0a
[ "C++" ]
3
C++
TommasoS/LIS302DL
16969edc5f2777d29cc7bf5faa267fe1572d7d52
535fdcbe7c0aa50406e10c992525a7ea378b2b1b
refs/heads/master
<repo_name>Refuro/StockBot<file_sep>/README.md # StockBot A bot that pulls stock information on Discord <file_sep>/main.js const { prefix, token } = require('./config.json'); const Discord = require('discord.js'); const client = new Discord.Client(); //const server = new Server(); client.once('ready', () => { console.log('Ready!'); }); client.on('message', message => { if (!message.content.startsWith(prefix) || message.author.bot) return; const args = message.content.slice(prefix.length).split(/ +/); const command = args.shift().toLowerCase(); if (command === 'help'){ message.channel.send('Currently this bot has little functionality and is in testing phase.\n\nCurrent Commands: !hello(returns a greeting).\n!time(returns time).\n\nFuture commands: !(stock ticker name). For example, !MSFT would return \'Microsoft:$178.72\''); console.log('!help was called'); } if (command === 'hello'){ message.channel.send('Hey there @'+String(message.author)); console.log('!hello was called'); } if (command === 'time'){ const now = new Date(); message.channel.send(String(now.getHours()) + ":" + String(now.getMinutes()) + ":" + String(now.getSeconds())); console.log('!time was called'); delete now; } if (command === 'channel'){ message.channel.send(String(message.author)+ ' is in the ' +String(message.channel)+' channel in '+ String(message.guild.name)+' server.'); console.log('!channel was called'); } if (command === 'test'){ message.reply(`Vacant for now.`); console.log('!test'); } if (command === 'kick'){ if (!message.mentions.users.size) { return message.reply('you need to tag a user in order to kick them!'); } const kicker = message.author; const userX = message.mentions.users.first(); var reason; message.reply('Provide a reason or type skip'); if (message.author === kicker && message.content.startsWith('no')){ message.channel.send(':thumbsup'); } else{ reason = "Fuck"; } } }); client.login(token);
320f434f7be9a6314ba4ce0a16662eb05f860572
[ "Markdown", "JavaScript" ]
2
Markdown
Refuro/StockBot
36133edb202af523c15de86ca08a2b2c1ce7ac21
fd7b49483ca43e10ee05f9cedbf93d912e1739f3
refs/heads/master
<file_sep># -*- coding: utf-8 -*- menu={} while True: x = raw_input("Prosim vnesi jed: ") y = raw_input("Prosim vnesi ceno(v €): ") menu['Jed'] = x menu['Cena(EUR)'] = y print "Vnesili ste jed "+ x+ " in ji določili ceno "+y+"€" z = raw_input("Ali želite dodati še kakšno jed? (da/ne): ") if z=="ne": print "Najlepša hvala za sodelovanje." break menu_file = open("menu.txt", "w+") menu_file.write("Dnevni meni:\n") for key, value in menu.iteritems(): menu_file.write("%s: %s\n" % (key, value)) menu_file.close()
6671560942e6b974efe16ba204ee2d2727f80756
[ "Python" ]
1
Python
tadejbucar/jedilnik
a9ee77bae28dd30d1868adf5d09f5c85be720a16
db57e0f8f9f00db8248316d7326c7b686786e1d4
refs/heads/master
<file_sep>/** * Classe No (da arvore) */ /** * @author Eduardo * */ public class No { private Pessoa pessoa; private No noEsquerda; private No noDireita; public No() { } public No(Pessoa pessoa) { this.pessoa = pessoa; } public Pessoa getPessoa() { return pessoa; } public void setValor(Pessoa pessoa) { this.pessoa = pessoa; } public No getNoEsquerda() { return noEsquerda; } public void setNoEsquerda(No noEsquerda) { this.noEsquerda = noEsquerda; } public No getNoDireita() { return noDireita; } public void setNoDireita(No noDireita) { this.noDireita = noDireita; } @Override public String toString() { return "No [valor=" + pessoa + "]"; } } <file_sep># Trabalho sobre Árvores Trabalho sobre árvores da disciplina de LPII. <file_sep>/** * Classe Arvore */ /** * @author Eduardo, Tharles * */ public class Arvore { public No raiz; public Arvore() { this.raiz = null; } /** * @author <NAME> * @param nome * Busca uma nó na árvore. */ public No busca(String nome) { No noatual = this.raiz; while (noatual != null) { if (nome == noatual.getPessoa().getNome()) { return noatual; } else if (noatual.getPessoa().getNome().compareTo(nome) > 0) { noatual = noatual.getNoEsquerda(); } else { noatual = noatual.getNoDireita(); } } return noatual; } /** * @author Eduardo, Tharles * @param no * @param pessoa * Busca um nó na árvore. */ public void inserirNo(No no, Pessoa pessoa) { if (this.raiz == null) { this.raiz = new No(pessoa); } else if (no.getPessoa().getNome().compareTo(pessoa.getNome()) == 0) { return; } else if (no.getPessoa().getNome().compareTo(pessoa.getNome()) > 0) { if (no.getNoEsquerda() != null) { inserirNo(no.getNoEsquerda(), pessoa); } else { no.setNoEsquerda(new No(pessoa)); } } else if (no.getPessoa().getNome().compareTo(pessoa.getNome()) < 0) { if (no.getNoDireita() != null) { inserirNo(no.getNoDireita(), pessoa); } else { no.setNoDireita(new No(pessoa)); } } } /** * @author <NAME> * @param no * @param pessoa * @return no * @throws Exception * Remove um nó da árvore. */ public No removerNo(No no, String pessoa) throws Exception { if (this.raiz == null) { throw new Exception("A árvore está vazia."); } else { if (no.getPessoa().getNome().compareTo(pessoa) > 0) { no.setNoEsquerda(removerNo(no.getNoEsquerda(), pessoa)); } else if (no.getPessoa().getNome().compareTo(pessoa) < 0) { no.setNoDireita(removerNo(no.getNoDireita(), pessoa)); } else { if (no.getNoEsquerda() != null && no.getNoDireita() != null) { System.out.println("Removido."); no.setValor(encontrarMinimo(no.getNoDireita()).getPessoa()); no.setNoDireita(removerMinimo(no.getNoDireita())); } else if (no.getNoDireita() != null) { no = no.getNoDireita(); } else { no = no.getNoEsquerda(); } } } return no; } /** * @author Eduardo * @param no * @return no * Busca o nó mínimo da árvore. */ public No removerMinimo(No no) { if (no == null) { System.out.println("Erro. Nó vazio."); } else if (no.getNoEsquerda() != null) { no.setNoEsquerda(removerMinimo(no.getNoEsquerda())); return no; } else { return no.getNoDireita(); } return null; } /** * @author Eduardo * @param no * @return no * Encontro o nó mínimo da árvore. */ public No encontrarMinimo(No no) { if (no != null) { while (no.getNoEsquerda() != null) { no = no.getNoEsquerda(); } } return no; } /** * @author Tharles * @param no * @return no * Encontro o nó máximo da árvore */ public No encontrarMaximo(No no) { if (no != null) { while (no.getNoDireita() != null) { no = no.getNoDireita(); } } return no; } /** * @author Eduardo * @param no * @return no * Encontra a altura da árvore */ public int alturaNo(No no) { if (no == null) { return 0; } int altEsq = alturaNo(no.getNoEsquerda()); int altDir = alturaNo(no.getNoDireita()); if (altEsq > altDir) { return altEsq + 1; } else { return altDir + 1; } } /** * @author Tharles * @param no * @return no * Caminhamento pré-fixado da árvore */ public void prefixado(No no) { if (no != null) { no.getPessoa().imprimeDados(); prefixado(no.getNoEsquerda()); prefixado(no.getNoDireita()); } } /** * @author Tharles * @param no * @return no * Caminhamento pós-fixado da árvore */ public void posfixado(No no) { if (no != null) { posfixado(no.getNoEsquerda()); posfixado(no.getNoDireita()); no.getPessoa().imprimeDados(); } } }
63d6f0cb9c7a020384092274e4408319b09fcfb7
[ "Markdown", "Java" ]
3
Java
edumarques/TrabalhoArvores
d9fa87c426f8ccda42e9fedaf47765c5ca169acf
21f6f159f55edfd7b11a41a2f5be0a650b8ecf6a
refs/heads/master
<file_sep># JogoDaVelha_RBC Trabalho para a disciplina GCC251 - Fundamentos de Programação II, que consiste na implementação de um jogo da velha com raciocínio baseado em caso. A máquina aprende a jogar salvando os resultados e jogadas em memória, e reutilizando-os em outras partidas. <file_sep>#include <iostream> #include <fstream> #include <cstdlib> using namespace std; typedef struct { char jogador = '-'; int linha = -1; int coluna = -1; } Movimento; class noh { friend class tabelaHash; //~ friend inline bool operator==(const noh& noh1, const noh& noh2); private: /* Vetor de 9 posições, as posições são as seguintes * 0 | 1 | 2 * ---+---+--- * 3 | 4 | 5 * ---+---+--- * 6 | 7 | 8 */ Movimento* movimento; char vencedor; int nVitorias; noh* proximo; public: noh(Movimento* m, char winner, int vitorias = 0) { // for (int i = 0; i < 9; i++) { // cout << m[i].linha << "*" << m[i].coluna << endl; // } movimento = new Movimento[9]; for (int i = 0; i < 9; i++) movimento[i] = m[i]; vencedor = winner; nVitorias = vitorias; proximo = NULL; } ~noh(){ delete[] movimento; proximo = NULL; } }; // Sobrecarga de operadores //~ inline bool operator==(const noh& noh1, const noh& noh2){ //~ for (int i = 0; i < 9; i++) { //~ if(noh1.movimento[i].coluna != noh2.movimento[i].coluna) return false; //~ else if(noh1.movimento[i].linha != noh2.movimento[i].linha) return false; //~ else if(noh1.movimento[i].jogador != noh2.movimento[i].jogador) return false; //~ } //~ return true; //~ } inline int funcaoHash(Movimento* m) { return m[0].linha*3 + m[0].coluna; } class tabelaHash { private: //vetor de ponteiro de no noh** elementos; int capacidade; public: tabelaHash(int cap = 9) { elementos = new noh*[cap]; capacidade = cap; for (int i = 0; i < cap; i++) { elementos[i] = NULL; } } ~tabelaHash() { for (int i = 0; i < capacidade; i++) { noh* atual = elementos[i]; //percorre a lista removendo todos os nos while (atual != NULL) { noh* aux = atual; atual = atual->proximo; delete aux; } } delete[] elementos; } //insere um valor v com chave c void insere(Movimento* m, char winner, int vitorias = 0) { //cout << "Inserindo no hash" << endl; // Encontrando a posição para inserir int h; h = funcaoHash(m); if (recupera(m) == "NAO ENCONTRADO!") { if (elementos[h] == NULL) { elementos[h] = new noh(m, winner, vitorias); } else { //cout << "colidiu" << endl; noh* atual = elementos[h]; //achando local para inserção while (atual->proximo != NULL) { atual = atual->proximo; } noh* novo = new noh(m, winner); atual->proximo = novo; } } else if(recupera(m) == "JA ESTA NO HASH") { altera(m); } else { cout << "Item ja esta na tabela2" << endl; } } bool comparaMovimentos(Movimento* noh1, Movimento* noh2){ for (int i = 0; i < 9; i++) { if(noh1[i].coluna != noh2[i].coluna) return false; else if(noh1[i].linha != noh2[i].linha) return false; else if(noh1[i].jogador != noh2[i].jogador) return false; } return true; } //recupera um valor associado a uma chave string recupera(Movimento* m) { int h; h = funcaoHash(m); if ((elementos[h] != NULL) and (comparaMovimentos(elementos[h]->movimento, m))) { //~ for (int i = 0; i < 9; i++) { //~ cout << elementos[h]->movimento[i].linha << " " << elementos[h]->movimento[i].coluna << endl; //~ } return "JA ESTA NO HASH"; } else { noh* atual = elementos[h]; while ((atual != NULL) and !(comparaMovimentos(atual->movimento, m))) { atual = atual->proximo; } if ((atual != NULL) and (comparaMovimentos(atual->movimento, m))) { return "JA ESTA NO HASH"; } else { return "NAO ENCONTRADO!"; } } } //altera um valor associado a uma chave, basicamente incrementa o numero de vitorias void altera(Movimento* m) { //nao trata colisao e nem chave nao encontrada int h; h = funcaoHash(m); if(recupera(m) == "JA ESTA NO HASH"){ if ((elementos[h] != NULL) and (comparaMovimentos(elementos[h]->movimento, m))) { elementos[h]->nVitorias += 1; } else { noh* atual = elementos[h]; while ((atual != NULL) and !(comparaMovimentos(atual->movimento, m))) { atual = atual->proximo; } if ((atual != NULL) and (comparaMovimentos(atual->movimento, m))) { atual->nVitorias += 1; } else { cerr << "ERRO NA ALTERACAO!" << endl; } } } else { cerr << "O jogo não está armazenado" << endl; } } int gerarMovimentoAleatorio(char** tabuleiro){ int* posicoes_disponiveis = new int[9]; int quantidade_disponivel = 0; // Verifica todas as posições disponíveis e adiciona elas em um vetor for (int lin = 0; lin < 3; lin++) { for (int col = 0; col < 3; col++){ if(tabuleiro[lin][col] == '-') { posicoes_disponiveis[quantidade_disponivel] = lin*3 + col; quantidade_disponivel++; } } } srand(time(NULL)); // Pega um indice aleatorio e retorna a posição atribuida a ele int retorno = posicoes_disponiveis[rand() % quantidade_disponivel]; delete[] posicoes_disponiveis; return retorno; } int obterProximoMovimento(Movimento* m, int numero_da_jogada){ int h; h = funcaoHash(m); noh* atual = elementos[h]; if(atual != NULL) { while(atual != NULL) { // Procurar jogada idêntica bool jogada_ainda_serve = true; // Verificando até a posição da jogada atual se é igual a jogada armazenada for (int i = 0; i < numero_da_jogada and jogada_ainda_serve; i++) { if((m[i].linha == atual->movimento[i].linha) or (m[i].coluna == atual->movimento[i].coluna)){ if(atual->movimento[numero_da_jogada].jogador == atual->vencedor and m[numero_da_jogada].jogador == '-'){ cout << "Encontrei uma jogada :)" << endl << endl; return atual->movimento[numero_da_jogada].linha * 3 + atual->movimento[numero_da_jogada].coluna; } } else{ jogada_ainda_serve = false; } } //~ if(jogada_ainda_serve and (atual->movimento[numero_da_jogada].jogador == atual->vencedor)){ //~ cout << "Encontrei uma jogada :)" << endl << endl; //~ return atual->movimento[numero_da_jogada].linha * 3 + atual->movimento[numero_da_jogada].coluna; //~ } atual = atual->proximo; } // Se chegar aqui, gerar aleatorio também, não encontrou jogada igual cout << "Não encontrei uma jogada, vou gerar aleatorio :|" << endl << endl; return -1; } else { cout << "Não encontrei uma jogada, vou gerar aleatorio :|" << endl << endl; return -1; // Não tem jogo em que o primeiro movimento é nesta posição, necessário gerar aleatorio } } /* //retira um valor associado a uma chave void remove(string c) { int h; h = funcaoHash(c, capacidade); if ((elementos[h] != NULL) and (elementos[h]->chave == c)) { //removendo a cabeca da lista noh* aux = elementos[h]; elementos[h] = elementos[h]->proximo; delete aux; } else { noh* atual = elementos[h]; noh* anterior; while ((atual != NULL) and (atual->chave != c)) { anterior = atual; atual = atual->proximo; } if ((atual != NULL) and (atual->chave == c)) { anterio->proximo = atual->proximo; delete atual; } else { cerr << "ERRO NA REMOCAO" << endl; } } } */ //percorrendo a tabela hash (para fins de debug) void percorre() { cout << "Imprimindo..." << endl; noh* atual; for (int i = 0; i < capacidade; i++) { cout << i << ": "; atual = elementos[i]; while (atual != NULL) { cout << "["; for (int i = 0; i < 9; i++) cout << "(" << atual->movimento[i].linha << " " << atual->movimento[i].coluna << " " << atual->movimento[i].jogador << ")"; cout << "/" << atual->vencedor << "/" << atual->nVitorias << "]->" << endl; atual = atual->proximo; } cout << "NULL" << endl << endl; } } void carregarDadosArquivo(){ // Abrindo o arquivo binario em modo leitura ifstream myFile("jogos.bin", ios::in | ios::binary); //system("clear"); // Se o arquivo existe e foi aberto, leia os dados if(myFile){ cout << "Procurando jogos em arquivo." << endl; // Verificando quantos jogos estão armazenados myFile.seekg(0, ios::end); // Posicionando o ponteiro no fim do arquivo long nJogos = myFile.tellg()/((sizeof(Movimento)*9) + sizeof(char) + sizeof(int)); cout << "Encontramos " << nJogos << " jogos armazenados" << endl; // Posicionando o ponteiro de leitura no inicio do arquivo para começar a ler myFile.seekg(0); Movimento* movimentos = new Movimento[9]; char winner; int nVitorias = 0; // Para cada jogo no arquivo for(int i = 0; i < nJogos; i++){ // Lendo cada movimento do jogo for (int j = 0; j < 9; j++) { myFile.read(reinterpret_cast<char*>(&(movimentos[j])), sizeof(Movimento)); } myFile.read(reinterpret_cast<char*>(&winner), sizeof(char)); myFile.read(reinterpret_cast<char*>(&(nVitorias)), sizeof(int)); // Inserindo o jogo lido na hash insere(movimentos, winner, nVitorias); // cout << "Winner " << winner << endl; } myFile.close(); } else{ cout << "Falha ao abrir o arquivo ou arquivo nao encontrado." << endl << endl; } } void gravarDadosArquivo(){ // Abrindo o arquivo em modo escrita, apagando todo o conteudo que já existia ofstream myFile("jogos.bin", ios::trunc | ios::out | ios::binary); // Verificando se o arquivo foi aberto if(myFile) cout << "Arquivo criado com sucesso!" << endl; else cout << "Erro ao salvar as jogadas" << endl; // Posicionando o ponteiro de escrita no inicio do arquivo myFile.seekp(0); // Percorre em todas as posições do Hash for (int i = 0; i < capacidade; i++) { noh* atual = elementos[i]; if(atual != NULL) { //Grava no arquivo while(atual != NULL) { for(int j = 0; j < 9; j++){ // cout << "Nova linha: " << atual->movimento[j].linha << " " << atual->movimento[j].coluna << endl; myFile.write(reinterpret_cast<char*>(&(atual->movimento[j])), sizeof(Movimento)); } myFile.write(reinterpret_cast<char*>(&(atual->vencedor)), sizeof(char)); myFile.write(reinterpret_cast<char*>(&(atual->nVitorias)), sizeof(int)); atual = atual->proximo; } } } cout << "Cada jogo no arquivo ocupa cerca de " << sizeof(Movimento)*9 + sizeof(char) + sizeof(int) << " bytes." << endl; myFile.close(); } }; <file_sep>#include <iostream> #include "hash.cpp" #include <cstdlib> #include <time.h> using namespace std; ostream& operator<<(ostream& output, const char** tabuleiro) { for (int k = 0; k < 3; ++k){ for (int j = 0; j < 3; ++j){ output << tabuleiro[k][j] << " "; } output << endl; } output << endl; return output; } char verificaGanhador(char jogador, char** tabuleiro){ if (tabuleiro[0][0] == jogador and tabuleiro[0][1] == jogador and tabuleiro[0][2] == jogador){ return jogador; } if (tabuleiro[1][0] == jogador and tabuleiro[1][1] == jogador and tabuleiro[1][2] == jogador){ return jogador; } if (tabuleiro[2][0] == jogador and tabuleiro[2][1] == jogador and tabuleiro[2][2] == jogador){ return jogador; } if (tabuleiro[0][0] == jogador and tabuleiro[1][0] == jogador and tabuleiro[2][0] == jogador){ return jogador; } if (tabuleiro[0][1] == jogador and tabuleiro[1][1] == jogador and tabuleiro[2][1] == jogador){ return jogador; } if (tabuleiro[0][2] == jogador and tabuleiro[1][2] == jogador and tabuleiro[2][2] == jogador){ return jogador; } if (tabuleiro[0][0] == jogador and tabuleiro[1][1] == jogador and tabuleiro[2][2] == jogador){ return jogador; } if (tabuleiro[0][2] == jogador and tabuleiro[1][1] == jogador and tabuleiro[2][0] == jogador){ return jogador; } return 'v'; } int retornaLinha(int l){ if (l >= 0 and l < 3) return 0; else if (l >= 3 and l < 6) return 1; else return 2; } int retornaColuna(int c){ if (c == 0 or c == 3 or c == 6) return 0; else if (c == 1 or c == 4 or c == 7) return 1; else return 2; } int* retornaVetor(){ srand(time(NULL)); int *vetor = new int[9]; for (int i = 0; i < 9; i++) vetor[i] = i; for (int i = 0; i < 9; i++) { int r = rand() % 9; swap(vetor[r], vetor[i]); } for (int i = 0; i < 9; i++) cout << vetor[i] << ' '; cout << endl; return vetor; } char** novoTabuleiro(){ char** tabuleiro = new char*[3]; for(int lin = 0; lin < 3; lin++) { tabuleiro[lin] = new char[3]; } for (int lin = 0; lin < 3; lin++) { for (int col = 0; col < 3; col++) { tabuleiro[lin][col] = '-'; } } return tabuleiro; } int main() { tabelaHash minhaHash; minhaHash.carregarDadosArquivo(); //minhaHash.percorre(); int tipoJogo; cout << "0 - Jogador contra Jogador" << endl; cout << "1 - Jogador contra Maquina" << endl; cout << "2 - Maquina contra Maquina (Treino)" << endl; cout << "9 - Sair" << endl; cout << "Selecione o modo de jogo: "; cin >> tipoJogo; /* //Criando o tabuleiro char** tabuleiro = new char*[3]; for(int lin = 0; lin < 3; lin++) { tabuleiro[lin] = new char[3]; } */ while(tipoJogo != 9) { switch(tipoJogo) { case 0: { // Jogador contra jogador bool jogo_em_andamento = true; char jogador1 = 'X'; char jogador2 = 'O'; int linha, coluna; srand(time(NULL)); if ((rand() % 2 + 1) == 2) swap(jogador1, jogador2); cout << "O jogador \'" << jogador1 << "\' irá começar!" << endl; // Inicializando o tabuleiro char** tabuleiro = novoTabuleiro(); // Vetor que armazena informações dos movimentos Movimento* movimentos = new Movimento[9]; // Controla o numero da jogada int nJogada = 0; while(jogo_em_andamento){ cout << tabuleiro << endl; cout << "Jogador \'" << jogador1 << "\', digite o movimento [linha] [coluna]: "; cin >> linha >> coluna; tabuleiro[linha][coluna] = jogador1; movimentos[nJogada].jogador = jogador1; movimentos[nJogada].linha = linha; movimentos[nJogada].coluna = coluna; if (verificaGanhador(jogador1, tabuleiro) == jogador1){ cout << "Jogador \'" << jogador1 << "\' venceu!" << endl; jogo_em_andamento = false; } else if(verificaGanhador(jogador1, tabuleiro) == 'v' and nJogada == 8){ jogo_em_andamento = false; cout << "Deu velha :(" << endl; } else{ system("clear"); swap(jogador1, jogador2); ++nJogada; } } // Desalocando o tabuleiro for (int v = 0; v < 3; v++) { delete[] tabuleiro[v]; } delete[] tabuleiro; } break; case 1: { // Jogador contra Maquina bool jogo_em_andamento = true; char jogador1 = 'C'; char jogador2 = 'U'; int linha, coluna; srand(time(NULL)); if ((rand() % 2 + 1) == 2) swap(jogador1, jogador2); cout << "O jogador \'" << jogador1 << "\' irá começar!" << endl << endl;; // Inicializando o tabuleiro char** tabuleiro = novoTabuleiro(); // Vetor que armazena informações dos movimentos Movimento* movimentos = new Movimento[9]; // Controla o numero da jogada int nJogada = 0; for (int k = 0; k < 3; ++k){ for (int j = 0; j < 3; ++j){ cout << tabuleiro[k][j] << " "; } cout << endl; } cout << endl; while(jogo_em_andamento){ if(jogador1 == 'U'){ // Vez do computador jogar cout << "Jogador \'" << jogador1 << "\', digite o movimento [linha] [coluna]: "; cin >> linha >> coluna; cout << endl; tabuleiro[linha][coluna] = jogador1; movimentos[nJogada].jogador = jogador1; movimentos[nJogada].linha = linha; movimentos[nJogada].coluna = coluna; } else if(jogador1 == 'C') { // Vez do usuario jogar int pos = minhaHash.obterProximoMovimento(movimentos, nJogada); if(pos == -1) pos = minhaHash.gerarMovimentoAleatorio(tabuleiro); linha = retornaLinha(pos); coluna = retornaColuna(pos); tabuleiro[linha][coluna] = jogador1; movimentos[nJogada].jogador = jogador1; movimentos[nJogada].linha = linha; movimentos[nJogada].coluna = coluna; } // Verifica se alguem ganhou if (verificaGanhador(jogador1, tabuleiro) == jogador1){ cout << "Jogador \'" << jogador1 << "\' venceu!" << endl << endl;; jogo_em_andamento = false; // Se foi o computador que ganhou, armazena a jogada if(jogador1 == 'C') minhaHash.insere(movimentos, jogador1); } else if(verificaGanhador(jogador1, tabuleiro) == 'v' and nJogada == 8){ jogo_em_andamento = false; cout << "Deu velha :(" << endl; } else{ //system("clear"); swap(jogador1, jogador2); ++nJogada; } for (int k = 0; k < 3; ++k){ for (int j = 0; j < 3; ++j){ cout << tabuleiro[k][j] << " "; } cout << endl; } cout << endl; } delete[] movimentos; // Desalocando o tabuleiro for (int v = 0; v < 3; v++) { delete[] tabuleiro[v]; } delete[] tabuleiro; } break; case 2: { //Maquina contra maquina int qtdJogos; cout << "Digite a quantidade de jogos que a máquina jogará contra a máquina: "; cin >> qtdJogos; int i = 0; while(i < qtdJogos) { char** tabuleiro = novoTabuleiro(); bool jogo_em_andamento = true; char jogador1 = 'X'; char jogador2 = 'O'; int jogadorInicial = rand() % 2 + 1; srand(time(NULL)); //cout << jogadorInicial << endl; if (jogadorInicial == 2) swap(jogador1, jogador2); cout << "O jogador \'" << jogador1 << "\' irá começar!" << endl; int* vetor = retornaVetor(); Movimento* movimentos = new Movimento[9]; int nJogada = 0; int linha = 0; int coluna = 0; while(jogo_em_andamento) { linha = retornaLinha(vetor[nJogada]); coluna = retornaColuna(vetor[nJogada]); //cout << linha << " " << coluna << " " << vetor[nJogada] << " " << nJogada << endl; movimentos[nJogada].jogador = jogador1; movimentos[nJogada].linha = linha; movimentos[nJogada].coluna = coluna; tabuleiro[linha][coluna] = jogador1; if (verificaGanhador(jogador1, tabuleiro) == jogador1){ cout << "Jogador \'" << jogador1 << "\' venceu!" << endl; jogo_em_andamento = false; } else if(verificaGanhador(jogador1, tabuleiro) == 'v' and nJogada == 8){ jogo_em_andamento = false; cout << "Deu velha :(" << endl; } else{ swap(jogador1, jogador2); ++nJogada; } } minhaHash.insere(movimentos, jogador1); ++i; delete[] movimentos; delete[] vetor; for (int k = 0; k < 3; ++k){ for (int j = 0; j < 3; ++j){ cout << tabuleiro[k][j] << " "; } cout << endl; } // Desalocando o tabuleiro for (int v = 0; v < 3; v++) { delete[] tabuleiro[v]; } delete[] tabuleiro; } } break; } cout << endl << endl; cout << "0 - Jogador contra Jogador" << endl; cout << "1 - Jogador contra Maquina" << endl; cout << "2 - Maquina contra Maquina (Treino)" << endl; cout << "9 - Sair" << endl; cout << "Selecione o modo de jogo: "; cin >> tipoJogo; cout << endl; } minhaHash.percorre(); minhaHash.gravarDadosArquivo(); return 0; } <file_sep># Makefile # igual indica atribuição de variavel CPP = g++ CPPFLAGS = -Wall -Wconversion OBJ = main.o hash.o # dois pontos indica dependencia main: $(OBJ) $(CPP) $(CPPFLAGS) $(OBJ) -o main main.o: main.cpp $(CPP) $(CPPFLAGS) -c main.cpp -o main.o hash.o: hash.cpp $(CPP) $(CPPFLAGS) -c hash.cpp -o hash.o all: main clean: rm -f *.o main
c09c94b7c7ce01c381eaf51809240892eb5cb32f
[ "Markdown", "Makefile", "C++" ]
4
Markdown
VSpinelliG/JogoDaVelha_RBC
1a2f0d15e9b371aacf29acd2f4ab40f4c23c2385
c88bf175ef71daa96f478af3b6b5530af0305c55
refs/heads/master
<repo_name>nabarunaguha/sentiment-review-analysis<file_sep>/Artificial_Neural_Network/testJob_CNN.sh #! /bin/bash # exec 1>PBS_O_WORKDIR/out 2>$PBS_O_WORKDIR/err # # ===== PBS Options ======== #PBS -N "AmazonReview_NN_Job" #PBS -q mamba #PBS -l walltime=5:00:00 #PBS -l nodes=1:ppn=4:gpus=1 #PBS -V # ==== Main ====== cd $PBS_O_WORKDIR mkdir log { module load python/3.5.1 python3 /users/clolla/machine_learning/Algorithms/SL_NeuralNetwork/AmazonReviewAnalysis/SL_NeuralNetwork_AmazonReview.py } > log/out_neuralnetwork_"$PBS_JOBNAME"_$PBS_JOBID 2>log/err_neuralnetwork_"$PBS_JOBNAME"_$PBS_JOBID <file_sep>/Adaboosting/testJob.sh #! /bin/bash # exec 1>PBS_O_WORKDIR/out 2>$PBS_O_WORKDIR/err # # ===== PBS Options ======== #PBS -N "AmazonReview_Adaboosting_Job" #PBS -q mamba #PBS -l walltime=7:50:00 #PBS -l nodes=3:ppn=5 #PBS -V # ==== Main ====== cd $PBS_O_WORKDIR mkdir log { module load python/3.5.1 python3 /users/clolla/machine_learning/Algorithms/SL_Adaboosting/AmazonReviewAnalysis/SL_Adaboosting_AmazonReview.py } > log/out_adaboosting3_"$PBS_JOBNAME"_$PBS_JOBID 2>log/err_adaboosting3_"$PBS_JOBNAME"_$PBS_JOBID <file_sep>/SVM/SL_SVM_AmazonReview.py ### This file contains the Support Vector Classification on the Amazon Dataset. ### The below contains the libraries used. ### @Author: <NAME>. import pandas as pd import numpy as np import nltk import string #get_ipython().magic('matplotlib inline') #import matplotlib.pyplot as plt import numpy as np import scipy.sparse as sparse from sklearn.feature_extraction.text import TfidfTransformer from sklearn.feature_extraction.text import CountVectorizer from sklearn.metrics import confusion_matrix from sklearn import metrics from nltk.corpus import stopwords from sklearn import svm ### Loading of the Training dataset and splitting the classes into two classes positive and negative. reviews = pd.read_csv('amazon_baby_train.csv') reviews.shape reviews = reviews.dropna() reviews.shape scores = reviews['rating'] reviews['rating'] = reviews['rating'].apply(lambda x: '1' if x >= 3 else '0') print("The Mean of the Rating Attribute is : ") print(scores.mean()) print("The standard deviation of the rating column is:") print(scores.std()) ### Distribution of the Training Output classes. reviews.groupby('rating')['review'].count() reviews.groupby('rating')['review'].count().plot(kind='bar', color= ['r','g'],title='Label Distribution', figsize = (10,6)) ## This method is responsible for splitting the data into positive and negative reviews. def splitPosNeg(Summaries): neg = reviews.loc[Summaries['rating']== '0'] pos = reviews.loc[Summaries['rating']== '1'] return [pos,neg] # In[7]: [pos,neg] = splitPosNeg(reviews) # In[8]: ## Pre Processing Steps which uses lemmitizer and stopwords to clean the reviews. lemmatizer = nltk.WordNetLemmatizer() stop = stopwords.words('english') translation = str.maketrans(string.punctuation,' '*len(string.punctuation)) def preprocessing(line): tokens=[] line = line.translate(translation) line = nltk.word_tokenize(line.lower()) stops = stopwords.words('english') stops.remove('not') stops.remove('no') line = [word for word in line if word not in stops] for t in line: stemmed = lemmatizer.lemmatize(t) tokens.append(stemmed) return ' '.join(tokens) ### This method actually preprocesses the data. pos_data = [] neg_data = [] for p in pos['review']: pos_data.append(preprocessing(p)) for n in neg['review']: neg_data.append(preprocessing(n)) print("Done") ### The formation of the Training Data. data = pos_data + neg_data labels = np.concatenate((pos['rating'].values,neg['rating'].values)) print("Done formation of the training features.") ### This tokenizes the training data using word_tokenize. t = [] for line in data: l = nltk.word_tokenize(line) for w in l: t.append(w) ### This tries to find the word features from the training dataset using the frequency distribution. word_features = nltk.FreqDist(t) print(len(word_features)) ### Identifying the training top words for formation of the sparse matrix. topwords = [fpair[0] for fpair in list(word_features.most_common(5000))] print(word_features.most_common(25)) ## Printing the top 20 words and its count. word_his = pd.DataFrame(word_features.most_common(200), columns = ['words','count']) ### This method is repsonsible for forming the sparse matrix using the training top words. vec = CountVectorizer() c_fit = vec.fit_transform([' '.join(topwords)]) ## This is responsible for forming the training features using the training data and top words. tf_vec = TfidfTransformer() tf_fit = tf_vec.fit_transform(c_fit) # In[17]: ctr_features = vec.transform(data) tr_features = tf_vec.transform(ctr_features) # In[18]: tr_features.shape ## SVM Classification Implementation. For various results, please check the Results Report. clf = svm.SVC(kernel='linear') clf = clf.fit(tr_features, labels) print("Done Classifying") # In[ ]: ## Prediction on the Training Dataset. output_prediction_train = clf.predict(tr_features) output_train_accuracy = metrics.accuracy_score(output_prediction_train,labels) print("Accuracy on the Training dataset.") print(output_train_accuracy * 100) # In[21]: ## Testing Dataset. reviews = pd.read_csv('amazon_baby_test.csv') reviews.shape reviews = reviews.dropna() reviews.shape #print(reviews.head(25)) scores = reviews['rating'] reviews['rating'] = reviews['rating'].apply(lambda x: '1' if x > 3 else '0') #print(reviews.head(25)) scores.mean() # In[22]: reviews.groupby('rating')['review'].count() # In[23]: reviews.groupby('rating')['review'].count().plot(kind='bar', color= ['r','g'],title='Label Distribution', figsize = (10,6)) # In[24]: [pos,neg] = splitPosNeg(reviews) # In[25]: pos_data = [] neg_data = [] for p in pos['review']: pos_data.append(preprocessing(p)) for n in neg['review']: neg_data.append(preprocessing(n)) print("Done") # In[26]: data = pos_data + neg_data labels = np.concatenate((pos['rating'].values,neg['rating'].values)) #print(labels) # In[27]: t = [] for line in data: l = nltk.word_tokenize(line) for w in l: t.append(w) #print(t) # In[28]: word_features = nltk.FreqDist(t) print(len(word_features)) # In[29]: topwords = [fpair[0] for fpair in list(word_features.most_common(5002))] print(word_features.most_common(25)) # In[30]: word_his = pd.DataFrame(word_features.most_common(200), columns = ['words','count']) #print(word_his) # In[31]: len(topwords) # In[32]: vec = CountVectorizer() c_fit = vec.fit_transform([' '.join(topwords)]) # In[33]: tf_vec = TfidfTransformer() tf_fit = tf_vec.fit_transform(c_fit) # In[34]: cte_features = vec.transform(data) te_features = tf_vec.transform(cte_features) # In[35]: te_features.shape # In[36]: tePredication = clf.predict(te_features) teAccuracy = metrics.accuracy_score(tePredication,labels) print(teAccuracy*100) # In[37]: print(metrics.classification_report(labels, tePredication)) <file_sep>/NaiveBayes/SL_NaiveBayes_AmazonReview.py # coding: utf-8 # In[1]: ### This file contains the Naive Bayes Implementation on the Amazon Review Dataset. ### The below contains the libraries used. ### @Author: <NAME>. import pandas as pd import numpy as np import nltk import string #get_ipython().magic('matplotlib inline') #import matplotlib.pyplot as plt import numpy as np from sklearn.feature_extraction.text import TfidfTransformer from sklearn.feature_extraction.text import CountVectorizer from sklearn import metrics from nltk.corpus import stopwords from sklearn.naive_bayes import GaussianNB # In[2]: ## Loading of the Training dataset and splitting the classes into two classes positive and negative. reviews = pd.read_csv('amazon_baby_train.csv') reviews.shape reviews = reviews.dropna() reviews.shape scores = reviews['rating'] reviews['rating'] = reviews['rating'].apply(lambda x: 1 if x >= 3 else 0) print("Done formation of the Training dataset.") ## The calculation of the Mean and standard deviation for the Training Classes. print("The mean of output classes in the Training dataset is:") print(scores.mean()) print("The standard deviation of the output classes in the Training dataset is:") print(scores.std()) # In[3]: ### Distribution of the Training Output classes. #reviews.groupby('rating')['review'].count() # In[4]: #reviews.groupby('rating')['review'].count().plot(kind='bar', color= ['r','g'],title='Label Distribution', figsize = (10,6)) # In[5]: ## This method is responsible for splitting the data into positive and negative reviews. def splitPosNeg(Summaries): neg = reviews.loc[Summaries['rating']== 0] pos = reviews.loc[Summaries['rating']== 1] return [pos,neg] # In[6]: [pos,neg] = splitPosNeg(reviews) # In[7]: ## Pre Processing Steps which uses lemmitizer and stopwords to clean the reviews. lemmatizer = nltk.WordNetLemmatizer() stop = stopwords.words('english') translation = str.maketrans(string.punctuation,' '*len(string.punctuation)) def preprocessing(line): tokens=[] line = line.translate(translation) line = nltk.word_tokenize(line.lower()) stops = stopwords.words('english') stops.remove('not') stops.remove('no') line = [word for word in line if word not in stops] for t in line: stemmed = lemmatizer.lemmatize(t) tokens.append(stemmed) return ' '.join(tokens) # In[8]: ### This method actually preprocesses the data. pos_data = [] neg_data = [] for p in pos['review']: pos_data.append(preprocessing(p)) for n in neg['review']: neg_data.append(preprocessing(n)) print("Done forming the positive and negative reveiws.") # In[9]: ### The formation of the Training Data. training_data = pos_data + neg_data training_labels = np.concatenate((pos['rating'].values,neg['rating'].values)) print("Done formation of the training features.") # In[10]: ### This tokenizes the training data using word_tokenize. tokens = [] for line in training_data: l = nltk.word_tokenize(line) for w in l: tokens.append(w) # In[11]: ### This tries to find the word features from the training dataset using the frequency distribution. word_features = nltk.FreqDist(tokens) print(len(word_features)) # In[12]: ### Identifying the training top words for formation of the sparse matrix. training_topwords = [fpair[0] for fpair in list(word_features.most_common(5000))] print(word_features.most_common(25)) # In[13]: ## Printing the top 20 words and its count. word_his = pd.DataFrame(word_features.most_common(20), columns = ['words','count']) print(word_his) # In[14]: ### This method is repsonsible for forming the sparse matrix using the training top words. vec = CountVectorizer() c_fit = vec.fit_transform([' '.join(training_topwords)]) # In[15]: tf_vec = TfidfTransformer() tf_fit = tf_vec.fit_transform(c_fit) # In[16]: ## This is responsible for forming the training features using the training data and top words. ctr_features = vec.transform(training_data) training_features = tf_vec.transform(ctr_features) # In[17]: print(training_features.shape) # In[20]: ### Naive Bayes Classification model using Gaussian Naive Bayes Implementation without any priors. clf = GaussianNB() training_features = training_features.toarray() clf = clf.fit(training_features,training_labels) print("Classification is Done using Gaussian NB.") # In[ ]: ## Formation of the Errors and Accuracies of Training dataset. output_Predicted = clf.predict(training_features); accuracy_training = metrics.accuracy_score(output_Predicted,training_labels) print(accuracy_training* 100) # In[ ]: ### This is responsible for loading the Testing dataset. reviews = pd.read_csv('amazon_baby_test.csv') reviews.shape reviews = reviews.dropna() reviews.shape scores = reviews['rating'] reviews['rating'] = reviews['rating'].apply(lambda x: 1 if x >= 3 else 0) print("Done loading the testing dataset.") print("Mean of the output classes in Testing dataset:") print(scores.mean()) print("Standard Deviation of the output classes in the Testing dataset is:") print(scores.std()) # In[ ]: ### Splitting the testing data into postive and negative reviews. [pos,neg] = splitPosNeg(reviews) # In[ ]: pos_data = [] neg_data = [] for p in pos['review']: pos_data.append(preprocessing(p)) for n in neg['review']: neg_data.append(preprocessing(n)) print("Done forming the positive and negative reviews in testing dataset.") # In[ ]: ## Formation of the Testing data. testing_data = pos_data + neg_data testing_labels = np.concatenate((pos['rating'].values,neg['rating'].values)) # In[ ]: ## Formation of tokesn in testing dataset. t = [] for line in testing_data: l = nltk.word_tokenize(line) for w in l: t.append(w) # In[ ]: ## Formation of the word features for the testing dataset. word_features = nltk.FreqDist(t) print(len(word_features)) # In[ ]: topwords = [fpair[0] for fpair in list(word_features.most_common(5002))] print(word_features.most_common(25)) # In[ ]: ## Printing the count and top words formed. word_his = pd.DataFrame(word_features.most_common(20), columns = ['words','count']) print(word_his) # In[ ]: ### Formation of the sparse matrix vec = CountVectorizer() c_fit = vec.fit_transform([' '.join(topwords)]) # In[ ]: tf_vec = TfidfTransformer() tf_fit = tf_vec.fit_transform(c_fit) # In[ ]: cte_features = vec.transform(testing_data) te_features = tf_vec.transform(cte_features) # In[ ]: te_features.shape # In[ ]: te_features = te_features.toarray() tePredication = clf.predict(te_features) teAccuracy = metrics.accuracy_score(tePredication,testing_labels) print("Accuracy of the Testing dataset is:") print(teAccuracy * 100) # In[ ]: # printing the metrics print(metrics.classification_report(labels, tePredication)) <file_sep>/KNN/SL_KNN_AmazonReview.py # coding: utf-8 # In[1]: import pandas as pd import numpy as np import nltk import string #get_ipython().magic('matplotlib inline') #import matplotlib.pyplot as plt import numpy as np #import scipy.sparse as sparse from sklearn.feature_extraction.text import TfidfTransformer from sklearn.feature_extraction.text import CountVectorizer #from sklearn.metrics import confusion_matrix from sklearn import metrics from nltk.corpus import stopwords from sklearn.neighbors import KNeighborsClassifier # In[2]: reviews = pd.read_csv('amazon_baby_train.csv') reviews.shape reviews = reviews.dropna() reviews.shape print("Done loading the Training Data.") scores = reviews['rating'] reviews['rating'] = reviews['rating'].apply(lambda x: 1 if x >= 3 else 0) print("The Mean of the Rating Attribute is : ") print(scores.mean()) print("The Standard Deviation for the Rating Attribute is : ") print(scores.std()) # In[3]: #reviews.groupby('rating')['review'].count() # In[4]: #reviews.groupby('rating')['review'].count().plot(kind='bar', color= ['r','g'],title='Label Distribution', figsize = (10,6)) # In[5]: def splitPosNeg(Summaries): neg = reviews.loc[Summaries['rating']== 0] pos = reviews.loc[Summaries['rating']== 1] return [pos,neg] # In[6]: [pos,neg] = splitPosNeg(reviews) # In[7]: ## Pre Processing Steps. lemmatizer = nltk.WordNetLemmatizer() stop = stopwords.words('english') translation = str.maketrans(string.punctuation,' '*len(string.punctuation)) def preprocessing(line): tokens=[] line = line.translate(translation) line = nltk.word_tokenize(line.lower()) stops = stopwords.words('english') stops.remove('not') stops.remove('no') line = [word for word in line if word not in stops] for t in line: stemmed = lemmatizer.lemmatize(t) tokens.append(stemmed) return ' '.join(tokens) # In[8]: pos_data = [] neg_data = [] for p in pos['review']: pos_data.append(preprocessing(p)) for n in neg['review']: neg_data.append(preprocessing(n)) print("Done seperating positive and negative reviews.") # In[9]: training_data = pos_data + neg_data training_labels = np.concatenate((pos['rating'].values,neg['rating'].values)) print(training_labels) # In[10]: ### Splitting the Datasets into 4 Folds to avoid any Memory Errors that could occur while classifying the data. import math data_len = len(training_data) print(data_len) splitPercentage = 0.25 len_train = math.floor(data_len * splitPercentage); X_train1 = training_data[:len_train] Y_train1 = training_labels[:len_train] print(len(X_train1)) X_train2 = training_data[len_train:len_train+len(X_train1)] Y_train2= training_labels[len_train:len_train+ len(Y_train1)] print(len(X_train2)) X_train3 = training_data[len_train+len(X_train1):len_train+len(X_train1)+len(X_train2)] Y_train3= training_labels[len_train+len(Y_train1):len_train+len(Y_train1)+len(Y_train2)] print(len(X_train3)) X_train4 = training_data[len_train+len(X_train1)+len(X_train2):data_len] Y_train4= training_labels[len_train+len(Y_train1)+len(Y_train2):data_len] print(len(X_train4)) # In[11]: train_tokens1 = [] train_tokens2 = [] train_tokens3 = [] train_tokens4 = [] for line in X_train1: l = nltk.word_tokenize(line) for word in l: train_tokens1.append(word) print("Done with tokenizing the reviews for Train Fold 1") for line in X_train2: l = nltk.word_tokenize(line) for word in l: train_tokens2.append(word) print("Done with tokenizing the reviews for Train Fold 2") for line in X_train3: l = nltk.word_tokenize(line) for word in l: train_tokens3.append(word) print("Done with tokenizing the reviews for Train Fold 3") for line in X_train4: l = nltk.word_tokenize(line) for word in l: train_tokens4.append(word) print("Done with tokenizing the reviews for Train Fold 4") # In[12]: word_features1 = nltk.FreqDist(train_tokens1) print("The length of the word features 1 we obtained:") print(len(word_features1)) word_features2 = nltk.FreqDist(train_tokens2) print("The length of the word features 2 we obtained:") print(len(word_features2)) word_features3 = nltk.FreqDist(train_tokens3) print("The length of the word features 3 we obtained:") print(len(word_features3)) word_features4 = nltk.FreqDist(train_tokens1) print("The length of the word features 4 we obtained:") print(len(word_features4)) # In[13]: topwords1 = [fpair[0] for fpair in list(word_features1.most_common(4000))] topwords2 = [fpair[0] for fpair in list(word_features2.most_common(4000))] topwords3 = [fpair[0] for fpair in list(word_features3.most_common(4000))] topwords4 = [fpair[0] for fpair in list(word_features4.most_common(4000))] # In[14]: ## Data formation of the Words. word_his = pd.DataFrame(word_features1.most_common(20), columns = ['words','count']) print(word_his) # In[28]: vec = CountVectorizer() c_fit1 = vec.fit_transform([' '.join(topwords1)]) c_fit2 = vec.fit_transform([' '.join(topwords2)]) c_fit3 = vec.fit_transform([' '.join(topwords3)]) c_fit4 = vec.fit_transform([' '.join(topwords4)]) print(c_fit1.shape) print(c_fit2.shape) print(c_fit3.shape) print(c_fit4.shape) # In[29]: tf_vec = TfidfTransformer() tf_fit1 = tf_vec.fit_transform(c_fit1) tf_fit2 = tf_vec.fit_transform(c_fit2) tf_fit3 = tf_vec.fit_transform(c_fit3) tf_fit4 = tf_vec.fit_transform(c_fit4) print(tf_fit1.shape) print(tf_fit2.shape) print(tf_fit3.shape) print(tf_fit4.shape) # In[30]: ctr_features1 = vec.transform(X_train1) tr_features1 = tf_vec.transform(ctr_features1) print("Done with forming the Training Features for Fold 1") ctr_features2 = vec.transform(X_train2) tr_features2 = tf_vec.transform(ctr_features2) print("Done with forming the Training Features for Fold 2") ctr_features3 = vec.transform(X_train3) tr_features3 = tf_vec.transform(ctr_features3) print("Done with forming the Training Features for Fold 3") ctr_features4 = vec.transform(X_train4) tr_features4 = tf_vec.transform(ctr_features4) print("Done with forming the Training Features for Fold 4") # In[31]: print(tr_features1.shape) print(Y_train1.shape) print(tr_features2.shape) print(Y_train2.shape) print(tr_features3.shape) print(Y_train3.shape) print(tr_features4.shape) print(Y_train4.shape) # In[39]: clf = KNeighborsClassifier(n_neighbors= 6) clf1 = clf.fit(tr_features1,Y_train1) clf2 = clf.fit(tr_features2,Y_train2) clf3 = clf.fit(tr_features3,Y_train3) clf4 = clf.fit(tr_features4,Y_train4) print("Done with the classification using KNN with K=6.") # In[48]: num_correct1 = 0; len_tr1 = tr_features1.shape[0] print(len_tr1) for i in range(0,len_tr1): output_prediction_train = clf1.predict(tr_features1[i]) if(output_prediction_train[0]== Y_train1[i]): num_correct1 = num_correct1 + 1; num_correct2= 0; len_tr2 = tr_features2.shape[0] for i in range(0,len_tr2): output_prediction_train = clf2.predict(tr_features2[i]) if(output_prediction_train[0]== Y_train2[i]): num_correct2 = num_correct2 + 1; num_correct3 = 0; len_tr3 = tr_features3.shape[0] for i in range(0,len_tr3): output_prediction_train = clf3.predict(tr_features3[i]) if(output_prediction_train[0]== Y_train3[i]): num_correct3 = num_correct3 + 1; num_correct4 = 0; len_tr4 = tr_features4.shape[0] for i in range(0,len_tr4): output_prediction_train = clf4.predict(tr_features4[i]) if(output_prediction_train[0]== Y_train4[i]): num_correct4 = num_correct4 + 1; accuracy_train = (num_correct1 + num_correct2 + num_correct3 + num_correct4)/(len_tr1+len_tr2+len_tr3+len_tr4) print("Accuracy on the Training Dataset is:") print(accuracy_train*100) # In[50]: ## Formation of the Testing Dataset. reviews = pd.read_csv('amazon_baby_test.csv') reviews.shape reviews = reviews.dropna() reviews.shape scores = reviews['rating'] reviews['rating'] = reviews['rating'].apply(lambda x: 1 if x >= 3 else 0) print("Done with loading the Test Dataset.") print("Mean of the ratings is : ") print(scores.mean()) print("Standard Deviation of the ratings is: ") print(scores.std()) # In[51]: #reviews.groupby('rating')['review'].count() # In[52]: #reviews.groupby('rating')['review'].count().plot(kind='bar', color= ['r','g'],title='Label Distribution', figsize = (10,6)) # In[53]: [pos,neg] = splitPosNeg(reviews) # In[54]: pos_data = [] neg_data = [] for p in pos['review']: pos_data.append(preprocessing(p)) for n in neg['review']: neg_data.append(preprocessing(n)) print("Done splitting the positives and negatives in the testing dataset") # In[55]: testing_data = pos_data + neg_data testing_labels = np.concatenate((pos['rating'].values,neg['rating'].values)) # In[56]: print(len(testing_data)) print(len(testing_labels)) # In[57]: t = [] for line in testing_data: l = nltk.word_tokenize(line) for w in l: t.append(w) print("Done with tokenizing the Testing dataset.") # In[58]: test_word_features = nltk.FreqDist(t) print(len(test_word_features)) # In[81]: test_topwords = [fpair[0] for fpair in list(test_word_features.most_common(3999))] # In[82]: word_his = pd.DataFrame(test_word_features.most_common(20), columns = ['words','count']) print(word_his) # In[83]: len(test_topwords) # In[84]: vec = CountVectorizer() c_fit = vec.fit_transform([' '.join(test_topwords)]) # In[85]: tf_vec = TfidfTransformer() tf_fit = tf_vec.fit_transform(c_fit) # In[86]: test_features = vec.transform(testing_data) test_features = tf_vec.transform(test_features) # In[87]: print(test_features.shape) print(len(testing_labels)) # In[93]: num_correct1 = 0; len_test = test_features.shape[0] print(len_test) for i in range(0,len_test): output_prediction_train = clf1.predict(test_features[i]) if(output_prediction_train[0]== testing_labels[i]): num_correct1 = num_correct1 + 1; accuracy_test = (num_correct1)/len_test print("Accuracy on the Testing Dataset is:") print(accuracy_test*100) # In[ ]: <file_sep>/Artificial_Neural_Network/SL_NeuralNetwork_AmazonReview.py #### Assignment2 #### This script includes the implementation of the Neural Networks for the Amazon Sentiment Analysis Dataset. #### It takes the following libararies - NLTK, pandas, numpy, string, matplotlib, scipy, sklearn. ### @Author: <NAME>, Student ID: 800960353 ### Libraries. import pandas as pd import numpy as np import nltk import string #get_ipython().magic('matplotlib inline') #import matplotlib.pyplot as plt import numpy as np import scipy.sparse as sparse from sklearn.feature_extraction.text import TfidfTransformer from sklearn.feature_extraction.text import CountVectorizer #from sklearn.cross_validation import train_test_split from sklearn.metrics import confusion_matrix from sklearn import metrics from nltk.corpus import stopwords from sklearn.neural_network import MLPClassifier # In[2]: ### Reading the Given Training Dataset. reviews = pd.read_csv('amazon_baby_train.csv') reviews.shape reviews = reviews.dropna() reviews.shape #print(reviews.head(25)) ### Converting the Training dataset to follow binary classification with only positive and negative. ### Here the rating above three is considered positive and less than or equal to three are considered as negative cases. scores = reviews['rating'] reviews['rating'] = reviews['rating'].apply(lambda x: '1' if x >= 3 else '0') #print(reviews.head(25)) ### Mean calculation of the Rating . print("The Mean of the Rating Attribute is : ") print(scores.mean()) # In[3]: ## Distribution of the Ratings and its type. reviews.groupby('rating')['review'].count() # In[4]: ### Distribution plot of the Ratings. #reviews.groupby('rating')['review'].count().plot(kind='bar', color= ['r','g'],title='Label Distribution', figsize = (10,6)) # In[5]: ### This function splits the rating into positive or negative and returns the indices of them in the given array. def splitPosNeg(Summaries): neg = reviews.loc[Summaries['rating'] == '0'] pos = reviews.loc[Summaries['rating'] == '1'] return [pos,neg] # In[6]: [pos,neg] = splitPosNeg(reviews) # In[7]: ##This step includes pre processing of the review data with the NLP Tool kit . ## This Lemmitizes (Noun, Verb etc of same word is considered as one word) the word ## stems the unnecessary words removing the punctuation. #stemmer = PorterStemmer() lemmatizer = nltk.WordNetLemmatizer() stop = stopwords.words('english') translation = str.maketrans(string.punctuation,' '*len(string.punctuation)) #filtered_words = [word for word in word_list if word not in stopwords.words('english')] def preprocessing(line): tokens=[] line = line.translate(translation) line = nltk.word_tokenize(line.lower()) #print(line) stops = stopwords.words('english') stops.remove('not') stops.remove('no') line = [word for word in line if word not in stops] #print("After removing stop words") #print(line) for t in line: #if(t not in stop): #stemmed = stemmer.stem(t) stemmed = lemmatizer.lemmatize(t) tokens.append(stemmed) return ' '.join(tokens) # In[8]: ### Splitting the positive and negative words using the preprocessing method we have written. pos_data = [] neg_data = [] for p in pos['review']: pos_data.append(preprocessing(p)) for n in neg['review']: neg_data.append(preprocessing(n)) print("Done") # In[9]: ### Concatenating the positive and negative data into a single array and also the labels corrosponding to them. data = pos_data + neg_data labels = np.concatenate((pos['rating'].values,neg['rating'].values)) #print(labels) # In[10]: ### Tokenize the words in the given training data. t = [] for line in data: l = nltk.word_tokenize(line) for w in l: t.append(w) #print(t) # In[11]: ### Identifying the counts of the words. word_features = nltk.FreqDist(t) print(len(word_features)) # In[12]: ## Displaying what are the counts of the topwords . topwords = [fpair[0] for fpair in list(word_features.most_common(5000))] print(word_features.most_common(25)) # In[13]: ## Checking what are the most common words used from the above. word_his = pd.DataFrame(word_features.most_common(200), columns = ['words','count']) #print(word_his) # In[14]: ### Count Vectorizer is used to convert the text into a matrix that contains the count of each word. vec = CountVectorizer() c_fit = vec.fit_transform([' '.join(topwords)]) # In[15]: ### TFID Transformer is used for normalization of the above matrix we have formed using the topwords. tf_vec = TfidfTransformer() tf_fit = tf_vec.fit_transform(c_fit) # In[16]: #### This step is used for forming the training features that we are going to give to our classification problem. ctr_features = vec.transform(data) tr_features = tf_vec.transform(ctr_features) # In[17]: tr_features.shape # In[18]: ### Applying Multi Layer Perceptron (Neural Networks) classification on the above training features formed. ### Prediction on the training dataset and accuracy calculation. ### The Default Parameters of Iteration = 600, solver = "sgd'- Stochastic Gradient Descent Algorithm, Hidden layers = 600, and learning rate = 0.001, activation layer = 'relu' ### has been used for the classification. clf = MLPClassifier(hidden_layer_sizes = (600,), activation='relu', solver='sgd', alpha = 0.0001, verbose=True, learning_rate = 'constant',learning_rate_init= 0.001,max_iter=500) clf = clf.fit(tr_features, labels) tfPredication = clf.predict(tr_features) tfAccuracy = metrics.accuracy_score(tfPredication,labels) print(tfAccuracy * 100) # In[19]: #### Testing Dataset and its prediction following the above same procedure. reviews = pd.read_csv('amazon_baby_test.csv') reviews.shape reviews = reviews.dropna() reviews.shape #print(reviews.head(25)) scores = reviews['rating'] reviews['rating'] = reviews['rating'].apply(lambda x: '1' if x > 3 else '0') #print(reviews.head(25)) scores.mean() # In[20]: reviews.groupby('rating')['review'].count() # In[21]: #reviews.groupby('rating')['review'].count().plot(kind='bar', color= ['r','g'],title='Label Distribution', figsize = (10,6)) # In[22]: [pos,neg] = splitPosNeg(reviews) # In[23]: pos_data = [] neg_data = [] for p in pos['review']: pos_data.append(preprocessing(p)) for n in neg['review']: neg_data.append(preprocessing(n)) print("Done") # In[24]: data = pos_data + neg_data labels = np.concatenate((pos['rating'].values,neg['rating'].values)) #print(labels) # In[25]: t = [] for line in data: l = nltk.word_tokenize(line) for w in l: t.append(w) #print(t) # In[26]: word_features = nltk.FreqDist(t) print(len(word_features)) # In[41]: topwords = [fpair[0] for fpair in list(word_features.most_common(5002))] print(word_features.most_common(25)) # In[42]: word_his = pd.DataFrame(word_features.most_common(200), columns = ['words','count']) #print(word_his) # In[43]: vec = CountVectorizer() c_fit = vec.fit_transform([' '.join(topwords)]) # In[44]: tf_vec = TfidfTransformer() tf_fit = tf_vec.fit_transform(c_fit) # In[45]: cte_features = vec.transform(data) te_features = tf_vec.transform(cte_features) # In[46]: ### Prediction of the Given Testing dataset and its accuracy. tePredication = clf.predict(te_features) teAccuracy = metrics.accuracy_score(tePredication,labels) print(teAccuracy) # In[47]: te_features.shape # In[48]: ### Printing the various metrics used for accuracy on Testing dataset - F1 Score, Recall,Precision. print(metrics.classification_report(labels, tePredication)) # In[ ]: <file_sep>/README.md # Amazon Baby Product Sentiment Review analysis ## Pre-requisites 1. Anaconda (2.7 or 3.4) 2. scikit-learn 3. NLP tool kit Note: Having a GPU takes less time during the training. ## Dataset Amazon reviews dataset can be found here : [Link](https://snap.stanford.edu/data/web-Amazon.html) ## Goal To predict the rating of a review given to a particular amazon baby products. ## Algorithms Used The following algorithms have been used and analyzed for this dataset: 1. Decision Tree 2. KNN 3. Artificial Neural Networks 4. Adaboosting. 5. SVM 6. Naive Bayes. ## Analysis The analysis is present in [Analysis.pdf](Analysis.pdf) and this gives a differentiation of how well each of the machine learning algorithms perform over the other in this particular dataset. <file_sep>/KNN/testJob.sh #! /bin/bash # exec 1>PBS_O_WORKDIR/out 2>$PBS_O_WORKDIR/err # # ===== PBS Options ======== #PBS -N "AmazonReview_KNN_Job" #PBS -q mamba #PBS -l walltime=4:00:00 #PBS -l nodes=2:ppn=2 #PBS -V # ==== Main ====== cd $PBS_O_WORKDIR mkdir log { module load python/3.5.1 python3 /users/clolla/machine_learning/Algorithms/SL_KNN/AmazonReviewAnalysis/SL_KNN_AmazonReview.py } > log/out_knn_amazon2_"$PBS_JOBNAME"_$PBS_JOBID 2>log/err_knn_amazon2_"$PBS_JOBNAME"_$PBS_JOBID
487669a99759e05f668966d0e83f067a2483b344
[ "Markdown", "Python", "Shell" ]
8
Shell
nabarunaguha/sentiment-review-analysis
ceee69e5ff81afca138f01beeec012a2a9d0642a
3fc76a75d951954d5c6082e109006b242e93afde
refs/heads/master
<repo_name>Ekibzgit/workproject<file_sep>/project/infosub.php <?php //require ("conn.php"); $dbhost = "localhost"; $dbuser = "root"; $dbpass = <PASSWORD>"; $dbselect = "eventlist"; $conn =mysql_connect($dbhost, $dbuser, $dbpass)or die("Could not connect to the database."); $select=mysql_select_db($dbselect,$conn) or die("Could not select database"); $id=$_POST['id']; $work=$_POST['work']; $date=$_POST['date']; $time=$_POST['time']; $venue=$_POST['venue']; $user_details= "INSERT INTO task (id,work,date,time,venue) VALUES ('$id','$work','$date','$time','$venue')"; $results=mysql_query($user_details,$conn); if (!$results) { die('Error: ' .mysql_error()) ; } else { echo "your submission was succesful"; } //<a href="home.php">Back</a> mysql_close($conn); ?> <file_sep>/project/validlogin.php <?php //start the session session_start(); if(isset($_SESSION['username'])) //the user is logged in { //show the logged in users details echo "Welcome ".$_SESSION['username']; echo " | <a href='logout.php'>Logout</a>"; } else //the user is not logged in { //redirect the user to the home page header("location: home.php"); } ?> <file_sep>/project/remove.php <html> <head> <title>Delete a Record from MySQL Database</title> <link href="//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> </head> <body> <?php if(isset($_POST['delete'])) { require ("conn.php");// establishing connections to the database $id = $_POST['id']; $sql = "DELETE FROM task ". "WHERE id = $id" ; $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not delete data: ' . mysql_error()); } echo "Deleted data successfully\n"; mysql_close($conn); } else { ?> <form method="post" action="<?php $_PHP_SELF ?>"> <table width="400" border="0" cellspacing="1" cellpadding="2"> <tr> <td width="100">ID</td> <td><input name="id" type="text" id="id"></td> </tr> <tr> <td width="100"> </td> </tr> <tr> <td width="100"> </td> <td> <input name="delete" type="submit" id="delete" value="Delete"> </td> <td><a href="display.php">View Db content</a></td> </tr> </table> <td><a href="home.php">Home</a></td><br> </form> <?php } ?> </body> </html> <file_sep>/project/login.php <?php //start the session session_start(); //check if someone submited the login form if(isset($_POST['username'])) { //include database connection file include "conn.php"; $username=$_POST['username']; $password=$_POST['password']; $sql = "SELECT * FROM validation_tb WHERE 'username' ='$username' AND password ='$password'"; //execute the query and store the record set in the variable $result $result=mysql_query($sql) or die("couldn't select ".mysql_error()); //count the number of rows returned $num = mysql_num_rows($result); if($num > 0) //user entered valid login details { //do the checks to verify the users info here before you set the session variables $_SESSION['username'] = mysql_result($result,0,"username"); $_SESSION['password'] = mysql_result($result,0,"<PASSWORD>"); //redirect the user to the valid login page header("location: validlogin.php"); } else { //redirect the user to the invalid login page header("location: invalidlogin.php"); } } else { //redirect the user to the home page header("location: home.php"); } ?> <file_sep>/project/display.php <?php require ("conn.php"); $sql="SELECT * FROM task"; $records=mysql_query($sql); ?> <html> <head> <link href="//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> </head> <body> <h1>Database Content Display</h1> <table width="500px" border="1" cellpaddin="5"> <tr> <th>id</th> <th>work</th> <th>date</th> <th>time</th> <th>venue</th> </tr> <?php while($result=mysql_fetch_assoc($records)) { echo "<tr>"; echo "<td>".$result['id']."</td>"; echo "<td>".$result['work']."</td>"; echo "<td>".$result['date']."</td>"; echo "<td>".$result['time']."</td>"; echo "<td>".$result['venue']."</td>"; echo"</tr>"; } ?> </table> <a href="home.php">Home</a> </body> </html> <file_sep>/project/logout.php <?php //start the session session_start(); if(isset($_SESSION['username'])) //the user is logged in { //clear the session variables containing the users info unset($_SESSION['username']); unset($_SESSION['password']); } //redirect the user to the home page header("location: home.php"); ?>
076f69ce5d87d8400df1e87bd64aa5a4226d68ae
[ "PHP" ]
6
PHP
Ekibzgit/workproject
2396c7e79d0bc000e17c9e49cd58b294aee190dc
a900cfc59a68b663c750fe793e5c074f18657570
refs/heads/master
<repo_name>MrFraiday/Lab4RPO<file_sep>/Sunny/View Controllers/ViewController.swift import UIKit import CoreLocation import RealmSwift class ViewController: UIViewController { // MARK: - Outlets @IBOutlet private weak var weatherIconImageView: UIImageView! @IBOutlet private weak var cityLabel: UILabel! @IBOutlet private weak var temperatureLabel: UILabel! @IBOutlet private weak var feelsLikeTemperatureLabel: UILabel! // MARK: - Public Properties var networkWeatherManager = NetworkWeatherManager() var city: String? = nil private var activityIndicator = UIActivityIndicatorView() private let realm = try! Realm() lazy var locationManager: CLLocationManager = { let locManager = CLLocationManager() locManager.delegate = self locManager.desiredAccuracy = kCLLocationAccuracyKilometer locManager.requestWhenInUseAuthorization() return locManager }() // MARK: - Action @IBAction func searchPressed(_ sender: UIButton) { presentSearchAlertController(withTitle: Constants.placeHolder, message: nil, style: .alert) { [weak self] city in guard let self = self else { return } self.networkWeatherManager.fentchCurrentWeather(forRequestType: .cityName(city: city)) guard !MockCities.shared.cities.contains(city) else { return } MockCities.shared.cities.append(city) } } // MARK: - UIViewController override func viewDidLoad() { super.viewDidLoad() setupApplication() setupIndicator() view.addSubview(activityIndicator) guard let city = city else { return } networkWeatherManager.fentchCurrentWeather(forRequestType: .cityName(city: city)) } // MARK: - Private Methods private func setupIndicator() { activityIndicator.center = self.view.center activityIndicator.hidesWhenStopped = true activityIndicator.isHidden = false activityIndicator.style = .large activityIndicator.startAnimating() } private func setupApplication() { networkWeatherManager.delegate = self guard CLLocationManager.locationServicesEnabled() else { return } locationManager.requestLocation() } } // MARK: - NetworkWeatherManagerDelegate extension ViewController: NetworkWeatherManagerDelegate { func updateInteface(_: NetworkWeatherManager, with currentWeather: CurrentWeather) { DispatchQueue.main.async { self.cityLabel.text = currentWeather.cityName self.temperatureLabel.text = currentWeather.temperatureString self.feelsLikeTemperatureLabel.text = currentWeather.feelsLikeTemperatureString self.weatherIconImageView.image = UIImage(systemName: currentWeather.systemIconNameString) } } func showAlert() { let alert = UIAlertController(title: "Нет доступа", message: "Подключитесь к сети", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Понятно", style: .cancel, handler: nil)) self.present(alert, animated: true) } func showInfo() { let alert = UIAlertController(title: "Нет доступа к сети", message: "Были загруженны последние сохранённые данные.", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Понятно", style: .cancel, handler: nil)) self.present(alert, animated: true) } func hideActivityView() { DispatchQueue.main.async { self.activityIndicator.isHidden = true } } } // MARK: - CLLocationManagerDelegate extension ViewController: CLLocationManagerDelegate { func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { guard let location = locations.last else { return } let latitude = location.coordinate.latitude let longitude = location.coordinate.longitude networkWeatherManager.fentchCurrentWeather(forRequestType: .coordinate(latitude: latitude, longitude: longitude)) } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print(error.localizedDescription) } } <file_sep>/Sunny/View Controllers/CitiesViewController.swift // // CitiesViewController.swift // Sunny // // Created by Harbros38 on 3/22/21. // Copyright © 2021 <NAME>. All rights reserved. // import UIKit class CitiesViewController: UIViewController { private let tableview = UITableView() private let identifier = "cell" override func viewDidLoad() { super.viewDidLoad() createFrames() tableview.delegate = self tableview.dataSource = self tableview.register(UITableViewCell.self, forCellReuseIdentifier: identifier) view.addSubview(tableview) } private func createFrames() { tableview.frame = UIScreen.main.bounds let background = UIView() background.frame = UIScreen.main.bounds let backgroundImage = UIImageView(image: UIImage(named: "background")) backgroundImage.frame = background.frame background.addSubview(backgroundImage) tableview.backgroundView = background } } extension CitiesViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableview.deselectRow(at: indexPath, animated: true) let vc = navigationController?.storyboard?.instantiateViewController(withIdentifier: "ViewController") as! ViewController vc.city = MockCities.shared.cities[indexPath.row] navigationController?.pushViewController(vc, animated: true) } } extension CitiesViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return MockCities.shared.cities.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell(style: .default, reuseIdentifier: identifier) cell.textLabel?.text = MockCities.shared.cities[indexPath.row] cell.backgroundColor = .clear return cell } } <file_sep>/Sunny/Supporting files/MockCities.swift // // MockCities.swift // Sunny // // Created by Harbros38 on 3/22/21. // Copyright © 2021 <NAME>. All rights reserved. // import Foundation final class MockCities { static var shared: MockCities = .init() var cities = ["Abuja","Algeria","Amman","Apia","Asuncion","Athens","Banjul","Belmopan","Berlin","Brazzaville","Canberra","Conakry","Dakar","Djibouti","Doha","Dublin","Harare","Honiara","Kinshasa","Kuala lumpur","Ljubljana","Luanda","Lusaka","Majuro","Manama","Maputo","Maseru","Minsk","Moscow","Muscat","Nicosia","Nouakchott","Nukualofa","Panama","Paramaribo","Praia","Quito","Rabat","Riga","Rome","Sarajevo","Stepanakert","Sukhum","Tskhinval","Valletta","Victoria","Yamoussoukro","Yerevan"] } <file_sep>/Sunny/Supporting files/Constants.swift import Foundation // MARK: - Constats enum Constants { static let apiKey = "e7e2f3381a734460a05504f2c8c4af64" static let placeHolder = "Enter a city" static let titleAlert = "Search" static let titleCancelButton = "Cancel" } <file_sep>/Sunny/Models/RealmModel.swift // // RealmModel.swift // Sunny // // Created by Harbros38 on 3/23/21. // Copyright © 2021 <NAME>. All rights reserved. // import Foundation import RealmSwift @objcMembers class RealmModel: Object { dynamic var cityName = "" dynamic var temperature = 0.0 dynamic var feelsLikeTemperature = 0.0 dynamic var conditionCode = 0 dynamic var id = UUID().uuidString class override func primaryKey() -> String? { return "id" } } <file_sep>/Sunny/Extensions/ViewController+alertController.swift import UIKit extension ViewController { func presentSearchAlertController( withTitle title: String?, message: String?, style: UIAlertController.Style, completionHandler: @escaping (String) -> Void ) { let alertController = UIAlertController(title: title, message: message, preferredStyle: style) alertController.addTextField { textField in textField.placeholder = Constants.placeHolder } let search = UIAlertAction(title: Constants.titleAlert, style: .default) { action in let textField = alertController.textFields?.first guard let cityName = textField?.text else { return } guard cityName != "" else { return } let city = cityName.split(separator: " ").joined(separator: "%20") completionHandler(city) } let cancel = UIAlertAction(title: Constants.titleCancelButton, style: .cancel, handler: nil) alertController.addAction(search) alertController.addAction(cancel) present(alertController, animated: true, completion: nil) } } <file_sep>/Sunny/Models/NetworkWeatherManager.swift import Foundation import CoreLocation import RealmSwift // MARK: - NetworkWeatherManagerDelegate protocol NetworkWeatherManagerDelegate: class { func updateInteface(_: NetworkWeatherManager, with currentWeather: CurrentWeather) func showAlert() func showInfo() func hideActivityView() } // MARK: - NetworkWeatherManager class NetworkWeatherManager { enum RequestType { case cityName(city: String) case coordinate(latitude: Double, longitude: Double) } // MARK: - Delegate weak var delegate: NetworkWeatherManagerDelegate? private let realm = try! Realm() // MARK: - Public Methods func fentchCurrentWeather(forRequestType requestType: RequestType) { var urlString = "" var cityName = "" switch requestType { case .cityName(let city): cityName = city urlString = "https://api.openweathermap.org/data/2.5/weather?q=\(city)&apikey=\(Constants.apiKey)&units=metric" case .coordinate(let latitude, let longitude): urlString = "https://api.openweathermap.org/data/2.5/weather?lat=\(latitude)&lon=\(longitude)&apikey=\(Constants.apiKey)&units=metric" } performRequest(withURLString: urlString, cityName: cityName) } // MARK: - Private Methods private func performRequest(withURLString urlString: String, cityName: String) { guard let url = URL(string: urlString) else { return } let session = URLSession(configuration: .default) let task = session.dataTask(with: url) { data, response, error in guard (error == nil) else { DispatchQueue.main.async { self.loadFromRealm(cityName: cityName) } return } guard let data = data else { return } guard let currentWeather = self.parseJSON(withData: data) else { return } self.delegate?.updateInteface(self, with: currentWeather) self.delegate?.hideActivityView() DispatchQueue.main.async { self.addToRealm(currentWeather: currentWeather) } } task.resume() } private func loadFromRealm(cityName: String) { let allCache = self.realm.objects(RealmModel.self).filter("cityName=%@", cityName) guard let tergetCity = allCache.first else { self.delegate?.showAlert() return } self.delegate?.showInfo() let currentWeather = CurrentWeather(realmModel: tergetCity) self.delegate?.updateInteface(self, with: currentWeather) } private func addToRealm(currentWeather: CurrentWeather) { let model = RealmModel() model.cityName = currentWeather.cityName model.conditionCode = currentWeather.conditionCode model.feelsLikeTemperature = currentWeather.feelsLikeTemperature model.temperature = currentWeather.temperature try? realm.write { realm.add(model, update: .modified) } } private func parseJSON(withData data: Data) -> CurrentWeather? { let decoder = JSONDecoder() guard let currentWeatherData = try? decoder.decode(CurrentWeatherData.self, from: data) else { return nil } guard let currentWeather = CurrentWeather(currentWeatherData: currentWeatherData) else { return nil } return currentWeather } }
c06dc4fed667beb111b05cfbed54d4d2c77b4a44
[ "Swift" ]
7
Swift
MrFraiday/Lab4RPO
436ea159681807d6229b460c02f340a02879593b
550f9b17755555497adfafbbf44fec5f63ce5610
refs/heads/master
<file_sep>import { Component } from "react"; import Link from "next/link"; class AboutPage extends Component { render() { return ( <main> <section> I am a <br/> <Link href="/"> <a>Go to Home</a> </Link> </section> </main> ); } } export default AboutPage;<file_sep>#### About the project This repository is dedicated to exploring next.js. Each branch corresponds to a tutorial I have writen and the master branch will always have code from the latest tutorial. #### Setup ```sh npm install # install dependencies npm run api # run json-server npm start # run next.js ``` #### Tutorials so far: - [Introduction to the basics of Next.js](https://dev.to/aurelkurtula/introduction-to-the-basics-of-nextjs-1loa) - branch : [part1](https://github.com/aurelkurtula/basics-of-nextJS/tree/part1) - [Retrieving data from an external API](https://dev.to/aurelkurtula/introduction-to-the-basics-of-nextjs---part-two-pad) To illustrate the features I have decided to create a prototype that resembles instagram Home page: ![](./thumb1.png) Photo page: ![](./thumb2.png)
b7ff0425ab5d3eb7db3106ec62cb33cf6ae9578f
[ "JavaScript", "Markdown" ]
2
JavaScript
geekyoperand/test
bfbb93642cf4b55016d7c20d8df0cd9f536ad957
2d3a8af98f9e09d71a670f07e9b64496a82486ac
refs/heads/main
<repo_name>sofiscode/ctd-frontend3-primer-evaluacion<file_sep>/src/components/Boton.js import React, { Component } from "react"; class Boton extends Component { render() { return ( <div className="opcion"> <button id={this.props.nombreBoton} className="botones" onClick={this.props.handleClick}> {this.props.nombreBoton} </button> <h2>{this.props.opcion}</h2> </div> ); } } export default Boton;<file_sep>/src/components/Estado.js import React, { Component } from "react"; import Recordatorio from "./Recordatorio"; import Opciones from "./Opciones"; class Estado extends Component { render() { return ( <div className="layout"> <h1 className="historia">{this.props.historia}</h1> <Opciones handleClick={this.props.handleClick} opcionA={this.props.opcionA} opcionB={this.props.opcionB} /> <Recordatorio seleccionPrevia={this.props.seleccionPrevia} selecciones={this.props.listaSeleccionPrevia.map( (e, index) => ( <li key={index}>{e}</li> ), this.props.id )} /> </div> ); } } export default Estado; <file_sep>/src/components/Opciones.js import React, { Component } from "react"; import Boton from "./Boton"; class Opciones extends Component { render() { return ( <div className="opciones"> <Boton handleClick={this.props.handleClick} opcion={this.props.opcionA} nombreBoton="A" /> <Boton handleClick={this.props.handleClick} opcion={this.props.opcionB} nombreBoton="B" /> </div> ); } } export default Opciones;<file_sep>/README.md # ctd-frontend3-primer-evaluacion Código en CodeSandbox https://codesandbox.io/s/funny-northcutt-vw82b
d76a61dffcfda8b74cbc30c1c50ff09808447c33
[ "JavaScript", "Markdown" ]
4
JavaScript
sofiscode/ctd-frontend3-primer-evaluacion
8fc1ec1c853c28c6a9839a55b8a249e72c34fcf3
481f68cb4c2955b5fb8fbd6398d8988b72b09dd9
refs/heads/master
<file_sep><h2>Item list</h2> <table class="table table-condensed"> <thead> <tr> <th>#</th> <th>Name</th> <th>Description</th> <th>Action</th> </tr> </thead> <tbody> <tr ng-repeat="item in vm.items"> <th>{{item.id}}</th> <td>{{item.name}}</td> <td>{{item.description}}</td> <td> <button class="btn btn-primary" ng-click="vm.removeItem(item.id)">remove</button> </td> </tr> </tbody> </table><file_sep>import * as angular from 'angular'; import 'angular-ui-router'; import './app/home/config'; import './app/items/config'; import './assets/css/bootstrap.css'; import './assets/scss/app.scss'; angular.module('app', [ 'ui.router', 'app.items', 'app.home' ]).config(config); config.$inject = ['$stateProvider', '$urlRouterProvider']; function config( $stateProvider: ng.ui.IStateProvider, $urlRouterProvider: ng.ui.IUrlRouterProvider ): void { $urlRouterProvider.otherwise('/'); };;<file_sep>import * as angular from 'angular'; import {ItemListCtrl} from './ItemListCtrl'; import {ItemService} from './ItemService'; angular.module('app.items', []) .service('ItemService', ItemService) .controller('ItemListCtrl', ItemListCtrl) .config(config); function config( $stateProvider: ng.ui.IStateProvider, $urlRouterProvider: ng.ui.IUrlRouterProvider ): void { $stateProvider .state('items', { url: '/items', templateUrl: './app/items/itemList.html', controller: 'ItemListCtrl as vm' }); };;<file_sep>import * as angular from 'angular'; import HomeBoxDirective from './HomeBoxDirective'; angular.module('app.home', []) .directive('homeBox', <any>HomeBoxDirective) .config(config); function config( $stateProvider: ng.ui.IStateProvider, $urlRouterProvider: ng.ui.IUrlRouterProvider ): void { $stateProvider .state('home', { url: '/', templateUrl: './app/home/home.html' }); };;<file_sep>export interface IItem { id: number; name: string; description: string; } export class Item implements IItem { constructor( public id: number, public name: string, public description: string ) {} }<file_sep># ng-ts-starter Simple Angular &amp; Typescript starter Quick start: **npm install -g typescript tsd webpack webpack-dev-server**<br> **npm install**<br> **tsd install**<br> **npm start** <file_sep>import directive from '../common/decorators/directive'; @directive('$rootScope') export default class HomeBoxDirective implements ng.IDirective { public templateUrl: string; public restrict: string; public scope: Object; constructor(private $rootScope: ng.IScope) { this.templateUrl = './app/home/homeDirective.html'; this.restrict = 'EA'; this.scope = { type: '=' }; //dependencies test console.log('$inject', $rootScope); } public link(scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes): void { //scope attrs test console.log(attrs); } }<file_sep>import {Item, IItem} from './Item'; export interface IItemService { getItems(): IItem[]; } export class ItemService implements IItemService { getItems(): IItem[] { return [ new Item(1, 'Item 1', 'Description 1'), new Item(2, 'Item 2', 'Description 2'), new Item(3, 'Item 3', 'Description 3') ]; } }<file_sep>import {Item, IItem} from './Item'; import {ItemService} from './ItemService'; export interface IItemListModel { title: string; items: IItem[]; removeItem(id: number): void; } export class ItemListCtrl implements IItemListModel { public title: string; public items: IItem[]; static $inject = ['ItemService']; constructor(private itemService: ItemService) { this.title = 'Item list'; this.items = itemService.getItems(); } public removeItem(id: number) { let i = this.items.length; while(i--) { let item = this.items[i]; if (item.id === id) { this.items.splice(i, 1); } } } }
3354130ad12519d583c6c3f8f1dda531d1cd1400
[ "Markdown", "TypeScript", "HTML" ]
9
HTML
rpoltorak/ng-ts-starter
80fee6d094def86b53a4ae5f2eba65fc794a4899
debd32f33e3c51ae9180161c07f28b17ca038d9b
refs/heads/master
<file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package DTO; import java.io.Serializable; import java.util.Date; import java.util.List; /** * * @author julie */ public class DemandeFormationDTO implements Serializable { private String codeFormation; private int codeClient; private String nomClient; private String intitule; private int nbPersonnes; private List<FormateurDTO> listFormateursPressentis; private List<SalleDTO> listSallesPressenties; private int capaciteMax; private int capaciteMin; private String typeFormation; public DemandeFormationDTO() { } /** * get nombre de personne * @return nombre de personne */ public int getNbPersonnes() { return nbPersonnes; } /** * set nombre de personne * @param nbPersonnes nombre de personne */ public void setNbPersonnes(int nbPersonnes) { this.nbPersonnes = nbPersonnes; } /** * get le nom du client * @return nom du client */ public String getNomClient() { return nomClient; } /** * set le nom du client * @param nomClient nom du client */ public void setNomClient(String nomClient) { this.nomClient = nomClient; } /** * get l'intitule * @return intitule de la formation */ public String getIntitule() { return intitule; } /** * set l'intitule * @param intitule intitule de la formation */ public void setIntitule(String intitule) { this.intitule = intitule; } /** * get code de la formation * @return code de la formation */ public String getCodeFormation() { return codeFormation; } /** * set code de la formation * @param codeFormation code de la formation */ public void setCodeFormation(String codeFormation) { this.codeFormation = codeFormation; } /** * get code du client * @return code du client */ public int getCodeClient() { return codeClient; } /** * set code du client * @param codeClient code du client */ public void setCodeClient(int codeClient) { this.codeClient = codeClient; } /** * get la liste des formateurs préssentis de la formation * @return la liste des formateurs préssentis de la formation */ public List<FormateurDTO> getListFormateursPressentis() { return listFormateursPressentis; } /** * set la liste des formateurs pressentis * @param listFormateursPressentis la liste des formateurs pressentis */ public void setListFormateursPressentis(List<FormateurDTO> listFormateursPressentis) { this.listFormateursPressentis = listFormateursPressentis; } /** * get la liste des salles pressenties * @return la liste des salles pressenties */ public List<SalleDTO> getListSallesPressenties() { return listSallesPressenties; } /** * set la liste des salles pressenties * @param listSallesPressenties la liste des salles pressenties */ public void setListSallesPressenties(List<SalleDTO> listSallesPressenties) { this.listSallesPressenties = listSallesPressenties; } /** *get la capacite maximum * @return la capacite maximum */ public int getCapaciteMax() { return capaciteMax; } /** * set la capacite maximum * @param capaciteMax la capacite maximum */ public void setCapaciteMax(int capaciteMax) { this.capaciteMax = capaciteMax; } /** * get la capacite minimum * @return la capacite minimum */ public int getCapaciteMin() { return capaciteMin; } /** * set la capacite minimum * @param capaciteMin la capacite minimum */ public void setCapaciteMin(int capaciteMin) { this.capaciteMin = capaciteMin; } /** * get type de la formation * @return type de la formation */ public String getTypeFormation() { return typeFormation; } /** * set type de la formation * @param typeFormation type de la formation */ public void setTypeFormation(String typeFormation) { this.typeFormation = typeFormation; } @Override public String toString() { return "DemandeFormationDTO{" + "codeFormation=" + codeFormation + ", codeClient=" + codeClient + ", nomClient=" + nomClient + ", intitule=" + intitule + ", nbPersonnes=" + nbPersonnes + ", listFormateursPressentis=" + listFormateursPressentis + ", listSallesPressenties=" + listSallesPressenties + ", capaciteMax=" + capaciteMax + ", capaciteMin=" + capaciteMin + '}'; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.barban.corentin.commercial.business; import DTO.FormateurDTO; import DTO.FormationDTO; import DTO.SalleDTO; import Exceptions.ListeFormationsVideException; import com.barban.corentin.commercial.entities.Demandedeformation; import com.barban.corentin.commercial.repositories.DemandedeformationFacadeLocal; import com.barban.corentin.commercial.sender.SenderDemandeCompteRendu; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.ejb.EJB; import javax.ejb.Stateless; /** * Classe métier de la gestion commerciale * * @author <NAME> */ @Stateless public class gestionCommerciale implements gestionCommercialeLocal { @EJB private DemandedeformationFacadeLocal demandedeformationFacade; private List<FormationDTO> listeFormations; final String hostTechnico = "http://localhost:8085/MIAGETechnicoCommercial-web/webresources"; /** * Méthode permettant de récupérer le catalogue de formations. * */ @Override public void recupererCatalogueFormations() { try { URL url = new URL(hostTechnico + "/formationsCatalogue"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.connect(); Gson gson = new Gson(); this.listeFormations = new ArrayList<>(); if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } else { InputStreamReader in = new InputStreamReader(conn.getInputStream()); BufferedReader br = new BufferedReader(in); String output; while ((output = br.readLine()) != null) { FormationDTO formation = gson.fromJson(output, FormationDTO.class); this.listeFormations.add(formation); formation.toString(); } } conn.disconnect(); } catch (IOException ex) { Logger.getLogger(gestionCommerciale.class.getName()).log(Level.SEVERE, null, ex); } } /** * Méthode permettant de mémoriser une demande de formation * * @param nomClient Nom d'un client * @param dateDemande Date de la demande * @param codeFormation Code de la formation * @param intituleFormation Intitule de la formation * @param codeclient Code du client */ @Override public void memoriserDemandeFormation(String nomClient, Date dateDemande, String codeFormation, String intituleFormation, Integer codeclient) { Demandedeformation demandeFormation = new Demandedeformation(nomClient, dateDemande, codeFormation, intituleFormation, codeclient); Demandedeformation dfObjet = this.demandedeformationFacade.create(demandeFormation); } /** * Méthode permettant de générer des comptes rendus, positifs ou négatifs. * * @throws ListeFormationsVideException ListeFormationsVideException liste formation vide */ @Override public void editerComptesRendus() throws ListeFormationsVideException { SenderDemandeCompteRendu sender = new SenderDemandeCompteRendu(); sender.sendMessageDemandeInformationFormations(); } /** * Fonction permettant de valider l'existence d'une formation * * @param code code de la formation * @return true si la formation existe, false si la formation n'existe pas */ @Override public boolean validerExistenceFormation(String code) { boolean existe = false; try { URL url = new URL(hostTechnico + "/formationsCatalogue/" + code); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.connect(); Gson gson = new Gson(); if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } else { InputStreamReader in = new InputStreamReader(conn.getInputStream()); BufferedReader br = new BufferedReader(in); String output; if ((output = br.readLine()) != null) { existe = true; } conn.disconnect(); } } catch (IOException ex) { Logger.getLogger(gestionCommerciale.class.getName()).log(Level.SEVERE, null, ex); } return existe; } /** * Méthode permettant de demander l'état d'une formation * * @param idFormation l'id de la formation souhaitée * @return une chaine contenant l'état de la formation */ @Override public String demanderEtatFormation(int idFormation) { String etat = null; FormationDTO formation = null; try { URL url = new URL("/formations/" + idFormation); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.connect(); Gson gson = new Gson(); if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } else { InputStreamReader in = new InputStreamReader(conn.getInputStream()); BufferedReader br = new BufferedReader(in); String output; while ((output = br.readLine()) != null) { formation = gson.fromJson(output, FormationDTO.class); } etat = formation.getStatut(); } } catch (IOException ex) { Logger.getLogger(gestionCommerciale.class.getName()).log(Level.SEVERE, null, ex); } return etat; } /** * Méthode permettant de recuperer la liste des formateurs compétent pour * une formation * * @param code Code de la formation * @return liste des formateurs compétent pour une formation */ @Override public List<FormateurDTO> recupererListeFormateurCompetent(String code) { List<FormateurDTO> listeFormateurDTOs = new ArrayList<>(); try { URL url = new URL(hostTechnico + "/formationsCatalogue/" + code + "/formateurs"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.connect(); Gson gson = new Gson(); if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } else { InputStreamReader in = new InputStreamReader(conn.getInputStream()); BufferedReader br = new BufferedReader(in); String output; while ((output = br.readLine()) != null) { listeFormateurDTOs = gson.fromJson(output, new TypeToken<List<FormateurDTO>>() { }.getType()); } } conn.disconnect(); } catch (IOException ex) { Logger.getLogger(gestionCommerciale.class.getName()).log(Level.SEVERE, null, ex); } return listeFormateurDTOs; } /** * Méthode permettant de recuperer la liste des salles adequates pour une * formation * * @param code Code de la formation * @return lite des salles adequates pour une formation */ @Override public List<SalleDTO> recupererListeSallesAdequates(String code) { List<SalleDTO> listeSallesDTOs = new ArrayList<>(); try { URL url = new URL(hostTechnico + "/formationsCatalogue/" + code + "/salles"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.connect(); Gson gson = new Gson(); if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } else { InputStreamReader in = new InputStreamReader(conn.getInputStream()); BufferedReader br = new BufferedReader(in); String output; while ((output = br.readLine()) != null) { listeSallesDTOs = gson.fromJson(output, new TypeToken<List<SalleDTO>>() { }.getType()); } } conn.disconnect(); } catch (IOException ex) { Logger.getLogger(gestionCommerciale.class.getName()).log(Level.SEVERE, null, ex); } return listeSallesDTOs; } /** * Obtenir la capacité min d'une formation * @param codeFormation Code de la formation * @return la capacité min d'une formation */ @Override public FormationDTO recupererInformationFormationCatalogue(String codeFormation) { try { URL url = new URL(hostTechnico + "/formationsCatalogue/" + codeFormation); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.connect(); Gson gson = new Gson(); FormationDTO formationDTO = null; if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } else { InputStreamReader in = new InputStreamReader(conn.getInputStream()); BufferedReader br = new BufferedReader(in); String output; while ((output = br.readLine()) != null) { formationDTO = gson.fromJson(output, new TypeToken<FormationDTO>() { }.getType()); } } conn.disconnect(); return formationDTO; } catch (IOException ex) { Logger.getLogger(gestionCommerciale.class.getName()).log(Level.SEVERE, null, ex); } return null; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.barban.corentin.commercial.repositories; import com.barban.corentin.commercial.entities.Demandedeformation; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; /** * * @author Corentin */ @Stateless public class DemandedeformationFacade extends AbstractFacade<Demandedeformation> implements DemandedeformationFacadeLocal { @PersistenceContext(unitName = "com.barban.corentin_MIAGECommercial-ejb_ejb_1.0-SNAPSHOTPU") private EntityManager em; /** * Return l'entity manager * @return entity manager */ @Override protected EntityManager getEntityManager() { return em; } /** * demande la formation */ public DemandedeformationFacade() { super(Demandedeformation.class); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.barban.corentin.technicoCommercial.services; import DTO.FormateurDTO; import DTO.FormationDTO; import DTO.SalleDTO; import Exceptions.FormateurNotFoundException; import Exceptions.FormationCatalogueException; import Exceptions.FormationCatalogueNotFoundException; import Exceptions.LienFormateurFormationException; import java.util.List; import javax.ejb.Local; /** * * @author jdetr */ @Local public interface ServiceTechnicoCommercialLocal { /** * Ajoute une formation au catalogue * @param code code * @param intitule intitule * @param niveau niveau * @param typeduree type duree * @param capacitemin capacite minimum * @param capacitemax capacite maximum * @param tarifforfaitaire tarif forfaitaire * @return true si formation créer * @throws FormationCatalogueNotFoundException formation catalogue non trouvé * @throws FormationCatalogueException formation catalogue exception */ FormationDTO ajouterFormationCatalogue(String code, String intitule, String niveau, String typeduree, Integer capacitemin, Integer capacitemax, Double tarifforfaitaire) throws FormationCatalogueNotFoundException, FormationCatalogueException; /** * Supprimer la formation catalogue * @param code code * @return true si supprimé * @throws FormationCatalogueNotFoundException formation catalogue non trouvé */ boolean supprimerFormationCatalogue(String code) throws FormationCatalogueNotFoundException; /** * Consulter la formation catalogue * @param code code * @return la formation catalogue * @throws FormationCatalogueNotFoundException formation catalogue non trouvé */ FormationDTO consulterFormationCatalogue(String code) throws FormationCatalogueNotFoundException; /** * lister formation catalogue * @return le catalogue de formations */ List<FormationDTO> listerCatalogueFormations(); /** * Recherche la salle adequates * @param code code * @return la salle adequates */ List<SalleDTO> rechercherSallesAdequates(String code); /** * REcherche formateur adequats * @param code code * @return le formateur adequats */ List<FormateurDTO> rechercherFormateurAdequats(String code); /** * Ajouter un formateur dans la formation * @param code code * @param formateurkey formateur key * @return true si bien créer * @throws FormateurNotFoundException formateur not found * @throws LienFormateurFormationException lien entre formateur et formation non existant */ boolean ajouterFormateurDansFormation(String code, int formateurkey) throws FormateurNotFoundException, LienFormateurFormationException; /** * supprimer un formateur de la formation * @param code code * @param formateurkey formateur key * @return true si formateur supprimé de la formation * @throws FormateurNotFoundException formateur non trouvé * @throws LienFormateurFormationException lien formateur formation non trouvé */ boolean supprimerFormateurDeFormation(String code, int formateurkey) throws FormateurNotFoundException, LienFormateurFormationException; /** * ajouter salle dans formation * @param code code * @param sallekey salle key * @return true si salle ajouter à la formation * @throws FormateurNotFoundException formateur non trouvé * @throws LienFormateurFormationException lien formateur formation non trouvé */ boolean ajouterSalleDansFormation(String code, int sallekey) throws FormateurNotFoundException, LienFormateurFormationException; /** * Supprimer salle d'une formation * @param code code * @param sallekey key salle * @return true si salle bien supprimé de la formation * @throws FormateurNotFoundException formateur non trouvé * @throws LienFormateurFormationException lien formateur formation non trouvé */ boolean supprimerSalleDeFormation(String code, int sallekey) throws FormateurNotFoundException, LienFormateurFormationException; } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.barban.corentin.formation.services; import javax.ejb.Local; /** * * @author Corentin */ @Local public interface ServiceFormationLocal { /** * Demander l'état d'une formation * @param idFormation id de la formation * @return l'état d'une formation */ String demanderEtatFormation(Integer idFormation); } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.barban.corentin.RH.entities; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; /** * * @author Corentin */ @Entity @Table(name = "CALENDRIER_FORMATEUR") @XmlRootElement @NamedQueries({ @NamedQuery(name = "CalendrierFormateur.findAll", query = "SELECT c FROM CalendrierFormateur c") , @NamedQuery(name = "CalendrierFormateur.findByCalendrierkey", query = "SELECT c FROM CalendrierFormateur c WHERE c.calendrierFormateurPK.calendrierkey = :calendrierkey") , @NamedQuery(name = "CalendrierFormateur.findByFormateurkey", query = "SELECT c FROM CalendrierFormateur c WHERE c.calendrierFormateurPK.formateurkey = :formateurkey") , @NamedQuery(name = "CalendrierFormateur.findByStatut", query = "SELECT c FROM CalendrierFormateur c WHERE c.statut = :statut")}) public class CalendrierFormateur implements Serializable { private static final long serialVersionUID = 1L; @EmbeddedId protected CalendrierFormateurPK calendrierFormateurPK; @Size(max = 50) @Column(name = "STATUT") private String statut; @JoinColumn(name = "CALENDRIERKEY", referencedColumnName = "IDCALENDRIER", insertable = false, updatable = false) @ManyToOne(optional = false) private Calendrier calendrier; @JoinColumn(name = "FORMATEURKEY", referencedColumnName = "IDFORMATEUR", insertable = false, updatable = false) @ManyToOne(optional = false) private Formateur formateur; public CalendrierFormateur() { } /** * constructeur du calendrier formateur à partir de la primary key * * @param calendrierFormateurPK calendrier formateur primary key */ public CalendrierFormateur(CalendrierFormateurPK calendrierFormateurPK) { this.calendrierFormateurPK = calendrierFormateurPK; } /** * constructeur calendrier formateur à partir de la calendrier key et * formateur key * * @param calendrierkey calendrier key * @param formateurkey formateur key */ public CalendrierFormateur(int calendrierkey, int formateurkey) { this.calendrierFormateurPK = new CalendrierFormateurPK(calendrierkey, formateurkey); } /** * get la primary key du calendrier formateur * * @return la primary key du calendrier formateur */ public CalendrierFormateurPK getCalendrierFormateurPK() { return calendrierFormateurPK; } /** * set la primary ky du calendrier formateur * * @param calendrierFormateurPK la primary key du calendrier formateur */ public void setCalendrierFormateurPK(CalendrierFormateurPK calendrierFormateurPK) { this.calendrierFormateurPK = calendrierFormateurPK; } /** * get statut * * @return statut */ public String getStatut() { return statut; } /** * set statut * * @param statut statut */ public void setStatut(String statut) { this.statut = statut; } /** * get calendrier * @return calendrier */ public Calendrier getCalendrier() { return calendrier; } /** * set calendrier * @param calendrier calendrier */ public void setCalendrier(Calendrier calendrier) { this.calendrier = calendrier; } /** * get formateur * @return formateur */ public Formateur getFormateur() { return formateur; } /** * set formateur * @param formateur formateur */ public void setFormateur(Formateur formateur) { this.formateur = formateur; } @Override public int hashCode() { int hash = 0; hash += (calendrierFormateurPK != null ? calendrierFormateurPK.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof CalendrierFormateur)) { return false; } CalendrierFormateur other = (CalendrierFormateur) object; if ((this.calendrierFormateurPK == null && other.calendrierFormateurPK != null) || (this.calendrierFormateurPK != null && !this.calendrierFormateurPK.equals(other.calendrierFormateurPK))) { return false; } return true; } @Override public String toString() { return "com.barban.corentin.RH.entities.CalendrierFormateur[ calendrierFormateurPK=" + calendrierFormateurPK + " ]"; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.barban.corentin.commercial.sender; import DTO.DemandeFormationDTO; import java.util.Random; import java.util.logging.Level; import java.util.logging.Logger; import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageConsumer; import javax.jms.MessageListener; import javax.jms.MessageProducer; import javax.jms.ObjectMessage; import javax.jms.Session; import javax.jms.TextMessage; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; /** * * @author Corentin */ public class SenderDemandeFormationJMS implements MessageListener { Context context = null; ConnectionFactory factory = null; Connection connection = null; String factoryName = "ConnectionFactory"; String destName = "QUEUE_FORMATION_DEMANDEE"; Destination dest = null; Session session = null; MessageProducer producer = null; public SenderDemandeFormationJMS() { } /** * Envoyer une demande de formation via JMS * * @param demandeFormation Demande de formation */ public void sendMessageDemandeFormation(DemandeFormationDTO demandeFormation) { try { // create the JNDI initial context. context = new InitialContext(); // look up the ConnectionFactory factory = (ConnectionFactory) context.lookup(factoryName); // look up the Destination dest = (Destination) context.lookup(destName); // create the connection connection = factory.createConnection(); // start the connection, to enable message sends connection.start(); // create the session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); // create the sender producer = session.createProducer(dest); Destination tempDest = session.createTemporaryQueue(); MessageConsumer responseConsumer = session.createConsumer(tempDest); responseConsumer.setMessageListener(this); ObjectMessage message = session.createObjectMessage(demandeFormation); message.setJMSReplyTo(tempDest); String correlationId = this.createRandomString(); message.setJMSCorrelationID(correlationId); producer.send(message); } catch (NamingException ex) { Logger.getLogger(SenderDemandeFormationJMS.class.getName()).log(Level.SEVERE, null, ex); } catch (JMSException ex) { Logger.getLogger(SenderDemandeFormationJMS.class.getName()).log(Level.SEVERE, null, ex); } } /** * Créer un string aléatoire * @return string aléatoire */ private String createRandomString() { Random random = new Random(System.currentTimeMillis()); long randomLong = random.nextLong(); return Long.toHexString(randomLong); } /** * Attente de la message de confirmation de la prise en compte de demande de formation * @param message message */ @Override public void onMessage(Message message) { if (message instanceof TextMessage) { try { TextMessage textMessage = (TextMessage) message; System.out.println("messageText = " + textMessage.getText()); } catch (JMSException ex) { Logger.getLogger(SenderDemandeFormationJMS.class.getName()).log(Level.SEVERE, null, ex); } } } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.barban.corentin.patrimoine.business; import DTO.FormateurDTO; import DTO.SalleDTO; import Exceptions.SalleNotFoundException; import com.barban.corentin.patrimoine.entities.CalendrierSalle; import com.barban.corentin.patrimoine.entities.Salle; import com.barban.corentin.patrimoine.repositories.SalleFacadeLocal; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.List; import javax.ejb.EJB; import javax.ejb.Stateless; /** * * @author Corentin */ @Stateless public class gestionPatrimoine implements gestionPatrimoineLocal { @EJB private SalleFacadeLocal salleFacade; /** * Editer le statut d'une salle pour une date donnée * * @param idSalle identifiant d'une salle * @param statut statut à modifier * @param date date de la modification * @throws Exceptions.SalleNotFoundException salle non trouvé */ @Override public void editerStatutSalle(Integer idSalle, String statut, Date date) throws SalleNotFoundException { Salle s = this.salleFacade.find(idSalle); if (s == null) { throw new SalleNotFoundException(); } SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); Collection<CalendrierSalle> cs = s.getCalendrierSalleCollection(); for (CalendrierSalle c : cs) { if (dateFormat.format(c.getCalendrier().getDatecalendrier()).compareTo(dateFormat.format(date)) == 0) { c.setStatut(statut); } } } /** * Lister toutes les dates pour lesquelles les salle sont disponibles * * @param listSallesDemandees Liste des salles pressenties * @return les dates pour lesquelles les salle sont disponibles */ @Override public HashMap<SalleDTO, List<Date>> listerSalleDisponible(List<SalleDTO> listSallesDemandees) { HashMap<SalleDTO, List<Date>> listeSallesDiponibles = new HashMap(); for (SalleDTO salleDTO : listSallesDemandees) { Salle s = this.salleFacade.find(salleDTO.getIdsalle()); Collection<CalendrierSalle> cs = s.getCalendrierSalleCollection(); List<Date> listeDateDispo = new ArrayList(); for (CalendrierSalle c : cs) { if (c.getStatut().equals("DISPONIBLE")) { listeDateDispo.add(c.getCalendrier().getDatecalendrier()); } } listeSallesDiponibles.put(salleDTO, listeDateDispo); } return listeSallesDiponibles; } /** * Verfier l'existance d'une salle * @param salleKey Identifiant d'une salle * @return true si elle existe sinon false */ @Override public boolean validerExistenceSalle(Integer salleKey) { Salle s = this.salleFacade.find(salleKey); return s != null; } @Override public List<SalleDTO> listerSalles() { List<Salle> salle = this.salleFacade.findAll(); List<SalleDTO> sallesDTO = new ArrayList<>(); for (Salle salle1 : salle) { SalleDTO s = new SalleDTO(); s.setIdsalle(salle1.getIdsalle()); s.setNom(salle1.getNom()); sallesDTO.add(s); } return sallesDTO; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.barban.corentin.technicoCommercial.repositories; import com.barban.corentin.technicoCommercial.entities.Formationcatalogue; import java.util.List; import javax.ejb.Local; /** * * @author Corentin */ @Local public interface FormationcatalogueFacadeLocal { Formationcatalogue create(Formationcatalogue formationcatalogue); void edit(Formationcatalogue formationcatalogue); void remove(Formationcatalogue formationcatalogue); Formationcatalogue find(Object id); List<Formationcatalogue> findAll(); List<Formationcatalogue> findRange(int[] range); int count(); Formationcatalogue findByCode(String code); } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.barban.corentin.formation.services; import javax.ejb.EJB; import javax.ejb.Stateless; import com.barban.corentin.formation.business.GestionFormationLocal; /** * * @author Corentin */ @Stateless public class ServiceFormation implements ServiceFormationLocal { @EJB private GestionFormationLocal gestionFormation; /** * Demander l'état d'une formation * @param idFormation id de la formation * @return l'état d'une formation */ @Override public String demanderEtatFormation(Integer idFormation) { return this.gestionFormation.demanderEtatFormation(idFormation); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.barban.corentin.commercial.services; import DTO.CompteRenduDTO; import Exceptions.FormationCatalogueNotFoundException; import java.util.Date; import java.util.List; import javax.ejb.Local; /** * * @author Corentin */ @Local public interface serviceGestionCommercialeLocal { void demanderFormation(String nomClient,String codeFormation, String intitule ,Integer codeclient,Integer nbPersonnes) throws FormationCatalogueNotFoundException; void demandeEditionComptesRendus(); } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.barban.corentin.patrimoine.repositories; import com.barban.corentin.patrimoine.entities.Salle; import java.util.List; import javax.ejb.Local; /** * * @author Corentin */ @Local public interface SalleFacadeLocal { Salle create(Salle salle); void edit(Salle salle); void remove(Salle salle); Salle find(Object id); List<Salle> findAll(); List<Salle> findRange(int[] range); int count(); } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.barban.corentin.RH.entities; import java.io.Serializable; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Embeddable; import javax.validation.constraints.NotNull; /** * * @author Corentin */ @Embeddable public class CalendrierFormateurPK implements Serializable { @Basic(optional = false) @NotNull @Column(name = "CALENDRIERKEY") private int calendrierkey; @Basic(optional = false) @NotNull @Column(name = "FORMATEURKEY") private int formateurkey; public CalendrierFormateurPK() { } /** * constrcuteur calendrier formateur pk en focntion de calendrier key et formateur key * @param calendrierkey calendrier key * @param formateurkey formateur key */ public CalendrierFormateurPK(int calendrierkey, int formateurkey) { this.calendrierkey = calendrierkey; this.formateurkey = formateurkey; } /** * get calendrier key * @return calendrier key */ public int getCalendrierkey() { return calendrierkey; } /** * set calendrier key * @param calendrierkey calendrier key */ public void setCalendrierkey(int calendrierkey) { this.calendrierkey = calendrierkey; } /** * get formateur key * @return formateur key */ public int getFormateurkey() { return formateurkey; } /** * set formateur key * @param formateurkey formateur key */ public void setFormateurkey(int formateurkey) { this.formateurkey = formateurkey; } @Override public int hashCode() { int hash = 0; hash += (int) calendrierkey; hash += (int) formateurkey; return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof CalendrierFormateurPK)) { return false; } CalendrierFormateurPK other = (CalendrierFormateurPK) object; if (this.calendrierkey != other.calendrierkey) { return false; } if (this.formateurkey != other.formateurkey) { return false; } return true; } @Override public String toString() { return "com.barban.corentin.RH.entities.CalendrierFormateurPK[ calendrierkey=" + calendrierkey + ", formateurkey=" + formateurkey + " ]"; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.barban.corentin.formation.entities; import java.io.Serializable; import java.util.Collection; import java.util.Date; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; /** * * @author Corentin */ @Entity @Table(name = "STOCKAGEDEMANDEFORMATION") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Stockagedemandeformation.findAll", query = "SELECT s FROM Stockagedemandeformation s") , @NamedQuery(name = "Stockagedemandeformation.findByIddemandeformation", query = "SELECT s FROM Stockagedemandeformation s WHERE s.iddemandeformation = :iddemandeformation") , @NamedQuery(name = "Stockagedemandeformation.findByDatedemandeformation", query = "SELECT s FROM Stockagedemandeformation s WHERE s.datedemandeformation = :datedemandeformation") , @NamedQuery(name = "Stockagedemandeformation.findByCodeformationcatalogue", query = "SELECT s FROM Stockagedemandeformation s WHERE s.codeformationcatalogue = :codeformationcatalogue") , @NamedQuery(name = "Stockagedemandeformation.findByIntituleformation", query = "SELECT s FROM Stockagedemandeformation s WHERE s.intituleformation = :intituleformation") , @NamedQuery(name = "Stockagedemandeformation.findByCodeclient", query = "SELECT s FROM Stockagedemandeformation s WHERE s.codeclient = :codeclient") , @NamedQuery(name = "Stockagedemandeformation.findByNbpersonne", query = "SELECT s FROM Stockagedemandeformation s WHERE s.nbpersonne = :nbpersonne") , @NamedQuery(name = "Stockagedemandeformation.findByNomclient", query = "SELECT s FROM Stockagedemandeformation s WHERE s.nomclient = :nomclient")}) public class Stockagedemandeformation implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "IDDEMANDEFORMATION") private Integer iddemandeformation; @Column(name = "DATEDEMANDEFORMATION") @Temporal(TemporalType.DATE) private Date datedemandeformation; @Size(max = 100) @Column(name = "CODEFORMATIONCATALOGUE") private String codeformationcatalogue; @Size(max = 255) @Column(name = "INTITULEFORMATION") private String intituleformation; @Column(name = "CODECLIENT") private Integer codeclient; @Column(name = "NBPERSONNE") private Integer nbpersonne; @Size(max = 100) @Column(name = "NOMCLIENT") private String nomclient; @OneToMany(cascade = CascadeType.ALL, mappedBy = "stockagedemandeformation") private Collection<Formationcompose> formationcomposeCollection; public Stockagedemandeformation() { } /** * Constructeur sockage demande formation à partir de l'id demande formation * @param iddemandeformation id demande formation */ public Stockagedemandeformation(Integer iddemandeformation) { this.iddemandeformation = iddemandeformation; } /** * get Id demande formation * * @return id demande formation */ public Integer getIddemandeformation() { return iddemandeformation; } /** * Set id demande formation * * @param iddemandeformation id demande formation */ public void setIddemandeformation(Integer iddemandeformation) { this.iddemandeformation = iddemandeformation; } /** * get date demande formation * * @return date demande formation */ public Date getDatedemandeformation() { return datedemandeformation; } /** * set date demande formation * * @param datedemandeformation date demande formation */ public void setDatedemandeformation(Date datedemandeformation) { this.datedemandeformation = datedemandeformation; } /** * get Code formation catalogue * * @return Code formation catalogue */ public String getCodeformationcatalogue() { return codeformationcatalogue; } /** * set code formation catalogue * * @param codeformationcatalogue Code formation catalogue */ public void setCodeformationcatalogue(String codeformationcatalogue) { this.codeformationcatalogue = codeformationcatalogue; } /** * get l intitule de la formation * * @return l intitule de la formation */ public String getIntituleformation() { return intituleformation; } /** * set l'intitule de la formation * @param intituleformation l intitule de la formation */ public void setIntituleformation(String intituleformation) { this.intituleformation = intituleformation; } /** * get le code client * @return code client */ public Integer getCodeclient() { return codeclient; } /** * set le code client * @param codeclient code client */ public void setCodeclient(Integer codeclient) { this.codeclient = codeclient; } /** * get le nombre de personne dans la formation * @return le nombre de personne dans la formation */ public Integer getNbpersonne() { return nbpersonne; } /** * set le nombre de personne dans la formation * @param nbpersonne le nombre de personne dans la formation */ public void setNbpersonne(Integer nbpersonne) { this.nbpersonne = nbpersonne; } /** * get le nom du client * @return le nom du client */ public String getNomclient() { return nomclient; } /** * set le nom du client * @param nomclient le nom du client */ public void setNomclient(String nomclient) { this.nomclient = nomclient; } @XmlTransient /** * get Formation compose collection */ public Collection<Formationcompose> getFormationcomposeCollection() { return formationcomposeCollection; } /** * set formation compte collection * @param formationcomposeCollection formation compte collection */ public void setFormationcomposeCollection(Collection<Formationcompose> formationcomposeCollection) { this.formationcomposeCollection = formationcomposeCollection; } @Override public int hashCode() { int hash = 0; hash += (iddemandeformation != null ? iddemandeformation.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Stockagedemandeformation)) { return false; } Stockagedemandeformation other = (Stockagedemandeformation) object; if ((this.iddemandeformation == null && other.iddemandeformation != null) || (this.iddemandeformation != null && !this.iddemandeformation.equals(other.iddemandeformation))) { return false; } return true; } @Override public String toString() { return "com.barban.corentin.formation.entities.Stockagedemandeformation[ iddemandeformation=" + iddemandeformation + " ]"; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.barban.corentin.technicocommercial.rest; import Exceptions.FormateurNotFoundException; import Exceptions.FormationCatalogueNotFoundException; import Exceptions.LienFormateurFormationException; import com.barban.corentin.technicoCommercial.services.ServiceTechnicoCommercialLocal; import com.google.gson.Gson; import java.util.logging.Level; import java.util.logging.Logger; import javax.ws.rs.core.Context; import javax.ws.rs.core.UriInfo; import javax.ws.rs.Consumes; import javax.ws.rs.Produces; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PUT; import javax.enterprise.context.RequestScoped; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.ws.rs.DELETE; import javax.ws.rs.POST; import javax.ws.rs.PathParam; import javax.ws.rs.core.MediaType; /** * REST Web Service * * @author jdetr */ @Path("formationsCatalogue/{code}/formateur/{formateurkey}") @RequestScoped public class FormationCatalogueFormateurResource { ServiceTechnicoCommercialLocal serviceTC = lookupServiceTechnicoCommercialLocal(); @Context private UriInfo context; private Gson gson; /** * Creates a new instance of FormationCatalogueFormateurResourceResource */ public FormationCatalogueFormateurResource() { this.gson = new Gson(); } /** * Retrieves representation of an instance of com.barban.corentin.technicocommercial.rest.FormationCatalogueFormateurResource * @param code code * @param formateurkey formateur key * @return an instance of java.lang.String * @throws Exceptions.FormationCatalogueNotFoundException formateur catalogue non trouvé * @throws Exceptions.FormateurNotFoundException formateur non trouvé * @throws Exceptions.LienFormateurFormationException lien formateur formation non trouvé */ @POST @Produces(MediaType.APPLICATION_JSON) public boolean postJson(@PathParam("code") String code, @PathParam("formateurkey") int formateurkey) throws FormationCatalogueNotFoundException, FormateurNotFoundException, LienFormateurFormationException { return this.serviceTC.ajouterFormateurDansFormation(code, formateurkey); } /** * Delete JSON * @param code code * @param formateurkey key formateur * @return true si bien supprimé * @throws FormationCatalogueNotFoundException formation catalogue non trouvé * @throws FormateurNotFoundException formateur non trouvé * @throws LienFormateurFormationException lien formateur formation non trouvé */ @DELETE @Produces(MediaType.APPLICATION_JSON) public boolean deleteJson(@PathParam("code") String code, @PathParam("formateurkey") int formateurkey) throws FormationCatalogueNotFoundException, FormateurNotFoundException, LienFormateurFormationException { return this.serviceTC.supprimerFormateurDeFormation(code, formateurkey); } /** * PUT method for updating or creating an instance of FormationCatalogueFormateurResource * @param content representation for the resource */ @PUT @Consumes(MediaType.APPLICATION_JSON) public void putJson(String content) { } private ServiceTechnicoCommercialLocal lookupServiceTechnicoCommercialLocal() { try { javax.naming.Context c = new InitialContext(); return (ServiceTechnicoCommercialLocal) c.lookup("java:global/MIAGETechnicoCommercial-ear/MIAGETechnicoCommercial-ejb-1.0-SNAPSHOT/ServiceTechnicoCommercial!com.barban.corentin.technicoCommercial.services.ServiceTechnicoCommercialLocal"); } catch (NamingException ne) { Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne); throw new RuntimeException(ne); } } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.barban.corentin.patrimoine.entities; import java.io.Serializable; import java.util.Collection; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; /** * * @author Corentin */ @Entity @Table(name = "SALLE") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Salle.findAll", query = "SELECT s FROM Salle s") , @NamedQuery(name = "Salle.findByIdsalle", query = "SELECT s FROM Salle s WHERE s.idsalle = :idsalle") , @NamedQuery(name = "Salle.findByNom", query = "SELECT s FROM Salle s WHERE s.nom = :nom")}) public class Salle implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "IDSALLE") private Integer idsalle; @Size(max = 50) @Column(name = "NOM") private String nom; @JoinTable(name = "SALLE_EQUIPEMENT", joinColumns = { @JoinColumn(name = "SALLEKEY", referencedColumnName = "IDSALLE")}, inverseJoinColumns = { @JoinColumn(name = "EQUIPEMENTKEY", referencedColumnName = "IDEQUIPEMENT")}) @ManyToMany private Collection<Equipement> equipementCollection; @OneToMany(cascade = CascadeType.ALL, mappedBy = "salle") private Collection<CalendrierSalle> calendrierSalleCollection; public Salle() { } /** * constructeur de la salle à partir de son id * @param idsalle id de la salle */ public Salle(Integer idsalle) { this.idsalle = idsalle; } /** * get id salle * @return id de la salle */ public Integer getIdsalle() { return idsalle; } /** * set id salle * @param idsalle id de la salle */ public void setIdsalle(Integer idsalle) { this.idsalle = idsalle; } /** * get nom * @return nom */ public String getNom() { return nom; } /** * set nom * @param nom nom */ public void setNom(String nom) { this.nom = nom; } /** * get les équipements de la salle * @return les équipements de la salle */ @XmlTransient public Collection<Equipement> getEquipementCollection() { return equipementCollection; } /** * set les équipements de la salle * @param equipementCollection les équipements de la salle */ public void setEquipementCollection(Collection<Equipement> equipementCollection) { this.equipementCollection = equipementCollection; } /** * get les calendriers de la salle * @return les calendriers de la salle */ @XmlTransient public Collection<CalendrierSalle> getCalendrierSalleCollection() { return calendrierSalleCollection; } /** * set les calendriers de la salle * @param calendrierSalleCollection les calendriers de la salle */ public void setCalendrierSalleCollection(Collection<CalendrierSalle> calendrierSalleCollection) { this.calendrierSalleCollection = calendrierSalleCollection; } @Override public int hashCode() { int hash = 0; hash += (idsalle != null ? idsalle.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Salle)) { return false; } Salle other = (Salle) object; if ((this.idsalle == null && other.idsalle != null) || (this.idsalle != null && !this.idsalle.equals(other.idsalle))) { return false; } return true; } @Override public String toString() { return "com.barban.corentin.patrimoine.entities.Salle[ idsalle=" + idsalle + " ]"; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.barban.corentin.RH.entities; import java.io.Serializable; import java.util.Collection; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; /** * * @author Corentin */ @Entity @Table(name = "FORMATEUR") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Formateur.findAll", query = "SELECT f FROM Formateur f") , @NamedQuery(name = "Formateur.findByIdformateur", query = "SELECT f FROM Formateur f WHERE f.idformateur = :idformateur") , @NamedQuery(name = "Formateur.findByNom", query = "SELECT f FROM Formateur f WHERE f.nom = :nom") , @NamedQuery(name = "Formateur.findByPrenom", query = "SELECT f FROM Formateur f WHERE f.prenom = :prenom")}) public class Formateur implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "IDFORMATEUR") private Integer idformateur; @Size(max = 100) @Column(name = "NOM") private String nom; @Size(max = 100) @Column(name = "PRENOM") private String prenom; @JoinTable(name = "COMPETENCE_FORMATEUR", joinColumns = { @JoinColumn(name = "FORMATEURKEY", referencedColumnName = "IDFORMATEUR")}, inverseJoinColumns = { @JoinColumn(name = "COMPETENCEKEY", referencedColumnName = "IDCOMPETENCE")}) @ManyToMany private Collection<Competence> competenceCollection; @OneToMany(cascade = CascadeType.ALL, mappedBy = "formateur") private Collection<CalendrierFormateur> calendrierFormateurCollection; public Formateur() { } /** * constructeur formateur à partir de son id * @param idformateur id formateur */ public Formateur(Integer idformateur) { this.idformateur = idformateur; } /** * get id formateur * @return id formateur */ public Integer getIdformateur() { return idformateur; } /** * set id formateur * @param idformateur id formateur */ public void setIdformateur(Integer idformateur) { this.idformateur = idformateur; } /** * get nom formateur * @return nom formateur */ public String getNom() { return nom; } /** * set nom formateur * @param nom nom formateur */ public void setNom(String nom) { this.nom = nom; } /** * get prenom formateur * @return prenom formateur */ public String getPrenom() { return prenom; } /** * set prenom formateur * @param prenom prenom formateur */ public void setPrenom(String prenom) { this.prenom = prenom; } /** * get la liste des competences * @return liste des competences */ @XmlTransient public Collection<Competence> getCompetenceCollection() { return competenceCollection; } /** * set la liste des competences * @param competenceCollection liste des competences */ public void setCompetenceCollection(Collection<Competence> competenceCollection) { this.competenceCollection = competenceCollection; } /** * get la collection de calendrier formateur * @return la collection de calendrier formateur */ @XmlTransient public Collection<CalendrierFormateur> getCalendrierFormateurCollection() { return calendrierFormateurCollection; } public void setCalendrierFormateurCollection(Collection<CalendrierFormateur> calendrierFormateurCollection) { this.calendrierFormateurCollection = calendrierFormateurCollection; } @Override public int hashCode() { int hash = 0; hash += (idformateur != null ? idformateur.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Formateur)) { return false; } Formateur other = (Formateur) object; if ((this.idformateur == null && other.idformateur != null) || (this.idformateur != null && !this.idformateur.equals(other.idformateur))) { return false; } return true; } @Override public String toString() { return "com.barban.corentin.RH.entities.Formateur[ idformateur=" + idformateur + " ]"; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.barban.corentin.formation.listenner; import DTO.FormationDTO; import com.barban.corentin.formation.entities.Formation; import java.util.logging.Level; import java.util.logging.Logger; import javax.ejb.ActivationConfigProperty; import javax.ejb.EJB; import javax.ejb.MessageDriven; import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.DeliveryMode; import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.MessageProducer; import javax.jms.ObjectMessage; import javax.jms.Session; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import com.barban.corentin.formation.business.GestionFormationLocal; import com.barban.corentin.formation.entities.Formationcompose; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * * @author Corentin */ @MessageDriven(activationConfig = { @ActivationConfigProperty(propertyName = "destinationLookup", propertyValue = "QUEUE_COMPTE_RENDU_DEMANDE") , @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue") }) public class ListennerDemandeCompteRendu implements MessageListener { @EJB private GestionFormationLocal gestionFormation; Context context = null; ConnectionFactory factory = null; Connection connection = null; String factoryName = "ConnectionFactory"; String destName = "QUEUE_FORMATION_DEMANDEE"; Destination dest = null; Session session = null; MessageProducer replyProducer = null; public ListennerDemandeCompteRendu() { this.setupMessageQueueConsumer(); } /** * Mise en place d'une file temporaire pour les retours d'informations */ private void setupMessageQueueConsumer() { try { this.context = new InitialContext(); this.factory = (ConnectionFactory) context.lookup(factoryName); this.dest = (Destination) context.lookup(destName); this.connection = factory.createConnection(); this.connection.start(); this.session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); this.replyProducer = this.session.createProducer(null); this.replyProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); } catch (NamingException ex) { Logger.getLogger(ListennerDemandeCompteRendu.class.getName()).log(Level.SEVERE, null, ex); } catch (JMSException ex) { Logger.getLogger(ListennerDemandeCompteRendu.class.getName()).log(Level.SEVERE, null, ex); } } /** * Attente de l'arrivé d'un message Gestion de la demande avec les * formations deja existantes * * @param message message */ @Override public void onMessage(Message message) { try { List<FormationDTO> listeFormationDTO = new ArrayList(); List<Formation> listFormations = this.gestionFormation.recupererInformationFormation(); for (Formation formation : listFormations) { FormationDTO f = new FormationDTO(); f.setDateformation(formation.getDateformation()); f.setDateDemandeformation(formation.getFormationcomposeCollection().iterator().next().getStockagedemandeformation().getDatedemandeformation()); int nbPersonnes = 0; List<String> listeClient = new ArrayList(); for (Formationcompose formationcompose : formation.getFormationcomposeCollection()) { nbPersonnes += formationcompose.getNbparticipants(); if (!listeClient.contains(formationcompose.getStockagedemandeformation().getNomclient())) { listeClient.add(formationcompose.getStockagedemandeformation().getNomclient()); } } f.setListeClient(listeClient); f.setStatut(formation.getStatut()); f.setNbpersonne(nbPersonnes); f.setCode(formation.getFormationcomposeCollection().iterator().next().getStockagedemandeformation().getCodeformationcatalogue()); listeFormationDTO.add(f); } ObjectMessage messageCompterendu = session.createObjectMessage((Serializable) listeFormationDTO); messageCompterendu.setJMSCorrelationID(message.getJMSCorrelationID()); this.replyProducer.send(message.getJMSReplyTo(), messageCompterendu); } catch (JMSException e) { Logger.getLogger(ListennerDemandeCompteRendu.class.getName()).log(Level.SEVERE, null, e); } } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.barban.corentin.commercial.rest; import com.barban.corentin.commercial.services.serviceGestionCommercialeLocal; import com.google.gson.Gson; import java.util.logging.Level; import java.util.logging.Logger; import javax.ws.rs.core.Context; import javax.ws.rs.core.UriInfo; import javax.ws.rs.Produces; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PUT; import javax.enterprise.context.RequestScoped; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.ws.rs.core.MediaType; /** * REST Web Service * * @author Corentin */ @Path("comptesRendus") @RequestScoped public class ComptesRendusResource { serviceGestionCommercialeLocal serviceGestionCommerciale = lookupserviceGestionCommercialeLocal(); @Context private UriInfo context; private Gson gson; /** * Creates a new instance of ComptesRendusResource */ public ComptesRendusResource() { this.gson = new Gson(); } /** * Retrieves representation of an instance of * com.barban.corentin.commercial.rest.ComptesRendusResource * */ @GET @Produces(MediaType.APPLICATION_JSON) public void getJson() { this.serviceGestionCommerciale.demandeEditionComptesRendus(); } /** * PUT method for updating or creating an instance of ComptesRendusResource * * @param content representation for the resource */ @PUT @Consumes(MediaType.APPLICATION_JSON) public void putJson(String content) { } /** * Cherche la gestion commerciale local * @return la gestion commerciale local */ private serviceGestionCommercialeLocal lookupserviceGestionCommercialeLocal() { try { javax.naming.Context c = new InitialContext(); return (serviceGestionCommercialeLocal) c.lookup("java:global/MIAGECommercial-ear/MIAGECommercial-ejb-1.0-SNAPSHOT/serviceGestionCommerciale"); } catch (NamingException ne) { Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne); throw new RuntimeException(ne); } } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.barban.corentin.technicoCommercial.repositories; import com.barban.corentin.technicoCommercial.entities.Salleadequate; import java.util.List; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; /** * * @author Corentin */ @Stateless public class SalleadequateFacade extends AbstractFacade<Salleadequate> implements SalleadequateFacadeLocal { @PersistenceContext(unitName = "com.barban.corentin_MIAGETechnicoCommercial-ejb_ejb_1.0-SNAPSHOTPU") private EntityManager em; @Override protected EntityManager getEntityManager() { return em; } public SalleadequateFacade() { super(Salleadequate.class); } @Override public Salleadequate findByKey(Integer salleKey) { Salleadequate result = null; List<Salleadequate> salleadequate = em.createNamedQuery("Salleadequate.findBySallekey") .setParameter("sallekey", salleKey).getResultList(); if (!salleadequate.isEmpty()) { result = salleadequate.get(0); } return result; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.barban.corentin.RH.business; import DTO.FormateurDTO; import Exceptions.FormateurNotFoundException; import com.barban.corentin.RH.entities.Formateur; import java.util.Date; import java.util.HashMap; import java.util.List; import javax.ejb.Local; /** * * @author Julie */ @Local public interface gestionRHLocal { void modifierStatutFormateur(Integer idFormateur, String statut, Date date) throws FormateurNotFoundException; HashMap<FormateurDTO, List<Date>> fournirPlanningFormateur(List<FormateurDTO> listFormateurDemandees); boolean verifierExistenceFormateur(Integer idFormateur); List<FormateurDTO> listerFormateurs(); } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.barban.corentin.technicoCommercial.repositories; import com.barban.corentin.technicoCommercial.entities.Formationcatalogue; import java.util.List; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; /** * * @author Corentin */ @Stateless public class FormationcatalogueFacade extends AbstractFacade<Formationcatalogue> implements FormationcatalogueFacadeLocal { @PersistenceContext(unitName = "com.barban.corentin_MIAGETechnicoCommercial-ejb_ejb_1.0-SNAPSHOTPU") private EntityManager em; @Override protected EntityManager getEntityManager() { return em; } public FormationcatalogueFacade() { super(Formationcatalogue.class); } @Override public Formationcatalogue findByCode(String code) { Formationcatalogue result = null; List<Formationcatalogue> formationCatalogue = em.createNamedQuery("Formationcatalogue.findByCode") .setParameter("code", code).getResultList(); if (!formationCatalogue.isEmpty()) { result = formationCatalogue.get(0); } return result; } }
a65cb863ae1bb6f2e70875a21b9985969fe86426
[ "Java" ]
22
Java
CorentinBarban/MIAGEFormation
4836b2e95eac5e87a4135f90d4e95c052af2434e
c89e81445ca76b5958c4ea67b15d6dae70156ea4