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>PierreThiollent/Jeu-du-pendu<file_sep>/src/App/App.js import React, {Component} from 'react'; import './App.css'; import logo from '../logo.svg'; import Letter from '../Letter/Letter.js' import Keyboard from '../Keyboard/Keyboard.js' import Counter from '../Counter/Counter.js' const alphabet = "abcdefghijklmnopqrstuvwxyz"; const words = ["joystick", "false", "vegetarian", "organisation", "tenant", "fascinate", "soft", "neighborhood", "goat", "straw", "sin", "monster", "loot", "pierce", "area", "applied", "honest", "panic", "tap", "tasty"]; class App extends Component { state = { letters: App.generateWords(), keyboard: App.generateKeyboard(), selection: [], gameState: "En cours", }; static generateWords() { const result = []; let oneWord = Math.floor(Math.random() * words.length); oneWord = words[oneWord] const word = oneWord.split(''); while (word.length > 0) { const letter = word.shift(); result.push(letter) } return result } static generateKeyboard() { const result = []; const size = 26; const allLetters = alphabet.split(''); while (result.length < size) { const letter = allLetters.shift(); result.push(letter) } return result } getFeedback(letter) { const {selection} = this.state; return selection.includes(letter) } handleClick = (letter) => { const {selection, gameState} = this.state; if (gameState === "En cours") { this.setState({selection: [...selection, letter]}, this.gameState) } }; newGame = () => { this.setState({selection: [], letters: App.generateWords(), gameState: "En cours"}) }; trying = () => { const {letters, selection} = this.state; return selection.filter(el => !letters.includes(el)).length }; gameState = () => { const {letters, selection} = this.state; const lastTests = 10 - this.trying(); const findWord = letters.filter(elt => selection.includes(elt)).length === letters.length; if (lastTests > 0 && findWord) { this.setState({gameState: "Gagnée"}) } else if (lastTests > 0) { } else { this.setState({gameState: "Perdue"}) } }; render() { const {letters, keyboard} = this.state; return ( <div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo"/> <p>Application créée avec <a className="App-link" href="https://reactjs.org" target="_blank" rel="noopener noreferrer">React</a> </p> </header> <div className="header"> <h1 className="title">Jeu du pendu</h1> <button className="btn" onClick={this.newGame}>Nouvelle partie</button> </div> <div className="game"> <div className="content"> {letters.map((letter, index) => ( <Letter letter={letter} feedback={this.getFeedback(letter) ? "visible" : "hidden"} key={index} /> ))} </div> <Counter counter={this.trying()} gameState={this.state.gameState}/> </div> <div className="keyboard"> {keyboard.map((letter, index) => ( <Keyboard letter={letter} key={index} onClick={this.handleClick} feedback={this.getFeedback(letter) ? "gray" : "#282c34"} /> ))} </div> </div> ) } } export default App; <file_sep>/README.md # Jeu du pendu Ce projet est un exercice sur le Framework React JS. ## Getting started Cette application à été créée à l'aide de [create-react-native-app](https://github.com/react-community/create-react-native-app) ### Pré-requis Installer create-react-app à l'aide de cette commande : ```sh $ npm install -g create-react-app ``` ### Installation Télécharger le projet et lancer le serveur node : ```sh $ git clone https://github.com/PierreThiollent/Jeu-du-pendu.git $ cd Jeu-du-pendu $ npm start ```
c4a268d6b0a3f7a72c0745fcb0d0ca50af15a0bc
[ "JavaScript", "Markdown" ]
2
JavaScript
PierreThiollent/Jeu-du-pendu
5afe9a5edf6453c8d5c61ad235608b69316c3a8c
93bb60f165c3c17d955371d9c0a2f2c1d03f9185
refs/heads/master
<repo_name>punkhaa/syd<file_sep>/project/script.js var bandListing = angular.module('bandListing', ['ui.router', 'ngStorage']); bandListing.controller('bandListController', function ($scope, $localStorage, $state, $rootScope) { $localStorage.state = 'home'; var b="hello world"; $rootScope.stage='main'; $scope.bands = [{ "name": "<NAME>", "members": ["David", "richard", "Wright", "syd", "mason"], "albums": ["dark side of the moon", "animals", "the wall", "division bell"], "yearStart": 1967, "yearEnd": 2015, "wiki": "https://en.wikipedia.org/wiki/Pink_Floyd" }, { "name": "<NAME>", "members": ["wilson", "harrison", "richard", "colin"], "albums": ["deadwing", "in absentia", "signify", "the incident"], "yearStart": 1990, "yearEnd": 2010, "wiki": "https://en.wikipedia.org/wiki/Porcupine_Tree" }, { "name": "Radiohead", "members": ["Thom", "jonny", "colin", "phil", "Ed"], "albums": ["pablo honey", "the bends", "ok computer", "kid a"], "yearStart": 1990, "yearEnd": 2023, "wiki": "https://en.wikipedia.org/wiki/Radiohead" }, { "name": "TOOL", "megmbers": ["maynard", "adam", "danny", "adam", "paul"], "albums": ["aenema", "lateralus", "undertow", "10000 days"], "yearStart": 1967, "yearEnd": 2015, "wiki": "https://en.wikipedia.org/wiki/Tool_(band)" }, { "name": "Rapture", "members": ["petri", "tomi", "ahokas", "huntely", "pete"], "albums": ["songs for the withering", "silent stage", "futile"], "yearStart": 1995, "yearEnd": 2034, "wiki": "https://en.wikipedia.org/wiki/Rapture_(band)" }]; $scope.myfunction = function (data) { //console.log($rootScope.stage); $scope.details = data; $state.go('index1.child1') }; $scope.setDefault= function() { //console.log($rootScope.stage); $rootScope.stage='main'; $state.go('index1'); }; $scope.destroyScope= function() { //console.log($scope); /* scope=angular.element(document.getElementsByTagName('body')[0]).scope()*/ $scope.$destroy(); //console.log($scope); }; $scope.$on('wikilink',function(event){ console.log('1212121'); }); /*$rootScope.$on('$stateChangeStart',function(e,toState,toParams,fromState,fromParams,options){ console.log("index1 to index1.child1 state change starting"); }) $rootScope.$on('$stateChangeSuccess',function(e,toState,toParams,fromState,fromParams,options){ console.log("state is now index1.child1"); }) $rootScope.$on('$viewContentLoading',function(event,config){ console.log('started index1...') }) $rootScope.$on('$viewContentLoaded',function(event){ console.log('loaded index1...') })*/ }) bandListing.controller('dirAnimation',function($scope,$state){ $scope.$on('changeAnim',function(){ console.log('broadcast catched'); $state.go('index1.child1'); }) console.log($state); }).directive('animDiv',function(){ return{ restrict:'A', templateUrl:'directive.html', scope:{ width:'@containerWidth', height:'@containerHeight', border:'@containerBorder' }, link:function(scope,el,attr){ console.log(el,attr); el[0].style.width=scope.width; el[0].style.height=scope.height; el[0].style.border=scope.border; el[0].style.transition="all 300ms ease"; } }; }) bandListing.config(function ($stateProvider) { $stateProvider.state('index1', { templateUrl: 'template.html', controller:'bandListController', onEnter:function(){ console.log( 'welcome to state 1'); }, onExit: function () { console.log('state change from index1') } }).state('index1.child1',{ templateUrl:'temp1.html', onEnter:function(){ console.log('hey we are inside index1.child') }, onExit: function () { console.log('state changed from index1.child1'); }, controller: function ($rootScope,$scope,$state) { var parent=$scope; /*var kid=parent.$new(); console.log(kid,"new kid in the town");*/ $rootScope.stage='subMain'; console.log($scope); $scope.destroyChildScope=function(){ console.log('lmao ahahah') } $scope.performThis=function(){ console.log(323232); $scope.$emit('wikilink'); } $rootScope.$on('$viewContentLoading',function(event,config){ console.log('started index1.child1...') }) $rootScope.$on('$viewContentLoaded',function(event){ console.log('loaded index1.child1...') }) $scope.animation=function(){ console.log('here is parent scope'); $state.go('index1.child1.dir'); $scope.$broadcast('changeAnim'); } }, controllerAs:'bandDet' }).state('index1.child1.dir',{ name:'aniamtion', templateUrl:'temp2.html', controller:'dirAnimation' }) }) bandListing.run(function($state){ $state.go('index1'); }); <file_sep>/project/temp1.html <div class="containerGreen"> <div class="header"> <h3>{{details.bandname}}</h3> <p>{{details.yearStart}}</p> <p>{{details.yearEnd}}</p> </div> <div class="jumbo"> <p>Members</p> <ul ng-repeat="member in details.members track by $index"> <li>{{$index}}:---{{member}}</li> </ul> <p>Albums</p> <ul ng-repeat="album in details.albums"> <li> {{album}} </li> </ul> <a ng-href="javascript:void(0)" ng-click="performThis($event)">wiki page--{{details.wiki}}</a> </div> <div ng-click="destroyChildScope()"> <h2>kill this</h2> </div> <a ng-click="animation()">click me for animation</a> <div ui-view> </div> </div> <ul> <li>this is item 01</li> <li>this is item 02</li> <li>this is item 03</li> <li>this is item 04</li> <li>this is item 05</li> <li>this is item 06</li> <li>this is item 07</li> <li>this is item 08</li> <li>this is item 09</li> <li>this is item 10</li> <li>this is item 11</li> <li>this is item 12</li> <li>this is item 13</li> <li>this is item 14</li> <li>this is item 15</li> <li>this is item 16</li> <li>this is item 17</li> <li>this is item 18</li> <li>this is item 19</li> <li>this is item 20</li> <li>this is item 21</li> <li>this is item 22</li> <li>this is item 23</li> <li>this is item 24</li> <li>this is item 25</li> <li>this is item 26</li> <li>this is item 27</li> <li>this is item 28</li> <li>this is item 29</li> <li>this is item 30</li> <li>this is item 31</li> <li>this is item 32</li> <li>this is item 33</li> <li>this is item 34</li> <li>this is item 35</li> <li>this is item 36</li> <li>this is item 37</li> <li>this is item 38</li> <li>this is item 39</li> <li>this is item 40</li> <li>this is item 41</li> <li>this is item 42</li> <li>this is item 43</li> <li>this is item 44</li> <li>this is item 45</li> <li>this is item 46</li> <li>this is item 47</li> <li>this is item 48</li> <li>this is item 49</li> <li>this is item 50</li> </ul>
04d49a3190a5a41b8e5442c1e3fdd24fe797ae31
[ "JavaScript", "HTML" ]
2
JavaScript
punkhaa/syd
38cf48459fa62be55c1c428fad2cec2db46eee90
6ae860e5eee1e2a78c6859cfcc74b499b681014f
refs/heads/master
<repo_name>GuruVcomputers/my_web-<file_sep>/src/main/java/com/ptitsyn/alexey/my_web/Pc.java package com.ptitsyn.alexey.my_web; public class Pc { private int Number_Kab; private String Name_Pc; public String getName_pc() { return Name_Pc; } public void setName_pc(String name_pc) { this.Name_Pc = name_pc; } public int getNumber_kab() { return Number_Kab; } public void setNumber_kab(int number_kab) { this.Number_Kab = number_kab; } }
b71d629c072f47b37e89059cc4d55613ba532083
[ "Java" ]
1
Java
GuruVcomputers/my_web-
c8c5654227eea2fb45e0ecd621f677bf980f7405
3f15ac59eacba59f6057c1dd8e7e6a6cf20ac33d
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Threading.Tasks; using System.Net.Mail; using PhoneStore.Models; using System.Security.Policy; namespace PhoneStore.BL.Email { public static class EmailHelper { private const string fromAddress = "<EMAIL>"; private const string password = "<PASSWORD>"; private const string smtpServer = "smtp.gmail.com"; private const string server = "localhost:49742"; private static int port = 587; public async static Task SendMail(User user) { MailAddress from = new MailAddress(fromAddress, "Phone store registration"); MailAddress to = new MailAddress(user.Email); MailMessage m = new MailMessage(from, to); m.Subject = "Email confirmation"; m.Body = string.Format("Для завершения регистрации перейдите по ссылке:" + "<a href=\"{0}\"title=\"Подтвердить регистрацию\">{0}</a>", $"http://{server}/Account/ConfirmEmail?token=" + user.Cookie); m.IsBodyHtml = true; SmtpClient smtp = new SmtpClient(smtpServer, port); smtp.UseDefaultCredentials = true; smtp.EnableSsl = true; smtp.Credentials = new System.Net.NetworkCredential(fromAddress, password); System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; await smtp.SendMailAsync(m); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using PhoneStore.Models; using PhoneStore.BL.Service; using PhoneStore.BL.Repository.EF; using PhoneStore.BL.Auth; using System.Net.Mail; using System.Threading.Tasks; using PhoneStore.BL.Email; using PhoneStore.Security; namespace PhoneStore.Controllers { public class AccountController : Controller { private IUserManager manager; private AuthHelper authHelper; public AccountController(IUserManager manager) { this.manager = manager; authHelper = new AuthHelper(manager); } // GET: Home [HttpGet] public ActionResult Login() { if (!authHelper.IsAuthenticated(HttpContext)) return View(); return RedirectToAction("Ads", "Home"); } [HttpPost] public ActionResult Login(Login login) { if (ModelState.IsValid) { login.Password = <PASSWORD>(login.Password); User currentUser = manager.GetUser(login); if (currentUser != null) { if (currentUser.IsActive == true) { authHelper.UserSetCookie(HttpContext, currentUser, Guid.NewGuid().ToString()); return RedirectToAction("Ads", "Home"); } else ModelState.AddModelError("", "Подтвердите регистрацию по email"); } else ModelState.AddModelError("", "Неверный логин или пароль"); } return View(); } [HttpGet] public ActionResult LogOff() { authHelper.LogOffUser(HttpContext); return RedirectToAction("Login"); } [HttpGet] public ActionResult Registration() { return View(); } [HttpPost] [AllowAnonymous] public async Task<ActionResult> Registration(User user) { if (ModelState.IsValid) { if (manager.IsAlreadyRegister(user)) { user.RegDate = DateTime.Now; user.Cookie = Guid.NewGuid().ToString(); user.IsActive = false; user.Password = <PASSWORD>(user.Password); manager.Add(user); try { await EmailHelper.SendMail(user); } catch (Exception) { throw; } return RedirectToAction("ResultRegister"); } else ModelState.AddModelError("", "Пользователь с таким e-mail уже существует"); } return View(); } [AllowAnonymous] public ActionResult ConfirmEmail(string token) { User currentUser = manager.GetUserByCookies(token); if (currentUser != null) { currentUser.IsActive = true; manager.UpdateIsActive(currentUser); return RedirectToAction("Login"); } return View(); } [HttpGet] public ActionResult ResultRegister() { return View(); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PhoneStore.Models { public interface IApplicationModel { } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using PhoneStore.Models; using PhoneStore.BL.Service; namespace PhoneStore.DAL.EF { public partial class UserEntity { public User ConvertToApplicationModel() { User user = new User() { UserId = this.UserId, FirstName = this.FirstName, LastName = this.LastName, Password = <PASSWORD>, Email = this.Email, ContactPhone = this.ContactPhone, IsActive = this.IsActive, Cookie = this.Cookie, RegDate = this.RegDate }; return user; } public IStorageModel<User> FromApplicationModel(User model) { if (model == null) return null; UserEntity userEntity = new UserEntity() { FirstName = model.FirstName, LastName = model.LastName, Password = <PASSWORD>, Email = model.Email, ContactPhone = model.ContactPhone, IsActive = model.IsActive, Cookie = model.Cookie, RegDate = model.RegDate }; return userEntity; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using PhoneStore.Models; namespace PhoneStore.UI.ViewModels { public class PhoneListViewModel { public IEnumerable<Phone> Phones { get; set; } public PagingInfo PagingInfo { get; set; } public Phone Phone { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using PhoneStore.Models; namespace PhoneStore.BL.Service { public interface IUserManager { void Add(User user); User GetUser(Login login); User GetUserByCookies(string cookie); void UpdateCookies(User user, string cookie); void UpdateIsActive(User user); bool IsAlreadyRegister(User user); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using StructureMap; using System.Web.Mvc; namespace PhoneStore.IoC { public class Bootstrapper { public static void ConfigureStructureMap(Action<ConfigurationExpression> configurationAction) { IContainer container = new Container(configurationAction); DependencyResolver.SetResolver(new StructureMapDependencyResolver(container)); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; using System.Net.Mail; namespace PhoneStore.Models { public class Login : IApplicationModel { [Required (ErrorMessage = "Email не заполнен")] [StringLength(25, MinimumLength = 5, ErrorMessage = "Email не менее 5 и не более 256 символов")] public string Email { get; set; } [Required (ErrorMessage = "Пароль не заполнен")] [StringLength(15, ErrorMessage = "Пароль не менее 5 и не более 15 символов ", MinimumLength = 5)] public string Password { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using StructureMap; using PhoneStore.BL.Repository; using PhoneStore.BL.Repository.EF; using PhoneStore.DAL.EF; using PhoneStore.BL.Service; using PhoneStore.BL.Service.Image; namespace PhoneStore.IoC { public class ConfigurationHelper { public static void ConfigureDependies(ConfigurationExpression temp) { temp.For<IUserRepository>().Use<EfUserRepository>(); temp.For<IUserManager>().Use<UserManager>(); temp.For<IPhoneManager>().Use<PhoneManager>(); temp.For<IPhoneRepository>().Use<EfPhoneRepository>(); temp.For<IImageRepository>().Use<EfImageRepository>(); temp.For<IImageManager>().Use<ImageManager>(); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; namespace PhoneStore.Models { public class User : IApplicationModel { public int UserId { get; set; } [Required(ErrorMessage = "Имя обязательно для заполнения")] public string FirstName { get; set; } [Required(ErrorMessage = "Фамилия обязательно для заполнения")] public string LastName { get; set; } [Required(ErrorMessage = "Пароль обязателен для заполнения")] [StringLength(15, MinimumLength = 5, ErrorMessage = "Пароль не менее 5 и не более 15 символов")] [DataType(DataType.Password)] public string Password { get; set; } [Compare("Password", ErrorMessage = "Пароли не совпадают")] [DataType(DataType.Password)] public string ConfirmPassword { get; set; } [Required(ErrorMessage = "Почта обязательная для заполнения")] [StringLength(25, MinimumLength = 5, ErrorMessage = "Электронный адрес не менее 5 и не более 256 символов")] [DataType(DataType.EmailAddress)] public string Email { get; set; } public string ContactPhone { get; set; } public DateTime RegDate { get; set; } public string Cookie { get; set; } public bool IsActive { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Security.Cryptography; using System.Text; namespace PhoneStore.BL.Security { public static class SecurityHelper { public static string GetHashSha256(string value) { byte[] byteResult = Encoding.UTF8.GetBytes(value); SHA256Managed hash = new SHA256Managed(); byte[] bytesHash = hash.ComputeHash(byteResult); StringBuilder builder = new StringBuilder(); foreach (byte x in bytesHash) { builder.Append(String.Format("{0:x2}", x)); } return builder.ToString(); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace PhoneStore.Models { public class ApplicationImage : IApplicationModel { public int ImageId { get; set; } public string Image { get; set; } public int PhoneId { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using PhoneStore.Models; using PhoneStore.BL.Repository; using PhoneStore.BL.Repository.EF; namespace PhoneStore.BL.Service.Image { public class ImageManager : IImageManager { private IImageRepository repository; public ImageManager(IImageRepository repository) { this.repository = repository; } public void Add(ApplicationImage image) { if (image == null) throw new ArgumentNullException(nameof(image)); repository.Add(image); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using PhoneStore.Models; namespace PhoneStore.BL.Service { public interface IStorageModel<T> where T : IApplicationModel { T ConvertToApplicationModel(); IStorageModel<T> FromApplicationModel(T model); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using PhoneStore.Models; namespace PhoneStore.BL.Repository { public interface IImageRepository { void Add(ApplicationImage image); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using PhoneStore.BL.Auth; using PhoneStore.Models; using PhoneStore.BL.Service; using PhoneStore.BL.Repository.EF; using PhoneStore.UI.ViewModels; using PhoneStore.UI; using System.IO; using PhoneStore.BL.Service.Image; namespace PhoneStore.Controllers { public class HomeController : Controller { private IUserManager userManager; private IPhoneManager phoneManager; private IImageManager imageManager; private AuthHelper authHelper; public int PageSize { get; set; } = 5; public HomeController(IUserManager userManager, IPhoneManager phoneManager, IImageManager imageManager) { this.userManager = userManager; this.phoneManager = phoneManager; this.imageManager = imageManager; authHelper = new AuthHelper(userManager); } [HttpGet] public ActionResult Ads(string filter = null, int page = 1) { if (authHelper.IsAuthenticated(HttpContext)) { if (filter == "") filter = null; PhoneListViewModel model = new PhoneListViewModel() { Phones = phoneManager.GetAllPhones() }; model.PagingInfo = new PagingInfo() { CurrentPage = page, PhoneCurrentPage = PageSize, TotalPhone = filter == null ? model.Phones.Count() : model.Phones.Where(e => e.Model.ToLower().Contains(filter.ToLower())).Count() }; model.Phones = model.Phones .Where(e => filter == null || e.Model.ToLower().Contains(filter.ToLower())) .OrderBy(e => e.PhoneId) .Skip((page - 1) * PageSize) .Take(PageSize); if (filter == null) return View(model); else return PartialView("_PartialAds", model); } else return RedirectToAction("Login", "Account"); } [HttpPost] public ActionResult Ads(Phone phone) { return RedirectToAction("AdsAdditional", phone); } [HttpGet] public ActionResult AdsAdditional(Phone phone) { if (authHelper.IsAuthenticated(HttpContext)) return View(phone); return RedirectToAction("Login", "Account"); } [HttpPost] public ActionResult AdsAdditional(Phone phone, HttpPostedFileBase image = null) { if (ModelState.IsValid) { User user = userManager.GetUserByCookies(HttpContext.Request.Cookies[Constants.NameCookie].Value); phone.UserId = user.UserId; phoneManager.Add(phone); if (image != null) { string fileName = Path.GetFileName(image.FileName); var path = Path.Combine(Server.MapPath("~/Images/"), fileName); image.SaveAs(path); ApplicationImage appImage = new ApplicationImage() { Image = Url.Content("~/Images/" + fileName), PhoneId = phoneManager.GetPhoneId(phone) }; imageManager.Add(appImage); } return RedirectToAction("AdResult", phone); } return View(phone); } [HttpGet] public ActionResult AdResult(Phone phone) { if (authHelper.IsAuthenticated(HttpContext)) { if (phone.Model == null) { return RedirectToAction("Ads"); } return View(phone); } return RedirectToAction("Login", "Account"); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using PhoneStore.Models; namespace PhoneStore.BL.Repository.EF { public interface IPhoneRepository { IEnumerable<Phone> GetAllPhones(); void Add(Phone phone); int GetPhoneId(Phone phone); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace PhoneStore { public static class Constants { public const string NameCookie = "auth"; } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using PhoneStore.Models; namespace PhoneStore.BL.Service.Image { public interface IImageManager { void Add(ApplicationImage image); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using PhoneStore.Models; using PhoneStore.DAL.EF; namespace PhoneStore.BL.Repository.EF { public class EfImageRepository : IImageRepository { public void Add(ApplicationImage image) { using (PhoneStoreContext context = new PhoneStoreContext()) { ImageEntity imageEntity = (ImageEntity)new ImageEntity().FromApplicationModel(image); context.Images.Add(imageEntity); context.SaveChanges(); } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; namespace PhoneStore.Models { public class Phone : IApplicationModel { public int PhoneId { get; set; } [Required(ErrorMessage = "Модель обязательно для заполнения")] [StringLength(45, MinimumLength = 1, ErrorMessage = "Модель более 1 символа и не более 45")] public string Model { get; set; } [Required(ErrorMessage = "Производитель обязателен для заполнения")] [StringLength(15, MinimumLength = 1, ErrorMessage = "Производитель более 1 символа и не более 15")] public string Brand { get; set; } [Required(ErrorMessage = "Описание обязательно для заполнения")] [StringLength(250, MinimumLength = 10, ErrorMessage = "Описание не менее 10 символов и не более 250")] public string Description { get; set; } [Range(typeof(Decimal), "1", "1000000", ErrorMessage = "Цена должна быть в диапазоне от 1$ до 1000000$")] public decimal Price { get; set; } public int UserId { get; set; } public Lazy<List<ApplicationImage>> Images = new Lazy<List<ApplicationImage>>(); } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using PhoneStore.Models; using PhoneStore.BL.Service; namespace PhoneStore.DAL.EF { public partial class PhoneEntity { public Phone ConvertToApplicationModel() { Phone phone = new Phone { PhoneId = this.PhoneId, Model = this.Model, Brand = this.Brand, Description = this.Description, Price = this.Price, UserId = this.UserId, }; if (Images.Count != 0) { foreach (var i in Images) { phone.Images.Value.Add(i.ConvertToApplicationModel()); } } return phone; } public IStorageModel<Phone> FromApplicationModel(Phone model) { if (model == null) return null; PhoneEntity phoneEntity = new PhoneEntity { Model = model.Model, Brand = model.Brand, Description = model.Description, Price = model.Price, UserId = model.UserId }; return phoneEntity; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using PhoneStore.Models; using PhoneStore.DAL.EF; namespace PhoneStore.BL.Repository.EF { public class EfPhoneRepository : IPhoneRepository { public void Add(Phone phone) { using (PhoneStoreContext context = new PhoneStoreContext()) { PhoneEntity phoneEntity = (PhoneEntity)new PhoneEntity().FromApplicationModel(phone); context.Phones.Add(phoneEntity); context.SaveChanges(); } } public IEnumerable<Phone> GetAllPhones() { using (PhoneStoreContext context = new PhoneStoreContext()) { IEnumerable<PhoneEntity> listPhonesEntity = context.Phones.Include("Images"); return listPhonesEntity.Count() == 0 ? null : listPhonesEntity.Select(e => e.ConvertToApplicationModel()).ToList(); } } public int GetPhoneId(Phone phone) { using (PhoneStoreContext context = new PhoneStoreContext()) { return context.Phones.FirstOrDefault(e => e.Model == phone.Model).PhoneId; } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using PhoneStore.Models; using PhoneStore.BL.Service; using System.Web.Mvc; using System.Security.Cryptography; using System.Text; using PhoneStore.BL.Repository.EF; using PhoneStore.BL.Repository; namespace PhoneStore.BL.Auth { public class AuthHelper { private IUserManager manager; public AuthHelper(IUserManager manager) { this.manager = manager; } public void UserSetCookie(HttpContextBase context, User user, string value) { if (value == null) throw new Exception("Cookie is empty"); HttpCookie cookie = new HttpCookie(Constants.NameCookie) { Value = value, Expires = DateTime.Now.AddDays(1) }; context.Response.Cookies.Add(cookie); UpdateCookies(user, context.Response.Cookies[Constants.NameCookie].Value); } public void LogOffUser(HttpContextBase context) { if (context.Request.Cookies[Constants.NameCookie] != null) { HttpCookie cookie = new HttpCookie(Constants.NameCookie) { Expires = DateTime.Now.AddDays(-1) }; context.Response.Cookies.Add(cookie); } } public bool IsAuthenticated(HttpContextBase context) { HttpCookie cookie = context.Request.Cookies[Constants.NameCookie]; if (cookie != null) { User user = manager.GetUserByCookies(cookie.Value); return user != null; } return false; } private void UpdateCookies(User user, string cookie) { manager.UpdateCookies(user, cookie); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace PhoneStore.UI { public class PagingInfo { public int TotalPhone { get; set; } // общее кол телефонов public int PhoneCurrentPage { get; set; } // кол телефонов на текущей странице public int CurrentPage { get; set; } // текущая страница // количество страниц public int TotalPages { get { return (int)Math.Ceiling((decimal)TotalPhone / PhoneCurrentPage); } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using PhoneStore.Models; using PhoneStore.BL.Service; namespace PhoneStore.DAL.EF { public partial class ImageEntity { public ApplicationImage ConvertToApplicationModel() { ApplicationImage appImage = new ApplicationImage { ImageId = this.ImageId, Image = this.Image, PhoneId = this.PhoneId }; return appImage; } public IStorageModel<ApplicationImage> FromApplicationModel(ApplicationImage model) { if (model == null) return null; ImageEntity imageEntity = new ImageEntity() { Image = model.Image, PhoneId = model.PhoneId }; return imageEntity; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using PhoneStore.Models; namespace PhoneStore.BL.Service { public interface IPhoneManager { IEnumerable<Phone> GetAllPhones(); void Add(Phone phone); int GetPhoneId(Phone phone); } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using PhoneStore.BL.Repository.EF; using PhoneStore.Models; namespace PhoneStore.BL.Service { public class PhoneManager : IPhoneManager { private IPhoneRepository repository; public PhoneManager (IPhoneRepository repository) { this.repository = repository; } public IEnumerable<Phone> GetAllPhones() { IEnumerable<Phone> phones = repository.GetAllPhones(); return phones; } public void Add(Phone phone) { if (phone == null) throw new ArgumentNullException(nameof(phone)); repository.Add(phone); } public int GetPhoneId(Phone phone) { if (phone == null) throw new ArgumentNullException(nameof(phone)); return repository.GetPhoneId(phone); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using PhoneStore.Models; using PhoneStore.BL.Repository.EF; using PhoneStore.DAL.EF; using PhoneStore.BL.Repository; namespace PhoneStore.BL.Service { public class UserManager : IUserManager { private IUserRepository userRepository; public UserManager(IUserRepository userRepository) { this.userRepository = userRepository; } public void Add(User user) { if (user == null) throw new NullReferenceException(nameof(user)); //ArgumentNull.... userRepository.Add(user); } public User GetUser(Login login) { if (login == null) return null; return userRepository.GetUser(login); } public User GetUserByCookies(string cookie) { if (cookie == null) return null; return userRepository.GetUserByCookies(cookie); } public void UpdateCookies(User user, string cookie) { if (user == null || cookie == null) throw new NullReferenceException(); userRepository.UpdateCookies(user, cookie); } public void UpdateIsActive(User user) { if (user == null) throw new NullReferenceException(nameof(user)); userRepository.UpdateIsActive(user, user.IsActive); } public bool IsAlreadyRegister(User user) { if (user == null) throw new NullReferenceException(nameof(user)); return userRepository.IsAlreadyRegister(user); } } }
fa16eab590eb0c7d2c6cdbec15430ab0888d76c3
[ "C#" ]
29
C#
jaakob/store
a599d8e43326912d5fd7376f47f1f7c98f224673
2c54578581cb5a5f018f647371341bfdf31c5d9a
refs/heads/master
<repo_name>thinkful-ei19/victoria-DSA-Recursion<file_sep>/drills.js //Counting Sheep function sheep(num) { if(num === 0) { return; } console.log(`${num} -Another sheep jump over the fence`); return sheep(num-1); } sheep(4) //Arr Double function double(arr) { if (arr.length === 0) { return []; } const doubleNum = arr[0] * 2; return [doubleNum, ...double(arr.slice(1))]; } double([1, 2, 3]); //Reverse Str function reverse(str) { if (str.length === 1) { return str; } const lastChar = str[str.length - 1]; return lastChar + reverse(str.slice(0, -1)); } reverse('hello'); //nth Triangular Number function triangular(num) { if (num <= 1) { return num } return num + triangular(num - 1); } triangular(6) //Binary Representation// function splitString(str, separator) { const indx = str.indexOf(separator); if (indx === -1) { return str; } const newStr = str.slice(0, indx); return newStr + splitString(str.slice(indx+1), separator); } //Binary function binary(num) { if(num === 0){ return ""; } const remainder = num % 2; return remainder + binary((num-remainder)/2) } binary(25) //Factorial function factorial(num) { if(num === 0){ return 1; } return num * factorial(num-1) } factorial(5) //Fibonacci function fibonacci(num) { if(num <= 2){ return 1; } return fibonacci(num-1) + fibonacci(num-2) } fibonacci(4) //Anagrams function anagrams(prefix, str) { if(str.length <= 1) { console.log.log(`The anagram is ${prefix}}${str}`); } else { for (let i=0; i<str.length; i++) { let current = str.substring(1, i + 1); let previous = str.substring(0, i); let after = str.substring(i + 1); anagrams(prefix + current, previous + after); } } } function printAnagram(word) { anagrams(' ', word) } anagrams('e', 'east');
86df620fc31cb15a8ae4cabf02c3d3fd1419a8e7
[ "JavaScript" ]
1
JavaScript
thinkful-ei19/victoria-DSA-Recursion
72f5265d43c0545f3f8e9ac992032cf80d6a74f4
d95161ce2ec2deaef60505e39bd480ca2c9377c6
refs/heads/master
<file_sep># how to setup 1. install rustup ref: https://github.com/rust-lang-nursery/rustup.rs 2. `cargo install cargo-web` # how to run `cargo web start` if you want access from remote: `cargo web start --host 0.0.0.0`<file_sep>[package] name = "ow_damage_calc_web" version = "0.1.0" authors = ["iguto <<EMAIL>>"] [dependencies] # strum = "0.8.0" # strum_macros = "0.8.0" # serde = "1" # serde_derive = "1" chrono = "0.4.0" [dependencies.yew] git = "https://github.com/DenisKolodin/yew.git"<file_sep>use std::fmt; const BOARD_SIZE: usize = 8; const DIRS: [(i64, i64); 8] = [ (-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1), ]; type Board = [[Cell; BOARD_SIZE]; BOARD_SIZE]; #[derive(Clone, Copy, Debug)] pub struct Coordinate(pub usize, pub usize); pub struct Map { pub col_size: usize, pub row_size: usize, pub inner_map: Board, } impl Coordinate { pub fn next(&self, other: (i64, i64)) -> Option<Coordinate> { let row = other.0 + (self.0 as i64); let column = other.1 + (self.1 as i64); if row < 0 || column < 0 || row >= BOARD_SIZE as i64 || column >= BOARD_SIZE as i64 { return None; } Some(Coordinate(row as usize, column as usize)) } } impl Map { pub fn new(row_size: usize, col_size: usize) -> Self { let board = Self::setup_board(); Map { row_size, col_size, inner_map: board, } } pub fn get_cell(&self, coord: Coordinate) -> Option<Cell> { match self.inner_map.get(coord.0) { Some(column_data) => match column_data.get(coord.1) { Some(cell) => Some(*cell), None => return None, }, None => return None, } } pub fn get_mut_cell(&mut self, coord: Coordinate) -> Option<&mut Cell> { match self.inner_map.get_mut(coord.0) { Some(column_data) => match column_data.get_mut(coord.1) { Some(cell) => Some(cell), None => return None, }, None => return None, } } pub fn put_hand(&mut self, row: usize, column: usize, player: CellColors) { self.inner_map[row][column].color = player; let coord = Coordinate(row, column); self.flip_hands(coord, player); } fn flip_hands(&mut self, coord: Coordinate, player: CellColors) { for dir in DIRS.iter() { self.flip_hands_dir(coord, player, *dir); } } fn flip_hands_dir(&mut self, coord: Coordinate, player: CellColors, dir: (i64, i64)) { let mut coord: Coordinate = coord.clone(); if !self.is_reversible_dir(coord, player, dir) { return; } loop { coord = match coord.next(dir) { Some(c) => c, None => break, }; let cell: &mut Cell = match self.get_mut_cell(coord) { Some(cell) => cell, None => panic!("out of bound error"), }; match player { CellColors::Black => match cell.color { CellColors::White => cell.color = CellColors::Black, _ => break, }, CellColors::White => match cell.color { CellColors::Black => cell.color = CellColors::White, _ => break, }, _ => unreachable!(), } } } pub fn is_reversible(&self, coord: Coordinate, player: CellColors) -> bool { for dir in DIRS.iter() { if self.is_reversible_dir(coord, player, *dir) { return true; } } false } fn is_reversible_dir(&self, coord: Coordinate, player: CellColors, dir: (i64, i64)) -> bool { let mut coord = coord.clone(); let mut reversible_count = 0; loop { coord = match coord.next(dir) { Some(coord) => coord, None => return false, }; let cell_color = match self.get_cell(coord) { Some(cell) => cell, None => panic!("out of bound error"), }.color; match player { CellColors::Black => match cell_color { CellColors::White => reversible_count += 1, CellColors::Black if reversible_count > 0 => return true, _ => return false, }, CellColors::White => match cell_color { CellColors::Black => reversible_count += 1, CellColors::White if reversible_count > 0 => return true, _ => return false, }, _ => return false, }; } } fn setup_board() -> Board { let cell = Cell { row: 0, column: 0, color: CellColors::Empty, }; let mut board = [[cell.clone(); BOARD_SIZE]; BOARD_SIZE]; // set position to every cells for (row, column_cells) in board.iter_mut().enumerate() { let row = row.clone(); for (column, cell) in column_cells.iter_mut().enumerate() { cell.set_position(row, column); } } Self::put_hands_on_init(&mut board) } fn put_hands_on_init(board: &mut Board) -> Board { board[3][3].color = CellColors::Black; board[4][4].color = CellColors::Black; board[3][4].color = CellColors::White; board[4][3].color = CellColors::White; *board } } #[derive(Clone, Copy, Debug)] pub enum CellColors { Empty, White, Black, } #[derive(Clone, Copy, Debug)] pub struct Cell { pub column: usize, pub row: usize, pub color: CellColors, } impl fmt::Display for CellColors { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { CellColors::Black => write!(f, "black"), CellColors::White => write!(f, "white"), CellColors::Empty => write!(f, "empty"), } } } impl fmt::Display for Cell { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.color { CellColors::Empty | CellColors::Black | CellColors::White => write!(f, " "), } } } impl Cell { fn set_position(&mut self, row: usize, column: usize) { self.row = row; self.column = column; } pub fn hand(&mut self, player: CellColors) { println!("flip called cell:{:?}", self); self.color = player; } } <file_sep>#[macro_use] extern crate yew; use yew::prelude::*; use yew::services::console::ConsoleService; mod map; use map::{Cell, CellColors, Coordinate, Map}; struct Context { console: ConsoleService, } struct Model { map: Map, player: CellColors, } #[derive(Debug)] enum Msg { Nope, Hand(usize, usize), } impl Component<Context> for Model { type Msg = Msg; type Properties = (); fn create(_: Self::Properties, _: &mut Env<Context, Self>) -> Self { Model { map: Map::new(8, 8), player: CellColors::Black, } } fn update(&mut self, msg: Self::Msg, context: &mut Env<Context, Self>) -> ShouldRender { println!("msg: {:?}", msg); match msg { Msg::Hand(row, column) => { self.map.put_hand(row, column, self.player); println!("in hand row:{} column:{}", row, column); self.switch_player(); } Msg::Nope => (), } true } } impl Renderable<Context, Model> for Model { fn view(&self) -> Html<Context, Self> { html! { <div> { self.render_player_indicator() } { self.render_map() } </div> } } } impl Model { fn render_map(&self) -> Html<Context, Self> { let render_map_elem = |cell: &Cell| { let c = cell.clone(); match cell.color { CellColors::Empty if self.map .is_reversible(Coordinate(cell.row, cell.column), self.player) => { html!{ <td class=("gray-cell", "clickable"), onclick=move |_: MouseData| Msg::Hand(c.row, c.column), /> } } CellColors::Empty => html!{ <td class="gray-cell", ></td> }, CellColors::Black => html!{ <td class="black-cell" ,></td> }, CellColors::White => html!{ <td class="white-cell" ,></td> }, } }; html!{ <table>{ for self.map.inner_map.iter().map(|column| { html!{ <tr> { for column.iter().map(|cell| render_map_elem(cell)) } </tr> } })}</table> } } fn render_player_indicator(&self) -> Html<Context, Self> { html! { <div class="player-indicator-container", > <span>{ "player:" }</span> <span class=("player-indicator", { match self.player { CellColors::Black => "player-black", CellColors::White => "player-white", _ => "", } }),></span> </div> } // match self.player { // CellColors::Black => html!{ // <p>player: <div class=("player-indicator", "player-black"),></div></p> // }, // CellColors::White => html!{ // <p>player: <div class=("player-indicator", "player-white"),></div></p> // }, // _ => unreachable!(), // } } fn switch_player(&mut self) { self.player = match self.player { CellColors::White => CellColors::Black, CellColors::Black => CellColors::White, CellColors::Empty => unreachable!(), } } } fn main() { yew::initialize(); let context = Context { console: ConsoleService, }; let app: App<_, Model> = App::new(context); app.mount_to_body(); yew::run_loop(); }
57d63510233448d1a605e46e9eb0e766dfaab8b7
[ "Markdown", "TOML", "Rust" ]
4
Markdown
iguto/test_othello
2d9128df5fabc47c283269105f4f81c1c8aa42f4
c304eb49459dd44c16d0b23a19881408da27f61d
refs/heads/master
<repo_name>jonathanbutler7/my-list-project<file_sep>/index.js function enterText() { $('#js-shopping-list-form').find('button').on('click', function(event) { const newItemText = $('input').val(); event.preventDefault(); $('ul').append( `<li> <span class="shopping-item">${newItemText}</span> <div class="shopping-item-controls"> <button class="shopping-item-toggle"> <span class="button-label">check</span> </button> <button class="shopping-item-delete"> <span class="button-label">delete</span> </button> </div> </li>` ); }); } // html method, append method function checkHandler() { $('ul').on('click', '.shopping-item-toggle', function (event) { const itemCheck = $(this).parent().closest('li').find('.shopping-item'); event.stopPropagation(); $(itemCheck).toggleClass('shopping-item__checked'); }); } function deleteHandler() { $('ul').on('click', '.shopping-item-delete', function(event) { const itemDiv = $(this).closest('li'); event.stopPropagation(); $(itemDiv).remove(); }); } deleteHandler(); checkHandler(); enterText();
b1609e8fe950e6af8667e423d751b36241ce30de
[ "JavaScript" ]
1
JavaScript
jonathanbutler7/my-list-project
f931288149b35faa8f0633973453dd204d0c6abc
be55417698255283ec28da5320cb926de5b82d89
refs/heads/master
<file_sep>import { WS_ADDRESS } from "../configs"; export function useWebSocket() { const ws = new WebSocket(WS_ADDRESS) const init = () =>{ bindEvent(); } function bindEvent(){ ws.addEventListener('open',handleOpen,false) ws.addEventListener('close',handleClose,false) ws.addEventListener('error',handleError,false) ws.addEventListener('message ',handleMessage,false) } function handleOpen(event:any){ console.log("WebSocket is open now.",event); } function handleClose(event:any){ console.log("WebSocket is close now.",event); } function handleError(event:any){ console.log("WebSocket is error now.",event); } function handleMessage(event:any){ console.log("WebSocket is message now.",event); } init(); return ws; } <file_sep>export default [{ imageL: require("@/assets/images/dark.svg"), alt: "dark", name: "ThemeDark", }, { imageL: require("@/assets/images/light.svg"), alt: "light", name: "ThemeLight", }, { imageL: require("@/assets/images/gray.svg"), alt: "gray", name: "ThemeGray", }, { imageL: require("@/assets/images/green.svg"), alt: "green", name: "ThemeGreen", }, { imageL: require("@/assets/images/blue.svg"), alt: "blue", name: "ThemeBlue", }, { imageL: require("@/assets/images/purple.svg"), alt: "purple", name: "ThemePurple", }, { imageL: require("@/assets/images/red.svg"), alt: "red", name: "ThemeRed", }, { imageL: require("@/assets/images/yellow.svg"), alt: "yellow", name: "ThemeYellow", }, { imageL: require("@/assets/images/orange.svg"), alt: "orange", name: "ThemeOrange", }, ]<file_sep>import { createApp } from 'vue' import App from './App.vue' import router from './router/index' import {store,key} from '@/store/index' import ElementPlus from 'element-plus' import 'element-plus/dist/index.css' import '@/assets/CSS/common.scss' createApp(App) .use(router) .use(store,key) .use(ElementPlus) .mount('#app') <file_sep>import {createRouter,createWebHistory,RouteRecordRaw} from 'vue-router'; const routes:Array<RouteRecordRaw> = [ { path:'/', name:'home', component:() => import('@/views/home.vue') } ] //创建 const router = createRouter({ history:createWebHistory(), routes }) export default router <file_sep>import { useWebSocket } from "./websocket"; export default { useWebSocket } <file_sep>import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import { resolve } from 'path' import * as path from 'path/posix' // https://vitejs.dev/config/ export default defineConfig({ plugins: [vue()], server: { host:'0.0.0.0', port:8000, open: true }, resolve:{ alias:{ '@':path. resolve(__dirname,'src') } } }) <file_sep>// store.ts import { InjectionKey } from 'vue' import { createStore, useStore as baseUseStore, Store } from 'vuex' export interface State { count: number } export const key: InjectionKey<Store<State>> = Symbol() export const store = createStore<State>({ state: { count: 0 }, mutations:{ setCount(state:State,count:number){ state.count = count; } }, getters:{ getCount(state:State){ return state.count; } } }) // 定义自己的 `useStore` 组合式函数 export function useStore () { return baseUseStore(key) }<file_sep>const BASE_URL: string = 'loclhost'; const WS_PORT: string = '8000'; export const WS_ADDRESS:string | URL = `ws://${BASE_URL}:${WS_PORT}` export default {WS_ADDRESS}
3e61803bc3af59ae5c59d8951d197832331359a5
[ "JavaScript", "TypeScript" ]
8
TypeScript
SincereCSL/Vue.js-Study
c02bd73294787c8868ff551d795227036f00c13e
1cd02df0556ffc718e77cb6c527c206129175004
refs/heads/master
<repo_name>EloiEloi/ptemier-projet-maven<file_sep>/src/main/resources/application.properties titre=Super App de MALADE ! :) environnement=${mode}<file_sep>/src/main/java/dev/App.java package dev; import java.util.ResourceBundle; import com.github.lalyos.jfiglet.FigletFont; /** * Hello world! * */ public class App { public static void main(String[] args) { String titre = ResourceBundle.getBundle("application").getString("titre"); String asciiArt = FigletFont.convertOneLine(titre); System.out.println(asciiArt); // affichage de l'environnement String environnement = ResourceBundle.getBundle("application").getString("environnement"); System.out.println("Environnement : " + environnement); } }
4b479a5d767f1cbbced4b4993757456183b644f6
[ "Java", "INI" ]
2
INI
EloiEloi/ptemier-projet-maven
a86f16b0d5ae57acef36f87e98d857b48c68a25c
4604094023fdc9503585639cbbaea499a86c2624
refs/heads/master
<repo_name>rolaleks/patterns<file_sep>/src/main/java/ru/geekbrains/atm/service/UserService.java package ru.geekbrains.atm.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import ru.geekbrains.atm.entity.User; import ru.geekbrains.atm.repo.UserRepository; import ru.geekbrains.atm.service.interdafaces.UserServerInterface; import java.util.List; import java.util.Optional; @Service public class UserService implements UserServerInterface { private UserRepository repository; private BCryptPasswordEncoder passwordEncoder; @Autowired public UserService(UserRepository repository) { this.repository = repository; this.passwordEncoder = new BCryptPasswordEncoder(); } @Transactional(readOnly = true) public List<User> findAll() { return repository.findAll(); } @Transactional public void save(User user) { user.setPassword(passwordEncoder.encode(user.getPassword())); repository.save(user); } @Transactional(readOnly = true) public Optional<User> findById(long id) { return repository.findById(id); } } <file_sep>/src/main/java/ru/geekbrains/atm/notify/SlackNotifier.java package ru.geekbrains.atm.notify; import org.springframework.beans.factory.annotation.Value; public class SlackNotifier implements EventListener { @Value("{slack.url}") private String appUrl; @Value("{slack.token}") private String token; public SlackNotifier(String appUrl, String token) { this.appUrl = appUrl; this.token = token; } public SlackNotifier() { } @Override public void notify(String msg, String category) { //TODO отправка сообщений в слак } } <file_sep>/src/main/resources/application.properties server.servlet.context-path=/ server.port=8080 spring.datasource.url=jdbc:mysql://172.16.17.32:3306/atm?createDatabaseIfNotExist=true&allowPublicKeyRetrieval=true&useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC spring.datasource.username=geekbrains spring.datasource.password=<PASSWORD> spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.jpa.show-sql=true spring.jpa.properties.hibernate.format_sql=true spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect file-log.path="app.log"<file_sep>/src/main/java/ru/geekbrains/atm/policy/LogPolicy.java package ru.geekbrains.atm.policy; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import ru.geekbrains.atm.service.interdafaces.LogServiceInterface; import java.util.ArrayList; @Service public class LogPolicy { private LogServiceInterface logService; private int logSize = 10; @Autowired public LogPolicy(LogServiceInterface logService) { this.logService = logService; } public ArrayList<String> getLogs() { return logService.readLogs(logSize); } public int getLogSize() { return logSize; } public void setLogSize(int logSize) { this.logSize = logSize; } } <file_sep>/lesson_1.md Для небольшой CRM подходит многослойная архитектура, так как ее относительно легко поддерживать и разворачивать и она позволяет с небольшими усилиями масштабировать систему на разные типы интерфейсы (web, mobile, desktop), также зачастую для CRM необходимо часто реализовываться различные интеграции со сторонними сервисами и многосолойная архитектура позволит это сделать с наименьшими трудозатратами<file_sep>/src/main/java/ru/geekbrains/atm/repo/TransactionRepository.java package ru.geekbrains.atm.repo; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import ru.geekbrains.atm.entity.Transaction; import ru.geekbrains.atm.entity.User; import java.util.List; @Repository public interface TransactionRepository extends JpaRepository<Transaction, Long> { List<Transaction> findByUser(User user); } <file_sep>/src/main/java/ru/geekbrains/atm/notify/EmailNotifier.java package ru.geekbrains.atm.notify; import org.springframework.beans.factory.annotation.Value; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSenderImpl; public class EmailNotifier implements EventListener { private String email; @Value("${email-from}") private String emailFrom; @Value("${admin-email}") private String adminEmail; public EmailNotifier(String email) { this.email = email; } public EmailNotifier() { this.email = adminEmail; } @Override public void notify(String msg, String category) { JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); SimpleMailMessage message = new SimpleMailMessage(); message.setFrom(emailFrom); message.setTo(email); message.setSubject("Notification: " + category); message.setText(msg); mailSender.send(message); } } <file_sep>/src/main/java/ru/geekbrains/atm/service/TransactionService.java package ru.geekbrains.atm.service; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import ru.geekbrains.atm.entity.Transaction; import ru.geekbrains.atm.repo.TransactionRepository; import ru.geekbrains.atm.service.interdafaces.TransactionServerInterface; import java.util.List; import java.util.Optional; @Service public class TransactionService implements TransactionServerInterface { private TransactionRepository repository; @Transactional(readOnly = true) @Override public List<Transaction> findAll() { return repository.findAll(); } @Override @Transactional public void save(Transaction transaction) { repository.save(transaction); } @Override @Transactional(readOnly = true) public Optional<Transaction> findById(long id) { return repository.findById(id); } } <file_sep>/src/main/java/ru/geekbrains/atm/service/interdafaces/UserServerInterface.java package ru.geekbrains.atm.service.interdafaces; import ru.geekbrains.atm.entity.User; import java.util.List; import java.util.Optional; public interface UserServerInterface { public List<User> findAll() ; public void save(User user); public Optional<User> findById(long id) ; } <file_sep>/src/main/java/ru/geekbrains/atm/policy/UserTransactionPolicy.java package ru.geekbrains.atm.policy; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import ru.geekbrains.atm.entity.Transaction; import ru.geekbrains.atm.entity.User; import ru.geekbrains.atm.notify.HttpNotifier; import ru.geekbrains.atm.notify.LogManager; import ru.geekbrains.atm.notify.SlackNotifier; import ru.geekbrains.atm.service.interdafaces.TransactionServerInterface; import ru.geekbrains.atm.service.interdafaces.UserServerInterface; import java.util.Optional; @Service public class UserTransactionPolicy { @Autowired private UserServerInterface userService; @Autowired private TransactionServerInterface transactionService; private LogManager logManager; @Autowired public UserTransactionPolicy(LogManager logManager) { this.logManager = logManager; logManager.subscribe("error", new SlackNotifier()); logManager.subscribe("warning", new HttpNotifier()); } public void createWithdrawTransaction(long userId, float amount) { if (amount < 0) { logManager.notify("Invalid amount", "error"); throw new RuntimeException("Invalid amount"); } User user = this.findUser(userId); Transaction transaction = new Transaction(); transaction.setUser(user); transaction.setAmount(-1 * amount); transactionService.save(transaction); logManager.notify("Transaction saved", "warning"); } public void createDepositTransaction(long userId, float amount) { if (amount < 0) { logManager.notify("Invalid amount", "error"); throw new RuntimeException("Invalid amount"); } User user = this.findUser(userId); Transaction transaction = new Transaction(); transaction.setUser(user); transaction.setAmount(amount); transactionService.save(transaction); logManager.notify("Transaction saved", "warning"); } private User findUser(long userId) { Optional<User> user = userService.findById(userId); return user.orElseThrow(); } }
c55aeb0edb53b68f67cde56bd724877019415563
[ "Markdown", "Java", "INI" ]
10
Java
rolaleks/patterns
c435c881eb298c98eb5c6ae0d8f87a5222d78641
c41a7fe20a15202631c7f652d09705f4ff475a7b
refs/heads/master
<repo_name>vikasvk05/DailyCode<file_sep>/Day1/WindowSlidTech.java // Time complexcity is O(n) // Sliding window concept class WindowSlidTech{ static void slidWindow(int[] arr,int k){ int max = 0; int window_sum = 0; for(int i=0;i<k;i++){ window_sum += arr[i]; } max = window_sum; //System.out.println("Window sum:"+window_sum); for(int i=k;i<arr.length;i++){ window_sum += arr[i] - arr[i-k]; //System.out.println("Window sum:"+window_sum); if(window_sum > max) max = window_sum; } System.out.println("Max Window sum is:"+max); } static void dis(int arr[]){ for(int i=0;i<arr.length;i++){ System.out.print(arr[i]+" "); } System.out.print("\n"); } public static void main(String[] args) { int[] arr = { 5,2,-1,7,3}; int k =3; slidWindow(arr,k); } }
0912cb17a01c910b6cea5d3275bebd6d21a3e9aa
[ "Java" ]
1
Java
vikasvk05/DailyCode
93a8738dde141aa1b7ef7aa5974a679fb854a553
2b2eae99f50df67f28baed183b08e642254365d5
refs/heads/develop
<repo_name>Jesse-Fan/js-fp<file_sep>/src/index.js const pickProp = prop => obj => obj[prop] const pickLen = pickProp('length') const curry = wrappedFn => (...args) => pickLen(wrappedFn) <= pickLen(args) ? wrappedFn(...args) : (...extraArgs) => curry(wrappedFn)(...args, ...extraArgs) module.exports = curry
46f9da1d799f2444b9f9116564d893142d5699bb
[ "JavaScript" ]
1
JavaScript
Jesse-Fan/js-fp
63ed85a9a1eb24d4c6892aa2e06485f6a3b0caec
3c37f3f6965ceafa818a063f2669bdcb199ec9f6
refs/heads/main
<file_sep>-- Stammdaten SELECT * FROM tbl_CvAvailability SELECT * FROM tbl_CvApproval SELECT * FROM tbl_CvCountry SELECT * FROM tbl_CvDiploma SELECT * FROM tbl_CvEducationLevel SELECT * FROM tbl_CvEmailType SELECT * FROM tbl_CvGender SELECT * FROM tbl_CvHighestEducationLevel SELECT * FROM tbl_CvLanguageProficiency SELECT * FROM tbl_CvLanguageSkillType SELECT * FROM tbl_CvMaritalStatus SELECT * FROM tbl_CvNationality SELECT * FROM tbl_CvPhoneNumberType SELECT * FROM tbl_CvProfileStatus SELECT * FROM tbl_CvRegion SELECT * FROM tbl_CvSalary -- Stammdaten Dynamisch SELECT * FROM tbl_CvComputerSkillType SELECT * FROM tbl_CvDegreeDirection SELECT * FROM tbl_CvDriversLicence SELECT * FROM tbl_CvEducation SELECT * FROM tbl_CvEducationDetail SELECT * FROM tbl_CvInstituteType SELECT * FROM tbl_CvJobTitle SELECT * FROM tbl_CvSocialMediaType SELECT * FROM tbl_CvSoftSkillType -- Dynamische Daten SELECT * FROM tbl_CvProfile SELECT * FROM tbl_CvPersonal SELECT * FROM tbl_CvAddress SELECT * FROM tbl_CvPhoneNumber SELECT * FROM tbl_CvEmail SELECT * FROM tbl_CvSocialMedia SELECT * FROM tbl_CvDocumentText SELECT * FROM tbl_CvDocumentHtml SELECT * FROM tbl_CvEducationHistory SELECT * FROM tbl_CvEmploymentHistory SELECT * FROM tbl_CvSkill SELECT * FROM tbl_CvComputerSkill SELECT * FROM tbl_CvLanguageSkill SELECT * FROM tbl_CvSoftSkill SELECT * FROM tbl_CvOther SELECT * FROM tbl_CvHobby SELECT * FROM tbl_CvReference SELECT * FROM tbl_CvCustomArea SELECT * FROM tbl_CvPicture SELECT * FROM tbl_CvExtraInfo SELECT * FROM tbl_CvTransportation -- Dynamische Daten löschen /* DELETE FROM tbl_CvProfile DELETE FROM tbl_CvPhoneNumber DELETE FROM tbl_CvEmail DELETE FROM tbl_CvSocialMedia DELETE FROM tbl_CvPersonal DELETE FROM tbl_CvAddress DELETE FROM tbl_CvDocumentText DELETE FROM tbl_CvDocumentHtml */ <file_sep>Startup arguments that can be used for testing. // Convert a pdf ProcessStarter CONVERT_PDF <pdfPath> <mdguid> e.g. ProcessStarter CONVERT_PDF C:\Users\Technik\Desktop\test.pdf A0BB18D4-84EB-42d7-B366-721ED0E296EC // Analyze a pdf in order to find a DataMatrix code ProcessStarter ANALYZE_PDF <pdfPath> e.g. ProcessStarter ANALYZE_PDF C:\Users\Technik\Desktop\test.pdf // Start the file system watcher. ProcessStarter START_FILESYSTEMWATCHER<file_sep>namespace DevExpress.Metro.Navigation { using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using DevExpress.XtraEditors; using DevExpress.Metro.Navigation.Properties; public partial class _Layout : DevExpress.XtraEditors.XtraUserControl, IChrome { public _Layout() { InitializeComponent(); if (LookAndFeel.ActiveSkinName == "Metropolis") { this.back.Image = Resources.ArrowBlack; } else { this.back.Image = Resources.ArrowNormal; } this.back.MouseClick += Back_MouseClick; this.back.MouseHover += Back_MouseHover; this.back.MouseLeave += Back_MouseLeave; } Control _previous; void IChrome.Navigate(Control previous) { _previous = previous; } public override string Text { get { return this.title.Text; } set { this.title.Text = value; } } void Back_MouseLeave(object sender, EventArgs e) { if (LookAndFeel.ActiveSkinName == "Metropolis") { this.back.Image = Resources.ArrowBlack; } else { this.back.Image = Resources.ArrowNormal; } } void Back_MouseHover(object sender, EventArgs e) { if (LookAndFeel.ActiveSkinName == "Metropolis") { this.back.Image = Resources.ArrowNormal; } else { this.back.Image = Resources.ArrowHover; } } void Back_MouseClick(object sender, MouseEventArgs e) { this.Parent.GoTo(_previous, null); } private void _Layout_Load(object sender, EventArgs e) { } } }
065c0f0e98e0ec33c97d74533ed509d7453667fd
[ "C#", "SQL", "Text" ]
3
SQL
erinaldo/sputnik-enterprise-master
091bb297c7015b0794a1727cc39690023aee317c
b2b4c8a6fef3bcf536cff975213fc822c99fd1c5
refs/heads/main
<repo_name>ljwhite/mod3_midmod_prep<file_sep>/app/models/park.rb class Park attr_reader :name, :description, :directions, :hours def initialize(attributes) @name = attributes[:name] @description = attributes[:description] @directions = attributes[:directionsInfo] @hours = attributes[:operatingHours].first[:standardHours] end end <file_sep>/spec/requests/user_story_spec.rb require 'rails_helper' feature "user can search for parks " do scenario "user submits state name" do visit '/' select "Tennessee", from: :state click_on "Find Parks" expect(current_path).to eq(parks_path) expect(page).to have_content("15 Parks") expect(page).to have_css(".park", count: 15) within(first(".park")) do expect(page).to have_css(".name") expect(page).to have_css(".description") expect(page).to have_css(".directions") expect(page).to have_css(".hours") end end end <file_sep>/app/services/parks_service.rb class ParksService def find_parks_in_state(state) response = conn.get("/api/v1/parks?stateCode=#{state}") json = JSON.parse(response.body, symbolize_names: true)[:data] end private def conn @conn ||= Faraday.new(url: "https://developer.nps.gov") do |faraday| faraday.headers["X-API-KEY"] = ENV['PARKS_FINDER_API-KEY'] end end end <file_sep>/app/facades/search_result.rb class SearchResult def parks(state) json = ParksService.new.find_parks_in_state(state) @parks = json.map do |park_data| Park.new(park_data) end end end <file_sep>/app/controllers/parks_controller.rb class ParksController < ApplicationController def index # state = params[:state] # @parks = call(state) # # # # def conn # @conn ||= Faraday.new(url: "https://developer.nps.gov/api/v1") do |faraday| # farday.headers["X-API-KEY"] = ENV['PARKS_FINDER_API-KEY'] # end # end # # # response = conn.get("/api/v1/parks?stateCode=#{state}") # json = JSON.parse(response.body, symbolize_names: true) # @parks = json[:data].map do |park| # Park.new(park) # end search_results = SearchResult.new @parks = search_results.parks(params[:state]) end end
fca8b5b8bde198850eb5cf9e79c4d427ae23f15e
[ "Ruby" ]
5
Ruby
ljwhite/mod3_midmod_prep
b5716805d03def054dee446046efdba511062420
d69d58984d56dda0add5adf75d514504cd66fe7f
refs/heads/master
<file_sep># -*- coding: utf-8 -*- from __future__ import unicode_literals import swapper from django.contrib import admin from django_ipam.admin import AbstractIpAddressAdmin, AbstractSubnetAdmin IpAddress = swapper.load_model("django_ipam", "IpAddress") Subnet = swapper.load_model("django_ipam", "Subnet") @admin.register(IpAddress) class IPAddressAdmin(AbstractIpAddressAdmin): pass @admin.register(Subnet) class SubnetAdmin(AbstractSubnetAdmin): app_name = "sample_ipam" <file_sep>import swapper from django.test import TestCase from . import CreateModelsMixin, PostDataMixin from .base.test_api import BaseTestApi class TestApi(BaseTestApi, CreateModelsMixin, PostDataMixin, TestCase): ipaddress_model = swapper.load_model('django_ipam', 'IPAddress') subnet_model = swapper.load_model('django_ipam', 'Subnet') <file_sep>import swapper from . import BaseExportSubnetCommand class Command(BaseExportSubnetCommand): subnet_model = swapper.load_model('django_ipam', 'Subnet') <file_sep>from ipaddress import ip_network class BaseTestForms(object): def test_none_value(self): form = self.form_class({'subnet': None}) self.assertFalse(form.is_valid()) def test_field_base_network_value(self): form = self.form_class({'subnet': ip_network(b'\xC0\xA8\x00\x01')}) self.assertTrue(form.is_valid()) def test_form_ipv4_valid(self): form = self.form_class({'subnet': '10.0.1.0/24'}) self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data['subnet'], ip_network('10.0.1.0/24')) def test_form_ipv4_invalid(self): form = self.form_class({'subnet': '10.0.0.1.2/32'}) self.assertFalse(form.is_valid()) def test_form_ipv4_strip(self): form = self.form_class({'subnet': ' 10.0.1.0/24 '}) self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data['subnet'], ip_network('10.0.1.0/24')) def test_form_ipv6_valid(self): form = self.form_class({'subnet': '2001:0:1::/64'}) self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data['subnet'], ip_network('2001:0:1::/64')) def test_form_ipv6_invalid(self): form = self.form_class({'subnet': '2001:0::1::2/128'}) self.assertFalse(form.is_valid()) def test_form_ipv6_strip(self): form = self.form_class({'subnet': ' 2001:0:1::/64 '}) self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data['subnet'], ip_network('2001:0:1::/64')) <file_sep>import swapper from django.test import TestCase from . import CreateModelsMixin, FileMixin from .base.test_commands import BaseTestCommands class TestCommands(BaseTestCommands, CreateModelsMixin, TestCase, FileMixin): subnet_model = swapper.load_model('django_ipam', 'Subnet') ipaddress_model = swapper.load_model('django_ipam', 'IpAddress') <file_sep># -*- coding: utf-8 -*- from __future__ import unicode_literals from django_ipam.models import AbstractIpAddress, AbstractSubnet class IpAddress(AbstractIpAddress): pass class Subnet(AbstractSubnet): pass <file_sep>from django.apps import AppConfig from .compat import patch_ipaddress_lib class DjangoIpamConfig(AppConfig): name = 'django_ipam' verbose_name = 'IPAM' def ready(self): patch_ipaddress_lib() <file_sep># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.apps import AppConfig class SampleIpamConfig(AppConfig): name = 'sample_ipam' <file_sep>/*jslint browser:true */ function dismissAddAnotherPopup(win) { "use strict"; win.close(); window.location.reload(); } <file_sep>from django.conf.urls import url from . import views urlpatterns = [ url(r'^import-subnet/$', views.import_subnet, name='import-subnet'), url(r'^subnet/(?P<subnet_id>[^/]+)/get-first-available-ip/$', views.get_first_available_ip, name='get_first_available_ip'), url(r'^subnet/(?P<subnet_id>[^/]+)/request-ip/$', views.request_ip, name='request_ip'), url(r'^subnet/(?P<subnet_id>[^/]+)/export/$', views.export_subnet, name='export-subnet'), url(r'^subnet/(?P<subnet_id>[^/]+)/ip-address$', views.subnet_list_ipaddress, name='list_create_ip_address'), url(r'^subnet/$', views.subnet_list_create, name='subnet_list_create'), url(r'^subnet/(?P<pk>[^/]+)$', views.subnet, name='subnet'), url(r'^ip-address/(?P<pk>[^/]+)/$', views.ip_address, name='ip_address'), ] <file_sep>import os from unittest import skipIf import swapper from django.test import TestCase from . import CreateModelsMixin, PostDataMixin from .base.test_admin import BaseTestAdmin @skipIf(os.environ.get('SAMPLE_APP', False), 'Running tests on SAMPLE_APP') class TestAdmin(BaseTestAdmin, CreateModelsMixin, PostDataMixin, TestCase): app_name = 'django_ipam' ipaddress_model = swapper.load_model('django_ipam', 'IPAddress') subnet_model = swapper.load_model('django_ipam', 'Subnet') <file_sep>from django.conf.urls import include, url from openwisp_utils.admin_theme.admin import admin, openwisp_admin openwisp_admin() admin.autodiscover() urlpatterns = [ url(r'^', include('django_ipam.urls', namespace='ipam')), url(r'^admin/', admin.site.urls), ] <file_sep>import os from unittest import skipIf import swapper from django.forms import ModelForm from django.test import TestCase from .base.test_forms import BaseTestForms class NetworkAddressTestModelForm(ModelForm): class Meta: model = swapper.load_model('django_ipam', 'Subnet') fields = ('subnet',) @skipIf(os.environ.get('SAMPLE_APP', False), 'Running tests on SAMPLE_APP') class TestForms(BaseTestForms, TestCase): form_class = NetworkAddressTestModelForm <file_sep>from django.contrib import admin from .base.admin import AbstractIpAddressAdmin, AbstractSubnetAdmin from .models import IpAddress, Subnet @admin.register(IpAddress) class IPAddressAdmin(AbstractIpAddressAdmin): pass @admin.register(Subnet) class BaseSubnet(AbstractSubnetAdmin): pass <file_sep>import json import os import swapper IpAddress = swapper.load_model("django_ipam", "IPAddress") Subnet = swapper.load_model("django_ipam", "Subnet") class FileMixin(object): def _get_path(self, file): d = os.path.dirname(os.path.abspath(__file__)) return os.path.join(d, file) class CreateModelsMixin(object): def _get_extra_fields(self, **kwargs): # For adding mandatory extra fields options = dict() options.update(**kwargs) return options def _create_subnet(self, **kwargs): options = dict( subnet='', description='', ) options.update(self._get_extra_fields()) options.update(kwargs) instance = Subnet(**options) instance.full_clean() instance.save() return instance def _create_ipaddress(self, **kwargs): options = dict( ip_address='', description='', ) options.update(self._get_extra_fields()) options.update(kwargs) instance = IpAddress(**options) instance.full_clean() instance.save() return instance class PostDataMixin(object): def _post_data(self, **kwargs): return json.dumps(dict(kwargs)) <file_sep>import swapper from .generics import ( BaseAvailableIpView, BaseExportSubnetView, BaseImportSubnetView, BaseIpAddressListCreateView, BaseIpAddressView, BaseRequestIPView, BaseSubnetListCreateView, BaseSubnetView, ) IpAddress = swapper.load_model('django_ipam', 'IpAddress') Subnet = swapper.load_model('django_ipam', 'Subnet') class AvailableIpView(BaseAvailableIpView): """ Get the next available IP address under a subnet """ subnet_model = Subnet queryset = IpAddress.objects.none() class RequestIPView(BaseRequestIPView): """ Request and create a record for the next available IP address under a subnet """ subnet_model = Subnet queryset = IpAddress.objects.none() class SubnetIpAddressListCreateView(BaseIpAddressListCreateView): """ List/Create IP addresses under a specific subnet """ subnet_model = Subnet class SubnetListCreateView(BaseSubnetListCreateView): """ List/Create subnets """ queryset = Subnet.objects.all() class SubnetView(BaseSubnetView): """ View for retrieving, updating or deleting a subnet instance. """ queryset = Subnet.objects.all() class IpAddressView(BaseIpAddressView): """ View for retrieving, updating or deleting a IP address instance. """ queryset = IpAddress.objects.all() class ImportSubnetView(BaseImportSubnetView): """ View for importing a subnet from csv/xls/xlsx file. """ subnet_model = Subnet queryset = Subnet.objects.none() class ExportSubnetView(BaseExportSubnetView): """ View for exporting a subnet to a csv file. """ subnet_model = Subnet queryset = Subnet.objects.none() import_subnet = ImportSubnetView.as_view() export_subnet = ExportSubnetView.as_view() request_ip = RequestIPView.as_view() subnet_list_create = SubnetListCreateView.as_view() subnet = SubnetView.as_view() ip_address = IpAddressView.as_view() subnet_list_ipaddress = SubnetIpAddressListCreateView.as_view() get_first_available_ip = AvailableIpView.as_view() <file_sep>django>=1.11,<2.3 swapper>=1.1.0 openwisp-utils>=0.3,<0.4 djangorestframework>=3.7,<3.11 xlrd>=1.1.0
f99d8510634bf91b8c1c2b200fbf6be46ca19649
[ "JavaScript", "Python", "Text" ]
17
Python
nikitaermishin/django-ipam
3d563b771c1faa8c362608954fdadce77a6b19c7
a299052171b986a7d4c6e5cb64bf3e2ac703c7c1
refs/heads/master
<repo_name>PrototypeX29A/epong<file_sep>/src/EPongStelModule.hpp /* * Copyright (C) 2007 <NAME> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef EPONGSTELMODULE_HPP_ #define EPONGSTELMODULE_HPP_ #include "StelModule.hpp" #include <QFont> #include "VecMath.hpp" //! This is an example of a plug-in which can be dynamically loaded into stellarium class EPongStelModule : public StelModule { public: EPongStelModule(); virtual ~EPongStelModule(); /////////////////////////////////////////////////////////////////////////// // Methods defined in the StelModule class virtual void init(); virtual void update(double) {;} virtual void draw(StelCore* core); virtual double getCallOrder(StelModuleActionName actionName) const; private: // Font used for displaying our text QFont font; }; #include "fixx11h.h" #include <QObject> #include "StelPluginInterface.hpp" //! This class is used by Qt to manage a plug-in interface class EPongStelModuleStelPluginInterface : public QObject, public StelPluginInterface { Q_OBJECT Q_INTERFACES(StelPluginInterface) public: virtual StelModule* getStelModule() const; virtual StelPluginInfo getPluginInfo() const; }; class PongEvent { public: float time; char type; }; class PongBall { public: void move(double alpha); void create(); Vec3f pos; Vec3f normal; char event; //double event_time; bool alive; double moved; void handle_event(PongEvent*, double); private: void get_next_event(PongEvent*, double); }; #endif /*EPONGSTELMODULE_HPP_*/ <file_sep>/src/EPongStelModule.cpp /* * Copyright (C) 2007 <NAME> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "StelProjector.hpp" #include "StelNavigator.hpp" #include "StelPainter.hpp" #include "StelApp.hpp" #include "StelCore.hpp" #include "StelLocaleMgr.hpp" #include "StelModuleMgr.hpp" #include "EPongStelModule.hpp" #include <QDebug> #define BALLS 100 // better divisble by 4 //Vec3f ballPos[BALLS]; //Vec3f ballNormal[BALLS]; //char ballEvent[BALLS]; //double eventTime[BALLS]; PongBall *ball[BALLS]; PongEvent *pevent[BALLS]; static double lastTime; enum { BALL_CREATE, BALL_COLLIDE, BALL_BOUNCE }; #define PI 3.1415927 #define HTT 4.0 // Time in seconds a ball needs to travel 180 degrees /************************************************************************* This method is the one called automatically by the StelModuleMgr just after loading the dynamic library *************************************************************************/ StelModule* EPongStelModuleStelPluginInterface::getStelModule() const { return new EPongStelModule(); } StelPluginInfo EPongStelModuleStelPluginInterface::getPluginInfo() const { StelPluginInfo info; info.id = "EPongStelModule"; info.displayedName = "EPong World test plugin"; info.authors = "Stellari<NAME>"; info.contact = "www.stellarium.org"; info.description = "An minimal plugin example."; return info; } Q_EXPORT_PLUGIN2(EPongStelModule, EPongStelModuleStelPluginInterface) /************************************************************************* Constructor *************************************************************************/ EPongStelModule::EPongStelModule() { setObjectName("EPongStelModule"); font.setPixelSize(25); } /************************************************************************* Destructor *************************************************************************/ EPongStelModule::~EPongStelModule() { } /************************************************************************* Reimplementation of the getCallOrder method *************************************************************************/ double EPongStelModule::getCallOrder(StelModuleActionName actionName) const { if (actionName==StelModule::ActionDraw) return StelApp::getInstance().getModuleMgr().getModule("NebulaMgr")->getCallOrder(actionName)+10.; return 0; } /************************************************************************* Init our module *************************************************************************/ void EPongStelModule::init() { qDebug() << "init called for EPongStelModule"; //time = 0; lastTime = StelApp::getTotalRunTime(); int i; for(i = 0; i < BALLS; i++) { ball[i] = new PongBall(); ball[i]->pos.set(0.0f, 0.0f, 1.0f); ball[i]->normal.set(sin(2.0f * PI * i/BALLS), cos(2.0f * PI * i / BALLS), 0.0f); ball[i]->alive = 0; pevent[i] = new PongEvent(); pevent[i]->type = BALL_CREATE; pevent[i]->time = lastTime + HTT * (i % (BALLS / 4)) / (BALLS / 4); printf("HTT: %f, i:%d\n", HTT, i); printf("Ball creation of Ball %i at %f\n", i, pevent[i]->time); } } inline void PongBall::move(double alpha) { double x,y,z; double s,c,t; s = sin(alpha); c = cos(alpha); //printf("s = %f, c = %f\n", s,c); t = 1.0f - c; x = pos[0] * (t * normal[0] * normal[0] + c) + pos[1] * (t * normal[0] * normal[1] - s * normal[2]) + pos[2] * (t * normal[0] * normal[2] + s * normal[1]); y = pos[0] * (t * normal[0] * normal[2] + s * normal[2]) + pos[1] * (t * normal[1] * normal[1] + c) + pos[2] * (t * normal[1] * normal[2] - s * normal[0]); z = pos[0] * (t * normal[0] * normal[2] - s * normal[1]) + pos[1] * (t * normal[1] * normal[2] + s * normal[0]) + pos[2] * (t * normal[2] * normal[2] + c); pos.set(x,y,z); //printf("x = %f, y = %f, z = %f\n",pos[0], pos[1], pos[2]); } void PongBall::handle_event(PongEvent *event, double time) { printf("Time: %f\n", time); if (this->alive) this->move((time - this->moved)/HTT * PI); switch (event->type) { case BALL_CREATE: printf("\tCreate ball\n"); this->alive = 1; this->moved = time; break; case BALL_BOUNCE: printf("\tBounce ball\n"); this->normal[0] = - this->normal[0]; this->normal[1] = - this->normal[1]; this->moved = time; break; default: break; } this->get_next_event(event, time); } double arccos(double x) { if (x > 1.0) return 0.0; if (x < -1.0) return PI; return acos(x); } double get_bounce_time(PongBall *ball) { printf("px: %f, py: %f, pz: %f, nx: %f, ny: %f, nz: %f\n", ball->pos[0], ball->pos[1], ball->pos[2], ball->normal[0], ball->normal[1], ball->normal[2]); printf("foo: %f, arccos(-1.0): %f\n", (ball->normal[1] * ball->pos[0] - ball->normal[0] * ball->pos[1]), arccos(-1.0)); /* cos (alpha) = n * p */ return HTT * arccos(ball->normal[1] * ball->pos[0] - ball->normal[0] * ball->pos[1]) / PI; } void PongBall::get_next_event(PongEvent *event, double now) { event->type = BALL_BOUNCE; double delta = get_bounce_time(this); event->time = now + delta; printf("Setting bounce time to %f\n",delta); } void handle_events(double time) { //printf("enter handle\n"); int first; double first_time; do { first = BALLS; int i; for (i = 0; i < BALLS; i++) { if (pevent[i]->time < time) { if ((first == BALLS) || ((pevent[i]->time) < first_time)) { first = i; first_time = pevent[i]->time; } } } if (first < BALLS) { ball[first]->handle_event(pevent[first], first_time); /* printf("Time: %f\n", first_time); switch (pevent[first]->type) { case BALL_CREATE: printf("\tCreate ball\n"); ball[first]->alive = 1; ball[first]->moved = first_time; break; case BALL_BOUNCE: printf("\tBounce ball\n"); // ball->advance_to(first_time); ball[first]->normal[0] = - ball[first]->normal[0]; ball[first]->normal[1] = - ball[first]->normal[1]; ball[first]->moved = first_time; break; default: break; } get_next_event(pevent[first], ball[first], first_time); */ } } while (first != BALLS); //printf("leave handle\n"); } /************************************************************************* *************************************************************************/ void EPongStelModule::draw(StelCore* core) { double currentTime = StelApp::getTotalRunTime(); handle_events(currentTime); Vec3f xy; StelProjectorP prj = core->getProjection(StelCore::FrameAltAz); StelPainter painter(prj); painter.setColor(1,1,1,1); painter.setFont(font); int i; for (i = 0; i<BALLS; i++) { if (ball[i]->alive == 1) { ball[i]->move((currentTime - ball[i]->moved)/HTT * PI); ball[i]->moved = currentTime; } prj->project(ball[i]->pos, xy); painter.drawCircle(xy[0], xy[1], 10); //qDebug() << "end of drawing epong"; ball[i]->pos.normalize(); ball[i]->normal.normalize(); } lastTime = currentTime; }
a86acd5ba2ed015b4915a78e8c6b0d6f0a26a8ed
[ "C++" ]
2
C++
PrototypeX29A/epong
271d68fb56c48e8999358f29d0ce828f6d40dfab
1fa609a771b2380cb7ce57f42a009b3f90d3223f
refs/heads/master
<file_sep># A-2019-backend ## Overview * The App server will send an url of the image to the backend using JSON format. * The backend will download this image on the server and call the **color** recognition part to get the color result of this image. * The backend will use this color result to match the good facts in our kb, and see if there is good matching color, and if there exists matching color, then we try to find whether there exists such cloth that has this color. If not, then we just randomly recommend the clothes to the user based on other contraints we have in our knowledge base. And currently our constraints are based on the weather, occasion, color and what clothes the user already has in their wardrobe. ## Installation ### Configure AMS Server * We use Amazon GPU server because we have ML model, the one we have is [p2.xlarge model](https://console.aws.amazon.com/ec2/v2/home?region=us-east-1#Instances:sort=availabilityZone). * After you have this server, download the private key from the AWS website, keep it in somewhere in your local desktop. (In my case, I store it in ~/Downloads) * Open the terminal in your computer, and run the following command. Type "yes" for the second command. ```sh $ cd Downloads/ $ ssh -i "GPU-FashionAI.pem" ubuntu@ec2-52-71-250-83.compute-1.amazonaws.com ``` ### Run Django Apps on server * First, you need to activate the environment in order to run our app. To do this, type below command. This environment is pre-installed by AWS, so it's much more convenient. ```sh $ source activate pytorch_p36 ``` * Clone the repository to the server. (In my case, I put it inside ~/django-apps/testsite/) ```sh $ git clone https://github.com/nuvention-web/A-2019-backend.git $ cd django-apps/testsite/ ``` * After you finish the above procedure, you can run the django backend server by typing the below command: ```sh $ python manage.py runserver 0:8000 ``` There is another way to run server, the above one will disconnect from time to time. The below one will suspend the server and will not disconnect from time to time. ```sh $ nohup python manage.py runserver 0:8000 & ``` ## Contact If you need our AWS Server account information or there is problem running the server, please contact: <NAME> <<EMAIL> > <file_sep>from TRE.dds import * _attributes_ = ['plays-piano', 'plays-harp', 'smooth-talker', 'likes-gambling', 'likes-animals'] _objects_ = ['groucho', 'harpo', 'chico'] _attributes_ = ['jacket', 'pants'] _objects_ = ['red', 'black', 'green'] def makeAttributeChoiceSets(attributes, objects): """ Each attribute is assumed to apply to exactly one of the objects :param attributes: :param objects: :return: """ choiceSets = [] for attribute in attributes: attributeSet = [] for object in objects: attributeSet.append({attribute : object}) choiceSets.append(attributeSet) return choiceSets def ex1 (debugging = False): inLtre(createLtre(title="Ex1", debugging = debugging)) forms = ['(rassert! (:not (plays-piano plays-harp)))', '(rassert! (:not (plays-piano smooth-talker)))', '(rassert! (:not (plays-harp smooth-talker)))', '(rassert! (:not (likes-money likes-gambling)))', '(rassert! (:not (likes-gambling likes-animals)))', '(rassert! (:not (smooth-talker likes-gambling)))', '(rassert! (same-entity likes-animals plays-harp))', '(rassert! (:not (likes-animals groucho)))', '(rassert! (:not (smooth-talker harpo)))', '(rassert! (plays-piano chico))', '(rule ((:not (?attribute1 ?attribute2)) (?attribute1 ?obj) (?attribute2 ?obj)) (rassert! (:not (:and (:not (?attribute1 ?attribute2)) (?attribute1 ?obj) (?attribute2 ?obj)))))'] forms = [ '(rassert! (plays-piano sally))', '(rassert! (plays-harp sally))', '(rule ((plays-piano ?a) (plays-harp ?b)) (when (eql ?a ?b) (rassert! (:not (:and (plays-piano ?a) (plays-harp ?b))))))'] #runForms(myglobal._ltre_, forms) ### These rules and facts are the finally ones!!! forms = [ '(rule ((plays-piano ?a) (plays-harp ?b)) (when (eql ?a ?b) (rassert! (:not ((plays-piano ?a) (plays-harp ?b))))))', '(rule ((plays-piano ?a) (smooth-talker ?b)) (when (eql ?a ?b) (rassert! (:not ((plays-piano ?a) (smooth-talker ?b))))))', '(rule ((plays-harp ?a) (smooth-talker ?b)) (when (eql ?a ?b) (rassert! (:not ((plays-harp ?a) (smooth-talker ?b))))))', '(rule ((likes-money ?a) (likes-gambling ?b)) (when (eql ?a ?b) (rassert! (:not ((likes-money ?a) (likes-gambling ?b))))))', '(rule ((likes-gambling ?a) (likes-animals ?b)) (when (eql ?a ?b) (rassert! (:not ((likes-gambling ?a) (likes-animals ?b))))))', '(rule ((smooth-talker ?a) (likes-gambling ?b)) (when (eql ?a ?b) (rassert! (:not ((smooth-talker ?a) (likes-gambling ?b))))))', '(rassert! (same-entity likes-animals plays-harp))', '(rassert! (:not (likes-animals groucho)))', '(rassert! (:not (smooth-talker harpo)))', '(rassert! (plays-piano chico))', '(rule ((same-entity ?a1 ?a2) (?a1 ?obj)) (rassert! (:implies ((same-entity ?a1 ?a2) (?a1 ?obj)) (?a2 ?obj))))', '(rassert! (likes-animals chico))', ] forms = [ '(rassert! (:not ((jacket red) (pants green))))', '(rassert! (:not ((jacket green) (pants red))))' ] runForms(myglobal._ltre_, forms) # ddSearch & making Choice Sets choiceSets = makeAttributeChoiceSets(_attributes_, _objects_) #print(choiceSets) myglobal.num = 0 myglobal.ans = {} ddSearch(choiceSets) return myglobal.ans # ============ Test for get not dbclass facts #dbclass = getDbClass('plays-piano', myglobal._ltre_) #for data in dbclass.notFacts: # print(data) def repl(prompt='ltre.py> '): """ A prompt-read-eval-print loop. :param prompt: :return: """ while True: val = input(prompt) if val == 'ex1()': ex1() elif val == 'ex1(True)': ex1(True) elif val == 'showRules()': showRules() elif val == 'showData()': showData() if __name__ == '__main__': print(makeAttributeChoiceSets(attributes=_attributes_, objects=_objects_)) ex1() #print('======== Show Rules ========') #showRules() #print('======== Show Facts ========') #showData() #repl() <file_sep>from TRE import myglobal from TRE.ltinter import * import TRE.lrules as rules from TRE.lunify import * import warnings Symbol = str # A Lisp Symbol is implemented as a Python str myglobal._lenv_ = None class DbClass(object): def __init__(self, name=None, ltre=None, facts=[], rules=[], notFacts=[]): self.name = name self.ltre = ltre self.facts = facts self.rules = rules self.notFacts = notFacts def showData(): """ Print out whole facts :return: counter """ counter = 0 for key,dbclass in myglobal._ltre_.dbclassTable.items(): for datum in dbclass.facts: counter += 1 print("Fact #", counter, "=>", datum) return counter def getDbClass(fact, ltre, flag=0): if fact == None: warnings.warn("nil can't be a dbclass!") elif isinstance(fact, list) and (not isinstance(fact[0], list)) and flag == 0: return getDbClass(fact[0], ltre, flag) elif len(fact) > 1 and isinstance(fact[0], list): tmpLst = [] flag = 1 # means need to construct tuple used as dbclass name # assume that only will appear secondary level list for lst in fact: tmpLst.append(lst[0]) return getDbClass(tuple(tmpLst), ltre, flag) else: dbclass = ltre.dbclassTable[fact] if fact in ltre.dbclassTable else None if dbclass != None: return dbclass else: dbclass = DbClass(name=fact, ltre=ltre, facts=[], rules=[], notFacts=[]) ltre.dbclassTable[fact] = dbclass return dbclass def getCandidates(pattern, ltre=None): """ Retrieve all facts from the dbclass of a given pattern :param pattern: :param ltre: :return: """ #print('pattern => ', pattern) #print('getDbclass => ', getDbClass(pattern, ltre).name) if ltre == None: ltre = myglobal._ltre_ dbclass = getDbClass(pattern, ltre) facts = [] if isinstance(dbclass.name, tuple): idx = 0 for item in dbclass.name: facts.append([]) for item in dbclass.name: # if it starts with '?', then retrieve all the facts, # because we don't know which one to match if isVariable(item): for key, dbclass in ltre.dbclassTable.items(): for datum in dbclass.facts: facts[idx].append(datum) else: for fact in getDbClass(item, ltre).facts: facts[idx].append(fact) idx += 1 return facts else: return getDbClass(pattern, ltre).facts # Installing new facts def assertFact(fact, ltre=None): if ltre == None: ltre = myglobal._ltre_ #print('assertFact fact = ', fact) #### Store the False facts explicitly (like false node) if fact[0] == ':not': if insertNoGoodFact(fact[1:][0], ltre) == True: rules.tryRules(fact, ltre) if insertFact(fact, ltre) == True: # When it isn't already there rules.tryRules(fact, ltre) # run the rules on it def insertFact(fact, ltre): """ Insert a single fact into the database :param fact: :param ltre: :return: """ dbclass = getDbClass(fact, ltre) if fact not in dbclass.facts: if ltre.debugging: print(ltre, 'Inserting',fact,'into database.') dbclass.facts.append(fact) return True return False def insertNoGoodFact(nogoodfact, ltre): """ Insert a single not fact into the database :param nogoodfact: :param ltre: :return: """ dbclass = getDbClass(nogoodfact, ltre) if nogoodfact not in dbclass.notFacts: if ltre.debugging: print(ltre, 'Inserting',nogoodfact,'into database.') dbclass.notFacts.append(nogoodfact) return True return False if __name__ == '__main__': a = [1,3,4] b = [[1,2,3], [1,3,4]] print(a in b)<file_sep>from TRE import ldata from TRE.ltinter import * from TRE.ldata import * from TRE.lunify import * import copy import operator as op Symbol = str # A Lisp Symbol is implemented as a Python str List = list # A Lisp List is implemented as a Python list class Rule(object): def __init__(self, counter=0, dbclass=None, trigger=None, body=None, environment={}, label=[]): self.counter = counter self.dbclass = dbclass self.trigger = trigger self.body = body self.environment = environment self.label = label ################ Global Environment def standard_env(): "An environment with some Lisp standard procedures." env = {} env.update({ 'mod':op.mod, '+':op.add, '-':op.sub, '*':op.mul, '/':op.truediv, '>':op.gt, '<':op.lt, '>=':op.ge, '<=':op.le, '=':op.eq, 'eql':op.eq }) return env global_env = standard_env() def showRules(): """ Print a list of all rules within the default ltre. :return: """ counter = 0 for key,dbclass in myglobal._ltre_.dbclassTable.items(): #print('dbclass name => ', dbclass.name) #print('dbclass rules => ', dbclass.rules) for rule in dbclass.rules: counter += 1 printRule(rule) return counter def tokenize(chars: str) -> list: return chars.replace('(', '( ').replace(')', ' )').split() def parse(program: str): return read_from_tokens(tokenize(program)) def read_from_tokens(tokens: list): if len(tokens) == 0: raise SyntaxError('unexpected EOF') token = tokens.pop(0) if token == '(': L = [] while tokens[0] != ')': L.append(read_from_tokens(tokens)) tokens.pop(0) return L elif token == ')': raise SyntaxError('unexcepted )') else: return atom(token) def atom(token: str): try: return int(token) except ValueError: try: return float(token) except ValueError: return Symbol(token) #### eval def eval(x, env=global_env): if x == None: return # all values in the parse result list are symbol! if x[0] == Symbol('rule'): addRule(x[1], x[2:]) elif x[0] == Symbol('assert!'): ldata.assertFact(x[1:][0]) elif x[0] == Symbol('rassert!'): ldata.assertFact(x[1:][0]) elif isinstance(x, Symbol): # variable reference if x in env: return env[x] else: return x elif not isinstance(x, List): # constant literal return x elif x[0] == 'when': (_, test, conseq) = x exp = (conseq if eval(test, env) else None) return eval(exp, env) else: # (proc arg...) proc = eval(x[0], env) args = [eval(exp, env) for exp in x[1:]] return proc(*args) def addRule(trigger, body): # First build the struct myglobal._ltre_.rule_counter += 1 rule = Rule(trigger=trigger, body=body, counter=myglobal._ltre_.rule_counter, environment=myglobal._lenv_) # Now index it dbclass = ldata.getDbClass(trigger, myglobal._ltre_) dbclass.rules.append(rule) rule.dbclass = dbclass #print("====== debugging the ltre with New Rule =======") #print('get candidates => ', getCandidates(trigger, myglobal._ltre_)) #printRule(rule) # Go into the database and see what it might trigger on #print('candidates', getCandidates(trigger, myglobal._ltre_)) #for candidate in getCandidates(trigger, myglobal._ltre_): #tryRuleOn(rule, candidate, myglobal._ltre_) constructCandidates(ldata.getCandidates(trigger, myglobal._ltre_), rule, 0, len(trigger), myglobal._ltre_) def constructCandidates(candidates, rule, idx, level, ltre, ans=[]): # like using dfs to construct the whole candidats facts within a list (list of lists) if idx == level: tryRuleOn(rule, ans, ltre) return for candidate in candidates[idx]: ans.append(candidate) constructCandidates(candidates, rule, idx+1, level, ltre, ans) ans.pop() def printRule(rule): """ Print representation of rule :param rule: :return: """ print("Rule #", rule.counter, rule.trigger, rule.body) def tryRules(fact, ltre): #### Used for testing if fact == ['likes-animals', 'chico']: #print('tryRules Fact => ', fact) #print('getCandidateRules => ', getCandidateRules(fact, ltre)) pass for rule in getCandidateRules(fact, ltre): #printRule(rule) #tryRuleOn(rule, fact, ltre) constructCandidates(ldata.getCandidates(rule.trigger, ltre), rule, 0, len(rule.trigger), ltre) def getCandidateRules(fact, ltre): """ Return lists of all applicable rules for a given fact :param fact: :param ltre: :return: """ ### store all the rules that this fact might trigger rules = [] for key,dbclass in myglobal._ltre_.dbclassTable.items(): #print('dbclass name => ', dbclass.name) if dbclass.rules != [] and (fact[0] in dbclass.name or any(isVariable(x) for x in dbclass.name)): for rule in dbclass.rules: rules.append(rule) #print('rules???') #printRule(rule) return rules def tryRuleOn(rule, fact, ltre): """ Try a single rule on a single fact If the trigger matches, queue it up :param rule: :param fact: :param ltre: :return: """ #print('tryRuleOn ====== ') #print('rule trigger => ', rule.trigger, ' fact => ', fact) #print('rule environment => ', rule.environment) #print('rule len => ', rule.trigger) #print('fact len => ', fact) if len(rule.trigger) != len(fact): return None else: #print('fact => ', fact) #print('rule trigger => ', rule.trigger) #print('rule environment => ', rule.environment) ##### it seems that we have to clear the environment??? bindings = unify(fact, rule.trigger, {}) #print('bindings ???? ', bindings) if bindings != None: enqueue([rule.body, bindings], ltre) def runRules(ltre): counter = 0 #print('runRules length ===> ', len(ltre.queue)) while len(ltre.queue) > 0: rulePair = dequeue(ltre) counter += 1 runRule(rulePair, ltre) if ltre.debugging: print('Total', counter, 'rules run!') # It's a LIFO queue def enqueue(new, ltre): ltre.queue.append(new) def dequeue(ltre): if len(ltre.queue) > 0: return ltre.queue.pop() else: return None def runRule(pair, ltre): """ Here pair is ([body], {bindings}) :param pair: :param ltre: :return: """ myglobal._lenv_ = pair[1] myglobal._ltre_ = ltre ltre.rules_run += 1 #print("======= run Rule Part =========") #print('body ===> ', pair[0]) #print('bindings => ', pair[1]) newBody = copy.deepcopy(pair[0]) newBody[0] = bindVar(newBody[0], pair[1]) #print('newnewnew body => ', newBody[0]) eval(newBody[0]) def bindVar(lst, bindings): for item in lst: for key, value in bindings.items(): if key in item: item[item.index(key)] = value if any(isinstance(item, list) for i in item): item = bindVar(item, bindings) return lst if __name__ == '__main__': forms = ['(rule (implies ?ante ?conse) (rule ?ante (assert! ?conse)))', '(rule (not (not ?x)) (assert! ?x))'] """ for form in forms: print('form => ', form) print("tokenize result ======>") print(tokenize(form)) print("parse result =====> ") print(parse(form)) """<file_sep>import cv2 import numpy as np import json def getColor(img_path, colorTbl): im = cv2.imread(img_path) h, w, c = im.shape cReg = im[int(0.45 * h):int(0.55 * h), int(0.45 * w):int(0.55 * w)] rgbAvg = [np.mean(cReg[:, :, 2]), np.mean(cReg[:, :, 1]), np.mean(cReg[:, :, 0])] minVal = 255 * 255 * 3 color = None rgb = None for k in colorTbl: v = colorTbl[k] tmpVal = 0 for i in range(3): tmpVal = tmpVal + (v[i] - rgbAvg[i]) * (v[i] - rgbAvg[i]) if tmpVal < minVal: minVal = tmpVal color = k rgb = v return color, rgb def getColorTable(ct_path): with open(ct_path) as jsonFile: colorTbl = json.load(jsonFile) return colorTbl def getColorMapping(color): json = { 'red': ['LightPink', 'Pink', 'Crimson', 'HotPink', 'DeepPink', 'Orchid', 'Thistle', 'Plum', 'Magenta', 'DarkMagenta', 'PeachPuff', 'LightSalmon', 'OrangeRed', 'DarkSalmon', 'Tomato', 'MistyRose', 'LightCoral', 'RosyBrown', 'IndianRed', 'Red', 'FireBrick', 'DarkRed'], 'purple': ['LavenderBlush', 'PaleVioletRed', 'MediumVioletRed', 'Violet', 'Purple', 'MediumOrchid', 'DarkViolet', 'DarkOrchid', 'Indigo', 'BlueViolet', 'MediumPurple'], 'blue': ['MediumSlateBlue', 'SlateBlue', 'DarkSlateBlue', 'Lavender', 'Blue', 'MediumBlue', 'MidnightBlue', 'DarkBlue', 'Navy', 'RoyalBlue', 'CornflowerBlue', 'LightSteelBlue', 'DodgerBlue', 'AliceBlue', 'SteelBlue', 'LightSkyBlue', 'SkyBlue', 'DeepSkyBlue', 'LightBlue', 'PowderBlue', 'CadetBlue', 'Azure', 'PaleTurquoise', 'Aqua', 'DarkTurquoise', 'MediumTurquoise', 'Aquamarine', 'MediumAquamarine'], 'gray': ['SlateGray', 'LightSlateGray', 'DarkSlateGray', 'Gainsboro', 'LightGrey', 'Silver', 'DarkGray', 'Gray', 'DimGray'], 'black': ['Black'], 'green': ['LightCyan', 'Cyan', 'DarkCyan', 'Teal', 'LightSeaGreen', 'Turquoise', 'MediumSpringGreen', 'SpringGreen', 'MediumSeaGreen', 'SeaGreen', 'LightGreen', 'PaleGreen', 'DarkSeaGreen', 'LimeGreen', 'Lime', 'ForestGreen', 'Green', 'DarkGreen', 'Chartreuse', 'LawnGreen', 'GreenYellow', 'DarkOliveGreen', 'YellowGreen', 'OliveDrab', 'Olive'], 'white': ['GhostWhite', 'MintCream', 'Honeydew', 'Beige', 'Ivory', 'FloralWhite', 'OldLace', 'BlanchedAlmond', 'NavajoWhite', 'AntiqueWhite', 'Snow', 'White', 'WhiteSmoke', ], 'yellow': ['LightGoldenrodYellow', 'LightYellow', 'Yellow', 'DarkKhaki', 'LemonChiffon', 'PaleGoldenrod', 'Khaki', 'Gold', 'Cornsilk', 'Goldenrod', 'DarkGoldenrod', 'Wheat', 'Moccasin', 'Orange', 'PapayaWhip', 'Tan', 'BurlyWood', 'Bisque', 'DarkOrange', 'Linen', 'Peru', 'Seashell', 'Sienna', 'Salmon', 'Maroon'], 'brown': ['Chocolate', 'SandyBrown', 'SaddleBrown', 'Coral', 'Brown', ] } for key, value in json.items(): if color in value: return key def CalHSV(rgbR, rgbG, rgbB): maxRGB = max(rgbR, rgbG, rgbB) minRGB = min(rgbR, rgbG, rgbB) if maxRGB == minRGB: hsbH = 0.0 elif maxRGB == rgbR and rgbG >= rgbB: hsbH = 60 * (rgbG - rgbB) / (maxRGB - minRGB) elif maxRGB == rgbR and rgbG < rgbB: hsbH = 60 * (rgbG - rgbB) / (maxRGB - minRGB) + 360 elif maxRGB == rgbG: hsbH = 60 * (rgbB - rgbR) / (maxRGB - minRGB) + 120 elif maxRGB == rgbB: hsbH = 60 * (rgbR - rgbG) / (maxRGB - minRGB) + 240 if maxRGB == 0: hsbS = 0.0 else: hsbS = 1 - minRGB / maxRGB hsbV = maxRGB return [hsbH, hsbS, hsbV] def CalColorGrade(hsv1, hsv2): if abs(hsv1[0] - hsv2[0]) < 128: delH = abs(hsv1[0] - hsv2[0]) else: delH = 256 - abs(hsv1[0] - hsv2[0]) delS = abs(hsv1[1] - hsv2[1]) delV = abs(hsv1[2] - hsv2[2]) return CalHueGrade(delH) + CalSaturGrade(delS) + CalVGrade(delV) def CalHueGrade(delH): return -1.0 * delH / 128.0 + 1 def CalSaturGrade(delS): if delS <= 128: return 1.0 else: return -1.0 * delS / 128.0 + 255.0 / 128.0 def CalVGrade(delV): return delV / 512.0 + 0.5 if __name__ == '__main__': colorTbl = getColorTable('color.json') print(colorTbl) color, rgb = getColor('../image/yellow_collarless.png', colorTbl) print('color => ', color) print('rgb => ', rgb) hsv = CalHSV(rgb[0], rgb[1], rgb[2]) print('hsv => ', hsv) <file_sep>from utils import colorDetect colorTbl = colorDetect.getColorTable('../utils/color.json') print(colorTbl) color, rgb = colorDetect.getColor('../image/img1.png', colorTbl) color = colorDetect.getColorMapping(color) print('color => ', color)<file_sep>from utils import colorDetect from utils import weather import random def selectMatchCloth(user, temperature, hsv, matchType, colorTbl): possible_answer = calWeatherScore(user, temperature, matchType) matchCloth = None maxScore = 0.0 for key, item in user.val()['items'].items(): if item and item['type'] == matchType: tcolor = item['color'] rgb = colorTbl[tcolor] hsv2 = colorDetect.CalHSV(rgb[0], rgb[1], rgb[2]) score = colorDetect.CalColorGrade(hsv, hsv2) if key in possible_answer: score += possible_answer[key] if score > maxScore: maxScore = score matchCloth = item return matchCloth, maxScore def calWeatherScore(user, temperature, matchType): possible_answer = {} for key, item in user.val()['items'].items(): if item == None or item['type'] != matchType: continue possible_answer[key] = 0 if matchType == 'tops': if temperature < -10.0: if 'coat_length' in item: if (item['coat_length'] == 'High Waist Length' or item['coat_length'] == 'Knee Length' or item['coat_length'] == 'Long Length' or item['coat_length'] == 'Ankle&Floor Length'): possible_answer[key] += 10.0 elif item['coat_length'] == 'Regular Length': possible_answer[key] += 8.0 elif item['coat_length'] == 'Midi Length': possible_answer[key] += 7.0 elif item['coat_length'] == 'Micro Length': possible_answer[key] += 2.0 if 'sleeve_length' in item: if item['sleeve_length'] == 'Extra Long Sleeves': possible_answer[key] += 10.0 elif item['sleeve_length'] == 'Long Sleeves': possible_answer[key] += 9.0 elif -10.0 <= temperature < 0: if 'coat_length' in item: if (item['coat_length'] == 'High Waist Length' or item['coat_length'] == 'Knee Length' or item['coat_length'] == 'Regular Length' or item['coat_length'] == 'Long Length' or item['coat_length'] == 'Ankle&Floor Length'): possible_answer[key] += 10.0 elif item['coat_length'] == 'Midi Length': possible_answer[key] += 8.0 elif item['coat_length'] == 'Micro Length': possible_answer[key] += 2.0 if 'sleeve_length' in item: if (item['sleeve_length'] == 'Extra Long Sleeves' or item['sleeve_length'] == 'Long Sleeves'): possible_answer[key] += 10.0 else: possible_answer[key] += 0.0 elif 0.0 <= temperature < 10.0: if 'coat_length' in item: if (item['coat_length'] == 'Regular Length' or item['coat_length'] == 'Midi Length'): possible_answer[key] += 10.0 elif (item['coat_length'] == 'High Waist Length' or item['coat_length'] == 'Long Length' or item['coat_length'] == 'Knee Length' or item['coat_length'] == 'Ankle&Floor Length'): possible_answer[key] += 9.0 elif item['coat_length'] == 'Micro Length': possible_answer[key] += 8.0 elif 'sleeve_length' in item: if item['sleeve_length'] == 'Long Sleeves': possible_answer[key] += 10.0 elif item['sleeve_length'] == 'Extra Long Sleeves': possible_answer[key] += 8.0 elif item['sleeve_length'] == 'Wrist Length': possible_answer[key] += 6.0 elif 10.0 <= temperature < 20.0: if 'coat_length' in item: if item['coat_length'] == 'Micro Length': possible_answer[key] += 10.0 elif item['coat_length'] == 'Regular Length': possible_answer[key] += 7.0 elif item['coat_length'] == 'Midi Length': possible_answer[key] += 6.0 elif (item['coat_length'] == 'High Waist Length' or item['coat_length'] == 'Knee Length'): possible_answer[key] += 5.0 elif item['coat_length'] == 'Long Length': possible_answer[key] += 4.0 elif item['coat_length'] == 'Ankle&Floor Length': possible_answer[key] += 3.0 if 'skirt_length' in item: if (item['skirt_length'] == 'Short Length' or item['skirt_length'] == 'Ankle Length'): possible_answer[key] += 7.0 elif (item['skirt_length'] == 'Knee Length' or item['skirt_length'] == 'Midi Length'): possible_answer[key] += 8.0 elif item['skirt_length'] == 'Floor Length': possible_answer[key] += 5.0 if 'sleeve_length' in item: if item['sleeve_length'] == 'Sleeveless': possible_answer[key] += 7.0 elif (item['sleeve_length'] == 'Cup Sleeves' or item['sleeve_length'] == 'Wrist Length'): possible_answer[key] += 8.0 elif (item['sleeve_length'] == 'Short Sleeves' or item['sleeve_length'] == '3/4 Sleeves'): possible_answer[key] += 9.0 elif item['sleeve_length'] == 'Long Sleeves': possible_answer[key] += 3.0 elif item['sleeve_length'] == 'Extra Long Sleeves': possible_answer[key] += 1.0 elif 20.0 <= temperature < 30.0: if 'coat_length' in item: if (item['coat_length'] == 'High Waist Length' or item['coat_length'] == 'Long Length' or item['coat_length'] == 'Ankle&Floor Length'): possible_answer[key] += 0.0 elif item['coat_length'] == 'Regular Length': possible_answer[key] += 6.0 elif item['coat_length'] == 'Micro Length': possible_answer[key] += 5.0 elif (item['coat_length'] == 'Knee Length' or item['coat_length'] == 'Midi Length'): possible_answer[key] += 1.0 if 'skirt_length' in item: if (item['skirt_length'] == 'Short Length' or item['skirt_length'] == 'Knee Length'): possible_answer[key] += 9.0 elif item['skirt_length'] == 'Midi Length': possible_answer[key] += 8.0 elif item['skirt_length'] == 'Ankle Length': possible_answer[key] += 6.0 elif item['skirt_length'] == 'Floor Length': possible_answer[key] += 3.0 if 'sleeve_length' in item: if item['sleeve_length'] == 'Sleeveless': possible_answer[key] += 9.0 elif (item['sleeve_length'] == 'Cup Sleeves' or item['sleeve_length'] == 'Short Length' or item['sleeve_length'] == 'Elbow Sleeves'): possible_answer[key] += 10.0 elif item['sleeve_length'] == '3/4 Sleeves': possible_answer[key] += 7.0 elif item['sleeve_length'] == 'Wrist Length': possible_answer[key] += 5.0 else: possible_answer[key] += 0.0 elif 30.0 <= temperature < 40.0: if 'coat_length' in item: if item['coat_length'] == 'Micro Length': possible_answer[key] += 2.0 if 'skirt_length' in item: if item['skirt_length'] == 'Short Length': possible_answer[key] += 10.0 elif item['skirt_length'] == 'Knee Length': possible_answer[key] += 9.0 elif item['skirt_length'] == 'Midi Length': possible_answer[key] += 8.0 elif item['skirt_length'] == 'Ankle Length': possible_answer[key] += 3.0 elif item['skirt_length'] == 'Floor Length': possible_answer[key] += 1.0 if 'sleeve_length' in item: if item['sleeve_length'] == 'Sleeveless': possible_answer[key] += 10.0 elif (item['sleeve_length'] == 'Cup Sleeves' or item['sleeve_length'] == 'Short Length'): possible_answer[key] += 9.0 elif item['sleeve_length'] == 'Elbow Sleeves': possible_answer[key] += 8.0 elif item['sleeve_length'] == '3/4 Sleeves': possible_answer[key] += 7.0 elif item['sleeve_length'] == 'Wrist Length': possible_answer[key] += 6.0 if matchType == 'bottoms': if temperature < -10.0 or -10.0 <= temperature < 0.0: if 'pant_length' in item: if item['pant_length'] == 'Full Length': possible_answer[key] += 10.0 elif 0.0 <= temperature < 10.0: if 'pant_length' in item: if item['pant_length'] == 'Full Length': possible_answer[key] += 10.0 elif item['pant_length'] == 'Cropped Pant': possible_answer[key] += 5.0 elif item['pant_length'] == '3/4 Length': possible_answer[key] += 3.0 elif item['pant_length'] == 'Mid Length': possible_answer[key] += 2.0 elif item['pant_length'] == 'Short Pant': possible_answer[key] += 1.0 elif 10.0 <= temperature < 20.0: if 'pant_length' in item: if item['pant_length'] == 'Full Length': possible_answer[key] += 9.0 elif item['pant_length'] == 'Cropped Pant': possible_answer[key] += 10.0 elif item['pant_length'] == '3/4 Length': possible_answer[key] += 7.0 elif item['pant_length'] == 'Mid Length': possible_answer[key] += 6.0 elif item['pant_length'] == 'Short Pant': possible_answer[key] += 5.0 elif 20.0 <= temperature < 30.0: if 'pant_length' in item: if item['pant_length'] == 'Full Length': possible_answer[key] += 6.0 elif item['pant_length'] == 'Cropped Pant': possible_answer[key] += 8.0 elif item['pant_length'] == '3/4 Length': possible_answer[key] += 8.0 elif item['pant_length'] == 'Mid Length': possible_answer[key] += 8.0 elif item['pant_length'] == 'Short Pant': possible_answer[key] += 8.0 elif 30.0 <= temperature < 40.0: if 'pant_length' in item: if item['pant_length'] == 'Full Length': possible_answer[key] += 4.0 elif item['pant_length'] == 'Cropped Pant': possible_answer[key] += 7.0 elif item['pant_length'] == '3/4 Length': possible_answer[key] += 8.0 elif item['pant_length'] == 'Mid Length': possible_answer[key] += 9.0 elif item['pant_length'] == 'Short Pant': possible_answer[key] += 10.0 return possible_answer def calScoreBetweenClothes(cloth, matchCloth, type): score = 0 if type == 'formal': if 'lapel_design' in cloth: if cloth['lapel_design'] == 'Shawl Collar': score = 10.0 if 'pant_length' in matchCloth: if matchCloth['pant_length'] == 'Full Length': score += 10.0 elif matchCloth['pant_length'] == 'Cropped Pant': score += 9.0 elif type == 'semiformal': if 'lapel_design' in cloth: if cloth['lapel_design'] == 'Notched': score = 10.0 if 'pant_length' in matchCloth: if matchCloth['pant_length'] == 'Full Length': score += 8.0 elif matchCloth['pant_length'] == 'Cropped Pant': score += 10.0 elif type == 'casual': if 'lapel_design' in cloth: if (cloth['lapel_design'] == 'Collarless' or cloth['lapel_design'] == 'Plus Size Shawl'): score = 10.0 if 'pant_length' in matchCloth: if matchCloth['pant_length'] == 'Full Length': score += 5.0 elif matchCloth['pant_length'] == 'Cropped Pant': score += 7.0 elif matchCloth['pant_length'] == 'Short Pant': score += 10.0 return score def calOccasionScore(user, colorTbl): formal = -1 formalDress = [] formalTop = [] formalBottoms = [] semiformal = -1 semiformalDress = [] semiformalTop = [] semiformalBottoms = [] casual = -1 casualDress = [] casualDressTop = [] casualDressBottoms = [] temperature = weather.getWeatherInfo() for key, item in user.val()['items'].items(): if item == None: continue if item['type'] == 'tops': tcolor = item['color'] rgb = colorTbl[tcolor] hsv = colorDetect.CalHSV(rgb[0], rgb[1], rgb[2]) matchCloth, matchScore = selectMatchCloth(user, temperature, hsv, 'bottoms', colorTbl) tmpFormal = calScoreBetweenClothes(item, matchCloth, 'formal') tmpSemiFormal = calScoreBetweenClothes(item, matchCloth, 'semiformal') tmpCasual = calScoreBetweenClothes(item, matchCloth, 'casual') if tmpFormal > formal or formal == -1: formal = tmpFormal formalTop.clear() formalTop.append(item) formalBottoms.clear() formalBottoms.append(matchCloth) formalDress = [formalTop, formalBottoms] elif tmpFormal == formal: formalTop.append(item) formalBottoms.append(matchCloth) formalDress = [formalTop, formalBottoms] if tmpSemiFormal > semiformal or semiformal == -1: semiformal = tmpSemiFormal semiformalTop.clear() semiformalTop.append(item) semiformalBottoms.clear() semiformalBottoms.append(matchCloth) semiformalDress = [semiformalTop, semiformalBottoms] elif tmpSemiFormal == semiformal: semiformalTop.append(item) semiformalBottoms.append(matchCloth) semiformalDress = [semiformalTop, semiformalBottoms] if tmpCasual > casual or casual == -1: casual = tmpCasual casualDressTop.clear() casualDressTop.append(item) casualDressBottoms.clear() casualDressBottoms.append(matchCloth) casualDress = [casualDressTop, casualDressBottoms] elif tmpCasual == casual: casualDressTop.append(item) casualDressBottoms.append(matchCloth) casualDress = [casualDressTop, casualDressBottoms] if len(formalDress[0]) > 1: randInt = random.randint(0, len(formalDress[0])-1) formalDress = [formalTop[randInt], formalBottoms[randInt]] if len(semiformalDress[0]) > 1: randInt = random.randint(0, len(semiformalDress[0])-1) semiformalDress = [semiformalTop[randInt], semiformalBottoms[randInt]] if len(casualDress[0]) > 1: randInt = random.randint(0, len(casualDress[0]) - 1) casualDress = [casualDressTop[randInt], casualDressBottoms[randInt]] return [formalDress, semiformalDress, casualDress]<file_sep>from TRE.ltinter import createLtre global _ltre_ global _lenv_ _ltre_ = createLtre(title = "Name for the default ltre") _lenv_ = {} global num num = 0 global ans ans = {}<file_sep>import numbers Symbol = str # A Lisp Symbol is implemented as a Python str def isVariable(x): """ True if x is a pattern variable :param x: :return: """ if isinstance(x, Symbol) and x[0] == '?': return True return False def unify(a, b, bindings = {}): """ Unify <a> with <b>, returning a new set of bindings if successful, None represents :fail. :param a: :param b: :param bindings: :return: """ if bindings == None: return None elif a == b: return bindings elif isVariable(a): return unifyVariable(a, b, bindings) elif isVariable(b): return unifyVariable(b, a, bindings) elif (not (isinstance(a, list))) or (not (isinstance(b, list))): return None else: if len(a) != len(b): return None elif len(a) == 1: return unify(a[0], b[0], bindings) else: return unify(a[1:], b[1:], unify(a[0], b[0], bindings)) def unifyVariable(var, exp, bindings): """ Binds variable with value :param var: :param exp: :param bindings: :return: """ binding = None if var in bindings: binding = bindings[var] if binding != None: return unify(binding, exp, bindings) elif freeInVar(var, exp, bindings): bindings[var] = exp return bindings else: return None def freeInVar(var, exp, bindings): """ Returns [] if <var> occurs in <exp>, assuming <bindings> :param var: :param exp: :param bindings: :return: """ if isinstance(exp, numbers.Number) or len(exp) == 0: return True elif var == exp: return False elif isVariable(exp): if exp in bindings: return freeInVar(var, bindings[exp], bindings) else: return True elif not isinstance(exp, list): return True elif freeInVar(var, exp[0], bindings): if len(exp) > 1: return freeInVar(var, exp[1:], bindings) else: return True else: return None if __name__ == '__main__': # Test case #1 - expects None (Fail) pat = [['plays-piano', '?a'], ['plays-harp', '?b']] obj = [['plays-piano', 'sam'], ['plays-harp', 'sam']] print(unify(pat, obj)) """ # Test case #2 - expects {'?x': ['a', 'b']} pat = '?x' obj = ['a', 'b'] print(unify(pat, obj)) #pat = ['?y', '?x'] #obj = ['a', 'b'] #print(unify(pat, obj)) print(Symbol(0)) print(isVariable(0)) """ a1 = ('a', 'b', '?x') print(any(isVariable(a) for a in a1))<file_sep>def getUserByName(db, username): all_users = db.child("users").get() for user in all_users.each(): if username == user.val()['username']: print('success!!!') return user return None<file_sep>import pyrebase from utils import firebaseConfig # Temporarily replace quote function def noquote(s): return s pyrebase.pyrebase.quote = noquote def initializeFB(): firebase = pyrebase.initialize_app(firebaseConfig.config) #print('firebase => ', firebase) db = firebase.database() return db if __name__ == '__main__': db = initializeFB() allUsers = db.child('users') print(allUsers.get().val()) query = db.child("users").order_by_child("username") query = query.get() print('type allUsers => ', type(allUsers)) print('query => ', query)<file_sep># 前端传过来的时候是 JSON 格式 # 然后在这里构建 RULE,进行分词 # 获取到结果,返回给 API<file_sep>import warnings from TRE.ldata import * from TRE.lrules import * import copy def solveCryptarithmeticProblem(): sendMoreMoney = [ ['column 1 D E Y'], ['column 2 N R E'], ['column 3 E O N'], ['column 4 S M O'], ['column 5 :blank :blank M'], ['leftmost-column 5'] ] choiceSets = makeLetterChoiceSets(sendMoreMoney) return choiceSets def makeLetterChoiceSets(problem): """ Form a possible choice sets letters :param problem: :return: """ choiceSets = [] for letter in set(extractProblemLetters(problem)): dict = {} letterSet = [] for i in range(0, 10): letterSet.append({letter: i}) choiceSets.append(letterSet) print(choiceSets) return choiceSets def extractProblemLetters(problem): """ Extract all letters inside the problem except ':blank' :param problem: :return: """ letters = [] for line in problem: for letter in line[0].split()[1:]: if letter != ':blank' and letter.isalpha(): letters.append(letter) return letters # ================= Useless above ============================ global tmpEnv def ddSearch(choiceSets, level=0, stack=[[]], ltre=[], debugging=False): #print('level ==> ', level) if choiceSets == None or choiceSets == []: print('***********************************************************') print('A feasible ddsearch solution is:') print('level =', level, ' stack =', stack[level-1]) myglobal.ans[myglobal.num] = stack[level-1] myglobal.num += 1 return choices = choiceSets[0] for choice in choices: if len(stack) >= level + 1: if level == 0: stack[level] = [] stack[level].append(reformatPhrase(choice)) else: stack[level] = copy.deepcopy(stack[level-1]) stack[level].append(reformatPhrase(choice)) ltre.append(copy.deepcopy(myglobal._ltre_)) else: stack.append([]) stack[level] = copy.deepcopy(stack[level-1]) stack[level].append(reformatPhrase(choice)) ltre.append(copy.deepcopy(ltre[level-1])) # if true, then ddsearch, otherwise, contradition!!! if checkContradictionAssumptions(level, stack[level], ltre[level], debugging) == False\ and withContradictionHandler(level, stack[level], ltre[level], debugging) == False: ddSearch(choiceSets[1:], level+1, stack, ltre, debugging) def withContradictionHandler(level, stack, ltre, debugging=False): for assumption in stack: tmpEnv = ltre #print('assumption => ', assumption) #print('tmpEnv => ', tmpEnv) assertFact(assumption, tmpEnv) runRules(tmpEnv) if checkContradictionAssumptions(level, stack, ltre, debugging) == True: return True return False def checkContradictionAssumptions(level, stack, ltre, debugging=False): #print('level =', level, 'stack =', stack) dbclass = getDbClass(':not', ltre) flag = False for nogoodfacts in dbclass.facts: #print('nogoodfact => ', nogoodfacts[1:][0]) if isinstance(nogoodfacts[1:][0][0], list): tmpflag = False for nogoodfact in nogoodfacts[1:][0]: if nogoodfact not in stack: tmpflag = True break if tmpflag == False: flag = True if debugging: printContradictionInfo(level, stack, nogoodfacts[1:][0]) else: nogoodfact = nogoodfacts[1:][0] if nogoodfact in stack: flag = True if debugging: printContradictionInfo(level, stack, nogoodfact) if flag == True: break return True if flag == True else False def printContradictionInfo(level, stack, assumption): print('=================================================') print('Making Contradition!!!!!!') print('level = ', level, ' stack = ', stack) tmp = [':not'] tmp.append(assumption) print('Assumption:', assumption, ' Facts: ', tmp) #### Need to be modified!!! Because different phrase has different format!!!!!! #### def reformatPhrase(choice): phrases = [] for attribute, object in choice.items(): return parse('('+attribute+' '+object+')') if __name__ == '__main__': #solveCryptarithmeticProblem() #choiceSets = solveCryptarithmeticProblem() #ddSearch(choiceSets) ss = [':not', [['likes-gambling', '?a'], ['likes-animals', '?b']]] print(ss[1:][0]) ss = [':not', ['likes-gambling', '?a']] print(ss[1:][0])<file_sep>import operator global facts class ColorsDbClass(object): def __init__(self, fact=[], popularity=None): self.fact = fact self.popularity = popularity ## General rules about colors facts = [ {'fact': [':not', ['red', 'green']]}, {'fact': [':not', ['green', 'blue']]}, {'fact': [':not', ['red', 'blue']]}, {'fact': [':not', ['purple', 'blue']]}, {'fact':['black', '*'], 'popularity': 0.80}, {'fact': ['white', '*'], 'popularity': 0.95}, {'fact': ['gray', 'white'], 'popularity': 0.93}, ] # if has weather, we can use implies => to infer about the suitable color in specific season notLst = [] x = [] for fact in facts: if fact['fact'][0] == ':not': notLst.append(fact['fact'][1:][0]) else: if 'popularity' in fact: p1 = ColorsDbClass(fact = fact['fact'], popularity=fact['popularity']) else: p1 = ColorsDbClass(fact = fact['fact']) x.append(p1) #print('facts => ', x) #print('notfacts => ', notLst) sorted_x = sorted(x, key=operator.attrgetter('popularity'), reverse=True) #print('sort_ed x => ', sorted_x) for fact in sorted_x: p1 = fact print('fact => ', p1.fact) print('popularity => ', p1.popularity) print('===============') def createKB(): notLst = [] x = [] for fact in facts: if fact['fact'][0] == ':not': notLst.append(fact['fact'][1:][0]) else: if 'popularity' in fact: p1 = ColorsDbClass(fact=fact['fact'], popularity=fact['popularity']) else: p1 = ColorsDbClass(fact=fact['fact']) x.append(p1) sorted_x = sorted(x, key=operator.attrgetter('popularity'), reverse=True) kb_facts = {"color_popularity_sorted": sorted_x, "color_nogood_facts": notLst} return kb_facts<file_sep>from TRE import myglobal from TRE.lrules import * class Ltre(object): def __init__(self, title=None, dbclassTable={}, debugging=False, queue=[], rule_counter=0, rules_run=0): self.title = title self.dbclassTable = dbclassTable self.debugging = debugging self.queue = queue self.rule_counter = rule_counter self.rules_run = rules_run def inLtre(ltre): """ Set the default ltre to a new value. :param ltre: :return: """ myglobal._ltre_ = ltre def createLtre(title, debugging=False): """ :param title: :param debugging: :return: create a logic-based Tiny Rule Engine """ return Ltre(title=title, dbclassTable={}, debugging=debugging) def runForms(ltre, forms): for form in forms: eval(parse(form)) runRules(ltre) """ if __name__ == "__main__": inTre(createTre("Ex1")) print(myglobal._tre_.title) """ <file_sep># import firebase_admin # from firebase_admin import credentials, firestore # cred = credentials.Certificate('../profashion-firebase-adminsdk-vf1ta-35e8761196.json') # prof_app = firebase_admin.initialize_app(cred) # db = firestore.client() # print(prof_app.project_id) # doc_ref = db.collection('profashion').document('users') # try: # doc = doc_ref.get('users') # print('document data : {}'.format(doc.to_dict())) # except: # print('document is not found!') import pyrebase config = { "apiKey": "<KEY>", "authDomain": "profashion.firebaseapp.com", "databaseURL": "https://profashion.firebaseio.com", "storageBucket": "profashion.appspot.com", "serviceAccount": "../profashion-firebase-adminsdk-vf1ta-35e8761196.json" } firebase = pyrebase.initialize_app(config) db = firebase.database() all_users = db.child("users").get() tmp_user = None for user in all_users.each(): print('user key???? = ', user.key()) users_by_name = db.child("users").order_by_child("username").equal_to("Cathy").get() print('userByName => ', users_by_name.key()) for user in users_by_name.each(): print('user key => ', user.key()) print('user value => ', user.val())<file_sep>from __future__ import absolute_import import json from django.http import HttpResponse from rest_framework.views import APIView import os from utils import initializeFirebase from utils import colorDetect import prediction import math import random from utils import weather from utils import clothMatching def urllib_download(IMAGE_URL, USER_KEY): from urllib.request import urlretrieve urlretrieve(IMAGE_URL, './image/' + USER_KEY + '.png') class ClothInfo(APIView): def post(self, request, *args, **kwargs): jsonstr = str(request.body, 'utf-8') req = json.loads(jsonstr) os.makedirs('./image/', exist_ok=True) ### Initialize Firebase, should use cache to store that later. db = initializeFirebase.initializeFB() dbKey = req['dbkey'] user = None for tuser in db.child("users").get(): if tuser.key() == dbKey: user = tuser break img_url = req['img_url'] urllib_download(img_url, user.key()) clothType = req['type'] if clothType == 'tops': matchType = 'bottoms' else: matchType = 'tops' ### Call the color matching algorithm colorTbl = colorDetect.getColorTable('./utils/color.json') color, rgb = colorDetect.getColor('./image/' + user.key() + '.png', colorTbl) hsv = colorDetect.CalHSV(rgb[0], rgb[1], rgb[2]) print('#### Start ML Part ####') answer_lst = prediction.predict(["collar_design_labels", "skirt_length_labels", "coat_length_labels", "lapel_design_labels", "neck_design_labels", "neckline_design_labels", "pant_length_labels", "sleeve_length_labels"], ["./image/"+ user.key() +".png"]) print('answer_lst => ', answer_lst) req['labels'] = { 'collar_design_labels': answer_lst[0]['collar_design_labels'], 'skirt_length_labels': answer_lst[0]['skirt_length_labels'], 'coat_length_labels': answer_lst[0]['coat_length_labels'], 'lapel_design_labels': answer_lst[0]['lapel_design_labels'], 'neck_design_labels': answer_lst[0]['neck_design_labels'], 'neckline_design_labels': answer_lst[0]['neckline_design_labels'], 'pant_length_labels': answer_lst[0]['pant_length_labels'], 'sleeve_length_labels': answer_lst[0]['sleeve_length_labels'] } ############### ML Part End ################ ### Matching Clothes ALG temperature = weather.getWeatherInfo() req['matchCloth'] = clothMatching.selectMatchCloth(user, temperature, hsv, matchType, colorTbl) req['labels']['colorPredict'] = color print('req => ', req) return HttpResponse(json.dumps(req)) class RecommendPurchase(APIView): def post(self, request, *args, **kwargs): jsonstr = str(request.body, 'utf-8') req = json.loads(jsonstr) db = initializeFirebase.initializeFB() dbKey = req['dbkey'] user = None for tuser in db.child("users").get(): if tuser.key() == dbKey: user = tuser break clothID = req['clothID'] cloth = None for item in user.val()['items'].items(): if item[0] == clothID: cloth = item[1] clothType = cloth['type'] if clothType == 'tops': matchType = 'bottoms' else: matchType = 'tops' colorTbl = colorDetect.getColorTable('./utils/color.json') clothColor = cloth['color'] if clothColor in colorTbl: clothColorRGB = colorTbl[clothColor] else: clothColorRGB = None hsv = None if clothColorRGB: hsv = colorDetect.CalHSV(clothColorRGB[0], clothColorRGB[1], clothColorRGB[2]) maxScore = 0.0 matchCloth = None ### save the color already exists to the list for item in user.val()['items'].values(): if item and item['type'] == matchType: tcolor = item['color'] if tcolor != None: rgb = colorTbl[tcolor] hsv2 = colorDetect.CalHSV(rgb[0], rgb[1], rgb[2]) score = colorDetect.CalColorGrade(hsv, hsv2) if score > maxScore: maxScore = score matchCloth = item req['matchCloth'] = matchCloth matchColor = matchCloth['color'] if matchColor in colorTbl: matchColorRGB = colorTbl[matchColor] else: matchColorRGB = None minDistance = 1<<31 allPossibleClothes = [] for item in db.child("purchase").get(): if item.val() == None: continue itemColor = item.val()['color'] if itemColor in colorTbl: itemRGB = colorTbl[itemColor] else: itemRGB = None distance = math.sqrt((matchColorRGB[0] - itemRGB[0]) ** 2 +\ (matchColorRGB[1] - itemRGB[1]) ** 2 +\ (matchColorRGB[2] - itemRGB[2]) ** 2) if distance < minDistance and item.val()['type'] == matchType: minDistance = distance allPossibleClothes.clear() allPossibleClothes.append(item.val()) elif distance == minDistance and item.val()['type'] == matchType: allPossibleClothes.append(item.val()) if allPossibleClothes != []: req['recommendPurchase'] = random.choice(allPossibleClothes) else: req['recommendPurchase'] = None return HttpResponse(json.dumps(req)) class WeatherInfo(APIView): def get(self, request, *args, **kwargs): return HttpResponse(json.dumps(weather.getWeatherInfo())) class GetDailyOutfit(APIView): def post(self, request, *args, **kwargs): jsonstr = str(request.body, 'utf-8') req = json.loads(jsonstr) db = initializeFirebase.initializeFB() dbKey = req['dbkey'] user = None for tuser in db.child("users").get(): if tuser.key() == dbKey: user = tuser break colorTbl = colorDetect.getColorTable('./utils/color.json') [formalDress, semiformalDress, casualDress] = clothMatching.calOccasionScore(user, colorTbl) req['formalDressTop'] = formalDress[0] req['formalDressBottom'] = formalDress[1] req['semiformalDressTop'] = semiformalDress[0] req['semiformalDressBottom'] = semiformalDress[1] req['casualDressTop'] = casualDress[0][0] req['casualDressBottom'] = casualDress[1][0] return HttpResponse(json.dumps(req))<file_sep>import requests import pytemperature def getWeatherInfo(): api_address = 'http://api.openweathermap.org/data/2.5/weather?q=Evanston,us&APPID=00635a2705abb24f3c1e116788d7614e' json_data = requests.get(url=api_address).json() formatted_data = json_data['main'] temperature = pytemperature.k2c(formatted_data['temp']) return round(temperature, 2)<file_sep>from django.conf.urls import url from .views import * urlpatterns = [ url(r'^clothInfo/$', ClothInfo.as_view()), url(r'^purchaseRecommend/$', RecommendPurchase.as_view()), url(r'^weatherInfo/$', WeatherInfo.as_view()), url(r'^dailyOutfit/$', GetDailyOutfit.as_view()) ]
4e927251a393bb75b8b175e91a48e54a7a05d8b8
[ "Markdown", "Python" ]
19
Markdown
nuvention-web/A-2019-backend
8cd3b8c8d60a52b7d019de01d985388fd73be7eb
26adbbdf436bea77b71869ef4af507f94afa210b
refs/heads/main
<file_sep>library(shiny nice) output&fit(extremely nice i liked it ) my roommate is very stupid. he only studys and say his friends that he watch movies. he is very cunning. }) print("naughtyyyyyy")<file_sep>library(shiny) {(uri is very nice movie. i enjoyed very much. }) thank you for reviewing me. i will never forget your help. <file_sep>title: <NAME>ain author:myself remember me always
02264475b37e3e165e63b3aeaacdb91cbf714efe
[ "R", "RMarkdown" ]
3
R
abhinandan1425/developingdataproduct
158b525f419384fee00b6dec56cc289b544f4448
579a12476f982d2a60cdc4f2ef5b66d39a8252f2
refs/heads/master
<file_sep><?php $name = $_POST['name']; if(isset($_POST['comment'])){ if(empty($name)){ echo "<script>alert('Nhập Tên NGười CHơi Để Comment!');</script>"; } else{ $content = $_POST['content-comment']; $timeCMT = date('Y-m-d'); if(isset($_POST['comment'])){ $sqlc = mysqli_query($con,"INSERT INTO comment VALUES('".$name."', '".$content."', '".$timeCMT."', 4)"); } } } ?> <form method="POST"> <input type="text" name="name"> <h4>Viết Bình Luận...<i class="fa fa-pencil"></i></h4> <div class="form-group"> <textarea class="form-control" rows="4" cols="50" name="content-comment"></textarea> </div> <div> <button class="btn btn-primary" name="comment">Comment</button> </div> <?php $sqlcm = mysqli_query($con,"SELECT * FROM comment WHERE idGame = '".$id."'"); while ($result = mysqli_fetch_array($sqlcm)) { ?> <div class="show-comment"> <table> <tr> <td><h6><?= $result['timeCmt'] ?></h6></td> </tr> <tr> <td><h5><?= $result['namePlayer'] ?> : </h5></td> <div id="contentCMT"><td><p><?= $result['contentCmt'] ?></p></td></div> </tr> </table> </div> <?php } ?> </form> <file_sep>var CELL_SIZE = 10; var FPS = 10 ; var WIDTH = 400; var HEIGHT = 400; var score = 0; function Game(canvas_id){ var _pressedKey; var _cols = WIDTH/CELL_SIZE; var _rows = HEIGHT/CELL_SIZE; var _snake = new Snake(_cols,_rows); var _canvas = document.getElementById(canvas_id); var _context = _canvas.getContext('2d'); _context.fillStyle = "black"; var sc = document.getElementById("score"); var _food = {}; var _running = false; var _timer; this.init = function() { _canvas.width = WIDTH; _canvas.height = HEIGHT; _canvas.onkeydown = function(e) { e.preventDefault(); if(e.keyCode == 13) // Enter key { if(!_running) startGame(); } else if(_running) { _pressedKey = e.keyCode; } }; // draw the welcome screen _context.textAlign = "center"; //_context.font = "36px Arial"; //_context.fillText("Canvas Snake v1.0",WIDTH/2,HEIGHT/3); _context.font = "16px Arial"; _context.fillText("Press Enter To Start",WIDTH/2,HEIGHT/2); _context.fillText("Score:"+score,200, 230); } function startGame() { _pressedKey = null; clearInterval(_timer); _snake.init(); createFood(); _running = true; _timer = setInterval(update,1000/FPS); _context.font = "16px Arial"; } function update() { if(!_running) return; _snake.handleKey(_pressedKey); var ret = _snake.update(_food); if(ret==1) { createFood(); score++; sc.innerHTML = score; }else if(ret==2) { // end game _running = false; _context.save(); _context.fillStyle = "rgba(0,0,0,0.2)"; _context.fillRect(0,0,WIDTH,HEIGHT); _context.restore(); _context.fillText("Press Enter To Start",WIDTH/2,HEIGHT/2); _context.fillText('Score:'+score,200, 230); document.getElementById("scGame").value = score; return; } draw(); } function draw(){ _context.beginPath(); _context.clearRect(0,0,WIDTH,HEIGHT); _context.fill(); _snake.draw(_context); // draw food _context.beginPath(); _context.arc((_food.x*CELL_SIZE)+CELL_SIZE/2, (_food.y*CELL_SIZE)+CELL_SIZE/2, CELL_SIZE/2, 0, Math.PI*2, false); _context.fill(); } function createFood() { var x = Math.floor(Math.random()*_cols); var y; do { y = Math.floor(Math.random()*_rows); } while(_snake.collide(x, y)); _food = {x: x, y: y}; } }<file_sep>function Snake(mapCols,mapRows){ // directions var LEFT = 0, UP = 1, RIGHT = 2, DOWN = 3; var direction; // moving direction var data; // snake's body // PROTOTYPES this.init = function(){ var x = 3; var y = 0; data = [ {x: x, y: y}, {x: x-1, y: y}, {x: x-2, y: y} ]; direction = RIGHT; }; this.handleKey = function(key){ // 37: left, 38: up, 39: rigth, 40: down if(key >= 37 && key <=40) { var newdir = key - 37; if(Math.abs(direction-newdir)!=2) // can not turn to the opposite direction direction = newdir; } }; this.draw = function(ctx) { for(var i = 0;i < data.length; i++) ctx.fillRect(data[i].x*CELL_SIZE, data[i].y*CELL_SIZE, CELL_SIZE, CELL_SIZE); }; this.update = function(food){ var x = data[0].x; var y = data[0].y; switch(direction) { case LEFT: x--; break; case UP: y--; break; case RIGHT: x++; break; case DOWN: y++; break; } // eat food: return 1 if(x == food.x && y == food.y) { data.unshift(food); return 1; } // collide: return 2 if(this.collide(x,y)) return 2; // snake move by // adding the head data.unshift({x:x, y:y}); // and cutting the tail data.pop(); // default: return 0 return 0; }; this.collide = function(x, y) { if(x < 0 || x > mapCols-1) return true; if(y < 0 || y > mapRows-1) return true; for(var i = 0; i<data.length; i++) { if(x == data[i].x && y == data[i].y) return true; } return false; } }<file_sep><?php include'connection.php'; ?> <?php $id = $_GET['idGame']; $query = mysqli_query($con, "SELECT * FROM games WHERE idGame = $id"); $row = mysqli_fetch_array($query); if($id) { ?> <a href="$row['play']">chơi</a> <?php } ?><file_sep>-- phpMyAdmin SQL Dump -- version 4.8.5 -- https://www.phpmyadmin.net/ -- -- Máy chủ: 127.0.0.1 -- Thời gian đã tạo: Th1 08, 2020 lúc 07:19 AM -- Phiên bản máy phục vụ: 10.1.39-MariaDB -- Phiên bản PHP: 7.3.5 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Cơ sở dữ liệu: `game` -- -- -------------------------------------------------------- -- -- Cấu trúc bảng cho bảng `comment` -- CREATE TABLE `comment` ( `namePlayer` varchar(30) COLLATE utf8mb4_vietnamese_ci NOT NULL, `contentCmt` varchar(500) COLLATE utf8mb4_vietnamese_ci NOT NULL, `timeCmt` date NOT NULL, `idGame` int(5) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_vietnamese_ci; -- -- Đang đổ dữ liệu cho bảng `comment` -- INSERT INTO `comment` (`namePlayer`, `contentCmt`, `timeCmt`, `idGame`) VALUES ('4', 'phú', '0000-00-00', 2020), ('phú', 'hi', '2020-01-02', 4), ('dương', 'Game Hay Quá!', '2020-01-02', 4); -- -------------------------------------------------------- -- -- Cấu trúc bảng cho bảng `games` -- CREATE TABLE `games` ( `idGame` int(5) NOT NULL, `name` varchar(40) COLLATE utf8mb4_vietnamese_ci NOT NULL, `image` varchar(1000) COLLATE utf8mb4_vietnamese_ci NOT NULL, `category` varchar(30) COLLATE utf8mb4_vietnamese_ci NOT NULL, `view` int(9) NOT NULL, `play` varchar(3000) COLLATE utf8mb4_vietnamese_ci NOT NULL, `tag` varchar(20) COLLATE utf8mb4_vietnamese_ci NOT NULL, `tagSecond` varchar(20) COLLATE utf8mb4_vietnamese_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_vietnamese_ci; -- -- Đang đổ dữ liệu cho bảng `games` -- INSERT INTO `games` (`idGame`, `name`, `image`, `category`, `view`, `play`, `tag`, `tagSecond`) VALUES (1, 'Flappy Bird', 'images/flappy.png', 'Phiêu Lưu', 1090, 'FlappyBird/flappyBird.php', 'flappy', 'bird'), (2, '<NAME> ', 'images/xepgach.jpg', 'Trí Tuệ', 542, 'xephinh/xephinh.php', 'xephinh', ''), (3, 'Hứng Trứng', 'images/hungtrung.png', 'Hành Động', 421, 'egg_game/engGame.php', 'trứng', 'eggs'), (4, 'a hunting snake', 'images/snake.jpg', '<NAME>', 705, 'snake/snake.php', 'snake', 'hunt'); -- -------------------------------------------------------- -- -- Cấu trúc bảng cho bảng `player` -- CREATE TABLE `player` ( `idPlayer` int(5) NOT NULL, `idGame` int(5) NOT NULL, `namePlayer` varchar(30) COLLATE utf8mb4_vietnamese_ci NOT NULL, `score` int(10) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_vietnamese_ci; -- -- Đang đổ dữ liệu cho bảng `player` -- INSERT INTO `player` (`idPlayer`, `idGame`, `namePlayer`, `score`) VALUES (2, 2, '<NAME>', 456), (3, 2, '<NAME>', 789), (6, 2, 'phú', 1000), (7, 2, 'phú', 2000), (8, 2, 'phú', 4444), (26, 4, '<NAME>', 10), (90, 4, 'hưng', 1), (99, 4, 'phú', 10), (102, 4, 'khương', 3), (218, 4, 'phú', 5), (219, 4, 'phú', 5), (220, 4, 'phú', 5), (221, 4, 'phú', 5), (222, 4, 'aka', 10), (223, 4, 'aka', 10), (224, 4, 'phú', 1), (225, 4, 'phú', 1), (226, 4, 'phú', 2), (227, 4, 'phú', 2), (228, 4, 'aka', 3); -- -- Chỉ mục cho các bảng đã đổ -- -- -- Chỉ mục cho bảng `games` -- ALTER TABLE `games` ADD PRIMARY KEY (`idGame`); -- -- Chỉ mục cho bảng `player` -- ALTER TABLE `player` ADD PRIMARY KEY (`idPlayer`); -- -- AUTO_INCREMENT cho các bảng đã đổ -- -- -- AUTO_INCREMENT cho bảng `games` -- ALTER TABLE `games` MODIFY `idGame` int(5) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; -- -- AUTO_INCREMENT cho bảng `player` -- ALTER TABLE `player` MODIFY `idPlayer` int(5) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=229; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>var bird = function(game){ this.game = game; this.image = []; this.img1loaded = false; this.img2loaded = false; this.currentImage = null; this.currentFrame = 0; this.currentImageIndex = 0; this.x = 70; this.y = 0; this.speedY = 0; this.acceleration = 2; this.direction = 'down'; self = this; this.init = function(){ this.loadImage(); } this.loadImage = function(){ var img1 = new Image(); var img2 = new Image(); img1.onload = function(){ self.img1loaded = true; self.currentImage = img1; self.image.push(img1); } img2.onload = function(){ self.img2loaded = true; self.currentImage = img2; self.image.push(img2); } //load all images img1.src = "img/bird1.png"; img2.src = "img/bird2.png"; } this.update = function(){ if(!self.img1loaded || !self.img2loaded){ return; } self.currentFrame++; if(self.currentFrame % 6 == 0){ self.changeImage(); } //forget all stuff above if(this.y <= 600){ if(this.direction=='down'){ this.speedY += this.acceleration; } else{ this.speedY -= this.acceleration; } this.y += this.speedY; } if(this.y > 480){ this.y = 480; } //check gameover if(this.y >=475){ this.game.gameOver = true; } //check hit this.ckeckHitPipe(); } this.ckeckHitPipe = function(){ console.log("y bird:"+Math.floor(this.y)); console.log("y pipe:"+Math.floor(this.game.pipe.y - 230)); if( ( (this.x + 30 > this.game.pipe.x + 320) )&& ( (this.y < this.game.pipe.y - 320) ||(this.y - 147 > this.game.pipe.y) ) ) { this.game.gameOver = true; } } this.flap = function(){ if(this.game.gameOver){ return; } this.speedY = -18; } this.changeImage = function(){ if(this.game.gameOver){ return; } if(this.currentImageIndex == 1){ this.currentImageIndex = 0; } else{ this.currentImageIndex++; } this.currentImage = this.image[this.currentImageIndex]; } this.draw = function(){ if(this.img1loaded && this.img2loaded){ self.game.context.drawImage(self.currentImage, this.x, this.y); } } }<file_sep><?php include'../connection.php'; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <style type="text/css"> body { width: 1100px; margin-left: auto; margin-right: auto; } canvas { } #box { padding: 10px; width: 300px; float: left; } #box2 { width: 202px; height: 401px; float: left; border: 1px solid black; } #box3 { width: 450px; height: 401px; border: 1px solid black; margin-left: 30px; float: left; } </style> <title>Xếp Hình</title> </head> <body> <div id="box"> <?php $query = mysqli_query($con, "SELECT * FROM games WHERE idGame = 2"); $row = mysqli_fetch_array($query); $id = $row['idGame']; ?> <h2>Game: <?=$row['name']?></h2> <h3>Cách Chơi</h3> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. A repudiandae explicabo quasi deserunt esse, voluptatem quos non, dicta, sint illum provident adipisci laudantium et amet doloribus officia porro fugit, aut!</p> <form method="POST" action=""> <input type="button" name="btn" id="btn" value="Chơi" onclick=" new game();"> <div>Điểm Cao: <p></p></div> <input type="text" name="player" id="text1" > <input type="submit" value="Nhập"> <div>Name: <p> <?php $name = $_POST['player']; if (empty($name)) { echo "Name is empty"; } else { echo $name; $sql = mysqli_query($con, "INSERT INTO player(idGame,namePlayer) VALUES($id,N'$name') "); } ?> </p></div> <table border="1"> <tr> <td>Người Chơi</td> <td>Điểm</td> </tr> <?php $sql1 = mysqli_query($con, "SELECT * FROM player ORDER BY score DESC LIMIT 0,5 "); while($row1=mysqli_fetch_array($sql1)){ ?> <tr> <td><?=$row1['namePlayer']?></td> <td><?=$row1['score']?></td> </tr> <?php } ?> </table> </form> </div> <div id="box2"> <canvas id="canvas"></canvas> </div> <div id="box3"> <h2>Comment</h2> <form method="POST" action=""> <div class="form-group"> <textarea class="form-control" rows="4" cols="50" name="content-comment"></textarea> </div> <div> <button class="btn btn-primary" name="comment">Gửi</button> </div> </form> </div> </body> <script type="text/javascript" src="const.js"></script> <script type="text/javascript" src="dot.js"></script> <script type="text/javascript" src="board.js"></script> <script type="text/javascript" src="brick.js"></script> <script type="text/javascript" src="game.js"></script> </html> <file_sep><?php error_reporting(0); if(isset($_GET['muc'])){ $muc = $_GET['muc']; }else{ $muc = "home"; } switch ($muc) { case 'home': include'home.php'; break; case 'hanhdong': include'hanhdong.php'; break; case 'phieuluu': include'phieuluu.php'; break; case 'tritue': include'tritue.php'; break; case 'giaitri': include'giaitri.php'; break; default: aler("Some Thing was Wrong!"); break; } ?> <file_sep>var pipe = function(game){ this.game = game; this.image = null; this.loaded = false; var self = this; this.x = 320; this.y = 100; this.init = function(){ this.loadImage(); } this.loadImage = function(){ this.image = new Image(); this.image.onload = function(){ self.loaded = true; console.log('image loaded'); } this.image.src = "img/pipe2.png"; } this.update = function(){ if(this.game.gameOver){ return; } function TaoSoNgauNhien(min, max){ return Math.floor(Math.random() * (max - min + 1)) + min; } var a = TaoSoNgauNhien(1, 220); this.x-=4; if(this.x == -440){ this.x = 100; this.y = a; } } this.draw = function(){ if(self.loaded==false){ return; } self.game.context.drawImage(this.image, this.x, this.y - 330 -100); self.game.context.drawImage(this.image, this.x, this.y); } }<file_sep><!DOCTYPE html> <html> <head> <title>Web Game</title> <meta charset="UTF-8"> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body> <div id="container"> <div id="header"> <h1>19 Enter Games</h1> </div> <div id="content"> <div id="nav"> <?php include'nav.php'; ?> </div> <div id="main"> <?php include'main.php'; ?> </div> </div> <!--<a href="egg_game/engGame.html">link</a>--> <div id="footer"> <?php include'footer.php'; ?> </div> </div> </body> </html><file_sep>class game { constructor(){ this.canvas = null; this.context = null; this.init(); } init() { this.canvas = document.getElementById("canvas"); this.context = this.canvas.getContext('2d'); this.canvas.height = GAME_HEIGHT; this.canvas.width = GAME_WIDTH; //document.body.appendChild(this.canvas); //create the board this.board = new board(this); //get keyboard this.listenkeyboard(); //create the brick this.brick = new brick(this); //start the game this.startGame(); this.loop(); } listenkeyboard() { document.addEventListener('keydown', (event) => { //console.log(event); switch(event.code){ case 'ArrowDown': this.brick.fall(); break; case 'ArrowLeft': this.brick.moveLeft(); break; case 'ArrowRight': this.brick.moveRight(); break; case 'ArrowUp': this.brick.rotate(); break; } }); } startGame() { //console.log(NUM_COLS-1); setInterval( () => { this.brick.fall(); },500); } createNewBrick() { this.brick = new brick(this); } loop() { console.log('loop'); this.update(); this.draw(); setTimeout(() => this.loop(), 30); } update() { if(this.brick.canFall()&&this.brick.row==20){ this.setTimeout(() => this.loop(), 30); } } clearScreen() { this.context.fillStyle = "#F0F8FF"; this.context.fillRect(0, 0, GAME_WIDTH, GAME_HEIGHT); } draw() { this.clearScreen(); this.board.draw(); this.brick.draw(); } } //var g = new game();<file_sep><?php include'connection.php'; error_reporting(0); ?> <div class="Navigation"> <h3 style="margin-left: 10px;">Navigation</h3> <ul> <li><a class="selected" href="index.php?muc=home">Home</a></li> <li><a class="selected" href="index.php?muc=hanhdong">Hành Động</a></li> <li><a class="selected" href="index.php?muc=phieuluu">Phiêu Lưu</a></li> <li><a class="selected" href="index.php?muc=tritue">Trí Tuệ</a></li> <li><a class="selected" href="index.php?muc=giaitri">Giải Trí</a></li> </ul> </div> <div class="gamePlays"> <h3 style="margin-left: 10px;">Game Chơi Nhiều</h3> <?php $query = mysqli_query($con, "SELECT * FROM games ORDER BY view DESC LIMIT 0,5"); while ( $row = mysqli_fetch_array($query)) { ?> <div class="gameView"> <img src="<?= $row['image'] ?>" width="30px" height="30px"> <a href="index.php?idGame=<?=$row['idGame']?>"><?= $row['name'] ?></a> <h6>Lượt Chơi: <?= $row['view'] ?></h6> </div> <?php } ?> </div> <?php $idGame = $_GET['idGame']; $sql = mysqli_query($con, "UPDATE games SET view=view+1 WHERE idGame = $idGame"); ?> <file_sep><?php include'../connection.php'; error_reporting(0); ?> <html> <head> <title></title> <html lang="en"> <script src="snake.js"></script> <script src="game.js"></script> <script type='text/javascript'> window.onload = function() { var game = new Game("canvas"); game.init(); } </script> <style type="text/css"> body { width: 1200px; background-color: #EEE; margin-left: auto; margin-right: auto; } #container { background-color: white; } #box { padding: 10px; width: 300px; float: left; } #box2 { float: left; } #box3 { width: 400px; height: 401px; border: 1px solid black; margin-left: 10px; float: left; } </style> </head> <body> <div id="container"> <div id="box"> <?php include'box.php'; ?> </div> <div id="box2"> <canvas id="canvas" tabindex="0" style="margin:0px; border: 1px solid"> </canvas> </div> <div id="box3"> <?php include'box3.php'; ?> </div> </body> </html><file_sep><?php include'connection.php' ?> <h2>Home Page</h2> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Deleniti, placeat. Adipisci ducimus, aliquam animi illum sunt repellendus nisi numquam, ut quam maiores natus provident iure consequatur optio, quas incidunt molestias!</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Veniam explicabo laboriosam nam debitis, inventore, itaque nostrum dolore a eligendi dignissimos ex. Perspiciatis voluptates deserunt eos minus laudantium delectus natus dolore.</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tempore voluptates, aliquam cupiditate illum magni earum accusantium reprehenderit consectetur, illo explicabo incidunt consequatur amet? In nisi nihil officia sit laudantium dolor.</p> <h2>Game</h2> <?php $query = mysqli_query($con,"SELECT * FROM games"); while ($row = mysqli_fetch_array($query)) { ?> <div class="showGame"> <img src="<?= $row['image'] ?>" width="200px"> <p><?= $row['name'] ?></p> <p><?= $row['category'] ?></p> <a href="index.php?idGame=<?=$row['idGame']?> ">chơi</a> </div> <?php } ?> <?php $idGame = $_GET['idGame']; switch ($idGame) { case 1: header('location:FlappyBird/flappyBird.php'); break; case '2': header('location:xephinh/xephinh.php'); break; case '3': header('location:egg_game/engGame.php'); break; case '4': header('location:snake/snake.php'); break; default: aler("Lỗi!"); break; } ?> <file_sep>const GAME_HEIGHT = 400; const GAME_WIDTH = 200; const NUM_ROWS = 20; const NUM_COLS = 10; const _ = null; const x = 'x'; const dem = document.getElementById("btn");<file_sep><?php include'connection.php' ?> <h2>GAMES > Phiêu Lưu</h2> <?php $query = mysqli_query($con,"SELECT * FROM games WHERE category LIKE '%Phiêu Lưu%'"); while ($row = mysqli_fetch_array($query)) { ?> <div class="showGame"> <img src="<?= $row['image'] ?>" width="200px"> <p><?= $row['name'] ?></p> <a href="index.php?idGame=<?=$row['idGame']?> ">chơi</a> </div> <?php } ?> <file_sep><?php $query = mysqli_query($con, "SELECT * FROM games WHERE idGame = 4"); $row = mysqli_fetch_array($query); $id = $row['idGame']; ?> <h2>Game: <?=$row['name']?></h2> <h3>Cách Chơi</h3> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. A repudiandae explicabo quasi deserunt esse, voluptatem quos non, dicta, sint illum provident adipisci laudantium et amet doloribus officia porro fugit, aut!</p> <?php $scGame = $_POST['scGame']; echo "test".$scGame; $name = $_POST['player']; $sql = "INSERT INTO player(idGame, namePlayer, score) VALUES('".$id."', N'".$name."', '".$scGame."' )"; if(isset($_POST['btnSubmit'])){ if(!empty($name)){ mysqli_query($con, $sql); } else { echo "<script>alert('Nhập Tên Người Chơi');</script>"; } //echo $dmm; } ?> <form method="POST"> <h3>Tên Người Chơi:</h3><input type="text" name="player" value="<?php echo $name; ?>"> <h3>Điểm: </h3><p id="score" name="score">0</p> <h3>Điểm Cao: </h3> <input type="text" id="scGame" name="scGame" disabled=""> <button type="submit" name="btnSubmit">Lưu Điểm</button> <table border="1"> <tr> <td>Người Chơi</td> <td>Điểm</td> </tr> <?php $sql1 = mysqli_query($con, "SELECT * FROM player WHERE idGame = 4 ORDER BY score DESC LIMIT 0,5 "); while($row1=mysqli_fetch_array($sql1)){ ?> <tr> <td><?=$row1['namePlayer']?></td> <td><?=$row1['score']?></td> </tr> <?php } ?> </table> </form>
83e94a886b4919d61ede390dbdf72ef5dcb464b1
[ "JavaScript", "SQL", "PHP" ]
17
PHP
0nesh/Game
1a9b5ebf523841eff28c03b9bca9de4095606e4c
d3babe3d736909a25564ae5c518f92e231d5baa4
refs/heads/main
<file_sep>import requests import favicon import sys import logging import metadata_parser def write_to_file(file_name, content): f = open(file_name, "a") f.write(content+"\n") f.close() def get_favicon_url(url): fixed_url = "http://{}".format(url).strip() try: icons = favicon.get(fixed_url, timeout=25) icon = icons[0] return icon.url except: logger.info("no favicon fetched for url: {}".format(url)) # <meta property="og:image"> def scrap_images_from_url(url): fixed_url = "http://{}".format(url).strip() rvalue = None try: rvalue = metadata_parser.MetadataParser(url=fixed_url).get_metadata_link('image') except metadata_parser.NotParsableFetchError: logger.info("Exception - no image fetched for url: {}".format(url)) except metadata_parser.NotParsable: logger.info("Exception - no image fetched for url: {}".format(url)) return rvalue # program #config logging logging.basicConfig(filename="log_scrapper.log", format="%(asctime)s %(message)s", filemode='w') logger = logging.getLogger() logger.setLevel(logging.DEBUG) #main loop file_input = sys.argv[1] #file_input = "alexa1M.txt" file_input = file_input.rstrip() #strip input file name file_output = "output.txt" try: logger.debug("opening file {}".format(file_input)) f = open(file_input, "r") url = f.readline() while url: logger.debug("scrapping images from {}".format(url)) image_url = scrap_images_from_url(url) if image_url != None: logger.debug("get favicon image from {}".format(url)) image_url = get_favicon_url(url) if image_url != None: write_to_file(file_output, image_url) url = f.readline() f.close except IOError: logger.error("IOError writing the url: {}".format(url))<file_sep># Data Scrapper ## Program This program receives a file containing website urls that it visits and fetch the images from, finally the program stores the image links on an output file. # Run Python 2.7.16 * libs to install: favicon, metada_parser, requests * run: python <input_file> * log_file: log_scrapper.log * output_file: output.txt
ed47935a89190143c97e136fb62a3446815bc8b6
[ "Markdown", "Python" ]
2
Python
jvarandas/python-web-scrapper
adfdbed0b245e01c72d6f8b8453cfc55ebbf0add
fc097cb6cb8054078fba0c0d35ab03dc95723725
refs/heads/master
<repo_name>as2466967/SafaieA_CIS12_48939<file_sep>/Hmwk/Assignment 1/Script 1.03.php <!doctype html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Using Echo</title> </head> <body> <!-- Script 1.3 - second.php --> <p>This is standard HTML.</p> <?php echo 'This was generated using PHP!'; ?> </body> </html><file_sep>/Hmwk/Assignment 1/Script 1.05.php <!doctype html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Predefined Variables</</title> </head> <body> <?php # Script 1.5 - predefined.php // Create a shorthand version of the variable names: $file = $_SERVER['SCRIPT_FILENAME']; $user = $_SERVER['HTTP_USER_AGENT']; $server = $_SERVER['SERVER_SOFTWARE']; // Print the name of this script: echo "<p>You are running the file:<br /><b>$file</b>.</p>\n"; // Print the user's information: echo "<p>You are viewing this page using:<br /><b>$user</b></p>\n"; // Print the server's information: echo "<p>This server is running: <br /><b>$server</b>.</p>\n"; ?> </body> </html><file_sep>/Hmwk/Assignment 1/Script 1.02.php <!doctype html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Basic PHP Page</title> </head> <body> <!-- Script 1.2 - first.php --> <p>This is standard HTML.</p> <?php ?> </body> </html><file_sep>/Class/3-Truth Table/Truth Table.php <?php /* <NAME> Sept 3rd, 2014 Purpuse: Duplicate Truth TAble */ ?> <!doctype html> <html> <head> <meta charset="utf-8"> <title>Truth Table</title> </head> <body> <?php //echo out a heading echo "<h1> Truth Table<h1/>"; ?> <table width="200" border="1"> <tr> <th>X</th> <th>Y</th> <th>!X</th> <th>!Y</th> <th>X&&Y</th> <th>X||Y</th> <th>X^Y</th> <th>X^Y^Y</th> <th>X^Y^X</th> <th>!(X&&Y)</th> <th>!X||!Y</th> <th>!(X||Y)</th> <th>!X&&!Y</th> </tr> <tr> <?php $x=true; $y=true; echo "<td>".($x?"T":"F")."</td>"; echo "<td>".($y?"T":"F")."</td>"; echo "<td>".(!$x?"T":"F")."</td>"; echo "<td>".(!$y?"T":"F")."</td>"; echo "<td>".($x&&$y?"T":"F")."</td>"; ?> </tr><tr> <?php $y=false; echo "<td>".($x?"T":"F")."</td>"; echo "<td>".($y?"T":"F")."</td>"; echo "<td>".(!$x?"T":"F")."</td>"; echo "<td>".(!$y?"T":"F")."</td>"; echo "<td>".($x&&$y?"T":"F")."</td>"; ?> <tr> </table> </body> </html><file_sep>/Hmwk/Assignment 1/Script 1.04.php <!doctype html> <html> <head> <meta charset="utf-8"> <title>Comments</title> </head> <body> <?php # Script 1.4 - comments.php # Created Sep 01, 2014 # Created by <NAME> # This script does nothing much. echo '<p>This is a line of text.<br /> This is another line of text.</p>'; /* echo 'This line will not be executed.'; */ echo "<p>Now I'm done.</p>"; // End of PHP code. ?> </body> </html><file_sep>/Class/2-Variables/Variables.php <?php /* <NAME> Augest 27th, 2014 Purpose: comments/ Variables */ ?> <!doctype html> <html> <head> <meta charset="utf-8"> <title>Strings and Variables</title> </head> <body> <?php // declare variables $hours=40;// Worked 40 hours $payRate=9;//$'s/hour //calculate the paycheck $grosspay=$hours*$payRate; //output the result echo "<p>Hours worked = $hours (hrs)</p>"; echo '<p>Pay Rate = $$payRate</p>'; echo "<p>Pay check = ".$grosspay.'</p>' ?> </body> </html>
f2d794400a288e6955c92ebb50b458684a3b283a
[ "PHP" ]
6
PHP
as2466967/SafaieA_CIS12_48939
38f4e5e86a2728fd153a88611dad5cdb75a04507
b9ddc3de6b1f6d3451e3d18ca9057bb1e92b8c64
refs/heads/master
<file_sep>Emergency Social Media Trainer is a tool that helps emergency responders practice monitoring social media in a non-emergency setting. The goal of this tool is to help emergency responders understand the types of information they might encounter over social media during an emergency event. <file_sep>class TweetsController < ApplicationController $global_var = 1 $counter = 0 def index $counter = 0 @tweets = Tweet.order(:time => :desc) session[:ids] = @tweets respond_to do |format| format.html format.json { render json: @tweets } end end def create @tweet = Tweet.new respond_to do |format| format.html format.js end end def show @tweet = Tweet.find(params[:id]) render layout: false, json: @tweet end def import tweet_category = TweetCategory.find_by(name: params[:title]) if tweet_category.nil? tweetcat = TweetCategory.new tweetcat.name = params[:title] tweetcat.description = params[:desc] tweetcat.save! tweet_category = TweetCategory.find_by(name: params[:title]) end begin Tweet.import(params[:file],tweet_category) redirect_to root_url, :notice => "Messages Imported!" rescue redirect_to tweets_upload_path, notice: "Invalid CSV file format." end end def setglobal var = params["edit"].keys $global_var = var redirect_to tweets_url end def eachcat @catdata = Tweet.where(tweet_category_id: 2) end def category @data = TweetCategory.all end def upload end def set_counter @counter = 0 end def set_a @twee = Tweet.where(tweet_category_id: $global_var) @oldesttweet = @twee.last render layout: false, json: @twee[$counter] $counter = $counter + 1 end end<file_sep>class WelcomeController < ApplicationController respond_to :xml, :json def index end end
013929dbc15816aedf8936bf02349ba706db0601
[ "RDoc", "Ruby" ]
3
RDoc
venuchitta/EmergencySocialMediaTrainer
89f658910ad46d222ab501430a11457c0b4e7fb1
2aa472cc2456d31a0c58a151178255ea63064245
refs/heads/master
<file_sep>using System.Data.Entity; using CodedHomes.Models; namespace CodedHomes.Data { public class UsersRepository : GenericRepository<User> { public UsersRepository(DbContext context) : base(context) {} } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MESSADIIS.Data { public class MessadiisRepository : IMessadiisRepository { //the goog choice is to create an instance of the db context hihin lol //bonne pratique je préfére because DbContext n'est une classe statique ici lol et // ne le sera jaamais pour moi pour de rire ni abstract, ni extension method avec db context MessadiisContext _ctx; public MessadiisRepository(MessadiisContext ctx) { _ctx = ctx; } public IQueryable<Question> GetQuestions() { //the context is a disposable object return _ctx.Questions; } public IQueryable<Reponse> GetReponsesByQuestion(int QuestionId) { return _ctx.Reponses.Where(r => r.QuestionId == QuestionId); } public bool Save() { try { //retourne an integer of how many request we done return _ctx.SaveChanges() >0 ; } catch (Exception ex) { //TODO log this error return false; } } public bool AddQuestion(Question newQuestion) { try { _ctx.Questions.Add(newQuestion); return true; } catch (Exception ex) { //TODO log this error return false; } } public IQueryable<Question> GetQuestionsInclusReponses() { return _ctx.Questions.Include("Reponses"); } public bool AddReponse(Reponse newReponse) { try { _ctx.Reponses.Add(newReponse); return true; } catch (Exception ex) { //TODO log this error return false; } } } }<file_sep>using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web; namespace MESSADIIS.Data { public class MessadiisContext : DbContext { //we use simply defaultConnectin vs express public MessadiisContext() : base("DefaultConnection") { this.Configuration.LazyLoadingEnabled = false; this.Configuration.ProxyCreationEnabled = false; Database.SetInitializer( new MigrateDatabaseToLatestVersion<MessadiisContext,MessadiisMigrationConfiguration>() ); } public DbSet<Question> Questions{ get; set; } public DbSet<Reponse> Reponses { get; set; } } }<file_sep>using System; using System.Linq; using AWModel; namespace SimpleQueries { class QueryExamples { static void Main() { GetSomeCustomers(); } private static void GetSomeCustomers() { var context = new SalesEntities(); var query = from c in context.Customers orderby c.LastName where c.FirstName=="Robert" select c; var customers =query.ToList(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AccountAtAGlance.Repository { class C_DataContext { } } <file_sep>using EF7Samurai.Domain; using Microsoft.Data.Entity; namespace EF7Samurai.Context { public class SamuraiContext : DbContext { public DbSet<Samurai> Samurais { get; set; } public DbSet<Battle> Battles { get; set; } public DbSet<Quote> Quotes { get; set; } protected override void OnConfiguring(DbContextOptions options) { //options.UseInMemoryStore(); options.UseSqlServer("Server = (localdb)\\mssqllocaldb; Database=EF7Samurai; Trusted_Connection=True;"); base.OnConfiguring(options); } } } <file_sep>-- Demo: GROUP BY clause -- GROUP BY , single Column (notice it isn't ordered) SELECT [sod].[ProductID], SUM([sod].OrderQty) AS [OrderQtyByProdcutId] FROM [sales].[SalesOrderDetail] AS[sod] GROUP By [sod].[ProductID]; -- GROUP BY , single Column ( ordered) SELECT [sod].[ProductID], SUM([sod].OrderQty) AS [OrderQtyByProdcutId] FROM [sales].[SalesOrderDetail] AS[sod] GROUP By [sod].[ProductID] ORDER By [sod].[ProductID]; --GROUP BY, mutli-column , with ordering SELECT [sod].[ProductID], SUM([sod].OrderQty) AS [OrderQtyByProdcutId] FROM [sales].[SalesOrderDetail] AS[sod] GROUP By [sod].[ProductID], [sod].[SpecialOfferID] ORDER By [sod].[ProductID]; <file_sep>using System.Web.Optimization; namespace CodeCamper.Web { public class BundleConfig { public static void RegisterBundles(BundleCollection bundles) { // Force optimization to be on or off, regardless of web.config setting //BundleTable.EnableOptimizations = false; // .debug.js, -vsdoc.js and .intellisense.js files // are in BundleTable.Bundles.IgnoreList by default. // Clear out the list and add back the ones we want to ignore. // Don't add back .debug.js. bundles.IgnoreList.Clear(); bundles.IgnoreList.Ignore("*-vsdoc.js"); bundles.IgnoreList.Ignore("*intellisense.js"); // All application JS files (except mocks") bundles.Add(new ScriptBundle("~/bundles/jsapplibs") // Include all files in the named directory that match "*.js"; // Could include subdirs too by flipping the flag // but not doing so because the only subdir holds mocks // which we would exclude anyway in production. .IncludeDirectory("~/Scripts/app/", "*.js", searchSubdirectories: false)); // the following equivalent file-pattern alternative // could not consider subdirectories if we wanted those //.Include("~/Scripts/app/*.js")); bundles.Add(new ScriptBundle("~/bundles/jsmocks") .IncludeDirectory("~/Scripts/app/mock", "*.js", searchSubdirectories: false)); // Modernizr goes separate since its a shiv bundles.Add(new ScriptBundle("~/bundles/modernizr") .Include("~/Scripts/lib/modernizr-*")); // 3rd Party JavaScript files bundles.Add(new ScriptBundle("~/bundles/jsextlibs") .Include( "~/Scripts/lib/json2.min.js", // IE7 needs this // jQuery and its plugins //"~/Scripts/lib/jquery-1.7.2.min.js", // use CDN instead // jQuery plugins "~/Scripts/lib/activity-indicator.js", "~/Scripts/lib/jquery.mockjson.js", "~/Scripts/lib/TrafficCop.js", "~/Scripts/lib/infuser.js", // depends on TrafficCop // Knockout and its plugins "~/Scripts/lib/knockout-2.1.0.js", "~/Scripts/lib/knockout.validation.js", "~/Scripts/lib/koExternalTemplateEngine.js", "~/Scripts/lib/underscore.min.js", "~/Scripts/lib/moment.js", "~/Scripts/lib/sammy.*", "~/Scripts/lib/amplify.*", "~/Scripts/lib/toastr.js" )); // 3rd Party CSS files bundles.Add(new StyleBundle("~/Content/css") .Include("~/Content/toastr.css") .Include("~/Content/toastr-responsive.css")); // Custom LESS files var lessBundle = new Bundle("~/Content/Less") .Include("~/Content/styles.less"); lessBundle.Transforms.Add(new LessTransform()); lessBundle.Transforms.Add(new CssMinify()); bundles.Add(lessBundle); } } }<file_sep>-- Demo : TOP --No Top SELECT [FirstName], [LastName], [StartDate], [EndDate] FROM [HumanResources].[vEmployeeDepartmentHistory] AS [edh] ORDER By [edh].[StartDate]; --Top Rows SELECT TOP(10) [FirstName], [LastName], [StartDate], [EndDate] FROM [HumanResources].[vEmployeeDepartmentHistory] AS [edh] ORDER By [edh].[StartDate]; SELECT TOP(50) PERCENT [FirstName], [LastName], [StartDate], [EndDate] FROM [HumanResources].[vEmployeeDepartmentHistory] AS [edh] ORDER By [edh].[StartDate]; SELECT TOP(10) WITH TIES [FirstName], [LastName], [StartDate], [EndDate] FROM [HumanResources].[vEmployeeDepartmentHistory] AS [edh] ORDER By [edh].[StartDate];<file_sep>using System.Data.Entity; using Model; using System.Data.Common; using System.Data.Entity.ModelConfiguration.Conventions; using System; using System.Data.Entity.Infrastructure; namespace DataAccess { public class BreakAwayContext : DbContext { public BreakAwayContext() { } public BreakAwayContext(string databaseName) : base(databaseName) { } public BreakAwayContext(DbConnection connection) : base(connection, contextOwnsConnection: false) { } public BreakAwayContext(DbConnection connection, DbCompiledModel model) : base(connection, model, contextOwnsConnection: false) { } public DbSet<Destination> Destinations { get; set; } public DbSet<Lodging> Lodgings { get; set; } public DbSet<Trip> Trips { get; set; } public DbSet<Person> People { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { Console.WriteLine("OnModelCreating called!"); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using Microsoft.AspNet.Mvc; using ASPNET5Samurai.DataModel; using ASPNET5Samurai.Models; // For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860 namespace ASPNET5Samurai.Controllers.Controllers { public class HomeController : Controller { private readonly SamuraiContext _context; public HomeController(SamuraiContext context) { _context=context; } public IActionResult Index() { var samurais = _context.Samurais.ToList(); return View(samurais); } public IActionResult Insert(string name) { _context.Add(new Samurai { Name = name }); _context.SaveChanges(); return RedirectToAction("Index", "Home"); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Model; using DataAccess; using System.Data.Entity; using System.Data.SqlClient; using System.Data.Entity.Infrastructure; using System.Data.SqlServerCe; namespace BreakAwayConsole { class Program { static void Main(string[] args) { Database.SetInitializer( new DropCreateDatabaseIfModelChanges<BreakAwayContext>()); InsertDestination(); } private static void InsertDestination() { var destination = new Destination { Country = "Indonesia", Description = "EcoTourism at its best in exquisite Bali", Name = "Bali" }; using (var context = new BreakAwayContext()) { context.Destinations.Add(destination); context.SaveChanges(); } } private static void InsertTrip() { var trip = new Trip { CostUSD = 800, StartDate = new DateTime(2011, 9, 1), EndDate = new DateTime(2011, 9, 14) }; using (var context = new BreakAwayContext()) { context.Trips.Add(trip); context.SaveChanges(); } } private static void InsertPerson() { var person = new Person { FirstName = "Rowan", LastName = "Miller", SocialSecurityNumber = 12345678, Photo = new PersonPhoto { Photo = new Byte[] { 0 } } }; using (var context = new BreakAwayContext()) { context.People.Add(person); context.SaveChanges(); } } private static void UpdateTrip() { using (var context = new BreakAwayContext()) { var trip = context.Trips.FirstOrDefault(); trip.CostUSD = 750; context.SaveChanges(); } } private static void UpdatePerson() { using (var context = new BreakAwayContext()) { var person = context.People.Include("Photo").FirstOrDefault(); person.FirstName = "Rowena"; if (person.Photo == null) { person.Photo = new PersonPhoto { Photo = new Byte[] { 0 } }; } context.SaveChanges(); } } private static void DeleteDestinationInMemoryAndDbCascade() { int destinationId; using (var context = new BreakAwayContext()) { var destination = new Destination { Name = "<NAME>", Lodgings = new List<Lodging> { new Lodging { Name = "Lodging One" }, new Lodging { Name = "Lodging Two" } } }; context.Destinations.Add(destination); context.SaveChanges(); destinationId = destination.DestinationId; } using (var context = new BreakAwayContext()) { var destination = context.Destinations .Single(d => d.DestinationId == destinationId); context.Destinations.Remove(destination); context.SaveChanges(); } using (var context = new BreakAwayContext()) { var lodgings = context.Lodgings .Where(l => l.DestinationId == destinationId).ToList(); Console.WriteLine("Lodgings: {0}", lodgings.Count); } } private static void InsertLodging() { var lodging = new Lodging { Name = "<NAME>", Destination = new Destination { Name = "Seattle, Washington", Country = "USA" } }; using (var context = new BreakAwayContext()) { context.Lodgings.Add(lodging); context.SaveChanges(); } } private static void InsertResort() { var resort = new Resort { Name = "Top Notch Resort and Spa", MilesFromNearestAirport = 30, Activities = "Spa, Hiking, Skiing, Ballooning", Destination = new Destination { Name = "<NAME>", Country = "USA" } }; using (var context = new BreakAwayContext()) { context.Lodgings.Add(resort); context.SaveChanges(); } } private static void InsertHostel() { var hostel = new Hostel { Name = "AAA Budget Youth Hostel", MilesFromNearestAirport = 25, PrivateRoomsAvailable = false, Destination = new Destination { Name = "Hanksville, Vermont", Country = "USA" } }; using (var context = new BreakAwayContext()) { context.Lodgings.Add(hostel); context.SaveChanges(); } } private static void GetAllLodgings() { var context = new BreakAwayContext(); var lodgings = context.Lodgings.ToList(); foreach (var lodging in lodgings) { Console.WriteLine("Name: {0} Type: {1}", lodging.Name, lodging.GetType().ToString()); } } private static void SpecifyDatabaseName() { using (var context = new BreakAwayContext("BreakAwayStringConstructor")) { context.Destinations.Add(new Destination { Name = "Tasmania" }); context.SaveChanges(); } } private static void ReuseDbConnection() { var cstr = @"Server=.\SQLEXPRESS; Database=BreakAwayDbConnectionConstructor; Trusted_Connection=true"; using (var connection = new SqlConnection(cstr)) { using (var context = new BreakAwayContext(connection)) { context.Destinations.Add(new Destination { Name = "Hawaii" }); context.SaveChanges(); } using (var context = new BreakAwayContext(connection)) { foreach (var destination in context.Destinations) { Console.WriteLine(destination.Name); } } } } static void RunTest() { using (var context = new BreakAwayContext()) { context.Database.Initialize(force: true); context.Destinations.Add(new Destination { Name = "Fiji" }); context.SaveChanges(); } using (var context = new BreakAwayContext()) { if (context.Destinations.Count() == 1) { Console.WriteLine( "Test Passed: 1 destination saved to database"); } else { Console.WriteLine( "Test Failed: {0} destinations saved to database", context.Destinations.Count()); } } } static void GreatBarrierReefTest() { using (var context = new BreakAwayContext()) { var reef = from destination in context.Destinations where destination.Name == "Great Barrier Reef" select destination; if (reef.Count() == 1) { Console.WriteLine("Test Passed: 1 'Great Barrier Reef' destination found"); } else { Console.WriteLine( "Test Failed: {0} 'Great Barrier Reef' destinations found", context.Destinations.Count()); } } } private static void TargetMultipleProviders() { // To run this method you will need to remove the // configuration in TripConfiguration that configures // Trip.Identifier as database generated. This is required // because SQL Compact does not support generating GUIDs var sql_model = GetBuilder().Build( new DbProviderInfo("System.Data.SqlClient", "2008")) .Compile(); var ce_model = GetBuilder().Build( new DbProviderInfo("System.Data.SqlServerCe.4.0", "4.0")) .Compile(); var sql_cstr = @"Server=.\SQLEXPRESS; Database=DataAccess.BreakAwayContext; Trusted_Connection=true"; using (var connection = new SqlConnection(sql_cstr)) { using (var context = new BreakAwayContext(connection, sql_model)) { context.Destinations.Add(new Destination { Name = "Hawaii" }); context.SaveChanges(); } } var ce_cstr = @"Data Source=|DataDirectory|\DataAccess.BreakAwayContext.sdf"; using (var connection = new SqlCeConnection(ce_cstr)) { using (var context = new BreakAwayContext(connection, ce_model)) { context.Database.Initialize(force: true); context.Destinations.Add(new Destination { Name = "Hawaii" }); context.SaveChanges(); } } } private static DbModelBuilder GetBuilder() { var modelBuilder = new DbModelBuilder(); modelBuilder.Entity<EdmMetadata>().ToTable("EdmMetadata"); // Entity Type Configuration modelBuilder.Configurations.Add(new DestinationConfiguration()); modelBuilder.Configurations.Add(new LodgingConfiguration()); modelBuilder.Configurations.Add(new TripConfiguration()); modelBuilder.Configurations.Add(new PersonConfiguration()); modelBuilder.Configurations.Add(new InternetSpecialConfiguration()); modelBuilder.Configurations.Add(new ActivityConfiguration()); modelBuilder.Configurations.Add(new PersonPhotoConfiguration()); modelBuilder.Configurations.Add(new ReservationConfiguration()); // Complex Type Configuration modelBuilder.Configurations.Add(new AddressConfiguration()); modelBuilder.ComplexType<PersonalInfo>(); return modelBuilder; } private static void UseEdmMetadataTable() { using (var context = new BreakAwayContext()) { var modelHash = EdmMetadata.TryGetModelHash(context); Console.WriteLine("Current Model Hash: {0}", modelHash); var databaseHash = context.Set<EdmMetadata>().Single().ModelHash; Console.WriteLine("Current Database Hash: {0}", databaseHash); var compatible = context.Database.CompatibleWithModel(throwIfNoMetadata: true); Console.WriteLine("Model Compatible With Database?: {0}", compatible); } } private static void UseObjectContext() { var builder = GetBuilder(); var cstr = @"Server=.\SQLEXPRESS; Database=BreakAwayObjectContext; Trusted_Connection=true"; using (var connection = new SqlConnection(cstr)) { var model = builder.Build(connection).Compile(); using (var context = model.CreateObjectContext<BreakAwayObjectContext>(connection)) { if (!context.DatabaseExists()) { context.CreateDatabase(); } context.Destinations.AddObject( new Destination { Name = "<NAME>" }); context.SaveChanges(); } } } } } <file_sep>using RibbitMvc.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace RibbitMvc.Data { public interface IUserProfileRepository : IRepository<UserProfile> { } }<file_sep>using CodedHomes.Models; using System.Data.Entity.ModelConfiguration; using System.ComponentModel.DataAnnotations.Schema; namespace CodedHomes.Data.Configuration { public class UserConfiguration : EntityTypeConfiguration<User> { public UserConfiguration() { this.Property(p => p.Id).HasColumnOrder(0); this.Property(p => p.Username) .IsRequired().HasMaxLength(200); this.Property(p => p.FirstName) .IsOptional().HasMaxLength(100); this.Property(p => p.LastName) .IsOptional().HasMaxLength(100); this.HasMany(a => a.Roles).WithMany(b => b.Users).Map(m => { m.MapLeftKey("UserId"); m.MapRightKey("RoleId"); m.ToTable("webpages_UsersInRoles"); }); } } } <file_sep>using Microsoft.Data.Entity.Migrations; using Microsoft.Data.Entity.Migrations.Builders; using Microsoft.Data.Entity.Migrations.Model; using System; namespace ASPNET5Samurai.Migrations { public partial class NicknameAdded : Migration { public override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn("Samurai", "NickName", c => c.String()); } public override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn("Samurai", "NickName"); } } }<file_sep>USE DataBizCustomers; Create table Customer( Id Int ); Create table Orders( Id Int ); create Table CusommerOrders( Customer_Id Int ,Order_Id Int );<file_sep>using Microsoft.Data.Entity.Migrations; using Microsoft.Data.Entity.Migrations.Builders; using Microsoft.Data.Entity.Migrations.Model; using System; namespace ASPNET5Samurai.Migrations { public partial class Initial : Migration { public override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable("Samurai", c => new { Id = c.Int(nullable: false, identity: true), Living = c.Boolean(nullable: false), Name = c.String() }) .PrimaryKey("PK_Samurai", t => t.Id); } public override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable("Samurai"); } } }<file_sep>using Microsoft.Data.Entity.Relational.Migrations; using Microsoft.Data.Entity.Relational.Migrations.Builders; using Microsoft.Data.Entity.Relational.Migrations.MigrationsModel; using System; namespace EF7Samurai.Context.Migrations { public partial class initialModel : Migration { public override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable("Battle", c => new { Id = c.Int(nullable: false, identity: true), EndDate = c.DateTime(nullable: false), Name = c.String(), StartDate = c.DateTime(nullable: false) }) .PrimaryKey("PK_Battle", t => t.Id); migrationBuilder.CreateTable("Quote", c => new { Id = c.Int(nullable: false, identity: true), Text = c.String(), SamuraiId = c.Int(nullable: false) }) .PrimaryKey("PK_Quote", t => t.Id); migrationBuilder.CreateTable("Samurai", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String() }) .PrimaryKey("PK_Samurai", t => t.Id); migrationBuilder.AddForeignKey( "Quote", "FK_Quote_Samurai_SamuraiId", new[] { "SamuraiId" }, "Samurai", new[] { "Id" }, cascadeDelete: false); } public override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey("Quote", "FK_Quote_Samurai_SamuraiId"); migrationBuilder.DropTable("Battle"); migrationBuilder.DropTable("Quote"); migrationBuilder.DropTable("Samurai"); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Transactions; using AWModel; namespace SimpleQueries { class Program { static void Main() { //ModifyDetailsForSalesOrder(); //DeleteOrders(); RetrieveAndUpdateCustomer(); //CustomersQuery(); //CustomerWithOrders(); //CustomersThatHaveOrders(); } private static void ModifyDetailsForSalesOrder() { using (var context = new AWEntities()) { var detailList = context.SalesOrderDetails.Where(d => d.SalesOrderID == 71816).ToList(); // modify an OrderDetail detailList[0].OrderQty = 10; //delete an OrderDetail context.DeleteObject(detailList[1]); //insert a new OrderDetail var product = context.Products.SingleOrDefault(p => p.ProductID == 711); var newDetail = new SalesOrderDetail { SalesOrderID = 71816, ProductID = product.ProductID, OrderQty = 2, UnitPrice = product.ListPrice, UnitPriceDiscount = 0, ModifiedDate = DateTime.Today }; context.SalesOrderDetails.AddObject(newDetail); context.SaveChanges(); } } private static void DeleteOrders() { using (var context = new AWEntities()) { var orders = from o in context.SalesOrderHeaders where o.CustomerID == 721 select o; foreach (var order in orders) { context.SalesOrderHeaders.DeleteObject(order); } context.SaveChanges(); } } private static void RetrieveAndUpdateCustomer() { using (var context = new AWEntities()) { var query = from c in context.Customers where c.CustomerID == 5 select c; var customer = query.FirstOrDefault(); var newOrder = new SalesOrderHeader { OrderDate = DateTime.Now, DueDate = DateTime.Now.AddMonths(1), ModifiedDate = DateTime.Now, Comment = "Don't forget to ship this!" }; context.ContextOptions.LazyLoadingEnabled = false; customer.SalesOrderHeaders.Add(newOrder); context.SaveChanges(); } } private static void NewCustomer() { using (var context = new AWEntities()) { var customer = new Customer { FirstName = "Julie", LastName = "Lerman", ModifiedDate = DateTime.Now }; customer.SalesOrderHeaders.Add(new SalesOrderHeader { OrderDate = DateTime.Now, DueDate = DateTime.Now.AddMonths(1), ModifiedDate = DateTime.Now, Comment = "Don't forget to ship this too!" }); context.Customers.AddObject(customer); context.SaveChanges(); } } private static void CustomerWithOrders() { var context = new AWModel.AWEntities(); var query = from c in context.Customers where c.CustomerID == 5 select new { c.CustomerID, c.FirstName, c.LastName, c.SalesOrderHeaders }; var cust = query.FirstOrDefault(); } private static void CustomersThatHaveOrders() { var context = new AWModel.AWEntities(); var customers = context.Customers.Where(c => c.SalesOrderHeaders.Any()).ToList(); } private static void CustomersQuery() { var context = new AWModel.AWEntities(); var query = from c in context.Customers where c.CustomerID == 5 select c; var customers = query.FirstOrDefault(); } } }<file_sep> using Microsoft.AspNet.Diagnostics; using Microsoft.AspNet.Diagnostics.Entity; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Routing; using Microsoft.Data.Entity; //using Microsoft.Framework.Cache.Memory; using System; using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; using Microsoft.AspNet.Hosting; using Microsoft.Framework.ConfigurationModel; using Microsoft.Framework.DependencyInjection; using ASPNET5Samurai.DataModel; namespace ASPNET5Samurai { public class Startup { public static IConfiguration configuration { get; set; } public Startup(IHostingEnvironment env) { configuration = new Configuration().AddJsonFile("config.json").AddEnvironmentVariables(); } public void ConfigureServices(IServiceCollection services) { // Add EF services to the services container. services.AddEntityFramework(configuration) .AddSqlServer() .AddDbContext<SamuraiContext>(options => options.UseSqlServer()); services.AddMvc(); } public void Configure(IApplicationBuilder app) { app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller}/{action}/{id?}", defaults: new { controller = "Home", action = "Index" }); }); app.UseWelcomePage(); } } } <file_sep>-- Demo: TAbles ALiases -- Table allias SELECT [dept].[Name] FROM [HUmanResources]. [Department] AS [dept]; -- Compact table alias example SELECT [d].[Name] FROM [HumanResources].[Department] AS [d]; -- Counter -intuitive table alias example SELECT [q].[Name] FROM [HumanResources].[Department] AS [q];<file_sep>use Contacts; select a.address_locality, a.address_city, a.address_state_province_county From address a where a.address_locality IS Null; select a.address_locality, a.address_city, a.address_state_province_county From address a where a.address_locality IS not Null; select p.person_first_name, p.person_contacted_number From person p where p.person_first_name IN('Jon' ,'Shanon'); select p.person_first_name, p.person_contacted_number From person p where p.person_contacted_number IN(0,1); select p.person_first_name From person p Where p.person_first_name like '%o%'; select p.person_first_name From person p where p.person_first_name LIKE '%n'; select p.person_first_name From person p where p.person_first_name LIKE 'J%'; select p.person_first_name, p.person_contacted_number from person p where p.person_contacted_number Between 0 and 4; select p.person_first_name, p.person_contacted_number FROM person p where p.person_contacted_number BETWEEN 0 ANd 4; select a.address_city, a.address_state_province_county from address a; select a.address_city, a.address_state_province_county from address a where a.address_city ='Los Angeles' OR a.address_state_province_county ='California'; select a.address_city, a.address_state_province_county from address a where a.address_city ='Los Angeles' AND a.address_state_province_county ='California'; select a.address_city, a.address_state_province_county From address a; <file_sep>using System.Data.EntityClient; using System.Data.Objects; using Model; namespace DataAccess { public class BreakAwayObjectContext : ObjectContext { public BreakAwayObjectContext(EntityConnection connection) : base(connection) { this.Destinations = this.CreateObjectSet<Destination>(); this.Lodgings = this.CreateObjectSet<Lodging>(); this.Trips = this.CreateObjectSet<Trip>(); this.People = this.CreateObjectSet<Person>(); this.PersonPhotos = this.CreateObjectSet<PersonPhoto>(); } public ObjectSet<Destination> Destinations { get; private set; } public ObjectSet<Lodging> Lodgings { get; private set; } public ObjectSet<Trip> Trips { get; private set; } public ObjectSet<Person> People { get; private set; } public ObjectSet<PersonPhoto> PersonPhotos { get; private set; } } }<file_sep>using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; using VillaSenegal.Models; namespace VillaSenegalDAL { public class UsersRepository : GenericRepository<User> { public UsersRepository(DbContext context) : base(context) { } } } <file_sep>/* Course Data */ /* Table: CHILDSTAT */ /* Database: Oracle */ DROP TABLE CHILDSTAT; CREATE TABLE CHILDSTAT(FIRSTNAME VARCHAR2(50),GENDER VARCHAR2(1),BIRTHDATE DATE,HEIGHT NUMBER,WEIGHT NUMBER); INSERT INTO CHILDSTAT VALUES('ROSEMARY','F',DATE '2000-05-08',35,123); INSERT INTO CHILDSTAT VALUES('LAUREN','F',DATE '2000-06-10',54,876); INSERT INTO CHILDSTAT VALUES('ALBERT','M',DATE '2000-08-02',45,150); INSERT INTO CHILDSTAT VALUES('BUDDY','M',DATE '1998-10-02',45,189); INSERT INTO CHILDSTAT VALUES('FARQUAR','M',DATE '1998-11-05',76,198); INSERT INTO CHILDSTAT VALUES('TOMMY','M',DATE '1998-12-11',78,167); INSERT INTO CHILDSTAT VALUES('SIMON','M',DATE '1999-01-03',87,256); /* Course Data */ /* Table: CHILDSTAT */ /* Database: SQL Server */ DROP TABLE CHILDSTAT; CREATE TABLE CHILDSTAT(FIRSTNAME VARCHAR(50),GENDER VARCHAR(1),BIRTHDATE SMALLDATETIME,HEIGHT SMALLINT,WEIGHT SMALLINT); INSERT INTO CHILDSTAT VALUES('ROSEMARY','F','2000-05-08',35,123); INSERT INTO CHILDSTAT VALUES('LAUREN','F','2000-06-10',54,876); INSERT INTO CHILDSTAT VALUES('ALBERT','M','2000-08-02',45,150); INSERT INTO CHILDSTAT VALUES('BUDDY','M','1998-10-02',45,189); INSERT INTO CHILDSTAT VALUES('FARQUAR','M','1998-11-05',76,198); INSERT INTO CHILDSTAT VALUES('TOMMY','M','1998-12-11',78,167); INSERT INTO CHILDSTAT VALUES('SIMON','M','1999-01-03',87,256); /* Example #22*/ SELECT A.FIRSTNAME,A.HEIGHT, DENSE_RANK() OVER (PARTITION BY A.GENDER ORDER BY A.HEIGHT) AS HEIGHT_DENSERANK FROM CHILDSTAT A ORDER BY A.GENDER,A.HEIGHT /* Example #23*/ SELECT A.FIRSTNAME,A.GENDER,A.WEIGHT,A.HEIGHT, DENSE_RANK() OVER (PARTITION BY A.GENDER ORDER BY A.HEIGHT) AS HEIGHT_DENSERANK, AVG(A.WEIGHT) KEEP (DENSE_RANK FIRST ORDER BY A.HEIGHT) OVER (PARTITION BY A.GENDER) AS AVG_WT FROM CHILDSTAT A ORDER BY A.GENDER,A.HEIGHT /* Example #24*/ SELECT A.FIRSTNAME,A.GENDER,A.WEIGHT,A.HEIGHT, DENSE_RANK() OVER (PARTITION BY A.GENDER ORDER BY A.HEIGHT) AS HEIGHT_DENSERANK, AVG(A.WEIGHT) KEEP (DENSE_RANK LAST ORDER BY A.HEIGHT) OVER (PARTITION BY A.GENDER) AS AVG_WT FROM CHILDSTAT A ORDER BY A.GENDER,A.HEIGHT /* Example #25*/ SELECT A.FIRSTNAME,A.GENDER,A.WEIGHT, MEDIAN(A.WEIGHT) OVER (PARTITION BY A.GENDER) AS MEDIAN_WT FROM CHILDSTAT A ORDER BY A.GENDER,A.WEIGHT /* Example #26*/ SELECT A.FIRSTNAME,A.HEIGHT, NTILE(4) OVER (ORDER BY A.HEIGHT) AS GRP4_HT FROM CHILDSTAT A ORDER BY A.HEIGHT /* Example #27*/ SELECT A.FIRSTNAME,A.GENDER,A.HEIGHT, NTILE(4) OVER (PARTITION BY A.GENDER ORDER BY A.HEIGHT) AS GRP4_HT FROM CHILDSTAT A ORDER BY A.GENDER,A.HEIGHT /* Example #28*/ SELECT A.FIRSTNAME,A.HEIGHT, CUME_DIST() OVER (ORDER BY A.HEIGHT) AS CUMDIST_HEIGHT FROM CHILDSTAT A ORDER BY A.HEIGHT /* Example #29*/ SELECT A.FIRSTNAME,A.HEIGHT, RANK() OVER (ORDER BY A.HEIGHT) AS RANK_HEIGHT, PERCENT_RANK() OVER (ORDER BY A.HEIGHT) AS PCTDIST_HEIGHT FROM CHILDSTAT A ORDER BY A.HEIGHT /* Example #30*/ SELECT A.FIRSTNAME,A.HEIGHT, CUME_DIST() OVER (ORDER BY A.HEIGHT) AS CUMDIST_HEIGHT, PERCENTILE_DISC(.50) WITHIN GROUP (ORDER BY A.HEIGHT) OVER () AS PCTDISC_50_HT, PERCENTILE_DISC(.72) WITHIN GROUP (ORDER BY A.HEIGHT) OVER () AS PCTDISC_72_HT FROM CHILDSTAT A ORDER BY A.HEIGHT /* Example #31*/ SELECT A.FIRSTNAME,A.HEIGHT, PERCENTILE_CONT(.50) WITHIN GROUP (ORDER BY A.HEIGHT) OVER () AS PCTCONT_50_HT, PERCENTILE_CONT(.72) WITHIN GROUP (ORDER BY A.HEIGHT) OVER () AS PCTCONT_72_HT FROM CHILDSTAT A ORDER BY A.HEIGHT <file_sep>using CodedHomes.Data.Configuration; using CodedHomes.Models; using System; using System.Configuration; using System.Data; using System.Data.Entity; using System.Linq; namespace CodedHomes.Data { public class DataContext : DbContext { public DbSet<Home> Homes { get; set; } public DbSet<User> Users { get; set; } public DbSet<Role> Roles { get; set; } public static string ConnectionStringName { get { if (ConfigurationManager.AppSettings["ConnectionStringName"] != null) { return ConfigurationManager.AppSettings["ConnectionStringName"].ToString(); } return "DefaultConnection"; } } static DataContext() { Database.SetInitializer(new CustomDatabaseInitializer()); } public DataContext() : base(nameOrConnectionString: DataContext.ConnectionStringName) {} protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Configurations.Add(new HomeConfiguration()); modelBuilder.Configurations.Add(new UserConfiguration()); // Add ASP.NET WebPages SimpleSecurity tables modelBuilder.Configurations.Add(new RoleConfiguration()); modelBuilder.Configurations.Add(new OAuthMembershipConfiguration()); modelBuilder.Configurations.Add(new MembershipConfiguration()); //base.OnModelCreating(modelBuilder); } private void ApplyRules() { // Approach via @julielerman: http://bit.ly/123661P foreach (var entry in this.ChangeTracker.Entries() .Where( e => e.Entity is IAuditInfo && (e.State == EntityState.Added) || (e.State == EntityState.Modified))) { IAuditInfo e = (IAuditInfo)entry.Entity; if (entry.State == EntityState.Added) { e.CreatedOn = DateTime.Now; } e.ModifiedOn = DateTime.Now; } } public override int SaveChanges() { this.ApplyRules(); return base.SaveChanges(); } } }<file_sep>using System.Data.Entity; using CodedHomes.Models; using System.Collections.Generic; namespace CodedHomes.Data { public class HomesRepository : GenericRepository<Home> { public HomesRepository(DbContext context) : base(context) {} } } <file_sep>using System; using System.Linq; using EF7Samurai.Domain; using EF7Samurai.Context; namespace EF7Samurai.ConsoleApp { class Program { static void Main(string[] args) { TrackingGraphChangesWhileConnected(); } private static void TrackingGraphChangesWhileConnected() { using (var context = new SamuraiContext()) { var samurai= new Samurai { Name = "Kikuchiyo" }; context.Samurais.Add(samurai); samurai.Quotes.Add(new Quote { Text = "I can't kill a lot with 1 sword!" }); Console.WriteLine("How many quotes before saving:" + samurai.Quotes.Count()); context.SaveChanges(); Console.WriteLine("How many quotes after saving:" + samurai.Quotes.Count()); Console.ReadLine(); } } } } <file_sep>using System.Data.Entity.ModelConfiguration; using CodedHomes.Models; namespace CodedHomes.Data.Configuration { public class OAuthMembershipConfiguration : EntityTypeConfiguration<OAuthMembership> { public OAuthMembershipConfiguration() { this.ToTable("webpages_OAuthMembership"); this.HasKey(k => new { k.Provider, k.ProviderUserId }); this.Property(p => p.Provider) .HasColumnType("nvarchar").HasMaxLength(30).IsRequired(); this.Property(p => p.ProviderUserId) .HasColumnType("nvarchar").HasMaxLength(100).IsRequired(); this.Property(p => p.UserId).IsRequired(); } } } <file_sep>using System; using System.Linq; using EF7Samurai.Domain; using EF7Samurai.Context; using System.Collections.Generic; using Microsoft.Data.Entity; namespace EF7Samurai.ConsoleApp { class Program { static void Main(string[] args) { using (var context=new SamuraiContext()) { context.Database.EnsureDeleted(); context.Database.EnsureCreated(); } TrackingGraphChangesWhileConnected(); //Batch_CUD(); //DisconnectedEntities(); // DisconnectedGraphMethods(); } private static void DisconnectedGraphMethods() { AttachNewGraphUsingDbSetAdd(); AttachNewGraphUsingDbContextAdd(); AttachNewGraphUsingEntry(); AttachNewGraphViaChangeTracker(); AttachGraphWithExistingParentNewChild(); Console.ForegroundColor = ConsoleColor.Cyan; AttachExistingGraphWithModifiedParent(); AttachGraphWithModifiedParentAndCallBack(); AddGraphWithModifiedChild(); Console.Write("Press any key to continue..."); Console.Read(); } private static Samurai CreateNewSamuraiNewQuoteGraph() { var newSamurai = new Samurai { Name = "Gisaku" }; newSamurai.Quotes.Add(new Quote { Text = @"What's the use of worrying about your beard when your head's about to be taken?" }); return newSamurai; } private static void AttachNewGraphUsingDbContextAdd() { Samurai newSamurai = CreateNewSamuraiNewQuoteGraph(); using (var context = new SamuraiContext()) { context.Add(newSamurai); DisplayState(context, "DbContext.Add New Graph"); } } private static void AttachNewGraphUsingDbSetAdd() { Samurai newSamurai = CreateNewSamuraiNewQuoteGraph(); using (var context = new SamuraiContext()) { context.Samurais.Add(newSamurai); DisplayState(context, "DbSet.Add New Graph"); } } private static void AttachNewGraphUsingEntry() { Samurai newSamurai = CreateNewSamuraiNewQuoteGraph(); using (var context = new SamuraiContext()) { //EF4.3 -> EF6: context.Entry(newSamurai).State == EntityState.Added; context.Entry(newSamurai).SetState(EntityState.Added); DisplayState(context, "Entry/State Attach New Graph"); } } private static void AttachNewGraphViaChangeTracker() { Samurai newSamurai = CreateNewSamuraiNewQuoteGraph(); using (var context = new SamuraiContext()) { context.ChangeTracker.AttachGraph(newSamurai); DisplayState(context, "AttachGraph (no callback) New Graph"); } } private static Samurai GetExistingParentChildGraph() { Samurai samurai; using (var context = new SamuraiContext()) { samurai = context.Samurais .Include(s => s.Quotes) .FirstOrDefault(s => s.Quotes.Any()); } return samurai; } private static void AttachExistingGraphWithModifiedParent() { Samurai samurai = GetExistingParentChildGraph(); samurai.Name += " Modified"; using (var context = new SamuraiContext()) { context.ChangeTracker.AttachGraph(samurai); DisplayState(context, "Attach Graph (no callback) with modified parent"); } } private static void AttachGraphWithExistingParentNewChild() { Samurai samurai; using (var context = new SamuraiContext()) { samurai = context.Samurais.FirstOrDefault(s => s.Name.Contains("Shimada")); } samurai.Quotes.Add(new Quote {Text = "Danger always strikes when everything seems fine." }); using (var context = new SamuraiContext()) { context.ChangeTracker.AttachGraph(samurai); DisplayState(context, "Attach Graph (no callback) existing unchanged parent, new child"); } } private static void AttachGraphWithModifiedParentAndCallBack() { Samurai samurai = GetExistingParentChildGraph(); samurai.Name += " Modified"; using (var context = new SamuraiContext()) { context.ChangeTracker.AttachGraph(samurai, e => e.SetState(EntityState.Modified)); DisplayState(context, "Attach Graph using Callback with modified parent, unchanged child"); } } private static void AddGraphWithModifiedChild() { Samurai samurai = GetExistingParentChildGraph(); samurai.Quotes[0].Text += "Modified"; using (var context = new SamuraiContext()) { context.ChangeTracker.AttachGraph(samurai); DisplayState(context, "Attach Graph (no callback) unchanged parent with modified child"); } } private static void DisconnectedEntities() { //Setup List<Samurai> disconnectedSamurais; using (var context = new SamuraiContext()) { context.Database.EnsureDeleted(); context.Database.EnsureCreated(); context.Samurais.Add(Samurai_KK, Samurai_KS, Samurai_GK, Samurai_KK, Samurai_KZ); Samurai_KK.Quotes.Add(new Quote { Text = "I'm the funny one" }); context.SaveChanges(); } using (var context = new SamuraiContext()) { //Include requires MARS support in connection string disconnectedSamurais = context.Samurais.Include(s => s.Quotes).ToList(); } //work with disconnected samurais var modifiedSamurai = disconnectedSamurais[0]; modifiedSamurai.Name += "The Glorious"; var modifiedQuote = disconnectedSamurais.FirstOrDefault(s => s.Quotes.Any()).Quotes.FirstOrDefault(); modifiedQuote.Text += "Julizuro was here!"; var ksId = disconnectedSamurais.FirstOrDefault(n => n.Name.Contains("Shimada")).Id; var newQuote = new Quote { Text = @"This is the nature of war. By protecting others, you save yourself. If you only think of yourself, you’ll only destroy yourself.", SamuraiId = ksId }; var newSamurai = new Samurai { Name = "Julizuro" }; using (var context = new SamuraiContext()) { context.Add(newQuote, newSamurai); context.Update(modifiedQuote, modifiedSamurai); } } private static void DisplayState(SamuraiContext context, string message) { Console.WriteLine(); Console.WriteLine(message); context.ChangeTracker.Entries().ToList().ForEach(e => Console.WriteLine(" {0}: {1}", e.Entity.GetType(), e.State)); } static Samurai Samurai_KK = new Samurai { Name = "Kikuchiyo" }; static Samurai Samurai_KS = new Samurai { Name = "<NAME>" }; static Samurai Samurai_S = new Samurai { Name = "Shichirōji" }; static Samurai Samurai_KO = new Samurai { Name = "<NAME>" }; static Samurai Samurai_HH = new Samurai { Name = "<NAME>" }; static Samurai Samurai_KZ = new Samurai { Name = "Kyūzō" }; static Samurai Samurai_GK = new Samurai { Name = "<NAME>" }; private static void Batch_CUD() { using (var context = new SamuraiContext()) { context.Samurais.Add(Samurai_KK, Samurai_KS, Samurai_GK); context.SaveChanges(); } using (var context = new SamuraiContext()) { var samurais = context.Samurais.ToList(); samurais[0].Name += "The Glorious"; var ks = samurais.FirstOrDefault(n => n.Name.Contains("Shimada")); ks.Quotes.Add( new Quote { Text = @"This is the nature of war. By protecting others, you save yourself. If you only think of yourself, you’ll only destroy yourself." }); context.Remove(samurais.Where(n => n.Name.Contains("Gorōbei")).ToArray()); context.Samurais.Add(new Samurai { Name = "Julizuro" }); context.SaveChanges(); } } private static void TrackingGraphChangesWhileConnected() { using (var context = new SamuraiContext()) { context.Samurais.Add(Samurai_KK); Samurai_KK.Quotes.Add(new Quote { Text = "I can't kill a lot with 1 sword!" }); System.Console.Write("1)"); DisplayState(context); context.SaveChanges(); Samurai_KK.Quotes.Add(new Quote { Text = "You call yourself a horse!" }); System.Console.Write("2)"); DisplayState(context); Samurai_KK.Quotes[0].Text = "I can't kill a lot with one sword!!"; System.Console.Write("3)"); DisplayState(context); //Note: With the alpha version I am using of the SQL SErver Provider, //there seems to be a bug that is preventing this from working. //It works correctly with the in memory //provider. Follow the issue on github here: https://github.com/aspnet/EntityFramework/issues/1449 //context.Remove(Samurai_KK.Quotes[1]); //System.Console.Write("4)"); //DisplayState(context); System.Console.ReadLine(); } } private static void DisplayState(SamuraiContext context) { context.ChangeTracker.Entries().ToList().ForEach(e => System.Console.WriteLine(" {0}: {1}", e.Entity.GetType(), e.State)); } private static void TrackingChangesWhileConnected() { using (var context = new SamuraiContext()) { context.Samurais.Add(Samurai_KK); System.Console.WriteLine("1)" + context.Entry(Samurai_KK).State); context.SaveChanges(); System.Console.WriteLine("2)" + context.Entry(Samurai_KK).State); Samurai_KK.Name += "No.7! "; System.Console.WriteLine("3)" + context.Entry(Samurai_KK).State); context.Samurais.Remove(Samurai_KK); System.Console.WriteLine("4)" + context.Entry(Samurai_KK).State); System.Console.ReadLine(); } } private static void PlayWithContext() { using (var context = new SamuraiContext()) { context.Samurais.Add(Samurai_KK); context.Samurais.Add(Samurai_KS, Samurai_S, Samurai_HH); context.SaveChanges(); //System.Console.WriteLine(context.Samurais.Count()); //var samurais=context.Samurais.Where(s => s.Name.Contains("Shi")).ToList(); //samurais.ForEach(s => System.Console.WriteLine(s.Name)); var samurai = context.Samurais.FirstOrDefault(s => s.Name.Contains("Shi")); System.Console.WriteLine(samurai.Name); System.Console.ReadLine(); } } } } // context.ChangeTracker.Entries().ToList().ForEach(e=>System.Console.WriteLine(e.State)); <file_sep>ALTER TABLE phone_number ADD CONSTRAINT FK_phone_number_person FOREIN KEY (phone_number_id) REFERENCES person(person_id); <file_sep>Create table Positions ( PositionId Int IDENTITY ,Name NVARCHAR(100) NOT NULL ,Abbreviation NVARCHAR(3) NOT NULL ,PRIMARY KEY (PositionId) ); INSERT INTO Positions values ('Quarterback', 'QB'); INSERT INTO Positions values ('Runningback', 'QB'); INSERT INTO Positions values ('Wide Receiver', 'WR'); ALTER TABLE Players ADD PositionId INT INSERT INTO Players values('Eyebe', 'TouchDown', 3); ALTER TABLE Players ADD CONSTRAINT FK_PLayers_Positions FOREIGN KEY (PositionId) REFERENCES Positions(PositionId); UPDATE Players SET PositionId=1;<file_sep>using System; namespace CodedHomes.Models { public class Membership { public int UserId {get;set;} public DateTime? CreateDate {get;set;} public string ConfirmationToken {get;set;} public bool? IsConfirmed {get;set;} public DateTime? LastPasswordFailureDate {get;set;} public int PasswordFailuresSinceLastSuccess {get;set;} public string Password {get;set;} public DateTime? PasswordChangedDate {get;set;} public string PasswordSalt {get;set;} public string PasswordVerificationToken {get;set;} public DateTime? PasswordVerificationTokenExpirationDate { get; set; } } } <file_sep>using CodedHomes.Models; using System.Data.Entity.ModelConfiguration; namespace CodedHomes.Data.Configuration { public class RoleConfiguration : EntityTypeConfiguration<Role> { public RoleConfiguration() { this.ToTable("webpages_Roles"); this.Property(p => p.RoleName).HasMaxLength(256).IsRequired(); } } } <file_sep>using CodedHomes.Models; using System.Data.Entity.ModelConfiguration; namespace CodedHomes.Data.Configuration { public class HomeConfiguration : EntityTypeConfiguration<Home> { public HomeConfiguration() { this.Property(p => p.StreetAddress) .IsRequired().HasMaxLength(100); this.Property(p => p.StreetAddress2) .IsOptional().HasMaxLength(100); this.Property(p => p.City) .IsRequired().HasMaxLength(50); this.Property(p => p.ZipCode) .IsRequired(); this.Property(p => p.ImageName) .HasMaxLength(100); this.Property(p => p.CreatedOn) .IsRequired().HasColumnType("datetime"); this.Property(p => p.ModifiedOn) .IsRequired().HasColumnType("datetime"); } } } <file_sep> SELECT [sod].[salesOrderID] FROM [Sales].[SalesOrderDetail] AS [sod] WHERE [sod].[CarrierTrackingNumber] ='4911-403c-98'; --With DISTINCT SELECT DISTINCT [sod].[SalesOrderID] FROM [Sales].[SalesOrderDetail] AS [sod] WHERE [sod].[CarrierTrackingNumber] ='4911-403c-98'; --Count of rows with null SELECT Count(*) FROM [Sales].[SalesOrderDetail] AS [sod] WHERE [CarrierTrackingNumber] IS NULL; <file_sep>using System; using Microsoft.Data.Entity.Infrastructure; using Microsoft.Framework.DependencyInjection; using Microsoft.Framework.Logging; using Microsoft.Framework.Logging.Console; namespace EF7Samurai.Context { public static class ExtensionMethods { public static void LogToConsole(this SamuraiContext context) { // IServiceProvider represents registered DI container IServiceProvider contextServices = ((IDbContextServices)context).ScopedServiceProvider; // Get the registered ILoggerFactory from the DI container var loggerFactory = contextServices.GetRequiredService<ILoggerFactory>(); // Add a logging provider with a console trace listener loggerFactory.AddConsole(LogLevel.Verbose); } } } <file_sep>using RibbitMvc.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace RibbitMvc.Data { public interface IRibbitRepository : IRepository<Ribbit> { Ribbit GetBy(int id); IEnumerable<Ribbit> GetFor(User user); void AddFor(Ribbit ribbit, User user); } }<file_sep> use NFL; select * from Passess; -- update Passess --set Quarterback = '<NAME>' --where Quarterback ='<NAME>';<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.Entity.Migrations; namespace MESSADIIS.Data { class MessadiisMigrationConfiguration : DbMigrationsConfiguration<MessadiisContext> { public MessadiisMigrationConfiguration() { this.AutomaticMigrationDataLossAllowed = true; this.AutomaticMigrationsEnabled = true; } //called everytime that the application is restart protected override void Seed(MessadiisContext context) { base.Seed(context); # if DEBUG if(context.Questions.Count() == 0 ) { var Question = new Question () { Titre="Apple Quelle prétentetion !" , Texte ="L'informatique, ça fait gagner beaucoup de temps... à condition d'en avoir beaucoup devant soi !" , Creation=DateTime.Now, Reponses = new List<Reponse> { new Reponse() { Texte="Quelle prétention de prétendre que l'informatique est récente : Adam et Eve avaient déjà un Apple !", Creation=DateTime.Now }, new Reponse() { Texte="Quelle prétention de prétendre que l'informatique est récente : Adam et Eve avaient déjà un Apple !", Creation=DateTime.Now }, new Reponse() { Texte="Quelle prétention de prétendre que l'informatique est récente : Adam et Eve avaient déjà un Apple !", Creation=DateTime.Now }, new Reponse() { Texte="Quelle prétention de prétendre que l'informatique est récente : Adam et Eve avaient déjà un Apple !", Creation=DateTime.Now }, } }; context.Questions.Add(Question); //an another one var Question2 = new Question () { Titre="Apple Quelle prétentetion !" , Texte ="L'informatique, ça fait gagner beaucoup de temps... à condition d'en avoir beaucoup devant soi !", Creation=DateTime.Now, Reponses = new List<Reponse> { new Reponse() { Texte="Quelle prétention de prétendre que l'informatique est récente : Adam et Eve avaient déjà un Apple !", Creation=DateTime.Now }, new Reponse() { Texte="Quelle prétention de prétendre que l'informatique est récente : Adam et Eve avaient déjà un Apple !", Creation=DateTime.Now }, new Reponse() { Texte="Quelle prétention de prétendre que l'informatique est récente : Adam et Eve avaient déjà un Apple !", Creation=DateTime.Now }, new Reponse() { Texte="Quelle prétention de prétendre que l'informatique est récente : Adam et Eve avaient déjà un Apple !", Creation=DateTime.Now }, } }; context.Questions.Add(Question2); var Question3 = new Question () { Titre="Apple Quelle prétentetion !" , Texte ="L'informatique, ça fait gagner beaucoup de temps... à condition d'en avoir beaucoup devant soi !" , Creation=DateTime.Now, Reponses = new List<Reponse> { new Reponse() { Texte="Quelle prétention de prétendre que l'informatique est récente : Adam et Eve avaient déjà un Apple !", Creation=DateTime.Now }, new Reponse() { Texte="Quelle prétention de prétendre que l'informatique est récente : Adam et Eve avaient déjà un Apple !", Creation=DateTime.Now }, new Reponse() { Texte="Quelle prétention de prétendre que l'informatique est récente : Adam et Eve avaient déjà un Apple !", Creation=DateTime.Now }, new Reponse() { Texte="Quelle prétention de prétendre que l'informatique est récente : Adam et Eve avaient déjà un Apple !", Creation=DateTime.Now }, } }; context.Questions.Add(Question3); var Question4 = new Question () { Titre="Apple Quelle prétentetion !" , Texte ="L'informatique, ça fait gagner beaucoup de temps... à condition d'en avoir beaucoup devant soi !" , Creation=DateTime.Now, Reponses = new List<Reponse> { new Reponse() { Texte="Quelle prétention de prétendre que l'informatique est récente : Adam et Eve avaient déjà un Apple !", Creation=DateTime.Now }, new Reponse() { Texte="Quelle prétention de prétendre que l'informatique est récente : Adam et Eve avaient déjà un Apple !", Creation=DateTime.Now }, new Reponse() { Texte="Quelle prétention de prétendre que l'informatique est récente : Adam et Eve avaient déjà un Apple !", Creation=DateTime.Now }, new Reponse() { Texte="Quelle prétention de prétendre que l'informatique est récente : Adam et Eve avaient déjà un Apple !", Creation=DateTime.Now }, } }; context.Questions.Add(Question4); var Question5 = new Question () { Titre="Apple Quelle prétentetion !" , Texte ="L'informatique, ça fait gagner beaucoup de temps... à condition d'en avoir beaucoup devant soi !" , Creation=DateTime.Now, Reponses = new List<Reponse> { new Reponse() { Texte="Quelle prétention de prétendre que l'informatique est récente : Adam et Eve avaient déjà un Apple !", Creation=DateTime.Now }, new Reponse() { Texte="Quelle prétention de prétendre que l'informatique est récente : Adam et Eve avaient déjà un Apple !", Creation=DateTime.Now }, new Reponse() { Texte="Quelle prétention de prétendre que l'informatique est récente : Adam et Eve avaient déjà un Apple !", Creation=DateTime.Now }, new Reponse() { Texte="Quelle prétention de prétendre que l'informatique est récente : Adam et Eve avaient déjà un Apple !", Creation=DateTime.Now }, } }; context.Questions.Add(Question5); try { context.SaveChanges(); } catch(Exception ex) { var msg = ex.Message; } } #endif } } } <file_sep>-- Demo : SELECT CLAUSE USE AdventureWorks2012; --No data source SELECT '1' As [col01], '2' AS [col2]; --check avaibl data source columns EXEC sp_help 'Production.TransacionHistory'; --one data source SELECT [TransactionID], [ProductID], [Quantity], [ActualCost], 'Batch 1' As [BatchID], ([Quantity]* [ActualCost] ) AS [TotalCost] FROM [Production].[TransactionHistory]; <file_sep>using AWModel; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Linq; using System.Data; using System.Collections.Generic; namespace QueryTests { [TestClass()] public class SalesEntitiesTest { [TestMethod] public void MiniCustomerProjectionReturnsListOfTypedObjects() { Assert.IsTrue(ExploreQueryProjections() is List<MiniCustomer>); } private List<MiniCustomer> ExploreQueryProjections() { var context = new SalesEntities(); var query = from c in context.Customers select new MiniCustomer { FirstName = c.FirstName, LastName = c.LastName, CustomerID = c.CustomerID }; return query.ToList(); //foreach (var whatever in query) // Debug.WriteLine(whatever.FirstName.Trim() + ' ' + whatever.LastName); } [TestMethod] public void QueryingWithNavigationProperties() { var context = new SalesEntities(); //var query = from c in context.Customers // where c.Orders.Sum(o => o.SubTotal) > 10000 // from o in c.Orders // select new { c.Company, Orders = o }; var query = from c in context.Customers where c.Orders.Any() select new { c.Company, Orders = c.Orders }; var customers = query.ToList(); } [TestMethod] public void NestedQuery() { var context = new SalesEntities(); var universe = from c in context.Customers where c.Orders.Any() select c; var queryA = (from c in universe select new { c.Company, c.Orders.Count }).ToList(); // var queryB=from c in universe select c; //another type of nested query var nested = from c in context.Customers from o in c.Orders where o.OnlineOrderFlag == true select new { c.Company, o.SalesOrderNumber }; } [TestMethod] public void GroupedQueries() { var context = new SalesEntities(); var query = from o in context.Orders group o by o.DueDate into mygroupedorders select mygroupedorders; } [TestMethod] public void ReturnsASingleCustomer() { var context = new SalesEntities(); Order order=(from o in context.Orders orderby o.SubTotal descending select o).SingleOrDefault(); Assert.IsNotNull(order); } [TestMethod] public void GetObjectByKeyReturnsAnObject() { var context=new SalesEntities(); var key=new EntityKey("SalesEntities.Customers","CustomerID",16); object customer; Assert.IsTrue(context.TryGetObjectByKey(key, out customer)); Assert.IsInstanceOfType(customer, typeof(Customer)); } } public class MiniCustomer { public string FirstName { get; set; } public string LastName { get; set; } public int CustomerID { get; set; } } } <file_sep>using Microsoft.Practices.Unity; using AccountAtAGlance.Model.Repository; namespace AccountAtAGlance.Model { public static class ModelContainer { private static readonly object _Key = new object(); private static UnityContainer _Instance; public static UnityContainer Instance { get { if (_Instance == null) { lock (_Key) { if (_Instance == null) { _Instance = new UnityContainer(); _Instance.RegisterType<IAccountRepository, AccountRepository>(); _Instance.RegisterType<ISecurityRepository, SecurityRepository>(); _Instance.RegisterType<IMarketsAndNewsRepository, MarketsAndNewsRepository>(); } } } return _Instance; } } } } <file_sep>public class Capture { /// <summary> /// Get and Set Capture's Unique Identifier. /// </summary> public int Id { get; set; } /// <summary> /// Get and Set Capture's Operating System. /// </summary> public virtual OperatingSystem OperatingSystem { get; set; } } public class OperatingSystem { /// <summary> /// Operating System's Unique Identifier. /// </summary> public int Id { get; set; } } /////////////////////////////////////////////////////////////////////// internal sealed class EntityCaptureConfiguration : EntityTypeConfiguration<Capture> { /// <summary> /// Create an Entity Capture Configuration. /// </summary> public EntityCaptureConfiguration() { this.ToTable("Capture"); this.HasKey(m => m.Id); this.Property(m => m.Id).HasColumnName("Id"); this.HasRequired(m => m.OperatingSystem).WithRequiredDependent().Map(m => m.MapKey("OperatingSystemId")); } } /////////////////////////////////////////////////////////////////////////// public sealed class EntityDefaultContext : DbContext { /// <summary> /// Model Creating Event Handler. /// </summary> protected override void OnModelCreating(DbModelBuilder modelBuilder) { var entityCaptureConfiguration = new EntityCaptureConfiguration(); var entityOperatingSystemConfiguration = new EntityOperatingSystemConfiguration(); modelBuilder.Configurations.Add(entityOperatingSystemConfiguration); modelBuilder.Configurations.Add(entityCaptureConfiguration); this.Configuration.LazyLoadingEnabled = false; this.Configuration.ProxyCreationEnabled = false; } } <file_sep>using System.Data.Entity; using RibbitMvc.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace RibbitMvc.Data { public class UserProfileRepository : EfRepository<UserProfile>, IUserProfileRepository { public UserProfileRepository(DbContext context, bool sharedContext) : base(context, sharedContext) { } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VillaSenegal.DAL; using VillaSenegal.Models; namespace VillaSenegalDAL { public class ApplicationUnit : IDisposable { private DataContext _context = new DataContext(); private IRepository<Villa> _villas = null; private IRepository<User> _users = null; public IRepository<Villa> Villas { get { if (this.Villas == null) { this._villas = new GenericRepository<Villa>(this._context); } return this._villas; } } public IRepository<User> Users { get { if(this._users== null) { this._users = new GenericRepository<User>(this._context); } return this._users; } } public void SaveChanges() { this._context.SaveChanges(); } public void Dispose() { if (this._context != null) { this._context.Dispose(); } } } } <file_sep>using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; using VillaSenegal.Models; namespace VillaSenegalDAL { public class VillasRepository : GenericRepository<Villa> { public VillasRepository(DbContext context) : base(context) { } } } <file_sep>using EF7Samurai.Domain; using Microsoft.Data.Entity; using System; namespace EF7Samurai.Context { public class SamuraiContext : DbContext { public DbSet<Samurai> Samurais { get; set; } public DbSet<Battle> Battles { get; set; } public DbSet<Quote> Quotes { get; set; } protected override void OnConfiguring(DbContextOptions options) { //options.UseInMemoryStore(); options .UseSqlServer("Server = (localdb)\\mssqllocaldb; Database=EF7Samurai; Trusted_Connection=True; MultipleActiveResultSets = True;") .MaxBatchSize(40); //base.OnConfiguring(options); <-- a reminder that this does nothing, so unneeded (no-op) } #if false //alternate to hard coding options, pass them in from calling app //this would be the constructor //do not set options in OnConfiguring public SamuraiContext(DbContextOptions options) :base(options) { } #endif } } <file_sep>using ASPNET5Samurai.Models; using Microsoft.Data.Entity; using System; namespace ASPNET5Samurai.DataModel { public class SamuraiContext :DbContext { public DbSet<Samurai> Samurais { get; set; } } }<file_sep>-- Demo : Where Clause -- One predicate SELECT [sod].[SalesOrderID], [sod].[SalesOrderDetailID] FROM [Sales].[SalesOrderDetail] AS [sod] WHERE [sod].[CarrierTrackingNumber]= '4911-403C-98'; SELECT [sod].[SalesOrderID], [sod].[SalesOrderDetailID], [sod].[SpecialOfferID], [sod].[CarrierTrackingNumber] FROM [Sales].[SalesOrderDetail] AS [sod] WHERE [sod].[CarrierTrackingNumber]= '4911-403C-98' AND [sod].[SpecialOfferID] =1; SELECT [sod].[SalesOrderID], [sod].[SalesOrderDetailID], [sod].[SpecialOfferID], [sod].[CarrierTrackingNumber] FROM [Sales].[SalesOrderDetail] AS [sod] WHERE [sod].[CarrierTrackingNumber]= '4911-403C-98' OR [sod].[SpecialOfferID] =1 ; <file_sep>ALTER TABLE Players DROP CONSTRAINT FK_Players_Positions; ALTER TABLE Players DROP COLUMN PositionId; CREATE TABLE PlayersPositions ( PlayerId INT ,PositionId INT ,PRIMARY KEY(PlayerId, Positionid) ); INSERT INTO PlayersPositions VALUES (5, 2); INSERT INTO PlayersPositions VALUES (5, 3); SELECT * FROM PlayersPositions; INSERT INTO Players VALUES ('Calvin', 'Johnson'); INSERT INTO PlayersPositions VALUES (6, 2); ALTER TABLE PlayersPositions ADD CONSTRAINT FK_PlayersPositions_Players FOREIGN KEY (PlayerId) REFERENCES Players(PlayerId) ALTER TABLE PlayersPositions ADD CONSTRAINT FK_PlayersPositions_Positions FOREIGN KEY (PositionId) REFERENCES Positions(PositionId) <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MESSADIIS.Data { public interface IMessadiisRepository { IQueryable<Question> GetQuestions(); IQueryable<Question> GetQuestionsInclusReponses(); IQueryable<Reponse> GetReponsesByQuestion(int QuestionId); bool Save(); bool AddQuestion(Question newQuestion); bool AddReponse(Reponse newReponse); } }<file_sep>SELECT * FROM Passes; CREATE TABLE Players ( PlayerId INT IDENTITY ,FirstName NVARCHAR(100) ,LastName NVARCHAR(100) ,PRIMARY KEY(PlayerId) ); INSERT INTO Players VALUES ('Peyton', 'Manning'); SELECT * FROM Players; ALTER TABLE Passes DROP COLUMN Quarterback; ALTER TABLE Passes ADD PlayerId INT; UPDATE Passes SET PlayerId = 1 SELECT pl.FirstName + pl.LastName AS PlayerName ,COUNT(WasTouchdown) FROM Passes AS p INNER JOIN Players AS pl ON p.PlayerId = pl.PlayerId WHERE WasTouchdown = 1 GROUP BY pl.FirstName + pl.LastName<file_sep>using CodedHomes.Models; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.ModelConfiguration; namespace CodedHomes.Data.Configuration { public class MembershipConfiguration : EntityTypeConfiguration<Membership> { public MembershipConfiguration() { this.ToTable("webpages_Membership"); this.HasKey(p => p.UserId); this.Property(p => p.UserId) .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None); this.Property(p => p.ConfirmationToken) .HasMaxLength(128).HasColumnType("nvarchar"); this.Property(p => p.PasswordFailuresSinceLastSuccess) .IsRequired(); this.Property(p => p.Password).IsRequired() .HasMaxLength(128).HasColumnType("nvarchar"); this.Property(p => p.PasswordSalt) .IsRequired().HasMaxLength(128).HasColumnType("nvarchar"); this.Property(p => p.PasswordVerificationToken) .HasMaxLength(128).HasColumnType("nvarchar"); } } } <file_sep>using AWModel; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Data.Objects; using System.Diagnostics; using System.Linq; using System.Data.EntityClient; using System.Data; namespace QueryTests { [TestClass()] public class SalesEntitiesTest { [TestMethod()] public void GetSomeCustomers() { var context = new SalesEntities(); var query = from c in context.Customers orderby c.LastName where c.FirstName=="Robert" select c; var customers =query.ToList(); foreach (var cust in customers) Debug.WriteLine(cust.LastName.Trim() + ", " + cust.FirstName); } [TestMethod()] public void GetSomeCustomersUsingLinqMethod() { var context = new SalesEntities(); var query = context.Customers.OrderBy(c => c.LastName).Where(c => c.FirstName == "Robert"); var customers = query.ToList(); foreach (var cust in customers) Debug.WriteLine(cust.LastName.Trim() + ", " + cust.FirstName); } [TestMethod()] public void GetSomeCustomersUsingESQL() { var context = new SalesEntities(); var esql = "SELECT VALUE c FROM SalesEntities.Customers AS c " + "WHERE c.FirstName='Robert' ORDER BY c.LastName"; var query=context.CreateQuery<Customer>(esql); var customers = query.ToList(); foreach (var cust in customers) Debug.WriteLine(cust.LastName.Trim() + ", " + cust.FirstName); } [TestMethod()] public void GetSomeCustomersUsingESQLRawQuerying() { var context=new SalesEntities(); //I needed this in the test, but you shouldn't need it in regular code using (var conn = new EntityConnection("name=SalesEntities")) { conn.Open(); EntityCommand cmd = conn.CreateCommand(); cmd.CommandText = "SELECT VALUE c FROM SalesEntities.Customers AS c " + "WHERE c.FirstName='Robert' ORDER BY c.LastName"; EntityDataReader rdr = cmd.ExecuteReader(CommandBehavior.SequentialAccess|CommandBehavior.CloseConnection); } } [TestMethod()] public void RunVariousQueriesForProfiling() { var context = new SalesEntities(); //simple query (from c in context.Customers select c).ToList(); //query with variable parameter string sort = "Robert"; (from c in context.Customers orderby c.LastName where c.FirstName == sort select c).ToList(); //query with hard coded parameter (from c in context.Customers orderby c.LastName where c.FirstName == "Robert" select c).ToList(); //Entity SQL via Query Builder Methods context.Customers.OrderBy("it.LastName").Where("it.FirstName='Robert'").ToList(); //Entity SQL with forced parameters var query = context.CreateQuery<Customer>("SELECT VALUE c FROM SalesEntities.Customers AS c WHERE c.FirstName=@fn"); var whereParameter = new ObjectParameter("fn", "Robert"); query.Parameters.Add(whereParameter); query.ToList(); //sql injection with LINQ to Entities? sort = "John';EXEC sys.sp_helpuser--"; (from c in context.Customers orderby c.LastName where c.FirstName == sort select c).ToList(); //sql injection with Entity SQL? sort = "John';EXEC sys.sp_helpuser--"; var esql = "it.FirstName=" + sort; context.Customers.Where(esql).ToList(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading.Tasks; namespace RibbitMvc.Data { public interface IContext : IDisposable { IUserRepository Users { get; } IRibbitRepository Ribbits { get; } int SaveChanges(); } } <file_sep>-- Demo: Column Aliases SELECT [Name] AS [DepartmentName] ,-- Recommended approach [Name] [DepartmentName], -- Not Recommended [GroupName] AS [GN] FROM [HumanResources].[Department];
ea0c1716c493232101862b2537bec6aa493dacd2
[ "C#", "SQL" ]
57
C#
aly-ba/couche-donnee-avec-entity-framework.
180104663e680cbf3ca13410a2cdfa7ac2097037
97f60aedcc7c4d92c7b70bf476780d139037af8e
refs/heads/main
<repo_name>dieterstueken/mills<file_sep>/src/main/java/mills/partitions/Partitions.java package mills.partitions; import mills.bits.PopCount; import mills.util.AbstractRandomArray; /** * Created by IntelliJ IDEA. * User: stueken * Date: 24.04.16 * Time: 12:30 */ abstract public class Partitions<P> extends AbstractRandomArray<PartitionTable<P>> { public Partitions() { super(100); } public PartitionTable<P> get(PopCount pop) { return get(pop.index); } } <file_sep>/core/src/test/java/mills/util/ListSetTest.java package mills.util; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Set; import java.util.TreeSet; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; /** * Created by IntelliJ IDEA. * User: stueken * Date: 07.10.19 * Time: 22:09 */ public class ListSetTest { final List<Integer> base = List.of(1, 5, 7, 11); @Test public void testNaturalOrder() { List<Integer> mutable = new ArrayList<>(base); ListSet<Integer> list = ListSet.of(); list.addAll(base); // based on a mutable list ListSet<Integer> list1 = ListSet.of(mutable); assertEquals(list, list1); list1.clear(); list1.addAll(List.of(1, 11, 5, 7)); assertEquals(list, list1); Set<Integer> iset = new TreeSet<>(Arrays.asList(11, 7, 1, 5)); assertEquals(list, iset); assertTrue(list.remove((Integer)7)); assertTrue(iset.remove(7)); assertEquals(list, iset); } @Test public void testBounds() { ListSet<Integer> entryTable = ListSet.of(base); TreeSet<Integer> intTable = new TreeSet<>(entryTable); assertEquals(entryTable, intTable); for(int i=0; i<12; ++i) { int index = entryTable.indexOf(i); int lower = entryTable.lowerBound(i); int upper = entryTable.upperBound(i); String message = String.format("entry %2d: %2d %2d %2d", i, index, lower, upper); //System.out.println(message); if(index>=0 && index< entryTable.size()) assertTrue(i==entryTable.get(index), message); for(int k=0; k<lower; ++k) assertTrue(entryTable.get(k) < i, message); for(int k=lower; k< entryTable.size(); ++k) assertTrue(entryTable.get(k) >= i, message); for(int k=0; k<upper; ++k) assertTrue(entryTable.get(k) <= i, message); for(int k=upper; k< entryTable.size(); ++k) assertTrue(entryTable.get(k) > i, message); assertEquals(entryTable.headSet(i), intTable.headSet(i), "equal head"); assertEquals(entryTable.tailSet(i), intTable.tailSet(i), "equal tail"); } } @Test public void testParallelism() { ListSet<Integer> entryTable = ListSet.ofIndexed(64, i->i, i->i); entryTable.parallelStream().forEach(System.out::println); } }<file_sep>/core/src/main/java/mills/ring/EntryTables.java package mills.ring; import mills.util.AbstractListSet; import mills.util.AbstractRandomList; import java.io.PrintStream; import java.util.*; import java.util.concurrent.ConcurrentSkipListMap; /** * Created by IntelliJ IDEA. * User: stueken * Date: 12/21/14 * Time: 8:49 PM */ public class EntryTables { static final short OFFSET = RingEntry.MAX_INDEX+1; static final int MAX_VALUE = 0xffff - OFFSET - 2; private final List<IndexedEntryArray> tables = new ArrayList<>(); // must never be resized private final List<Map<List<RingEntry>, IndexedEntryArray>> maps = AbstractRandomList.preset(RingEntry.MAX_INDEX-2, null); // generated maps so far private final Map<Short, Map<List<RingEntry>, IndexedEntryArray>> metamap = new ConcurrentSkipListMap<>(); public EntryTables() { // prefetch some maps needed anyway for(int i=2; i<128; ++i) map(i); } /** * Public normalisation. * @param list to normalize. * @return a normalized list. */ public IndexedEntryTable table(List<RingEntry> list) { if(list==null) return null; int size = list.size(); if(size==0) return IndexedEntryTable.of(); if(size==1) return list.get(0).singleton; if(Entries.TABLE.equals(list)) return Entries.TABLE; return getEntry(list); } private Map<List<RingEntry>, IndexedEntryArray> map(int size) { if(size<2) throw new IndexOutOfBoundsException("index < 2"); int index = size-2; // try map array first Map<List<RingEntry>, IndexedEntryArray> map = maps.get(index); // generate on demand if still missing if(map==null) { map = metamap.computeIfAbsent((short)index, i->new ConcurrentSkipListMap<>(Entries.BY_ORDER)); maps.set(index, map); } return map; } private IndexedEntryTable getEntry(List<RingEntry> list) { try { return _getEntry(list); } catch(RuntimeException error) { return _getEntry(list); } } private IndexedEntryTable _getEntry(List<RingEntry> list) { if(list==null) return null; if(list instanceof IndexedEntryTable entry) { int index = entry.getIndex(); if(entry == get(index)) return entry; } int size = list.size(); // lookup (no keyed entry of size<2) Map<List<RingEntry>, IndexedEntryArray> map = map(size); IndexedEntryArray entry = map.get(list); if(entry!=null) return entry; synchronized(map) { // double check entry = map.get(list); if(entry==null) { entry = createEntry(list); map.put(entry, entry); } } return entry; } private IndexedEntryArray createEntry(List<RingEntry> list) { if(list instanceof EntryArray) { short[] indices = ((EntryArray)list).indices; return keyedEntry(indices); } short[] indices = new short[list.size()]; short l=-1; boolean ordered = true; for(int i=0; i<indices.length; ++i) { short k = list.get(i).index; indices[i] = k; ordered &= k>l; l=k; } if(!ordered) Arrays.sort(indices); return keyedEntry(indices); } /** * Very short synchronized block to generate unique key and table entry. * The index array is already created. * @param indices of RingEntrys * @return a registered KeyedEntry. */ private synchronized IndexedEntryArray keyedEntry(short[] indices) { int key = tables.size() + OFFSET; if(key>MAX_VALUE) throw new IndexOutOfBoundsException("too many entries"); IndexedEntryArray entry = IndexedEntryArray.of(indices, (short) key); tables.add(entry); return entry; } public short key(List<RingEntry> list) { if(list==null) return -2; IndexedEntryTable indexed = getEntry(list); return (short) indexed.getIndex(); } int size() { return tables.size() + OFFSET; } /** * Public lookup of normalized table by index. * @param index previously generated. * @return a normalized EntryTable. */ public EntryTable get(int index) { if(index<-1) return null; if(index == -1) return EntryTable.of(); if(index < RingEntry.MAX_INDEX) return RingEntry.of(index).singleton; if(index == RingEntry.MAX_INDEX) return Entries.TABLE; index -= OFFSET; return index<tables.size() ? tables.get(index) : null; } public List<EntryTable> register(Collection<? extends List<RingEntry>> s1) { if(s1==null) return null; int size = s1.size(); if(size==0) return Collections.emptyList(); if(size==1) { EntryTable table = EntryTables.this.table(s1.iterator().next()); return AbstractListSet.singleton(table); } List<EntryTable> table = allocate(size); if(s1 instanceof List) { List<? extends List<RingEntry>> l1 = (List)s1; for (int i = 0; i < size; ++i) { List<RingEntry> list = l1.get(i); table.set(i, table(list)); } } else { int i = 0; for (List<RingEntry> list : s1) { table.set(i, table(list)); ++i; } if (i != size) throw new IllegalStateException("size does not match"); } return table; } public List<EntryTable> allocate(int size) { return allocate(size, null); } public List<EntryTable> allocate(int size, EntryTable defaultValue) { short[] indexes = new short[size]; Arrays.fill(indexes, key(defaultValue)); return new AbstractRandomList<>() { @Override public int size() { return indexes.length; } @Override public EntryTable get(int index) { int key = indexes[index]; return EntryTables.this.get(key); } @Override public EntryTable set(int index, EntryTable table) { EntryTable prev = get(index); short key = key(table); indexes[index] = key; return prev; } }; } public int count() { return tables.size(); } public void stat(PrintStream out) { out.format("total: %d/%d\n", metamap.size(), tables.size()); metamap.forEach((key, value) -> out.format("%2d %3d\n", key + 2, value.size())); } } <file_sep>/scores/build.gradle plugins { id "java-library" } dependencies { implementation project(':core') runtimeOnly project(':index') }<file_sep>/core/src/main/java/mills/ring/SingleEntry.java package mills.ring; import java.util.Iterator; import java.util.Objects; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.stream.Stream; /** * Created by IntelliJ IDEA. * User: stueken * Date: 13.08.11 * Time: 18:16 */ class SingleEntry extends AbstractEntryTable implements IndexedEntryTable { final RingEntry entry; SingleEntry(RingEntry entry) { this.entry = entry; } public static SingleEntry of(RingEntry entry) { return entry.singleton; } public static SingleEntry of(int index) { return RingEntry.of(index).singleton; } @Override public int size() { return 1; } @Override public int getIndex() { return entry.index; } @Override public EntryTable filter(Predicate<? super RingEntry> predicate) { if (predicate.test(entry)) return this; else return EntryTable.of(); } @Override public RingEntry get(int index) { if (index == 0) return entry; else throw new IndexOutOfBoundsException("Index: " + index); } @Override public int findIndex(int ringIndex) { int i = entry.index(); if(i==ringIndex) return 0; if(ringIndex<i) return -1; return -2; } @Override public int indexOf(Object obj) { return Objects.equals(obj, entry) ? 0 : -1; } @Override public Iterator<RingEntry> iterator() { //return Iterators.singletonIterator(entry()); return super.iterator(); } @Override public Stream<RingEntry> stream() { return Stream.of(entry); } @Override public void forEach(Consumer<? super RingEntry> action) { action.accept(entry); } @Override public int hashCode() { return entry.hashCode(); } } <file_sep>/scores/src/main/java/mills/score/generator/Layer.java package mills.score.generator; import mills.bits.Player; import mills.bits.PopCount; /** * Created by IntelliJ IDEA. * User: stueken * Date: 01.11.19 * Time: 21:57 */ public interface Layer { PopCount pop(); Player player(); default boolean canJump() { return player().canJump(pop()); } } <file_sep>/core/src/test/java/mills/util/IndexTableTest.java package mills.util; import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.List; public class IndexTableTest { final List<Integer> list = Arrays.asList(2, 4, 1); final IndexTable index = IndexTable.sum0(list, i -> i); @Test public void testLowerBound() throws Exception { for(int i=0; i<list.size(); ++i) { System.out.format("%d: %d -> %d\n", i, list.get(i), index.get(i)); } for(int i=-2; i<10; ++i) { int k = index.lowerBound(i); System.out.format("%d %d\n", i, k); } } @Test public void testRange() throws Exception { int range = index.range(); //assertEquals(range, 28); } } <file_sep>/core/src/main/java/mills/ring/SubTable.java package mills.ring; /** * version: $Revision$ * created by: dst * created on: 10.07.2014 11:56 * modified by: $Author$ * modified on: $Date$ */ public class SubTable extends AbstractEntryTable { final EntryTable parent; final int offset; final int size; SubTable(EntryTable parent, int offset, int size) { this.parent = parent; this.offset = offset; this.size = size; assert offset >= 0; assert size > 1; // should be empty or a singleton instead } @Override public int findIndex(int ringIndex) { int index = parent.findIndex(ringIndex); if(index<offset) { index+=offset; if(index>=0) // was between [0,offset[ return -1; // was negative, limit negative size. int limit = -(size+1); return Math.max(index, limit); } // index >= offset index -= offset; return index<size ? index : -(size+1); } @Override public EntryTable subList(int fromIndex, int toIndex) { // Prevent from extending the range beyond given bounds. checkRange(fromIndex, toIndex); return parent.subList(fromIndex + offset, toIndex + offset); } @Override public int size() { return size; } @Override public RingEntry get(int index) { return parent.get(index+offset); } } <file_sep>/core/src/main/java/mills/index/IndexProcessor.java package mills.index; /** * version: $Revision$ * created by: dst * created on: 10.12.12 10:31 * modified by: $Author$ * modified on: $Date$ */ public interface IndexProcessor { void process(int posIndex, long i201); } <file_sep>/scores/src/main/java/mills/score/ScoreMap.java package mills.score; import mills.bits.Player; import mills.bits.PopCount; import mills.index.IndexProcessor; import mills.index.PosIndex; import mills.position.Position; import mills.stones.Moves; import java.io.Closeable; import java.nio.ByteBuffer; import java.nio.MappedByteBuffer; import java.util.HashSet; import java.util.Set; /** * version: $Revision$ * created by: dst * created on: 16.11.12 17:24 * modified by: $Author$ * modified on: $Date$ */ public class ScoreMap implements Position.Factory, Closeable { private final ByteBuffer scores; private final PosIndex index; final Player player; public ScoreMap(final ByteBuffer scores, final PosIndex index, Player player) { this.scores = scores; this.index = index; this.player = player; assert scores.limit() >= index.range(); } public void force() { if(scores instanceof MappedByteBuffer) { ((MappedByteBuffer) scores).force(); } } public void close() {} /** * Get current score as an unsigned value. * * @param index to seek. * @return current score. */ public int getScore(int index) { int value = scores.get(index); value &= 0xff; // clip off sign bit return value; } public void setScore(int posIndex, int score) { byte value = (byte) (score&0xff); scores.put(posIndex, value); } public PosIndex index() { return index; } public int size() { return index.range(); } public long i201(int posIndex) { return index.i201(posIndex); } public void process(IndexProcessor processor, int base, int i) { index.process(processor, base, i); } public PopCount pop() { return index.pop(); } public int posIndex(long i201) { return index.posIndex(i201); } public Moves moves(Player player) { boolean jumps = player.canJump(pop()); return Moves.moves(jumps); } public static Integer posIndex(Position pos) { return pos==null ? null : pos.posIndex; } public class Position extends mills.position.Position { final Position normalized; final int posIndex; final int score; public Position(long i201) { super(i201); posIndex = index.posIndex(i201); score = posIndex<0 ? -1 : getScore(posIndex); if(super.isNormalized) normalized = this; else normalized = position(i201(posIndex)); } public Position position(long i201) { return new Position(i201); } @Override public StringBuilder format(StringBuilder sb) { sb = super.format(sb); sb.insert(3, player.name().charAt(0)); sb.append(" ").append(posIndex).append(" : "); sb.append(score); return sb; } } public Position position(long i201) { return new Position(i201); } public Position indexPosition(int posIndex) { long i201 = i201(posIndex); return new Position(i201); } public final Set<Position> debug = new HashSet<>(); public void debug(Position position) { debug.add(position); } public void debug(int index) { debug.add(position(i201(index))); } public void debug(long i201) { debug.add(position(i201)); } public Thread load() { Thread thread = new Thread(() -> { for (int i = 0; i < scores.limit(); i += 4096) scores.get(i); }); thread.start(); Thread.yield(); return thread; } } <file_sep>/core/src/main/java/mills/util/IndexedListSet.java package mills.util; import java.util.List; /** * Created by IntelliJ IDEA. * User: stueken * Date: 21.08.22 * Time: 14:09 */ public interface IndexedListSet<T> extends ListSet<T> { @Override Indexer<? super T> comparator(); default int findIndex(int key) { return comparator().binarySearchKey(this, key); } default int indexOf(Object o) { return o instanceof Indexed idx ? findIndex(idx.getIndex()) : -1; } static <T> IndexedDelegate<T> of(List<T> values, Indexer<? super T> comparator) { return new IndexedDelegate<>(values) { @Override public Indexer<? super T> comparator() { return comparator; } }; } static <T extends Indexed> IndexedDelegate<T> of(List<T> values) { return new IndexedDelegate<>(values) { @Override public Indexer<? super T> comparator() { return Indexer.INDEXED; } }; } static <T extends Indexed> IndexedListSet<T> ifDirect(List<T> values) { if(DirectListSet.isDirect(values, Indexer.INDEXED)) return DirectListSet.of(values, Indexer.INDEXED); else return IndexedListSet.of(values); } } <file_sep>/scores/src/main/java/mills/score/opening/OpeningMaps.java package mills.score.opening; import mills.bits.Clops; import mills.index.IndexProvider; import mills.position.Positions; import mills.util.Indexer; import java.util.Map; import java.util.TreeMap; import java.util.function.LongPredicate; import static mills.score.opening.OpeningLayer.MAX_TURN; /** * Created by IntelliJ IDEA. * User: stueken * Date: 29.08.22 * Time: 17:26 */ public class OpeningMaps { final IndexProvider provider; final int turn; final Map<Clops, OpeningLayer> maps = new TreeMap<>(Indexer.INDEXED); public OpeningMaps(IndexProvider provider, int turn) { this.provider = provider; this.turn = turn; } public OpeningMaps(IndexProvider provider) { this(provider, 0); completeLayer(Clops.EMPTY); } public static OpeningMaps start(IndexProvider provider) { return new OpeningMaps(provider); } //static final Clops DEBUG = Clops.of(PopCount.of(2,3), PopCount.of(0,1)); OpeningLayer openMap(Clops clops) { //if(clops.equals(DEBUG)) // clops = clops; return maps.computeIfAbsent(clops, this::createMap); } OpeningLayer completeLayer(Clops clops) { return maps.computeIfAbsent(clops, this::createLayer); } OpeningMap createMap(Clops clops) { return OpeningMap.open(provider, turn, clops); } OpeningLayer createLayer(Clops clops) { return new OpeningLayer(turn, clops); } public OpeningMaps next() { if(turn==MAX_TURN) return null; OpeningMaps next = new OpeningMaps(provider, turn+1); // setup finished target maps for (OpeningLayer layer : maps.values()) { if(layer.isComplete()) { Clops clops = layer.nextLayer(); next.completeLayer(clops); } } // setup remaining layers for (OpeningLayer layer : maps.values()) { layer.nextLayers(next::openMap); } next.propagate(this::get); return next; } void propagate(LongPredicate source) { maps.values().parallelStream().forEach(layer->layer.propagate(source)); } void reduce() { for (Clops clops : maps.keySet()) { maps.computeIfPresent(clops, (c,l)->l.reduce()); } maps.values().removeIf(OpeningLayer::isEmpty); } boolean get(Long i201) { Clops clops = Positions.clops(i201); OpeningLayer map = maps.get(clops); if(map==null) return false; return map.get(i201); } private int count() { return maps.values().stream().mapToInt(OpeningLayer::range).sum(); } public void stat() { maps.values().stream().map(OpeningLayer::toString).forEach(System.out::println); } public static void main(String ... args) { IndexProvider provider = IndexProvider.load(); long total = 0; double start = System.currentTimeMillis(); for(OpeningMaps maps = start(provider); maps!=null; maps = maps.next()) { double stop = System.currentTimeMillis(); double seconds = (stop - start) / 1000; int count = maps.count(); total += count; maps.stat(); System.out.format("turn: %d %d %,d %.3fs\n", maps.turn, maps.maps.size(), count, seconds); maps.reduce(); } double stop = System.currentTimeMillis(); System.out.format("total: %,d %.3fs\n", total, (stop - start) / 1000); } } <file_sep>/index/src/main/java/mills/index/tables/R2Entry.java package mills.index.tables; import mills.ring.RingEntry; import mills.util.Indexer; /** * Created by IntelliJ IDEA. * User: stueken * Date: 05.10.19 * Time: 20:31 */ public class R2Entry { public static final Indexer<R2Entry> R2 = element -> element.e2.index; final RingEntry e2; final R0Table t0; public R2Entry(RingEntry e2, R0Table t0) { this.e2 = e2; this.t0 = t0; } public RingEntry r2() { return e2; } public R0Table t0() { return t0; } @Override public String toString() { return String.format("%s : %d", e2, t0.size()); } } <file_sep>/core/src/main/java/mills/position/Board.java package mills.position; import mills.bits.Player; import mills.bits.Sector; import mills.ring.RingEntry; import java.util.List; import static mills.bits.Sector.E; import static mills.bits.Sector.N; import static mills.bits.Sector.NE; import static mills.bits.Sector.NW; import static mills.bits.Sector.S; import static mills.bits.Sector.SE; import static mills.bits.Sector.SW; import static mills.bits.Sector.W; /** * version: $ * created by: d.stueken * created on: 07.03.2021 18:45 * modified by: $ * modified on: $ */ public class Board { static final String DUMMY = "◯━━●━━o"; static final List<String> BOARD = List.of( "┏━━━━━━━━┳━━━━━━━━┓", "┃ ┏━━━━━╋━━━━━┓ ┃", "┃ ┃ ┏━━┻━━┓ ┃ ┃", "┣━━╋━━┫ ┣━━╋━━┫", "┃ ┃ ┗━━┳━━┛ ┃ ┃", "┃ ┗━━━━━╋━━━━━┛ ┃", "┗━━━━━━━━┻━━━━━━━━┛" ); static final int K = 3; // stretch factor static final int M = 3; // center point static final int NY = BOARD.size(); // 7 static final int NX = K*NY - K + 1; // 19 static String board(long i201, Player player) { if(player==Player.Black) i201 = Positions.inverted(i201); StringBuilder sb = new StringBuilder(); for(int iy=0; iy<NY; ++iy) { for (int ix = 0; ix < NX; ++ix) sb.append(get(ix, iy, i201)); sb.append('\n'); } return sb.toString(); } static void show(long i201) { for(int iy=0; iy<NY; ++iy) { for (int ix = 0; ix < NX; ++ix) System.out.append(get(ix, iy, i201)); System.out.println(); } } static char get(int ix, int iy, long i201) { Player player = player(ix, iy, i201); if(player==Player.Black) return '●'; if(player==Player.White) return '◯'; return BOARD.get(iy).charAt(ix); } static Player player(int ix, int iy, long i201) { // odd values if((ix%K)!=0) return Player.None; ix /= K; ix -= M; iy -= M; int ir = Math.max(Math.abs(ix), Math.abs(iy)); RingEntry e = ring(i201, ir); if(e==null) return Player.None; if((ix%ir)!=0 || (iy%ir)!=0) return Player.None; Sector s = sector(ix/ir, iy/ir); if(s==null) return Player.None; return e.player(s); } static Sector sector(int ix, int iy) { int k = (ix+1) + 10*(iy+1); return switch (k) { case 0 -> NW; case 1 -> N; case 2 -> NE; case 10 -> W; case 12 -> E; case 20 -> SW; case 21 -> S; case 22 -> SE; default -> null; }; } static RingEntry ring(long i201, int ir) { return switch (ir) { case 1 -> Positions.r0(i201); case 2 -> Positions.r1(i201); case 3 -> Positions.r2(i201); default -> null; }; } public static void main(String ... args) { RingEntry e0 = RingEntry.of(1234); RingEntry e2 = RingEntry.of(5514); RingEntry e1 = RingEntry.of(2456); long i201 = Positions.i201(e2, e0, e1, 0); show(i201); } } <file_sep>/src/main/java/mills/main/IndexRange.java package mills.main; import mills.bits.PopCount; import mills.index.IndexProcessor; import mills.index.IndexProvider; import mills.index.PosIndex; import mills.position.Positions; import java.util.AbstractList; import java.util.List; import java.util.Random; import java.util.concurrent.RecursiveAction; /** * Created by IntelliJ IDEA. * User: stueken * Date: 16.11.12 * Time: 23:36 */ public class IndexRange extends RecursiveAction { protected final Random random = new Random(123456789); public final IndexProvider indexes = IndexProvider.load(); public void compute() { for (PopCount pop : PopCount.TABLE) { PosIndex pi = indexes.build(pop); verify(pi); } } private void verify(final PosIndex pi) { final int size = pi.range(); System.out.format("verify %s\n", pi.pop()); List<Runnable> tasks = new AbstractList<>() { public int size() { return 100; } public Runnable get(int i) { int i1 = random.nextInt(size); int i2 = random.nextInt(size); final int start = Math.min(i1, i2); final int end = Math.max(i1, i2); final IndexProcessor processor = (posIndex, i201) -> { if (posIndex < start || posIndex >= end) throw new IndexOutOfBoundsException(); long k201 = pi.i201(posIndex); if (!Positions.equals(k201, i201)) throw new RuntimeException(); }; return () -> pi.process(processor, start, end); } }; for (Runnable r : tasks) { r.run(); } } public static void main(String... args) { new IndexRange().invoke(); } } <file_sep>/scores/src/main/java/mills/score/generator/ScoreSlices.java package mills.score.generator; import mills.bits.Player; import mills.index.PosIndex; import mills.util.AbstractRandomList; import java.util.List; import java.util.logging.Level; import java.util.stream.Stream; /** * Created by IntelliJ IDEA. * User: stueken * Date: 19.05.13 * Time: 17:04 */ abstract public class ScoreSlices implements IndexLayer { abstract public ScoreSet scores(); abstract List<? extends ScoreSlice<?>> slices(); public int size() { return slices().size(); } public Stream<? extends ScoreSlice<?>> stream() { return slices().stream(); } public ScoreSlice<?> get(int posIndex) { return slices().get(posIndex / MapSlice.SIZE); } public int posIndex(long i201) { return scores().posIndex(i201); } public void stat() { scores().stat(Level.FINE); } public String toString() { return String.format("ScoreSlices %s (%d)", scores(), max()); } /** * Determine max score. * @return current max score of all slices. */ public int max() { return slices().stream().mapToInt(ScoreSlice::max).reduce(0, Integer::max); } @Override public PosIndex index() { return scores().index(); } @Override public Player player() { return scores().player(); } public int getScore(long i201) { int posIndex = scores().index.posIndex(i201); return get(posIndex).getScore(posIndex); } static ScoreSlices of(ScoreSet scores) { int size = ScoreSlice.sliceCount(scores); List<? extends ScoreSlice<?>> slices = AbstractRandomList.generate(size, scores::openSlice); return new ScoreSlices() { @Override public ScoreSet scores() { return scores; } @Override List<? extends ScoreSlice<?>> slices() { return slices; } }; } } <file_sep>/scores/src/main/java/mills/score/generator/GroupElevator.java package mills.score.generator; import mills.bits.Player; import mills.bits.PopCount; import mills.index.IndexProcessor; import mills.position.Position; import mills.position.Positions; import mills.score.Score; import mills.stones.Mover; import mills.stones.Moves; import mills.stones.Stones; import mills.util.AbstractRandomList; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; /** * Created by IntelliJ IDEA. * User: stueken * Date: 06.01.20 * Time: 14:44 */ public class GroupElevator extends LayerGroup<ScoreSet> { static final Logger LOGGER = Logger.getLogger(GroupElevator.class.getName()); private GroupElevator(PopCount pop, Player player, Map<PopCount, ? extends ScoreSet> group) { super(pop, player, group); } static GroupElevator create(PopCount pop, Player player, Map<PopCount, ? extends ScoreSet> group) { return new GroupElevator(pop, player, group); } static GroupElevator create(LayerGroup<? extends ScoreSet> group) { return create(group.pop, group.player, group.group); } ScoreSlices elevate(ScoreTarget scores) { TargetSlices slices = TargetSlices.of(scores); int max = slices.slices().parallelStream() .map(Processor::new) .mapToInt(Processor::process) .reduce(0, Math::max); LOGGER.log(Level.FINE, ()->String.format("elevate: %s <- %s M:%d", scores, this, max)); return slices; } class Processor extends Mover implements IndexProcessor { final TargetSlice slice; transient long i201; final List<ScoredPosition> debug = new AbstractRandomList<>() { @Override public int size() { return Processor.this.size(); } @Override public ScoredPosition get(int index) { long i201 = get201(index); int score = getScore(i201); return new ScoredPosition(i201, player(), score); } }; Position position() { return new Position(i201, slice.player()); } Processor(TargetSlice slice) { super(Moves.TAKE, player()==Player.Black); this.slice = slice; } int process() { slice.process(this); return slice.max; } @Override public void process(int posIndex, long i201) { this.i201 = i201; Player player = slice.player(); // take an opponents stone int move = Stones.stones(i201, player); int stay = Stones.stones(i201, player.opponent()); int closed = Stones.closed(move); int mask = move==closed ? closed : move^closed; int size = move(stay, move, mask).size(); if(size==0) throw new IllegalStateException("no moves"); int worst = Score.WON.value; for(int i=0; i<size; ++i) { long m201 = Positions.normalize(get201(i)); int score = getScore(m201); if(Score.betterThan(worst, score)) worst = score; } if(worst!=0) slice.setScore(slice.offset(posIndex), worst); } int getScore(long m201) { assert Positions.pop(m201).equals(pop) : "swapped"; PopCount clop = Positions.clop(m201); ScoreSet scores = group.get(clop); int posIndex = scores.index.posIndex(m201); return scores.getScore(posIndex); } } } <file_sep>/core/src/main/java/mills/bits/Perm.java package mills.bits; import mills.util.ListSet; import java.util.function.UnaryOperator; /** * Created by IntelliJ IDEA. * User: stueken * Date: 27.12.2009 * Time: 15:59:29 */ /* A permutation is a sequence of mirror (M) and rotate (R) operations. For these holds: M*M = ID R*R*R*R = ID M * R^k = R^-k * M; (with R^-k == R^(4-k)) Each sequence may be reduced to: M^i * R^k with i:[01] and k:[0123] Introducing an inversion with X = R*R a sequence may be represented as: M^i * X^j * R^k with i,j,k of [0,1] Thus, there are 8 possible combinations: A B D C rotations: ___ R0 identity ABCD __R R1 rotate 90° DABC _X_ R2 rotate 180° CDAB _XR R3 rotate 270° BCDA mirrors: M__ M0 | BADC M_R M1 = M * RR / ADCB MX_ M2 = M * RX - DCBA MXR M3 = M * RL \ CBAD The permutation can be applied to a pattern of stones. */ public enum Perm implements UnaryOperator<Sector>, Operation { /** * Enum ordinates select operations applied: * bit 0: rotate right. * bit 1: */ R0, R1, R2, R3, M0, M1, M2, M3; public static final int ROT = 1; public static final int INV = 2; public static final int MIR = 4; public static final int MSK = 7; // pre calculated permutations private final int composed = composed(ordinal()); /** * @return Return bit mask to use for meq. */ public int msk() { return 1<<ordinal(); } public short perm() { return (short) ordinal(); } /** * @return number of right rotations performed. */ public int rotates() { return ordinal()%4; } /** * @return if mirroring takes place. */ public boolean mirrors() { return (ordinal()&MIR)!=0; } /** * Apply permutation to a given position mask. * The mask may be composed of three 8-bit patterns to represent a full 24-bit position. * @param pattern of stones. * @return permuted pattern. */ @Override public int apply(int pattern) { int result = rotate(pattern, rotates()); if(mirrors()) result = mirror(result); return result; } /** * Implement the Sector -> Sector mapping. * @param sector to map. * @return mapped sector. */ @Override public Sector apply(Sector sector) { sector = sector.rotate(rotates()); if(mirrors()) sector = sector.mirror(); return sector; } // return inverse operation @Override public Perm invert() { return switch (this) { case R3 -> R1; case R1 -> R3; // all others are self inverting. default -> this; }; } /** * Apply this permutation on a given perm leaving other bits untouched. * @param perm previous permutation. * @return composed permutation. */ public int compose(int perm) { int n = 4*(perm&MSK); // cut off new permutation return (composed>>>n)&MSK; } public Perm compose(Perm before) { return get(compose(before.ordinal())); } /** * Compose p0 and p1 preserving additional flags from p0. * @param p0 current permutation. * @param p1 additional permutation. * @return composition of p0 * p1 */ public static short compose(short p0, int p1) { int perm = p0&MSK; p0 ^= perm; // clear current perm bits p0 |= get(perm).compose(p1); return p0; } /** * Invert the permutation bits of a status code * @param stat status code * @return permuted status code */ public static short invert(short stat) { // is R1 | R3 if((stat&5)==1) stat ^= 2; return stat; } @Override public String toString() { return String.format("%s[%d]", name(), ordinal()); } /////////////////////// static utilities /////////////////////// private static int composed(int m) { m &= 7; // # of rotations int mr = m%4; for(int k=1; k<8; ++k) { // mirrors ? 1 : -1 int mm = 1 - (k&4)/2; // rotation gets possibly mirrored int mc = (mm * mr + k) & 3; // xor mirrors mc |= (m^k)&4; // shift up mc <<= 4*k; // setup m |= mc; } return m; } private static int rotate(int pattern, int count) { count &= 3; if(count!=0) { pattern <<= count; int mask = (0x0f << count) & 0xf0; mask *= 0x111111; mask &= pattern; mask ^= mask >>> 4; pattern ^= mask; } return pattern; } private static final int MEDGES = Sector.E.masks(); private static final int MCORNERS = Sector.NW.masks() | Sector.SE.masks(); private static int mirror(int pattern) { int mask = pattern ^ (pattern>>>2); mask &= MEDGES; mask |= mask<<2; pattern ^= mask; mask = pattern ^ (pattern>>>1); mask &= MCORNERS; mask |= mask<<1; pattern ^= mask; return pattern; } public static final ListSet<Perm> VALUES = ListSet.of(Perm.class); // get by index [0,8[ public static Perm get(int i) { return VALUES.get(i & Perms.MSK);} } <file_sep>/scores/src/main/java/mills/score/Diff.java package mills.score; import java.io.File; import java.io.IOException; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.file.OpenOption; import java.nio.file.StandardOpenOption; /** * Created by IntelliJ IDEA. * User: stueken * Date: 26.05.13 * Time: 18:56 */ public class Diff { final MappedByteBuffer a; final MappedByteBuffer b; void run() { if(a.capacity()!=b.capacity()) System.out.format("different sizes: %d %d\n", a.capacity(), b.capacity()); else { int diff = 0; for(int pos=0; pos<a.capacity(); ++pos) { byte va = a.get(pos); byte vb = b.get(pos); if(va!=vb) { System.out.format("%d: %d %d\n", pos, va, vb); ++diff; } } } } public Diff(MappedByteBuffer a, MappedByteBuffer b) { this.a = a; this.b = b; } private static final OpenOption[] READ = new OpenOption[]{StandardOpenOption.READ}; public static MappedByteBuffer open(String name) throws IOException { final File file = new File(name); final FileChannel fc = FileChannel.open(file.toPath(), READ); final int size = (int) fc.size(); return fc.map(FileChannel.MapMode.READ_ONLY, 0, size); } public static void main(String ... args) throws IOException { if(args.length!=2) throw new IllegalArgumentException(); new Diff(open(args[0]), open(args[1])).run(); } } <file_sep>/scores/src/main/java/mills/score/attic/opening/PlopLayer.java package mills.score.attic.opening; import mills.index.IndexProvider; /** * Created by IntelliJ IDEA. * User: stueken * Date: 12.11.19 * Time: 17:58 */ abstract class PlopLayer extends PlopSets { PlopLayer(IndexProvider indexes, Plop plop) { super(indexes, plop); } protected PlopLayer(PlopLayer parent) { super(parent); } abstract protected void trace(MovedLayer source, PlopSet tgt); public void show() { for (PlopSet ps : plops.values()) { System.out.format("%c %s[%s] %d/%d\n", getClass().getSimpleName().charAt(0), ps.pop(), ps.clop(), ps.set.cardinality(), ps.index.range()); } } } <file_sep>/core/src/main/java/mills/ring/IndexedMap.java package mills.ring; import mills.util.IndexTable; import java.util.List; import java.util.function.ToIntFunction; /** * version: $Revision$ * created by: dst * created on: 10.07.2014 16:20 * modified by: $Author$ * modified on: $Date$ */ public class IndexedMap<T> extends EntryMap<T> { protected final IndexTable it; public int range() { return it.range(); } public IndexedMap(EntryTable keys, List<T> values, IndexTable it) { super(keys, values); this.it = it; assert it.size() == size(); } public IndexedMap(EntryTable keys, List<T> values, final ToIntFunction<? super T> indexer) { super(keys, values); this.it = IndexTable.sum(values, indexer); } } <file_sep>/scores/src/main/java/mills/score/attic/opening/PlopSets.java package mills.score.attic.opening; import mills.bits.Clops; import mills.bits.Player; import mills.bits.PopCount; import mills.index.IndexProvider; import mills.index.PosIndex; import mills.position.Position; import mills.position.Positions; import mills.stones.Moves; import mills.stones.Stones; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Consumer; /** * version: $ * created by: d.stueken * created on: 14.11.2019 12:42 * modified by: $ * modified on: $ */ public class PlopSets implements Moves.Process { final Plop plop; final IndexProvider indexes; final Map<Clops, PlopSet> plops = new ConcurrentHashMap<>(); PlopSets(IndexProvider indexes, Plop plop) { this.plop = plop; this.indexes = indexes; } protected PlopSets(PlopLayer parent) { this.plop = parent.plop; this.indexes = parent.indexes; } @Override public String toString() { return String.format("%s[%d]", plop.toString(), plops.size()); } private PlopSet newPlops(Clops clops) { assert plop.pop.sub(clops.pop()) !=null; PosIndex index = index(clops); return new PlopSet(plop, index); } PosIndex index(Clops clops) { return indexes.build(clops); } public Player player() { return plop.player(); } public PlopSet plops(Clops clops) { PlopSet ps = plops.get(clops); if(ps==null) { synchronized (plops) { ps = plops.computeIfAbsent(clops, this::newPlops); } } return ps; } PlopSet plops(PopCount pop, PopCount clop) { Clops clops = Clops.of(pop, clop); return plops(clops); } boolean lookup(long i201) { PopCount pop = Positions.pop(i201); PopCount clop = Positions.clop(i201); Clops clops = Clops.of(pop, clop); PlopSet ps = plops.get(clops); // may be missing if(ps==null) return false; int index = ps.index.posIndex(i201); return ps.get(index); } @Override public boolean process(int stay, int move, int mask) { // apply move move ^= mask; Player player = player(); long i201 = Stones.i201(stay, move, player); try { return lookup(i201); } catch (Throwable err) { Position pos = Position.of(i201); System.out.println(pos); lookup(i201); throw err; } } void forEach(Consumer<? super PlopSet> process) { plops.values().parallelStream().forEach(process); } } <file_sep>/src/main/java/mills/main/IndexDigest.java package mills.main; import mills.bits.PopCount; import mills.index.IndexProvider; import mills.index.PosIndex; import mills.position.Position; import mills.ring.Entries; import mills.util.IntegerDigest; import java.io.IOException; import java.security.NoSuchAlgorithmException; import java.util.List; import java.util.concurrent.ForkJoinTask; /** * version: $Revision$ * created by: dst * created on: 08.10.12 11:18 * modified by: $Author$ * modified on: $Date$ */ public class IndexDigest { final IntegerDigest digest = new IntegerDigest("MD5"); protected final IndexProvider indexes = IndexProvider.load(); //final List<? extends PosIndex> table = IndexBuilder.table(); //final List<? extends PosIndex> table = Indexes.build(executor).table(); IndexDigest() throws NoSuchAlgorithmException {} ForkJoinTask<? extends PosIndex> start(int nb, int nw) { PopCount pop = PopCount.of(nb, nw); return ForkJoinTask.adapt(() -> indexes.build(pop)).fork(); } int analyze(ForkJoinTask<? extends PosIndex> task) { if(task!=null) { PosIndex posIndex = task.join(); List<Position> posList = posIndex.positions(); PopCount pop = posIndex.pop(); int range = posIndex.range(); int n20 = posIndex.n20(); System.out.format("l%d%d%10d, %4d\n", pop.nb, pop.nw, range, n20); digest.update(range); return range; } return 0; } public void run() { System.out.format("start %d\n", Entries.TABLE.size()); double start = System.currentTimeMillis(); ForkJoinTask<? extends PosIndex> task = null; long total = 0; //for(PopCount pop:PopCount.TABLE) { for(int nb=0; nb<10; ++nb) for(int nw=0; nw<10; ++nw) { ForkJoinTask<? extends PosIndex> next = start(nb, nw); total += analyze(task); task = next; } total += analyze(task); double stop = System.currentTimeMillis(); System.out.format("%.3f s\n", (stop - start) / 1000); System.out.format("total: %s\n" , total); System.out.println("digest: " + digest); } static void verify(PosIndex posIndex) { posIndex.process((index, i201) -> { int i = posIndex.posIndex(i201); if(i!=index) throw new IllegalStateException(); long j201 = posIndex.i201(index); if(j201!=i201) throw new IllegalStateException(); }); } // e1f9dd6500301e4649063163f3c0d633 public static void main(String ... args) throws NoSuchAlgorithmException, IOException { new IndexDigest().run(); //System.in.read(); } } <file_sep>/core/src/main/java/mills/util/IndexedDelegate.java package mills.util; import java.util.List; /** * Created by IntelliJ IDEA. * User: stueken * Date: 03.09.22 * Time: 17:32 */ abstract public class IndexedDelegate<T> extends DelegateListSet<T> implements IndexedListSet<T> { public IndexedDelegate(List<T> values) { super(values); } } <file_sep>/build.gradle plugins { id "java" id "idea" } version = '1.0' idea.project { jdkName = '17' languageLevel = JavaVersion.VERSION_11 vcs = 'Git' } allprojects { apply plugin: 'idea' group="mills" repositories { mavenCentral() } tasks.withType(JavaCompile) { options.encoding = 'UTF-8' sourceCompatibility = JavaVersion.VERSION_17 targetCompatibility = JavaVersion.VERSION_17 } plugins.withType(JavaPlugin) { idea { module { outputDir file('build/idea/main') testOutputDir file('build/idea/test') } } dependencies { testImplementation group: 'org.junit.jupiter', name: 'junit-jupiter-engine', version: '5.8.1' } } } dependencies { implementation project(':core') implementation project(':index') implementation project(':scores') } <file_sep>/core/src/main/java/mills/util/Index.java package mills.util; /** * Created by IntelliJ IDEA. * User: stueken * Date: 11.09.2010 * Time: 10:30:09 */ public class Index extends AbstractRandomList<Integer> { final int size; public Index(final int size) { this.size = size; } public static Index of(int i) { return new Index(i); } @Override public Integer get(int index) { if(index<0 || index>=size()) throw new IndexOutOfBoundsException("Index: "+index); return index; } @Override public int size() { return size; } } <file_sep>/src/test/java/mills/partitions/PGroupTest.java package mills.partitions; import org.junit.jupiter.api.Test; import java.util.EnumSet; import java.util.IntSummaryStatistics; import java.util.stream.IntStream; import static org.junit.jupiter.api.Assertions.assertEquals; /** * version: $Revision$ * created by: dst * created on: 27.07.2015 10:22 * modified by: $Author$ * modified on: $Date$ */ public class PGroupTest { @Test public void testLindex() throws Exception { IntStream.range(0, 512).forEach(igrp ->{ EnumSet<PGroup> groups = groups(igrp); IntStream.range(0, 128).forEach(msk ->{ EnumSet<PGroup> subset = subset(groups, msk); IntSummaryStatistics stat = IntStream.range(0, 128) .filter(i -> subset(subset, i).equals(subset)) .summaryStatistics(); int min = PGroup.lindex(subset, msk); int max = PGroup.pindex(subset, msk); //System.out.format("%03x %02x %02x %02x %3d\n", igrp, msk, min, max, stat.getCount()); assertEquals(stat.getMax(), max); assertEquals(stat.getMin(), min); }); }); } static EnumSet<PGroup> groups(int igrp) { EnumSet<PGroup> groups = EnumSet.noneOf(PGroup.class); for (PGroup pg : PGroup.values()) { if((igrp&(1<<pg.ordinal()))!=0) groups.add(pg); } return groups; } static EnumSet<PGroup> subset(EnumSet<PGroup> groups, int msk) { EnumSet<PGroup> subset = EnumSet.copyOf(groups); subset.removeIf(pg->pg.collides(msk)); return subset; } }<file_sep>/src/main/java/mills/partitions/PGroup.java package mills.partitions; /** * Created by IntelliJ IDEA. * User: stueken * Date: 24.06.12 * Time: 22:32 */ import mills.bits.Perm; import mills.ring.Entries; import mills.ring.EntryTable; import mills.ring.RingEntry; import java.util.EnumSet; import java.util.List; import java.util.Set; import static mills.bits.Perm.*; /** * For some reason for a single RingEntry exactly 9 different MEQ permutation masks exist. * This Enum provides functions to map from and to a PGroup. */ public enum PGroup { // no symmetry at all P0(R0), // 5616:702 // mirror one axis (54) P1(R0, M0), // 216:54 P2(R0, M1), // 216:96 P3(R0, M3), // 216:54 P4(R0, M2), // 216:12 // central point mirror (9) P5(R0, R2), // 36:9 // central point plus and two mirror axis P6(R0, R2, M0, M2), // 18:9 P7(R0, R2, M1, M3), // 18:9 // fully symmetric P8(Perm.values()); // 9:9 public final int meq; public int msk() {return meq/2;} public int meq() {return meq;} /** * Return colliding bits of given permutation mask. * @param msk of permutations (mlt20/2). * @return mask of colliding bits. */ public int collisions(int msk) { return msk & this.msk(); } /** * Find if any of the permutations of msk (mlt20/2) collides with any permutation of this group. * @param msk of permutations (mlt20/2). * @return if any permutation of perm collides with any permutation of this. */ public boolean collides(int msk) { return collisions(msk) != 0; } PGroup(Perm ... pg) { int m = 0; for(Perm p:pg) m |= 1<<(p.ordinal()); this.meq = m; } public static final List<PGroup> VALUES = List.of(values()); public String toString() { return String.format("%s(%x)", name(), meq); } /** * Generate a unique hash code smaller than 256 to implement a reverse lookup. * The actual form depends on the enumeration of Perm which cause the actual codes of meq. * This formula has been found by try and error and spreads about [0-11]. * @param meq one of the nine different patterns. * @return a compact and unique hash code. */ private static int hashCode(int meq) { return (meq/3)%13; } private static final PGroup[] GROUP = new PGroup[12]; static { // prepare a reverse lookup table // GROUP is a sparse table with unexpected masks == null // bit #0-2 are not relevant for distinction. for(PGroup p:VALUES) { int k = hashCode(p.meq); assert GROUP[k]==null : "duplicate mapping"; GROUP[k] = p; } } /** * Inverse lookup meq -> PGroup. * @param meq of RingEntry. * @return matching PGroup. */ public static PGroup group(int meq) { meq &= 0xff; // lower bits #0-2 are irrelevant for distinction. PGroup pg = GROUP[hashCode(meq)]; // verify assert pg!=null && pg.meq==meq : "PGroup does not match"; return pg; } public static PGroup group(RingEntry entry) { return group(entry.pmeq()); } public static EnumSet<PGroup> groups(final Iterable<RingEntry> entries) { EnumSet<PGroup> groups = EnumSet.noneOf(PGroup.class); for(final RingEntry e : entries) { groups.add(group(e)); } return groups; } /** * Calculate maximum partition index for a given restriction mask. * @param msk of volatile bits (1=reducing permutation). * @return the highest partition index with all permitted bits set. */ public static int pindex(Set<PGroup> groups, int msk) { // bits allowed int index = 127; for(PGroup pg:groups) { if ((pg.msk() & msk) == 0) { // clear all msk bits from index index &= 127 ^ pg.msk(); } } return index; } /** * Calculate lowest index for a given restriction mask. * @param groups occurring permutation groups. * @param msk given mlt mask. * @return lowest relevant mask filtering the same permutations. */ public static int lindex(Set<PGroup> groups, int msk) { // or ing all collisions. return groups.stream() .mapToInt(pg->pg.collisions(msk)) .reduce(0, (a,b) -> a|b); } public static int code(Set<PGroup> groups) { int code = 0; for(PGroup pg:groups) { int m = 1<<pg.ordinal(); code |= m; } return code; } public static int mask(Set<PGroup> groups) { int mask = 0; for(PGroup pg:groups) { mask |= pg.msk(); } return mask; } public static void main(String ... args) { VALUES.forEach( pg->{ EntryTable t = Entries.TABLE.filter(e->group(e)==pg); System.out.format("%s: %2d\n", pg.toString(), t.size()); } ); } } <file_sep>/scores/src/main/java/mills/score/generator/TargetGroup.java package mills.score.generator; import mills.bits.Player; import mills.bits.PopCount; import mills.index.GroupIndex; import java.util.Map; import java.util.function.Function; /** * version: $ * created by: d.stueken * created on: 07.04.2023 17:48 * modified by: $ * modified on: $ */ public class TargetGroup extends MovingGroup<TargetSlices> { public TargetGroup(PopCount pop, Player player, Map<PopCount, ? extends TargetSlices> group) { super(pop, player, group); } public static TargetGroup create(GroupIndex groups, Player player) { Function<PopCount, ScoreTarget> newTarget = clop -> ScoreTarget.allocate(groups.getIndex(clop), player); return create(groups.pop(), player, newTarget.andThen(TargetGroup::newSlices)); } public static TargetGroup create(PopCount pop, Player player, Function<PopCount, ? extends TargetSlices> slices) { Map<PopCount, ? extends TargetSlices> group = LayerGroup.group(clops(pop), slices); return new TargetGroup(pop, player, group); } static TargetSlices newSlices(ScoreTarget scores) { TargetSlices slices = TargetSlices.of(scores); slices.slices().parallelStream().forEach(TargetSlice::init); return slices; } } <file_sep>/scores/src/main/java/mills/score/generator/MovingGroups.java package mills.score.generator; import mills.bits.Player; import mills.bits.PopCount; import mills.position.Positions; import mills.score.Score; import java.util.function.LongConsumer; import java.util.stream.IntStream; /** * Created by IntelliJ IDEA. * User: stueken * Date: 27.12.19 * Time: 21:18 */ public class MovingGroups { final TargetGroup moved; final ClosingGroup closed; public MovingGroups(TargetGroup moved, ClosingGroup closed) { this.moved = moved; this.closed = closed; } public IntStream propagate(MovingGroups target, Score score) { //if(score.value>3) // DEBUG = true; Score next = score.next(); LongConsumer analyzer = m201 -> target.propagate(this, m201, next); Player targetPlayer = target.moved.player; IntStream movingTasks = moved.propagate(score, targetPlayer, analyzer); IntStream closingTasks = closed.propagate(score, targetPlayer, analyzer); return concat(closingTasks, movingTasks); } static IntStream concat(IntStream a, IntStream b) { if(a==null) return b; if(b==null) return a; return IntStream.concat(a,b); } void propagate(MovingGroups source, long i201, Score newScore) { PopCount clop = Positions.clop(i201); TargetSlices slices = moved.group.get(clop); if(slices!=null) { int posIndex = slices.scores().index.posIndex(i201); TargetSlice mapSlice = slices.get(posIndex); mapSlice.propagate(posIndex, i201, newScore.value); //ScoredPosition debug = debug(source, i201); } } } <file_sep>/scores/src/main/java/mills/score/Score.java package mills.score; import mills.util.AbstractRandomList; import java.util.List; /** * Created by IntelliJ IDEA. * User: stueken * Date: 01.01.12 * Time: 17:36 */ /* score (weight) * 0 (0) indifferent * 1 (-1) immediate loss * 2 (2) win * 3 (-3) loss * 4 (4) win * ... * 255 loss (worst) */ public class Score implements Comparable<Score> { public enum Result {LOST, DRAWN, WON} public final int value; private Score(int score) { this.value = score; } public String toString() { return String.format("%s(%d)", result(), value); } public Result result() { if(value ==0) return Result.DRAWN; if((value &1)==1) return Result.LOST; return Result.WON; } public boolean is(Result result) { return result() == result; } public int value() { return value; } public Score next() { return Score.of(value+1); } @Override public int compareTo(Score other) { if(is(Result.WON)) { if(other.is(Result.WON)) // shorter path is better return Integer.compare(other.value, value); else // or better than everything else. return +1; } if(is(Result.LOST)) { if(other.is(Result.LOST)) // longer path is better return Integer.compare(value, other.value); else // or worse than everything else. return -1; } // DRAWN assert result()!=Result.DRAWN; return Result.DRAWN.compareTo(other.result()); } //////////////////////////////////////////////////////////// public static final List<Score> SCORES = AbstractRandomList.generate(256, Score::new); public static final Score DRAWN = Score.of(0); public static final Score LOST = Score.of(1); public static final Score WON = Score.of(2); public static Score of(int score) { return SCORES.get(score); } public static boolean isWon(int score) { return score>0 && ((score & 1) == 0); } public static boolean isLost(int score) { return score>0 && (score & 1) != 0; } // calculate the shortest win or longest lost public static boolean betterThan(int s1, int s2) { assert s2>=0; // shorter win path if(Score.isWon(s1)) { if(Score.isWon(s2)) return s1 < s2; else return true; } // longer loss path if(Score.isLost(s1)) { if(Score.isLost(s2)) return s1 > s2; else return false; } assert s1==0; return isLost(s2); } } <file_sep>/scores/src/main/java/mills/score/ScoreGroup.java package mills.score; import mills.bits.Player; import mills.bits.PopCount; import mills.index.GroupIndex; import mills.index.PosIndex; import mills.util.PopMap; import java.io.File; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.ByteBuffer; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.file.StandardOpenOption; import java.util.List; /** * Created by IntelliJ IDEA. * User: stueken * Date: 19.02.23 * Time: 14:19 */ public class ScoreGroup implements AutoCloseable { final File root; final PopMap<ScoreMap> maps; ScoreGroup(GroupIndex index, File root, boolean create) { this.root = root; List<ScoreMap> scores = index.group().values().stream().map(ix->open(ix, create)).toList(); this.maps = PopMap.of(index.group().keySet(), scores); } public Player player() { return Player.White; } public ScoreMap get(PopCount clop) { return maps.get(clop); } ScoreMap open(PosIndex index, boolean create) { try { String name = String.format("m%sc%s%s.map", index.pop(), index.clop(), player()); File file = new File(root, name); if (create) return wopen(index, file); else return ropen(index, file); } catch (IOException e) { throw new UncheckedIOException(e); } } ScoreMap ropen(PosIndex index, File file) throws IOException { int size = index.range(); FileChannel fc = FileChannel.open(file.toPath(), StandardOpenOption.READ); MappedByteBuffer scores = fc.map(FileChannel.MapMode.READ_ONLY, 0, size); return new ScoreMap(scores, index, player()); } ScoreMap wopen(PosIndex index, File file) throws IOException { if(file.exists()) throw new IOException("output file already exists: " + file.getName()); int size = index.range(); ByteBuffer scores = ByteBuffer.allocateDirect(size); return new ScoreMap(scores, index, player()) { @Override public void close() { super.close(); try { FileChannel fc = FileChannel.open(file.toPath(), StandardOpenOption.WRITE, StandardOpenOption.CREATE); fc.write(scores); fc.close(); } catch (IOException e) { throw new UncheckedIOException(e); } } }; } @Override public void close() { maps.values().forEach(ScoreMap::close); } } <file_sep>/core/src/main/java/mills/util/QueueActor.java package mills.util; import java.lang.ref.Reference; import java.lang.ref.SoftReference; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.RecursiveAction; import java.util.concurrent.atomic.AtomicBoolean; /** * version: $Revision$ * created by: dst * created on: 14.05.13 11:40 * modified by: $Author$ * modified on: $Date$ */ /** * Class QueueActor executes submitted actions sequentially like synchronized operations. * If the Actor is idle, the action is executed immediately. * If the actor is busy the action is queued to be executed by someone else. */ public class QueueActor implements AutoCloseable { final ConcurrentLinkedQueue<Runnable> mbox = new ConcurrentLinkedQueue<>(); final AtomicBoolean idle = new AtomicBoolean(true); public int size() { return mbox.size(); } /** * Submit a new Action to be executed concurrently. * @param action to be executed. * @return # of executed tasks */ public int submit(Runnable action) { int processed = 0; do { if(idle.compareAndSet(true, false)) { try { processed += work(); // process any local action if(action!=null) { action.run(); action = null; ++processed; } } finally { // reset to idle idle.set(true); } } else if(action!=null) { // someone else is currently working mbox.offer(action); action = null; } // anything to do } while(!(mbox.isEmpty())); return processed; } /** * Execute any pending work. * May be called concurrently any time. * @return # of executed tasks */ protected int work() { int done = 0; // execute all actions queued for (Runnable action = mbox.poll(); action != null; action = mbox.poll()) { action.run(); ++done; } return done; } public boolean isIdle() { return idle.get(); } public void close() { if(isIdle()) return; final RecursiveAction task = new RecursiveAction() { @Override protected void compute() {} }; submit(()->task.complete(null)); task.join(); } static final Reference<Object> EMPTY = new SoftReference<>(null); @SuppressWarnings("unchecked") static <T> Reference<T> emptyRef() { return (Reference<T>)EMPTY; } }<file_sep>/core/src/main/java/mills/stones/Mills.java package mills.stones; import mills.bits.Player; import mills.bits.Sector; import java.util.List; /** * Created by IntelliJ IDEA. * User: stueken * Date: 30.12.11 * Time: 13:41 */ /** * Each entry represents a stone mask of closed mills. */ public enum Mills { NR, ER, SR, WR, // radial mills N2, E2, S2, W2, // edges on r2 N0, E0, S0, W0, // edges on r0 N1, E1, S1, W1; // edges on r1 final int closed; public static final List<Mills> MILLS = List.of(values()); Mills() { this.closed = closed(ordinal()); } public boolean matches(int stones) { return (stones& closed)== closed; } static Mills mills(int index) { return MILLS.get(index); } static int closed(int i) { if(i<4) // radial mills return 0x010101 * Sector.EDGES.get(i).mask(); // sector int k = i%4; // edge and neighboring corners int m = Sector.CORNERS.get(k).mask(); m |= Sector.EDGES.get(k).mask(); m |= Sector.CORNERS.get((k+1)%4).mask(); // ring int l = (i-4)/4; m <<= 8*l; return m; } /** * Return a bit mask (like enum set) of closed mills [0,16[ * @param stones to analyze * @return mill mask */ public static int mask(int stones) { int mask = 0; for(Mills m:MILLS) { if(m.matches(stones)) mask |= 1<<m.ordinal(); } return mask; } public static int count(int stones) { return Integer.bitCount(mask(stones)); } public static int count(long i201, Player player) { int stones = Stones.stones(i201, player); return Integer.bitCount(mask(stones)); } } <file_sep>/core/src/main/java/mills/index/GroupIndex.java package mills.index; import mills.bits.PopCount; import mills.util.PopMap; /** * Created by IntelliJ IDEA. * User: stueken * Date: 19.02.23 * Time: 14:43 */ public interface GroupIndex extends PosIndex { PopMap<? extends PosIndex> group(); default PosIndex getIndex(PopCount clop) { return clop == null ? this : group().get(clop); } } <file_sep>/scores/src/main/java/mills/score/generator/ClosingGroup.java package mills.score.generator; import mills.bits.Player; import mills.bits.PopCount; import java.util.Map; import java.util.function.Function; import java.util.stream.Stream; /** * Created by IntelliJ IDEA. * User: stueken * Date: 27.12.19 * Time: 18:55 */ public class ClosingGroup extends MovingGroup<ScoreSlices> { @Override public boolean closing() { return true; } public ClosingGroup(PopCount pop, Player player, Map<PopCount, ? extends ScoreSlices> group) { super(pop, player, group); } /** * Stream of clops for a given player after closing a mill by opponent. * @param pop count of layer. * @param opponent who closed the mill. * @return stream of clops with at least one closed mill of opponent. */ public static Stream<PopCount> clops(PopCount pop, Player opponent) { return MovingGroup.clops(pop).filter(opponent.pop::ge); } public static ClosingGroup closed(PopCount pop, Player player, Function<PopCount, ? extends ScoreSlices> slice) { Map<PopCount, ? extends ScoreSlices> slices = LayerGroup.group(clops(pop, player.opponent()), slice); return new ClosingGroup(pop, player, slices); } } <file_sep>/src/main/java/mills/board/Locations.java package mills.board; import mills.bits.Ring; import mills.bits.Sector; import java.awt.*; import java.util.ArrayList; import java.util.List; /** * Created by IntelliJ IDEA. * User: stueken * Date: 03.10.2010 * Time: 17:38:50 */ class Locations { static final int RADIUS = 100; final List<Ring2D> board = new ArrayList<>(3); class Ring2D { final List<Point> points = new ArrayList<>(8); public Point position(final Sector s) { return points.get(s.ordinal()); } Ring2D(final Ring ring) { final int size = 30 * ring.radius; for (final Sector sector : Sector.values()) { final int x = sector.x() - 1; final int y = sector.y() - 1; final Point point = new Point(RADIUS + size * x, RADIUS + size * y); points.add(point); } } } Locations() { for(final Ring r:Ring.values()) { board.add(new Ring2D(r)); } } Ring2D ring(final Ring ring) { return board.get(ring.ordinal()); } Point position(final Ring r, final Sector s) { return ring(r).position(s); } } <file_sep>/scores/src/main/java/mills/score/generator/ScoreSet.java package mills.score.generator; import mills.bits.Player; import mills.index.IndexProcessor; import mills.index.PosIndex; import mills.position.Position; import mills.position.Positions; import mills.score.Score; import java.util.logging.Level; import java.util.logging.Logger; /** * Created by IntelliJ IDEA. * User: stueken * Date: 26.10.19 * Time: 17:50 */ /** * Class ScoreSet represents a read only view of scores for a given index (pop:clop). * ScoreSets may be purely virtual if they refer to an IndexLayer which is completely lost. */ abstract public class ScoreSet implements IndexLayer { final PosIndex index; final Player player; public ScoreSet(PosIndex index, Player player) { this.index = index; this.player = player; } public String toString() { return String.format("%s%c%s", pop(), player().key(), clop()); } public int size() { return index.range(); } abstract public int getScore(int index); public void process(IndexProcessor processor, int base, int end) { index.process(processor, base, end); } public void stat(Level level) { final Logger LOGGER = Logger.getLogger(this.getClass().getName()); if(!LOGGER.isLoggable(level)) return; int won = 0; int lost = 0; int dawn = 0; int max = 0; for(int posIndex=0; posIndex<size(); ++posIndex) { int score = getScore(posIndex); if(Score.isWon(score)) ++won; else if(Score.isLost(score)) ++lost; else ++dawn; if(score>max) max = score; } LOGGER.log(level, String.format("stat %s D:%,d W:%,d L:%,d M:%d", this, dawn, won, lost, max)); } class IndexCounter implements IndexProcessor { final IndexProcessor delegate; final int score; int count = 0; IndexCounter(IndexProcessor delegate, int score) { this.delegate = delegate; this.score = score; } @Override public void process(int posIndex, long i201) { if(getScore(posIndex)==score) { delegate.process(posIndex, i201); ++count; } } } public PosIndex index() { return index; } public Player player() { return player; } public int posIndex(long i201) { int posIndex = index.posIndex(i201); if(posIndex<0) { Position pos = position(i201, player()); index.posIndex(i201); throw new IllegalStateException("missing index on:" + pos.toString()); } return posIndex; } public long i201(int posIndex) { return index.i201(posIndex); } abstract ScoreSlice<? extends ScoreSet> openSlice(int index); public ScoredPosition position(long i201) { return position(i201, player); } public ScoredPosition position(long i201, Player player) { boolean inverted = player!=this.player; int posIndex = index.posIndex(inverted ? Positions.inverted(i201) : i201); int score = getScore(posIndex); // todo: max value return new ScoredPosition(i201, player, score); } } <file_sep>/core/src/main/java/mills/ring/EmptyTable.java package mills.ring; import java.util.Collections; import java.util.Iterator; import java.util.function.Predicate; import java.util.stream.Stream; /** * Created by IntelliJ IDEA. * User: stueken * Date: 13.08.11 * Time: 18:15 */ class EmptyTable extends AbstractEntryTable implements IndexedEntryTable { static final IndexedEntryTable EMPTY = new EmptyTable(); @Override public EmptyTable filter(Predicate<? super RingEntry> predicate) { return this; } @Override public int size() { return 0; } @Override public int getIndex() { return -1; } @Override public int hashCode() { return Collections.emptyList().hashCode(); } public RingEntry get(int index) { throw new IndexOutOfBoundsException("Index: " + index); } @Override public int findIndex(int ringIndex) { return -1; } @Override public int indexOf(RingEntry entry) { return -1; } public int findIndex(RingEntry entry) { return -1; } @Override public Iterator<RingEntry> iterator() { return Collections.emptyIterator(); } public static final RingEntry[] empty = new RingEntry[0]; @Override public RingEntry[] toArray() { return empty; } @Override public Stream<RingEntry> stream() { return Stream.empty(); } } <file_sep>/core/src/main/java/mills/bits/Player.java package mills.bits; /** * Created by IntelliJ IDEA. * User: stueken * Date: 07.09.2010 * Time: 18:17:23 */ import mills.util.ListSet; import java.util.List; /** * Class Player serves as a base of a ternary system * to map a sequence of Player objects to an integer value. */ public enum Player { None(0,0) { @Override public int count(PopCount pop) { return 8 - pop.nb() - pop.nw(); } public boolean canJump(PopCount pop) { throw new IllegalArgumentException("can't jump"); } @Override public Player opponent() { throw new IllegalStateException(); } @Override public int stones(BW bw) { // void places: no white nor black return (bw.w.stones()|bw.b.stones()) ^ 0xff; } }, Black(1,0) { @Override public int count(PopCount pop) { return pop.nb(); } @Override public Player opponent() { return White; } @Override public int stones(BW bw) { return bw.b.stones(); } }, White(0,1){ @Override public int count(PopCount pop) { return pop.nw(); } @Override public Player opponent() { return Black; } @Override public int stones(BW bw) { return bw.w.stones(); } }; public int wgt() { return ordinal(); } public char key() { return Character.toLowerCase(name().charAt(0)); } abstract public int count(PopCount pop); public boolean canJump(PopCount pop) { return count(pop)<=3; } abstract public Player opponent(); public Player and(Player other) { return other==this ? this : None; } public Player either(boolean swap) { return swap ? opponent() : this; } abstract public int stones(BW bw); Player(int nb, int nw) { this.pop = PopCount.get(nb,nw); } public final PopCount pop; public static final ListSet<Player> PLAYERS = ListSet.of(Player.class); public static final List<Player> BW = List.of(Black, White); public static Player of(int i) { return PLAYERS.get(i); } } <file_sep>/core/src/test/java/mills/ring/RingEntryTest.java package mills.ring; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertTrue; public class RingEntryTest { @Test public void testCompareTo() throws Exception { RingEntry r7 = RingEntry.of(7); RingEntry r77 = RingEntry.of(77); int result = r7.compareTo(r77); assertTrue(result < 0); } }<file_sep>/scores/src/main/java/mills/score/Pair.java package mills.score; import java.util.Objects; import java.util.concurrent.ForkJoinTask; import java.util.concurrent.RecursiveTask; import java.util.function.Function; import java.util.function.Predicate; /** * version: $Revision$ * created by: dst * created on: 12.12.12 18:45 * modified by: $Author$ * modified on: $Date$ */ public class Pair<V> { public final V self; public final V other; public Pair(V self, V other) { this.self = self; this.other = other; } public Pair(Pair<? extends V> pair) { this(pair.self, pair.other); } public static <T> Pair<T> of(T self, T other) { return new Pair<>(self, other); } public String toString() { return String.format("<%s%s%s>", self, equal()?"-":",", other); } public Pair<V> swap() { if(equal()) return this; else return of(other, self); } public static <T> Pair<T> join(ForkJoinTask<T> self, ForkJoinTask<T> other) { return new Pair<>(self.join(), other.join()); } public boolean equal() { return Objects.equals(self, other); } public boolean all(Predicate<V> predicate) { return predicate.test(self) && (equal() || predicate.test(other)); } public <T> Pair<T> map(Function<? super V,? extends T> map) { final T b = map.apply(self); final T w = equal() ? b : map.apply(other); return of(b, w); } public <T> Pair<T> mapParallel(Function<? super V,? extends T> map) { if(equal()) { T mapped = map.apply(self); return of(mapped, mapped); } ForkJoinTask<T> task = new RecursiveTask<T>() { @Override protected T compute() { return map.apply(other); } }.fork(); return of(map.apply(self), task.join()); } public <T> Pair<T> pair(Function<Pair<? super V>, ? extends T> f) { final T b = f.apply(this); final T w = equal() ? b : f.apply(swap()); return of(b, w); } public <T> Pair<T> parallel1(Function<V, ? extends ForkJoinTask<T>> f) { ForkJoinTask<? extends T> t1 = f.apply(self); if(equal()) { T self = t1!=null ? t1.invoke() : null; return of(self, self); } else { if(t1!=null) t1.fork(); ForkJoinTask<? extends T> tx = f.apply(other); T other = tx!=null ? tx.invoke() : null; T self = (t1!=null) ? t1.join() : null; return of(self, other); } } public <T> Pair<T> parallel2(Function<Pair<V>, ? extends ForkJoinTask<T>> f) { ForkJoinTask<? extends T> t1 = f.apply(this); if(equal()) { T self = t1!=null ? t1.invoke() : null; return of(self, self); } else { if(t1!=null) t1.fork(); ForkJoinTask<? extends T> tx = f.apply(swap()); T other = tx!=null ? tx.invoke() : null; T self = (t1!=null) ? t1.join() : null; return of(self, other); } } public static <T> ForkJoinTask<Pair<T>> task(ForkJoinTask<T> self, ForkJoinTask<T> other) { return task(of(self, other)); } public static <T> ForkJoinTask<Pair<T>> task(final Pair<ForkJoinTask<T>> tasks) { return new RecursiveTask<>() { @Override protected Pair<T> compute() { if (tasks.equal()) { T self = tasks.self.invoke(); return of(self, self); } else { tasks.other.fork(); T self = tasks.self.invoke(); T other = tasks.other.join(); return of(self, other); } } }; } } <file_sep>/core/src/main/java/mills/util/OrderedListSet.java package mills.util; import java.util.Comparator; import java.util.List; /** * Created by IntelliJ IDEA. * User: stueken * Date: 21.08.22 * Time: 13:38 */ class OrderedListSet<T> extends DelegateListSet<T> { protected final Comparator<? super T> comparator; protected OrderedListSet(List<T> values, Comparator<? super T> comparator) { super(values); this.comparator = comparator; } @Override public Comparator<? super T> comparator() { return comparator; } @Override public boolean add(T t) { int index = findIndex(t); // already contained if (index >= 0) return false; values.add(-index - 1, t); return true; } @Override public void clear() { values.clear(); } @Override public boolean remove(Object o) { int index = findIndex((T)o); if(index<0) return false; values.remove(index); return true; } @Override public T remove(int index) { return values.remove(index); } public static <T> OrderedListSet<T> of(List<T> values, Comparator<? super T> comparator) { assert isOrdered(values, comparator) : "index mismatch"; return new OrderedListSet<>(values, comparator); } } <file_sep>/core/src/main/java/mills/position/Builder.java package mills.position; import mills.ring.RingEntry; /** * version: $ * created by: d.stueken * created on: 01.12.2022 18:04 * modified by: $ * modified on: $ */ public interface Builder { long build(RingEntry r2, RingEntry r0, RingEntry r1, int stat); default long build(short i2, short i0, short i1, int stat) { return build(RingEntry.of(i2), RingEntry.of(i0), RingEntry.of(i1), stat); } default long build(long i201) { RingEntry r2= Positions.r2(i201); RingEntry r0 = Positions.r0(i201); RingEntry r1 = Positions.r1(i201); short stat = Positions.stat(i201); return build(r2, r0, r1, stat); } } <file_sep>/scores/src/main/java/mills/score/generator/ScoreFiles.java package mills.score.generator; import mills.bits.Clops; import mills.bits.Player; import mills.bits.PopCount; import mills.index.PosIndex; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.file.FileAlreadyExistsException; import java.nio.file.NotDirectoryException; import java.nio.file.OpenOption; import java.util.Set; import static java.nio.file.StandardOpenOption.CREATE; import static java.nio.file.StandardOpenOption.READ; import static java.nio.file.StandardOpenOption.WRITE; /** * Created by IntelliJ IDEA. * User: stueken * Date: 27.10.19 * Time: 16:21 */ public class ScoreFiles { private final File root; public ScoreFiles(File root) throws IOException { this.root = root; if (root.exists()) { if (!root.isDirectory()) throw new FileAlreadyExistsException("file already exist: " + root); } root.mkdirs(); if (!root.isDirectory()) throw new NotDirectoryException(root.toString()); } public File file(Clops clops, Player player) { return file(clops.pop(), clops.clop(), player); } public File file(PopCount pop, PopCount clop, Player player) { String name = String.format("m%d%d%c%d%d.scores", pop.nb(), pop.nw(), player.key(), clop.nb(), clop.nw()); return new File(root, name); } static final Set<OpenOption> LOAD = Set.of(READ); static final Set<OpenOption> SAVE = Set.of(CREATE, WRITE); static final int BLOCK = 1<<12; int save(ScoreMap scores) throws IOException { File file = file(scores.index(), scores.player()); if(file.exists()) throw new FileAlreadyExistsException("file already exist: " + file); try(FileChannel fc = FileChannel.open(file.toPath(), SAVE)) { ByteBuffer buffer = scores.scores; int size = scores.size(); int count = 0; boolean write = false; for(int pos=0; pos<size; ++pos) { write = scores.getScore(pos)!=0; if(write) { buffer.position(pos); int last = Math.min(pos|(BLOCK-1), size-1); buffer.limit(last+1); fc.write(scores.scores, pos); buffer.clear(); pos = last; ++count; } } // last byte(s) not written. if(!write) { // add and remove a dummy byte buffer.limit(1); fc.write(scores.scores, size); buffer.clear(); fc.truncate(size); } return count; } } public ScoreMap load(PosIndex index, Player player) throws IOException { File file = file(index, player); if(file.length() != index.range()) throw new IOException("unexpected file size: " + file); try(FileChannel fc = FileChannel.open(file.toPath(), LOAD)) { int size = index.range(); ByteBuffer scores = ByteBuffer.allocateDirect(size); size -= fc.read(scores); if(size!=0) throw new IOException("incomplete read: " + file); return new ScoreMap(index, player, scores); } } public ScoreMap map(PosIndex index, Player player, boolean readonly) throws IOException { File file = file(index, player); int size = index.range(); if (file.length() != size) throw new IOException("unexpected file size: " + file); try(FileChannel fc = FileChannel.open(file.toPath(), readonly ? READ : WRITE)) { MappedByteBuffer scores = fc.map(readonly ? FileChannel.MapMode.READ_ONLY : FileChannel.MapMode.READ_WRITE, 0, size); return new ScoreMap(index, player, scores); } } } <file_sep>/src/main/java/mills/board/Stones.java package mills.board; import mills.bits.Player; import mills.bits.Ring; import mills.bits.Sector; import mills.position.Positions; import mills.ring.RingEntry; /* * version : $Revision: $ * created by : dst * date created : 05.10.2010, 14:42:32 * last mod by : $Author: $ * date last mod : $Date: $ * */ public class Stones { long stones = 0; public Stones() {} public Stones(final RingEntry inner, final RingEntry middle, final RingEntry outer) { stones |= Ring.INNER.seek(inner.index); stones |= Ring.MIDDLE.seek(middle.index); stones |= Ring.OUTER.seek(outer.index); } public Player getPlayer(int i) { final Ring r = Ring.of((i/8)%3); final Sector s = Sector.of(i%8); return getPlayer(r, s); } long seek(final Ring r, final Sector s) { return r.seek(s.pow3()); } public Player getPlayer(final Ring r, final Sector s) { long ip = stones / seek(r, s); return Player.of((int)(ip%3)); } public void setPlayer(final Ring r, final Sector s, final Player player) { long seek = seek(r, s); long ip = stones / seek(r, s); ip %= 3; ip = player.ordinal() - ip; ip *= seek; stones += ip; // not normalized any more stones &= ~Positions.NORMALIZED; } } <file_sep>/src/main/java/mills/partitions/PartitionTable.java package mills.partitions; /** * Created by IntelliJ IDEA. * User: stueken * Date: 24.04.16 * Time: 10:15 */ import mills.ring.Entries; import mills.ring.EntryTable; import mills.util.AbstractRandomArray; import java.util.Collections; import java.util.List; /** * A PartitionTable provides a list of 128 RingTables for a given restriction mask [0,128[ * Each partition contains minimized ring entries only. * */ abstract public class PartitionTable<P> extends AbstractRandomArray<P> { public final EntryTable lePop; public final List<P> partitions; public PartitionTable(List<P> partitions, EntryTable lePop) { super(128); this.lePop = lePop; this.partitions = partitions; } public static <P> PartitionTable<P> empty(P empty) { return new PartitionTable<>(Collections.emptyList(), Entries.TABLE) { @Override public P get(int index) { return empty; } }; } public static <P> PartitionTable<P> of(List<P> partitions, List<P> table, EntryTable lePop) { partitions = List.copyOf(partitions); return new PartitionTable<>(partitions, lePop) { @Override public P get(int index) { return table.get(index); } }; } } <file_sep>/src/main/java/mills/partitions/Generator.java package mills.partitions; import mills.bits.PopCount; import mills.ring.Entries; import mills.ring.EntryTable; import mills.ring.EntryTables; import mills.util.AbstractRandomList; import java.util.*; /** * Created by IntelliJ IDEA. * User: stueken * Date: 5/15/15 * Time: 3:57 PM */ class Generator { final Map<Set<PGroup>, Partition> partitions = new HashMap<>(); final EntryTables registry = new EntryTables(); public final List<Partition> table = AbstractRandomList.generate(128, this::partition); static Set<PGroup> gset(int mlt) { Set<PGroup> gset = EnumSet.allOf(PGroup.class); gset.removeIf(pg -> pg.collides(mlt)); return gset; } Partition partition(Set<PGroup> gset) { EntryTable root = Entries.MINIMIZED.filter(e -> gset.contains(PGroup.group(e))); root = registry.table(root); List<EntryTable> partitions = new ArrayList<>(); for (PopCount pop : PopCount.TABLE.subList(0, PopCount.P88.index)) { EntryTable part = root.filter(e->e.pop==pop); partitions.add(part); } partitions = registry.register(partitions); return new Partition(root, partitions, registry); } private Partition partition(int mlt) { Partition p = partitions.computeIfAbsent(Generator.gset(mlt), this::partition); return p; } public static List<Partition> partitions() { return new Generator().table; } public static void main(String ... args) { Generator g = new Generator(); for (int i = 0, tableSize = g.partitions.size(); i < tableSize; i++) { Partition partition = g.partitions.get(i); EntryTable t33 = partition.pop(PopCount.of(3,3).index); int k = t33.filter(e -> e.clop()==PopCount.EMPTY).size(); System.out.format("partition %02x [%d] %2d %2d\n", i, partition.root.size(), t33.size(), k); for(int nb=0; nb<9; ++nb) { for(int nw=0; nw<9; ++nw) { PopCount pop = PopCount.of(nb,nw); System.out.format("%3d", partition.pop(pop.index).size()); } System.out.println(); } System.out.println(); } } } <file_sep>/scores/src/main/java/mills/score/generator/ConstSet.java package mills.score.generator; import mills.bits.Player; import mills.index.PosIndex; import mills.score.Score; /** * Created by IntelliJ IDEA. * User: stueken * Date: 02.01.20 * Time: 13:05 */ public class ConstSet extends ScoreSet { final int score; public ConstSet(PosIndex index, Player player, int score) { super(index, player); this.score = score; } public ConstSet(PosIndex index, Player player, Score score) { this(index, player, score.value); } public static ConstSet lost(PosIndex index, Player player) { return new ConstSet(index, player, Score.LOST); } @Override public int getScore(int index) { return score; } @Override ScoreSlice<ConstSet> openSlice(int index) { return new ScoreSlice<>(this, index) { @Override public int max() { return score; } @Override public long marked(Score s) { return s.value==score ? 0xfffffff : 0; } @Override public ConstSet scores() { return ConstSet.this; } }; } @Override public String toString() { return super.toString() + "!" + score; } } <file_sep>/core/src/main/java/mills/util/AbstractListSet.java package mills.util; import java.util.*; import java.util.function.Consumer; import java.util.stream.Stream; import static mills.ring.RingEntry.MAX_INDEX; /** * Created by IntelliJ IDEA. * User: stueken * Date: 7/20/14 * Time: 10:32 AM */ abstract public class AbstractListSet<T> extends AbstractRandomList<T> implements ListSet<T> { @Override abstract public T get(int index); @Override abstract public int size(); @Override abstract public ListSet<T> subList(int fromIndex, int toIndex); public int checkRange(int fromIndex, int toIndex) { if(fromIndex<0) throw new IndexOutOfBoundsException("fromIndex = " + fromIndex); if (toIndex > size()) throw new IndexOutOfBoundsException("toIndex = " + toIndex); if (fromIndex > toIndex) throw new IllegalArgumentException("fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")"); return toIndex-fromIndex; } @Override public int lastIndexOf(final Object o) { // unique elements return indexOf(o); } public boolean inRange(int index) { return index >= 0 && index < MAX_INDEX; } @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof List<?> l)) return false; if (l.size() != size()) return false; for(int i=0; i<size(); ++i) { if(!Objects.equals(get(i), l.get(i))) return false; } return true; } private static final AbstractListSet<Object> EMPTY = new AbstractListSet<>() { @Override public Object get(int index) { throw new IndexOutOfBoundsException("Index: " + index); } @Override public int size() { return 0; } @Override public ListSet<Object> subList(int fromIndex, int toIndex) { checkRange(fromIndex, toIndex); return this; } @Override public Stream<Object> stream() { return Stream.of(); } @Override public void forEach(Consumer<? super Object> action) { } @Override public int hashCode() { return Collections.emptyList().hashCode(); } @Override public Comparator<Object> comparator() { return null; } }; @SuppressWarnings("unchecked") public static <T> ListSet<T> empty() { return (AbstractListSet<T>) EMPTY; } public static class Singleton<T> extends AbstractListSet<T> { final T value; public Singleton(T value) { this.value = value; } @Override public int size() { return 1; } @Override public int indexOf(Object obj) { return Objects.equals(obj, value) ? 0 : -1; } @Override public ListSet<T> subList(int fromIndex, int toIndex) { int size = checkRange(fromIndex, toIndex); if(size==0) return empty(); return this; } @Override public T get(int index) { if (index == 0) return value; else return AbstractListSet.<T>empty().get(index); } @Override public Iterator<T> iterator() { //return Iterators.singletonIterator(entry()); return super.iterator(); } @Override public Stream<T> stream() { return Stream.of(value); } @Override public void forEach(Consumer<? super T> action) { action.accept(value); } @Override public int hashCode() { return 31 + value.hashCode(); } @Override public Comparator<? super T> comparator() { return null; } } public static <T> ListSet<T> singleton(T value) { return new Singleton<>(value); } } <file_sep>/settings.gradle pluginManagement { repositories { mavenCentral() gradlePluginPortal() } } rootProject.name = 'Mills' include "core" include "index" include "scores" include "native" <file_sep>/README.md Algorithms to solve Nine Men's Morris. ===== The implementation is inspired by the paper: http://library.msri.org/books/Book29/files/gasser.pdf This is a try to realize the sketched algorithms using Java. The board itself consists of three rings of 8 positions. Each position may be void or occupied by a black or white stone. Thus we get 3^24 = 282,429,536,481 positions at all which is about 2^38.34. To 'solve' it we need some kind of score for each possible position. A first attempt is to break it down into separate partitions. A simple solution is to break it down into separate subsets of positions with a fixed population count of stones on the board: PopCount(#black, #white) During the game the number of stones first increases up to PopCount(9,9) (opening). Then players move around and may close mills. Each closed mill takes an opposite stone. This decreases the PopCount again until any Player reaches n=3. At this stage it can jump around. The final endgame is reached with PopCount(3,3) while both players can jump. Either the winner is able to close a mill and reduce the opposite stones below 3 the game ends drawn. To 'solve' the game each position is associated to a score telling if the player to move is able to win or loose or if all possible moves will be drawn (which is mostly the case). The score associated is either zero, if all possible moves are drawn, or the move count until the player wins or looses the game definitely. Even scores indicate a won position while odd scores indicate a lost position. For each PopCount(#black, #white) it must be taken into account which player will move next. Thus, there a separate score tables for black and white for each position of a given PopCount(nb,nw). However, since S(5,6,W) is equivalent S(6,5,B) the score tables to evaluate reduce to #b<=#w. Thus, with 9 stones each we only need 45 different score table instead of 100. Since all 9 score table with n<3 are lost anyway we end up with 36 different score table to evaluate. Score tables a calculated back to front starting with the end game of (3,3). Based on (3,3) the situations (4,3) and (3,4) may be evaluated until (9,9). Finally, the opening has to be traced back down to (0,1). To reduce the amount of calculations the symmetry of each position may be considered. The empty board can be rotated (*4) and mirrored (*2) to get 8 different orientations. In addition, the outer and the inner ring may be swapped without consequences on the final result. For (3:3) all rings may be interchanged without any consequences on the result. This optimization is currently not realized since the complication of the algorithm is unreasonable. One of the first tasks is to find an index function. This index will assign a unique index to each possible position. It must also be taken into account, that up to eight positions may be equivalent due to symmetry operations. The whole universe counts 8947989348 different positions. Unfortunately this is even more than 2^33. Thus, a unique position cannot be represented by a 32-bit integer. A solution is to separate the problem into different levels. Each level is represented by its occupation count. With nine stones each we get 100 possible occupations ([PopCount](https://github.com/dieterstueken/mills/blob/master/core/src/main/java/mills/bits/PopCount.java)) up to (9,9) inclusive. Class PopCount is an example of a set of precalculated instances ([Popcount.TABLE](https://github.com/dieterstueken/mills/blob/master/core/src/main/java/mills/bits/PopCount.java#L237)). For 0<=n<=9 a [ PopCount.index(nb, nw)](https://github.com/dieterstueken/mills/blob/master/core/src/main/java/mills/bits/PopCount.java#L44) can be calculated to access precalculated instances of a PopCount object. Thus, a PopCount object is equivalent to an integer. Both can be converted into each other without generating additional objects. Any object representable by an integer may implement the interface [Indexed](https://github.com/dieterstueken/mills/blob/master/core/src/main/java/mills/util/Indexed.java). This interface allows compacted representations as List, Map or Set, Indexed Objects are inherently comparable. There is a special class [ListSet](https://github.com/dieterstueken/mills/blob/master/core/src/main/java/mills/util/ListSet.java) which represents an ordered List of elements also as an SortedSet. ### Boards and Rings The board consists of three rings of eight positions each. To break down the situation further a representation of a single ring seems helpful. Each position is addressed by a [Sector](https://github.com/dieterstueken/mills/blob/master/core/src/main/java/mills/bits/Sector.java). Each Serctor may be occupied by a stone owned by a [Player](https://github.com/dieterstueken/mills/blob/master/core/src/main/java/mills/bits/Player.java) of Black(1) or White(2) while Void(0) positions are occupied by [Player.None](https://github.com/dieterstueken/mills/blob/master/core/src/main/java/mills/bits/Player.java#L18). The occupied positions of a ring are represented by a bitmask of eight bits for each [Sector](https://github.com/dieterstueken/mills/blob/master/core/src/main/java/mills/bits/Sector.java). So we get 256 different occupation [Pattern](https://github.com/dieterstueken/mills/blob/master/core/src/main/java/mills/bits/Pattern.java) represented by a List of [Pattern.PATTERNS](https://github.com/dieterstueken/mills/blob/master/core/src/main/java/mills/bits/Pattern.java#L204). Sectors are grouped into radial sectors (0-4) and positions on the edges (4-7). This groups the edge sectors onto the lower four bits of a Pattern and may be clipped using `&=0x0f`. This simplifies the handling of radial mills later on. As we have two [Player.None](https://github.com/dieterstueken/mills/blob/master/core/src/main/java/mills/bits/Player.java#L18) a Ring is represented by two [Patterns](https://github.com/dieterstueken/mills/blob/master/core/src/main/java/mills/bits/Patterns.java) for black and white each. Assuming there are no duplicate occupations on each Sector, we end up with 3^8=6561 different [Patterns](https://github.com/dieterstueken/mills/blob/master/core/src/main/java/mills/bits/Patterns.java). A Pattern is extended to a class [RingEntry](https://github.com/dieterstueken/mills/blob/master/core/src/main/java/mills/ring/RingEntry.java) which carries a lot of additional precalculated values. All possible instances of [RingEntry](https://github.com/dieterstueken/mills/blob/master/core/src/main/java/mills/ring/RingEntry.java) form a List of [Entries.TABLE](https://github.com/dieterstueken/mills/blob/master/core/src/main/java/mills/ring/Entries.java#L22). This is one of the most important objects. Each RingEntry may be transformed into an equivalent position by performing one of eight symmetry operations. A symmetry permutation is represented by the [enum Perm](https://github.com/dieterstueken/mills/blob/master/core/src/main/java/mills/bits/Perm.java). Each RingEntry has a array of eight related entries for each permutation. To brear cyclic references this array is represented by short indexes which are converted into RingEntry objects on runtime after Entries.TABLE becomes available. This is also the reason to place static Entries.TABLE into a separate class to avoid deadlocks during class loading. Important information is how one of the eight permutations affect the RingEntry. Especially if the entry (resp. its index) can be reduced by any of the eight permutations. This is represented by a mask of bits (represented by a byte) like [RingEntry.mlt](https://github.com/dieterstueken/mills/blob/master/core/src/main/java/mills/ring/RingEntry.java#L37). Several other mask are representing other questions, i.e. if the index stays stable ([RingEntry.meq](https://github.com/dieterstueken/mills/blob/master/core/src/main/java/mills/ring/RingEntry.java#L34)). <file_sep>/src/test/java/mills/TestOpening.java package mills; import mills.bits.Clops; import mills.index.IndexProvider; import mills.score.attic.opening.MovedLayer; import mills.score.attic.opening.Plop; import org.junit.jupiter.api.Test; /** * Created by IntelliJ IDEA. * User: stueken * Date: 12.11.19 * Time: 22:39 */ public class TestOpening { @Test public void testOpening() { try(IndexProvider indexes = IndexProvider.load()) { double start = System.currentTimeMillis(); MovedLayer layer = new MovedLayer(indexes, Plop.EMPTY); layer.plops(Clops.EMPTY).set(0); while(layer!=null) { double stop = System.currentTimeMillis(); System.out.format("elevate %s %.3fs\n", layer, (stop - start) / 1000); layer = layer.next(); } double stop = System.currentTimeMillis(); System.out.format("\n%.3fs\n", (stop - start) / 1000); } } } <file_sep>/index/src/main/java/mills/index/builder/Fragments.java package mills.index.builder; import mills.ring.Entries; import mills.ring.IndexedEntryTable; import mills.ring.RingEntry; import mills.util.AbstractRandomArray; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.UnaryOperator; import java.util.stream.Collectors; /** * Created by IntelliJ IDEA. * User: stueken * Date: 02.02.21 * Time: 22:40 */ public class Fragments { final IndexedEntryTable root; final List<List<IndexedEntryTable>> fragments; Fragments(IndexedEntryTable root, List<List<IndexedEntryTable>> fragments) { this.root = root; this.fragments = fragments; } public List<IndexedEntryTable> get(RingEntry rad) { return fragments.get(rad.radix()); } public String toString() { return String.format("f[%d]", root.size()); } static final Fragments EMPTY = new Fragments(IndexedEntryTable.of(), AbstractRandomArray.constant(81, List.of())); static Fragments of(IndexedEntryTable root, Tables registry) { if(root.isEmpty()) return EMPTY; if(root.size()==1) { return new Fragments(root, AbstractRandomArray.constant(81, List.of(root))); } Map<List<IndexedEntryTable>, List<IndexedEntryTable>> fragset = new HashMap<>(); var fragments = Entries.RADIALS.stream() .map(rad -> { var group = root.stream() .collect(Collectors.groupingBy(rad::clops)); var list = registry.tablesOf(group.values()); return list; }) .map(tables -> fragset.computeIfAbsent(tables, UnaryOperator.identity())).toList(); return new Fragments(root, fragments) { public String toString() { return String.format("f[%d:%d]", root.size(), fragset.size()); } }; } } <file_sep>/core/src/main/java/mills/bits/Operation.java package mills.bits; /** * Created by IntelliJ IDEA. * User: stueken * Date: 07.09.19 * Time: 15:42 */ public interface Operation { int apply(int pattern); Operation invert(); } <file_sep>/native/src/main/java/mills/Main.java package mills; import mills.position.Normalizer; import mills.position.Positions; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.LongUnaryOperator; import java.util.stream.IntStream; import static mills.ring.RingEntry.MAX_INDEX; class Main { public static void main(String ... args) { new Main().normalizerTest(); } static final long PRIME = 1009; static short index(int index) { long m = index*PRIME; return (short) (m%MAX_INDEX); } long start=System.currentTimeMillis(); final AtomicInteger count = new AtomicInteger(); volatile double limit; final double INCREMENT = Math.pow(3, 1/3.0); void normalizerTest() { count.set(0); limit = 3; long start = System.currentTimeMillis(); IntStream.range(0, MAX_INDEX).parallel().forEach(this::testI201); long stop = System.currentTimeMillis(); System.out.format("%4d: %.1f\n", count.get(), (stop - start) / 1000.0); } private void testI201(int i2) { short s2 = index(i2); for (int i0 = 0; i0 < MAX_INDEX; ++i0) { short s0 = index(i0); for (int i1 = 0; i1 < MAX_INDEX; ++i1) { short s1 = index(i0); testI201(s2, s0, s1); } } int i = count.incrementAndGet(); if(i>limit+0.5) { limit *= INCREMENT; long stop = System.currentTimeMillis(); System.out.format("%4d: %.1f\n", i-1, (stop - start) / 1000.0); } } private void testI201(short i2, short i0, short i1) { long i201 = Positions.i201(i2, i0, i1); //long m201 = Positions.NORMALIZER.build(i201); long m201 = Normalizer.NORMAL.build(i201); //assertOp(i201, m201, Normalizer.NORMAL::build); //assertOp(m201, i201, Positions::revert); } static void assertOp(long i201, long r201, LongUnaryOperator op) { long m201 = op.applyAsLong(i201); if(!Positions.equals(m201,r201)) { System.err.format("(%s)->(%s) != (%s)\n", Positions.format(i201), Positions.format(m201), Positions.format(r201)); op.applyAsLong(i201); throw new AssertionError(); } } }<file_sep>/core/src/main/java/mills/util/RandomList.java package mills.util; import java.util.Comparator; import java.util.List; import java.util.RandomAccess; import java.util.function.Function; /** * version: $ * created by: d.stueken * created on: 26.08.2022 13:12 * modified by: $ * modified on: $ */ public interface RandomList<T> extends List<T>, RandomAccess { default <E> RandomList<E> transform(Function<? super T, ? extends E> mapper) { return AbstractRandomList.transform(this, mapper); } default ListSet<T> asListSet(Comparator<? super T> comparator) { return ListSet.of(this, comparator); } default List<T> copyOf() { return List.copyOf(this); } } <file_sep>/scores/src/main/java/mills/score/attic/ScoreElevator.java package mills.score.attic; import mills.bits.Player; import mills.index.IndexProcessor; import mills.score.Score; import mills.stones.Stones; /** * Created by IntelliJ IDEA. * User: stueken * Date: 19.05.13 * Time: 16:56 */ abstract class ScoreElevator extends ScoreWorker { final IndexProcessor stuck; ScoreElevator(ScoreSlices source, ScoreSlices target) { super(source, target); this.stuck = source.stuck(); } protected SliceElevator processor() { return new SliceElevator(); } protected void processSlice(IndexProcessor processor, ScoreSlice slice) { slice.processAll(processor); } interface Elevator { int elevate(long i201); } abstract Elevator elevator(); class SliceElevator extends Processor { final Move open = Move.reverse(source.map, target.map); final Elevator elevator = elevator(); int score = 0; @Override public boolean analyze(final ScoreSlice slice, short offset, long i201) { // try to open any mill final int size = open.close(i201).size(); if (size == 0) { // no closings, any stuck? if (stuck != null) stuck.process(slice.posIndex(offset), i201); return false; } score = elevator.elevate(i201)+1; if(score==1) open.analyze(count); else if(Score.isWon(score)) open.analyze(won); else open.analyze(lost); return true; } abstract class Analyzer implements Move.Analyzer { public void analyze(final long i201) { final int index = target.map.posIndex(i201); final ScoreSlice slice = target.getSlice(index); final short offset = slice.offset(index); propagate(slice, offset, i201, score); } abstract boolean resolved(ScoreSlice slice, short offset, int score); void propagate(final ScoreSlice slice, final short offset, long i201, final int score) { if(!resolved(slice,offset, score)) slice.submit(() -> resolve(slice, offset, score)); } private void resolve(ScoreSlice slice, short offset, int score) { if(!resolved(slice, offset, score)) slice.setScore(offset, score); } } final Analyzer count = new Analyzer() { final Move count = Move.forward(target.map, source.map); void propagate(final ScoreSlice slice, final short offset, long i201, int score) { score = count.level(i201).size(); if(score!=0) super.propagate(slice, offset, i201, score); } @Override boolean resolved(ScoreSlice slice, short offset, int score) { final int current = slice.getScore(offset); if(current==score || Score.isWon(current)) return true; // leave if done or any won if(current==0) // replace any empty score return false; if(current>0) // terminate any loss path by an indifferent return false; // something went wrong String error = String.format("%s: indifferent results on %s %d/%d: %d x %d", ScoreElevator.this, slice, offset, slice.posIndex(offset), current, score); throw new IllegalStateException(error); } }; final Analyzer won = new Analyzer() { @Override boolean resolved(ScoreSlice slice, short offset, int score) { final int current = slice.getScore(offset); // only shorter win will stay return Score.isWon(current) && current <= score; } }; final Analyzer lost = new Analyzer() { @Override boolean resolved(ScoreSlice slice, short offset, int score) { final int current = slice.getScore(offset); if(current==score || Score.isWon(current)) // leave if done or any won return true; if(current==0) // replace any empty score return false; // leave any longer or even indifferent return current>=score || current < 0; } }; } public static ScoreElevator of(ScoreSlices source, ScoreSlices target, final ScoreMap downMap) { if (downMap == null) return new ScoreElevator(source, target) { public String name() { return "ScoreElevator"; } final Elevator lost = new Elevator() { public int elevate(long i201) { assert mayTake(i201); return Score.LOST.value; } // Debug private boolean mayTake(long i201) { final ScoreMap map = source.map; final Player player = map.player(); // see if opponent has closed any mill int other = Stones.stones(i201, player.opponent()); final int closed = Stones.closed(other); if (closed != 0) { int self = Stones.stones(i201, player); if (map.moves(player.opponent()).any(self, other, closed)) return true; } return false; } }; @Override Elevator elevator() { return lost; } }; else return new ScoreElevator(source, target) { public String name() { return String.format("ScoreElevator [%s]", downMap); } @Override Elevator elevator() { return new Elevator() { final Move take = Move.take(source.map, downMap); @Override public int elevate(long i201) { final int size = take.move(i201).size(); if (size == 0) return 0; int score = Score.LOST.value; for (int i = 0; i < size; ++i) { long t201 = take.get201(i); int downIndex = downMap.posIndex(t201); int s = downMap.getScore(downIndex); if(Score.betterThan(s, score)) score = s; } return score; } }; } }; } } <file_sep>/scores/src/main/java/mills/score/opening/MapProcessor.java package mills.score.opening; import mills.bits.Player; import mills.stones.Stones; import mills.util.ConcurrentCompleter; import java.util.function.LongPredicate; /** * Created by IntelliJ IDEA. * User: stueken * Date: 29.08.22 * Time: 16:33 */ public class MapProcessor { static final int CHUNK = 16*64; // this is the player on Target final OpeningMap map; final LongPredicate source; final Player player; public MapProcessor(OpeningMap map, LongPredicate source) { this.map = map; this.source = source; this.player = map.player().opponent(); } public void run() { int count = (map.index.range() + CHUNK - 1) / CHUNK; ConcurrentCompleter.compute(count, this::processChunk); } void processChunk(int chunk) { int start = chunk*CHUNK; map.index.process(this::process, start, start+CHUNK); } public void process(int posIndex, long i201) { if(analyze(i201)) map.set(posIndex); } boolean analyze(long i201) { int stay = Stones.stones(i201, player.opponent()); int move = Stones.stones(i201, player); int free = Stones.STONES ^ (stay|move); int closed = Stones.closed(move); for(int m=move, j=m&-m; j!=0; m^=j, j=m&-m) { int moved = move^j; if((closed&j)==0) { if(analyze(stay, moved)) return true; } else { if(analyzeClosed(stay, moved, free)) return true; } } // nothing hit. return false; } boolean analyze(int stay, int moved) { long i201 = Stones.i201(stay, moved, player); return source.test(i201); } boolean analyzeClosed(int removed, int moved, int free) { // closed mills after remove int closed = Stones.closed(removed); // some mill was broken boolean anyBroken = false; for(int j=free&-free; j!=0; free^=j, j=free&-free) { // j was taken int before = removed | j; // find if any mill was broken if(analyze(before, moved)) { // regular remove if((closed&j)==0) return true; else anyBroken = true; } } // report if any mill was broken. return anyBroken; } } <file_sep>/scores/src/main/java/mills/score/generator/GroupGenerator.java package mills.score.generator; import mills.bits.Player; import mills.bits.PopCount; import mills.index.GroupIndex; import mills.index.PosIndex; import java.util.Map; import java.util.concurrent.ForkJoinTask; import java.util.function.Function; import java.util.logging.Level; import java.util.logging.Logger; /** * version: $ * created by: d.stueken * created on: 11.04.2023 13:03 * modified by: $ * modified on: $ */ public class GroupGenerator extends LayerGroup<IndexLayer> { static final Logger LOGGER = Logger.getLogger(GroupGenerator.class.getName()); final GroupsGenerator groups; public GroupGenerator(GroupsGenerator groups, Player player, Map<PopCount, ? extends IndexLayer> group) { super(groups.pop, player, group); this.groups = groups; } public static GroupGenerator create(GroupsGenerator groups, GroupIndex index, Player player) { return new GroupGenerator(groups, player, IndexLayer.group(index, player)); } MovingGroups groups() { LOGGER.log(Level.FINE, ()->String.format("MovingGroups: %s%c", pop, player.key())); ForkJoinTask<ClosingGroup> closingTask = GroupsGenerator.submit(this::closingGroup); return new MovingGroups(targetGroup(), closingTask.join()); } PosIndex index(PopCount clop) { return group.get(clop).index(); } private TargetSlices targetSlices(PopCount clop) { ScoreTarget scores = ScoreTarget.allocate(index(clop), player); return TargetGroup.newSlices(scores); } private TargetGroup targetGroup() { Map<PopCount, ? extends TargetSlices> group = LayerGroup.group( MovingGroup.clops(pop), this::targetSlices); return new TargetGroup(pop, player, group); } private ScoreSlices lost(PopCount clop) { return ScoreSlices.of(ConstSet.lost(index(clop), player)); } ClosingGroup closingGroup() { if (player.count(pop) <= 3) { return ClosingGroup.closed(pop, player, this::lost); } Function<PopCount, ScoreTarget> scores = clop -> ScoreTarget.allocate(index(clop), player); GroupElevator elevator = elevator(); return ClosingGroup.closed(pop, player, scores.andThen(elevator::elevate)); } GroupElevator elevator() { Player next = this.player; PopCount down = pop.sub(player.pop); // possible swap. if(down.nw>down.nb || (down.isSym() && next==Player.Black)) { next = next.opponent(); down = down.swap(); } LayerGroup<ScoreMap> group = groups.generator.generate(down).load(next); return GroupElevator.create(group); } } <file_sep>/core/src/main/java/mills/util/AbstractRandomArray.java package mills.util; import java.util.Arrays; /** * Created by IntelliJ IDEA. * User: stueken * Date: 09.12.12 * Time: 11:58 */ public abstract class AbstractRandomArray<T> extends AbstractRandomList<T> { protected final int size; public AbstractRandomArray(int size) { this.size = size; } @Override public int size() { return size; } public static <T> AbstractRandomArray<T> virtual(T[] data) { return _asList(data); } static <T> AbstractRandomArray<T> _asList(Object[] data) { return new AbstractRandomArray<>(data.length) { @Override @SuppressWarnings("unchecked") public T get(int index) { return (T) data[index]; } @Override @SuppressWarnings("unchecked") public T set(int index, T value) { T t = (T) data[index]; if (t == value) return t; data[index] = value; modCount = 0; return t; } @Override public int hashCode() { if (modCount == 0) { this.modCount = Arrays.hashCode(data); if (this.modCount == 0) this.modCount = 1; } return modCount; } }; } } <file_sep>/scores/src/main/java/mills/score/attic/MapSlice.java package mills.score.attic; import mills.bits.Player; import mills.index.IndexProcessor; import mills.position.Position; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; /** * Created by IntelliJ IDEA. * User: stueken * Date: 07.10.13 * Time: 18:02 */ public class MapSlice { // either %= SIZE or & MAX_VALUE public static final int SIZE = Short.MAX_VALUE + 1; // a dirty block public static final int BLOCK = SIZE/Long.SIZE; public final ScoreMap map; public final int base; protected MapSlice(ScoreMap map, int index) { this.map = map; this.base = SIZE * index; } public String toString() { return String.format("%s@%d", map, sliceIndex()); } public Player player() { return map.player(); } public int size() { int size = map.size()-base; return Math.min(size, SIZE); } public static long mask(short offset) { return 1L<<(offset/BLOCK); } public int sliceIndex() { return base / SIZE; } public short offset(int posIndex) { posIndex -= base; //assert posIndex >= 0 && posIndex < SIZE; // SIZE maps to -1 return (short) (posIndex&0xffff); } public int posIndex(short offset) { int index = offset; // strip off sign bit index &= Short.MAX_VALUE; return base + index; } public long i201(short offset) { if(offset<0) throw new IllegalArgumentException("negative offset"); int posIndex = posIndex(offset); long i201 = map.i201(posIndex); //if(offset<0) // tag closed positions // i201 |= Positions.CLOSED; return i201; } // debug public Position position(long i201) { return map.position(i201); } public Position position(short offset) { long i201 = i201(offset); return map.position(i201); } public int getScore(short offset) { int posIndex = posIndex(offset); return map.getScore(posIndex); } public void setScore(short offset, int score) { int posIndex = posIndex(offset); map.setScore(posIndex, score); } public void processAll(IndexProcessor processor) { map.process(processor, base, base + size()); } public void close(final List<AtomicInteger> stat) { int size = size(); final AtomicInteger stat0 = stat.get(0); for(int i=0; i<size; ++i) { short offset = (short) i; int score = getScore(offset); if(score<0) { int posIndex = posIndex(offset); map.setScore(posIndex, 0); stat0.incrementAndGet(); } else if(score>0) { stat.get(score).incrementAndGet(); } } } } <file_sep>/scores/src/main/java/mills/score/generator/ScoredPosition.java package mills.score.generator; import mills.bits.Player; import mills.bits.PopCount; import mills.position.Position; import mills.position.Positions; class ScoredPosition extends Position implements Layer { final int score; final ScoredPosition normalized; @Override protected Position position(long i201) { return position(Positions.inverted(i201), player, score); } protected ScoredPosition position(long i201, Player player, int score) { return new ScoredPosition(i201, player, score); } protected ScoredPosition(long i201, Player player, int score) { super(i201, player); this.score = score; //posIndex = scores.index.posIndex(player==scores.player()? i201 : j201); //score = posIndex < 0 ? -1 : scores.getScore(posIndex); if (super.isNormalized) normalized = this; else normalized = position(Positions.normalize(i201), player, score); //this.inverted = inverted;//!=null ? inverted : position(j201, player.other(), score, this); } public ScoredPosition inverted() { return new ScoredPosition(Positions.inverted(i201), player.opponent(), score) { @Override public ScoredPosition inverted() { return ScoredPosition.this; } }; } @Override public StringBuilder format(StringBuilder sb) { sb = super.format(sb); sb.insert(3, player.key()); //sb.append("[").append(posIndex).append("]: "); sb.append(':'); sb.append(score); return sb; } @Override public PopCount pop() { return pop; } @Override public Player player() { return player; } } <file_sep>/src/main/java/mills/partitions/Partition.java package mills.partitions; import mills.ring.EntryTable; import mills.ring.EntryTables; import java.util.List; /** * Created by IntelliJ IDEA. * User: stueken * Date: 5/15/15 * Time: 1:38 PM */ public class Partition { public static final List<Partition> TABLE = Generator.partitions(); public final EntryTable root; public final List<EntryTable> partitions; final EntryTables registry; Partition(EntryTable root, List<EntryTable> partitions, EntryTables registry) { this.root = root; this.registry = registry; this.partitions = partitions; } public EntryTable pop(int pop) { if(pop<0 || pop>=partitions.size()) return EntryTable.of(); return partitions.get(pop); } public String toString() { return String.format("%3d", root.size()); } } <file_sep>/scores/src/main/java/mills/score/attic/ScoreCloser.java package mills.score.attic; import mills.index.IndexProcessor; import mills.score.Pair; import mills.score.Score; /** * Created by IntelliJ IDEA. * User: stueken * Date: 04.06.13 * Time: 21:04 */ public class ScoreCloser extends ScoreWorker { final int score; public ScoreCloser(ScoreSlices source, ScoreSlices target, int score) { super(source, target); this.score = score; } protected Closer processor() { return new Closer(); } protected void processSlice(IndexProcessor processor, ScoreSlice slice) { slice.processAny(processor, score); } /** * Process all lost closings of given score and replace them by a count down. * On countdown == 0 the score value is resolved. * Won closings stay unresolved. */ class Closer extends Processor { final Move count = Move.forward(source.map, target.map); boolean resolved(int current) { // either it is won or any resolved lost return Score.isWon(current) || (current>0 && current<score); } @Override boolean analyze(final ScoreSlice slice, short offset, long i201) { int current = slice.getScore(offset); if(current!=score) return false; int count = this.count.level(i201).size(); // closed score == 1 -> 0 if(count>0) // start countdown slice.setScore(offset, -count); else // leave as resolved but mark dirty again slice.any[score] |= ScoreSlice.mask(offset); return true; } } static ScoreCloser of(Pair<ScoreSlices> input, int score) { return new ScoreCloser(input.other, input.self, score); } } <file_sep>/scores/src/test/java/mills/score/ScoreTree.java package mills.score; import mills.bits.Player; import mills.bits.PopCount; import mills.position.Situation; import java.util.Collection; import java.util.Map; import java.util.NavigableSet; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; /** * Created by IntelliJ IDEA. * User: stueken * Date: 20.02.23 * Time: 15:02 */ public class ScoreTree { final Map<Situation, Set<PopCount>> layers = new TreeMap<>(); final NavigableSet<Situation> todo = new TreeSet<>(); public ScoreTree() { clops(Situation.start()).add(PopCount.EMPTY); while(!todo.isEmpty()) process(todo.pollFirst()); } void process(Situation s) { if(s==null) return; process(s, s.next()); System.out.format("%s:", s); clops(s).forEach(c->System.out.format(" %s", c)); System.out.println(); } void process(Situation s, Situation next) { Set<PopCount> clops = clops(s); // regular turn add(next, clops); // strokes // todo: may close or destroy 1 or 2 mills Player opp = s.player.opponent(); PopCount px = next.pop.sub(opp.pop); Situation stroke = Situation.of(px, next.stock, opp); if(stroke!=null) { PopCount mclop = s.pop.mclop(false); clops.stream() .map(c -> c.add(s.player.pop)) .filter(mclop::ge) .forEach(c -> stroke(next, stroke, c)); } } void stroke(Situation next, Situation stroke, PopCount clop) { add(stroke, clop); if(mayBeFrozen(next, clop)) add(next, clop); } static boolean mayBeFrozen(Situation s, PopCount clop) { Player p = s.player.opponent(); int n = p.count(s.pop); int c = p.count(clop); return switch (n) { case 3 -> c == 1; case 5, 6 -> c == 2; case 7 -> c == 3; case 8, 9 -> c == 3 || c == 4; default -> false; }; } void add(Situation s, Collection<PopCount> clops) { for (PopCount clop : clops) { add(s, clop); } } //static final Situation DEBUG = Situation.of(PopCount.of(4,6), 7, Player.Black); boolean add(Situation s, PopCount clop) { if(s.stock==0 && s.pop.nb>s.pop.nw) { s = s.swap(); clop = clop.swap(); } Set<PopCount> clops = clops(s); boolean added = clops.add(clop); if(added && s.stock>0) added = true; return added; } Set<PopCount> clops(Situation s) { return layers.computeIfAbsent(s, this::compute); } Set<PopCount> compute(Situation s) { Set<PopCount> clops = new TreeSet<>(); if(s.stock==0) { PopCount mclop = s.pop.mclop(true); PopCount.CLOPS.stream() .filter(mclop::ge) .forEach(clops::add); } else { if(s.stock+s.pop.sum()==18) clops.add(PopCount.EMPTY); } todo.add(s); return clops; } public static void main(String ... args) { new ScoreTree(); } } <file_sep>/scores/src/main/java/mills/score/generator/TargetSlices.java package mills.score.generator; import mills.util.AbstractRandomList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * Created by IntelliJ IDEA. * User: stueken * Date: 05.01.20 * Time: 10:29 */ public abstract class TargetSlices extends ScoreSlices { static final Logger LOGGER = Logger.getLogger(TargetSlices.class.getName()); abstract public ScoreTarget scores(); abstract List<? extends TargetSlice> slices(); public TargetSlice get(int posIndex) { return slices().get(posIndex / MapSlice.SIZE); } static TargetSlices of(ScoreTarget scores) { int size = ScoreSlice.sliceCount(scores); List<TargetSlice> slices = AbstractRandomList.generate(size, scores::openSlice); //slices.parallelStream().forEach(TargetSlice::init); return new TargetSlices() { @Override public ScoreTarget scores() { return scores; } @Override List<? extends TargetSlice> slices() { return slices; } }; } public void close() { slices().parallelStream().forEach(TargetSlice::close); log(); } int pending() { return slices().stream().mapToInt(TargetSlice::pending).reduce(0, Integer::max); } private void log() { if(LOGGER.isLoggable(Level.INFO)) { scores().stat(Level.INFO); LOGGER.log(Level.INFO, String.format("finished %s M:%d P:%d", scores(), max(), pending())); } } } <file_sep>/core/src/main/java/mills/position/Situation.java package mills.position; import mills.bits.Player; import mills.bits.PopCount; import mills.util.AbstractRandomList; import java.util.List; import java.util.Objects; /** * Created by IntelliJ IDEA. * User: stueken * Date: 22.12.12 * Time: 14:43 */ public class Situation implements Comparable<Situation> { public final PopCount pop; public final Player player; public final int stock; public static Situation of(PopCount pop, int stock, Player player) { assert stock >= 0 && stock <= 18 : "invalid stock"; assert player != Player.None && player != null : "no player"; if (pop == null) // null transparent return null; // no stones taken Situation full = OPENINGS.get(stock); // use directly if (full.pop.equals(pop) && full.player == player) return full; assert pop.sum() + stock <= 18 : "too many stones"; return new Situation(pop, stock, player); } public static Situation of(PopCount pop, Player player) { return of(pop, 0, player); } public Player player() { return player; } public PopCount pop() { return pop; } public String toString() { if (stock == 0) return String.format("%d%d%c", pop.nb, pop.nw, player.name().charAt(0)); else return String.format("%02d+%d%d%c", stock, pop.nb, pop.nw, player.name().charAt(0)); } public Situation swap() { return new Situation(pop.swap(), stock, player.opponent()); } public Situation next() { Player opp = player.opponent(); PopCount next = stock==0 ? pop : this.pop.add(player.pop); int stock = Math.max(0, this.stock-1); return Situation.of(next, stock, opp); } public PopCount popMax() { Situation full = OPENINGS.get(stock); return full.pop.swapIf(full.player != player); } public PopCount popTaken() { return popMax().sub(pop); } public PopCount popStock() { return PopCount.of(9, 9).sub(popTaken()); } public int taken() { return 18 - stock - pop.sum(); } public Situation hit(Player who) { PopCount hit = pop.sub(who.pop); return Situation.of(hit, stock, player); } /** * Put a new stone from stock and possibly hit some opponents stone. * * @param hit if some opponents stone to take away. * @return the new Situation or null if this action is impossible. */ public Situation put(boolean hit) { if (stock <= 0) return null; PopCount put = pop.add(player.pop); if (hit) { // take a stone put = put.sub(player.opponent().pop); if (put == null) return null; // compare stone taken to stones set PopCount full = OPENINGS.get(stock - 1).pop(); int take = player.count(full.sub(put)); int set = player.count(full); // impossible since too few mills to close if (set <= 2 * take) return null; } return Situation.of(put, stock - 1, player.opponent()); } /** * Opposite/reverse action of put(). * * @param hit if some opponents stone was taken away. * @return the new Situation or null if this action is impossible. */ public Situation xput(boolean hit) { if (stock >= 18) return null; // reverse move PopCount xput = pop.sub(player.opponent().pop); // may cause underflow if (xput == null) return null; if (hit) { // todo: compare stone taken to stones set // all stones already on board, too many stones needed. if (xput.sum() + stock + 1 >= 18) return null; xput = xput.add(player.pop); } return Situation.of(xput, stock + 1, player.opponent()); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Situation s = (Situation) o; return (stock == s.stock) && Objects.equals(player, s.player) && Objects.equals(pop, s.pop); } @Override public int hashCode() { int result = pop.hashCode(); result += 100 * stock; result += 10000 * player.ordinal(); return result; } @Override public int compareTo(final Situation o) { int result = Integer.compare(o.stock, stock); if(result==0) result = Integer.compare(o.pop.nb, pop.nb); if(result==0) result = Integer.compare(o.pop.nw, pop.nw); if(result==0) result = player.compareTo(o.player); return result; } public Position position(long i201) { return new Position(i201) { @Override public StringBuilder format(StringBuilder sb) { sb.append(Situation.this).append(" / "); sb = super.format(sb); return sb; } }; } private Situation(PopCount pop, int stock, Player player) { this.pop = pop; this.player = player; this.stock = stock; } public static final List<Situation> OPENINGS = openings(); public static Situation start() { return OPENINGS.get(18); } private static List<Situation> openings() { return AbstractRandomList.generate(19, stock -> { int step = 18 - stock; int nb = step / 2; int nw = (step + 1) / 2; PopCount pop = PopCount.of(nb, nw); Player player = (step % 2) == 0 ? Player.White : Player.Black; return new Situation(pop, stock, player); }); } } <file_sep>/core/src/main/java/mills/bits/Pattern.java package mills.bits; /** * Created by IntelliJ IDEA. * User: stueken * Date: 07.09.2010 * Time: 15:43:39 */ import mills.util.Indexed; import mills.util.ListSet; import java.util.Arrays; import java.util.function.IntFunction; /** * class Pattern represents the occupied positions on a ringTable of 8 positions. * The 256 possible combinations are kept in a static lookup table. * Thus no new objects have to be created. * Each Pattern object also keeps all possible permutations of itself in a pre calculated lookup array. */ public class Pattern extends Sectors implements Indexed { // the pattern is composed of 8 bytes of permuted pattern public final long patterns; public final short pow3; public final byte meq; public final byte count; public final byte closed; public final byte closes; public final byte mcount; // return the bit mask of occupied positions public int stones() { return (0xff & pattern); } public int getIndex() { return stones(); } // return the count of occupied bits. public int count() { //return Integer.bitCount(stones()); return count; } @Override public int size() { return count(); } public int closed() { return 0xff & closed; } public int closes() { return 0xff & closes; } public int closes(Pattern pa, Pattern pb) { int radials = pa.pattern & pb.pattern & (pattern^Sector.RADIALS); radials &= pattern^Sector.RADIALS; return 0xff & (closes | radials); } /** * Compute closed radial mills. The explicit sequence of patterns is irrelevant. * @param p2 outer pattern * @param p0 inner pattern * @param p1 middle pattern * @return a pattern of closed radial mills. */ public static int radials(Pattern p2, Pattern p0, Pattern p1) { // find radial mills first int radials = (int) (p2.pattern & p0.pattern & p1.pattern & Sector.RADIALS); // expand single bits into three radial mills again radials *= 0x010101; return radials; } public Pattern and(Pattern other) { int stones = pattern & other.pattern; return of(stones); } public Pattern or(Pattern other) { int stones = pattern | other.pattern; return of(stones); } public Pattern not() { return of(~pattern); } public Pattern of(Sector s) { return of(s.mask()); } public Pattern set(Sector sector) { return of(pattern | sector.mask()); } public Pattern clr(Sector sector) { return of(pattern & ~sector.mask()); } public boolean contains(Pattern other) { return (pattern | other.pattern) == pattern; } public Pattern radials() { return and(RADIALS); } /** * Count # of closed mills * @param p2 outer pattern * @param p0 inner pattern * @param p1 middle pattern * @return # of closed mills */ public static int mcount(Pattern p2, Pattern p0, Pattern p1) { int radials = (p2.pattern & p0.pattern & p1.pattern & Sector.RADIALS); int mcount = Sector.N.getBit(radials) + Sector.S.getBit(radials) + Sector.W.getBit(radials) + Sector.E.getBit(radials) + p2.mcount + p0.mcount + p1.mcount ; return mcount; } public int meq() { return meq; } // return permutation #i public Pattern perm(int i) { int perm = (int) (0xff & (patterns>>>8*i)); return of(perm); } /** * Map each bit to a power of 3(9, 27, 81, 243, ...). * @return accumulated results. */ public short pow3() { return pow3; } public static short pow3(int pattern) { short result = 0; for(short i3=1; pattern!=0; pattern>>>=1, i3*=3) if((pattern&1)==1) result += i3; return result; } private static final char[] SIG = {'_', '+', '?', 'x'}; public String toString() { StringBuilder sb = new StringBuilder(32); int stones = stones(); int closed = closed(); sb.append(String.format("[%02x] ", stones)); for(int i=0; i<8; i++, stones/=2, closed/=2) { int k = (stones&1) + 2*(closed&1); sb.append(SIG[k]); if(((i%8)==3)) sb.append('|'); } return sb.toString(); } /////////////////////////////////////////////////////////// // there is no need ever to create any further Bit objects private Pattern(long patterns, byte meq, byte closed, byte closes, byte mcount) { super((int)(patterns&0xff)); this.patterns = patterns; this.pow3 = pow3(pattern); this.count = (byte) super.size(); this.meq = meq; this.closed = closed; this.closes = closes; this.mcount = mcount; } public static Pattern of(int i) { return PATTERNS.get(i&0xff); } // a pre calculated list of all 256 Pattern public static final ListSet<Pattern> PATTERNS = ListSet.of(values()); public static final Pattern NONE = of(0); public static final Pattern RADIALS = of(Sector.RADIALS); public static final Pattern ALL = of(0xff); private static Pattern[] values() { IntFunction<Pattern> generate = new IntFunction<>() { final int[] mills = Sector.mills(); @Override public Pattern apply(final int i) { long pattern = 0; byte meq = 0; for(int p=0; p<8; p++) { long perm = Perm.get(p).apply(i); pattern |= perm<<(8*p); if(perm==i) meq |= 1<<p; } assert (pattern&0xff) == i : "pattern mismatch"; byte closed = 0; byte closes = 0; byte mcount = 0; for(int m:mills) { int c = m&i; if(c!=0 && c == m) {// if all thee bits are set closed |= m; // mark all of them as closed ++mcount; } else if(Integer.bitCount(c)==2) { // one of three bits is zero closes |= m^c; // accumulate as closing candidate } } return new Pattern(pattern, meq, closed, closes, mcount); } }; Pattern[] patterns = new Pattern[256]; Arrays.setAll(patterns, generate); return patterns; } } <file_sep>/core/src/main/java/mills/ring/AbstractEntryTable.java package mills.ring; import mills.util.AbstractListSet; import mills.util.Indexed; import mills.util.Indexer; import java.util.function.Predicate; /** * Created by IntelliJ IDEA. * User: stueken * Date: 15.10.11 * Time: 22:41 */ /** * An EntryTable is a List of RingEntries. * In addition, it provides utility methods to get the RingEntry.index directly, * to find the table indexOf a given RingEntry and to generate filtered subsets of itself. */ abstract public class AbstractEntryTable extends AbstractListSet<RingEntry> implements EntryTable { @Override public Indexer<Indexed> comparator() { return Indexer.INDEXED; } public int indexOf(RingEntry entry) { return findIndex(entry.index); } @Override public boolean contains(Object obj) { return indexOf(obj) >= 0; } /** * Return the index of the first element.index which is greater or equal than ringIndex. * The returned index is between [0, size] * @param ringIndex to find. * @return index of the first element which is greater than ringIndex. */ public int lowerBound(int ringIndex) { int index = findIndex(ringIndex); return index<0 ? -(index+1) : index; } /** * Return the index of the first element.index which is strictly greater than ringIndex. * The returned index is between [0, size] * @param ringIndex to find. * @return index of the first element which is greater than ringIndex. */ public int upperBound(int ringIndex) { int index = findIndex(ringIndex); return index<0 ? -(index+1) : index+1; } @Override public int indexOf(Object obj) { if(obj instanceof RingEntry) return indexOf((RingEntry) obj); else return -1; } @Override public EntryTable subList(int fromIndex, int toIndex) { int size = checkRange(fromIndex, toIndex); if(size==0) return EntryTable.of(); if(size==1) return get(fromIndex).singleton; if(size==this.size()) return this; return partition(fromIndex, size); } public EntryTable partition(int fromIndex, int size) { return new SubTable(this, fromIndex, size); } @Override public EntryTable subSet(RingEntry fromElement, RingEntry toElement) { return subList(lowerBound(fromElement.index), lowerBound(toElement.index)); } @Override public EntryTable headSet(RingEntry toElement) { return subList(0, lowerBound(toElement.index)); } @Override public EntryTable tailSet(RingEntry fromElement) { return subList(lowerBound(fromElement.index), size()); } public EntryTable filter(Predicate<? super RingEntry> predicate) { if(predicate == Entries.ALL) return this; if(predicate == Entries.NONE) return EntryTable.of(); int i0; // first match // find start of sequence for(i0=0; i0<size(); ++i0) { final RingEntry e = get(i0); if(predicate.test(e)) break; } if(i0==size()) return EntryTable.of(); int i1; // first miss // find end of sequence for(i1=i0+1; i1<size(); ++i1) { final RingEntry e = get(i1); if(!predicate.test(e)) break; } // full match if(i0==0 && i1==size()) return this; // count filtered tables int count = i1-i0; int i2 = size(); // last match (if any) for(int i=i1+1; i<size(); ++i) { final RingEntry e = get(i); if(predicate.test(e)) { ++count; i2 = Math.min(i2, i); } } if(count==1) return get(i0).singleton; // may be a sub list if(i1-i0 == count) return subList(i0, i1); // have to generate a separate list short[] indexes = new short[count]; count = 0; for(int i=i0; i<i1; ++i) { final RingEntry e = get(i); indexes[count++] = e.index; } for(int i=i2; i<size(); ++i) { final RingEntry e = get(i); if(predicate.test(e)) indexes[count++] = e.index; } assert count == indexes.length : "filter mismatch"; return EntryArray.of(indexes); } } <file_sep>/index/src/main/java/mills/index/builder/C2Builder.java package mills.index.builder; import mills.bits.PopCount; import mills.index.tables.R0Table; import mills.ring.EntryMap; import mills.ring.EntryTable; import mills.ring.RingEntry; import static java.util.function.Predicate.not; /** * Created by IntelliJ IDEA. * User: stueken * Date: 03.09.22 * Time: 15:54 */ class C2Builder { final PopCount clop; final EntryMap<R0Table> t0Tables; C2Builder(PopCount clop, EntryTable t2) { this.clop = clop; this.t0Tables = EntryMap.preset(t2, R0Table.EMPTY); } void put(RingEntry r2, R0Table t0Table) { t0Tables.put(r2, t0Table); } EntryMap<R0Table> tables() { return t0Tables.filterValues(not(R0Table::isEmpty)); } } <file_sep>/core/src/main/java/mills/bits/PopCount.java package mills.bits; import mills.util.Indexed; import mills.util.ListSet; import java.util.Objects; import java.util.function.Consumer; import java.util.function.Predicate; /** * Created by IntelliJ IDEA. * User: stueken * Date: 07.09.2010 * Time: 15:12:08 */ /** * Class PopCount defines the population of black and white stones. * PopCounts are always positive. * PopCounts<100 are provided by a precalculated lookup table. */ public class PopCount implements Indexed, Comparable<PopCount> { public final byte nb; public final byte nw; public final byte index; public final byte nb() { return nb; } public final byte nw() { return nw; } /** * Create some index function for a pair of population counts. * * @param nb black population count. * @param nw white population count. * @return a compact index for positive populations. */ public static int getIndex(int nb, int nw) { if (Math.min(nb, nw)<0) return -1; int m = Math.max(nb, nw)+1; m *= m; int d = 2*(nb-nw); m += d>0 ? 1-d : d; return m-1; } public int getIndex() { return 0xff&index; } public int sum() { return nb + nw; } public boolean isEven() { return sum()%2==0; } // fits into a single ring public boolean singleRing() { return sum()<=8; } public boolean isEmpty() { return max()==0; } public boolean isSym() { return nb==nw; } public PopCount remains() { return _of(9 - nb, 9 - nw); } public PopCount truncate(int max) { return _of(Math.min(nb, max), Math.min(nw, max)); } public static int mclop(int count) { if(count>=8) return 4; if(count>=7) return 3; if(count>=5) return 2; return count>=3 ? 1 : 0; } // maximum possible closed population /** * Maximum possible closed population. * Since each closed mill takes an opponent stone * the closed count + opponents count is limited to 9. * @param limited if the # closed mills is limited by the opponents count. * @return the maximum count of closed mills possible. */ public PopCount mclop(boolean limited) { // limit by given stones PopCount mclop = PopCount.get(mclop(nb), mclop(nw)); if(limited) { // limit by missing stones. PopCount limit = PopCount.P99.sub(this).swap(); mclop = mclop.min(limit); } return mclop; } public PopCount mclop() { return mclop(false); } /** * Return if this PopCount has less or equal occupations than another one. * An instance of PopCount is never le than null. * * @param other PopCount to compare to (may be null) * @return if this <= other. */ public boolean le(PopCount other) { return other != null && nb <= other.nb && nw <= other.nw; } public boolean ge(PopCount other) { return other != null && nb >= other.nb && nw >= other.nw; } /** * Subtract another pop count and return thr remaining population. * or null, if the remaining population drops below zero. * * @param other pop count to subtract * @return remaining population or null if negative */ public PopCount sub(final PopCount other) { final int nb = this.nb - other.nb; final int nw = this.nw - other.nw; return _of(nb, nw); } public PopCount add(final PopCount other) { final int nb = this.nb + other.nb; final int nw = this.nw + other.nw; return _of(nb, nw); } public PopCount max(final PopCount other) { final int nb = Math.max(this.nb, other.nb); final int nw = Math.max(this.nw, other.nw); return _of(nb, nw); } public PopCount min(PopCount other) { final int nb = Math.min(this.nb, other.nb); final int nw = Math.min(this.nw, other.nw); return _of(nb, nw); } public void forEach(Consumer<? super PopCount> action) { Objects.requireNonNull(action); for(int rb = 0; rb<=nb; ++rb) for(int rw = 0; rw<=nw; ++rw) { action.accept(_of(rb, rw)); } } public boolean equals() { return nb == nw; } public boolean valid() { return min() >= 3 && max() < 10; } public PopCount swap() { return _of(nw, nb); } public PopCount swapIf(boolean swap) { return swap ? swap() : this; } public int min() { return Math.min(nb, nw); } public int max() { return Math.max(nb, nw); } public final Predicate<BW> eq = (bw) -> bw != null && equals(bw.pop); public final Predicate<BW> le = (bw) -> bw != null && bw.pop.le(this); public final Predicate<BW> gt = (bw) -> bw != null && !bw.pop.le(this); @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof PopCount pop)) return false; if (nb != pop.nb) return false; if (nw != pop.nw) return false; return true; } @Override public int hashCode() { return index; } /** * Create a new PopCount. * Use factory of() to benefit from pre calculated instances * * @param nb black population count. * @param nw white population count. */ private PopCount(int nb, int nw) { this.nb = (byte) nb; this.nw = (byte) nw; this.index = (byte) getIndex(nb, nw); this.string = String.format("%X:%X", nb, nw); } private final String string; public String toString() { return string; } private PopCount _of(int nb, int nw) { if(nb==this.nb && nw==this.nw) return this; return of(nb, nw); } /** * Return a PopCount, either from the predefined table or create some new one. * Return null if either count is negative. * * @param nb black population count. * @param nw white population count. * @return a PopCount describing the given occupations, or null if negative. */ public static PopCount of(int nb, int nw) { if (Math.min(nb, nw)<0) return null; else return get(nb, nw); } /** * Get a PopCount from given positive population counts. * PopCount beyond 100 are not cached but generated. * * @param nb black population count. * @param nw white population count. * @return a PopCount describing the given occupations. */ public static PopCount get(int nb, int nw) { int index = getIndex(nb, nw); if (index < SIZE) return TABLE.get(index); // create an individual PopCount return new PopCount(nb, nw); } //////////////////////////////////////////////////////////////////////////// public static final int SIZE = 100; // index(9,9)+1 // PopCounts <= (9,9) public static final ListSet<PopCount> TABLE = ListSet.of(values()); public static final PopCount EMPTY = get(0,0); public static final PopCount P11 = get(1,1); public static final PopCount P33 = get(3,3); public static final PopCount P44 = get(4,4); public static final PopCount P88 = get(8,8); public static final PopCount P99 = get(9,9); // # of closed mills (0-4) public static final int NCLOPS = P44.index+1; public static final ListSet<PopCount> CLOPS = TABLE.subList(NCLOPS); // clop counts with at least one closed mill. public static final ListSet<PopCount> CLOSED = TABLE.subList(1, NCLOPS); public static PopCount get(int index) { return TABLE.get(index); } private static PopCount[] values() { PopCount[] table = new PopCount[SIZE]; for (int nw = 0; nw < 10; ++nw) { for (int nb = 0; nb < 10; ++nb) { PopCount p = new PopCount(nb, nw); int index = p.getIndex(); assert table[index]==null; table[index] = p; } } return table; } /** * Dump table. * * @param args unused. */ public static void main(String... args) { System.out.println("PopCount index"); System.out.print("b\\w"); for (int nw = 0; nw < 12; ++nw) { System.out.format(" %X ", nw); } System.out.println(); for (int nb = 0; nb < 12; ++nb) { System.out.format("%X ", nb); for (int nw = 0; nw < 12; ++nw) { final PopCount p = PopCount.of(nb, nw); System.out.format("%4d", p.getIndex()); } System.out.println(); } } @Override public int compareTo(PopCount o) { return Indexed.super.compareTo(o); } } <file_sep>/core/src/main/java/mills/util/ListSet.java package mills.util; import java.util.*; import java.util.function.IntFunction; /** * Created by IntelliJ IDEA. * User: stueken * Date: 03.10.19 * Time: 19:52 */ public interface ListSet<T> extends RandomList<T>, SortedSet<T> { @Override Comparator<? super T> comparator(); @Override default boolean contains(Object obj) { return indexOf(obj) >= 0; } /** * * @param entry the entry to be searched for. * @return the index of the search entry, if it is contained in the list; * otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. */ default int findIndex(T entry) { if(isEmpty()) return -1; Comparator<? super T> comparator = comparator(); int size = size(); T last = get(size-1); int cmp = comparator.compare(entry, last); if(cmp<0) // within return Collections.binarySearch(this, entry, comparator); // at end or beyond return cmp==0 ? size-1 : -size-1; } /** * This may be overridden to speed up for direct access. * @param o element to search for * @return index of the requested element or -1 if missing. */ @Override int indexOf(Object o); @Override default int lastIndexOf(Object o) { // must be unique return indexOf(o); } /** * Return the index of the first element.index which is greater or equal than ringIndex. * The returned index is between [0, size] * @param key to find. * @return index of the first element which is greater than ringIndex. */ default int lowerBound(T key) { int index = findIndex(key); return index<0 ? -(index+1) : index; } /** * Return the index of the first element.index which is strictly greater than ringIndex. * The returned index is between [0, size] * @param key to find. * @return index of the first element which is greater than ringIndex. */ default int upperBound(T key) { int index = findIndex(key); return index<0 ? -(index+1) : index+1; } @Override default T first() { if(isEmpty()) throw new NoSuchElementException(); return get(0); } @Override default T last() { if(isEmpty()) throw new NoSuchElementException(); return get(size() - 1); } @Override default ListSet<T> subSet(T fromElement, T toElement) { return subList(lowerBound(fromElement), lowerBound(toElement)); } @Override default ListSet<T> headSet(T toElement) { return subList(0, lowerBound(toElement)); } @Override default ListSet<T> tailSet(T fromElement) { return subList(lowerBound(fromElement), size()); } @Override ListSet<T> subList(int fromIndex, int toIndex); default ListSet<T> subList(int toIndex) { return subList(0, toIndex); } int checkRange(int fromIndex, int toIndex); @Override default Spliterator<T> spliterator() { // prefer RandomAccessSpliterator return RandomList.super.spliterator(); } static <T> ListSet<T> of(Comparator<? super T> comparator) { return of(new ArrayList<>(), comparator); } static <T extends Comparable<T>> ListSet<T> of() { return of(Comparator.naturalOrder()); } static <T extends Indexed> ListSet<T> ofIndexed(List<T> values) { return IndexedListSet.of(values); } static <T extends Indexed> IndexedListSet<T> ifDirect(List<T> values) { return IndexedListSet.ifDirect(values); } static <T> ListSet<T> of(List<T> values, Comparator<? super T> comparator) { return DelegateListSet.of(values, comparator); } static <T extends Indexed> ListSet<T> ofIndexed(int size, IntFunction<? extends T> generate) { return ofIndexed(AbstractRandomList.generate(size, generate)); } static <T extends Indexed> ListSet<T> ofDirect(List<T> values) { return DirectListSet.of(values, Indexer.INDEXED); } static <T> ListSet<T> ofIndexed(int size, IntFunction<? extends T> generate, Indexer<T> indexer) { return IndexedDelegate.of(AbstractRandomList.generate(size, generate), indexer); } static <T extends Comparable<? super T>> ListSet<T> of(List<T> values) { // fast track if(values instanceof ListSet) return (ListSet<T>)values; return of(values, Comparator.naturalOrder()); } static <I extends Indexed> ListSet<I> of(I[] values) { return DirectListSet.of(values, Indexer.INDEXED); } static <E extends Enum<E>> ListSet<E> of(Class<E> type) { return DirectListSet.of(type.getEnumConstants(), Indexer.ENUM); } default <V> ListMap<T, V> mapOf(List<V> values) { return ListMap.create(this, values); } } <file_sep>/index/src/main/java/mills/index/builder/GroupBuilder.java package mills.index.builder; import mills.bits.PopCount; import mills.index.tables.C2Table; import mills.ring.EntryTable; import mills.ring.RingEntry; import mills.util.ListSet; import mills.util.PopMap; import java.util.List; import java.util.function.Function; /** * Created by IntelliJ IDEA. * User: stueken * Date: 03.09.22 * Time: 11:36 */ class GroupBuilder { final Partitions partitions; final PopCount pop; final EntryTable t2; final ListSet<PopCount> clops; final PopMap<C2Builder> builders = PopMap.allocate(PopCount.NCLOPS); final C2Table[] tables = new C2Table[PopCount.NCLOPS]; private GroupBuilder(Partitions partitions, PopCount pop) { this.partitions = partitions; this.pop = pop; this.t2 = partitions.minPops.get(pop); // subset of clops to build PopCount mclop = pop.mclop(false); clops = ListSet.of(PopCount.CLOPS.stream() .filter(mclop::ge).toList()); clops.forEach(this::setupBuilder); buildEntries(); } private void setupBuilder(PopCount clop) { builders.put(clop, new C2Builder(clop, t2)); } private void buildEntries() { T0Builder builder = new T0Builder(this); partitions.pool.invoke(builder); } public PopMap<C2Table> build(Function<C2Builder, C2Table> generator) { clops.parallelStream() .map(builders::get) .map(generator) .forEach(this::put); List<C2Table> results = clops.transform(this::get).copyOf(); return PopMap.of(clops, results); } private void put(C2Table result) { tables[result.clop().index] = result; } private C2Table get(PopCount pop) { return tables[pop.index]; } RingEntry limit(RingEntry r2, RingEntry r0) { return null; } static GroupBuilder jumping(Partitions partitions, PopCount pop) { return new GroupBuilder(partitions, pop) { RingEntry limit(RingEntry r2, RingEntry r0) { RingEntry limit = r2.index > r0.index ? r2 : r0; if (r0.min() < limit.index) limit = r0; return limit; } }; } static GroupBuilder create(Partitions partitions, PopCount pop, boolean jump) { if(jump) return jumping(partitions, pop); else return new GroupBuilder(partitions, pop); } } <file_sep>/core/src/main/java/mills/util/PopMap.java package mills.util; import mills.bits.PopCount; import mills.ring.EntryTable; import java.util.List; import java.util.function.Function; /** * Created by IntelliJ IDEA. * User: stueken * Date: 04.02.21 * Time: 10:16 */ public class PopMap<T> extends ListMap<PopCount, T> { protected PopMap(ListSet<PopCount> keys, List<T> values) { super(keys, values); } public static <T> PopMap<T> of(ListSet<PopCount> keys, List<T> values) { if(keys instanceof DirectListSet<PopCount>) return ofDirect(keys, values); else return new PopMap<>(keys, values); } public static <T> PopMap<T> ofDirect(ListSet<PopCount> keys, List<T> values) { assert DirectListSet.isDirect(keys, Indexer.INDEXED); return new PopMap<>(keys, values) { @Override public T get(PopCount pop) { return getValue(pop.index); } @Override public T getOf(int index) { return getValue(index); } }; } static <T> PopMap<T> of(List<T> values) { return ofDirect(PopCount.TABLE, values); } /** * In contrast to ListMap the values determine the size which may be smaller than 100 * @return the size of this map */ @Override public int size() { return keySet.size(); } public T get(PopCount pop) { if(pop==null) return null; else return super.get(pop); } public T getOf(int index) { return get(PopCount.get(index)); } public int findIndex(PopCount pop) { return keySet.findIndex(pop); } public T put(PopCount pop, T value) { int index = findIndex(pop); return values.set(index, value); } public static <T> PopMap<T> allocate(int size) { var table = AbstractRandomList.<T>preset(size, null); return PopMap.of(table); } public static PopMap<EntryTable> lePops(EntryTable root) { return PopMap.of(PopCount.TABLE.transform(pop -> root.filter(pop.le))); } public static <T> PopMap<T> allocate() { return allocate(PopCount.SIZE); } public void dump(String head, Function<T, String> dump) { System.out.println(head); for (int nb = 0; nb < 9; nb++) { for (int nw = 0; nw < 9; nw++) { PopCount pop = PopCount.of(nb, nw); T pt = get(pop); System.out.print(dump.apply(pt)); } System.out.println(); } System.out.println(); } } <file_sep>/native/build.gradle plugins { id "java-library" id 'org.graalvm.buildtools.native' version '0.9.20' } dependencies { implementation project(':core') implementation project(':index') } nativeBuild { // Main options imageName = 'mills' // The name of the native image, defaults to the project name mainClass = 'mills.Main' // The main class to use, defaults to the application.mainClass debug = true // Determines if debug info should be generated, defaults to false verbose = true // Add verbose output, defaults to false fallback = true // Sets the fallback mode of native-image, defaults to false sharedLibrary = false // Determines if image is a shared library, defaults to false if `java-library` plugin isn't included //systemProperties = [name1: 'value1', name2: 'value2'] // Sets the system properties to use for the native image builder //configurationFileDirectories.from(file('src/my-config')) // Adds a native image configuration file directory, containing files like reflection configuration // Advanced options //buildArgs.add('-H:Extra') // Passes '-H:Extra' to the native image builder options. This can be used to pass parameters which are not directly supported by this extension //jvmArgs.add('flag') // Passes 'flag' directly to the JVM running the native image builder // Runtime options //runtimeArgs.add('--help') // Passes '--help' to built image, during "nativeRun" task // Development options //agent = true // Enables the reflection agent. Can be also set on command line using '-Pagent' useFatJar = false // Instead of passing each jar individually, builds a fat jar } <file_sep>/scores/src/main/java/mills/score/generator/MovingGroup.java package mills.score.generator; import mills.bits.Player; import mills.bits.PopCount; import mills.index.IndexProcessor; import mills.score.Score; import mills.stones.Mover; import mills.stones.Moves; import mills.stones.Stones; import java.util.List; import java.util.Map; import java.util.function.LongConsumer; import java.util.function.ToIntFunction; import java.util.stream.IntStream; import java.util.stream.Stream; /** * Created by IntelliJ IDEA. * User: stueken * Date: 27.12.19 * Time: 18:09 */ public class MovingGroup<Slices extends ScoreSlices> extends LayerGroup<Slices> { public boolean closing() { return false; } public MovingGroup(PopCount pop, Player player, Map<PopCount, ? extends Slices> group) { super(pop, player, group); } public static Stream<PopCount> clops(PopCount pop) { PopCount mclop = pop.mclop(true); return PopCount.CLOPS.stream().filter(mclop::ge); } /** * Return a stream of propagations to perform. Each returns a count of propagations. * The stream may be performed in parallel. * * @param score to analyze. * @param targetPlayer next player of target level. * @param analyzer receiving i201 positions. * @return an IntStream to be processed. */ public IntStream propagate(Score score, Player targetPlayer, LongConsumer analyzer) { List<? extends ScoreSlice<?>> slices = group.values().stream() .flatMap(ScoreSlices::stream) .filter(slice -> slice.any(score)).toList(); // collect into a temporary array. // concat is null transparent. if(slices.isEmpty()) return null; return slices.parallelStream() //parallelStream() .mapToInt(slice -> slice.processScores(processor(targetPlayer, analyzer), score)); } /** * Create an IndexProcessor to process Scores of score for each of our slices, * The moved positions are then propagated to MovedGroup target. * @param targetPlayer of target to receive the result. * @param analyzer to analyze moved positions. * @return an IndexProcessor to process a single slice. */ IndexProcessor processor(Player targetPlayer, LongConsumer analyzer) { // backtrace: moved by opponent. Player opponent = player.opponent(); // backtrace moves: move Black boolean swap = targetPlayer!=Player.White; Mover mover = Moves.moves(opponent.canJump(pop)).mover(swap); return (posIndex, i201) -> { // reversed move int stay = Stones.stones(i201, player); int move = Stones.stones(i201, opponent); int mask = Stones.closed(move); if (!closing()) mask ^= move; //Position pos = Position.of(m201); mover.move(stay, move, mask).normalize().analyze(analyzer); }; } public int count() { int count = 0; for (Slices slices : group.values()) { count += slices.slices().size(); } return count; } public int range() { int range=0; for (Slices slices : group.values()) { range += slices.index().range(); } return range; } public int max(ToIntFunction<? super Slices> count) { return group.values().stream().mapToInt(count).reduce(0, Integer::max); } } <file_sep>/core/src/main/java/mills/bits/Perms.java package mills.bits; import mills.util.Indexed; import mills.util.ListSet; import java.util.AbstractSet; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.Spliterator; import java.util.Spliterators; import java.util.stream.IntStream; /** * Created by IntelliJ IDEA. * User: stueken * Date: 29.09.19 * Time: 18:03 */ public class Perms extends AbstractSet<Perm> implements Indexed, Comparable<Perms> { public final int perms; public final int bitseq; private Perms(int perms) { this.perms = perms; this.bitseq = bitseq(perms); } @Override public int getIndex() { return perms; } @Override public int size() { return Integer.bitCount(perms); } @Override public boolean isEmpty() { return perms==0; } @Override public boolean contains(Object o) { return o instanceof Perm && this.contains((Perm)o); } public boolean contains(Perm p) { return (perms & p.msk()) != 0; } @Override public Spliterator<Perm> spliterator() { return Spliterators.spliterator(this, Spliterator.DISTINCT|Spliterator.IMMUTABLE); } public Perm first() { if(perms ==0) throw new NoSuchElementException("empty"); int i = Integer.numberOfTrailingZeros(perms); return Perm.get(i); } public Perms next() { int l = Integer.lowestOneBit(perms); if(l==0) throw new NoSuchElementException("empty"); return Perms.of(perms-l); } @Override public Iterator<Perm> iterator() { return new Itr(this); } @Override public int compareTo(Perms o) { return Indexed.super.compareTo(o); } static class Itr implements Iterator<Perm> { Perms current; public Itr(Perms current) { this.current = current; } @Override public boolean hasNext() { return !current.isEmpty(); } @Override public Perm next() { Perm next = current.first(); current = current.next(); return next; } } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(String.format("%02x:[", perms)); String sep = ""; for (Perm perm : this) { sb.append(sep); sb.append(perm.name()); sep = "|"; } sb.append("]"); return sb.toString(); } // fill a long with byte indexes of set bits. // bit 0 is ignored static int bitseq(int perms) { int bits = 0; for(int i=7; i>0; --i) { int m = 1<<i; if((perms & m)!=0) { bits <<= 4; bits += i; } } return bits; } ////////////////////////////////////////// public static final ListSet<Perms> VALUES = ListSet.ofIndexed(256, Perms::new); public static final Perms EMPTY = of(0); public static final Perms OTHER = of(0xfe); public static final int MSK = 7; public static Perms of(int perms) { return VALUES.get(perms&0xff); } public static Perms of(Perm ... perms) { int perm = 0; for (Perm p : perms) { perm |= p.msk(); } return of(perm); } public static List<Perms> listOf(int ... perms) { return IntStream.of(perms).mapToObj(Perms::of).toList(); } } <file_sep>/scores/src/main/java/mills/score/generator/ScoreMap.java package mills.score.generator; import mills.bits.Player; import mills.index.PosIndex; import java.nio.ByteBuffer; /** * Created by IntelliJ IDEA. * User: stueken * Date: 26.10.19 * Time: 17:52 */ public class ScoreMap extends ScoreSet { protected final ByteBuffer scores; public ScoreMap(PosIndex index, Player player, ByteBuffer scores) { super(index, player); this.scores = scores; } @Override public int getScore(int index) { int value = scores.get(index); value &= 0xff; // clip off sign bit return value; } MapSlice<? extends ScoreMap> openSlice(int index) { return MapSlice.of(this, index); } } <file_sep>/Sample.md mills ===== ![Board](board.png) algorithms to solve Three Man Morris
91590827da1f125152751b328e969bc01bee7001
[ "Markdown", "Java", "Gradle" ]
80
Java
dieterstueken/mills
3238f864585fe34f68b066d19df85c5999805619
ba64a399dbca245e09876f393377334f9c6ae177
refs/heads/main
<repo_name>HWshots/JogoDaMemoria<file_sep>/app.js const game = document.querySelector(".game"); const colorDiv = document.querySelector(".colorSelect"); let cardImages = []; cardImages[0] = 'AS.png'; cardImages[1] = '2S.png'; cardImages[2] = '3S.png'; cardImages[3] = '4S.png'; cardImages[4] = '5S.png'; cardImages[5] = '6S.png'; cardImages[6] = '7S.png'; cardImages[7] = '8S.png'; cardImages[8] = '9S.png'; cardImages[9] = '10S.png'; cardImages[10] = 'QS.png'; cardImages[11] = 'JS.png'; cardImages[12] = 'KS.png'; cardImages[13] = 'AH.png'; cardImages[14] = '2H.png'; cardImages[15] = '3H.png'; cardImages[16] = '4H.png'; cardImages[17] = '5H.png'; cardImages[18] = '6H.png'; cardImages[19] = '7H.png'; cardImages[20] = '8H.png'; cardImages[21] = '9H.png'; cardImages[22] = '10H.png'; cardImages[23] = 'QH.png'; cardImages[24] = 'JH.png'; cardImages[25] = 'KH.png'; cardImages[26] = 'AC.png'; cardImages[27] = '2C.png'; cardImages[28] = '3C.png'; cardImages[29] = '4C.png'; cardImages[30] = '5C.png'; cardImages[31] = '6C.png'; cardImages[32] = '7C.png'; cardImages[33] = '8C.png'; cardImages[34] = '9C.png'; cardImages[35] = '10C.png'; cardImages[36] = 'QC.png'; cardImages[37] = 'JC.png'; cardImages[38] = 'KC.png'; cardImages[39] = 'AD.png'; cardImages[40] = '2D.png'; cardImages[41] = '3D.png'; cardImages[42] = '4D.png'; cardImages[43] = '5D.png'; cardImages[44] = '6D.png'; cardImages[45] = '7D.png'; cardImages[46] = '8D.png'; cardImages[47] = '9D.png'; cardImages[48] = '10D.png'; cardImages[49] = 'QD.png'; cardImages[50] = 'JD.png'; cardImages[51] = 'KD.png'; const colorImages = []; colorImages[0] = 'gray_back.png'; colorImages[1] = 'blue_back.png'; colorImages[2] = 'green_back.png'; colorImages[3] = 'red_back.png'; colorImages[4] = 'purple_back.png'; colorImages[5] = 'yellow_back.png'; let cardGenerator = []; let position = 0; let cardPair = 2; let nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]; let gen_nums = []; let currentImage = 0; function init() { generate(); frontCards(); colorChange(); backCards(); viewportSize(); play(); } function backCards() { for (let i = 0; i < 12; i++) { const card = document.createElement("div"); card.classList.add("card"); card.dataset.index = i; game.appendChild(card); const flipCard = document.createElement("div"); flipCard.classList.add("flip-card"); card.appendChild(flipCard); const cardFront = document.createElement("div"); cardFront.classList.add("card-front"); flipCard.appendChild(cardFront); const imageFront = document.createElement("img"); imageFront.src = "images/" + colorImages[currentImage]; imageFront.classList.add("image-front"); cardFront.appendChild(imageFront); const cardBack = document.createElement("div"); cardBack.classList.add("card-back"); flipCard.appendChild(cardBack); const imageBack = document.createElement("img"); imageBack.src = "images/" + cardImages[cardGenerator[i]]; imageBack.classList.add("image-back"); cardBack.appendChild(imageBack); console.log("carta " + (i + 1) + " = " + cardImages[cardGenerator[i]]); } } function frontCards() { for (let i = 0; i < 6; i++) { const cardColor = document.createElement("div"); cardColor.classList.add("cardColor"); cardColor.dataset.index = i; colorDiv.appendChild(cardColor); const imageSelect = document.createElement("img"); imageSelect.src = "images/" + colorImages[i]; imageSelect.classList.add("image-select"); cardColor.appendChild(imageSelect); } colorChange(); } function colorChange() { colorArray = document.querySelectorAll(".cardColor"); for (let j = 0; j < colorArray.length; j++) { if (j == currentImage) { colorArray[j].classList.add("selected"); } else { colorArray[j].classList.remove("selected"); } colorArray[j].onclick = function () { currentImage = j; console.log("baralho: " + colorImages[currentImage]); const divImage = document.querySelectorAll(".image-front"); for (let i = 0;i < divImage.length; i++){ divImage[i].src = "images/" + colorImages[currentImage]; } colorChange(); } } } function generate() { for (let i = 0; i < 12; i++) { const oldPosition = position; position = get_rand(nums) - 1; if (cardPair >= 2) { let randomNumber = Math.floor(Math.random() * 52); while (cardGenerator.includes(randomNumber)) { randomNumber = Math.floor(Math.random() * 52); } cardGenerator[position] = randomNumber; cardPair--; } else { cardGenerator[position] = cardGenerator[oldPosition]; cardPair++; } } } function in_array(array, el) { for (let i = 0; i < array.length; i++) if (array[i] == el) return true; return false; } function get_rand(array) { let rand = array[Math.floor(Math.random() * array.length)]; if (!in_array(gen_nums, rand)) { gen_nums.push(rand); return rand; } return get_rand(array); } let card1 = null; let card2 = null; let cardC = []; function play() { cardC = document.querySelectorAll(".card"); for (let j = 0; j < cardC.length; j++) { cardC[j].onclick = function () { if (!this.classList.contains("hover")) { this.classList.add("hover"); if (card1 == null) { card1 = this.dataset.index; } else { card2 = this.dataset.index; } check(); } }; } } function check() { console.log("carta1 :" + cardImages[cardGenerator[card1]]); console.log("carta2 :" + cardImages[cardGenerator[card2]]); const div1 = cardC[card1]; const div2 = cardC[card2]; const hovers = document.querySelectorAll(".hover"); console.log("cartas viradas: " + hovers.length); if (cardGenerator[card1] == cardGenerator[card2] && card1 != null && card2 != null) { card1 = null; card2 = null; if (hovers.length >= 12) { alert("Ganhou!!") reset(); } } else if (card1 != null && card2 != null) { setTimeout(function () { div1.classList.remove("hover"); div2.classList.remove("hover"); }, 1000); card1 = null; card2 = null; } } function reset() { game.innerHTML = ""; colorDiv.innerHTML = ""; cardGenerator = []; position = 0; cardPair = 2; gen_nums = []; card1 = null; card2 = null; cardC = []; confirm("Novo Jogo??") init(); } init(); const newGame = document.querySelector(".header button"); newGame.addEventListener("click", reset); const exit = document.querySelector("#exit"); exit.addEventListener("click", function(){ if (confirm('Quer mesmo sair?')) { location.href='/'; } else { return false; } }); function viewportSize() { let viewPortWidth; let viewPortHeight; // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight if (typeof window.innerWidth != 'undefined') { viewPortWidth = window.innerWidth, viewPortHeight = window.innerHeight } // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document) else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0) { viewPortWidth = document.documentElement.clientWidth, viewPortHeight = document.documentElement.clientHeight } // older versions of IE else { viewPortWidth = document.getElementsByTagName('body')[0].clientWidth, viewPortHeight = document.getElementsByTagName('body')[0].clientHeight } if (viewPortWidth > (viewPortHeight * (720 / 825))) { game.style.width = "calc(88vh * (720 / 825))"; game.style.height = "88vh"; } else { game.style.width = "89vw"; game.style.height = "calc(89vw / (720 / 825))"; } } window.onresize = viewportSize;<file_sep>/README.md # JogoDaMemoria Jogo da Memoria em formação JavaScript
9f37d033b31bbcfea9a0c468444ef60e8aac3694
[ "JavaScript", "Markdown" ]
2
JavaScript
HWshots/JogoDaMemoria
a4c494e7b872893958a2d5fd1e3f8c57b6558bc3
c2dc2ed09c10f420023eeef6c92d1b6171a1f7ee
refs/heads/master
<file_sep>// 获取全局应用程序实例对象 const app = getApp() // 创建页面实例对象 Page({ /** * 页面的初始数据 */ data: { currentRuler: 0, rulerArr: [ { t: '概述' }, { t: '契约金及奖金' }, { t: '额外奖励说明' }, { t: '监督收益说明' }, { t: '打卡说明' }, { t: 'Q&A' } ], title: 'ruler' }, tabChoose (e) { this.setData({ currentRuler: e.currentTarget.dataset.index }) }, /** * 生命周期函数--监听页面加载 */ onLoad () { app.getSelf(this) // TODO: onLoad }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady () { // TODO: onReady }, /** * 生命周期函数--监听页面显示 */ onShow () { // TODO: onShow }, /** * 生命周期函数--监听页面隐藏 */ onHide () { // TODO: onHide }, /** * 生命周期函数--监听页面卸载 */ onUnload () { // TODO: onUnload }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh () { // TODO: onPullDownRefresh } }) <file_sep>// components/component-tag-name.js // const app = getApp() Component({ externalClasses: ['mask', 'mask-in'], properties: { propNav: { type: Array, value: [ { i: '../../../images/index_h.png', t: '活动', url: '../index/index', active: true }, { i: '../../../images/card.png', t: '打卡', url: '../card/card' }, { i: '../../../images/user.png', t: '我的', url: '../user/user' } ] } }, data: {} }) <file_sep># wx-sport <file_sep>// 获取全局应用程序实例对象 const app = getApp() // 创建页面实例对象 Page({ /** * 页面的初始数据 */ data: { showLocation: true, tabArr2: [ { i: '../../../images/index.png', t: '活动', url: '../index/index' }, { i: '../../../images/card_h.png', t: '打卡', url: '../card/card', active: true }, { i: '../../../images/user.png', t: '我的', url: '../user/user' } ], circles: [], title: 'siteCard' }, // 距离计算 distance (lat1, lng1, lat2, lng2) { let radLat1 = lat1 * Math.PI / 180.0 let radLat2 = lat2 * Math.PI / 180.0 let a = radLat1 - radLat2 let b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0 let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2))) s = s * 6378.137 s = Math.round(s * 10000) / 10000 if (s > 500) return false else return true }, record () { if (this.data.status) this.showModal() this.setData({ status: true }) }, // 设置打卡范围圆 setScircle (latitude, longitude) { let circle = { latitude, longitude, color: '#ffad0eff', fillColor: '#00a0e980', radius: 250, strokeWidth: 1 } this.data.circles.push(circle) this.setData({ circles: this.data.circles }) }, getUserLocation () { let that = this wx.getLocation({ type: 'gcj02', success (res2) { that.setData({ needSetting: false, latitude: res2.latitude, longitude: res2.longitude }) }, fail () { that.setData({ needSetting: true }) } }) }, openSetting () { let that = this wx.openSetting({ success (res) { if (res.authSetting['scope.userLocation']) { that.getUserLocation() } } }) }, showModal () { let that = this wx.showModal({ title: '记录结束', content: `打卡时长: ${that.data.time || '20分钟'}`, showCancel: false, confirmText: '返回', confirmColor: '#00a0e9' }) }, /** * 生命周期函数--监听页面加载 */ onLoad () { this.getUserLocation() app.getSelf(this) // TODO: onLoad }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady () { // TODO: onReady }, /** * 生命周期函数--监听页面显示 */ onShow () { // TODO: onShow }, /** * 生命周期函数--监听页面隐藏 */ onHide () { // TODO: onHide }, /** * 生命周期函数--监听页面卸载 */ onUnload () { // TODO: onUnload }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh () { // TODO: onPullDownRefresh } }) <file_sep>/** * Created by Administrator on 2017/6/2. */ // let baseDomain = 'http://group.lanzhangxiu.cn' let baseDomain = 'http://fmtg.lanzhangxiu.cn' let serviceUrl = { login: baseDomain + '/Api/User/login.html', index: baseDomain + '/Api/Index/index', goodsInfo: baseDomain + '/Api/Goods/goodsInfo', ajaxComment: baseDomain + '/Api/Goods/ajaxComment', carList: baseDomain + '/Api/Cart/index', changeNum: baseDomain + '/Api/Cart/changeNum', AsyncUpdateCart: baseDomain + '/Api/Cart/AsyncUpdateCart', delete: baseDomain + '/Api/Cart/delete', cart2: baseDomain + '/Api/Cart/cart2', cart3: baseDomain + '/Api/Cart/cart3', orderList: baseDomain + '/Api/Order/order_list', recharge: baseDomain + '/Api/User/recharge', userInfo: baseDomain + '/Api/User/index', orderConfirm: baseDomain + '/Api/Order/order_confirm', payByAccount: baseDomain + '/Api/Pay/payByAccount', fansList: baseDomain + '/Api/User/fans_list', // returnGoodsList: baseDomain + '/Api/Order/return_goods_list', taskUserList: baseDomain + '/Api/User/task_user_list', taskImageUpload: baseDomain + '/Api/User/task_image_upload', refundOrderList: baseDomain + '/Api/Order/refund_order_list', refundOrder: baseDomain + '/Api/Order/refund_order.html', refund_order_img: baseDomain + '/Api/Order/refund_order_img.html', addCar: baseDomain + '/Api/Cart/ajaxAddCart', payByUserMoney: baseDomain + '/Api/Pay/payByUserMoney', createDaifuOrder: baseDomain + '/Api/Cart/createDaifuOrder', orderTa: baseDomain + '/Api/Order/orderTa.html', payByOrderTa: baseDomain + '/Api/Pay/payByOrderTa', withdrawals: baseDomain + '/Api/User/withdrawals.html', coupon: baseDomain + '/Api/User/coupon.html', teamOrderList: baseDomain + '/Api/Order/team_order_list', orderStatus2: baseDomain + '/Api/Order/order_status2.html', pickupOrderList: baseDomain + '/Api/Order/pickup_order_list.html', withdrawalsList: baseDomain + '/Api/User/withdrawals_list.html', performance: baseDomain + '/Api/User/performance.html', orderMsg: baseDomain + '/Api/User/order_msg.html', orderDetail: baseDomain + '/Api/Order/order_detail.html', cancelOrder: baseDomain + '/Api/Order/cancel_order.html', proxySendMsg: baseDomain + '/Api/User/proxy_send_msg.html', proxyOrderList: baseDomain + '/Api/Order/proxy_order_list', proxyDelivery: baseDomain + '/Api/Order/proxy_delivery.html', pointsList: baseDomain + '/Api/User/points_list.html', accountList: baseDomain + '/Api/User/account_list', orderImageUpload: baseDomain + '/Api/Order/order_image_upload', addComment: baseDomain + '/Api/Order/add_comment', proxyRankingList: baseDomain + '/Api/User/proxy_ranking_list.html', tgList: baseDomain + '/Api/User/tg_list.html', createQRCode: baseDomain + '/Api/WeChatApp/createQRCode.html', delOrder: baseDomain + '/Api/Order/del_order.html', fansOrderList: baseDomain + '/Api/Order/fans_order_list.html', payByOrder: baseDomain + '/Api/Pay/payByOrder' } module.exports = serviceUrl <file_sep>// 获取全局应用程序实例对象 const app = getApp() // 创建页面实例对象 Page({ /** * 页面的初始数据 */ data: { testImg: app.data.testImg, indicatorColor: '#ffffff', indicatorActiveColor: '#3caa78', currentTan: 0, hot: 'https://c.jiangwenqiang.com/workProject/payKnowledge/hot.png', tabArr: ['官方活动', '主题活动'], tabArr2: [ { i: '../../../images/index_h.png', t: '活动', url: '../index/index', active: true }, { i: '../../../images/card.png', t: '打卡', url: '../card/card' }, { i: '../../../images/user.png', t: '我的', url: '../user/user' } ] }, tabChoose (e) { this.setData({ currentTan: e.currentTarget.dataset.index }) }, getLocation () { let that = this wx.getLocation({ type: 'gcj02', success (res) { that.setData({ latitude: res.latitude, longitude: res.longitude }) app.su('userLocation', res) that.getIndex() } }) }, /** * 生命周期函数--监听页面加载 */ onLoad () { app.setBar('首页') app.getSelf(this) }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady () { // console.log(' ---------- onReady ----------') }, /** * 生命周期函数--监听页面显示 */ onShow () { // console.log(' ---------- onShow ----------') }, /** * 生命周期函数--监听页面隐藏 */ onHide () { // console.log(' ---------- onHide ----------') }, /** * 生命周期函数--监听页面卸载 */ onUnload () { // console.log(' ---------- onUnload ----------') }, onShareAppMessage () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh () { // console.log(' ---------- onPullDownRefresh ----------') } }) <file_sep>// 获取全局应用程序实例对象 const app = getApp() // 创建页面实例对象 Page({ /** * 页面的初始数据 */ data: { currentTan: 0, tabArr: ['图片打卡', '位置打卡'], tabArr2: [ { i: '../../../images/index.png', t: '活动', url: '../index/index' }, { i: '../../../images/card_h.png', t: '打卡', url: '../card/card', active: true }, { i: '../../../images/user.png', t: '我的', url: '../user/user' } ], activityArr: [ { per: 20 }, { per: 30 }, { per: 40 }, { per: 50 }, { per: 55 }, { per: 78 }, { per: 90 }, { per: 95, finish: true }, { per: 100 } ], title: 'card' }, tabChoose (e) { this.setData({ currentTan: e.currentTarget.dataset.index }) }, /** * 生命周期函数--监听页面加载 */ onLoad () { app.getSelf(this) // TODO: onLoad }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady () { // TODO: onReady }, /** * 生命周期函数--监听页面显示 */ onShow () { // TODO: onShow }, /** * 生命周期函数--监听页面隐藏 */ onHide () { // TODO: onHide }, /** * 生命周期函数--监听页面卸载 */ onUnload () { // TODO: onUnload }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh () { // TODO: onPullDownRefresh } }) <file_sep>// 获取全局应用程序实例对象 const app = getApp() // 创建页面实例对象 Page({ /** * 页面的初始数据 */ data: { tabArr2: [ { i: '../../../images/index.png', t: '活动', url: '../index/index' }, { i: '../../../images/card.png', t: '打卡', url: '../card/card' }, { i: '../../../images/user_h.png', t: '我的', url: '../user/user', active: true } ], urlArr: [ { i: 'icon-09', t: '新手指南', url: '../ruler/ruler' }, { i: 'icon-tongzhi', t: '官方通知', url: '../notice/notice' }, { i: 'icon-fankuiyijian', t: '意见反馈', url: '../feedback/feedback' } ], title: 'user' }, /** * 生命周期函数--监听页面加载 */ onLoad () { app.getSelf(this) // TODO: onLoad }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady () { // TODO: onReady }, /** * 生命周期函数--监听页面显示 */ onShow () { // TODO: onShow }, /** * 生命周期函数--监听页面隐藏 */ onHide () { // TODO: onHide }, /** * 生命周期函数--监听页面卸载 */ onUnload () { // TODO: onUnload }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh () { // TODO: onPullDownRefresh } }) <file_sep>// components/component-tag-name.js const app = getApp() Component({ externalClasses: ['mask', 'mask-in'], properties: { propUser: { type: Object, value: { name: '默认用户', id: -1, url: app.data.testImg }, observer (newValue, oldValue, changePath) { this._showMask(newValue, oldValue, changePath) } } }, data: { testImg: app.data.testImg, naozai: 'https://c.jiangwenqiang.com/workProject/payKnowledge/naozai.png', currentIndex: -1, numArr: ['2', '5', '10', '20', '50', '100'] }, methods: { _choosePay (e) { this.setData({ currentIndex: e.currentTarget.dataset.index, userInputValue: this.data.numArr[e.currentTarget.dataset.index] }) }, _formSubmit (e) { let { money } = e.detail.value console.log(money) console.log(this.data.propUser) this._close() }, _close () { this.setData({ show: false, userInputValue: null, currentIndex: -1 }) }, _showMask (newValue, oldValue, changePath) { if (!newValue) { this.setData({ show: false }) } else { this.setData({ show: true }) } } } })
bca6810086f8765c3b9328ff15101a52bc18dabc
[ "JavaScript", "Markdown" ]
9
JavaScript
Say-hi/wx-sport
f829fcdb6920cd24cd28764fed8a6244a34c8ec6
dc4a65f3fae8ad6f502849d7a617f7c2f738f77a
refs/heads/master
<file_sep>package com.example.miguel.mapa_tesoro; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class WinActivity extends AppCompatActivity { String cadena = "Ya cumpliste tu trabajo, bien hecho. Asique... ¿Quieres irte ya?"; public static final int INTERVALO = 2000; //2 segundos para salir public long tiempoPrimerClick; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_win); Button btn = (Button) findViewById(R.id.bRepetir); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent (v.getContext(), MainActivity.class); startActivityForResult(intent, 0); } }); } public void salir (View view){ //para salir de la aplicacion con un dialogo de confirmacion //se prepara la alerta creando nueva instancia AlertDialog.Builder alertbox = new AlertDialog.Builder(this); //seleccionamos la cadena a mostrar alertbox.setMessage(cadena); //elegimos un positivo SI y creamos un Listener alertbox.setPositiveButton("Si", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Intent salida=new Intent( Intent.ACTION_MAIN); //Llamando a la activity principal finishAffinity(); } }); //elegimos un positivo NO y creamos un Listener alertbox.setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }); //mostramos el alertbox alertbox.show(); } public void onBackPressed(){ //se prepara la alerta creando nueva instancia AlertDialog.Builder alertbox = new AlertDialog.Builder(this); //seleccionamos la cadena a mostrar alertbox.setMessage(cadena); if (tiempoPrimerClick + INTERVALO > System.currentTimeMillis()){ super.onBackPressed(); return; }else{ alertbox.setMessage(cadena); //elegimos un positivo SI y creamos un Listener alertbox.setPositiveButton("Si", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Intent salida=new Intent( Intent.ACTION_MAIN); //Llamando a la activity principal finishAffinity(); } }); //elegimos un positivo NO y creamos un Listener alertbox.setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }); } //mostramos el alertbox alertbox.show(); } } <file_sep># La_Caza_de_los_Morty APP Juego de "La Caza de los Morty´s" ------ DATOS DEL JUEGO ------ El usuario deberá llegar a la ubicación del mapa y allí buscar el QR. Dispone de 45 minutos, su se acaba saltará la ACTIVITY de perder, Descactivará el botón de escáner y el tiempo pondrá que perdiste (por si falla algo y no haber la ACTIVITY). Si escanea los 3 QR en el tiempo saltará la ACTIVITY de ganar. Descactivará el botón de escáner y el tiempo pondrá que ganaste (por si falla algo y no haber la ACTIVITY). Una vez allí lo escaseará y lo capturará, cuando eso ocurra desaparecerá del mapa ese marcador con su radio. Si escasea un QR que no es valido le dirá por una imagen un error. Si escanea un QR correcto mas de una vez dirá por medio de una imagen que ya está escaneado. Si escanea un QR correcto le saltará una imagen de que capturó ese punto. ------ CONTENIDOS AÑADIDOS Y USADOS ------ Música en la ACTIVITY Principal Música en la ACTIVITY del MAPA Gif para las ACTIVITY Principal, Ganar y Perder Texto con fuente propia insertada en los Gif Imagen con fuente propia para el titulo del juego Icono en la ubicación del usuario cuando la localiza + botón para localizarla Marcador en el centro del Daniel Castelao Botón para una ventana de instrucciones Botones para salir y función de dar en el teléfono "Atrás" con mensaje en AlertBox Icono que será el botón de escaner Imagen para al escanear QR y capturar el punto Imagen para al escanear QR repetido Imagen para al escanear QR no compatible Clase de escaneo de QR Botón de reiniciar o de repetir en la respectiva ventana de Perder y Ganar Descripción en cada marcador a capturar y el marcado del <NAME>
07ba4165c799d5098298480b0a540bab30c96264
[ "Markdown", "Java" ]
2
Java
miguesan/La_Caza_de_los_Morty
553102c72f1a5d1ec3c50f5a072b7ffb274d8e25
996cfa6fc22df0e804b624cd303ceb05bb1729af
refs/heads/master
<file_sep>import pandas as pd import json import sqlite3 import datetime as dt import logging logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) CURRENT_DATE = dt.datetime.strftime(dt.datetime.now(), '%Y%m%d') # FUNCTION TO PULL TABLE FROM DB def pull_table(conn, name): c = conn.cursor() c.execute("SELECT * FROM "+name+CURRENT_DATE) column_slice = {'cdc_cases_by_state': [0, 1, 2, 3, 4], 'cdc_cases_by_report_date': [1, 2], 'cdc_cases_by_onset_date': [1, 2]} column_map = {'cdc_cases_by_state': {0: 'state', 1: 'range', 2: 'n_cases', 3: 'community_spread', 4: 'url'}, 'cdc_cases_by_report_date': {1: 'date', 2: 'n_cases'}, 'cdc_cases_by_onset_date': {1: 'date', 2: 'n_cases'}} index_col = {'cdc_cases_by_state': 'state', 'cdc_cases_by_report_date': 'date', 'cdc_cases_by_onset_date': 'date'} df = pd.DataFrame(c.fetchall())[column_slice[name]].rename(columns=column_map[name]).set_index(index_col[name], drop=True) logger.info(str(len(df)) + " ROWS PULLED FROM "+name) return df <file_sep>### Here's what it looks like: ![Example dashboard](https://github.com/lilyroberts/SARS-CoV-2-Analysis/blob/master/covid-dash-example.png?raw=true) ### How to run it for the first time: Navigate into project root using your command line client of choice. Run the command: ```pip install -r requirements.txt``` to prepare the environment. Then, run the command ```python application.py``` This will start the server at ```localhost:80```. The server will automatically pull updated data from the NYT and CDC sources (although the CDC has stopped updating their feed), update the database, and render the dashboard. To deploy as an application using a service like AWS Elastic Beanstalk, edit the line in ```application.py```: ```app.run_server(debug=False, port=80)``` to say: ```application.run_server(debug=False, port=80)```. This will pass the server object to the AWS backend, instead of the app object used to render the Dash app on a local server. <file_sep>import dash import dash_table import dash_core_components as dcc import dash_html_components as html import plotly.graph_objects as go import logging import sqlite3 import datetime import math import pandas as pd from update_db import update_db from pull_updated_data import pull_table from urllib.request import urlopen import json logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) logger.info('INITIALIZE DB CONNECTION') conn = sqlite3.connect('2019-nCoV-CDC.db') # UPDATE DB logger.info('UPDATE DATABASE W CDC DATA') update_db(conn) # PULL UPDATED DATA state_cols = ['state','n_cases','range','community_spread'] cases_by_state_df = pull_table(conn, 'cdc_cases_by_state')\ .sort_values('n_cases',ascending=False)\ .dropna().reset_index(drop=False)[state_cols] cases_by_report_date_df = pull_table(conn, 'cdc_cases_by_report_date').transpose() cases_by_onset_date_df = pull_table(conn, 'cdc_cases_by_onset_date').transpose() external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = dash.Dash(__name__, external_stylesheets=external_stylesheets) application = app.server colors = { 'background': '#011f4b', 'text': '#ffffff' } # show data tables # make bar chart Plotly figures cases_by_report_date_bar = go.Figure([go.Bar(x=cases_by_report_date_df.transpose().reset_index().date, y=cases_by_report_date_df.transpose().n_cases)]) cases_by_onset_date_bar = go.Figure([go.Bar(x=cases_by_onset_date_df.transpose().reset_index().date, y=cases_by_onset_date_df.transpose().n_cases)]) state_col_map = dict(state=dict(name='Jurisdiction', id='state'), range=dict(name='Range Confirmed Cases', id='range'), n_cases=dict(name='N Confirmed Cases', id='n_cases'), community_spread=dict(name='Community Spread', id='community_spread')) # create state name abbreviation mapping from file mapping_dict = pd.read_csv('state_abbrev_mapping.csv',index_col='state_name').to_dict(orient='index') cases_by_state_df['state_abbrev'] = [mapping_dict.get(i)['state_abbrev'] for i in cases_by_state_df.reset_index().dropna().state.values] # create chloropleth figure cases_by_state_chloropleth = go.Figure(data=go.Choropleth( locations=cases_by_state_df['state_abbrev'], z=cases_by_state_df['n_cases'], locationmode='USA-states', colorscale='Reds', colorbar_title='N Confirmed Cases' ) ) cases_by_state_chloropleth.update_layout(geo_scope='usa', title={'text':'Total Confirmed Cases of SARS-CoV-2 by U.S. State', 'xanchor': 'center', 'x':0.5, 'yanchor': 'top'}) counties_df = pd.read_csv('https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-counties.csv', dtype={'fips': 'str'}) nyc_fips = ['36005', '36047', '36085', '36081', '36061'] COLS = ['date', 'county', 'state', 'fips', 'cases', 'deaths'] def add_nyc_fips(row): temp_df = pd.DataFrame(columns=COLS) for i in nyc_fips: s = pd.Series([row.date, row.county, row.state, i, row.cases, row.deaths], index=COLS) temp_df = pd.concat([temp_df, pd.DataFrame(s).transpose()]).reset_index(drop=True) return temp_df nyc_counties_df = pd.DataFrame(columns=COLS) non_nyc_counties_df = counties_df[counties_df['county'] != 'New York City'] for row in counties_df[counties_df['county'] == 'New York City'].itertuples(): nyc_counties_df = pd.concat([nyc_counties_df, add_nyc_fips(row)]).reset_index(drop=True) counties_df = pd.concat([non_nyc_counties_df, nyc_counties_df]) with urlopen('https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json') as response: counties = json.load(response) most_recent_date = pd.DataFrame(counties_df.groupby(['fips']).max()['date']).to_dict()['date'] current_counties_df = counties_df[ counties_df.apply(lambda row: True if (row['date'] == most_recent_date.get(row['fips'])) else False, axis=1)] cases_by_county_chloropleth = \ go.Figure(data=go.Choroplethmapbox( geojson=counties, z=current_counties_df.cases.apply(lambda x: math.log(x)), locations=current_counties_df.fips, colorbar_title='log(N*1000) Cases', colorbar_title_side='right', colorscale='Reds', marker_opacity=0.5, marker_line_width=0)) cases_by_county_chloropleth.update_layout(mapbox_style="carto-positron", mapbox_zoom=3, mapbox_center={"lat": 37.0902, "lon": -95.7129}) cases_by_county_chloropleth.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0}, autosize=True, title_text="log(N) Confirmed Cases of SARS-CoV-2 by U.S. County", titlefont_color='#011f4b', title_x=0.5, title_y=0.95) cases_by_county_chloropleth.update_yaxes(automargin=True) display_counties_df = current_counties_df[['date','county','state','cases','deaths']] \ .drop_duplicates() \ .set_index('date') \ .sort_values('cases', ascending=False) app.layout = html.Div(children=[ html.H1(children='SARS-CoV-2', style={ 'textAlign': 'center', 'color': colors['text'], 'font':'Helvetica', 'font-weight':'bold' } ), html.Div(children=html.P(['Tracking the 2019 novel coronavirus pandemic.', html.Br(), 'Created by <NAME>', html.Br(), 'Project repository: ', html.A('https://github.com/lilyroberts/SARS-CoV-2-Analysis', href='https://github.com/lilyroberts/SARS-CoV-2-Analysis', target='_blank'), html.Br(), html.A('Donate to the Food Bank for New York City', href='https://secure3.convio.net/fbnyc/site/Donation2?df_id=9776&mfc_pref=T&9776.donation=form1&multiply=10&commas=yes', target='_blank'), html.Br()]), style={'textAlign': 'center', 'color': colors['text'], 'backgroundColor': colors['background'], 'font':'Helvetica', 'display':'block'}), # dcc.Graph( # id='cases-by-state-table', # figure=cases_by_state_table # ), # dcc.Graph( # id='cases-by-report-date-table', # figure=cases_by_report_date_table # ), html.H4(children='Reported Cases by US County', style={ 'textAlign': 'center', 'color': colors['text'], 'font': 'Helvetica' } ), dcc.Graph(id='cases_by_county_chloropleth', figure=cases_by_county_chloropleth), html.Br(), dash_table.DataTable(id='cases-by-county-dash-table', columns=[{"name": i, "id": i} for i in display_counties_df.columns], data=display_counties_df.to_dict('records'), style_cell={'textAlign': 'left'}, style_table={'overflowX': 'scroll', 'overflowY':'scroll', 'maxHeight':'330px', 'backgroundColor': colors['background'], 'color': colors['background']}, style_header={'backgroundColor': '#b3cde0', 'fontWeight': 'bold', 'textAlign': 'center'}), html.Caption('Data from New York Times - Updated at ' + str(datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %I:%M:%S %p' + ' ET')), style={'font': 'Helvetica', 'font-style':'italic', 'font-weight':'light', 'white-space': 'nowrap', 'overflowY': 'hidden', 'color': colors['text']}), html.Br(), html.H4(children='Reported Cases by US State/Territory', style={ 'textAlign': 'center', 'color': colors['text'], 'font':'Helvetica' } ), html.Br(), dcc.Graph(id='cases-by-state-chloropleth', figure=cases_by_state_chloropleth, style={'textAlign': 'center'}), html.Br(), dash_table.DataTable(id='cases-by-state-dash-table', columns=[{"name": state_col_map.get(i).get('name'), "id": state_col_map.get(i).get('id')} for i in state_cols], data=cases_by_state_df.to_dict('records'), style_table={'overflowX': 'scroll', 'backgroundColor':colors['background'], 'overflowY':'scroll', 'maxHeight':'330px'}, style_cell={'textAlign':'left'}, style_header={'backgroundColor':'#b3cde0', 'fontWeight':'bold', 'textAlign':'center'}), html.Caption('Data from CDC.gov - Updated at ' + str(datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %I:%M:%S %p' + ' ET')), style={'font': 'Helvetica', 'font-style':'italic', 'font-weight':'light', 'white-space': 'nowrap', 'overflow': 'hidden', 'color': colors['text']}), html.H4(children='Total Confirmed Cases of SARS-CoV-2 in United States', style={ 'textAlign': 'center', 'color': colors['text'], 'font':'Helvetica' } ), dcc.Graph(id='cases-by-report-date-bar', figure=cases_by_report_date_bar), html.Br(), html.Div(children='scroll >>>', style={'textAlign': 'right', 'color':'#b3cde0', 'font': 'Helvetica', 'font-style':'italic'}), dash_table.DataTable(id='cases_by_report_date_table', columns=[{"name": str(i)[:11], "id": i} for i in cases_by_report_date_df.columns], data=cases_by_report_date_df.to_dict('records'), style_cell={'textAlign': 'left'}, style_table={'overflowX': 'scroll', 'backgroundColor': colors['background'], 'color':colors['background']}, style_header={'backgroundColor': '#b3cde0', 'fontWeight': 'bold', 'textAlign': 'center'} ), html.Caption('Data from CDC.gov - Updated at ' + str(datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %I:%M:%S %p' + ' ET')), style={'font': 'Helvetica', 'font-style': 'italic', 'font-weight': 'light', 'white-space': 'nowrap', 'overflow': 'hidden', 'color': colors['text']}), html.H4(children='Count of Cases in United States by Onset Date', style={ 'textAlign': 'center', 'color': colors['text'], 'font':'Helvetica' } ), dcc.Graph(id='cases-by-onset-date-bar', figure=cases_by_onset_date_bar), html.Br(), html.Div(children='scroll >>>', style={'textAlign': 'right', 'color': '#b3cde0', 'font': 'Helvetica', 'font-style': 'italic'}), dash_table.DataTable(id='cases_by_onset_date_table', columns=[{"name": str(i)[:11], "id": i} for i in cases_by_onset_date_df.columns], data=cases_by_onset_date_df.to_dict('records'), style_table={'overflowX': 'scroll'}, style_cell={'textAlign': 'left'}, style_header={'backgroundColor': '#b3cde0', 'fontWeight': 'bold', 'font':'Helvetica', 'textAlign': 'center'} ), html.Caption('Data from CDC.gov - Updated at ' + str(datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %I:%M:%S %p' + ' ET')), style={'font': 'Helvetica', 'font-style': 'italic', 'font-weight': 'light', 'white-space': 'nowrap', 'overflow': 'hidden', 'color': colors['text']}) ], style=dict(padding='10%', margin='auto', backgroundColor=colors['background'])) if __name__ == '__main__': app.run_server(debug=False, port=80) <file_sep># -*- coding: utf-8 -*- # IMPORT NECESSARY PACKAGES import pandas as pd import numpy as np import requests import json import datetime as dt import logging logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) logger.info('SET ENVIRONMENT VARIABLES') # ENVIRONMENT VARIABLES CASES_BY_STATE_URL = 'https://www.cdc.gov/coronavirus/2019-ncov/map-cases-us.json' CASES_BY_REPORT_DATE_URL = 'https://www.cdc.gov/coronavirus/2019-ncov/cases-updates/total-cases-onset.json' CASES_BY_ONSET_DATE_URL = 'https://www.cdc.gov/coronavirus/2019-ncov/cases-updates/us-cases-epi-chart.json' CURRENT_DATE = dt.datetime.strftime(dt.datetime.now(), '%Y%m%d') # # CREDENTIALS IF NEEDED # credentials_json_path = "secrets/credentials.json" # credentials = json.load(open(credentials_json_path)) # MONGODB_USERNAME = credentials["mongodb_username"] # MONGODB_PASSWORD = credentials["<PASSWORD>"] def update_db(conn): c = conn.cursor() # GET UPDATED DATA FROM CDC logger.info('GET UPDATED DATA FROM CDC.GOV') cases_by_state_response = requests.get(CASES_BY_STATE_URL) cases_by_report_date_response = requests.get(CASES_BY_REPORT_DATE_URL) cases_by_onset_date_response = requests.get(CASES_BY_ONSET_DATE_URL) # DECODE JSON AND PULL OUT DATA logger.info('DECODE AND FORMAT DATA') cases_by_state = json.loads(cases_by_state_response.text)['data'] cases_by_report_date = json.loads(cases_by_report_date_response.text)['data']['columns'] cases_by_onset_date = json.loads(cases_by_onset_date_response.text)['data']['columns'] # CAST INTO DATAFRAMES / CLEAN / ORGANIZE cases_by_state_df = pd.DataFrame(cases_by_state) cases_by_state_df = cases_by_state_df.rename(columns={'Community Transmission�': 'community_transmission', 'Jurisdiction': 'state', 'Cases Reported': 'n_cases', 'Range': 'range', 'URL': 'url'}) cases_by_state_df = cases_by_state_df[cases_by_state_df['state'] != 'Northern Marianas'] cases_by_state_df = cases_by_state_df.set_index(['state']) cases_by_state_df.loc[(cases_by_state_df['n_cases'] == 'None'), 'n_cases'] = np.nan cases_by_state_df['n_cases'] = cases_by_state_df['n_cases'].astype(float) cases_by_report_date_df = pd.DataFrame(cases_by_report_date) cases_by_report_date_df = cases_by_report_date_df.set_index(cases_by_report_date_df[0], drop=True) cases_by_report_date_df = cases_by_report_date_df.iloc[:, 1:] \ .transpose() \ .rename(columns={'x': 'date', # ERROR IN CDC DATA HANDLED 'data1': 'n_cases', 'datat1': 'n_cases'}) \ .reset_index(drop=True) cases_by_report_date_df['date'] = pd.to_datetime(cases_by_report_date_df['date']) cases_by_report_date_df['n_cases'] = cases_by_report_date_df['n_cases'].astype(int) cases_by_onset_date_df = pd.DataFrame(cases_by_onset_date) cases_by_onset_date_df = cases_by_onset_date_df.set_index(cases_by_onset_date_df[0], drop=True) cases_by_onset_date_df = cases_by_onset_date_df.iloc[:, 1:] \ .transpose() \ .rename(columns={'x': 'date', # ERROR IN CDC DATA HANDLED 'data1': 'n_cases', 'datat1': 'n_cases'}) \ .reset_index(drop=True) cases_by_onset_date_df['date'] = pd.to_datetime(cases_by_onset_date_df['date']) cases_by_onset_date_df['n_cases'] = cases_by_onset_date_df['n_cases'].astype(int) # ADD OR UPDATE DATA INTO SQL DB logger.info('INSERT UPDATED DATA INTO DB') cases_by_state_df.to_sql(name='cdc_cases_by_state'+CURRENT_DATE, con=conn, if_exists='replace') cases_by_report_date_df.to_sql(name='cdc_cases_by_report_date'+CURRENT_DATE, con=conn, if_exists='replace') cases_by_onset_date_df.to_sql(name='cdc_cases_by_onset_date'+CURRENT_DATE, con=conn, if_exists='replace') # pull nrows for logging and error checking # by state c.execute("SELECT * FROM cdc_cases_by_state"+CURRENT_DATE) cases_by_state_nrows = len(pd.DataFrame(c.fetchall())) logger.info(str(cases_by_state_nrows) + " ROWS PERSISTED TO cdc_cases_by_state"+CURRENT_DATE) # by report date c.execute("SELECT * FROM cdc_cases_by_report_date"+CURRENT_DATE) cases_by_report_date_nrows = len(pd.DataFrame(c.fetchall())) logger.info(str(cases_by_report_date_nrows) + " ROWS PERSISTED TO cdc_cases_by_report_date"+CURRENT_DATE) # by onset date c.execute("SELECT * FROM cdc_cases_by_onset_date"+CURRENT_DATE) cases_by_onset_date_nrows = len(pd.DataFrame(c.fetchall())) logger.info(str(cases_by_onset_date_nrows) + " ROWS PERSISTED TO cdc_cases_by_onset_date"+CURRENT_DATE) return
1918edc5c390297661497c5633d67bf438aa71b3
[ "Markdown", "Python" ]
4
Python
queerpolymath/2019-nCoV-Analysis
e48e78aa694987fbda0bf7c21bf8b4f49f3e41f8
36eae08769b217fa3d4efe8e96d9a5a6160d32ad
refs/heads/master
<file_sep>package net.serenitybdd.practiseSession.pages; import org.openqa.selenium.support.FindBy; import net.serenitybdd.core.pages.PageObject; import net.serenitybdd.core.pages.WebElementFacade; import net.serenitybdd.practiseSession.utilities.HelperMethods; import net.serenitybdd.practiseSession.utilities.Utilities; public class Guru99HomePage extends PageObject { HelperMethods helper = new HelperMethods(); Utilities util = new Utilities(); // PAGE OBJECTs are located Here @FindBy(xpath = "//table//tr[@class='heading3']") private WebElementFacade homePageUserName; @FindBy(xpath = "//a[contains(text(), 'Telecom Project')]") private WebElementFacade telecomprojectLink; // Get the User name from Home Page public String getHomePageDashboardUserName() { return homePageUserName.getText(); } public void clickonTelecomprojectLink() { telecomprojectLink.waitUntilClickable().click(); } // public String getHomePageDashboardUserName() { // return homePageUserName.getText(); // } } <file_sep>package net.serenitybdd.practiseSession.steps; import cucumber.api.java.en.When; import net.serenitybdd.rest.SerenityRest; public class StudentSteps { static String email=null; // @Steps // StudentSerenitySteps steps; @When("^User sends a GET request to the list endpoint,they must get back a valid status code 200$") public void verify_status_code_200_for_listendpoint(){ // SerenityRest.rest() // .given().baseUri("https://reqres.in") // .when() // .get("/api/users") // .then() // .statusCode(200); SerenityRest.given().contentType("application/json") .when().get("https://reqres.in/api/users").then().statusCode(200); } } <file_sep>package net.serenitybdd.practiseSession.steps; import net.serenitybdd.practiseSession.model.LoginGmailData; import net.serenitybdd.practiseSession.pages.LoginGmailPage; import net.serenitybdd.practiseSession.pages.LoginPage; import net.thucydides.core.annotations.Step; import net.thucydides.core.steps.ScenarioSteps; public class LoginTestGmailSteps extends ScenarioSteps { LoginGmailPage LP; @Step public void open() { LP.openHomePage(); } @Step public void enterValidUNandPass(LoginGmailData dp) throws InterruptedException { LP.enterValidUNandPass(dp); } @Step public void closeBrowser() { getDriver().close(); getDriver().quit(); } @Step public void loginGmailAccount() { LP.loginAccount(); } } <file_sep>package net.serenitybdd.practiseSession.stepDef; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import net.serenitybdd.practiseSession.steps.WeatherApiSteps; import net.thucydides.core.annotations.Steps; public class WeatherApiStepDefinitions { // @Steps // private WeatherApiSteps wheatherCodeSteps; // // @When("I call weather api for $city") // public void callApiForCurrentWeather(String city){ // // } // // @When("I call weather api for $city and country $country") // public void callApiForCurrentWeather(String city, String country){ // // } // // @When("^I call weather api for city with \"([^\"]*)\" id$") // public void callApiForCurrentWeatherByCityId(String cityId){ // wheatherCodeSteps.requestWheatherWithCityID(cityId); // } // // @Then("weather data should be added") // public void thenDataShouldBeReceived() { // wheatherCodeSteps.verifyWheatherResponse(); // } } <file_sep>package net.serenitybdd.practiseSession.pages; import net.serenitybdd.core.annotations.findby.FindBy; import net.serenitybdd.core.pages.PageObject; import net.serenitybdd.core.pages.WebElementFacade; import net.serenitybdd.practiseSession.model.LoginGmailData; import net.thucydides.core.annotations.DefaultUrl; @DefaultUrl("https://www.gmail.com") public class LoginGmailPage extends PageObject { @FindBy(xpath="//a[contains(.,'Sign In')]") private WebElementFacade SigninButton; @FindBy(xpath="//input[contains(@type,'email')]") private WebElementFacade loginUserField; //@FindBy(xpath="//input[@type='password']") @FindBy(xpath="//*[@type='password']") private WebElementFacade loginPasswordField; @FindBy(xpath="//span[contains(.,'Next')]") private WebElementFacade NextButton; public void openHomePage() { open(); } public void enterValidUNandPass(LoginGmailData dp) throws InterruptedException { //SigninButton.click(); System.out.println("Logging in using:"+ dp.getUserName() +";" + dp.getPassword()); loginUserField.sendKeys(dp.getUserName()); NextButton.click(); Thread.sleep(2000); //loginPasswordField.waitUntilClickable().click(); //element.clear(); loginPasswordField.sendKeys(dp.<PASSWORD>()); //NextButton.click(); //loginSubmitButton.click(); } public void loginAccount() { NextButton.click(); } public boolean nextButtonIsVisible() { //boolean enabled =NextButton.isEnabled(); return NextButton.isVisible(); } } <file_sep>package net.serenitybdd.practiseSession.steps; import org.junit.Assert; import jline.internal.Log; import net.serenitybdd.practiseSession.pages.Guru99HomePage; import net.serenitybdd.practiseSession.pages.Guru99LoginPage; import net.serenitybdd.practiseSession.pages.Guru99TelecomProjectPage; import net.thucydides.core.annotations.Step; import net.thucydides.core.steps.ScenarioSteps; public class LoginTestGuru99Steps extends ScenarioSteps{ Guru99LoginPage GLP; Guru99HomePage GHP; Guru99TelecomProjectPage GTPP; @Step public void open() { GLP.open(); getDriver().manage().window().maximize(); Log.info("Browser window has been Maximized"); } @Step public void submitUnameandPass(String uname, String pass) { // TODO Auto-generated method stub GLP.loginToGuru99(uname, pass); } @Step public void logintoGuru99Accnt() { // TODO Auto-generated method stub String loginPageTitle =GLP.getLoginTitle(); Assert.assertTrue(loginPageTitle.toLowerCase().contains("guru99 bank")); Log.info("User is on the Login Page"); } @Step public void userIsOnHomePage() { // TODO Auto-generated method stub String homePageUserName = GHP.getHomePageDashboardUserName(); Log.info("User is on the Home Page"); } public void userClicksOnInsuranceProjLink() { // TODO Auto-generated method stub GHP.clickonTelecomprojectLink(); } public void insuranceLoginPagedisplayed() { // TODO Auto-generated method stub String telecomLogoInfo=GTPP.gettelecomlogoinfo(); Assert.assertTrue(telecomLogoInfo.toLowerCase().contains("guru99 telecom")); Log.info("User is on the Telecom Insurance Project Page"); } public void completeRegistration() { GTPP.clickAddCustomerLink(); } } <file_sep>package net.serenitybdd.practiseSession.steps; public class Employee { private String id; private String employee_name; private String employee_salary; private String employee_age; private String profile_image; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getEmployee_name() { return employee_name; } public void setEmployee_name(String employee_name) { this.employee_name = employee_name; } public String getEmployee_salary() { return employee_salary; } public void setEmployee_salary(String employee_salary) { this.employee_salary = employee_salary; } public String getEmployee_age() { return employee_age; } public void setEmployee_age(String employee_age) { this.employee_age = employee_age; } public String getProfile_image() { return profile_image; } public void setProfile_image(String profile_image) { this.profile_image = profile_image; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((employee_age == null) ? 0 : employee_age.hashCode()); result = prime * result + ((employee_name == null) ? 0 : employee_name.hashCode()); result = prime * result + ((employee_salary == null) ? 0 : employee_salary.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((profile_image == null) ? 0 : profile_image.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Employee other = (Employee) obj; if (employee_age == null) { if (other.employee_age != null) return false; } else if (!employee_age.equals(other.employee_age)) return false; if (employee_name == null) { if (other.employee_name != null) return false; } else if (!employee_name.equals(other.employee_name)) return false; if (employee_salary == null) { if (other.employee_salary != null) return false; } else if (!employee_salary.equals(other.employee_salary)) return false; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (profile_image == null) { if (other.profile_image != null) return false; } else if (!profile_image.equals(other.profile_image)) return false; return true; } @Override public String toString() { return "Employee [id=" + id + ", employee_name=" + employee_name + ", employee_salary=" + employee_salary + ", employee_age=" + employee_age + ", profile_image=" + profile_image + "]"; } } <file_sep>package net.serenitybdd.practiseSession.pages; import org.openqa.selenium.support.FindBy; import net.serenitybdd.core.pages.PageObject; import net.serenitybdd.core.pages.WebElementFacade; public class Guru99TelecomProjectPage extends PageObject { @FindBy(xpath="//a[@href='addcustomer.php'][1]") private WebElementFacade addCustomerlink; //@FindBy(xpath="//a[contains(text(),'Guru99 telecom')]") @FindBy(xpath=".//a[@class='logo']") private WebElementFacade Guru99telecomlogo; // @FindBy(name = "password") // WebElement password99Guru; // // @FindBy(className = "barone") // WebElement titleText; // // @FindBy(name = "btnLogin") // WebElement loginbtn; // // @FindBy(name = "btnReset") // WebElement resetbtn; // Click on login button public void clickAddCustomerLink() { addCustomerlink.click(); } // Get the info of Telecom project public String gettelecomlogoinfo() { return Guru99telecomlogo.getText(); } // public void loginToGuru99(String strUserName, String strPasword) { // // Fill user name // this.setUserName(strUserName); // // Fill password // this.setPassword(<PASSWORD>); // // Click Login button // this.clickLogin(); // } } <file_sep>package net.serenitybdd.practiseSession.steps.restapi; public class Employee { private String id; private String employee_name; private String employee_salary; private String employee_age; private String profile_image; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getEmployee_name() { return employee_name; } public void setEmployee_name(String employee_name) { this.employee_name = employee_name; } public String getEmployee_salary() { return employee_salary; } public void setEmployee_salary(String employee_salary) { this.employee_salary = employee_salary; } public String getEmployee_age() { return employee_age; } } <file_sep>package net.serenitybdd.practiseSession.pages; import com.google.common.base.Optional; import net.serenitybdd.core.pages.PageObject; import net.serenitybdd.core.pages.WebElementFacade; //import net.serenitybdd.practiseSession.utilities.HelperMethods; import net.serenitybdd.practiseSession.utilities.HelperMethods; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import java.util.List; import java.util.stream.Collectors; //tag::header[] public class SearchResultsPage extends PageObject { HelperMethods helpmeth; //end::header[] public static final String SCROLL_TO_FILTERS = "$('a.red')[0].scrollIntoView(false);"; //tag::searchByKeyword[] @FindBy(xpath="//a[contains(@href,'https://www.etsy.com/search/handmade?q=wool+fabric&explicit=1&guided_search=1&ref=guided_search_1_1')]") WebElementFacade woolfab_btn; @FindBy(xpath="//a[@data-path='link-Handmade']") WebElementFacade handmadeLink; @FindBy(xpath="//*[@data-path='link-Vintage']") WebElementFacade vintageLink; @FindBy(xpath="//*[@data-path='link-All items']") WebElementFacade allitemsLink; @FindBy(css=".listing-card") List<WebElement> listingCards; public List<String> getResultTitles() { return listingCards.stream() .map(element -> element.getText()) .collect(Collectors.toList()); } //end::searchByKeyword[] public void selectItem(int itemNumber) { listingCards.get(itemNumber - 1) .findElement(By.tagName("a")).click(); } public void filterByType(String type) { //WebElementFacade elementType; String type1 = "Handmade"; String type2="Vintage"; String type3 ="All items"; if (type.equalsIgnoreCase(type1)) { helpmeth.scrollIntoViewJS(handmadeLink); handmadeLink.click(); }else if(type.equalsIgnoreCase(type2)) { helpmeth.scrollIntoViewJS(vintageLink); // showFilters(); //findBy("#search-filter-reset-form").then(By.partialLinkText(type)).click(); vintageLink.click(); }else if(type.equalsIgnoreCase(type3)) { helpmeth.scrollIntoViewJS(allitemsLink); allitemsLink.click(); } } // public int getItemCount() { String resultCount = $(".result-count").getText() .replace("We found ","") .replace(" item","") .replace("s","") .replace("!","") .replace(",","") ; return Integer.parseInt(resultCount); } public Optional<String> getSelectedType() { List<WebElementFacade> selectedTypes = findAll("#search-filter-reset-form a.radio-label.strong"); return (selectedTypes.isEmpty()) ? Optional.absent() : Optional.of(selectedTypes.get(1).getText()); } public void showFilters() { evaluateJavascript(SCROLL_TO_FILTERS); } //tag::tail[] public String getSelectedVarietytype(String type) { String sval=null; List<WebElementFacade> selectedTypes = findAll("#search-filter-reset-form a.radio-label.strong"); int iSize = selectedTypes.size(); System.out.println(iSize); // Start the loop from first Check Box to last Check Boxe for(int i=0; i < iSize ; i++ ){ // Store the radiobutton name to the string variable, using 'Value' attribute String sValue = selectedTypes.get(i).getAttribute("value"); // Select the Check Box it the value of the Check Box is same what you are looking for if (sValue.equalsIgnoreCase(type)){ System.out.println("Type selected is"+ sValue); sval = sValue; break; } //return sValue; // TODO Auto-generated method stub } return sval; } } //end:tail[]
88c9b77f796caecb41fe21dcae8062e062f26c1d
[ "Java" ]
10
Java
sridevidonthi/sessionNew
93b39b3ef08bb20649d1c2fb1304a2447b43a4ca
22ea0be35a7e3561d6109a49933dff81d78a02c6
refs/heads/master
<repo_name>VitorLuizC/fetch-img<file_sep>/README.md # Fetch IMG [![Build Status](https://travis-ci.org/VitorLuizC/fetch-img.svg?branch=master)](https://travis-ci.org/VitorLuizC/fetch-img) Fetch asynchronously an image using it's source and resolve as `HTMLImageElement`. ## Install This module is published under NPM registry, so you can install using any Node.js package manager. ```sh npm install fetch-img --save # Use the command below for Yarn. yarn add fetch-img ``` ## Usage ```js import fetchIMG from 'fetch-img'; fetchIMG('https://nodejs.org/static/images/logo.svg') .then((img) => document.body.appendChild(img)) .catch((error) => console.error(error)); ``` ## License Released under [MIT license](./LICENSE). <file_sep>/index.ts /** * Fetch an image using an `Image` instance. * @param source - Image source, or `src` attribute. */ const fetchIMG = (source: string): Promise<HTMLImageElement> => new Promise((resolve, reject) => { const image = new Image(); /** * Remove listeners for `load` & `error` events and prevents its propagations. * @param event */ const clean = (event: Event) => { event.preventDefault(); event.stopPropagation(); image.removeEventListener('load', onLoad); image.removeEventListener('error', onError); }; /** * Listener for `load` event. * @param event */ const onLoad = (event: Event) => { clean(event); resolve(image); }; /** * Listener for `error` event. * @param event */ const onError = (event: ErrorEvent) => { clean(event); reject(new Error(event.message)); }; image.addEventListener('load', onLoad); image.addEventListener('error', onError); image.src = source; }); export default fetchIMG; <file_sep>/index.spec.ts import test from 'ava'; import image from './'; import env from 'browser-env'; env(); test('Module exports a function', (context) => { context.is(typeof image, 'function'); }); test('Function returns a Promise', (context) => { context.true(image('?') instanceof Promise); });
15438979ae306656a235d40b9180ab925dce4dec
[ "Markdown", "TypeScript" ]
3
Markdown
VitorLuizC/fetch-img
040e106f956e89bfa60c844d4674ec560c99d18a
956ebeaf55701eddfa44d65dea41a4f3c6898927
refs/heads/master
<repo_name>statisticalbiotechnology/pathstroll<file_sep>/decompose.py #!/usr/bin/python3 import os import numpy as np import pandas as pd from sklearn.decomposition import TruncatedSVD from sklearn.mixture import GaussianMixture import matplotlib.pyplot as plt import seaborn as sns print("## Analysis of LUAD pathways") results = pd.DataFrame() for r, d, f in os.walk("./luad_tcga_pub"): for fname in f: frame = pd.read_csv(os.path.join(r, fname), delimiter='\t') frame.drop(columns=['#Hugo_symbol'], inplace = True) # Xr = frame.to_numpy() Xr = frame.values X = Xr - Xr.mean(axis=1, keepdims=True) svd = TruncatedSVD(n_components=1) svd.fit(X.T) V = svd.transform(X.T) out_frame = pd.DataFrame(data=V.T,columns=frame.columns,index=[0]) out_frame.sort_values(by=[0], axis=1, ascending=True, inplace=True) dataname = os.path.join( "./out/", os.path.splitext(fname)[0]+'.txt') out_frame.to_csv(path_or_buf=dataname, sep='\t',index=False) figname = os.path.join( "./img/", os.path.splitext(fname)[0]+'.png') # Write markdown links print('![plt]({}) [values]({})'.format(figname,dataname)) sns.set_style("ticks") sns.distplot(V, rug=True) plt.savefig(figname) plt.clf() <file_sep>/decomp_plot.md ## Analysis of LUAD pathways ![plt](./img/luad_tcga_pub.EPHB3-ORC4.png) [values](./out/luad_tcga_pub.EPHB3-ORC4.txt) ![plt](./img/luad_tcga_pub.KDR-E2F6.png) [values](./out/luad_tcga_pub.KDR-E2F6.txt) ![plt](./img/luad_tcga_pub.MET-MCM8.png) [values](./out/luad_tcga_pub.MET-MCM8.txt) ![plt](./img/luad_tcga_pub.KIT-MCM3.png) [values](./out/luad_tcga_pub.KIT-MCM3.txt) ![plt](./img/luad_tcga_pub.EGFR-E2F6.png) [values](./out/luad_tcga_pub.EGFR-E2F6.txt) ![plt](./img/luad_tcga_pub.FLT3-ORC4.png) [values](./out/luad_tcga_pub.FLT3-ORC4.txt) ![plt](./img/luad_tcga_pub.INSR-MCM8.png) [values](./out/luad_tcga_pub.INSR-MCM8.txt) ![plt](./img/luad_tcga_pub.EPHA3-E2F5.png) [values](./out/luad_tcga_pub.EPHA3-E2F5.txt) ![plt](./img/luad_tcga_pub.EPHA2-E2F5.png) [values](./out/luad_tcga_pub.EPHA2-E2F5.txt) ![plt](./img/luad_tcga_pub.FLT4-CCNA2.png) [values](./out/luad_tcga_pub.FLT4-CCNA2.txt) ![plt](./img/luad_tcga_pub.CSF1R-E2F5.png) [values](./out/luad_tcga_pub.CSF1R-E2F5.txt) ![plt](./img/luad_tcga_pub.FLT4-MCM9.png) [values](./out/luad_tcga_pub.FLT4-MCM9.txt) ![plt](./img/luad_tcga_pub.EPHA8-E2F2.png) [values](./out/luad_tcga_pub.EPHA8-E2F2.txt) ![plt](./img/luad_tcga_pub.EGFR-E2F4.png) [values](./out/luad_tcga_pub.EGFR-E2F4.txt) ![plt](./img/luad_tcga_pub.ERBB4-MCM8.png) [values](./out/luad_tcga_pub.ERBB4-MCM8.txt) ![plt](./img/luad_tcga_pub.EPHA8-MCM3.png) [values](./out/luad_tcga_pub.EPHA8-MCM3.txt) ![plt](./img/luad_tcga_pub.CSF1R-ORC4.png) [values](./out/luad_tcga_pub.CSF1R-ORC4.txt) ![plt](./img/luad_tcga_pub.FLT3-E2F5.png) [values](./out/luad_tcga_pub.FLT3-E2F5.txt) ![plt](./img/luad_tcga_pub.PDGFRA-MCM3.png) [values](./out/luad_tcga_pub.PDGFRA-MCM3.txt) ![plt](./img/luad_tcga_pub.EPHA8-ORC1.png) [values](./out/luad_tcga_pub.EPHA8-ORC1.txt) ![plt](./img/luad_tcga_pub.IGF1R-ORC4.png) [values](./out/luad_tcga_pub.IGF1R-ORC4.txt) ![plt](./img/luad_tcga_pub.FLT4-E2F5.png) [values](./out/luad_tcga_pub.FLT4-E2F5.txt) ![plt](./img/luad_tcga_pub.EPHB3-E2F5.png) [values](./out/luad_tcga_pub.EPHB3-E2F5.txt) ![plt](./img/luad_tcga_pub.KIT-E2F6.png) [values](./out/luad_tcga_pub.KIT-E2F6.txt) ![plt](./img/luad_tcga_pub.EPHB4-E2F5.png) [values](./out/luad_tcga_pub.EPHB4-E2F5.txt) ![plt](./img/luad_tcga_pub.PDGFRA-E2F2.png) [values](./out/luad_tcga_pub.PDGFRA-E2F2.txt) ![plt](./img/luad_tcga_pub.PDGFRB-E2F5.png) [values](./out/luad_tcga_pub.PDGFRB-E2F5.txt) ![plt](./img/luad_tcga_pub.FLT3-MCM8.png) [values](./out/luad_tcga_pub.FLT3-MCM8.txt) ![plt](./img/luad_tcga_pub.EPHB3-MCM3.png) [values](./out/luad_tcga_pub.EPHB3-MCM3.txt) ![plt](./img/luad_tcga_pub.MET-MCM3.png) [values](./out/luad_tcga_pub.MET-MCM3.txt) ![plt](./img/luad_tcga_pub.EPHA4-MCM8.png) [values](./out/luad_tcga_pub.EPHA4-MCM8.txt) ![plt](./img/luad_tcga_pub.KDR-MCM9.png) [values](./out/luad_tcga_pub.KDR-MCM9.txt) ![plt](./img/luad_tcga_pub.EPHA8-CDT1.png) [values](./out/luad_tcga_pub.EPHA8-CDT1.txt) ![plt](./img/luad_tcga_pub.EGFR-ORC1.png) [values](./out/luad_tcga_pub.EGFR-ORC1.txt) ![plt](./img/luad_tcga_pub.NTRK2-E2F5.png) [values](./out/luad_tcga_pub.NTRK2-E2F5.txt) ![plt](./img/luad_tcga_pub.INSRR-MCM3.png) [values](./out/luad_tcga_pub.INSRR-MCM3.txt) ![plt](./img/luad_tcga_pub.ERBB2-E2F5.png) [values](./out/luad_tcga_pub.ERBB2-E2F5.txt) ![plt](./img/luad_tcga_pub.FGFR4-ORC4.png) [values](./out/luad_tcga_pub.FGFR4-ORC4.txt) ![plt](./img/luad_tcga_pub.KDR-E2F5.png) [values](./out/luad_tcga_pub.KDR-E2F5.txt) ![plt](./img/luad_tcga_pub.ERBB2-E2F6.png) [values](./out/luad_tcga_pub.ERBB2-E2F6.txt) ![plt](./img/luad_tcga_pub.KIT-E2F5.png) [values](./out/luad_tcga_pub.KIT-E2F5.txt) ![plt](./img/luad_tcga_pub.PDGFRA-E2F8.png) [values](./out/luad_tcga_pub.PDGFRA-E2F8.txt) ![plt](./img/luad_tcga_pub.EPHA1-E2F5.png) [values](./out/luad_tcga_pub.EPHA1-E2F5.txt) ![plt](./img/luad_tcga_pub.ERBB2-MCM8.png) [values](./out/luad_tcga_pub.ERBB2-MCM8.txt) ![plt](./img/luad_tcga_pub.FGFR3-E2F5.png) [values](./out/luad_tcga_pub.FGFR3-E2F5.txt) ![plt](./img/luad_tcga_pub.FLT4-E2F4.png) [values](./out/luad_tcga_pub.FLT4-E2F4.txt) ![plt](./img/luad_tcga_pub.EPHA8-E2F8.png) [values](./out/luad_tcga_pub.EPHA8-E2F8.txt) ![plt](./img/luad_tcga_pub.ERBB3-E2F5.png) [values](./out/luad_tcga_pub.ERBB3-E2F5.txt) ![plt](./img/luad_tcga_pub.KIT-ORC4.png) [values](./out/luad_tcga_pub.KIT-ORC4.txt) ![plt](./img/luad_tcga_pub.PDGFRB-E2F6.png) [values](./out/luad_tcga_pub.PDGFRB-E2F6.txt) ![plt](./img/luad_tcga_pub.ERBB2-MCM3.png) [values](./out/luad_tcga_pub.ERBB2-MCM3.txt) ![plt](./img/luad_tcga_pub.KIT-MCM8.png) [values](./out/luad_tcga_pub.KIT-MCM8.txt) ![plt](./img/luad_tcga_pub.EGFR-MCM3.png) [values](./out/luad_tcga_pub.EGFR-MCM3.txt) ![plt](./img/luad_tcga_pub.PDGFRB-MCM8.png) [values](./out/luad_tcga_pub.PDGFRB-MCM8.txt) ![plt](./img/luad_tcga_pub.INSRR-ORC4.png) [values](./out/luad_tcga_pub.INSRR-ORC4.txt) ![plt](./img/luad_tcga_pub.FGFR3-ORC4.png) [values](./out/luad_tcga_pub.FGFR3-ORC4.txt) ![plt](./img/luad_tcga_pub.ERBB4-MCM3.png) [values](./out/luad_tcga_pub.ERBB4-MCM3.txt) ![plt](./img/luad_tcga_pub.NTRK2-MCM8.png) [values](./out/luad_tcga_pub.NTRK2-MCM8.txt) ![plt](./img/luad_tcga_pub.FGFR3-MCM3.png) [values](./out/luad_tcga_pub.FGFR3-MCM3.txt) ![plt](./img/luad_tcga_pub.KDR-E2F8.png) [values](./out/luad_tcga_pub.KDR-E2F8.txt) ![plt](./img/luad_tcga_pub.ERBB3-ORC1.png) [values](./out/luad_tcga_pub.ERBB3-ORC1.txt) ![plt](./img/luad_tcga_pub.FGFR3-MCM8.png) [values](./out/luad_tcga_pub.FGFR3-MCM8.txt) ![plt](./img/luad_tcga_pub.ERBB4-E2F5.png) [values](./out/luad_tcga_pub.ERBB4-E2F5.txt) ![plt](./img/luad_tcga_pub.EPHA8-MCM7.png) [values](./out/luad_tcga_pub.EPHA8-MCM7.txt) ![plt](./img/luad_tcga_pub.FLT4-E2F1.png) [values](./out/luad_tcga_pub.FLT4-E2F1.txt) ![plt](./img/luad_tcga_pub.IGF1R-E2F4.png) [values](./out/luad_tcga_pub.IGF1R-E2F4.txt) ![plt](./img/luad_tcga_pub.ERBB2-ORC4.png) [values](./out/luad_tcga_pub.ERBB2-ORC4.txt) ![plt](./img/luad_tcga_pub.NTRK3-E2F5.png) [values](./out/luad_tcga_pub.NTRK3-E2F5.txt) ![plt](./img/luad_tcga_pub.FGFR4-E2F6.png) [values](./out/luad_tcga_pub.FGFR4-E2F6.txt) ![plt](./img/luad_tcga_pub.EPHA8-MCM9.png) [values](./out/luad_tcga_pub.EPHA8-MCM9.txt) ![plt](./img/luad_tcga_pub.PDGFRB-MCM7.png) [values](./out/luad_tcga_pub.PDGFRB-MCM7.txt) ![plt](./img/luad_tcga_pub.PDGFRB-E2F1.png) [values](./out/luad_tcga_pub.PDGFRB-E2F1.txt) ![plt](./img/luad_tcga_pub.RET-MCM3.png) [values](./out/luad_tcga_pub.RET-MCM3.txt) ![plt](./img/luad_tcga_pub.FLT4-MCM8.png) [values](./out/luad_tcga_pub.FLT4-MCM8.txt) ![plt](./img/luad_tcga_pub.INSR-E2F4.png) [values](./out/luad_tcga_pub.INSR-E2F4.txt) ![plt](./img/luad_tcga_pub.FLT4-E2F8.png) [values](./out/luad_tcga_pub.FLT4-E2F8.txt) ![plt](./img/luad_tcga_pub.CSF1R-E2F6.png) [values](./out/luad_tcga_pub.CSF1R-E2F6.txt) ![plt](./img/luad_tcga_pub.ERBB3-ORC4.png) [values](./out/luad_tcga_pub.ERBB3-ORC4.txt) ![plt](./img/luad_tcga_pub.IGF1R-MCM8.png) [values](./out/luad_tcga_pub.IGF1R-MCM8.txt) ![plt](./img/luad_tcga_pub.FLT4-ORC4.png) [values](./out/luad_tcga_pub.FLT4-ORC4.txt) ![plt](./img/luad_tcga_pub.INSR-ORC4.png) [values](./out/luad_tcga_pub.INSR-ORC4.txt) ![plt](./img/luad_tcga_pub.EPHB3-MCM8.png) [values](./out/luad_tcga_pub.EPHB3-MCM8.txt) ![plt](./img/luad_tcga_pub.MET-E2F5.png) [values](./out/luad_tcga_pub.MET-E2F5.txt) ![plt](./img/luad_tcga_pub.EPHA8-ORC4.png) [values](./out/luad_tcga_pub.EPHA8-ORC4.txt) ![plt](./img/luad_tcga_pub.KDR-E2F1.png) [values](./out/luad_tcga_pub.KDR-E2F1.txt) ![plt](./img/luad_tcga_pub.RET-ORC4.png) [values](./out/luad_tcga_pub.RET-ORC4.txt) ![plt](./img/luad_tcga_pub.KDR-E2F2.png) [values](./out/luad_tcga_pub.KDR-E2F2.txt) ![plt](./img/luad_tcga_pub.ERBB4-ORC4.png) [values](./out/luad_tcga_pub.ERBB4-ORC4.txt) ![plt](./img/luad_tcga_pub.EPHA2-ORC4.png) [values](./out/luad_tcga_pub.EPHA2-ORC4.txt) ![plt](./img/luad_tcga_pub.PDGFRA-E2F4.png) [values](./out/luad_tcga_pub.PDGFRA-E2F4.txt) ![plt](./img/luad_tcga_pub.EPHA8-E2F5.png) [values](./out/luad_tcga_pub.EPHA8-E2F5.txt) ![plt](./img/luad_tcga_pub.ERBB3-E2F6.png) [values](./out/luad_tcga_pub.ERBB3-E2F6.txt) ![plt](./img/luad_tcga_pub.INSR-E2F5.png) [values](./out/luad_tcga_pub.INSR-E2F5.txt) ![plt](./img/luad_tcga_pub.PDGFRA-MCM9.png) [values](./out/luad_tcga_pub.PDGFRA-MCM9.txt) ![plt](./img/luad_tcga_pub.PDGFRB-MCM9.png) [values](./out/luad_tcga_pub.PDGFRB-MCM9.txt) ![plt](./img/luad_tcga_pub.EPHB4-MCM3.png) [values](./out/luad_tcga_pub.EPHB4-MCM3.txt) ![plt](./img/luad_tcga_pub.FLT1-E2F5.png) [values](./out/luad_tcga_pub.FLT1-E2F5.txt) ![plt](./img/luad_tcga_pub.MET-E2F4.png) [values](./out/luad_tcga_pub.MET-E2F4.txt) ![plt](./img/luad_tcga_pub.KDR-MCM8.png) [values](./out/luad_tcga_pub.KDR-MCM8.txt) ![plt](./img/luad_tcga_pub.EGFR-ORC4.png) [values](./out/luad_tcga_pub.EGFR-ORC4.txt) ![plt](./img/luad_tcga_pub.CSF1R-E2F4.png) [values](./out/luad_tcga_pub.CSF1R-E2F4.txt) ![plt](./img/luad_tcga_pub.EPHA4-E2F6.png) [values](./out/luad_tcga_pub.EPHA4-E2F6.txt) ![plt](./img/luad_tcga_pub.EPHB3-E2F4.png) [values](./out/luad_tcga_pub.EPHB3-E2F4.txt) ![plt](./img/luad_tcga_pub.PDGFRA-CDT1.png) [values](./out/luad_tcga_pub.PDGFRA-CDT1.txt) ![plt](./img/luad_tcga_pub.RET-E2F5.png) [values](./out/luad_tcga_pub.RET-E2F5.txt) ![plt](./img/luad_tcga_pub.IGF1R-E2F5.png) [values](./out/luad_tcga_pub.IGF1R-E2F5.txt) ![plt](./img/luad_tcga_pub.EPHA1-E2F4.png) [values](./out/luad_tcga_pub.EPHA1-E2F4.txt) ![plt](./img/luad_tcga_pub.EPHA3-MCM8.png) [values](./out/luad_tcga_pub.EPHA3-MCM8.txt) ![plt](./img/luad_tcga_pub.EPHA4-E2F4.png) [values](./out/luad_tcga_pub.EPHA4-E2F4.txt) ![plt](./img/luad_tcga_pub.FLT4-E2F2.png) [values](./out/luad_tcga_pub.FLT4-E2F2.txt) ![plt](./img/luad_tcga_pub.FGFR4-E2F5.png) [values](./out/luad_tcga_pub.FGFR4-E2F5.txt) ![plt](./img/luad_tcga_pub.ERBB2-E2F4.png) [values](./out/luad_tcga_pub.ERBB2-E2F4.txt) ![plt](./img/luad_tcga_pub.PDGFRB-E2F4.png) [values](./out/luad_tcga_pub.PDGFRB-E2F4.txt) ![plt](./img/luad_tcga_pub.EPHA1-MCM3.png) [values](./out/luad_tcga_pub.EPHA1-MCM3.txt) ![plt](./img/luad_tcga_pub.EPHB3-E2F6.png) [values](./out/luad_tcga_pub.EPHB3-E2F6.txt) ![plt](./img/luad_tcga_pub.PDGFRA-ORC1.png) [values](./out/luad_tcga_pub.PDGFRA-ORC1.txt) ![plt](./img/luad_tcga_pub.EPHA3-ORC4.png) [values](./out/luad_tcga_pub.EPHA3-ORC4.txt) ![plt](./img/luad_tcga_pub.MET-ORC4.png) [values](./out/luad_tcga_pub.MET-ORC4.txt) ![plt](./img/luad_tcga_pub.FLT3-MCM3.png) [values](./out/luad_tcga_pub.FLT3-MCM3.txt) ![plt](./img/luad_tcga_pub.FLT4-ORC1.png) [values](./out/luad_tcga_pub.FLT4-ORC1.txt) ![plt](./img/luad_tcga_pub.AXL-E2F5.png) [values](./out/luad_tcga_pub.AXL-E2F5.txt) ![plt](./img/luad_tcga_pub.EPHA8-E2F1.png) [values](./out/luad_tcga_pub.EPHA8-E2F1.txt) ![plt](./img/luad_tcga_pub.EPHA4-E2F5.png) [values](./out/luad_tcga_pub.EPHA4-E2F5.txt) ![plt](./img/luad_tcga_pub.INSR-MCM3.png) [values](./out/luad_tcga_pub.INSR-MCM3.txt) ![plt](./img/luad_tcga_pub.NTRK2-E2F6.png) [values](./out/luad_tcga_pub.NTRK2-E2F6.txt) ![plt](./img/luad_tcga_pub.PDGFRB-MCM3.png) [values](./out/luad_tcga_pub.PDGFRB-MCM3.txt) ![plt](./img/luad_tcga_pub.KDR-CDT1.png) [values](./out/luad_tcga_pub.KDR-CDT1.txt) ![plt](./img/luad_tcga_pub.EPHA3-E2F4.png) [values](./out/luad_tcga_pub.EPHA3-E2F4.txt) ![plt](./img/luad_tcga_pub.NTRK3-MCM3.png) [values](./out/luad_tcga_pub.NTRK3-MCM3.txt) ![plt](./img/luad_tcga_pub.KDR-CCNA2.png) [values](./out/luad_tcga_pub.KDR-CCNA2.txt) ![plt](./img/luad_tcga_pub.ERBB4-E2F4.png) [values](./out/luad_tcga_pub.ERBB4-E2F4.txt) ![plt](./img/luad_tcga_pub.FGFR3-E2F6.png) [values](./out/luad_tcga_pub.FGFR3-E2F6.txt) ![plt](./img/luad_tcga_pub.EPHA2-MCM3.png) [values](./out/luad_tcga_pub.EPHA2-MCM3.txt) ![plt](./img/luad_tcga_pub.KDR-MCM3.png) [values](./out/luad_tcga_pub.KDR-MCM3.txt) ![plt](./img/luad_tcga_pub.FGFR3-E2F4.png) [values](./out/luad_tcga_pub.FGFR3-E2F4.txt) ![plt](./img/luad_tcga_pub.CSF1R-MCM8.png) [values](./out/luad_tcga_pub.CSF1R-MCM8.txt) ![plt](./img/luad_tcga_pub.PDGFRA-CCNA2.png) [values](./out/luad_tcga_pub.PDGFRA-CCNA2.txt) ![plt](./img/luad_tcga_pub.PDGFRA-E2F1.png) [values](./out/luad_tcga_pub.PDGFRA-E2F1.txt) ![plt](./img/luad_tcga_pub.FLT1-ORC4.png) [values](./out/luad_tcga_pub.FLT1-ORC4.txt) ![plt](./img/luad_tcga_pub.FLT4-MCM7.png) [values](./out/luad_tcga_pub.FLT4-MCM7.txt) ![plt](./img/luad_tcga_pub.NTRK2-E2F4.png) [values](./out/luad_tcga_pub.NTRK2-E2F4.txt) ![plt](./img/luad_tcga_pub.INSRR-E2F5.png) [values](./out/luad_tcga_pub.INSRR-E2F5.txt) ![plt](./img/luad_tcga_pub.EPHA1-E2F6.png) [values](./out/luad_tcga_pub.EPHA1-E2F6.txt) ![plt](./img/luad_tcga_pub.CSF1R-MCM3.png) [values](./out/luad_tcga_pub.CSF1R-MCM3.txt) ![plt](./img/luad_tcga_pub.FGFR4-E2F4.png) [values](./out/luad_tcga_pub.FGFR4-E2F4.txt) ![plt](./img/luad_tcga_pub.FLT1-MCM8.png) [values](./out/luad_tcga_pub.FLT1-MCM8.txt) ![plt](./img/luad_tcga_pub.IGF1R-MCM3.png) [values](./out/luad_tcga_pub.IGF1R-MCM3.txt) ![plt](./img/luad_tcga_pub.FLT3-E2F6.png) [values](./out/luad_tcga_pub.FLT3-E2F6.txt) ![plt](./img/luad_tcga_pub.EPHA8-E2F6.png) [values](./out/luad_tcga_pub.EPHA8-E2F6.txt) ![plt](./img/luad_tcga_pub.EPHA3-MCM3.png) [values](./out/luad_tcga_pub.EPHA3-MCM3.txt) ![plt](./img/luad_tcga_pub.EGFR-E2F5.png) [values](./out/luad_tcga_pub.EGFR-E2F5.txt) ![plt](./img/luad_tcga_pub.EPHA4-MCM3.png) [values](./out/luad_tcga_pub.EPHA4-MCM3.txt) ![plt](./img/luad_tcga_pub.NTRK2-ORC4.png) [values](./out/luad_tcga_pub.NTRK2-ORC4.txt) ![plt](./img/luad_tcga_pub.EPHA8-MCM8.png) [values](./out/luad_tcga_pub.EPHA8-MCM8.txt) ![plt](./img/luad_tcga_pub.EPHA8-E2F4.png) [values](./out/luad_tcga_pub.EPHA8-E2F4.txt) ![plt](./img/luad_tcga_pub.PDGFRB-E2F8.png) [values](./out/luad_tcga_pub.PDGFRB-E2F8.txt) ![plt](./img/luad_tcga_pub.KDR-MCM7.png) [values](./out/luad_tcga_pub.KDR-MCM7.txt) ![plt](./img/luad_tcga_pub.AXL-ORC4.png) [values](./out/luad_tcga_pub.AXL-ORC4.txt) ![plt](./img/luad_tcga_pub.NTRK2-MCM3.png) [values](./out/luad_tcga_pub.NTRK2-MCM3.txt) ![plt](./img/luad_tcga_pub.FLT3-E2F4.png) [values](./out/luad_tcga_pub.FLT3-E2F4.txt) ![plt](./img/luad_tcga_pub.EPHA1-ORC4.png) [values](./out/luad_tcga_pub.EPHA1-ORC4.txt) ![plt](./img/luad_tcga_pub.EPHB4-ORC4.png) [values](./out/luad_tcga_pub.EPHB4-ORC4.txt) ![plt](./img/luad_tcga_pub.FLT4-E2F6.png) [values](./out/luad_tcga_pub.FLT4-E2F6.txt) ![plt](./img/luad_tcga_pub.PDGFRA-E2F6.png) [values](./out/luad_tcga_pub.PDGFRA-E2F6.txt) ![plt](./img/luad_tcga_pub.PDGFRB-ORC1.png) [values](./out/luad_tcga_pub.PDGFRB-ORC1.txt) ![plt](./img/luad_tcga_pub.INSR-E2F6.png) [values](./out/luad_tcga_pub.INSR-E2F6.txt) ![plt](./img/luad_tcga_pub.PDGFRA-MCM7.png) [values](./out/luad_tcga_pub.PDGFRA-MCM7.txt) ![plt](./img/luad_tcga_pub.FGFR4-MCM3.png) [values](./out/luad_tcga_pub.FGFR4-MCM3.txt) ![plt](./img/luad_tcga_pub.MET-E2F6.png) [values](./out/luad_tcga_pub.MET-E2F6.txt) ![plt](./img/luad_tcga_pub.ERBB2-ORC1.png) [values](./out/luad_tcga_pub.ERBB2-ORC1.txt) ![plt](./img/luad_tcga_pub.PDGFRB-ORC4.png) [values](./out/luad_tcga_pub.PDGFRB-ORC4.txt) ![plt](./img/luad_tcga_pub.KDR-ORC4.png) [values](./out/luad_tcga_pub.KDR-ORC4.txt) ![plt](./img/luad_tcga_pub.EPHA3-E2F6.png) [values](./out/luad_tcga_pub.EPHA3-E2F6.txt) ![plt](./img/luad_tcga_pub.ERBB3-E2F4.png) [values](./out/luad_tcga_pub.ERBB3-E2F4.txt) ![plt](./img/luad_tcga_pub.ERBB4-E2F6.png) [values](./out/luad_tcga_pub.ERBB4-E2F6.txt) ![plt](./img/luad_tcga_pub.EPHA8-CCNA2.png) [values](./out/luad_tcga_pub.EPHA8-CCNA2.txt) ![plt](./img/luad_tcga_pub.AXL-MCM3.png) [values](./out/luad_tcga_pub.AXL-MCM3.txt) ![plt](./img/luad_tcga_pub.ERBB3-MCM3.png) [values](./out/luad_tcga_pub.ERBB3-MCM3.txt) ![plt](./img/luad_tcga_pub.FLT1-E2F6.png) [values](./out/luad_tcga_pub.FLT1-E2F6.txt) ![plt](./img/luad_tcga_pub.EPHA4-ORC4.png) [values](./out/luad_tcga_pub.EPHA4-ORC4.txt) ![plt](./img/luad_tcga_pub.FGFR4-MCM8.png) [values](./out/luad_tcga_pub.FGFR4-MCM8.txt) ![plt](./img/luad_tcga_pub.PDGFRB-CCNA2.png) [values](./out/luad_tcga_pub.PDGFRB-CCNA2.txt) ![plt](./img/luad_tcga_pub.IGF1R-E2F6.png) [values](./out/luad_tcga_pub.IGF1R-E2F6.txt) ![plt](./img/luad_tcga_pub.PDGFRA-MCM8.png) [values](./out/luad_tcga_pub.PDGFRA-MCM8.txt) ![plt](./img/luad_tcga_pub.KIT-E2F4.png) [values](./out/luad_tcga_pub.KIT-E2F4.txt) ![plt](./img/luad_tcga_pub.KDR-ORC1.png) [values](./out/luad_tcga_pub.KDR-ORC1.txt) ![plt](./img/luad_tcga_pub.KDR-E2F4.png) [values](./out/luad_tcga_pub.KDR-E2F4.txt) ![plt](./img/luad_tcga_pub.FLT1-MCM3.png) [values](./out/luad_tcga_pub.FLT1-MCM3.txt) ![plt](./img/luad_tcga_pub.FLT4-CDT1.png) [values](./out/luad_tcga_pub.FLT4-CDT1.txt) ![plt](./img/luad_tcga_pub.ERBB3-MCM8.png) [values](./out/luad_tcga_pub.ERBB3-MCM8.txt) ![plt](./img/luad_tcga_pub.NTRK3-ORC4.png) [values](./out/luad_tcga_pub.NTRK3-ORC4.txt) ![plt](./img/luad_tcga_pub.FLT4-MCM3.png) [values](./out/luad_tcga_pub.FLT4-MCM3.txt) ![plt](./img/luad_tcga_pub.PDGFRB-CDT1.png) [values](./out/luad_tcga_pub.PDGFRB-CDT1.txt) ![plt](./img/luad_tcga_pub.FLT1-E2F4.png) [values](./out/luad_tcga_pub.FLT1-E2F4.txt) ![plt](./img/luad_tcga_pub.PDGFRA-E2F5.png) [values](./out/luad_tcga_pub.PDGFRA-E2F5.txt) ![plt](./img/luad_tcga_pub.PDGFRB-E2F2.png) [values](./out/luad_tcga_pub.PDGFRB-E2F2.txt) ![plt](./img/luad_tcga_pub.EGFR-MCM8.png) [values](./out/luad_tcga_pub.EGFR-MCM8.txt) ![plt](./img/luad_tcga_pub.PDGFRA-ORC4.png) [values](./out/luad_tcga_pub.PDGFRA-ORC4.txt)
87c57c485dbe58940be5d3622ea93771d21184be
[ "Markdown", "Python" ]
2
Python
statisticalbiotechnology/pathstroll
8f42116d35ac8a25987bca9b14e7c396500d55e5
0af23733d5f1d3f973100f10aa8f9a5b8584987f
refs/heads/master
<repo_name>barunsarraf/KeepNote_step2_basic_building<file_sep>/src/main/java/com/stackroute/keepnote/controller/NoteController.java package com.stackroute.keepnote.controller; /* * Annotate the class with @Controller annotation.@Controller annotation is used to mark * any POJO class as a controller so that Spring can recognize this class as a Controller */ import com.stackroute.keepnote.dao.NoteDAO; import com.stackroute.keepnote.model.Note; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import java.time.LocalDateTime; import java.util.List; @Controller public class NoteController { /* * From the problem statement, we can understand that the application requires * us to implement the following functionalities. * * 1. display the list of existing notes from the persistence data. Each note * should contain Note Id, title, content, status and created date. * 2. Add a new note which should contain the note id, title, content and status. * 3. Delete an existing note * 4. Update an existing note * */ /* * Autowiring should be implemented for the NoteDAO. * Create a Note object. * */ NoteDAO noteDAO; @Autowired public NoteController(NoteDAO noteDAO) { this.noteDAO=noteDAO; } Note note= new Note(); /* * Define a handler method to read the existing notes from the database and add * it to the ModelMap which is an implementation of Map, used when building * model data for use with views. it should map to the default URL i.e. "/index" */ @RequestMapping("/") public String read(ModelMap map) { List<Note> notelist= noteDAO.getAllNotes(); map.addAttribute("list",notelist); return "index"; } /* * Define a handler method which will read the NoteTitle, NoteContent, * NoteStatus from request parameters and save the note in note table in * database. Please note that the CreatedAt should always be auto populated with * system time and should not be accepted from the user. Also, after saving the * note, it should show the same along with existing messages. Hence, reading * note has to be done here again and the retrieved notes object should be sent * back to the view using ModelMap This handler method should map to the URL * "/add". */ @PostMapping("/add") public String savenote(String noteTitle,String noteContent,String noteStatus) { note.setNoteContent(noteContent); note.setNoteTitle(noteTitle); note.setNoteStatus(noteStatus); LocalDateTime now= LocalDateTime.now(); note.setCreatedAt(now); if(noteDAO.saveNote(note)){ System.out.println(noteTitle+" "+noteContent+" "+noteStatus); ModelMap map= new ModelMap(); map.addAttribute("note",note); return "redirect:/";} else return "index"; } /* * Define a handler method which will read the NoteId from request parameters * and remove an existing note by calling the deleteNote() method of the * NoteRepository class.This handler method should map to the URL "/delete". */ @GetMapping("/delete") public String delete(int noteId) { noteDAO.deleteNote(noteId); return "redirect:/"; } /* * Define a handler method which will update the existing note. This handler * method should map to the URL "/update". */ @PostMapping("/update") public String update(int noteId,String noteTitle,String noteContent,String noteStatus) { note.setNoteId(noteId); note.setNoteContent(noteContent); note.setNoteStatus(noteStatus); note.setNoteTitle(noteTitle);; noteDAO.UpdateNote(note); return "redirect:/"; } }
f99ab4399b242b02c5c9b9f278e51ea97812c162
[ "Java" ]
1
Java
barunsarraf/KeepNote_step2_basic_building
cac26a0908bbb5d8a40fbbff5bb362205d5e2206
535f2468adf27f8ea01bc40af0c4c57dab871e3f
refs/heads/main
<file_sep>console.log("Hello, Val was here"); <file_sep>console.log('whoooo hooo')
3ceaf78153c558f42e92fe64205f84149515b0cf
[ "JavaScript" ]
2
JavaScript
Tzikas/SharingCodeWithRabiulAndVal
d249162368fb54599ce0dc8319c7dbb912e6f406
cd52e0d2c19eb0cb9734ff4e29cb545b16568cb6
refs/heads/master
<repo_name>ricardoschullerSL/atm-branch-finder-spring<file_sep>/src/main/java/ATMBranchFinderSpring/controllers/ATMController.java package ATMBranchFinderSpring.controllers; import ATMBranchFinderSpring.models.ATM; import ATMBranchFinderSpring.repos.ATMRepo; import ATMBranchFinderSpring.repos.BankRepo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.Collection; @RestController public class ATMController { private final ATMRepo atmRepo; private final double LATITUDE_TO_KM = 69; private final double LONGITUDE_TO_KM = 111; @Autowired ATMController( ATMRepo atmRepo) { this.atmRepo = atmRepo; } @RequestMapping(method = RequestMethod.GET, value = "/atms", produces="application/json") public Collection<ATM> allATMs() { return atmRepo.GetAll(); } @RequestMapping(method = RequestMethod.GET, value = "/atms/{id}") public ATM atm(@PathVariable int id) { return atmRepo.Get(id); } @RequestMapping(method = RequestMethod.GET, value = "/atms/city/{cityName}", produces="application/json") public Collection<ATM> FindAtmsByCity(@PathVariable String cityName) {return atmRepo.FindByCity(cityName); } @RequestMapping(method = RequestMethod.GET, value = "/atms/userlocation/{userLatitude}/{userLongitude}/{maxDistance}") public Collection<ATM> FindAtmsByUserLocation(@PathVariable double userLatitude, @PathVariable double userLongitude, @PathVariable double maxDistance) { ArrayList<ATM> atms = (ArrayList<ATM>) atmRepo.GetAll(); ArrayList<ATM> filteredAtms = new ArrayList<ATM>(); for(ATM atm: atms) { double distanceSquared = Math.pow((atm.getGeographicLocation().getLatitude() - userLatitude)*LATITUDE_TO_KM, 2) + Math.pow((atm.getGeographicLocation().getLongitude() - userLongitude)*LONGITUDE_TO_KM, 2); if (distanceSquared <= maxDistance) { atm.setDistanceSquared(distanceSquared); filteredAtms.add(atm); } } return filteredAtms; } } <file_sep>/src/main/java/ATMBranchFinderSpring/controllers/BankController.java package ATMBranchFinderSpring.controllers; import ATMBranchFinderSpring.models.ATM; import ATMBranchFinderSpring.models.Bank; import ATMBranchFinderSpring.models.Branch; import ATMBranchFinderSpring.models.PCA; import ATMBranchFinderSpring.repos.BankRepo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.util.Collection; @RestController public class BankController { private BankRepo bankRepo; @Autowired BankController(BankRepo bankRepo) { this.bankRepo = bankRepo; } @RequestMapping(method = RequestMethod.GET, value = "/banks", produces = "application/json") public Collection<Bank> allBanks() {return bankRepo.GetAll(); } @RequestMapping(method = RequestMethod.GET, value = "/banks/{bankId}", produces = "application/json") public Bank getBankById(@PathVariable String bankId) { Bank bank = bankRepo.FindByBankId(bankId); if (bank == null) throw new BankNotFoundException(); return bank; } @RequestMapping(method = RequestMethod.GET, value = "/banks/{bankId}/atms", produces = "application/json") public Collection<ATM> getATMsByBankId(@PathVariable String bankId) { Bank bank = bankRepo.FindByBankId(bankId); if (bank == null) throw new BankNotFoundException(); return bank.getAtms(); } @RequestMapping(method = RequestMethod.GET, value = "/banks/{bankId}/branches", produces = "application/json") public Collection<Branch> getBranchesByBankId(@PathVariable String bankId) { Bank bank = bankRepo.FindByBankId(bankId); if (bank == null) throw new BankNotFoundException(); return bank.getBranches(); } @RequestMapping(method = RequestMethod.GET, value = "/banks/{bankId}/branches/city/{cityName}", produces = "application/json") public Collection<Branch> getBranchesByBankIdAndCity(@PathVariable String bankId, @PathVariable String cityName) { Bank bank = bankRepo.FindByBankId(bankId); if (bank == null) throw new BankNotFoundException(); Collection<Branch> branches = bankRepo.GetBranchesByBankIdAndCityName(bankId, cityName); return bank.getBranches(); } @RequestMapping(method = RequestMethod.GET, value = "/banks/{bankId}/pca", produces = "application/json") public Collection<PCA> getPCAsByBankId(@PathVariable String bankId) { Bank bank = bankRepo.FindByBankId(bankId); if (bank == null) throw new BankNotFoundException(); return bank.getPcas(); } } <file_sep>/src/main/java/ATMBranchFinderSpring/services/GetBankDataService.java package ATMBranchFinderSpring.services; import ATMBranchFinderSpring.models.Bank; import ATMBranchFinderSpring.repos.BankRepo; import java.util.ArrayList; public class GetBankDataService implements Service { private String name; private BankRepo bankRepo; private ArrayList<Bank> banks; public GetBankDataService(BankRepo bankRepo) { this.name = "GetBankDataService"; this.bankRepo = bankRepo; this.banks = bankRepo.GetAll(); } @Override public String getName() { return name; } @Override public void execute() { } } <file_sep>/src/main/java/ATMBranchFinderSpring/repos/ATMRepo.java package ATMBranchFinderSpring.repos; import ATMBranchFinderSpring.models.ATM; import ATMBranchFinderSpring.models.Bank; import java.util.ArrayList; import java.util.List; @org.springframework.stereotype.Repository public class ATMRepo implements Repository<ATM> { private ArrayList<ATM> atms; public ATMRepo() { atms = new ArrayList<ATM>(); }; public void SetAllATMs(ArrayList<Bank> banks) { atms = new ArrayList<ATM>(); for (Bank bank : banks) { atms.addAll(bank.getAtms()); } System.out.format("%d number of ATMS set.%n", atms.size()); } @Override public ATM Get(int id) { return atms.get(id); } @Override public List<ATM> GetAll() { return atms; } @Override public void Add(ATM entity) { atms.add(entity); } @Override public void Remove(int id) { atms.remove(id); } public List<ATM> FindByCity(String city) { List<ATM> filteredAtms = new ArrayList<ATM>(); for (ATM atm : atms) { if (atm.getAddress().getTownName() == null) { continue; } if (atm.getAddress().getTownName().toUpperCase().equals(city.toUpperCase())) { filteredAtms.add(atm); } } return filteredAtms; } } <file_sep>/src/main/java/ATMBranchFinderSpring/models/EndPoint.java package ATMBranchFinderSpring.models; public interface EndPoint { String getId(); Class getClassType(); } <file_sep>/src/main/java/ATMBranchFinderSpring/services/GetEndPointDataService.java package ATMBranchFinderSpring.services; import ATMBranchFinderSpring.models.Bank; import ATMBranchFinderSpring.models.EndPoint; import ATMBranchFinderSpring.models.EndPointCollection; import com.fasterxml.jackson.databind.*; import org.springframework.web.client.RestTemplate; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; public class GetEndPointDataService implements Service { private String name; private Bank bank; private RestTemplate restTemplate; public GetEndPointDataService(RestTemplate restTemplate, Bank bank) { this.name = "GetEndPointDataService"; this.bank = bank; this.restTemplate = restTemplate; } @Override public String getName() { return name; } @Override public void execute() { for (EndPointCollection endPointCollection : bank.getEndPointCollections()) { try { URI uri = new URI(endPointCollection.getUri()); String json = restTemplate.getForObject(uri, String.class); ObjectMapper mapper = new ObjectMapper(); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); JavaType arrayType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, endPointCollection.getClassType()); ObjectReader reader = mapper.readerFor(arrayType); JsonNode node = mapper.readTree(json).get("data"); ArrayList<? extends EndPoint> data = reader.readValue(node); endPointCollection.setData(data); System.out.format("Set endpoint data for %s bank. \n", bank.getBankId()); } catch (IOException e) { System.out.println(e); } catch (URISyntaxException e) { System.out.println(e); } } } } <file_sep>/src/main/java/ATMBranchFinderSpring/repos/Repository.java package ATMBranchFinderSpring.repos; import java.util.List; public interface Repository<E> { E Get(int id); List<E> GetAll(); void Add(E entity); void Remove(int id); } <file_sep>/src/main/java/ATMBranchFinderSpring/models/Address.java package ATMBranchFinderSpring.models; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) public class Address { @JsonProperty("TownName") private String townName; @JsonProperty("PostCode") private String postCode; @JsonProperty("StreetName") private String streetName; public String getTownName() { return townName; } public void setTownName(String townName) { this.townName = townName; } public String getPostCode() { return postCode; } public void setPostCode(String postCode) { this.postCode = postCode; } public String getStreetName() { return streetName; } public void setStreetName(String streetName) { this.streetName = streetName; } } <file_sep>/src/main/java/ATMBranchFinderSpring/models/Branch.java package ATMBranchFinderSpring.models; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) public class Branch implements EndPoint{ @JsonProperty("BranchName") private String branchName; @JsonProperty("Address") private Address address; @JsonProperty("GeographicLocation") private GeographicLocation geographicLocation; public String getBranchName() { return branchName; } public void setBranchName(String branchName) { this.branchName = branchName; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public GeographicLocation getGeographicLocation() { return geographicLocation; } public void setGeographicLocation(GeographicLocation geographicLocation) { this.geographicLocation = geographicLocation; } @Override public String getId() { return branchName; } @Override @JsonIgnore public Class getClassType() { return Branch.class; } } <file_sep>/src/main/java/ATMBranchFinderSpring/repos/BankRepo.java package ATMBranchFinderSpring.repos; import ATMBranchFinderSpring.models.Bank; import ATMBranchFinderSpring.models.Branch; import java.util.ArrayList; import java.util.Collection; @org.springframework.stereotype.Repository public class BankRepo implements Repository<Bank> { private ArrayList<Bank> banks; public BankRepo() { banks = new ArrayList<Bank>(); } public void SetAllBanks(ArrayList<Bank> banks) { this.banks = banks; System.out.format("%d number of banks set. %n", banks.size() ); } @Override public Bank Get(int id) { return banks.get(id); } public Bank FindByBankId(String bankId) { for (Bank bank: banks) { if (bank.getBankId().toUpperCase().equals(bankId.toUpperCase())) { return bank; } } return null; } public Collection<Branch> GetBranchesByBankIdAndCityName(String bankId, String cityName) { Bank bank = FindByBankId(bankId); if (bank == null) return null; Collection<Branch> branches = new ArrayList<Branch>(); for (Branch branch: bank.getBranches()) { String townName = branch.getAddress().getTownName() != null ? branch.getAddress().getTownName() : "cityName"; if (townName.toUpperCase().equals(cityName.toUpperCase())) { branches.add(branch); } } return branches; } @Override public ArrayList<Bank> GetAll() { return banks; } @Override public void Add(Bank bank) { banks.add(bank); } @Override public void Remove(int id) { banks.remove(id); } }
fa0461d9d5e6b539ccb27088339379488d30a132
[ "Java" ]
10
Java
ricardoschullerSL/atm-branch-finder-spring
2d9a31829a99789338164d65cb19630280d33210
266889299c57622e216811be33cfbd6440d38e30
refs/heads/master
<repo_name>beckzl/ap<file_sep>/src/main/java/com/cooshare/ap/controller/backstage/SessionController.java package com.cooshare.ap.controller.backstage; import com.cooshare.ap.dto.Res; import com.cooshare.ap.dto.backstage.enter.PostBackstageSessionDto; import com.cooshare.ap.service.ResService; import com.cooshare.ap.service.abstraction.AbstractSessionService; import io.swagger.annotations.ApiOperation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import static com.cooshare.ap.enumerate.ApEnum.*; /** * @author beckzl */ @RestController(value = "backstageSessionController") @RequestMapping(value = "/backstage", name = "后台管理系统会话控制器") public class SessionController { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Resource(name = "sessionManage") private AbstractSessionService sessionService; @Resource private ResService resService; @PostMapping(value = "/session") @ApiOperation(value = "创建新的会话(登陆)", notes = "创建新的会话(登陆)") public Res<Object> session(@RequestBody PostBackstageSessionDto postBackstageSessionDto) { if (null == postBackstageSessionDto.getAccountName()) { logger.warn("The parameter 'accountName' is null"); return resService.unexpected(UNEXPECTED_24001); } if (null == postBackstageSessionDto.getPassword()) { logger.warn("The parameter 'password' is null"); return resService.unexpected(UNEXPECTED_24002); } Object o = sessionService.postSession(postBackstageSessionDto); if (null != o) return resService.success(o); else return resService.unexpected(UNEXPECTED_24003); } @DeleteMapping(value = "/session") @ApiOperation(value = "后台管理系统删除旧会话(登出)", notes = "删除旧会话(登出)") public Res<Boolean> session() { Boolean o = sessionService.deleteSession(); if (null != o) return resService.success(o); else return resService.unexpected(UNEXPECTED_24016); } } <file_sep>/src/main/java/com/cooshare/ap/service/impl/mobile/SessionServiceImpl.java package com.cooshare.ap.service.impl.mobile; import com.cooshare.ap.dto.backstage.enter.PostBackstageSessionDto; import com.cooshare.ap.service.abstraction.AbstractSessionService; import org.springframework.stereotype.Service; /** * @author beckzl */ @Service("sessionMobile") public class SessionServiceImpl extends AbstractSessionService { @Override public Object postSession(PostBackstageSessionDto postBackstageSessionDto) { return null; } } <file_sep>/src/main/java/com/cooshare/ap/service/feign/IpFeign.java package com.cooshare.ap.service.feign; import org.springframework.cloud.openfeign.FeignClient; /** * @author beckz */ @FeignClient(value = "institution-producer") public interface IpFeign { } <file_sep>/src/main/java/com/cooshare/ap/dto/backstage/out/GetBackstagePlatformAccountIdDto.java package com.cooshare.ap.dto.backstage.out; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; /** * @author beckzl */ @ApiModel(value = "后台管理系统获取某个平台用户信息返回类") public class GetBackstagePlatformAccountIdDto { @ApiModelProperty(value = "平台用户头像地址") private String headImgUrl; @ApiModelProperty(value = "平台用户昵称") private String nickName; public String getHeadImgUrl() { return headImgUrl; } public void setHeadImgUrl(String headImgUrl) { this.headImgUrl = headImgUrl; } public String getNickName() { return nickName; } public void setNickName(String nickName) { this.nickName = nickName; } } <file_sep>/src/main/java/com/cooshare/ap/service/RoleService.java package com.cooshare.ap.service; import com.cooshare.ap.dto.backstage.out.GetBackstageRoleDto; import java.util.List; /** * @author beckzl */ public interface RoleService { List<GetBackstageRoleDto> getRole(); } <file_sep>/src/main/java/com/cooshare/ap/service/SessionService.java package com.cooshare.ap.service; import com.cooshare.ap.dto.backstage.enter.PostBackstageSessionDto; /** * @author beckzl */ public interface SessionService { Object postSession(PostBackstageSessionDto postBackstageSessionDto); } <file_sep>/src/main/java/com/cooshare/ap/dto/backstage/out/GetBackstagePlatformAccountDto.java package com.cooshare.ap.dto.backstage.out; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; /** * @author beckzl */ @ApiModel(value = "平台账户返回类") public class GetBackstagePlatformAccountDto implements Serializable { @ApiModelProperty(value = "账户id") private Long accountId; @ApiModelProperty(value = "账户名称") private String accountName; @ApiModelProperty(value = "手机号码") private String cellphoneNumber; @ApiModelProperty(value = "邮箱账户") private String mailboxAccount; @ApiModelProperty(value = "机构角色") private Integer institutionRole; @ApiModelProperty(value = "平台角色") private Integer platformRole; @ApiModelProperty(value = "账户状态") private Boolean status_; public Long getAccountId() { return accountId; } public void setAccountId(Long accountId) { this.accountId = accountId; } public String getAccountName() { return accountName; } public void setAccountName(String accountName) { this.accountName = accountName; } public String getCellphoneNumber() { return cellphoneNumber; } public void setCellphoneNumber(String cellphoneNumber) { this.cellphoneNumber = cellphoneNumber; } public String getMailboxAccount() { return mailboxAccount; } public void setMailboxAccount(String mailboxAccount) { this.mailboxAccount = mailboxAccount; } public Integer getInstitutionRole() { return institutionRole; } public void setInstitutionRole(Integer institutionRole) { this.institutionRole = institutionRole; } public Integer getPlatformRole() { return platformRole; } public void setPlatformRole(Integer platformRole) { this.platformRole = platformRole; } public Boolean getStatus_() { return status_; } public void setStatus_(Boolean status_) { this.status_ = status_; } } <file_sep>/src/main/java/com/cooshare/ap/controller/backstage/AccountController.java package com.cooshare.ap.controller.backstage; import com.cooshare.ap.dto.Page; import com.cooshare.ap.dto.Res; import com.cooshare.ap.dto.backstage.enter.PostBackstageBackstageAccountDto; import com.cooshare.ap.dto.backstage.enter.PostBackstagePlatformAccountDto; import com.cooshare.ap.dto.backstage.out.*; import com.cooshare.ap.service.ResService; import com.cooshare.ap.service.impl.backstage.AccountServiceImpl; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import java.util.List; import static com.cooshare.ap.constant.Constants.CURRENT_USER_ID; import static com.cooshare.ap.enumerate.ApEnum.*; /** * @author beckzl */ @RestController(value = "backstageAccountController") @RequestMapping(value = "/backstage", name = "后台管理系统账户控制器") public class AccountController { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Resource private AccountServiceImpl accountService; @Resource private ResService resService; @ApiOperation(value = "(搜索)后台管理系统获取平台账户列表", notes = "获取平台账户列表") @GetMapping(value = "/platform/account") public Res<Page<GetBackstagePlatformAccountDto>> getPlatformAccount(com.cooshare.ap.dto.backstage.enter.GetBackstageAccountDto getBackstageAccountDto) { if (null == getBackstageAccountDto.getPageNumber()) { logger.warn("The parameter 'pageNumber' is null"); return resService.unexpected(UNEXPECTED_24005); } if (null == getBackstageAccountDto.getPageSize()) { logger.warn("The parameter 'pageSize' is null"); return resService.unexpected(UNEXPECTED_24006); } if (null == getBackstageAccountDto.getSortOrder()) { logger.warn("The parameter 'sortOrder' is null"); return resService.unexpected(UNEXPECTED_24007); } Page<GetBackstagePlatformAccountDto> o = accountService.getPlatformAccount(getBackstageAccountDto); return null == o ? resService.unexpected(UNEXPECTED_24008) : resService.success(o); } @ApiOperation(value = "(搜索)后台管理系统获取后台账户列表", notes = "获取后台账户列表") @GetMapping(value = "/backstage/account") public Res<Page<GetBackstageBackstageAccountDto>> getBackstageAccount(com.cooshare.ap.dto.backstage.enter.GetBackstageAccountDto getBackstageAccountDto) { if (null == getBackstageAccountDto.getPageNumber()) { logger.warn("The parameter 'pageNumber' is null"); return resService.unexpected(UNEXPECTED_24005); } if (null == getBackstageAccountDto.getPageSize()) { logger.warn("The parameter 'pageSize' is null"); return resService.unexpected(UNEXPECTED_24006); } if (null == getBackstageAccountDto.getSortOrder()) { logger.warn("The parameter 'sortOrder' is null"); return resService.unexpected(UNEXPECTED_24007); } Page<GetBackstageBackstageAccountDto> o = accountService.getBackstageAccount(getBackstageAccountDto); return null == o ? resService.unexpected(UNEXPECTED_24008) : resService.success(o); } @ApiOperation(value = "后台管理系统获取后台账户创建会话后的信息", notes = "获取后台账户创建会话后的信息") @GetMapping(value = "/account") public Res<GetBackstageAccountDto> getAccount(HttpServletRequest request) { Object accountId = request.getAttribute(CURRENT_USER_ID); if (null == accountId) { logger.warn("This user do not login"); resService.unexpected(UNEXPECTED_24010); } GetBackstageAccountDto o = accountService.getAccount(accountId); return null == o ? resService.unexpected(UNEXPECTED_24011) : resService.success(o); } @ApiOperation(value = "后台管理系统创建后台账户", notes = "后台管理系统创建后台账户") @PostMapping(value = "/backstage/account") public Res<Boolean> postBackstageAccount(@RequestBody PostBackstageBackstageAccountDto postBackstageBackstageAccountDto) { if (null == postBackstageBackstageAccountDto.getAccountName()) { logger.warn("The parameter 'accountName' is null"); return resService.unexpected(UNEXPECTED_24012); } if (null == postBackstageBackstageAccountDto.getPassword()) { logger.warn("The parameter 'password' is null"); return resService.unexpected(UNEXPECTED_24013); } if (null == postBackstageBackstageAccountDto.getAccountRole()) { logger.warn("The parameter 'accountRole' is null"); return resService.unexpected(UNEXPECTED_24014); } Boolean o = accountService.postBackstageAccount(postBackstageBackstageAccountDto); return o ? resService.success(true) : resService.unexpected(UNEXPECTED_24015); } @ApiOperation(value = "(搜索)获取后台管理系统获取平台非机构账户", notes = "(搜索)获取后台管理系统获取平台非机构账户") @ApiImplicitParams({@ApiImplicitParam(name = "start", value = "开始记录", required = true, dataType = "Integer"), @ApiImplicitParam(name = "length", value = "请求记录数", required = true, dataType = "Integer"), @ApiImplicitParam(name = "keyword", value = "搜索关键字(搜索的时候需要传)", dataType = "String")}) @GetMapping(value = "/platform/platform/account") public Res<List<GetBackstagePlatformPlatformAccountDto>> getPlatformPlatformAccount(Integer start, Integer length, String keyword) { if (null == start) { logger.warn("The parameter 'start' is null"); return resService.unexpected(UNEXPECTED_24017); } if (null == length) { logger.warn("The parameter 'length' is null"); return resService.unexpected(UNEXPECTED_24018); } List<GetBackstagePlatformPlatformAccountDto> o = accountService.getPlatformPlatformAccount(start, length, keyword); return null == o ? resService.unexpected(UNEXPECTED_24008) : resService.success(o); } @ApiOperation(value = "后台管理系统创建平台账户", notes = "后台管理系统创建平台账户") @PostMapping(value = "/platform/account") public Res<Boolean> postPlatformAccount(@RequestBody PostBackstagePlatformAccountDto postBackstagePlatformAccountDto) { if (null == postBackstagePlatformAccountDto.getCellphoneNumber()) { logger.warn("The parameter 'cellphoneNumber' is null"); return resService.unexpected(UNEXPECTED_24020); } if (null == postBackstagePlatformAccountDto.getPassword()) { logger.warn("The parameter 'password' is null"); return resService.unexpected(UNEXPECTED_24019); } Boolean o = accountService.postPlatformAccount(postBackstagePlatformAccountDto); return o ? resService.success(true) : resService.unexpected(UNEXPECTED_24015); } @ApiOperation(value = "后台管理系统获取平台某个账户信息", notes = "后台管理系统获取平台某个账户信息") @GetMapping(value = "/platform/account/id") public Res<GetBackstagePlatformAccountIdDto> getPlatformAccountId(String id){ if(null == id){ logger.warn("The parameter 'id' is null"); return resService.unexpected(UNEXPECTED_24021); } GetBackstagePlatformAccountIdDto o = accountService.getPlatformAccountId(id); return null == o ? resService.unexpected(UNEXPECTED_24022) : resService.success(o); } } <file_sep>/src/main/java/com/cooshare/ap/dao/AccountRoleDao.java package com.cooshare.ap.dao; import com.cooshare.ap.bean.CooShareAccountRole; import org.apache.ibatis.annotations.Mapper; /** * @author beckzl */ @Mapper public interface AccountRoleDao { void insertAccountRole(CooShareAccountRole cooShareAccountRole); } <file_sep>/src/main/java/com/cooshare/ap/controller/backstage/RoleController.java package com.cooshare.ap.controller.backstage; import com.cooshare.ap.dto.Res; import com.cooshare.ap.dto.backstage.out.GetBackstageRoleDto; import com.cooshare.ap.service.ResService; import com.cooshare.ap.service.RoleService; import io.swagger.annotations.ApiOperation; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import java.util.List; import static com.cooshare.ap.enumerate.ApEnum.UNEXPECTED_24009; /** * @author beckzl */ @RestController @RequestMapping(value = "/backstage") public class RoleController { @Resource private RoleService roleService; @Resource private ResService resService; @ApiOperation(value = "后台管理系统获取后台角色", notes = "获取后台角色") @GetMapping(value = "/role") public Res<List<GetBackstageRoleDto>> role() { List<GetBackstageRoleDto> getBackstageRoleDtoList = roleService.getRole(); return null == getBackstageRoleDtoList ? resService.unexpected(UNEXPECTED_24009) : resService.success(getBackstageRoleDtoList); } } <file_sep>/src/main/java/com/cooshare/ap/bean/CooShareAccountRole.java package com.cooshare.ap.bean; import java.io.Serializable; /** * @author beckzl */ public class CooShareAccountRole implements Serializable{ /*酷享易展机构账户唯一标识*/ private Long id; /*酷享易展机构账户机构唯一标识*/ private Long institutionId; /*酷享易展机构账户账户唯一标识*/ private Long accountId; /*酷享易展机构账户角色*/ private Integer role; /*酷享易展机构账户记录创建时间*/ private Long createTime; /*酷享易展机构账户记录更新时间*/ private Long updateTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getInstitutionId() { return institutionId; } public void setInstitutionId(Long institutionId) { this.institutionId = institutionId; } public Long getAccountId() { return accountId; } public void setAccountId(Long accountId) { this.accountId = accountId; } public Integer getRole() { return role; } public void setRole(Integer role) { this.role = role; } public Long getCreateTime() { return createTime; } public void setCreateTime(Long createTime) { this.createTime = createTime; } public Long getUpdateTime() { return updateTime; } public void setUpdateTime(Long updateTime) { this.updateTime = updateTime; } @Override public String toString() { return "CooShareAccountRole{" + "id=" + id + ", institutionsId=" + institutionId + ", accountId=" + accountId + ", role=" + role + ", createTime=" + createTime + ", updateTime=" + updateTime + '}'; } } <file_sep>/src/main/java/com/cooshare/ap/dao/AccountDao_.java package com.cooshare.ap.dao; import com.cooshare.ap.bean.CooShareAccount; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; /** * @author beckz */ @Mapper public interface AccountDao_ { void insertAccount(CooShareAccount cooShareAccount); CooShareAccount selectAccountByCellphoneNumber(@Param("cellphoneNumber") String cellphoneNumber); CooShareAccount selectAccountById(@Param("id") Long id); } <file_sep>/src/main/java/com/cooshare/ap/bean/backstage/CooShareAccount.java package com.cooshare.ap.bean.backstage; import java.io.Serializable; /** * @author beckz */ public class CooShareAccount implements Serializable { /*酷享易展后台账户唯一标识*/ private Long id; /*酷享易展后台账户名*/ private String accountName; /*酷享易展后台账户密码*/ private String password; /*酷享易展后台账户手机*/ private String cellphoneNumber; /*酷享易展后台账户邮箱*/ private String mailboxAccount; /*酷享易展后台账户角色*/ private Long accountRole; /*酷享易展后台账户创建时间*/ private String createTime; /*酷享易展后台账户更新时间*/ private String updateTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getAccountName() { return accountName; } public void setAccountName(String accountName) { this.accountName = accountName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getCellphoneNumber() { return cellphoneNumber; } public void setCellphoneNumber(String cellphoneNumber) { this.cellphoneNumber = cellphoneNumber; } public String getMailboxAccount() { return mailboxAccount; } public void setMailboxAccount(String mailboxAccount) { this.mailboxAccount = mailboxAccount; } public Long getAccountRole() { return accountRole; } public void setAccountRole(Long accountRole) { this.accountRole = accountRole; } public String getCreateTime() { return createTime; } public void setCreateTime(String createTime) { this.createTime = createTime; } public String getUpdateTime() { return updateTime; } public void setUpdateTime(String updateTime) { this.updateTime = updateTime; } @Override public String toString() { return "CooShareAccount{" + "id=" + id + ", accountName='" + accountName + '\'' + ", password='" + password + '\'' + ", cellphoneNumber='" + cellphoneNumber + '\'' + ", mailboxAccount='" + mailboxAccount + '\'' + ", accountRole=" + accountRole + ", createTime='" + createTime + '\'' + ", updateTime='" + updateTime + '\'' + '}'; } } <file_sep>/src/main/java/com/cooshare/ap/dto/backstage/enter/PostBackstagePlatformAccountDto.java package com.cooshare.ap.dto.backstage.enter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; /** * @author beckzl */ @ApiModel(value = "添加平台账户入参类") public class PostBackstagePlatformAccountDto { @ApiModelProperty(value = "手机号码", dataType = "String", required = true) private String cellphoneNumber; @ApiModelProperty(value = "账户密码", required = true, dataType = "String") private String password; public String getCellphoneNumber() { return cellphoneNumber; } public void setCellphoneNumber(String cellphoneNumber) { this.cellphoneNumber = cellphoneNumber; } public String getPassword() { return password; } public void setPassword(String password) { this.password = <PASSWORD>; } } <file_sep>/src/main/java/com/cooshare/ap/service/feign/CpFeign.java package com.cooshare.ap.service.feign; import com.cooshare.ap.dto.Res; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; import java.util.Map; /** * @author beckz */ @FeignClient(value = "certified-producer") public interface CpFeign { @GetMapping(value = "/backstage/token") Res<String> getToken(); @PatchMapping(value = "/backstage/token") Res<Boolean> patchToken(); @PostMapping(value = "/backstage/token", consumes = MediaType.APPLICATION_JSON_VALUE) Res<Object> postToken(@RequestBody Map<Object, Object> paras); @DeleteMapping(value = "/backstage/token") Res<Boolean> deleteToken(); } <file_sep>/src/main/java/com/cooshare/ap/service/impl/ResServiceImpl.java package com.cooshare.ap.service.impl; import com.alibaba.fastjson.JSON; import com.cooshare.ap.dto.Res; import com.cooshare.ap.enumerate.ApEnum; import com.cooshare.ap.service.ResService; import org.springframework.http.MediaType; import org.springframework.stereotype.Service; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import static com.cooshare.ap.enumerate.ApEnum.*; /** * @author beckz */ @Service public class ResServiceImpl implements ResService { @Override public <T> Res<T> success(T o) { Res<T> res = new Res<>(); res.setCode(SUCCESS.getKey()); res.setMsg(SUCCESS.getValue()); res.setObj(o); return res; } @Override public <T> Res<T> unexpected(Object o) { Res<T> res = new Res<>(); if (o instanceof ApEnum) { res.setCode(((ApEnum) o).getKey()); res.setMsg(((ApEnum) o).getValue()); } else { res.setCode(UNEXPECTED_24000.getKey()); res.setMsg(UNEXPECTED_24000.getValue()); } return res; } @Override public void unexpected(HttpServletResponse response) { response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE); PrintWriter writer; Res res = new Res(); res.setCode(UNEXPECTED_24004.getKey()); res.setMsg(UNEXPECTED_24004.getValue()); String s = JSON.toJSON(res).toString(); try { writer = response.getWriter(); writer.println(s); writer.flush(); writer.close(); } catch (IOException e) { e.printStackTrace(); } } } <file_sep>/README.md # ap coo-share account producer
6cbeac05393f188928fb1fdb06754cac4852935d
[ "Markdown", "Java" ]
17
Java
beckzl/ap
eda1fa6e32d5823e6e6e4c0d3a6fdb6a8308094e
ed5d5b2c37c5d5abcad8c1b80221fd64b9124ba5
refs/heads/master
<file_sep>const webpack = require('webpack'); var path = require('path'); module.exports = { devtool: 'eval-source-map', entry: { main: path.resolve(__dirname, './app/main.js'), }, output: { path: path.resolve(__dirname, './resources/static/js'), filename: 'bundle.js' }, devServer: { contentBase: "./resources/static/js", //本地服务器所加载的页面所在的目录 historyApiFallback: true, //不跳转 inline: true, //实时刷新 host: 'localhost', //本地前端服务 port: 8901, proxy: { '/api/*': { target: 'http://localhost:8900', // 本地后端服务 changeOrigin: true, secure: false } } }, resolve: { extensions: ['*', '.js', '.json', '.scss', '.less', 'jsonp'], }, module: { rules: [{ test: /\.less/, use: ['style', 'css', 'less'] }, { test: /\.css$/, use: [{ loader: "style-loader" }, { loader: "css-loader" }] }, { test: /\.(png|jpg|jpeg)$/, use: ['url'] }, { test: /\.js$/, exclude: /(node_modules|bower_components)/, use: { loader: 'babel-loader', options: { presets: ["es2015","stage-2","react"], } } } ] }, plugins: [ new webpack.BannerPlugin('版权所有,翻版必究'), new webpack.HotModuleReplacementPlugin() //热加载插件 ] }<file_sep>import {render} from 'react-dom'; import React, {Component} from 'react'; // 引入react-router模块 import { Router, Route, Link, hashHistory, IndexRoute, Redirect, IndexLink, browserHistory } from 'react-router' import './main.css' import ConversionPanel from './js/components/common/conversion-panel/ConversionPanel.js' import HDFSPanel from './js/components/common/hdfs-panel/HDFSPanel.js' import HBasePanel from './js/components/common/hbase-panel/HBasePanel.js' import {Layout, Menu, Breadcrumb, Icon} from 'antd'; const {Header, Content, Footer, Sider} = Layout; const SubMenu = Menu.SubMenu; class MainMenu extends React.Component { constructor(props) { super(props) this.state = { collapsed: false, current: '' } } onCollapse = (collapsed) => { this.setState({collapsed}); } handleClick = (e) => { this.setState({ current: e.key }) } componentDidMount() { } render() { return ( <Layout style={{minHeight: '100vh'}}> <Sider collapsible collapsed={this.state.collapsed} onCollapse={this.onCollapse}> <div className="logo"/> <Menu theme="dark" defaultSelectedKeys={['1']} onClick={this.handleClick} mode="inline"> <Menu.Item key="1"> <Link to="/"> <Icon type="desktop"/> <span>ORC 转换</span> </Link> </Menu.Item> <Menu.Item key="2"> <Link to="/hDFSPanel"> <Icon type="file"/> <span>HDFS Topics</span> </Link> </Menu.Item> <Menu.Item key="3"> <Link to="/hBasePanel"> <Icon type="file"/> <span>HBbase Topics</span> </Link> </Menu.Item> </Menu> </Sider> <Layout> <Header style={{background: '#fff', padding: 0}}/> <Content style={{margin: '0 16px'}}> <Breadcrumb style={{margin: '20px 0'}}> <Breadcrumb.Item>Upgrade</Breadcrumb.Item> </Breadcrumb> { this.props.children } </Content> <Footer style={{textAlign: 'center'}}> ORC File Upgrade </Footer> </Layout> </Layout> ); } } // 配置路由 render(( <Router history={hashHistory} > <Route path="/" component={MainMenu}> <IndexRoute component={ConversionPanel} /> <Route path="hDFSPanel" component={HDFSPanel} /> <Route path="hBasePanel" component={HBasePanel} /> </Route> </Router> ), document.getElementById('root')); <file_sep>import React from 'react' import { render } from 'react-dom' // 引入react-router模块 import { Router, Route, Link, hashHistory, IndexRoute, Redirect, IndexLink, browserHistory } from 'react-router' import HTTPUtil from '../../../actions/fetch/FetchUtils.js' import CommonTopics from '../../common/common-tables/CommonTopics.js' export default class HDFSPanel extends React.Component{ constructor(props) { super(props) this.state = { tablesNum: 0, tablesInfo: [] } } getData = () => { let urls = [ "/api/configInfo/get/getHDFSTopics" ]; let tableInfoAll; HTTPUtil.URLs(urls).then((text) => { if(text.size != 0 ){ let tableInfo = JSON.parse(text[0]); var tablesDetails = []; for(var o in tableInfo){ tablesDetails.push(tableInfo[o]); } this.setState({ tablesNum : tableInfo.length, tablesInfo : tablesDetails }) }else{ console.log("fetch exception " + text.code); } },(text)=>{ console.log("fetch fail " + text.code); }) } componentDidMount() { this.getData(); } update = (newState) => { this.getData(); } render() { return ( <div style={{padding: 24, background: '#fff', minHeight: 360}}> <CommonTopics tablesNum={this.state.tablesNum} tablesInfo={this.state.tablesInfo} updateConversionPanel={this.update}/> </div> ); } }<file_sep>import React from 'react' import { render } from 'react-dom' // 引入react-router模块 import { Router, Route, Link, hashHistory, IndexRoute, Redirect, IndexLink, browserHistory } from 'react-router' import { Table, Button } from 'antd'; import HTTPUtil from '../../../actions/fetch/FetchUtils.js' import CommonUtils from '../../common/utils/CommonUtils.js' const columns = [{ title: 'Table Name', dataIndex: 'table_name', } ]; export default class CommonTables extends React.Component { constructor(props) { super(props) this.state = { data: [], num: '' } } componentDidMount() { } /** * 更新父组件回调 */ updateConversionPanel = (status) => { this.props.updateConversionPanel(status); } refresh = () => { this.updateConversionPanel(true); } render() { this.state.num = this.props.tablesNum; this.state.data = this.props.tablesInfo; return ( <div> <div style={{ marginBottom: 16 }}> <Button type="primary" onClick={this.refresh} > 刷新 </Button> </div> <Table columns={columns} dataSource={this.state.data} footer={() => <div><strong>All Size:{this.state.data.length}</strong></div>} /> </div> ); } }<file_sep>var CommonUtils = {}; CommonUtils.formatDate = function formatDate(datetime) { var year = datetime.getFullYear(), month = (datetime.getMonth() + 1 < 10) ? '0' + (datetime.getMonth() + 1) : datetime.getMonth() + 1, day = datetime.getDate() < 10 ? '0' + datetime.getDate() : datetime.getDate(), hour = datetime.getHours() < 10 ? '0' + datetime.getHours() : datetime.getHours(), min = datetime.getMinutes() < 10 ? '0' + datetime.getMinutes() : datetime.getMinutes(), sec = datetime.getSeconds() < 10 ? '0' + datetime.getSeconds() : datetime.getSeconds(); return year + '-' + month + '-' + day + ' ' + hour + ':' + min + ':' + sec; } //添加或者修改json数据 CommonUtils.setJson = function setJson(jsonStr, name, value) { if(!jsonStr)jsonStr="{}"; var jsonObj = JSON.parse(jsonStr); jsonObj[name] = value; return JSON.stringify(jsonObj); } export default CommonUtils;<file_sep>import React from 'react' import { render } from 'react-dom' // 引入react-router模块 import { Router, Route, Link, hashHistory, IndexRoute, Redirect, IndexLink, browserHistory } from 'react-router' import { Table, Button, Form,Switch, Icon,Badge,message,Menu, Dropdown} from 'antd'; const FormItem = Form.Item; import HTTPUtil from '../../actions/fetch/FetchUtils.js' import CommonUtils from '../common/utils/CommonUtils.js' import './css/conversion.css' const TableStatus = React.createClass({ render() { let tableStatus = this.props.status; let badgeStatus = "default"; if(tableStatus == "Running") { badgeStatus = "processing"; } else if(tableStatus == "Finish") { badgeStatus = "success"; } return ( <span><Badge status={badgeStatus} />{tableStatus}</span> ); } }) const columns = [{ title: 'Id', dataIndex: 'table_id', }, { title: 'Table Name', dataIndex: 'table_name', }, { title: 'Table Type', dataIndex: 'table_type', }, { title: 'Table Status', dataIndex: 'table_status', render: (text) => <TableStatus status={text} /> }, { title: 'Upgrade PartDate', dataIndex: 'part_date', },{ title: 'Upgrade Time', dataIndex: 'upgrade_time', }, { title: 'Finish Time', dataIndex: 'finish_time', } ]; export default class Conversion extends React.Component { constructor(props) { super(props) this.state = { selectedRowKeys: [], selectedRows: [], loading: false, data: [], num: '', timer: null } } upgradeTable = (tableInfo) => { tableInfo.table_status = "Running"; tableInfo.part_date = CommonUtils.formatDate(new Date()).substring(0,10); tableInfo.upgrade_time = CommonUtils.formatDate(new Date()); var status = HTTPUtil.post("/api/upgrade/update/sequenceToOrcInfo", JSON.stringify(tableInfo)); message.info(tableInfo.table_name + " upgrading.......", 10); console.log("更新") } handleMenuClick = (e) => { this.updateConversionPanel(e.key); } typeMenu = ( <Menu onClick={this.handleMenuClick} > <Menu.Item key="all">All</Menu.Item> <Menu.Item key="Hive">Hive</Menu.Item> <Menu.Item key="HBase">HBase</Menu.Item> </Menu> ); statusMenu = ( <Menu onClick={this.handleMenuClick} > <Menu.Item key="Init">Init</Menu.Item> <Menu.Item key="Running">Running</Menu.Item> <Menu.Item key="Finish">Finish</Menu.Item> </Menu> ); /** * 更新父组件回调 */ updateConversionPanel = (status) => { this.props.updateConversionPanel(status); } refresh = () => { console.log("刷新"); this.updateConversionPanel(true); } start = () => { this.setState({ loading: true }); // ajax request after empty completing setTimeout(() => { for (var key in this.state.selectedRows) { var jsonData = this.state.selectedRows[key]; let urls = [ "/api/upgrade/getTopicByName/" + jsonData.table_name ]; HTTPUtil.URLs(urls).then((text) => { if(text.size != 0 ){ console.log(text[0]); this.upgradeTable(JSON.parse(text[0])); this.refresh(); }else{ console.log("fetch exception " + text.code); } },(text)=>{ console.log("fetch fail " + text.code); }) } this.setState({ selectedRowKeys: [], selectedRows: [], loading: false, }); }, 500); } componentWillUnmount() { clearInterval(this.state.timer); } componentDidMount() { } onSelectChange = (selectedRowKeys,selectedRows) => { this.setState({ selectedRowKeys, selectedRows }); } autoRefresh = (enable) => { if(enable) { this.state.timer = setInterval(() => { console.log('refresh: ', CommonUtils.formatDate(new Date())); this.updateConversionPanel(true); }, 60 * 1000); } else { clearInterval(this.state.timer); } } render() { this.state.num = this.props.tablesNum; this.state.data = this.props.tablesInfo; const { loading, selectedRowKeys } = this.state; const rowSelection = { selectedRowKeys, onChange: this.onSelectChange, hideDefaultSelections: true, onSelection: this.onSelection, }; const hasSelected = selectedRowKeys.length > 0; return ( <div> <div className="table-operations"> <Form layout="inline"> <FormItem label="自动刷新表状态(1min)"> <Switch checkedChildren="开" unCheckedChildren="关" onChange={this.autoRefresh} /> </FormItem> <FormItem> <Dropdown overlay={this.typeMenu}> <Button style={{ marginLeft: 8 }}> 分类 <Icon type="down" /> </Button> </Dropdown> </FormItem> <FormItem> <Dropdown overlay={this.statusMenu}> <Button style={{ marginLeft: 8 }}> 状态过滤 <Icon type="down" /> </Button> </Dropdown> </FormItem> <FormItem> <Button type="primary" onClick={this.refresh} > 刷新 </Button> </FormItem> <FormItem> <Button type="primary" onClick={this.start} disabled={!hasSelected} loading={loading}> 转换 </Button> <span style={{ marginLeft: 8 }}> {hasSelected ? `已选择 ${selectedRowKeys.length}` : ''} </span> </FormItem> </Form> </div> <Table rowSelection={rowSelection} columns={columns} dataSource={this.state.data} footer={() => <div><strong>All Size:{this.state.data.length}</strong></div>} /> </div> ); } }
0027c1559b02a5f8737cc0d7dadca40ba14bce93
[ "JavaScript" ]
6
JavaScript
imperio-wxm/react-demos-segment
2f6299939e1a492f7078000bd4e54fbb79e06b9e
8db37b6be8aa2a39bbbff85dc5509aad211a1814
refs/heads/master
<repo_name>VBulikov/etcd-java-driver<file_sep>/README.md # etcd-java-driver<file_sep>/etcd-driver/src/main/java/my/dev/libs/config/etcd_driver/request/EtcdKeyRequest.java package my.dev.libs.config.etcd_driver.request; import my.dev.libs.config.etcd_driver.transport.EtcdDriverImpl; import org.springframework.http.HttpMethod; import java.util.HashMap; import java.util.Map; /** * Created by <NAME> on 23.01.2017. */ public class EtcdKeyRequest extends AbstractEtcdRequest { protected final String key; protected final Map<String, String> requestParams; public EtcdKeyRequest(EtcdDriverImpl clientImpl, HttpMethod method) { this(clientImpl, method, null); } public EtcdKeyRequest(EtcdDriverImpl clientImpl, HttpMethod method, String key) { super(null, clientImpl, method); if (key != null && key.startsWith("/")){ key = key.substring(1); } this.key = key; this.requestParams = new HashMap<>(); } public String getKey() { return key; } @Override public Map<String, String> getRequestParams() { return requestParams; } @Override public String getUrl() { return "/v2/keys/" + ((key != null) ? key : ""); } } <file_sep>/etcd-driver/src/main/java/my/dev/libs/config/etcd_driver/request/EtcdKeyPutRequest.java package my.dev.libs.config.etcd_driver.request; import my.dev.libs.config.etcd_driver.transport.EtcdDriverImpl; import org.springframework.http.HttpMethod; /** * Created by <NAME> on 23.01.2017. */ public class EtcdKeyPutRequest extends EtcdKeyRequest { public EtcdKeyPutRequest(EtcdDriverImpl clientImpl, String key) { super(clientImpl, HttpMethod.PUT, key); } public EtcdKeyPutRequest value(String value) { this.requestParams.put("value", value); return this; } public EtcdKeyPutRequest ttl(Integer ttl) { this.requestParams.put("ttl", (ttl == null) ? "" : ttl + ""); return this; } public EtcdKeyPutRequest refresh(Integer ttl) { this.requestParams.put("refresh", "true"); this.prevExist(true); return ttl(ttl); } public EtcdKeyPutRequest isDir() { this.requestParams.put("dir", "true"); return this; } @Deprecated public EtcdKeyPutRequest prevExist() { this.requestParams.put("prevExist", "true"); return this; } public EtcdKeyPutRequest prevExist(boolean prevExists) { this.requestParams.put("prevExist", String.valueOf(prevExists)); return this; } public EtcdKeyPutRequest prevIndex(long prevIndex) { this.requestParams.put("prevIndex", prevIndex + ""); return this; } public EtcdKeyPutRequest prevValue(String value) { this.requestParams.put("prevValue", value); return this; } }<file_sep>/etcd-driver/src/main/java/my/dev/libs/config/etcd_driver/transport/EtcdDriverImpl.java package my.dev.libs.config.etcd_driver.transport; import my.dev.libs.config.etcd_driver.request.EtcdRequest; import my.dev.libs.config.etcd_driver.response.EtcdKeysResponse; import java.io.Closeable; import java.io.IOException; import java.net.URISyntaxException; /** * Created by <NAME> on 23.01.2017. */ public interface EtcdDriverImpl extends Closeable { EtcdKeysResponse send(EtcdRequest etcdRequest) throws IOException, URISyntaxException; @Override void close() throws IOException; } <file_sep>/etcd-driver/src/main/java/my/dev/libs/config/etcd_driver/request/EtcdRequest.java package my.dev.libs.config.etcd_driver.request; import my.dev.libs.config.etcd_driver.transport.EtcdDriverImpl; import my.dev.libs.config.etcd_driver.response.EtcdKeysResponse; import org.springframework.http.HttpMethod; import java.io.IOException; import java.net.URISyntaxException; import java.util.Map; /** * Created by <NAME> on 23.01.2017. */ public abstract class EtcdRequest { protected final EtcdDriverImpl clientImpl; protected final HttpMethod method; protected Map<String, String> requestParams; private String url; public abstract EtcdKeysResponse send() throws IOException, URISyntaxException; public EtcdRequest(EtcdDriverImpl clientImpl, HttpMethod method) { this.clientImpl = clientImpl; this.method = method; } public HttpMethod getMethod() { return method; } public String getUrl() { return url; } public Map<String, String> getRequestParams() { return requestParams; } } <file_sep>/etcd-driver/src/main/java/my/dev/libs/config/etcd_driver/request/AbstractEtcdRequest.java package my.dev.libs.config.etcd_driver.request; import my.dev.libs.config.etcd_driver.transport.EtcdDriverImpl; import my.dev.libs.config.etcd_driver.response.EtcdKeysResponse; import org.springframework.http.HttpMethod; import java.io.IOException; import java.net.URISyntaxException; /** * Created by <NAME> on 23.01.2017. */ public class AbstractEtcdRequest extends EtcdRequest { private final String url; public AbstractEtcdRequest(String url, EtcdDriverImpl clientImpl, HttpMethod method) { super(clientImpl, method); this.url = url; } @Override public EtcdKeysResponse send() throws IOException, URISyntaxException { return clientImpl.send(this); } @Override public String getUrl() { return super.getUrl(); } } <file_sep>/etcd-driver/src/main/java/my/dev/libs/config/etcd_driver/transport/EtcdDriverRestTemplate.java package my.dev.libs.config.etcd_driver.transport; import my.dev.libs.config.etcd_driver.request.EtcdRequest; import my.dev.libs.config.etcd_driver.response.EtcdKeysResponse; import org.apache.commons.validator.routines.UrlValidator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponentsBuilder; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.Iterator; import java.util.Map; /** * Created by <NAME> on 23.01.2017. */ public class EtcdDriverRestTemplate implements EtcdDriverImpl{ private final static Logger logger = LoggerFactory.getLogger(EtcdDriverRestTemplate.class); private final RestTemplate restTemplate; private String url; private UrlValidator validator = new UrlValidator(UrlValidator.ALLOW_LOCAL_URLS); public EtcdDriverRestTemplate(String url){ this.restTemplate = new RestTemplate(); if(this.validator.isValid(url)) { try { this.url = (new URL(url)).toString(); } catch (Exception e) { logger.error("Etcd server url : " + url + " - is not correct."); System.exit(-1); } }else { logger.error("Etcd server url : " + url + " - is not correct."); System.exit(-1); } } @Override public EtcdKeysResponse send(EtcdRequest etcdRequest) throws IOException, URISyntaxException { EtcdKeysResponse s = connect(etcdRequest); return s; } protected EtcdKeysResponse connect(final EtcdRequest etcdRequest) throws IOException, URISyntaxException { final URI uri; // when we are called from a redirect, the url in the com.ssc.etcd_driver.request may also // contain host and port! URI requestUri = new URI(this.url + etcdRequest.getUrl()); if (requestUri.getHost() != null && requestUri.getPort() > -1) { uri = requestUri; } else if (System.getenv("CONFIG_URL") != null) { String endpoint_uri = System.getenv("CONFIG_URL"); if(logger.isDebugEnabled()) { logger.debug("Will use environment variable {} as uri with value {}", "CONFIG_URL", endpoint_uri); } uri = new URI(endpoint_uri); } else { uri = new URI("http://127.0.0.1:2379"); } HttpEntity<String> requestEntity = new HttpEntity<>(new HttpHeaders()); UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(requestUri.toString()); if(etcdRequest.getMethod()!= HttpMethod.POST) { for (Iterator<Map.Entry<String, String>> mapIterator = etcdRequest.getRequestParams().entrySet().iterator(); mapIterator.hasNext(); ) { Map.Entry<String, String> entry = mapIterator.next(); uriComponentsBuilder.queryParam(entry.getKey(),entry.getValue()); } } ResponseEntity<EtcdKeysResponse> responseEntity = restTemplate.exchange(uriComponentsBuilder.toUriString(), etcdRequest.getMethod(), requestEntity, EtcdKeysResponse.class); return responseEntity.getBody(); } @Override public void close() { logger.info("Shutting down Etcd4j Netty client"); } }
783f1e3f1f6665edabc3fb30c4bd3f441214af84
[ "Markdown", "Java" ]
7
Markdown
VBulikov/etcd-java-driver
9c1fc53eac714a32d30ff4408d47c59919c608f9
4b050978c93b7701c8c31d3219493a7312dd999b
refs/heads/master
<file_sep>package example20180331; public class Student extends Human{ String major; public Student(String name, int age, String major) { this.setMajor(major); super.setName(name); super.setAge(age); } public void setMajor(String major) { this.major = major; } public String getMajor() { return this.major; } public static void main(String[] args) { Student Peter = new Student("Peter",19,"Programming"); } } <file_sep>package example20180331; public class Human { String name; int age; public Human() { } public Human(String name, int age) { this.setName(name); this.setAge(age); } public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } public String getName() { return this.name; } public int getAge() { return this.age; } public static void main(String[] args) { // TODO Auto-generated method stub } } <file_sep>package example20180331; import java.util.*; public class Figure { String color; boolean filled; String dateCreated; public Figure(){ this.color = "white"; this.filled = false; } public String getColor() { return this.color; } public void setColor(String color) { this.color = color; } public boolean getFilled() { return this.filled; } public void setFilled(boolean filled) { this.filled = filled; } public void toString(String str) { System.out.println(str); } } <file_sep>package example20180331; import java.util.*; public class Rectangle1 { double width, height; public Rectangle1() { } public Rectangle1(double width, double height) { this.width = width; this.height = height; } public double getWidth() { return this.width; } public void setWidth(double width) { this.width = width; } public double getHeight() { return this.height; } public void setHeight(double height) { this.height = height; } public double getArea() { double area = this.width * this.height; return area; } public double getPerimeter() { double perimeter = 2*(this.width + this.height); return perimeter; } public static void main(String[] args) { Rectangle1 ab = new Rectangle1(3,4); System.out.println(ab.getArea()); } } <file_sep>package example20180331; import java.util.*; public class CallPhone { String model, brand, color; int power, camera; public void setInfo(String model, String brand, String color, int camera) { this.model = model; this.brand = brand; this.color = color; this.camera = camera; } public String power() { if(this.power == 1) { this.power = 0; return "전원이 꺼집니다."; } else { this.power = 1; return "전원이 켜집니다."; } } public void camera() { if(this.camera == 1) { System.out.println("카메라가 장착된 휴대폰 입니다."); } else { System.out.println("카메라가 장착되지 않은 휴대폰 입니다."); } } public CallPhone(String model, String brand, String color,int camera){ this.setInfo(model, brand, color,camera); } public static void main(String[] args) { CallPhone galaxy = new CallPhone("s9","Samsung","black",1); galaxy.camera(); System.out.println(galaxy.power()); System.out.println(galaxy.power()); System.out.println(galaxy.power()); } }
1ed8b56bd34650d695da6c960ea79727860572dd
[ "Java" ]
5
Java
wjdtjq0630/Java_example
215efce61d5c62913cc421072d4c182280f876b8
3128ecc35c6dc801546f9210a322eada3c714d25
refs/heads/main
<repo_name>sakthikiruthika/3D-Effects<file_sep>/script.js const card=document.querySelector(".card"); const container=document.querySelector("#cardwrapper"); const pic=document.querySelector(".image"); console.log(window.pageXOffset); container.addEventListener('mousemove',(e) =>{ //console.log(e.pageY); let Xaxis=(window.innerWidth/2 - e.pageX)/10; let Yaxis=(window.innerHeight/2 - e.pageY)/10; card.style.transform=(`rotateY(${Yaxis}deg) rotateX(${Xaxis}deg)`); pic.style.transform=`translateZ(150px) rotateZ(-45deg)`; }); container.addEventListener('mouseenter',(e=>{ card.style.transform="none"; pic.style.transform="none"; })) container.addEventListener('mouseleave',(e)=>{ card.style.transition="all 0.5s ease"; pic.style.transition="all 0.5s ease"; card.style.transform=(`rotateY(0deg) rotateX(0deg)`); pic.style.transform=`translateZ(0px) rotateZ(0)`; }) <file_sep>/README.md # 3D-Effects ## about the effect ### The picture that has height,width and depth is 3D[Three dimensional] ### 3D imaging is an technique to develop or create the illusion of depth in an image. ### The 3D effects is used for easy learning.. ### Enjoy the effect!... ## [LIVE DEMO]( https://sakthikiruthika.github.io/3D-Effects/)
6661fd7876e18214f368f76aa8ed767568e67e01
[ "JavaScript", "Markdown" ]
2
JavaScript
sakthikiruthika/3D-Effects
78badd12be9cf0f0fa367ae01f36f63acc1acac3
7b6e322aa0d2176d4efe1a48cea92d94a7f55c61
refs/heads/master
<file_sep>// // ClothCell.swift // What to Wear Today // // Created by <NAME> on 10/06/15. // Copyright (c) 2015 akanksha. All rights reserved. // import UIKit class ClothCell: UICollectionViewCell { @IBOutlet weak var clothImg: UIImageView! } <file_sep>// // ShowPairsViewController.swift // What to Wear Today // // Created by <NAME> on 10/06/15. // Copyright (c) 2015 akanksha. All rights reserved. // import UIKit import Foundation import CoreData import FBSDKShareKit class ShowPairsViewController: UIViewController { @IBOutlet weak var view2: UIView! @IBOutlet weak var view1: UIView! @IBOutlet weak var upper1: UIImageView! @IBOutlet weak var lower1: UIImageView! @IBOutlet weak var upper2: UIImageView! @IBOutlet weak var lower2: UIImageView! var uppersArray : NSArray = NSArray() var lowersArray : NSArray = NSArray() var pairsArray : NSMutableArray = NSMutableArray() var upperId : Int = 0 var lowerId : Int = 0 var upperImagePath : String = "" var lowerImagePath : String = "" var view1Visible : Bool = true var view2Visible : Bool = false var pairsCount : Int = 0 var leftSwipeCount : Int = 0 var rightSwipeCount : Int = 0 let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext override func viewDidLoad() { super.viewDidLoad() var swipeLeft = UISwipeGestureRecognizer(target: self, action: "respondToSwipeGesture:") var swipeRight = UISwipeGestureRecognizer(target: self, action: "respondToSwipeGesture:") swipeLeft.direction = UISwipeGestureRecognizerDirection.Left swipeRight.direction = UISwipeGestureRecognizerDirection.Right self.view.addGestureRecognizer(swipeLeft) self.view.addGestureRecognizer(swipeRight) fetchClothes() upper1.image = getImageFromPath(pairsArray.objectAtIndex(0).objectForKey("upperImagePath") as! String) lower1.image = getImageFromPath(pairsArray.objectAtIndex(0).objectForKey("lowerImagePath") as! String) leftSwipeCount = leftSwipeCount + 1 rightSwipeCount = pairsCount - 1 } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewDidLayoutSubviews() { if(!view2Visible){ println("celled") view2Visible = true view2.center = CGPointMake(self.view2.center.x + 4000 , self.view2.center.y) } } func respondToSwipeGesture(gesture: UIGestureRecognizer) { // println("count before : \(count)") //if(count <= pairsCount - 1 && count > 0){ if(leftSwipeCount == pairsCount){ leftSwipeCount = 0 } if(rightSwipeCount == 0){ rightSwipeCount = pairsCount - 1 } if let swipeGesture = gesture as? UISwipeGestureRecognizer { println("View : \(self.view.center.x)") println("view 1 :: \(self.view1.center.x)") println("view 2 :: \(self.view2.center.x)") switch swipeGesture.direction { case UISwipeGestureRecognizerDirection.Left: if(leftSwipeCount <= pairsCount - 1){ self.upperImagePath = self.pairsArray.objectAtIndex(self.leftSwipeCount).objectForKey("upperImagePath") as! String self.upper1.image = getImageFromPath(self.upperImagePath) self.lowerImagePath = self.pairsArray.objectAtIndex(self.leftSwipeCount).objectForKey("lowerImagePath") as! String self.lower1.image = getImageFromPath(self.lowerImagePath) self.upperId = self.pairsArray.objectAtIndex(self.leftSwipeCount).objectForKey("upperClothId") as! Int self.lowerId = self.pairsArray.objectAtIndex(self.leftSwipeCount).objectForKey("lowerClothId") as! Int leftSwipeCount = leftSwipeCount + 1 } case UISwipeGestureRecognizerDirection.Right: if(rightSwipeCount >= 0){ self.upperImagePath = self.pairsArray.objectAtIndex(self.rightSwipeCount).objectForKey("upperImagePath") as! String self.upper1.image = getImageFromPath(self.upperImagePath) self.lowerImagePath = self.pairsArray.objectAtIndex(self.rightSwipeCount).objectForKey("lowerImagePath") as! String self.lower1.image = getImageFromPath(self.lowerImagePath) self.upperId = self.pairsArray.objectAtIndex(self.rightSwipeCount).objectForKey("upperClothId") as! Int self.lowerId = self.pairsArray.objectAtIndex(self.rightSwipeCount).objectForKey("lowerClothId") as! Int rightSwipeCount = rightSwipeCount - 1 } default: break } // upper1.contentMode = .ScaleAspectFit // lower1.contentMode = .ScaleAspectFit // upper2.contentMode = .ScaleAspectFit // lower2.contentMode = .ScaleAspectFit } //} //println("count after : \(count)") } func randRange (lower: Int , upper: Int) -> Int { return lower + Int(arc4random_uniform(UInt32(upper - lower + 1))) } func fetchClothes(){ let entityDescription1 = NSEntityDescription.entityForName("Cloth",inManagedObjectContext: managedObjectContext!) let uppersRequest = NSFetchRequest() uppersRequest.entity = entityDescription1 let pred = NSPredicate(format: "(type_id = %d)", CLOTH_TYPE_UPPER) uppersRequest.predicate = pred var error: NSError? var objects = managedObjectContext?.executeFetchRequest(uppersRequest, error: &error) uppersArray = (objects as? NSArray)! let lowersRequest = NSFetchRequest() lowersRequest.entity = entityDescription1 let lowerspred = NSPredicate(format: "(type_id = %d)", CLOTH_TYPE_LOWER) lowersRequest.predicate = lowerspred var error1: NSError? var lowersobjects = managedObjectContext?.executeFetchRequest(lowersRequest, error: &error1) lowersArray = (lowersobjects as? NSArray)! generatePairs() } func generatePairs(){ for ( var i = 0 ; i < uppersArray.count; i++) { for ( var j = 0 ; j < lowersArray.count; j++) { var pairDict : NSMutableDictionary = NSMutableDictionary() var upper : Cloth = uppersArray[i] as! Cloth var lower : Cloth = lowersArray[j] as! Cloth pairDict.setValue(upper.img_path, forKey: "upperImagePath") pairDict.setValue(lower.img_path, forKey: "lowerImagePath") pairDict.setValue(upper.cloth_id, forKey: "upperClothId") pairDict.setValue(lower.cloth_id, forKey: "lowerClothId") pairsArray.addObject(pairDict) } } pairsCount = pairsArray.count println("pairs count -- \(pairsArray.count)") } @IBAction func sharePair(sender: AnyObject) { UIGraphicsBeginImageContext(sender.superview!!.frame.size) view.layer.renderInContext(UIGraphicsGetCurrentContext()) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() var photo : FBSDKSharePhoto = FBSDKSharePhoto() photo.image = image photo.userGenerated = true var content : FBSDKSharePhotoContent = FBSDKSharePhotoContent() content.photos = [photo] FBSDKShareDialog.showFromViewController(self, withContent: content, delegate: nil) } @IBAction func bookMarkPair(sender: AnyObject) { let entityDescription = NSEntityDescription.entityForName("Pair", inManagedObjectContext: managedObjectContext!) let pair = Pair(entity: entityDescription!, insertIntoManagedObjectContext: managedObjectContext) pair.shirtPath = upperImagePath pair.jeansPath = lowerImagePath pair.jeans_id = lowerId pair.shirt_id = upperId pair.status = 1 var error: NSError? managedObjectContext?.save(&error) if let err = error { println(error) } else { println("Saved successfully") //performSegueWithIdentifier("showClothes", sender: self) } } @IBAction func dislikePair(sender: AnyObject) { var swipe = UISwipeGestureRecognizer() swipe.direction = UISwipeGestureRecognizerDirection.Left respondToSwipeGesture(swipe) } } <file_sep>// // Cloth.swift // What to Wear Today // // Created by <NAME> on 10/06/15. // Copyright (c) 2015 akanksha. All rights reserved. // import Foundation import CoreData class Cloth: NSManagedObject { @NSManaged var img_path: String @NSManaged var type_id: NSNumber @NSManaged var cloth_id: NSNumber } <file_sep>// // BookMarkCell.swift // What to Wear Today // // Created by <NAME> on 11/06/15. // Copyright (c) 2015 akanksha. All rights reserved. // import UIKit class BookMarkCell: UICollectionViewCell { @IBOutlet weak var loweImg: UIImageView! @IBOutlet weak var upperImg: UIImageView! } <file_sep>// // ImageUtil.swift // What to Wear Today // // Created by <NAME> on 6/9/15. // Copyright (c) 2015 akanksha. All rights reserved. // import Foundation import UIKit func getImageFromURL(var path :String)-> UIImage{ let url = NSURL(string : path) if(url != nil){ let data = NSData(contentsOfURL: url!) if(data != nil){ return UIImage(data: data!)! } else { return UIImage(named: "default-user.png")! } } else { return UIImage(named: "default-user.png")! } } func getImageFromPath(filePath : String) -> UIImage { var documentsDirectory : NSString = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! NSString var fullPathToFile2 : NSString = documentsDirectory.stringByAppendingPathComponent(filePath) var savedImageData :NSData = NSData(contentsOfFile: fullPathToFile2 as String)! return UIImage(data: savedImageData)! }<file_sep>// // ListClothesViewController.swift // What to Wear Today // // Created by <NAME> on 10/06/15. // Copyright (c) 2015 akanksha. All rights reserved. // import UIKit import CoreData class ListClothesViewController: UIViewController,UICollectionViewDataSource,UICollectionViewDelegate { @IBOutlet weak var uppers: UICollectionView! @IBOutlet weak var lowers: UICollectionView! @IBOutlet weak var message: UILabel! @IBOutlet weak var startMatchingBtn: UIButton! var uppersArray : NSArray = NSArray() var lowersArray : NSArray = NSArray() let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext override func viewDidLoad() { fetchClothes() if(uppersArray.count >= 2 && lowersArray.count >= 2){ startMatchingBtn.hidden = false message.hidden = true NSUserDefaults.standardUserDefaults().setValue(true, forKey: "hasPairs") NSUserDefaults.standardUserDefaults().synchronize() } } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{ if(collectionView == uppers){ return uppersArray.count } else { return lowersArray.count } } // The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath: func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell{ if(collectionView == uppers){ let cell : ClothCell = collectionView.dequeueReusableCellWithReuseIdentifier("uppersCell", forIndexPath: indexPath) as! ClothCell var cloth:Cloth = uppersArray.objectAtIndex(indexPath.row) as! Cloth println(cloth.img_path) var documentsDirectory : NSString = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! NSString var fullPathToFile2 : NSString = documentsDirectory.stringByAppendingPathComponent(cloth.img_path) cell.clothImg.contentMode = .ScaleAspectFit var savedImageData :NSData = NSData(contentsOfFile: fullPathToFile2 as String)! cell.clothImg.image = UIImage(data: savedImageData) return cell } else { let cell : ClothCell = collectionView.dequeueReusableCellWithReuseIdentifier("lowersCell", forIndexPath: indexPath) as! ClothCell var cloth:Cloth = lowersArray.objectAtIndex(indexPath.row) as! Cloth println(cloth.img_path) var documentsDirectory : NSString = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! NSString var fullPathToFile2 : NSString = documentsDirectory.stringByAppendingPathComponent(cloth.img_path) cell.clothImg.contentMode = .ScaleAspectFit var savedImageData :NSData = NSData(contentsOfFile: fullPathToFile2 as String)! cell.clothImg.image = UIImage(data: savedImageData) return cell } } func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func fetchClothes(){ let entityDescription = NSEntityDescription.entityForName("Cloth", inManagedObjectContext: managedObjectContext!) let uppersRequest = NSFetchRequest() uppersRequest.entity = entityDescription let pred = NSPredicate(format: "(type_id = %d)", CLOTH_TYPE_UPPER) uppersRequest.predicate = pred var error: NSError? var objects = managedObjectContext?.executeFetchRequest(uppersRequest, error: &error) uppersArray = (objects as? NSArray)! let lowersRequest = NSFetchRequest() lowersRequest.entity = entityDescription let lowerspred = NSPredicate(format: "(type_id = %d)", CLOTH_TYPE_LOWER) lowersRequest.predicate = lowerspred var error1: NSError? var lowersobjects = managedObjectContext?.executeFetchRequest(lowersRequest, error: &error1) lowersArray = (lowersobjects as? NSArray)! /*if let results = objects { if results.count > 0 { let match = results[0] as! NSManagedObject var fetchedCloth : Cloth = match as! Cloth } else { println("No macthes found") } }*/ uppers.reloadData() lowers.reloadData() } } <file_sep>// // Constants.swift // What to Wear Today // // Created by <NAME> on 10/06/15. // Copyright (c) 2015 akanksha. All rights reserved. // import Foundation let CLOTH_TYPE_UPPER = 1 let CLOTH_TYPE_LOWER = 2 <file_sep>// // Pair.swift // What to Wear Today // // Created by <NAME> on 10/06/15. // Copyright (c) 2015 akanksha. All rights reserved. // import Foundation import CoreData class Pair: NSManagedObject { @NSManaged var id: NSNumber @NSManaged var shirt_id: NSNumber @NSManaged var status: NSNumber @NSManaged var is_shared: NSNumber @NSManaged var jeans_id: NSNumber @NSManaged var jeansPath: NSString @NSManaged var shirtPath: NSString } <file_sep># myApps What to wear? <file_sep>// // HomeViewController.swift // What to Wear Today // // Created by <NAME> on 09/06/15. // Copyright (c) 2015 akanksha. All rights reserved. // import UIKit import MobileCoreServices import CoreData class HomeViewController: UIViewController , UINavigationControllerDelegate,UIImagePickerControllerDelegate{ @IBOutlet var imageView: UIImageView! @IBOutlet var chooseBuuton: UIButton! @IBOutlet weak var takePictureBtn: UIButton! @IBOutlet weak var addUpper: UIButton! @IBOutlet weak var addLower: UIButton! @IBOutlet weak var continueBtn: UIButton! @IBOutlet weak var savedImageView: UIView! @IBOutlet weak var savedImage: UIImageView! let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext var newMedia: Bool? var imagePicker = UIImagePickerController() var IMAGE_COUNTER : Int = 0 var clothTypeId : Int = 0 var imgPath : String = "" override func viewDidLoad() { super.viewDidLoad() if(NSUserDefaults.standardUserDefaults().objectForKey("image_counter") != nil){ IMAGE_COUNTER = NSUserDefaults.standardUserDefaults().objectForKey("image_counter") as! Int } // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidLayoutSubviews() { savedImageView.center = CGPointMake(self.savedImageView.center.x + 4000 , self.savedImageView.center.y) } @IBAction func savephoto(sender: AnyObject) { if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.SavedPhotosAlbum){ println("Button capture") imagePicker.delegate = self imagePicker.sourceType = UIImagePickerControllerSourceType.SavedPhotosAlbum; imagePicker.allowsEditing = false self.presentViewController(imagePicker, animated: true, completion: nil) } } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) { var img : UIImage = UIImage() if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage { imageView.contentMode = .ScaleAspectFit dismissViewControllerAnimated(true, completion: nil) IMAGE_COUNTER = IMAGE_COUNTER + 1; NSUserDefaults.standardUserDefaults().setObject(IMAGE_COUNTER, forKey: "image_counter") NSUserDefaults.standardUserDefaults().synchronize() // Get the data for the image var imageData : NSData = UIImageJPEGRepresentation(pickedImage, 1.0) // Give a name to the file var incrementedImgStr : NSString = NSString(format: "Img_%d.jpg",IMAGE_COUNTER) var documentsDirectory : NSString = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! NSString var fullPathToFile2 : NSString = documentsDirectory.stringByAppendingPathComponent(incrementedImgStr as String) imgPath = incrementedImgStr as String imageData.writeToFile(fullPathToFile2 as String, atomically: false) var savedImageData :NSData = NSData(contentsOfFile: fullPathToFile2 as String)! imageView.image = UIImage(data: savedImageData) if(picker.sourceType == UIImagePickerControllerSourceType.Camera){ UIImageWriteToSavedPhotosAlbum(UIImage(data: savedImageData), nil, nil, nil) } saveImageDetails(picker) continueBtn.hidden = false } } @IBAction func showSavedImage(sender: AnyObject) { var documentsDirectory : NSString = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! NSString var fullPathToFile2 : NSString = documentsDirectory.stringByAppendingPathComponent("Img_1.jpg") var savedImageData :NSData = NSData(contentsOfFile: fullPathToFile2 as! String)! self.savedImage.image = UIImage(data: savedImageData) UIView.animateWithDuration(1.0 as NSTimeInterval, animations: { self.savedImageView.center = CGPointMake(self.savedImageView.center.x - 4000 , self.savedImageView.center.y) }, completion: { finished in }) } @IBAction func useCameraRoll(sender: AnyObject) { if UIImagePickerController.isSourceTypeAvailable( UIImagePickerControllerSourceType.Camera) { let imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.sourceType = UIImagePickerControllerSourceType.Camera imagePicker.mediaTypes = [kUTTypeImage as NSString] imagePicker.allowsEditing = false self.presentViewController(imagePicker, animated: true, completion: nil) newMedia = true } } @IBAction func addUppers(sender: AnyObject) { clothTypeId = CLOTH_TYPE_UPPER chooseBuuton.hidden = false takePictureBtn.hidden = false addLower.hidden = true } @IBAction func addLowers(sender: AnyObject) { clothTypeId = CLOTH_TYPE_LOWER chooseBuuton.hidden = false takePictureBtn.hidden = false addUpper.hidden = true } @IBAction func saveImageDetails(sender: AnyObject){ let entityDescription = NSEntityDescription.entityForName("Cloth", inManagedObjectContext: managedObjectContext!) let cloth = Cloth(entity: entityDescription!, insertIntoManagedObjectContext: managedObjectContext) cloth.img_path = imgPath cloth.type_id = clothTypeId cloth.cloth_id = IMAGE_COUNTER var error: NSError? managedObjectContext?.save(&error) if let err = error { println(error) } else { println("Saved successfully") //performSegueWithIdentifier("showClothes", sender: self) } } /*func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController, animated: Bool){ if(doneBtn == nil){ doneBtn = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Done, target: self, action: "saveImagesDone:") } viewController.navigationItem.rightBarButtonItem = doneBtn } @IBAction func saveImagesDone(sender: AnyObject) { dismissViewControllerAnimated(true, completion: nil) }*/ // - (IBAction)SavePhotoOnClick:(id)sender{ // UIImageWriteToSavedPhotosAlbum(imageToBeSaved, nil, nil, nil); // } } <file_sep>// // BookmarksViewController.swift // What to Wear Today // // Created by <NAME> on 11/06/15. // Copyright (c) 2015 akanksha. All rights reserved. // import UIKit import CoreData class BookmarksViewController: UIViewController , UICollectionViewDataSource,UICollectionViewDelegate { @IBOutlet weak var bookmarks: UICollectionView! var bookMarkedPairs : NSArray = NSArray() let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext override func viewDidLoad() { fetchClothes() } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{ return bookMarkedPairs.count } // The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath: func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell{ let cell : BookMarkCell = collectionView.dequeueReusableCellWithReuseIdentifier("bookMarkCell", forIndexPath: indexPath) as! BookMarkCell var pair : Pair = bookMarkedPairs.objectAtIndex(indexPath.row) as! Pair cell.upperImg.contentMode = .ScaleAspectFit cell.loweImg.contentMode = .ScaleAspectFit cell.upperImg.image = getImageFromPath(pair.shirtPath as String) cell.loweImg.image = getImageFromPath(pair.jeansPath as String) return cell } func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func fetchClothes(){ let entityDescription = NSEntityDescription.entityForName("Pair", inManagedObjectContext: managedObjectContext!) let uppersRequest = NSFetchRequest() uppersRequest.entity = entityDescription var error: NSError? var objects = managedObjectContext?.executeFetchRequest(uppersRequest, error: &error) bookMarkedPairs = (objects as? NSArray)! bookmarks.reloadData() } } <file_sep>// // ViewController.swift // What to Wear Today // // Created by <NAME> on 06/06/15. // Copyright (c) 2015 akanksha. All rights reserved. // import UIKit import FBSDKCoreKit import FBSDKLoginKit //import FBSDKGraphRequest class ViewController: UIViewController,FBSDKLoginButtonDelegate { @IBOutlet weak var userProfileImg: UIImageView! @IBOutlet weak var userName: UILabel! @IBOutlet weak var welcomeLabel: UILabel! @IBOutlet weak var nextBtn: UIButton! @IBOutlet weak var fbloginBtn: UIButton! var dict : NSDictionary! override func viewDidLoad() { super.viewDidLoad() if(NSUserDefaults.standardUserDefaults().objectForKey("fbDetails") != nil){ dict = NSUserDefaults.standardUserDefaults().objectForKey("fbDetails") as! NSDictionary self.userName.text = self.dict.objectForKey("name") as? String self.userProfileImg.image = getImageFromURL(self.dict.objectForKey("picture")?.objectForKey("data")?.objectForKey("url")as! String) fbloginBtn.hidden = true userProfileImg.hidden = false userName.hidden = false nextBtn.hidden = false welcomeLabel.hidden = false } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func btnFBLoginPressed(sender: AnyObject) { var fbLoginManager : FBSDKLoginManager = FBSDKLoginManager() fbLoginManager .logInWithReadPermissions(["email"], handler: { (result, error) -> Void in if (error == nil){ var fbloginresult : FBSDKLoginManagerLoginResult = result if(fbloginresult.grantedPermissions.contains("email")) { self.fetchUserData() fbLoginManager.logOut() } } }) } /*! @abstract Sent to the delegate when the button was used to login. @param loginButton the sender @param result The results of the login @param error The error (if any) from the login */ func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!){ println(result.token.description) println(FBSDKProfile.currentProfile()) //var profile : NSDictionary = result as! NSDictionary //println(profile) if((FBSDKAccessToken.currentAccessToken()) != nil){ println(FBSDKGraphRequest().tokenString) } fetchUserData() } /*! @abstract Sent to the delegate when the button was used to logout. @param loginButton The button that was clicked. */ func loginButtonDidLogOut(loginButton: FBSDKLoginButton!){ } func fetchUserData(){ FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email,gender"]).startWithCompletionHandler({ (connection, result, error) -> Void in if (error == nil){ self.dict = result as! NSDictionary println(result) println(self.dict) NSLog(self.dict.objectForKey("picture")?.objectForKey("data")?.objectForKey("url")as! String) NSUserDefaults.standardUserDefaults().setObject(self.dict, forKey: "fbDetails") NSUserDefaults.standardUserDefaults().synchronize() self.userName.text = self.dict.objectForKey("name") as? String self.userProfileImg.image = getImageFromURL(self.dict.objectForKey("picture")?.objectForKey("data")?.objectForKey("url")as! String) self.fbloginBtn.hidden = true self.userProfileImg.hidden = false self.userName.hidden = false self.welcomeLabel.hidden = false self.nextBtn.hidden = false }else { println(error) } }) } }
860575c81ad1534b294c01c59491c6c1a1c9d98c
[ "Swift", "Markdown" ]
12
Swift
aKaNkShAdev/myApps
7c1642ffc901371909e1e85372a5a8be483f25ae
fe8162e11de0f066b0840ac8ee9b2d803ff2210a
refs/heads/master
<file_sep>cmake -D CMAKE_BUILD_TYPE=Release -D CMAKE_INSTALL_PREFIX=/usr/local \ -D OPENCV_EXTRA_MODULES_PATH=/home/x/Dev/opencv_contrib/modules \ -D OPENCV_TEST_DATA_PATH=/home/x/Dev/opencv_extra/testdata \ -D PYTHON3_EXECUTABLE=/home/x/anaconda3/bin/python \ -D PYTHON_INCLUDE_DIR=/home/x/anaconda3/include/python3.7m \ -D PYTHON_LIBRARY=/home/x/anaconda3/lib/libpython3.7m.so \ -D PYTHON3_NUMPY_INCLUDE_DIRS=/home/x/anaconda3/lib/python3.7/site-packages/numpy/core/include \ -BUILD_DOCS -BUILD_EXAMPLES -BUILD_CUDA_STUBS \ .. <file_sep># X-Scripts My .sh .bat .vimrc files
11f51adb208088150e9ed1ac555b19ad0e3101f4
[ "Markdown", "Shell" ]
2
Shell
xlert/X-Scripts
ef5ded09892bff2ef5ef0c2c6b62430e0b81d55d
0bfb73491f33c1a79cebaf00a5db992d9323ebe8
refs/heads/master
<file_sep># DSSCapstone NextWord - Data Science Specialization Capstone Project For the capstone project of the Data Science Specialization at Johns Hopkins University, I was tasked with creating a predictive text algorithm, similar to what you see when typing on a smartphone. When typing "I went to the", the keyboard presents three options for the most probable next word or phrase: 1) gym, 2) tanning salon, or 3) laundromat. In this presentation, I will answer the following questions: 1. How does NextWord work? 2. How well does NextWord perform? 3. How can I use NextWord? The skills needed to complete this capstone include data cleaning processes using regular expressions, exploratory data analysis, statistical inference, machine learning, natural language processing, and developing data products. NextWord was created using the Shiny Application in RStudio. How does NextWord work? ======================================================== First, a large corpus of text from US english-based tweets, news articles, and blog posts was read into R. The corpus was cleaned by removing punctuation, replacing contractions, removing emojis/emoticons, identifying internet slang (e.g., lol to "laughing out loud"), and removing profanity. Then, a series of summary tables were created to identify the most common words and n-grams in the corpus. Tne "n" in n-gram is the number of words in a phrase. For example, "I love you" is a common 3-gram. These summary tables were then used to create a series of prediction models using the [Katz Back-off (KBO) algorithm](https://en.wikipedia.org/wiki/Katz's_back-off_model) employing Good-Turing smoothing in order to most accurately capture how humans communicate using the english language. The KBO algorithm is a preferred method for prediction over other weighting [methods](https://web.stanford.edu/~jurafsky/slp3/3.pdf). In short, a user can feed NextWord some text, as little as a single word, and NextWord uses the prediction algorithm to predict the next most probable word. How well does NextWord perform? ======================================================== NextWord's corpus includes 211,644 words. Of these, 7,213 unique words comprise 90% of the entire corpus. The most common words are unsurprisingly, "the", "to", and "and", which comprise 4.7%, 2.8%, and 2.7% of the corpus, respectively. To assess NextWord's performance, I completed a series of out-of-sample validation tests on text excluded from NextWord's original corpus. NextWord will continue to be updated to improve prediction accuracy while maintaining high efficiency. How can I use NextWord? ======================================================== Try out NextWord for yourself! Click [here](https://ajohns34.shinyapps.io/DSS_Capstone/) to access the app! To learn more about the code used to generate this predictive algorithm and my other ongoing projects, please visit my github: <https://github.com/amandaleejohnson>. This project would not be possible without the partnership of Johns Hopkins University, Coursera, and SwiftKey. More information on SwiftKey can be found [here](https://www.microsoft.com/en-us/swiftkey?activetab=pivot_1:primaryr2). <file_sep># DSS Capstone - NextWord # This is the user-interface definition of a Shiny web application. You can # run the application by clicking 'Run App' above. # # Find out more about building applications with Shiny here: # # http://shiny.rstudio.com/ # suppressWarnings(library(shiny)) suppressWarnings(library(shinythemes)) suppressWarnings(library(datasets)) shinyUI(fluidPage( # define the theme used for the app theme = shinythemes::shinytheme("slate"), pageWithSidebar( headerPanel("Data Science Specialization Capstone Project - NextWord"), sidebarPanel( h4("Type at least one English word into the text box below and click Submit."), h4("To the right, you'll see a table of output."), h4("The column labeled PrecedingWords contains the word or phrase used to predict the next word."), h4("The column labeled NextWord contains the most probable next word."), textInput("Tcir", placeholder="Enter text here", label=h3("Type at least one English word here:")), submitButton("Submit") #Delays reaction until the user presses this button # h4('Predicted word :'), # verbatimTextOutput("prediction"), # textOutput("prediction") ), mainPanel( tabsetPanel( tabPanel('Output Table', dataTableOutput("mytable1")) ) ) ) )) <file_sep>#################################################### #DATA SCIENCE SPECIALIZATION######################## #CAPSTONE########################################### #PART 3############################################# #################################################### # load in libraries we'll need library(tidyverse) library(tidytext) #tidy text analysis library(glue) #pasting strings library(data.table) #for rbindlist, a faster version of rbind library(readr) library(stringr) library(tm) #Used to transform text to lowercase, remove punctuation, numbers, etc. library(sentimentr) #for identifying profanity words library(textclean) #Replace common non-ascii characters library(knitr) #for kable library(ggplot2) library(wordcloud) library(quanteda) gc() memory.limit(size = 15000) setwd("C:/Users/ajohns34/Desktop/Final Capstone Submission") load(file="C:/Users/ajohns34/Desktop/Final Capstone Submission/parts1thru3sofar.RData") rm(fourgram_freq_by_rank, fourgramcount.1to5, trigram_freq_by_rank, trigramcount.1to5, fourgram_trigram_prefix, hist.gr, bigram_freq_by_rank, trigram_bigram_prefix, bigramcount.1to5, bigramcount.2pl, trigramcount.2pl, word1_bigram, fourgramcount.2pl, trigramcount.6pl, bigramcount.6pl, freq_by_rank_subsample, wordcount.1to5, fourgramcount.6pl, wordcount.2pl, wordcount.6pl, word_freqoffreq, bigram_freqoffreq, trigram_freqoffreq, fourgram_freqoffreq, gts_matrix, remove_reg) #Subset the biggest dfs with only necessary columns: wordcount=subset(wordcount, select=c(word, n, GTfreq, GTprob, prefix)) bigramcount = subset(bigramcount, select=c(word1, word2, n, GTfreq, GTprob)) trigramcount = subset(trigramcount, select=c(bigram_prefix, word1, word2, word3, n, GTfreq, GTprob)) fourgramcount = subset(fourgramcount, select=c(trigram_prefix, word1, word2, word3, word4, n, GTfreq, GTprob)) ##Due to memory limitations in ShinyApp, we need to dramatically reduce the #size of each df wordcount = wordcount[order(-wordcount$n), ] bigramcount = bigramcount[order(-bigramcount$n), ] trigramcount = trigramcount[order(-trigramcount$n), ] fourgramcount = fourgramcount[order(-fourgramcount$n), ] wordcount = head(wordcount, 100000) bigramcount = head(bigramcount, 100000) trigramcount = head(trigramcount, 100000) fourgramcount = head(fourgramcount, 100000) #Step 5. Run the model! #Step 5a. Define a function to clean the inputted phrase clean_inputphrase = function(input) { # 1. Make all text lowercase input = tolower(input) # 2. Remove punctuation from phrase input = gsub("[^[:alnum:][:space:]\']", "",input) input <- gsub("“", "", input) input <- gsub("”", "", input) input <- gsub("‘", "", input) input <- gsub("’", "", input) # 3. Separate words connected with "-" or "/" in the phrase input = gsub("-", " ", input) input = gsub("/", " ", input) # 4. Identify the end of the phrase input = gsub("\\? |\\?$|\\! |\\!$", " EEOSS ", input) input = gsub("[A-Za-z]\\.[A-Za-z]\\.[A-Za-z]\\.[A-Za-z]\\. |[A-Za-z]\\.[A-Za-z]\\.[A-Za-z]\\. |[A-Za-z]\\.[A-Za-z]\\. ", " AABRR ", input) input = gsub("\\. |\\.$", " EEOSS ", input) input = gsub("[0-9]+"," NNUMM ",input) input = gsub("\\S+@\\S+","EEMAILL",input) input = gsub("[Hh}ttp([^ ]+)","HHTMLL",input) input = gsub("RT | via"," RTVIA ",input) # retweets input = gsub("@([^ ]+)","ATPPLE",input) # @people input = gsub("[@][a - zA - Z0 - 9_]{1,15}","UUSRNMSS",input) # usernames # 5. Replace any contractions - "n't" = "not" #Remove/replace &, @, 'm, 's, 'are, 'll, input = replace_contraction(input) #The list of contractions in replace_contractions is not complete - add these in just in case input = gsub("it's", "it is", input) input = gsub("haven't", "have not", input) input = gsub("hadn't", "had not", input) input = gsub("n't" , "not", input) input = gsub("'ve", "have", input) input = gsub("'d", "would", input) input = gsub("'ll", "will", input) input = gsub("'re", "are", input) input = gsub(" & ", " and ", input) #Make & = "and" input = gsub(" @ ", " at ", input) #Make @ = "at" # 6. Remove emoji's, emoticons from the phrase - usually a problem in Twitter input = gsub("[^\x01-\x7F]", "", input) # 7. Remove measurements of mass and time (e.g., g, mg, lbs) input = gsub(" [1-9]+g ", " ", input) #grams input = gsub(" +g ", " ", input) #grams input = gsub(" [1-9]+mg ", " ", input) #miligrams input = gsub(" +mg ", " ", input) #miligrams input = gsub(" [1-9]+kg ", " ", input) #kilograms input = gsub(" +kg ", " ", input) #kilograms input = gsub(" +kg ", " ", input) #kilograms input = gsub(" [1-9]+lbs ", " ", input) #pounds input = gsub(" +lbs ", " ", input) #pounds input = gsub(" +lbs ", " ", input) #pounds input = gsub(" [1-9]+s ", " ", input) #seconds input = gsub(" +s ", " ", input) #seconds input = gsub(" [1-9]+m ", " ", input) #minutes input = gsub(" +m ", " ", input) #minutes input = gsub(" [1-9]+h ", " ", input) #hours input = gsub(" +h ", " ", input) #hours # 8. Remove all single letters except i, b, c, u, and a input = gsub(" b ", " be ", input) input = gsub(" c ", " see ", input) input = gsub(" u ", " you ", input) input = gsub(" [b-hj-z] ", " ", input) #Replace any common internet slang: input = gsub(" jk ", " just kidding ", input) input = gsub(" lol ", " laughing out loud ", input) input = gsub(" rofl ", " rolling on floor laughing ", input) input = gsub(" stfu ", " shut the fuck up ", input) input = gsub(" lmk ", " let me know ", input) input = gsub(" ily ", " i love you ", input) input = gsub(" ilysm ", " i love you so much ", input) input = gsub(" yolo ", " you only live once ", input) input = gsub(" smh ", " shaking my head ", input) input = gsub(" lmfao ", " laughing my fucking head off ", input) input = gsub(" nvm ", " never mind ", input) input = gsub(" ikr ", " i know right ", input) input = gsub(" bae ", " before anyone else ", input) input = gsub(" lmk", "let me know", input) # 9. Exclude list of profane words/phrases #Source of profane word list: https://www.cs.cmu.edu/~biglou/resources/ profane_words = read.delim("./profane_words.txt", header = FALSE, sep="\n") #sep is signaling "new line" input = removeWords(input, profane_words[,1]) # 10. Remove extra spaces in phrase input = stripWhitespace(input) # Remove space at beginning of phrase input = gsub("^ ", "", input ) # Remove space at end of phrase input = gsub(" $", "", input) return(input) } #Step 5b. Define 4 functions to run KBO from words, bigrams, trigrams, and fourgrams #Word predict.onegram = function(wordcount, gram2.w1) { #Get a subset where prefix matches gram2.w1 prefix.gram1.match = wordcount[which(wordcount["word"]==gram2.w1), ] #Calculate Katzprob for gram 1: prefix.gram1.match$Kprob = prefix.gram1.match$GTprob #Rename variables names(prefix.gram1.match) = c("postfix", "n", "GTfreq", "GTprob", "prefix", "Kprob") prediction = prefix.gram1.match prediction = prediction[order(-prediction$Kprob), ] return(prediction) } #Bigram predict.bigram = function(bigramcount, wordcount, gram2.w1) { #Get a subset where prefix matches gram2.w1 prefix.gram2.match = bigramcount[which(bigramcount$word1==gram2.w1), ] #Subset gram1 into words predicted by gram2 or not predicted gr1.in.gr2 = wordcount[wordcount$word %in% prefix.gram2.match$word2, ] gr1.notin.gr2 = wordcount[!(wordcount$word %in% prefix.gram2.match$word2), ] #Calculate alpha for gram 1 (call gama the denominator of alpha) beta.gr1 = 1-sum(prefix.gram2.match$GTprob) gama.gr1 = 1-sum(gr1.in.gr2$GTprob) alpha.gr1 = beta.gr1/gama.gr1 #Calculate KatzProb for gram 1 gr1.notin.gr2$Kprob = gr1.notin.gr2$GTprob*alpha.gr1 names(gr1.notin.gr2) = c("postfix", "n", "GTfreq", "GTprob", "prefix", "Kprob") #Calculate KatzProb for gram 2 prefix.gram2.match$Kprob = prefix.gram2.match$GTprob names(prefix.gram2.match) #Drop some variables and rename so that they match with gr1.notin.gr2 prefix.gram2.match = prefix.gram2.match[, c("word1", "word2", "n", "GTfreq", "GTprob", "Kprob")] prefix.gram2.match = prefix.gram2.match[, c(2, 3, 4, 5, 1, 6)] names(prefix.gram2.match) = c("postfix", "n", "GTfreq", "GTprob", "prefix", "Kprob") #Bind the rows of the gr1 and gr matches prediction = rbind(prefix.gram2.match, gr1.notin.gr2) prediction = prediction[order(-prediction$Kprob), ] return(prediction) } #Trigram predict.trigram = function(trigramcount, bigramcount, wordcount, gram3.w12, gram2.w1) { #Gram 3 match and backoff to gram 2 #Subset from gram 3 where prefix matches gram3.w12 prefix.gram3.match = trigramcount[which(trigramcount$bigram_prefix==gram3.w12), ] #Subset from gram 2 where prefix matches gram2.w1 prefix.gram2.match = bigramcount[which(bigramcount$word1==gram2.w1), ] #Subset from gram 2 into words predicted by gram 3 or not predicted: gr2.in.gr3 = prefix.gram2.match[prefix.gram2.match$word2 %in% prefix.gram3.match$word3, ] gr2.notin.gr3 = prefix.gram2.match[!(prefix.gram2.match$word2 %in% prefix.gram3.match$word3), ] #Calculate alpha for gram 2 (call gama the denominator of alpha) beta.gr2 = 1 - sum(prefix.gram3.match$GTprob) gama.gr2 = 1 - sum(gr2.in.gr3$GTprob) alpha.gr2 = beta.gr2/gama.gr2 #Calculate KatzProb (Kprob) for gram 2 gr2.notin.gr3$Kprob = gr2.notin.gr3$GTprob *alpha.gr2 names(gr2.notin.gr3) gr2.notin.gr3 = gr2.notin.gr3[, c("word1", "word2", "n", "GTfreq", "GTprob", "Kprob")] gr2.notin.gr3 = gr2.notin.gr3[, c(2, 3, 4, 5, 1, 6)] names(gr2.notin.gr3) = c("postfix", "n", "GTfreq", "GTprob", "prefix", "Kprob") #Calculate KatzProb for gram 3 prefix.gram3.match$Kprob = prefix.gram3.match$GTprob names(prefix.gram3.match) prefix.gram3.match = prefix.gram3.match[, c("bigram_prefix", "word3", "n", "GTfreq", "GTprob", "Kprob")] names(prefix.gram3.match) = c("prefix", "postfix", "n", "GTfreq", "GTprob", "Kprob") prefix.gram3.match = prefix.gram3.match[, c(2, 3, 4, 5, 1, 6)] #If no matches, backoff to gram 1 #Subset gram1 into words predicted by gram2 or not predicted gr1.in.gr2 = wordcount[wordcount$word %in% prefix.gram2.match$word2, ] gr1.notin.gr2 = wordcount[!(wordcount$word %in% prefix.gram2.match$word2), ] #Calculate alpha for gram 1 (call gama the denominator of alpha) beta.gr1 = 1-sum(prefix.gram2.match$GTprob) gama.gr1 = 1-sum(gr1.in.gr2$GTprob) alpha.gr1 = beta.gr1/gama.gr1 #Calculate KatzProb for gram 1 gr1.notin.gr2$Kprob = gr1.notin.gr2$GTprob * alpha.gr1 * alpha.gr2 names(gr1.notin.gr2) = c("postfix", "n", "GTfreq", "GTprob", "prefix", "Kprob") #Bind the rows for gr1 and gr matches and then sort prediction = rbind(prefix.gram3.match, gr2.notin.gr3, gr1.notin.gr2) prediction = prediction[order(-prediction$Kprob), ] return(prediction) } #Fourgram predict.fourgram = function(fourgramcount, trigramcount, bigramcount, wordcount, gram4.w123, gram3.w12, gram2.w1) { #Gram 4 match and backoff to gram 1: #Subset from gram 4 where prefix matches gram4.w123 prefix.gram4.match = fourgramcount[which(fourgramcount$trigram_prefix==gram4.w123), ] #Subset from gram 3 where prefix matches gram3.w12 prefix.gram3.match = trigramcount[which(trigramcount$bigram_prefix==gram3.w12), ] #Subset from gram 3 into words predicted by gram 4 or not predicted gr3.in.gr4 = prefix.gram3.match[prefix.gram3.match$postfix %in% prefix.gram4.match$postfix, ] gr3.notin.gr4 = prefix.gram3.match[!(prefix.gram3.match$postfix %in% prefix.gram4.match$postfix), ] #Calculate alpha for gram 2 (call gama the denominator of alpha) beta.gr3 = 1-sum(prefix.gram4.match$GTprob) gama.gr3 = 1-sum(gr3.in.gr4$GTprob) alpha.gr3 = beta.gr3/gama.gr3 #Calculate KatzProb (Kprob) for gram 3 gr3.notin.gr4$Kprob = gr3.notin.gr4$GTprob * alpha.gr3 gr3.notin.gr4 = gr3.notin.gr4[, c("bigram_prefix", "word3", "n", "GTfreq", "GTprob", "Kprob")] names(gr3.notin.gr4) = c("prefix", "postfix", "n", "GTfreq", "GTprob", "Kprob") gr3.notin.gr4 = gr3.notin.gr4[, c(2, 3, 4, 5, 1, 6)] #Calculate KatzProb (Kprob) for gram 4 prefix.gram4.match$Kprob = prefix.gram4.match$GTprob prefix.gram4.match = prefix.gram4.match[, c("trigram_prefix", "word4", "n", "GTfreq", "GTprob", "Kprob")] names(prefix.gram4.match) = c("prefix", "postfix", "n", "GTfreq", "GTprob", "Kprob") prefix.gram4.match = prefix.gram4.match[, c(2, 3, 4, 5, 1, 6)] #Gram 3 match and backoff to gram 2 #Subset from gram 3 where prefix matches gram3.w12 prefix.gram3.match = trigramcount[which(trigramcount$bigram_prefix==gram3.w12), ] #Subset from gram 2 where prefix matches gram2.w1 prefix.gram2.match = bigramcount[which(bigramcount$word1==gram2.w1), ] #Subset from gram 2 into words predicted by gram 3 or not predicted: gr2.in.gr3 = prefix.gram2.match[prefix.gram2.match$word2 %in% prefix.gram3.match$word3, ] gr2.notin.gr3 = prefix.gram2.match[!(prefix.gram2.match$word2 %in% prefix.gram3.match$word3), ] #Calculate alpha for gram 2 (call gama the denominator of alpha) beta.gr2 = 1 - sum(prefix.gram3.match$GTprob) gama.gr2 = 1 - sum(gr2.in.gr3$GTprob) alpha.gr2 = beta.gr2/gama.gr2 #Calculate KatzProb (Kprob) for gram 2 gr2.notin.gr3$Kprob = gr2.notin.gr3$GTprob * alpha.gr2 * alpha.gr3 names(gr2.notin.gr3) gr2.notin.gr3 = gr2.notin.gr3[, c("word1", "word2", "n", "GTfreq", "GTprob", "Kprob")] gr2.notin.gr3 = gr2.notin.gr3[, c(2, 3, 4, 5, 1, 6)] names(gr2.notin.gr3) = c("postfix", "n", "GTfreq", "GTprob", "prefix", "Kprob") #If no matches, backoff to gram 1 #Subset gram1 into words predicted by gram2 or not predicted gr1.in.gr2 = wordcount[wordcount$word %in% prefix.gram2.match$word2, ] gr1.notin.gr2 = wordcount[!(wordcount$word %in% prefix.gram2.match$word2), ] #Calculate alpha for gram 1 (call gama the denominator of alpha) beta.gr1 = 1-sum(prefix.gram2.match$GTprob) gama.gr1 = 1-sum(gr1.in.gr2$GTprob) alpha.gr1 = beta.gr1/gama.gr1 #Calculate KatzProb for gram 1 gr1.notin.gr2$Kprob = gr1.notin.gr2$GTprob * alpha.gr1 * alpha.gr2 * alpha.gr3 names(gr1.notin.gr2) = c("postfix", "n", "GTfreq", "GTprob", "prefix", "Kprob") #Bind the rows for gr1 and gr matches and then sort prediction = rbind(prefix.gram4.match, gr3.notin.gr4, gr2.notin.gr3, gr1.notin.gr2) prediction = prediction[order(-prediction$Kprob), ] return(prediction) } #Step 5c. Define the main function that takes a phrase, runs Step 5a, runs Step 5b, #and then outputs a table with the predicted next word(s) nextword = function(input, wordcount, bigramcount, trigramcount, fourgramcount) { #Identify the number of words in the input: n.words.input = length(strsplit(input, "\\s+")[[1]]) #Output an error message if input wasn't provided: #if(n.words.input < 1) stop("At least one word is necessary") #Clean the input phrase and count the number of words after cleaning: clean.input = clean_inputphrase(input) #This is using the function defined in 5a. clean.input.words = strsplit(clean.input, "\\s+")[[1]] n.words = length(clean.input.words) #Once the input is cleaned, re-run to identify the number of words in the input: n.words.input = length(strsplit(clean.input, "\\s+")[[1]]) #Output an error message if input wasn't provided: #if(n.words.input < 1) stop("At least one word is necessary. The algorithm may have filtered out words it identifies as profane.") #Identify break words: ngram.break = as.list(c("eeoss", "aabrr", "nnumm", "eemaill", "hhtmll", "rtvia", "atpple", "uusrnmss")) #If the last word is a break word, or something that isn't english, stop the function #if (any(unlist(lapply(ngram.break, function(x) grepl(x, clean.input.words[n.words]))))) #stop("The last sequence of characters is something other than an English word. \n", #"Please input at least one word.") #"\n" reports a new line. #If the phrase is at least three words long: if (n.words >=3) { #Extract the (n-1) words from ngrams from the last words in the phrase gram4.w123 = paste(clean.input.words[n.words - 2], clean.input.words[n.words - 1], clean.input.words[n.words], sep = " ") gram3.w12 = sub("^[a-z]+ ","",gram4.w123) #Trying this out: gram2.w1 = word(gram3.w12, 2) #Original: gram2.w1 = sub("^[a-z]+ ","",gram3.w12) #gram1.w0 = sub("^[a-z]+ ","",gram3.w12) #If any of the words in the ngram4.w123 is a break word, then move to n-1 ngram if (any(unlist(lapply(ngram.break, function(x) grepl(x,gram4.w123))))) { # if any of the words in the ngram3.w12 is a break word, then move to n-1 ngram if (any(unlist(lapply(ngram.break, function(x) grepl(x,gram3.w12))))) { ###Count the frequency of bigramcount$word1 match.w1.count = sum(bigramcount[which(bigramcount$word1==gram2.w1),"GTfreq"]) #If the user only inputted 1 word and there are no matches, output just the sorted wordcount table if (match.w1.count == 0) { prediction = subset(wordcount, select=c(word, prefix)) #prediction = subset(predict.onegram(gram2.w1), select=c(postfix, prefix)) names(prediction) = c("NextWord", "PrecedingWords") prediction = prediction[, c(2, 1)] #prediction = predict.onegram(gram1.w0) #stop("This word is outside of our prediction capabilities. Please input another word.") } #If there IS a match, use the bigram prediction model else { prediction = subset(predict.bigram(bigramcount, wordcount, gram2.w1), select=c(postfix, prefix)) names(prediction) = c("NextWord", "PrecedingWords") prediction = prediction[, c(2, 1)] } } #If all of the words ARE NOT break words, execute from the 3-gram: else { match.w12.count = sum(trigramcount[which(trigramcount$bigram_prefix==gram3.w12),"GTfreq"]) #If no matches, use Katz backoff model to report the word from gram2.w1 if (match.w12.count == 0) { match.w1.count = sum(bigramcount[which(bigramcount$word1==gram2.w1),"GTfreq"]) #If the user only inputted 1 word and there are no matches, output just the sorted wordcount table if (match.w1.count == 0) { prediction = subset(wordcount, select=c(word, prefix)) #prediction = subset(predict.onegram(gram2.w1), select=c(postfix, prefix)) names(prediction) = c("NextWord", "PrecedingWords") prediction = prediction[, c(2, 1)] #prediction = predict.onegram(gram1.w0) #stop("This word is outside of our prediction capabilities. Please input another word.") } #If there IS a match, use the bigram prediction model else { prediction = subset(predict.bigram(bigramcount, wordcount, gram2.w1), select=c(postfix, prefix)) names(prediction) = c("NextWord", "PrecedingWords") prediction = prediction[, c(2, 1)] } } #If there IS a match, use the trigram prediction model else { prediction = subset(predict.trigram(trigramcount, bigramcount, wordcount, gram3.w12, gram2.w1), select=c(postfix, prefix)) names(prediction) = c("NextWord", "PrecedingWords") prediction = prediction[, c(2, 1)] } } #If all of the words ARE NOT break words, execute from the 4-gram: } else { #Check for matches in the fourgram list and then work backwards using the Katz back-off model as necessary # Count the frequency of fourgramcount$trigramcount_prefix when it equals gram4.w123 match.w123.count = sum(fourgramcount[which(fourgramcount$trigram_prefix==gram4.w123),"GTfreq"]) #If no matches, use Katz backoff model to find the frequency of trigram$bigram_prefix when #it equals gram3.w12 if (match.w123.count == 0) { match.w12.count = sum(trigramcount[which(trigramcount$bigram_prefix==gram3.w12),"GTfreq"]) #If no matches, use Katz backoff model to find the frequency of bigram$word1 when #it equals gram2.w1 if (match.w12.count == 0) { match.w1.count = sum(bigramcount[which(bigramcount$word1==gram2.w1),"GTfreq"]) #If the user only inputted 1 word and there are no matches, output just the sorted wordcount table if (match.w1.count == 0) { prediction = subset(wordcount, select=c(word, prefix)) #prediction = subset(predict.onegram(gram2.w1), select=c(postfix, prefix)) names(prediction) = c("NextWord", "PrecedingWords") prediction = prediction[, c(2, 1)] #prediction = predict.onegram(gram1.w0) #stop("This word is outside of our prediction capabilities. Please input another word.") } #If there IS a match, use the bigram prediction model else { prediction = subset(predict.bigram(bigramcount, wordcount, gram2.w1), select=c(postfix, prefix)) names(prediction) = c("NextWord", "PrecedingWords") prediction = prediction[, c(2, 1)] } } #If there IS a match, use the trigram prediction model else { prediction = subset(predict.trigram(trigramcount,bigramcount, wordcount, gram3.w12, gram2.w1), select=c(postfix, prefix)) names(prediction) = c("NextWord", "PrecedingWords") prediction = prediction[, c(2, 1)] } } #If there IS a match, use the fourgram prediction model else { prediction = subset(predict.fourgram(fourgramcount, trigramcount, bigramcount, wordcount, gram4.w123, gram3.w12, gram2.w1), select=c(postfix, prefix)) names(prediction) = c("NextWord", "PrecedingWords") prediction = prediction[, c(2, 1)] } } } #If the phrase is two words long: else if (n.words ==2) { #Extract the (n-1) words from ngrams from the last words in the phrase gram3.w12 = clean.input #Trying this out: gram2.w1 = word(gram3.w12, 2) #Original: gram2.w1 = sub("^[a-z]+ ","",gram3.w12) #gram1.w0 = sub("^[a-z]+ ","",gram3.w12) #If any of the words in the ngram3.w12 is a break word, then move to n-1 ngram if (any(unlist(lapply(ngram.break, function(x) grepl(x,gram3.w12))))) { #Check for matches in the trigram list and then work backwards using the Katz back-off model as necessary match.w1.count = sum(bigramcount[which(bigramcount$word1==gram2.w1),"GTfreq"]) #If the user only inputted 1 word and there are no matches, output just the sorted wordcount table if (match.w1.count == 0) { prediction = subset(wordcount, select=c(word, prefix)) #prediction = subset(predict.onegram(gram2.w1), select=c(postfix, prefix)) names(prediction) = c("NextWord", "PrecedingWords") prediction = prediction[, c(2, 1)] #prediction = predict.onegram(gram1.w0) #stop("This word is outside of our prediction capabilities. Please input another word.") } #If there IS a match, run the bigram prediction model else { prediction = subset(predict.bigram(bigramcount, wordcount, gram2.w1), select=c(postfix, prefix)) names(prediction) = c("NextWord", "PrecedingWords") prediction = prediction[, c(2, 1)] } } #If there are NO break words, find the frequency of trigramcount$bigram_prefix when it equals gram3.w12 else { match.w12.count = sum(trigramcount[which(trigramcount$bigram_prefix==gram3.w12),"GTfreq"]) #If there are no matches, find the frequency of bigramcount$word1 when it equals gram2.w1 if (match.w12.count == 0) { match.w1.count = sum(bigramcount[which(bigramcount$word1==gram2.w1),"GTfreq"]) #If there are no matches, report the gram2.w1 if (match.w1.count == 0) { #prediction = subset(predict.onegram(gram2.w1), select=c(postfix, prefix)) prediction = subset(wordcount, select=c(word, prefix)) names(prediction) = c("NextWord", "PrecedingWords") prediction = prediction[, c(2, 1)] #prediction = predict.onegram(gram1.w0) #stop("This word is outside of our prediction capabilities. Please input another word.") } #If there IS a match, run the bigram prediction model else { prediction = subset(predict.bigram(bigramcount, wordcount, gram2.w1), select=c(postfix, prefix)) names(prediction) = c("NextWord", "PrecedingWords") prediction = prediction[, c(2, 1)] } } #If there IS a match, run the trigram prediction model else { prediction = subset(predict.trigram(trigramcount,bigramcount, wordcount, gram3.w12, gram2.w1), select=c(postfix, prefix)) names(prediction) = c("NextWord", "PrecedingWords") prediction = prediction[, c(2, 1)] } } } #If the phrase is one word long: else { gram2.w1 = clean.input #Count the frequency of bigramcount$word1 when it equals gram2.w1 match.w1.count = sum(bigramcount[which(bigramcount$word1==gram2.w1),"GTfreq"]) #If the user only inputted 1 word and there are no matches, output just the sorted wordcount table if (match.w1.count == 0) { prediction = subset(wordcount, select=c(word, prefix)) #prediction = subset(predict.onegram(gram2.w1), select=c(postfix, prefix)) names(prediction) = c("NextWord", "PrecedingWords") prediction = prediction[, c(2, 1)] } #If there IS a match, use the bigram prediction model else { prediction = subset(predict.bigram(bigramcount, wordcount, gram2.w1), select=c(postfix, prefix)) names(prediction) = c("NextWord", "PrecedingWords") prediction = prediction[, c(2, 1)] } } return(prediction) } #Save the model: #save.image(file = "C:/Users/ajohns34/Desktop/Final Capstone Submission/NextWord_112719.RData") #Save on Desktop for now, not enough space in Box #load(file="C:/Users/ajohns34/Desktop/Final Capstone Submission/NextWord_112719.RData") save.image(file = "C:/Users/ajohns34/Desktop/Final Capstone Submission/NextWord_112919.RData") #Save on Desktop for now, not enough space in Box load(file="C:/Users/ajohns34/Desktop/Final Capstone Submission/NextWord_112919.RData") <file_sep>#################################################### #DATA SCIENCE SPECIALIZATION######################## #CAPSTONE########################################### #PART 1############################################# #################################################### #HELPFUL SOURCE: https://www.tidytextmining.com/ setwd("C:/Users/ajohns34/Box/Data Science Specialization/Capstone/data/en_US") # load in libraries we'll need library(tidyverse) library(tidytext) #tidy text analysis library(glue) #pasting strings library(data.table) #for rbindlist, a faster version of rbind library(readr) library(stringr) library(tm) #Used to transform text to lowercase, remove punctuation, numbers, etc. library(sentimentr) #for identifying profanity words library(textclean) #Replace common non-ascii characters library(knitr) #for kable library(ggplot2) library(wordcloud) library(quanteda) #Read in the english data files with a for loop: for (i in c("twitter", "blogs", "news")) { #Since the for loop doesn't know how to read in the value of i #in a name, use the paste0 function: filename = paste0("en_US.", i, ".txt") print(paste0("File info of ", filename, " below:")) print(file.info(paste0("./", filename))) #Read in the text file, suppressing warning messages: assign(i, suppressWarnings(readLines(filename))) #Transform the data into a tidy data frame using tibble #Create two columns: 1 "line" and 2 "text" length = length(suppressWarnings(readLines(filename))) print(paste0("Total number of lines of ", i, " file = ", length)) assign(paste0(i, "_df"), tibble(line = 1:length, text = assign(i, suppressWarnings(readLines(filename))))) } #Remove words with non-ASCII characters length(twitter) nonenglish = grep("twitter", iconv(twitter, "latin1", "ASCII", sub="twitter")) twitter = twitter[-nonenglish] length(twitter) tenth_twitter = length(twitter)/10 length(blogs) nonenglish = grep("blogs", iconv(blogs, "latin1", "ASCII", sub="blogs")) blogs = blogs[-nonenglish] length(blogs) half_blogs = length(blogs)/2 length(news) nonenglish = grep("news", iconv(news, "latin1", "ASCII", sub="news")) news = news[-nonenglish] length(news) most_news = length(news)*0.8 #Create a random sample of text across all three sources: twitter, blogs, news #in order to explore the data and train our prediction algorithm: twitter_sample = twitter[sample(1:length(twitter), tenth_twitter)] blogs_sample = blogs[sample(1:length(blogs), half_blogs)] news_sample = news[sample(1:length(news), most_news)] subsample = c(twitter_sample, blogs_sample, news_sample) #Save sample as a txt file to be easily loaded in later: writeLines(subsample, "./subsample.txt") subsample_df = tibble(line = 1:length(subsample), text = assign(subsample, suppressWarnings(readLines("./subsample.txt")))) #An important alternative to Corpus object has emerged in recent years in the form of tidytext. #Instead of saving a group of documents and associated meta data, text that is in tidytext format contains one word per row, #and each row also includes additional information about the name of the document where the word appears, and the order in which the words appear. #Remove unwanted characters, restructure the data so that each word is on a separate row, #and remove stop words: #Unwanted characters: remove_reg = "[0123456789!@#$%^*+=}{/><]" #Keep stop words in! subsample_df_word = subsample_df %>% mutate(text = str_remove_all(text, remove_reg)) %>% ##Remove unwanted characters like "&" unnest_tokens(word, text) ##Restructure the data so that each word is on a separate row #Use dplyr's count() to find the most common words subsample_words = subsample_df_word %>% count(word, sort = TRUE) #Calculate the total number of words: #THis might not work if you have multiple packages installed with a "summarize" command. #Therefore, you need to specify that we are using the "plyr" package: total_subsample_words = plyr::summarize(subsample_words, total = sum(n)) subsample_words = cbind(subsample_words, total_subsample_words) #Exclude list of profane words/phrases #Source of profane word list: https://www.cs.cmu.edu/~biglou/resources/ profane_words = read.delim("./profane_words.txt", header = FALSE, sep="\n") #sep is signaling "new line" #Rename the V1 column as "word" so that anti_join and inner_join work: profane_words = profane_words %>% rename(word = V1) #Since this is based on single word, we need to apply it to the word dataset #where each word is its own separate line: subsample_words_noprofane = anti_join(subsample_words, profane_words) subsample_words_profane = inner_join(subsample_words, profane_words) #Replace the subsample_words df with the subsample_words_noprofane: subsample_words = subsample_words_noprofane #Examine Zipf's law: #Zipf's law states that the frequency that a word appears is inversely proportional to its rank. freq_by_rank_subsample = subsample_words %>% mutate(rank = row_number(), `term frequency` = n/total) #Create a variable taht denotes cumulative count: freq_by_rank_subsample$`cum count` = cumsum(freq_by_rank_subsample$n) #Create a variable that denotes cumulative frequency: freq_by_rank_subsample$`cum freq` = cumsum(freq_by_rank_subsample$`term frequency`) #Create a variable that denotes the row number (this will be used later to find out how many words are 50% of the corpus) freq_by_rank_subsample$rownum = 1:dim(freq_by_rank_subsample)[1] #Create a frequency of frequency table that will be used later for Good-Turing Smoothing word_freqoffreq = data.frame(word=table(freq_by_rank_subsample$n)) #How many unique words do you need in order to cover 50% of all word instances in the language? 90%? #Step 1. Plot number of words vs. cumulative relative frequency in order display that coverage increases #with the addition of words. plot(freq_by_rank_subsample$rownum[1:50000], freq_by_rank_subsample$`rel cum freq`[1:50000], type="l", lty=1, ylab = "Percent of Coverage (Cumulative Relative Frequency)", xlab = "# Words (Starting with most common)") #How many words do we need to achieve 50% of coverage? head(freq_by_rank_subsample) paste("NUmber of words comprising 49.99-50.01% of the dictionary:", range(freq_by_rank_subsample$rownum[freq_by_rank_subsample$`cum freq`>0.4999 & freq_by_rank_subsample$`cum freq`<0.5001])[1], "to", range(freq_by_rank_subsample$rownum[freq_by_rank_subsample$`cum freq`>0.4999 & freq_by_rank_subsample$`cum freq`<0.5001])[2], "words.") paste("NUmber of words comprising 90.01-95.01% of the dictionary:", range(freq_by_rank_subsample$rownum[freq_by_rank_subsample$`cum freq`>0.9001 & freq_by_rank_subsample$`cum freq`<0.9501])[1], "to", range(freq_by_rank_subsample$rownum[freq_by_rank_subsample$`cum freq`>0.9001 & freq_by_rank_subsample$`cum freq`<0.9501])[2], "words.") ##Visualize the most common words: head(freq_by_rank_subsample, 5) ggplot(freq_by_rank_subsample[1:50,], aes(x = reorder(word, -n), y = n, fill = n)) + #reorder in aes orders the bars by frequency, not alphabetical geom_col() + geom_text(aes(label = n), vjust = -0.3, size = 3.5) + geom_text(aes(label = paste0(round((`term frequency`*100), 2), "%")), vjust = +1.3, size = 3, color = "white") + theme(axis.text.x = element_text(angle = 90)) + labs(title = "Most frequent words in sample (including stop words)", x = "Word", y = "N and Relative Frequency %") #Let's look at the distribution of n/total, #the number of times a word appears divided by the total number of terms (words). #This is exactly what term frequency is. ggplot(subsample_words, aes(n/total)) + geom_histogram(show.legend = FALSE) + xlim(NA, 0.0002) head(freq_by_rank_subsample, 5) tail(freq_by_rank_subsample, 5) #The rank column here tells us the rank of each word within the frequency table; #the table was already ordered by n so we could use row_number() to find the rank. #Then, we can calculate the term frequency in the same way we did before. #Zipf's law is often visualized by plotting rank on the x-axis and term frequency #on the y-axis, on logarithmic scales. Plotting this way, an inversely proportional #relationship will have a constant, negative slope. freq_by_rank_subsample %>% ggplot(aes(rank, `term frequency`)) + geom_line(size = 1.1, alpha = 0.8, show.legend = FALSE) + scale_x_log10() + scale_y_log10() #Ideally, this should be a 45 degree angle #NOTE - the figure above is in log-log coordinates. #Let's see if we can improve this slope. We can view this as a "broken power law" with three sections. #Let's see what the exponent of the power law is for the middle section of hte rank range. rank_subset_subsample = freq_by_rank_subsample %>% filter(rank < 1000, rank > 10) broken_power_model = lm(log10(`term frequency`) ~ log10(rank), data = rank_subset_subsample) summary(broken_power_model) pm_intercept = broken_power_model$coefficients[1] pm_slope = broken_power_model$coefficients[2] #Ideally, we want the slope close to -1. This is not the case here (around -0.5) #Let's plot this fited power law with the data to visualize it: freq_by_rank_subsample %>% ggplot(aes(rank, `term frequency`)) + geom_abline(intercept = pm_intercept, slope = pm_slope, color = "gray50", linetype = 2) + geom_line(size = 1.1, alpha = 0.8, show.legend = TRUE) + scale_x_log10() + scale_y_log10() #YIKES! # The deviations we see here at high rank are not uncommon for many kinds of language; # a corpus of language often contains fewer rare words than predicted by a single power law. # The deviations at low rank are more unusual. Jane Austen uses a lower percentage of the most common # words than many collections of language. This kind of analysis could be extended to compare authors, # or to compare any other collections of text; it can be implemented simply using tidy data principles. #3.3 The bind_tf_idf function #The idea of tf-idf is to find the important words for the content of each document by decreasing the weight for #commonly used words and increasing the weight for words that are not used very much in a collection or corpus #of documents, in this case, the group of Jane Austen's novels as a whole. Calculating tf-idf attempts to find #the words that are important (i.e., common) in a text, but not too common. Let's do that now. #The bind_tf_idf function in the tidytext package takes a tidy text dataset as input with one row per token (term), #per document. One column (word here) contains the terms/tokens, one column contains the documents (book in this case), #and the last necessary column contains the counts, how many times each document contains each term (n in this example). #We calculated a total for each book for our explorations in previous sections, but it is not necessary for the #bind_tf_idf function; the table only needs to contain all the words in each document. subsample_words$document = "document" subsample_words = subsample_words %>% bind_tf_idf(word, document, n) #The 2nd variable is necessary, but since all the words have the same #total, it's just filler and won't actually matter. #It would matter if we had used a dataset that had a categorical variable like "source" or "book" #Notice that idf and thus tf-idf are zero for these extremely common words. #In the example, These are all words that appear in all six of Jane Austen's novels, #so the idf term (which will then be the natural log of 1) is zero. #The inverse document frequency (and thus tf-idf) is very low (near zero) for words that occur in many of the documents in a collection; #this is how this approach decreases the weight for common words. The inverse document frequency will be a higher number for words that #occur in fewer of the documents in the collection. summary(subsample_words$tf) subsample_words %>% arrange(desc(idf)) #idf and tf_idf should be 0 for extremely common words subsample_words %>% arrange(idf) ### # Create the type to token ratio (TTR): # This demonstrates how rich/diverse the language is in a corpus. # The higher TTR the more unique words are used to achieve to number of tokens ### word_tokens = sum(freq_by_rank_subsample$n) word_types = dim(freq_by_rank_subsample)[1] word_ttr = word_types/word_tokens word_ttr = data.frame("Source" = "Corpus", "Tokens" = word_tokens, "Types" = word_types, "TTR" = word_ttr) #Remove dfs and objects no longer needed: rm(blogs, blogs_df, blogs_sample, broken_power_model, filename, half_blogs, length, most_news, news, news_df, news_sample, pm_intercept, pm_slope, rank_subset_subsample, tenth_twitter, total_subsample_words, twitter, twitter_df, twitter_sample) #Save the entire workspace as an RData file: save.image(file="part1.RData") <file_sep>#################################################### #DATA SCIENCE SPECIALIZATION######################## #CAPSTONE########################################### #PART 4############################################# #################################################### #Load in Part 3 load(file="C:/Users/ajohns34/Desktop/Final Capstone Submission/NextWord_112719.RData") <file_sep># # This is the server logic of a Shiny web application. You can run the # application by clicking 'Run App' above. # # Find out more about building applications with Shiny here: # # http://shiny.rstudio.com/ # library(shiny) #setwd("C:/Users/ajohns34/Desktop/Final Capstone Submission/Shiny App") #source("C:/Users/ajohns34/Desktop/Final Capstone Submission/FINAL Capstone - Part 4.R") source("FINAL Capstone - Part 4.R") shinyServer(function(input, output) { #Output a large table with the first 100 rows. # output$prediction = renderText({ # nextword(input$Tcir, wordcount, bigramcount, trigramcount, fourgramcount)[1, 2] # }) output$mytable1 = renderDataTable({ nextword(input$Tcir, wordcount, bigramcount, trigramcount, fourgramcount)[1:100, ] }) }) <file_sep>#################################################### #DATA SCIENCE SPECIALIZATION######################## #CAPSTONE########################################### #PART 2############################################# #################################################### #Set working directory setwd("C:/Users/ajohns34/Box/Data Science Specialization/Capstone/data/en_US") #Load in Part 1 into the R workspace: load(file="part1.RData") #Evaluate n-grams instead of words ngram_subsample = function(n_gram, numb) { n_gram = data.frame(subsample_df %>% mutate(text = str_remove_all(text, remove_reg)) %>% ##Remove unwanted characters like "&" unnest_tokens(ngram, text, token = "ngrams", n = numb)) ##Restructure the data so that each ngram is on a separate row return(n_gram) } bigram = ngram_subsample("bigram", 2) trigram = ngram_subsample("trigram", 3) fourgram = ngram_subsample("fourgram", 4) #As one might expect, a lot of the most common bigrams are pairs of common words, #such as "of the" and "to be": what are called "stop-words". #This is a useful time to use tidyr's separate(), which splits #a column into multiple based on a delimiter. This lets us separate it into two #columns, "word1" and "word2", at which point we can remove cases where either #is a stop-word. #In other analyses, we may want to work with the recombined words. #tidyr's unite() function is the inverse of separate(), and lets us recombine the columns into one. #Thus, "separate/filter/count/unite" let us find the most common bigrams not containing stop-words. ##Bi-grams## bigram_sep = bigram %>% separate(ngram, c("word1", "word2"), sep = " ") bigram_counts = bigram_sep %>% count(word1, word2, sort = TRUE) #Remove the "NA NA" row bigram_counts = na.omit(bigram_counts) #Create a new column that is the non-separated version of the bigram: bigram_counts$bigram = paste(bigram_counts$word1, bigram_counts$word2, sep=" ") #Calculate the total number of bigrams: total_subsample_bigrams = bigram_counts %>% plyr::summarize(total = sum(n)) bigram_counts = cbind(bigram_counts, total_subsample_bigrams) #Zipf's law states that the frequency that a bigram appears is inversely proportional to its rank. bigram_freq_by_rank = bigram_counts %>% mutate(rank = row_number(), `term frequency` = n/total) head(bigram_freq_by_rank, 5) tail(bigram_freq_by_rank, 5) #Create a variable that denotes cumulative count: bigram_freq_by_rank$`cum count` = cumsum(bigram_freq_by_rank$n) #Create a variable that denotes cumulative frequency: bigram_freq_by_rank$`cum freq` = cumsum(bigram_freq_by_rank$`term frequency`) #Create a variable that denotes the row number (this will be used later to find out how many words are 50% of the corpus) bigram_freq_by_rank$rownum = 1:dim(bigram_freq_by_rank)[1] #Create a frequency of frequency table that will be used later for Good-Turing Smoothing bigram_freqoffreq = data.frame(bi=table(bigram_freq_by_rank$n)) ##Tri-grams## trigram_sep = trigram %>% separate(ngram, c("word1", "word2", "word3"), sep = " ") trigram_counts = trigram_sep %>% count(word1, word2, word3, sort = TRUE) #Remove the "NA NA NA" row trigram_counts = na.omit(trigram_counts) #Create a new column that is the non-separated version of the trigram: trigram_counts$trigram = paste(trigram_counts$word1, trigram_counts$word2, trigram_counts$word3, sep=" ") #Create a new column that is the bigram prefix of the trigram (so word1 + word2): trigram_counts$bigram_prefix = paste(trigram_counts$word1, trigram_counts$word2, sep=" ") #Calculate the total number of trigrams: total_subsample_trigrams = trigram_counts %>% plyr::summarize(total = sum(n)) trigram_counts = cbind(trigram_counts, total_subsample_trigrams) #Zipf's law states that the frequency that a trigram appears is inversely proportional to its rank. trigram_freq_by_rank = trigram_counts %>% mutate(rank = row_number(), `term frequency` = n/total) head(trigram_freq_by_rank, 5) tail(trigram_freq_by_rank, 5) #Create a variable that denotes cumulative count: trigram_freq_by_rank$`cum count` = cumsum(trigram_freq_by_rank$n) #Create a variable that denotes cumulative frequency: trigram_freq_by_rank$`cum freq` = cumsum(trigram_freq_by_rank$`term frequency`) #Create a variable that denotes the row number (this will be used later to find out how many words are 50% of the corpus) trigram_freq_by_rank$rownum = 1:dim(trigram_freq_by_rank)[1] #Create a frequency of frequency table that will be used later for Good-Turing Smoothing trigram_freqoffreq = data.frame(tri=table(trigram_freq_by_rank$n)) ##Fourgrams## fourgram_sep = fourgram %>% separate(ngram, c("word1", "word2", "word3", "word4"), sep = " ") fourgram_counts = fourgram_sep %>% count(word1, word2, word3, word4, sort = TRUE) #Remove the "NA NA NA" row fourgram_counts = na.omit(fourgram_counts) #Create a new column that is the non-separated version of the fourgram: fourgram_counts$fourgram = paste(fourgram_counts$word1, fourgram_counts$word2, fourgram_counts$word3, fourgram_counts$word4, sep=" ") #Create a new column that is the trigram prefix of the trigram (so word1 + word2 + word3): fourgram_counts$trigram_prefix = paste(fourgram_counts$word1, fourgram_counts$word2, fourgram_counts$word3, sep=" ") #Calculate the total number of fourgrams: total_subsample_fourgrams = fourgram_counts %>% plyr::summarize(total = sum(n)) fourgram_counts = cbind(fourgram_counts, total_subsample_fourgrams) #Zipf's law states that the frequency that a fourgram appears is inversely proportional to its rank. fourgram_freq_by_rank = fourgram_counts %>% mutate(rank = row_number(), `term frequency` = n/total) #Create a variable taht denotes cumulative count: fourgram_freq_by_rank$`cum count` = cumsum(fourgram_freq_by_rank$n) #Create a variable that denotes cumulative frequency: fourgram_freq_by_rank$`cum freq` = cumsum(fourgram_freq_by_rank$`term frequency`) #Create a variable that denotes the row number (this will be used later to find out how many words are 50% of the corpus) fourgram_freq_by_rank$rownum = 1:dim(fourgram_freq_by_rank)[1] #Create a frequency of frequency table that will be used later for Good-Turing Smoothing fourgram_freqoffreq = data.frame(four=table(fourgram_freq_by_rank$n)) #Remove unnecessary objects in the environment: rm(bigram_filtered, trigram_filtered, fourgram_counts, trigram_counts, fourgram, trigram, fourgram_sep, trigram_sep, bigram, bigram_counts, bigram_sep, subsample_df_word, subsample_df, subsample, subsample_words, subsample_words_noprofane, profane_words, subsample_words_profane, nonenglish, ngram_subsample, word_ttr, total_subsample_bigrams, total_subsample_trigrams, total_subsample_fourgrams) #Save the entire workspace as an RData file: save.image(file="C:/Users/ajohns34/Desktop/parts1and2.RData") #Save it on desktop for now- not enough space in Box <file_sep>--- title: 'Data Science Specialization Capstone Project' author: "<NAME>" date: "`r format(Sys.time(), '%d %B, %Y')`" output: slidy_presentation: default ioslides_presentation: default subtitle: Nextword - A Swiftkey --- ## Background The associated Shiny app uses a corpus of English language text from Twitter, news sites, and blogs, provided by the Data Science Specializaion through Coursera. The Shiny app takes input text provided by the user and outputs the most probable next word using a series of prediction algorithms utilizinat three different n-grams (2-words, 3-words, and 4-words). ```{r, echo = FALSE} setwd("C:/Users/ajohns34/Box/Data Science Specialization") ``` ```{r, echo = TRUE} data(mtcars) covars = c("hp", "mpg", "disp", "wt") for (i in covars) { print(i) print(summary(mtcars[[i]])) #writeLines("\n") #writes empty line to separate outputs } ``` ## Varying Factors The user can modify each of the following factors by adjusting the associated slider: - Miles per gallon (min: 10, max: 35) - Displacement (min: 70, max: 500, in cu. in.) - Weight (min: 1, max: 6, in 1,000 lbs) The user can select to view each model specific to the number of cylinders on the vehicle (4, 6, or 8) be checking/unchecking each box below the sliders (e.g. "Show/Hide Model for 4-Cylinder Vehicles"). ## Plot and Predicted Outcome The plot displays a color-coded dot for each type of vehicle that corresponds to the user-specified MPG and associated horsepower, given the user-specified displacement and weight of the car. If any of the "show/hide" checkboxes are selected, the plot also displays the best fitting line from the linear regression model for the associated type of vehicle. The predicted horsepower for each type of vehicle are also displayed as text below the plot. ##Viewing the App in Action: The application can be viewed here: https://ajohns34.shinyapps.io/Course_Project/
8513e57b02b078181983a6aeac8431606b2e1e97
[ "Markdown", "R", "RMarkdown" ]
8
Markdown
amandaleejohnson/DSSCapstone
f812951c2029d437e614a7b05fcdf9a57ed2bfcf
9143af3fbecbdec154c89ec73b052e2251dbddb3
refs/heads/master
<file_sep> package best.solution; public interface Succulent extends Plant{ public abstract void storeWater(); } <file_sep> package imaginary.implementation2; public abstract class MythologicalBeing { private String cultureOfOrigin; public String getCultureOfOrigin() { return cultureOfOrigin; } public void setCultureOfOrigin(String cultureOfOrigin) { this.cultureOfOrigin = cultureOfOrigin; } }
9675ba9992459c55ded844779bd275773f4f6b55
[ "Java" ]
2
Java
jenna-dercole/Class5Homework
d90e747e42845c852acf9958b1707fd36a63c217
830cc2489c5515f7ca3fa6fa9657d4867ede6db7
refs/heads/master
<repo_name>tomkennedy513/Twenty20<file_sep>/src/app/Home/home.component.ts import {Component} from '@angular/core'; import {DiscountPipe} from "../discount.pipe"; @Component({ selector: 'home', template: ` <div id="heading" className="container-fluid"> <h1>Twenty20.</h1> </div> <discount-calculator (add)='onAdd($event)'></discount-calculator> <cart [items]="itemList" [totalValue]="total" (delete)='onDelete($event)' ></cart>` }) export class HomeComponent { newItem: number; total :number = 0; itemList:Array<number> = []; onAdd(message:number):void { this.newItem= message; this.itemList.push(this.newItem); this.total += this.newItem; } onDelete(index:number) :void{ var test = new DiscountPipe().transform(this.itemList[index].toString()); console.log(test); this.total -= this.itemList[index]; this.itemList.splice(index,1); } } <file_sep>/src/app/app.module.ts import {NgModule} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; import {FormsModule} from '@angular/forms'; import {HttpModule, JsonpModule} from '@angular/http'; import {AppComponent} from './app.component'; import {routing, appRoutingProviders} from './app.routing'; import {DiscountCalculatorComponent} from './DiscountCalculator/discount-calculator.component'; import {CartComponent} from "./Cart/cart.component"; import {DiscountPipe} from "./discount.pipe"; import {HomeComponent} from "./Home/home.component"; import MaskedInput from 'angular2-text-mask' @NgModule({ declarations: [ AppComponent, DiscountCalculatorComponent, CartComponent, DiscountPipe, HomeComponent, MaskedInput ], imports: [ BrowserModule, FormsModule, HttpModule, JsonpModule, routing ], providers: [appRoutingProviders], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>/src/app/Cart/cart.component.ts import {Component, Input,EventEmitter,Output } from '@angular/core'; @Component({ selector: 'cart', template: require('./cart.component.html') }) export class CartComponent{ @Input() items: number[]; @Input() totalValue: number; @Output() deleteItem: EventEmitter<number> = new EventEmitter<number>(); doneClicked(index:any) { this.deleteItem.emit(index) } } <file_sep>/src/app/DiscountCalculator/discount-calculator.component.ts import {Component, Output, EventEmitter} from '@angular/core'; import {DiscountPipe} from "../discount.pipe"; import createNumberMask from 'text-mask-addons/dist/createNumberMask'; @Component({ selector: 'discount-calculator', template: require('./discount-calculator.component.html'), providers: [DiscountPipe] }) export class DiscountCalculatorComponent { discountModel : any; discountedPrice: any; public mask: Array<string | RegExp>; onClick($event: any){ this.discountedPrice = new DiscountPipe().transform(this.discountModel); var roundedPrice = Math.round(this.discountedPrice * 100) / 100; this.add.emit(roundedPrice); this.discountModel = null; } @Output() add: EventEmitter<number> = new EventEmitter<number>(); constructor(){ this.mask = createNumberMask({ allowDecimal: true }) } } <file_sep>/src/app/discount.pipe.ts import { Pipe, PipeTransform } from '@angular/core'; @Pipe({name: 'Discount'}) export class DiscountPipe implements PipeTransform { transform(value: string): number { if (value != null) { value = value.replace(/\$|,/g, ''); var numberValue = parseFloat(value); var afterTax: number = numberValue * 1.0465; return (afterTax * .8) * .8; } else{ return 0; } } }
2641f8bc391acafa019a9daaad4d9a9543e2592c
[ "TypeScript" ]
5
TypeScript
tomkennedy513/Twenty20
cc73cb38896bcb32956476c134a936e54917c885
18e940cfbb577129fc60cd239b69d1c27b18df6f
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MudClient { public class ProtocolText : Protocol { public override bool HandleChar(byte c) { switch (c) { case 7: // BELL break; case 8: // Backspace state.Backspace(); break; case 9: // horizontal tab state.MoveCursorBy(8 - (state.CursorX % 8)); break; case 10: // line feed state.MoveCursorBy(-state.CursorX); break; case 11: // vertical tab break; case 12: // form feed state.ScrollLines(state.RowCount); break; case 13: // carriage return state.MoveCursorBy(state.ColumnCount); break; case 247: // erase character state.EraseChar(state.CursorX - 1, state.CursorY); break; case 248: // erase line state.EraseLine(state.CursorY); break; default: if (c >= 32) { state.AppendChar(c); state.MoveCursorBy(1); } break; } return true; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MudClient.MM { public class CharacterClasses { private Dictionary<string, CharacterClass> classes = new Dictionary<string, CharacterClass>(); public CharacterClasses() { classes["Druid"] = new CharacterClass { Name = "Druid", SpellClass = SpellClass.Druid, CasterLevel = 3 }; classes["Ranger"] = new CharacterClass { Name = "Ranger", SpellClass = SpellClass.Druid, CasterLevel = 1, Stealth = true }; classes["Mage"] = new CharacterClass { Name = "Mage", SpellClass = SpellClass.Mage, CasterLevel = 3 }; classes["Priest"] = new CharacterClass { Name = "Priest", SpellClass = SpellClass.Priest, CasterLevel = 3 }; classes["Cleric"] = new CharacterClass { Name = "Cleric", SpellClass = SpellClass.Priest, CasterLevel = 2 }; classes["Paladin"] = new CharacterClass { Name = "Paladin", SpellClass = SpellClass.Priest, CasterLevel = 1 }; classes["Bard"] = new CharacterClass { Name = "Bard", SpellClass = SpellClass.Bard, CasterLevel = 2, Stealth = true }; classes["Mystic"] = new CharacterClass { Name = "Mystic", SpellClass = SpellClass.Mystic, CasterLevel = 1, Stealth = true }; classes["Ninja"] = new CharacterClass { Name = "Ninja", CasterLevel = 0, Stealth = true }; classes["Warrior"] = new CharacterClass { Name = "Warrior", SpellClass = SpellClass.None, Stealth = false }; classes["Thief"] = new CharacterClass { Name = "Thief", SpellClass = SpellClass.None, Stealth = true }; } public CharacterClass GetClassByName(string name) { if (string.IsNullOrEmpty(name)) return null; CharacterClass chClass; classes.TryGetValue(name, out chClass); return chClass; } } public class CharacterClass { public List<string> Titles = new List<string>(); public string Name { get; set; } public SpellClass SpellClass { get; set; } public int CasterLevel { get; set; } public bool Stealth { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MudClient.MM { public class Shop { public readonly Inventory ItemsForSale = new Inventory(); public void ParseItems(MudMaster owner) { ItemsForSale.Clear(); for (int i = 0; i < 50; i++) { string line = owner.historicalLines.GetFromEnd(i); if (line == "------------------------------------------------------") break; string[] parts = line.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries); if (parts.Length == 3) { string name = parts[0].Trim(); Item item = owner.itemary.FindOrAdd(name); int quant; int ix = 0; parts[1].GetNextInt(ref ix, out quant); ItemStack stack = new ItemStack(quant, item); ix = parts[2].IndexOf('('); if (ix >= 0) parts[2] = parts[2].Substring(0, ix); var cost = owner.itemary.ParseStack(parts[2]); item.Cost = cost.Cost; ItemsForSale.Add(stack); } } } public string ToString(MudMaster owner) { var sb = new StringBuilder(); sb.AppendLine("For sale:"); foreach (var item in ItemsForSale.Items) { sb.Append(item.ToString()).Append(" = ").Append( owner.itemary.ConvertToCurrency(item.Item.Cost).ToString()).AppendLine(); } return sb.ToString(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MudClient.MM { public class Banks { public readonly List<Bank> banks = new List<Bank>(); public bool ParseBalance(MudMaster owner, string line) { if (!(line.StartsWith("On deposit: ") && line.EndsWith(" gold crowns]"))) return false; var prevLine = owner.historicalLines.GetFromEnd(1); if (!(prevLine.StartsWith("Your balance at ") && prevLine.EndsWith(") is:"))) return false; int ix = "On deposit: ".Length; int balance; if (!line.GetNextInt(ref ix, out balance)) return false; ix = prevLine.Length - ") is:".Length - 1; int bankNumber; if (!prevLine.GetPrevInt(ref ix, out bankNumber) || bankNumber < 0) return false; if (!prevLine.ExpectPrevString(ref ix, " (#")) return false; while (bankNumber >= banks.Count) banks.Add(null); var bank = banks[bankNumber]; if (bank == null) { bank = new Bank(); bank.BankNumber = bankNumber; banks[bankNumber] = bank; bank.Name = prevLine.SubstringRange("Your balance at ".Length, ix); } if (owner.curCharacter != null) { bank.Balances[owner.curCharacter] = balance; owner.curCharacter.TotalBankBalances = banks .Where(b => b != null && b.Balances.ContainsKey(owner.curCharacter)) .Sum(b => b.Balances[owner.curCharacter]); } return true; } public bool ParseDepositWithdrawal(MudMaster owner, string line) { if (line.StartsWith("You deposit ") && line.EndsWith(".")) { string[] parts = line.SubstringRange("You deposit ".Length, line.Length - 2) .Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries); int totalValue = 0; foreach (var part in parts) { var item = owner.itemary.ParseStack(part); totalValue += item.Cost; owner.curCharacter.Inventory.Remove(item); } UpdateBankBalance(owner, totalValue); owner.Reactors.AddTrigger(Trigger.Inventory); return true; } else if (line.StartsWith("You withdrew ") && line.EndsWith(" copper farthings.")) { int ix = "You withdrew ".Length; int totalValue; line.GetNextInt(ref ix, out totalValue); var stack = new ItemStack(totalValue, owner.itemary.Copper); owner.curCharacter.Inventory.Add(stack); owner.curCharacter.Inventory.ConsolidateMoney(owner.itemary); if (owner.curCharacter.Name != null) { UpdateBankBalance(owner, -totalValue); } owner.Reactors.AddTrigger(Trigger.Inventory); return true; } else return false; } private void UpdateBankBalance(MudMaster owner, int count) { owner.curCharacter.TotalBankBalances += count; foreach (var bank in banks) { if (bank == null) continue; if (owner.curCharacter.Location != null && bank.Name == owner.curCharacter.Location.Title) { bank.Location = owner.curCharacter.Location; bank.Location.Bank = bank; } if (bank.Location == owner.curCharacter.Location) { int oldBalance; if (bank.Balances.TryGetValue(owner.curCharacter, out oldBalance) && oldBalance >= count) { bank.Balances[owner.curCharacter] = oldBalance + count; } break; } } } } public class Bank { public string Name; public MapNode Location; public int BankNumber; public readonly Dictionary<Character, int> Balances = new Dictionary<Character, int>(); public override string ToString() { return Name ?? base.ToString(); } } } <file_sep># MudClient This is a client for MajorMUD, an old BBS game. Not too many servers around anymore. Some of the assumptions I went into it with turned out to be wrong. I assumed that I could auto-generate a map by keeping track of an X/Y/Z position, so if you move north 5 times, west 5 times, south 5 times, and east 5 times, you would get back to where you started. It turns out that's not always true. Sometimes it might take 6 rooms instead of 5 to get back to where you started. It still did OK in many circumstances, but it could get quite confused when trying to synchronize incongruous information like this. Also, I remember I kept finding more and more strings I needed to check for various ways of doing things. Almost like I would have to custom code every single area I wanted to handle, because they all acted differently. I think I might have been started to look into synchronizing multiple characters partying together, but never got very far with that. Anyway, if anyone wants to play with it, you can do whatever you like with this code. <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MudClient { public class RollingBuffer<T> : IList<T> { private readonly T[] data; private int nextIndex; public RollingBuffer(int size) { data = new T[size]; nextIndex = 0; } public T[] Last10 { get { return new T[] { GetFromEnd(10), GetFromEnd(9), GetFromEnd(8), GetFromEnd(7), GetFromEnd(6), GetFromEnd(5), GetFromEnd(4), GetFromEnd(3), GetFromEnd(2), GetFromEnd(1), GetFromEnd(0), }; } } public void Insert(int index, T item) { throw new NotSupportedException(); } public void RemoveAt(int index) { throw new NotSupportedException(); } public bool Remove(T item) { throw new NotSupportedException(); } public T this[int index] { get { if (index < 0 || index > data.Length) throw new IndexOutOfRangeException(); return data[(nextIndex + index) % data.Length]; } set { if (index < 0 || index > data.Length) throw new IndexOutOfRangeException(); data[(nextIndex + index) % data.Length] = value; } } public T GetFromEnd(int count) { return this[data.Length - count - 1]; } public void RemoveLast() { nextIndex--; if (nextIndex < 0) nextIndex = data.Length - 1; } public void Add(T item) { data[nextIndex] = item; nextIndex = (nextIndex + 1) % data.Length; } public void Clear() { Array.Clear(data, 0, data.Length); nextIndex = 0; } public bool Contains(T item) { foreach (T datum in data) if (EqualityComparer<T>.Default.Equals(item, datum)) return true; return false; } public void CopyTo(T[] array, int arrayIndex) { foreach (var item in this) array[arrayIndex++] = item; } public int Count { get { return data.Length; } } public bool IsReadOnly { get { return false; } } public int IndexOf(T item) { int ix = 0; for (int i = nextIndex; i < data.Length; i++, ix++) if (EqualityComparer<T>.Default.Equals(item, data[i])) return ix; for (int i = 0; i < nextIndex; i++, ix++) if (EqualityComparer<T>.Default.Equals(item, data[i])) return ix; return -1; } public IEnumerator<T> GetEnumerator() { for (int i = nextIndex; i < data.Length; i++) yield return data[i]; for (int i = 0; i < nextIndex; i++) yield return data[i]; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace MudClient.MM { public class Grimoire { private List<Spell> Spells = new List<Spell>(); public void ParseSpells(MudMaster owner) { owner.curCharacter.KnownSpells.Clear(); for (int i = 0; i < 100; i++) { var line = owner.historicalLines.GetFromEnd(i); if (line == "You have the following spells:") break; int ix = 0; int level, mana; string shortcut, fullname; if (line.GetNextInt(ref ix, out level) && line.GetNextInt(ref ix, out mana) && line.GetNextWord(ref ix, out shortcut) && line.SkipNextSpaces(ref ix) > 0 && ix < line.Length) { fullname = line.Substring(ix).Trim(); var spell = GetOrMake(owner, fullname, shortcut, level, mana); owner.curCharacter.KnownSpells.Add(spell); if (spell.Effect == SpellEffect.Attack) { if (!owner.curCharacter.Attacks.Contains(spell)) owner.curCharacter.Attacks.Add(spell); } } } } public Spell GetByName(string spellName) { foreach (var spell in Spells) if (spell.FullName == spellName) return spell; return null; } public Spell GetOrMake(MudMaster owner, string spellName, string shortcut, int level, int mana) { var spell = GetByName(spellName); if (spell != null) return spell; spell = new Spell(); spell.FullName = spellName; spell.Shortcut = shortcut; spell.LearnedLevel = level; spell.ManaCost = mana; spell.CausesBuff = owner.buffs.GetBySpellName(spellName); var curClass = owner.classes.GetClassByName(owner.curCharacter.Class); if (curClass != null) spell.Class = curClass.SpellClass; Spells.Add(spell); return spell; } public void TryGetExisting(ref Spell spell) { foreach (var knownSpell in this.Spells) { if (knownSpell.FullName == spell.FullName) { if (spell.Effect != knownSpell.Effect) knownSpell.Effect = spell.Effect; spell = knownSpell; return; } } this.Spells.Add(spell); } } public abstract class CombatAction { public abstract void Use(MudMaster owner, CharacterBase target); public abstract bool CanUse(MudMaster owner, CharacterBase target); } public enum SpellEffect { Buff, Heal, Attack, } public enum SpellClass { None, Mage = 1, Priest, Druid, Bard, Mystic, } public enum SpellTarget { Unknown, Self, Character, Party, Enemy, Room, Item, } public class Spell : CombatAction { public string FullName; public string Shortcut; public SpellClass Class; public int ManaCost; public int LearnedLevel; public int Duration; public int MinDamage; public int MaxDamage; public Buff CausesBuff; public Buff RemovesBuff; public bool AffectedByArmor; public SpellEffect Effect; public SpellTarget Target; public override void Use(MudMaster owner, CharacterBase target) { string castWord = "cast "; if (Class == SpellClass.Mystic) castWord = "invoke "; if (target == null) { owner.SendText(castWord + Shortcut + "\r\n"); } else { owner.SendText(castWord + Shortcut + " " + target.NameAsTarget + "\r\n"); } if (Effect != SpellEffect.Attack) { var me = owner.curCharacter; me.LastSpellcast = DateTime.UtcNow; me.InCombat = false; me.NextCombatCheck = DateTime.MinValue; owner.Reactors.AddTrigger(Trigger.CombatState); } } public override bool CanUse(MudMaster owner, CharacterBase target) { return owner.curCharacter.MPcur > ManaCost; } public void Deserialize(XElement elem) { FullName = elem.Element("FullName").Value; Shortcut = elem.Element("Shortcut").Value; ManaCost = elem.Element("Mana").Value.ToInt(); MinDamage = elem.Element("MinDamage").Value.ToInt(); MaxDamage = elem.Element("MaxDamage").Value.ToInt(); Enum.TryParse<SpellEffect>(elem.Element("Effect").Value, out Effect); } public void UpdateSpellData(MudMaster owner, int damage, SpellEffect effect, CharacterBase target) { if (this.Effect != effect) { Effect = effect; if (effect == SpellEffect.Attack) { if (!owner.curCharacter.Attacks.Contains(this)) owner.curCharacter.Attacks.Add(this); } } if (damage > 0) { if (damage > MaxDamage) MaxDamage = damage; if (MinDamage == 0 || damage < MinDamage) MinDamage = damage; } if (Target == SpellTarget.Unknown) { if (target is NPC) Target = SpellTarget.Enemy; else if (target is Character && target != owner.curCharacter) Target = SpellTarget.Character; else if (target == owner.curCharacter) Target = SpellTarget.Self; } else if (Target == SpellTarget.Self) { if (target is Character && target != owner.curCharacter) Target = SpellTarget.Character; } } public override string ToString() { return FullName; } } public class Backstab : CombatAction { public static readonly Backstab Instance = new Backstab(); public override void Use(MudMaster owner, CharacterBase target) { owner.SendText("backstab " + target.NameAsTarget + "\r\n"); } public override bool CanUse(MudMaster owner, CharacterBase target) { return target != null && (owner.curCharacter.Hidden || owner.curCharacter.Sneaking); } public override string ToString() { return "backstab"; } } public class Bash : CombatAction { public static readonly Bash Instance = new Bash(); public override void Use(MudMaster owner, CharacterBase target) { owner.SendText("bash " + target.NameAsTarget + "\r\n"); } public override bool CanUse(MudMaster owner, CharacterBase target) { return target != null; } public override string ToString() { return "bash"; } } public class Attack : CombatAction { public static readonly Attack Instance = new Attack(); public override void Use(MudMaster owner, CharacterBase target) { if (target == null) owner.SendText("attack\r\n"); else owner.SendText("attack " + target.NameAsTarget + "\r\n"); } public override bool CanUse(MudMaster owner, CharacterBase target) { return true; } public override string ToString() { return "attack"; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace MudClient { public class ProtocolLog : Protocol { private byte[] buffer = new byte[4096]; private int bufferPos; private string FileName; private FileStream stream; private DateTime nextFlush; public void SetLogFile(string fileName) { this.FileName = fileName; if (stream != null) { using (stream) { Flush(); stream = null; } } if (!string.IsNullOrWhiteSpace(fileName)) stream = new FileStream(FileName, FileMode.Append, FileAccess.Write, FileShare.Read); } public override bool HandleChar(byte c) { buffer[bufferPos++] = c; if (bufferPos >= buffer.Length || DateTime.UtcNow > nextFlush) Flush(); return false; } public void Flush() { if (bufferPos > 0 && stream != null) stream.Write(buffer, 0, bufferPos); bufferPos = 0; nextFlush = DateTime.UtcNow.AddSeconds(10); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MudClient.MM { [Flags] public enum AIPriorities { Flee = 1 << 0, Retreat = 1 << 1, Rest = 1 << 2, Fight = 1 << 3, Deposit = 1 << 4, Sell = 1 << 5, Train = 1 << 6, Patrol = 1 << 7, All = (1 << 8) - 1, } public class AI : BaseReactor { public AIPriorities AllowedActions = AIPriorities.All; public bool AutoSneak { get; set; } private AIPriorities CurrentPriorities; private HashSet<string> PatrolTargets = new HashSet<string>(); private HashSet<string> AvoidTargets = new HashSet<string>(); private HashSet<MapNode> PatrolNodes = new HashSet<MapNode>(); public float HPFleeRatio = .40f; public float ManaRestRatio = .90f; public float EncumbranceSellRatio = .75f; public float BankMinimumDeposit = 10000; public TimeSpan RegenTime = new TimeSpan(0, 1, 0); private DateTime MoveQueued; public AI() : base(Trigger.RoomCharacters | Trigger.Death | Trigger.CombatState | Trigger.HPandMana | Trigger.Location | Trigger.Inventory) { } public void SetPatrolTarget(string name, bool Target, bool Avoid) { if (Target) PatrolTargets.Add(name); else PatrolTargets.Remove(name); if (Avoid) AvoidTargets.Add(name); else AvoidTargets.Remove(name); PatrolNodes.Clear(); } public bool IsPatrol(string name) { return PatrolTargets.Contains(name); } public bool IsAvoid(string name) { return AvoidTargets.Contains(name); } public override void Execute(Trigger triggers, MudMaster owner) { if (triggers.HasFlag(Trigger.Death)) { this.Enabled = false; return; } if (owner.Reactors.Move.HasRoute) return; if (triggers.HasFlag(Trigger.Location)) { MoveQueued = DateTime.MinValue; } if (DateTime.UtcNow < MoveQueued.AddSeconds(3)) return; DeterminePriorities(triggers, owner); ExecutePriority(owner); } private void DeterminePriorities(Trigger triggers, MudMaster owner) { CurrentPriorities = 0; var me = owner.curCharacter; var here = me.Location; if (here == null) return; bool roomSafe = !here.IsDangerous(me) && !me.InCombat; bool roomScary = !roomSafe && here.IsDeadly(me, AvoidTargets); if (roomScary) CurrentPriorities |= AIPriorities.Retreat; if ((triggers & (Trigger.HPandMana | Trigger.Location | Trigger.RoomCharacters | Trigger.CombatState)) != 0) { CurrentPriorities |= AIPriorities.Patrol; if (!roomSafe) { CurrentPriorities |= AIPriorities.Fight; } if (me.HPcur + me.HPregen < me.HPmax || me.MPcur < me.MPmax * ManaRestRatio) { CurrentPriorities |= AIPriorities.Rest; } if (me.HPcur < HPFleeRatio * me.HPmax && !roomSafe) { CurrentPriorities |= AIPriorities.Flee; } } if (me.Inventory.Wealth > BankMinimumDeposit) { CurrentPriorities |= AIPriorities.Deposit; } if (me.Inventory.Encumbrance >= me.MaxEncumbrance * EncumbranceSellRatio) { CurrentPriorities |= AIPriorities.Sell; } } private bool CanMove(Route rt) { return string.IsNullOrEmpty(rt.Direction.Barrier) && !rt.Direction.Hidden && rt.ConnectTo != null && !rt.ConnectTo.SeenNPCs.Any(npc => AvoidTargets.Contains(npc.Name)); } private void ExecutePriority(MudMaster owner) { var me = owner.curCharacter; Route route = null; for (AIPriorities priority = (AIPriorities)1; priority < AIPriorities.All; priority = (AIPriorities)((int)priority << 1)) { if (!CurrentPriorities.HasFlag(priority) || !AllowedActions.HasFlag(priority)) continue; switch (priority) { case AIPriorities.Rest: case AIPriorities.Fight: // stay here return; case AIPriorities.Deposit: route = owner.map.FindNearestRouteReverseOrder(me.Location, n => n.Bank != null, CanMove).LastOrDefault(); break; case AIPriorities.Flee: route = owner.map.FindNearestRouteReverseOrder(me.Location, n => { return !n.IsDangerous(owner.curCharacter) && !n.IsDeadly(owner.curCharacter, AvoidTargets); }, CanMove).LastOrDefault(); if (route == null) { route = owner.map.FindNearestRouteReverseOrder(me.Location, n => { return !n.IsDangerous(owner.curCharacter) && !n.IsDeadly(owner.curCharacter, AvoidTargets); }).LastOrDefault(); } break; case AIPriorities.Retreat: foreach (var exit in me.Location.Exits) { if (!CanMove(exit)) continue; if (exit.ConnectTo.NPCInRoom.Any(npc => npc.type.AttacksAlignment.HasFlag(owner.curCharacter.Alignment))) continue; route = exit; break; } break; case AIPriorities.Patrol: { var nodes = GetPatrolLocations(owner); // first search for close rooms with known targets route = owner.map.FindNearestRouteReverseOrder(me.Location, (n) => { if (n.NPCInRoom.Any(npc => PatrolTargets.Contains(npc.Name))) return true; return false; }, CanMove, 3).LastOrDefault(); if (route != null) break; DateTime oldestTime = DateTime.UtcNow; foreach (var node in nodes) { if (node.LastVisit < oldestTime) { oldestTime = node.LastVisit; } } // then the oldest location which hasn't been visited route = owner.map.FindNearestRouteReverseOrder(me.Location, (n) => { return IsValidPatrolTarget(oldestTime, n); }, CanMove).LastOrDefault(); if (route != null) break; // then any location on the map route = owner.map.FindNearestRouteReverseOrder(me.Location, (n) => nodes.Contains(n), CanMove).LastOrDefault(); } break; case AIPriorities.Sell: route = owner.map.FindNearestRouteReverseOrder(owner.curCharacter.Location, n => { return n.Shop != null && n.Shop.ItemsForSale.Items.Any(i => i.Cost == 0); }, CanMove).LastOrDefault(); break; case AIPriorities.Train: break; } if (route != null) break; } if (route == null) { Console.WriteLine("No route found for priorities " + CurrentPriorities); return; } MoveQueued = DateTime.UtcNow; if (AutoSneak && !me.Sneaking && me.Location.NPCInRoom.Count == 0) owner.SendText("sneak\r\n"); route.Execute(owner); } private bool IsValidPatrolTarget(DateTime oldestTime, MapNode n) { if (n.NPCInRoom.Any(npc => PatrolTargets.Contains(npc.Name))) return true; return PatrolNodes.Contains(n) && n.LastVisit < oldestTime.AddSeconds(60); } private HashSet<MapNode> GetPatrolLocations(MudMaster owner) { if (PatrolNodes.Count > 0) return PatrolNodes; var loc = owner.curCharacter.Location; bool valid = false; foreach (var npc in loc.SeenNPCs) if (PatrolTargets.Contains(npc.Name)) valid = true; if (!valid) { var nearest = owner.map.FindNearestRouteReverseOrder(loc, n => { foreach (var npc in n.SeenNPCs) if (PatrolTargets.Contains(npc.Name)) return true; return false; }, CanMove).FirstOrDefault(); if (nearest != null && nearest.ConnectTo != null) loc = nearest.ConnectTo; else return PatrolNodes; } PatrolNodes.Add(loc); PatrolNodes.UnionWith( owner.map.VisitInRadius(loc, 4, n => n.SeenNPCs.Any(npc => PatrolTargets.Contains(npc.Name)), CanMove) .Where(n => n.SeenNPCs.Any(npc => PatrolTargets.Contains(npc.Name)))); return PatrolNodes; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MudClient.MM { public enum WearSlot { Head = 0, Legs, Feet, Hands, Torso, Weapon, Offhand, LeftFinger, RightFinger, Arms, Back, LeftWrist, RightWrist, Waist, Neck, Ears, Worn, Max = Worn } public class Inventory { public List<ItemStack> Items = new List<ItemStack>(); public void Clear() { Items.Clear(); } public virtual void Add(ItemStack stack) { stack.Busy = false; foreach (var item in Items) { if (item.Item == stack.Item) { item.Busy = false; item.Count += stack.Count; return; } } Items.Add(stack); } public virtual bool Remove(ItemStack stack) { stack.Busy = false; foreach (var item in Items) { if (item.Item == stack.Item) { item.Busy = false; item.Count -= stack.Count; if (item.Count <= 0) Items.Remove(item); return true; } } return false; } public void TransferTo(Inventory to, ItemStack stack) { Remove(stack); to.Add(stack); } public bool ShouldConsidateMoney(MudMaster owner) { foreach (var item in this.Items) { if (item.Item == owner.itemary.Copper && item.Count > 10) return true; if (item.Item == owner.itemary.Silver && item.Count > 10) return true; if (item.Item == owner.itemary.Gold && item.Count > 100) return true; if (item.Item == owner.itemary.Platinum && item.Count > 100) return true; } return false; } public bool ParseItemDrop(MudMaster owner, string line) { if (line.EndsWith(" drop to the ground.")) { line = line.Substring(0, line.Length - " drop to the ground.".Length); owner.curCharacter.Location.AddItemInRoom(owner, line); return true; } else if (line.StartsWith("You hid ")) { line = line.SubstringRange("You hid ".Length, line.Length - 2); var stack = owner.curCharacter.Location.AddItemInRoom(owner, line); owner.curCharacter.Inventory.Remove(stack); return true; } else if (line.StartsWith("You dropped ")) { line = line.SubstringRange("You dropped ".Length, line.Length - 2); var stack = owner.curCharacter.Location.AddItemInRoom(owner, line); owner.curCharacter.Inventory.Remove(stack); return true; } return false; } public override string ToString() { return string.Join(", ", Items); } } public class CharacterInventory : Inventory { private readonly Item[] worn = new Item[(int)WearSlot.Max + 1]; private readonly List<Item> wornUnknown = new List<Item>(); public float Encumbrance; public Item this[WearSlot slot] { get { return worn[(int)slot]; } set { worn[(int)slot] = value; } } public int Wealth { get { return Items.Where(i => i.Item.Type == ItemType.Currency) .Sum(i => i.Count * i.Item.Cost); } } public void ConsolidateMoney(Itemary items) { var existingMoney = this.Items.Where(i => i.Item.Type == ItemType.Currency).ToList(); int total = existingMoney.Sum(i => i.Cost); if (total < 10) return; foreach (var item in existingMoney) this.Remove(item); foreach (var currType in items.GetCurrencyTypes().OrderBy(c => -c.Cost)) { if (currType.Cost == 0) continue; int count = total / currType.Cost; if (count > 0) { total %= currType.Cost; var stack = new ItemStack(count, currType); this.Add(stack); } } } public void ParseItems(MudMaster owner, string line) { line = line.Substring("You are carrying ".Length); string[] items = line.Split(','); this.Items.Clear(); Array.Clear(worn, 0, worn.Length); wornUnknown.Clear(); for (int i = 0; i < items.Length; i++) { string item = items[i].Trim(); string slot = null; if (item.EndsWith(")")) { int startIx = item.LastIndexOf("("); slot = item.Substring(startIx + 1, item.Length - startIx - 2); item = item.Substring(0, startIx).Trim(); } var stack = owner.itemary.ParseStack(item); this.Items.Add(stack); if (slot != null) { AssignWornItem(slot, stack.Item); } } } public bool ParseWearRemove(MudMaster owner, string line) { if (line.StartsWith("You are now wearing ") && line.EndsWith(".")) { string added = line.SubstringRange("You are now wearing ".Length, line.Length - 2); foreach (var item in this.Items) { if (item.Item.Name == added) { SetItemWorn(item.Item); owner.Reactors.AddTrigger(Trigger.Inventory); return true; } } return true; } else if (line.StartsWith("You have removed ") && line.EndsWith(".")) { string removed = line.SubstringRange("You have removed ".Length, line.Length - 2); for (int i = 0; i < worn.Length; i++) { var item = worn[i]; if (item.Name == removed) { worn[i] = null; owner.Reactors.AddTrigger(Trigger.Inventory); return true; } } for (int i = 0; i < wornUnknown.Count; i++) { var item = wornUnknown[i]; if (item.Name == removed) { wornUnknown.RemoveAt(i); owner.Reactors.AddTrigger(Trigger.Inventory); return true; } } return true; } else return false; } private void ClearWornItems() { Array.Clear(worn, 0, worn.Length); wornUnknown.Clear(); } private void SetItemWorn(Item item) { switch (item.Type) { case ItemType.Head: this[WearSlot.Head] = item; break; case ItemType.Legs: this[WearSlot.Legs] = item; break; case ItemType.Feet: this[WearSlot.Feet] = item; break; case ItemType.Hands: this[WearSlot.Hands] = item; break; case ItemType.Torso: this[WearSlot.Torso] = item; break; case ItemType.Weapon1H: this[WearSlot.Weapon] = item; break; case ItemType.Weapon2H: this[WearSlot.Weapon] = item; break; case ItemType.Shield: this[WearSlot.Offhand] = item; break; case ItemType.Arms: this[WearSlot.Arms] = item; break; case ItemType.Back: this[WearSlot.Back] = item; break; case ItemType.Waist: this[WearSlot.Waist] = item; break; case ItemType.Neck: this[WearSlot.Neck] = item; break; case ItemType.Worn: this[WearSlot.Worn] = item; break; case ItemType.Ears: this[WearSlot.Ears] = item; break; case ItemType.Wrist: if (this[WearSlot.LeftWrist] == null) this[WearSlot.LeftWrist] = item; else this[WearSlot.RightWrist] = item; break; case ItemType.Finger: if (this[WearSlot.LeftFinger] == null) this[WearSlot.LeftFinger] = item; else this[WearSlot.RightFinger] = item; break; default: wornUnknown.Add(item); break; } } private void AssignWornItem(string slot, Item item) { switch (slot) { case "Head": item.Type = ItemType.Head; break; case "Legs": item.Type = ItemType.Legs; break; case "Feet": item.Type = ItemType.Feet; break; case "Hands": item.Type = ItemType.Hands; break; case "Torso": item.Type = ItemType.Torso; break; case "Weapon Hand": item.Type = ItemType.Weapon1H; break; case "Off-Hand": item.Type = ItemType.Shield; break; case "Arms": item.Type = ItemType.Arms; break; case "Back": item.Type = ItemType.Back; break; case "Waist": item.Type = ItemType.Waist; break; case "Neck": item.Type = ItemType.Neck; break; case "Worn": item.Type = ItemType.Worn; break; case "Ears": item.Type = ItemType.Ears; break; case "Wrist": item.Type = ItemType.Wrist; break; case "Finger": item.Type = ItemType.Finger; break; } SetItemWorn(item); } public bool ParseInventory(MudMaster owner, string line) { if (!line.StartsWith("Encumbrance: ")) return false; owner.Reactors.AddTrigger(Trigger.Inventory); foreach (var group in owner.GroupLines("You are carrying ", "Encumbrance: ", "Wealth: ", "You have ", "You are carrying ")) { if (group.StartsWith("Encumbrance: ")) ParseEncumbrance(owner, group); else if (group.StartsWith("Wealth: ")) ParseWealth(owner, group); else if (group.StartsWith("You have ")) ParseKeys(owner, group); else if (group.StartsWith("You are carrying ")) { ParseItems(owner, group); break; } } return true; } public void ParseLookInventory(MudMaster owner, List<string> lines) { Array.Clear(worn, 0, worn.Length); foreach (string line in lines) { int ix = line.Length - 1; if (!line.ExpectPrevString(ref ix, ")")) continue; string slot; if (!line.GetPrevWord(ref ix, out slot)) continue; if (!line.ExpectPrevString(ref ix, ")")) continue; line.SkipPrevSpaces(ref ix); string itemName = line.Substring(0, ix); var item = owner.itemary.FindOrAdd(itemName); AssignWornItem(slot, item); } } public override void Add(ItemStack stack) { base.Add(stack); this.Encumbrance += stack.Weight; } public override bool Remove(ItemStack stack) { float weight = stack.Weight; if (!base.Remove(stack)) return false; this.Encumbrance -= weight; return true; } private void ParseEncumbrance(MudMaster owner, string line) { int ix = "Encumbrance: ".Length; int enc, max; string stateString; EncumbranceState state; line.GetNextInt(ref ix, out enc); line.SkipNextChar(ref ix, '/'); line.GetNextInt(ref ix, out max); line.SkipNextSpaces(ref ix); line.SkipNextChar(ref ix, '-'); line.SkipNextSpaces(ref ix); line.GetNextWord(ref ix, out stateString); Enum.TryParse<EncumbranceState>(stateString, out state); if (enc != this.Encumbrance || state != owner.curCharacter.EncumbranceState || max != owner.curCharacter.MaxEncumbrance) { this.Encumbrance = enc; owner.curCharacter.EncumbranceState = state; owner.curCharacter.MaxEncumbrance = max; owner.Reactors.AddTrigger(Trigger.Inventory); } } private void ParseKeys(MudMaster owner, string line) { } private void ParseWealth(MudMaster owner, string line) { } public bool ParseGive(MudMaster owner, string line) { int ix; if (line.StartsWith("You just gave ")) { ix = line.IndexOf(" to ", "You just gave ".Length); if (ix > 0) { string item = line.SubstringRange("You just gave ".Length, ix); var stack = owner.itemary.ParseStack(item); Remove(stack); owner.Reactors.AddTrigger(Trigger.Inventory); } return true; } else if ((ix = line.IndexOf(" just gave you ")) > 0 && line.EndsWith(".")) { string item = line.SubstringRange(ix + " just gave you ".Length, line.Length - 2); var stack = owner.itemary.ParseStack(item); Add(stack); owner.Reactors.AddTrigger(Trigger.Inventory); return true; } return false; } public bool ParsePickup(MudMaster owner, string line) { if (line.StartsWith("You picked up ")) line = line.SubstringRange("You picked up ".Length, line.EndsWith(".") ? (line.Length - 2) : (line.Length - 1)); else if (line.StartsWith("You took ")) line = line.SubstringRange("You took ".Length, line.EndsWith(".") ? (line.Length - 2) : (line.Length - 1)); else return false; var stack = owner.itemary.ParseStack(line); if (owner.curCharacter.Location != null) { var here = owner.curCharacter.Location; if (here.ItemInRoom.Items.Any(i => i.Item == stack.Item)) owner.curCharacter.Location.ItemInRoom.TransferTo(this, stack); else owner.curCharacter.Location.HiddenItems.Clear(); } else this.Add(stack); owner.Reactors.AddTrigger(Trigger.RoomItems | Trigger.Inventory); return true; } public bool ParseBuySell(MudMaster owner, string line) { int ForIndex; string item, cost; bool buy; if (line.StartsWith("You just bought ")) { ForIndex = line.IndexOf(" for "); if (ForIndex < 0) return false; buy = true; item = line.SubstringRange("You just bought ".Length, ForIndex - 1); } else if (line.StartsWith("You sold ")) { ForIndex = line.IndexOf(" for "); if (ForIndex < 0) return false; buy = false; item = line.SubstringRange("You sold ".Length, ForIndex - 1); } else return false; cost = line.SubstringRange(ForIndex + " for ".Length, line.Length - 2); var itemExchanged = owner.itemary.ParseStack(item); if (buy) { Add(itemExchanged); } else { Remove(itemExchanged); } HandleMoneyExchange(owner, cost, buy); return true; } private void BreakCurrency(MudMaster owner, ItemStack stack) { // this is a really stupid implementation with lots of copy and paste, need to simplify it // into a general loop without currency type knowledge int runicCount = 0, platCount = 0, goldCount = 0, silverCount = 0, copperCount = 0; foreach (var item in Items) { if (item.Item == owner.itemary.Runic) runicCount = item.Count; if (item.Item == owner.itemary.Platinum) platCount = item.Count; if (item.Item == owner.itemary.Gold) goldCount = item.Count; if (item.Item == owner.itemary.Silver) silverCount = item.Count; if (item.Item == owner.itemary.Copper) copperCount = item.Count; } if (stack.Item == owner.itemary.Copper) copperCount -= stack.Count; if (stack.Item == owner.itemary.Silver) silverCount -= stack.Count; if (stack.Item == owner.itemary.Gold) goldCount -= stack.Count; if (stack.Item == owner.itemary.Platinum) platCount -= stack.Count; if (stack.Item == owner.itemary.Runic) runicCount -= stack.Count; if (copperCount < 0) { silverCount += (copperCount - 9) / 10; copperCount -= 10 * ((copperCount - 9) / 10); } if (silverCount < 0) { goldCount += (silverCount - 9) / 10; silverCount -= 10 * ((silverCount - 9) / 10); } if (goldCount < 0) { platCount += (goldCount - 99) / 100; goldCount -= 100 * ((goldCount - 99) / 100); } if (platCount < 0) { runicCount += (platCount - 99) / 100; platCount -= 100 * ((platCount - 99) / 100); } for (int i = 0; i < this.Items.Count; i++) { var item = this.Items[i]; if (item.Item.Type != ItemType.Currency) continue; if (item.Item == owner.itemary.Runic) { if (item.Count < runicCount) { Add(new ItemStack(runicCount - item.Count, owner.itemary.Runic)); } else if (item.Count > runicCount) { Remove(new ItemStack(item.Count - runicCount, owner.itemary.Runic)); } runicCount = 0; } if (item.Item == owner.itemary.Platinum) { if (item.Count < platCount) { Add(new ItemStack(platCount - item.Count, owner.itemary.Platinum)); } else if (item.Count > platCount) { Remove(new ItemStack(item.Count - platCount, owner.itemary.Platinum)); } platCount = 0; } if (item.Item == owner.itemary.Gold) { if (item.Count < goldCount) { Add(new ItemStack(goldCount - item.Count, owner.itemary.Gold)); } else if (item.Count > goldCount) { Remove(new ItemStack(item.Count - goldCount, owner.itemary.Gold)); } goldCount = 0; } if (item.Item == owner.itemary.Silver) { if (item.Count < silverCount) { Add(new ItemStack(silverCount - item.Count, owner.itemary.Silver)); } else if (item.Count > silverCount) { Remove(new ItemStack(item.Count - silverCount, owner.itemary.Silver)); } silverCount = 0; } if (item.Item == owner.itemary.Copper) { if (item.Count < copperCount) { Add(new ItemStack(copperCount - item.Count, owner.itemary.Copper)); } else if (item.Count > copperCount) { Remove(new ItemStack(item.Count - copperCount, owner.itemary.Copper)); } copperCount = 0; } } if (runicCount > 0) this.Add(new ItemStack(runicCount, owner.itemary.Runic)); if (platCount > 0) this.Add(new ItemStack(platCount, owner.itemary.Platinum)); if (goldCount > 0) this.Add(new ItemStack(goldCount, owner.itemary.Gold)); if (silverCount > 0) this.Add(new ItemStack(silverCount, owner.itemary.Silver)); if (copperCount > 0) this.Add(new ItemStack(silverCount, owner.itemary.Copper)); this.Add(stack); } public void HandleMoneyExchange(MudMaster owner, string costString, bool buy) { string[] costParts = costString.Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries); var monies = new ItemStack[costParts.Length]; for (int i = 0; i < costParts.Length; i++) { monies[i] = owner.itemary.ParseStack(costParts[i]); } if (buy) { foreach (var money in monies) { if (money.Cost == 0) continue; foreach (var item in Items) { if (money.Item == item.Item && money.Count > item.Count) { BreakCurrency(owner, money); break; } } Remove(money); } } else // sell { foreach (var money in monies) { Add(money); } ConsolidateMoney(owner.itemary); } owner.Reactors.AddTrigger(Trigger.Inventory); } public override string ToString() { StringBuilder sb = new StringBuilder(); foreach (var item in Items) { if (worn.Contains(item.Item) && item.Count < 2) continue; if (sb.Length > 0) sb.Append(", "); sb.Append(item.ToString()); } return sb.ToString(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MudClient.MM { public static class StringExtensions { public static bool IsLetter(char c) { return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'); } public static bool IsDigit(char c) { return c >= '0' && c <= '9'; } public static bool SkipNextChar(this string line, ref int curIx, char expectedChar) { if (curIx < 0 || line == null || curIx >= line.Length) return false; if (line[curIx] == expectedChar) { curIx++; return true; } return false; } public static bool SkipPrevChar(this string line, ref int curIx, char expectedChar) { if (curIx < 0 || line == null || curIx >= line.Length) return false; if (line[curIx] == expectedChar) { curIx--; return true; } return false; } public static int SkipNextSpaces(this string line, ref int curIx) { if (curIx < 0 || line == null || curIx >= line.Length) return -1; int count = 0; while (curIx < line.Length && line[curIx] == ' ') { curIx++; count++; } return count; } public static int SkipPrevSpaces(this string line, ref int curIx) { if (curIx < 0 || line == null || curIx >= line.Length) return -1; int count = 0; while (curIx >= 0 && line[curIx] == ' ') { curIx--; count++; } return count; } public static bool ExpectNextString(this string line, ref int curIx, string expected) { if (string.IsNullOrEmpty(expected) || curIx < 0) return true; if (curIx + expected.Length > line.Length) return false; if (expected[0] != line[curIx]) // verify first character last return false; int lineIx = curIx + expected.Length - 1; for (int i = expected.Length - 1; i > 0; i--, lineIx--) if (line[lineIx] != expected[i]) return false; curIx += expected.Length; return true; } public static bool ExpectPrevString(this string line, ref int curIx, string expected) { if (string.IsNullOrEmpty(expected) || curIx < 0) return true; int minIx = curIx - expected.Length + 1; if (minIx < 0) return false; if (expected[0] != line[minIx]) return false; int lineIx = curIx; for (int i = expected.Length - 1; i > 0; i--, lineIx--) if (line[lineIx] != expected[i]) return false; curIx -= expected.Length; return true; } public static bool GetNextUntil(this string line, ref int curIx, string expect, out string result) { result = null; if (curIx < 0 || line == null || curIx >= line.Length) return false; int endIx = line.IndexOf(expect, curIx); if (endIx < 0) return false; result = line.Substring(curIx, endIx - curIx); curIx = endIx + expect.Length; return true; } public static bool GetPrevUntil(this string line, ref int curIx, string expect, out string result) { result = null; if (curIx < 0 || line == null || curIx >= line.Length) return false; int endIx = line.LastIndexOf(expect, curIx); if (endIx < 0) return false; result = line.Substring(curIx, endIx - curIx); curIx = endIx - expect.Length; return true; } public static bool GetNextWord(this string line, ref int curIx, out string result) { result = null; if (curIx < 0 || line == null || curIx >= line.Length) return false; SkipNextSpaces(line, ref curIx); int startIx = -1, endIx = -1; while (curIx <= line.Length) { char c = line[curIx]; if (!IsLetter(c)) break; if (startIx < 0) startIx = curIx; endIx = curIx; curIx++; } if (startIx < 0) return false; result = line.Substring(startIx, endIx + 1 - startIx); return true; } public static bool GetPrevWord(this string line, ref int curIx, out string result) { result = null; if (curIx < 0 || line == null || curIx >= line.Length) return false; SkipPrevSpaces(line, ref curIx); int startIx = -1, endIx = -1; while (curIx >= 0) { char c = line[curIx]; if (!IsLetter(c)) break; if (endIx < 0) endIx = curIx; startIx = curIx; curIx--; } if (startIx < 0) return false; result = line.Substring(startIx, endIx + 1 - startIx); return true; } public static bool GetPrevInt(this string line, ref int curIx, out int result) { result = 0; if (curIx < 0 || line == null || curIx >= line.Length) return false; SkipPrevSpaces(line, ref curIx); int mult = 1; while (curIx >= 0) { char c = line[curIx]; if (!IsDigit(c)) { if (c == '-') { result = -result; curIx--; } break; } result += mult * (c - '0'); mult *= 10; curIx--; } return mult > 1; } public static bool GetNextInt(this string line, ref int curIx, out int result) { result = 0; if (curIx < 0 || line == null || curIx >= line.Length) return false; SkipNextSpaces(line, ref curIx); bool negative = false; if (curIx < line.Length - 2 && line[curIx] == '-' && IsDigit(line[curIx + 1])) { curIx++; negative = true; } bool found = false; while (curIx < line.Length) { char c = line[curIx]; if (!IsDigit(c)) break; found = true; result *= 10; result += (c - '0'); curIx++; } if (negative) result = -result; return found; } public static int ToInt(this string text) { int result; if (int.TryParse(text, out result)) return result; return 0; } public static string SubstringRange(this string s, int startIx, int endIx) { return s.Substring(startIx, endIx - startIx + 1); } public static string TrimSubstring(this string s, int startIx, int length) { return DoTrimSubstring(s, startIx, startIx + length - 1); } public static string TrimSubstring(this string s, int startIx) { return DoTrimSubstring(s, startIx, s.Length - 1); } private static string DoTrimSubstring(string s, int startIx, int endIx) { while (startIx <= endIx && s[endIx] <= ' ') endIx--; while (startIx <= endIx && s[startIx] <= ' ') startIx++; return s.SubstringRange(startIx, endIx); } public static bool Extract(this byte[] line, ref int ix, out int result) { result = 0; if (ix < 0 || line[ix] < '0' || line[ix] > '9') return false; int mult = 1; while (ix >= 0) { if (line[ix] == '-') { ix--; result = -result; return mult > 1; } int val = line[ix] - '0'; if (val < 0 || val > 9) return true; result += val * mult; mult *= 10; ix--; } return true; } public static bool Expect1(this byte[] line, ref int ix, char value) { if (ix < 0 || line[ix] != value) return false; ix--; return true; } public static bool ExpectString(this byte[] line, ref int ix, string expected) { for (int i = expected.Length - 1; i >= 0; i--) if (!Expect1(line, ref ix, expected[i])) return false; return true; } public static string ToStringOrNull(this object value) { if (value == null) return null; return value.ToString(); } } } <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; using System.Runtime.InteropServices; namespace MudClient.MM { public partial class frmMap : Form { public frmMap() { InitializeComponent(); this.act = new UpdateScreenAction(this); } protected override void OnClosing(CancelEventArgs e) { base.OnClosing(e); act.Remove = true; } private UpdateScreenAction act; private MudMaster mud; public void SetMud(MudMaster mudMaster) { this.mud = mudMaster; this.mud.Reactors.AddExternalScript(act); RefreshMap(); } private void btnRefresh_Click(object sender, EventArgs e) { RefreshMap(); } private void btnClear_Click(object sender, EventArgs e) { mud.ClearMap(); RefreshMap(); } private void RefreshMap() { mapDraw1.Nodes.Clear(); mapDraw1.HighlightedNode = null; lstNodes.Items.Clear(); if (mud == null) return; var nodes = mud.map.GetAllNodes().ToList(); nodes.Sort((n1, n2) => n1.Title.CompareTo(n2.Title)); foreach (var node in nodes) { lstNodes.Items.Add(node); mapDraw1.Nodes.Add(node); } mapDraw1.Invalidate(); } private void mapDraw1_NodeClicked(MapNode node) { lstNodes.SelectedItem = node; } private void lstNodes_SelectedIndexChanged(object sender, EventArgs e) { var cur = lstNodes.SelectedItem as MapNode; ShowNode(cur ?? MapNode.Empty); mapDraw1.HighlightedNode = cur; mapDraw1.Invalidate(); if (cur != null && cur.Shop != null) { lblShop.Text = cur.Shop.ToString(mud); } else { lblShop.Text = null; } } private void ShowNode(MapNode node) { lblCoordinate.Text = node.Location.ToString(); lblTitle.Text = node.Title; lblExits.Text = string.Join(", ", node.Exits); lblDark.Text = node.Dark.ToString(); lblFullDescription.Text = node.Description; lblNPCs.Text = string.Join(", ", node.SeenNPCs); } private void RefreshMove() { lblRoute.Text = mud.Reactors.Move.ToStringOrNull(); if (chkAutoHighlight.Checked && mud != null) { mapDraw1.HighlightedNode = mud.curCharacter.Location; mapDraw1.Invalidate(); } } private void btnGoto_Click(object sender, EventArgs e) { mud.Reactors.Move.Cancel(); lblRoute.Text = null; var cur = lstNodes.SelectedItem as MapNode; if (cur == null) { RefreshMove(); return; } mud.Reactors.Move.SetDestination(mud, cur); RefreshMove(); } private void btnCancelGoto_Click(object sender, EventArgs e) { mud.Reactors.Move.Cancel(); RefreshMove(); } private void btnSelectCurrent_Click(object sender, EventArgs e) { lstNodes.SelectedItem = mud.curCharacter.Location; } private class UpdateScreenAction : BaseReactor { private frmMap owner; public UpdateScreenAction(frmMap owner) : base(Trigger.Map | Trigger.Location) { this.owner = owner; } public override void Execute(Trigger triggers, MudMaster owner) { if (triggers.HasFlag(Trigger.Map)) { this.owner.RefreshMap(); this.owner.RefreshMove(); } if (triggers.HasFlag(Trigger.Location)) this.owner.RefreshMove(); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MudClient.MM { public abstract class CharacterBase { public MapNode Location; public string Name; public CharacterBase CurrentlyAttacking; public bool Hidden; public bool Sneaking; public int HPcur, HPmax; public int HPregen = 3; // todo, how do I calculate this? public readonly HashSet<Buff> CurrentBuffs = new HashSet<Buff>(); public virtual string NameAsTarget { get { return Name; } } public override string ToString() { return Name; } public void BreakStealth() { Sneaking = false; Hidden = false; } } public enum EncumbranceState { None, Light, Medium, Heavy, } [Flags] public enum Alignment { Neutral = 1, Good = 2, Evil = 4, } public class Character : CharacterBase { public string LastName; public string Class; public string Guild; public string Race; public int Lives; public int CharacterPoints = -1; public int Experience; public int ExpToLevel; public List<int> ExperienceTable = new List<int>(); public int Level; public int MPcur, MPmax, MPregen = 5; public int ArmorClass, ArmorAbsorb; public int Spellcasting; public int Perception, Stealth, Thievery, Traps, Picklocks, Tracking, MartialArts, MagicResist; public int Strength, Agility, Intellect, Willpower, Health, Charm; public readonly CharacterInventory Inventory = new CharacterInventory(); public int MaxEncumbrance; public EncumbranceState EncumbranceState; public long TotalBankBalances; public bool InCombat; public DateTime NextCombatCheck; public bool Resting; public List<Spell> KnownSpells = new List<Spell>(); public List<CombatAction> Attacks = new List<CombatAction>(); public DateTime LastSpellcast; public CombatAction CurrentAttackAction; public Alignment Alignment = Alignment.Neutral; public DateTime LastLogin; public DateTime LastLogout; public int ExpThisSession; public Character() { Attacks.Add(Backstab.Instance); Attacks.Add(Bash.Instance); Attacks.Add(Attack.Instance); } public void MergeValues(Character oldChar) { if (oldChar == null) return; this.Class = this.Class ?? oldChar.Class; this.Guild = this.Guild ?? oldChar.Guild; this.Race = this.Race ?? oldChar.Race; MergeFromOld(ref Lives, oldChar.Lives); MergeFromOld(ref CharacterPoints, oldChar.CharacterPoints); MergeFromOld(ref Experience, oldChar.Experience); MergeFromOld(ref Level, oldChar.Level); MergeFromOld(ref MPregen, oldChar.MPregen); MergeFromOld(ref HPregen, oldChar.HPregen); MergeFromOld(ref HPmax, oldChar.HPmax); MergeFromOld(ref MPmax, oldChar.MPmax); MergeFromOld(ref ArmorClass, oldChar.ArmorClass); MergeFromOld(ref ArmorAbsorb, oldChar.ArmorAbsorb); MergeFromOld(ref Spellcasting, oldChar.Spellcasting); MergeFromOld(ref Perception, oldChar.Perception); MergeFromOld(ref Thievery, oldChar.Thievery); MergeFromOld(ref Traps, oldChar.Traps); MergeFromOld(ref Picklocks, oldChar.Picklocks); MergeFromOld(ref Tracking, oldChar.Tracking); MergeFromOld(ref MartialArts, oldChar.MartialArts); MergeFromOld(ref MagicResist, oldChar.MagicResist); MergeFromOld(ref Strength, oldChar.Strength); MergeFromOld(ref Agility, oldChar.Agility); MergeFromOld(ref Intellect, oldChar.Intellect); MergeFromOld(ref Willpower, oldChar.Willpower); MergeFromOld(ref Health, oldChar.Health); MergeFromOld(ref Charm, oldChar.Charm); MergeFromOld(ref MaxEncumbrance, oldChar.MaxEncumbrance); if (oldChar.LastLogin > this.LastLogin) this.LastLogin = oldChar.LastLogin; if (oldChar.LastLogout > this.LastLogout) this.LastLogout = oldChar.LastLogout; for (int i = 0; i < oldChar.ExperienceTable.Count; i++) { if (i == this.ExperienceTable.Count) this.ExperienceTable.Add(oldChar.ExperienceTable[i]); else this.ExperienceTable[i] = oldChar.ExperienceTable[i]; } foreach (var attack in oldChar.Attacks) if (!this.Attacks.Any(s => s.ToString() == attack.ToString())) this.Attacks.Add(attack); foreach (var spell in oldChar.KnownSpells) if (!this.KnownSpells.Any(s => s.FullName == spell.FullName)) this.KnownSpells.Add(spell); } private void MergeFromOld(ref int value, int oldValue) { if (value == 0) value = oldValue; } public override string ToString() { if (LastName != null) return Name + " " + LastName; else return Name; } public string FormatSessionExperience() { double hours; if (LastLogout > LastLogin) hours = (LastLogout - LastLogin).TotalHours; else hours = (DateTime.UtcNow - LastLogin).TotalHours; if (hours > 0) return ExpThisSession + " (" + Math.Round(ExpThisSession / hours) + "/hr)"; else return ExpThisSession.ToString(); } public int NextLevelExp { get { if (ExpToLevel > 0) return Experience + ExpToLevel; if (Level > 0 && Level + 1 < ExperienceTable.Count) { var exp = ExperienceTable[Level + 1]; if (exp > 0) return exp; } return Experience; } } public bool TryParseStatLine(MudMaster owner, byte[] currentLine, int length) { // hardcoded for now, expect statline to be // set statline full custom [%h/%m/%X]:%r int exp, hp, mana; int ix = length - 1; if (currentLine.Expect1(ref ix, ':')) { if (!currentLine.Expect1(ref ix, ']')) return false; if (!currentLine.Extract(ref ix, out exp)) return false; if (!currentLine.Expect1(ref ix, '/')) return false; if (!currentLine.Extract(ref ix, out mana)) return false; if (!currentLine.Expect1(ref ix, '/')) return false; if (!currentLine.Extract(ref ix, out hp)) return false; if (!currentLine.Expect1(ref ix, '[')) return false; if (ix > 0) return false; } else { bool resting = length == " (Resting) ".Length && currentLine.ExpectString(ref ix, " (Resting) "); if (resting) { this.Resting = true; BreakStealth(); } return resting; } string priorLine = owner.historicalLines.GetFromEnd(0); if (priorLine != null && priorLine.StartsWith("\0\0\0") && !priorLine.EndsWith(" (Resting) ")) this.Resting = false; if (hp > HPmax) HPmax = hp; if (mana > MPmax) MPmax = mana; if (this.MPcur != mana || this.HPcur != hp) { this.MPcur = mana; this.HPcur = hp; owner.Reactors.AddTrigger(Trigger.HPandMana); } if (this.ExpToLevel != exp) { this.ExpToLevel = exp; owner.Reactors.AddTrigger(Trigger.Experience); } return true; } public void ParseStats(MudMaster owner, RollingBuffer<string> data) { bool hadName = Name != null; int i; for (i = 0; i < 20; i++) { var line = data.GetFromEnd(i); if (line.Length < 40) continue; if (line.StartsWith("Name:")) { int ix = line.IndexOf("Lives/CP:"); ParseStat(line.Substring(ix)); ParseStat(line.Substring(0, ix)); break; } string right = line.TrimSubstring(39); ParseStat(right); string middle = line.TrimSubstring(18, 21); ParseStat(middle); string left = line.TrimSubstring(0, 18); ParseStat(left); owner.Reactors.AddTrigger(Trigger.Stats); } if (!hadName && Name != null) { owner.beastiary.SetKnownCharacter(this); } } private void ParseStat(string part) { int ix = part.IndexOf(':'); if (ix < 0) return; string section = null, remaining = null; int value1 = -1, value2 = -1; section = part.Substring(0, ix); int numix = part.Length - 1; if (part.GetPrevInt(ref numix, out value2)) { if (part.ExpectPrevString(ref numix, "/")) part.GetPrevInt(ref numix, out value1); else { value1 = value2; value2 = -1; } } else { remaining = part.TrimSubstring(ix + 1); } AssignStat(section, remaining, value1, value2); } private void AssignStat(string section, string value, int intValue1, int intValue2) { switch (section) { case "Name": if (value != null) { int spaceIx = value.IndexOf(' '); if (spaceIx > 0) { Name = value.Substring(0, spaceIx); LastName = value.Substring(spaceIx + 1); } else { Name = value; LastName = string.Empty; } } break; case "Lives/CP": Lives = intValue1; CharacterPoints = intValue2; break; case "Mana": MPcur = intValue1; MPmax = intValue2; break; case "Hits": HPcur = intValue1; HPmax = intValue2; break; case "Armour Class": ArmorClass = intValue1; ArmorAbsorb = intValue2; break; case "Race": Race = value; break; case "Exp": Experience = intValue1; break; case "Perception": Perception = intValue1; break; case "Class": Class = value; break; case "Level": Level = intValue1; break; case "Stealth": Stealth = intValue1; break; case "Thievery": Thievery = intValue1; break; case "Spellcasting": Spellcasting = intValue1; break; case "Traps": Traps = intValue1; break; case "Picklocks": Picklocks = intValue1; break; case "Strength": Strength = intValue1; break; case "Agility": Agility = intValue1; break; case "Intellect": Intellect = intValue1; break; case "Health": Health = intValue1; break; case "Willpower": Willpower = intValue1; break; case "Charm": Charm = intValue1; break; case "Tracking": Tracking = intValue1; break; case "Martial Arts": MartialArts = intValue1; break; case "MagicRes": MagicResist = intValue1; break; default: return; } } public static void ParseLook(MudMaster owner) { string charNameLine = null; List<string> descriptionLines = new List<string>(); List<string> inventoryLines = new List<string>(); bool foundEquipped = false; for (int i = 1; i < 100; i++) { string line = owner.historicalLines.GetFromEnd(i); if (string.IsNullOrEmpty(line)) continue; if (foundEquipped) { if (line.Length > 4 && line.StartsWith("[ ") && line.EndsWith(" ]")) { charNameLine = line.Substring(2, line.Length - 4); break; } else descriptionLines.Add(line); } else { if (line == "He is equipped with:") foundEquipped = true; else inventoryLines.Add(line); } } if (charNameLine != null) { descriptionLines.Reverse(); inventoryLines.Reverse(); string name = charNameLine; if (charNameLine.Contains(' ')) { int spaceIx = charNameLine.IndexOf(' '); name = charNameLine.Substring(0, spaceIx); } var character = owner.beastiary.GetAsPlayingCharacter(owner, name); character.ParseLookDescription(owner, string.Join(" ", descriptionLines)); character.Inventory.ParseLookInventory(owner, inventoryLines); } } private void ParseLookDescription(MudMaster owner, string descriptionLines) { int ix = 0; string name; string health, strength, race, className, agility, charm, intellect, wisdom, damaged; descriptionLines.GetNextWord(ref ix, out name); if (!descriptionLines.ExpectNextString(ref ix, " is a ")) return; if (!descriptionLines.GetNextUntil(ref ix, ", ", out health)) return; string strengthRaceClass; if (!descriptionLines.GetNextUntil(ref ix, " with ", out strengthRaceClass)) return; int startIx = strengthRaceClass.Length - 1; if (!strengthRaceClass.GetPrevWord(ref startIx, out className)) return; if (!strengthRaceClass.GetPrevWord(ref startIx, out race)) return; strengthRaceClass.SkipPrevSpaces(ref startIx); strength = strengthRaceClass.Substring(0, startIx + 1); ix = descriptionLines.IndexOf(".", ix); if (!descriptionLines.ExpectNextString(ref ix, ". He moves ")) return; if (!descriptionLines.GetNextUntil(ref ix, ", and is ", out agility)) return; startIx = ix; ix = descriptionLines.IndexOf(".", ix); if (ix < 0) return; charm = descriptionLines.SubstringRange(startIx, ix - 1); if (!descriptionLines.ExpectNextString(ref ix, ". ") || !descriptionLines.ExpectNextString(ref ix, name) || !descriptionLines.ExpectNextString(ref ix, " appears to be ")) return; if (!descriptionLines.GetNextUntil(ref ix, " and ", out intellect)) return; startIx = ix; ix = descriptionLines.IndexOf(".", ix); if (ix < 0) return; wisdom = descriptionLines.SubstringRange(startIx, ix - 1); if (!descriptionLines.ExpectNextString(ref ix, ". He is ")) return; damaged = descriptionLines.SubstringRange(ix, descriptionLines.Length - 2); TryParseLookStat(ref this.Health, health); TryParseLookStat(ref this.Strength, strength); TryParseLookStat(ref this.Agility, agility); TryParseLookStat(ref this.Charm, charm); TryParseLookStat(ref this.Intellect, intellect); TryParseLookStat(ref this.Willpower, wisdom); this.Race = race; this.Class = className; } private void TryParseLookStat(ref int value, string description) { int min = 0, max = 0; switch (description) { case "sickly": min = 0; max = 29; break; case "frail": min = 30; max = 39; break; case "thin": min = 40; max = 49; break; case "healthy": min = 50; max = 59; break; case "stout": min = 60; max = 69; break; case "solid": min = 70; max = 79; break; case "massive": min = 80; max = 89; break; case "gigantic": min = 90; max = 99; break; case "colossal": min = 100; max = 200; break; case "puny": min = 0; max = 29; break; case "weak": min = 30; max = 39; break; case "slightly built": min = 40; max = 49; break; case "moderately built": min = 50; max = 59; break; case "well built": min = 60; max = 69; break; case "muscular": min = 70; max = 79; break; case "powerfully built": min = 80; max = 89; break; case "heroically proportioned": min = 90; max = 99; break; case "Herculean": min = 100; max = 109; break; case "physically Godlike": min = 110; max = 200; break; case "slowly": min = 0; max = 29; break; case "clumsily": min = 30; max = 39; break; case "sluggishly": min = 40; max = 49; break; case "cautiously": min = 50; max = 59; break; case "gracefully": min = 60; max = 69; break; case "very swiftly": min = 70; max = 79; break; case "with uncanny speed": min = 80; max = 89; break; case "with catlike agility": min = 90; max = 99; break; case "blindingly fast": min = 100; max = 200; break; case "openly hostile and quite revolting": min = 0; max = 29; break; case "hostile and rather unappealing": min = 30; max = 39; break; case "quite unfriendly and aloof": min = 40; max = 49; break; case "likeable in an unassuming sort of way": min = 50; max = 59; break; case "quite attractive and pleasant to be around": min = 60; max = 69; break; case "charismatic and outgoing": min = 70; max = 79; break; case "extremely likeable, and fairly radiates charisma": min = 80; max = 89; break; case "incredibly charismatic": min = 90; max = 99; break; case "overwhelmingly charismatic": min = 100; max = 200; break; case "utterly moronic": min = 0; max = 29; break; case "quite stupid": min = 30; max = 39; break; case "slightly dull": min = 40; max = 49; break; case "intelligent": min = 50; max = 59; break; case "bright": min = 60; max = 69; break; case "extremely clever": min = 70; max = 79; break; case "brilliant": min = 80; max = 89; break; case "a genius": min = 90; max = 99; break; case "all-knowing": min = 100; max = 200; break; case "seems selfish and hot-tempered": min = 0; max = 29; break; case "seems sullen and impulsive": min = 30; max = 39; break; case "seems a little naive": min = 40; max = 49; break; case "looks fairly knowledgeable": min = 50; max = 59; break; case "looks quite experienced and wise": min = 60; max = 69; break; case "has a worldly air about him": min = 70; max = 79; break; case "seems to possess a wisdom beyond his years": min = 80; max = 89; break; case "seems to be in an enlightened state of mind": min = 90; max = 99; break; case "looks like he is on with the Gods": min = 100; max = 200; break; } if (max == 0) return; if (value > max || value < min) value = (min + max) / 2; } public bool ParseTraining(MudMaster owner, string line) { if (!line.StartsWith("You hand over ")) return false; int ix = line.Length - 2; int newLevel; if (!line.GetPrevInt(ref ix, out newLevel) || newLevel < 2 || newLevel > 100) return false; if (!line.ExpectPrevString(ref ix, " and you receive training to attain level ")) return false; string cost = line.SubstringRange("You hand over ".Length, ix); this.Inventory.HandleMoneyExchange(owner, cost, true); this.Level = newLevel; owner.Reactors.AddTrigger(Trigger.Stats); return true; } public bool ParseExpGain(MudMaster owner, string line) { if (!(line.EndsWith("experience.") && line.StartsWith("You gain "))) return false; NPC target = null; for (int i = 1; i < 3; i++) { string priorLine = owner.historicalLines.GetFromEnd(i); if (priorLine.StartsWith("\0\0\0")) continue; if (!owner.beastiary.NPCDeathThroes.Contains(priorLine)) { owner.beastiary.NPCDeathThroes.Add(priorLine); } if (owner.curCharacter.Location != null) target = owner.curCharacter.Location.HandleNPCDeathThroe(owner, priorLine); break; } int ix = line.IndexOf(" experience."); int exp; if (line.GetPrevInt(ref ix, out exp)) { this.NextCombatCheck = DateTime.MinValue; this.Experience += exp; this.ExpThisSession += exp; if (target != null && exp > target.type.ExperienceValue) target.type.ExperienceValue = exp; owner.Reactors.AddTrigger(Trigger.Experience); } return true; } public bool ParseExpLine(MudMaster owner, string line) { if (!(line.StartsWith("Exp: ") && line.EndsWith("]") && line.Contains("Exp needed for next level: "))) return false; int ix = line.IndexOf("Exp:"); int exp, level, expToLevel, expTable; if (ix < 0) return false; ix += "Exp:".Length; if (!line.GetPrevInt(ref ix, out exp)) return false; ix = line.IndexOf("Level:"); if (ix < 0) return false; ix += "Level:".Length; if (!line.GetPrevInt(ref ix, out level)) return false; ix = line.IndexOf("Exp needed for next level:"); if (ix < 0) return false; ix += "Exp needed for next level:".Length; if (!line.GetPrevInt(ref ix, out expToLevel)) return false; while (ix < line.Length && line[ix] != '(') ix++; ix++; if (ix >= line.Length) return false; if (!line.GetPrevInt(ref ix, out expTable)) return false; if (this.Experience != exp || this.Level != level || this.ExpToLevel != expToLevel) { this.Experience = exp; this.Level = level; this.ExpToLevel = expToLevel; while (level >= ExperienceTable.Count) ExperienceTable.Add(0); ExperienceTable[level] = expTable; owner.Reactors.AddTrigger(Trigger.Experience); } return true; } public void ParseExpTable(MudMaster owner) { for (int i = 0; i < 20; i++) { var line = owner.historicalLines.GetFromEnd(i); int ix = 0; int level, exp; if (line.GetNextInt(ref ix, out level) && line.GetNextInt(ref ix, out exp) && level < 150) { while (level >= ExperienceTable.Count) ExperienceTable.Add(0); ExperienceTable[level] = exp; } else break; } } public void AttackTarget(MudMaster owner, CharacterBase target) { CurrentlyAttacking = target; CurrentAttackAction = null; NextCombatCheck = DateTime.UtcNow.AddMilliseconds(Config.RoundDurationMilliseconds); foreach (var action in Attacks) { if (action.CanUse(owner, target)) { if (action != CurrentAttackAction || (!InCombat && DateTime.UtcNow >= NextCombatCheck)) { action.Use(owner, target); } return; } } owner.SendText("attack " + target.NameAsTarget + "\r\n"); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.IO; using System.Net; using System.Net.Sockets; namespace MudClient { public interface IConnection { void QueueSend(byte[] data); void Disconnect(); event Action DataReceived; event Action Disconnected; byte[] DequeueReceieved(); } public class MockConnection : IConnection { public void QueueSend(byte[] data) { } public void Disconnect() { } public event Action DataReceived; public event Action Disconnected; public byte[] DequeueReceieved() { return null; } public void FakeCallEventsToAvoidWarnings() { DataReceived(); Disconnected(); throw new NotSupportedException(); } } public class Connection : IConnection { private TcpClient client; private Thread sendThread, receiveThread; private Queue<byte[]> SendBuffers = new Queue<byte[]>(); private Queue<byte[]> ReceiveBuffers = new Queue<byte[]>(); private volatile bool connected; public event Action DataReceived; public event Action Disconnected; public void Connect(string host, int port) { client = new TcpClient(); client.Connect(host, port); connected = true; sendThread = new Thread(SendLoop); receiveThread = new Thread(ReceiveLoop); sendThread.Name = "Send thread"; receiveThread.Name = "Receive thread"; sendThread.IsBackground = true; receiveThread.IsBackground = true; sendThread.Start(); receiveThread.Start(); } public void Disconnect() { try { lock (SendBuffers) { connected = false; Monitor.Pulse(SendBuffers); client.Close(); client = null; } } catch { } } public void QueueSend(byte[] data) { if (data == null || data.Length == 0) return; lock (SendBuffers) { SendBuffers.Enqueue(data); Monitor.Pulse(SendBuffers); } } public byte[] DequeueReceieved() { lock (ReceiveBuffers) { if (ReceiveBuffers.Count == 0) return null; return ReceiveBuffers.Dequeue(); } } private void SendLoop() { try { byte[] buffer; while (connected) { lock (SendBuffers) { if (SendBuffers.Count == 0) Monitor.Wait(SendBuffers); buffer = SendBuffers.Dequeue(); } client.Client.Send(buffer); } } catch { } } private void ReceiveLoop() { try { Thread.Sleep(2000); NativeMethods.SetThreadExecutionState( NativeMethods.EXECUTION_STATE.ES_CONTINIOUS | NativeMethods.EXECUTION_STATE.ES_SYSTEM_REQUIRED); var reads = new Socket[] { client.Client }; var writes = new Socket[0]; while (connected) { reads[0] = client.Client; Socket.Select(reads, writes, reads, -1); if (client.Available == 0) { connected = false; return; } byte[] data = new byte[client.Available]; client.Client.Receive(data); Console.WriteLine("Received " + data.Length + " bytes = " + Encoding.Default.GetString(data).Replace(((char)27).ToString(), "^[")); lock (ReceiveBuffers) { ReceiveBuffers.Enqueue(data); } var act = DataReceived; if (act != null) act(); } } catch { } finally { OnDisconnected(); } } private void OnDisconnected() { try { if (Disconnected != null) Disconnected(); } catch { } } private static class NativeMethods { public enum EXECUTION_STATE : uint { ES_AWAYMODE_REQUIRED = 0x40, ES_CONTINIOUS = 0x80000000, ES_DISPLAY_REQUIRED = 0x02, ES_SYSTEM_REQUIRED = 0x01, ES_USER_PRESENT = 0x04,// legacy value, do not use } [System.Runtime.InteropServices.DllImport("kernel32.dll")] public static extern uint SetThreadExecutionState(EXECUTION_STATE state); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MudClient { public class ProtocolTelnet : Protocol { int escapeCount = -1; byte[] escapeChars = new byte[20]; public override bool HandleChar(byte c) { if (escapeCount >= 0) return HandleEscapeSequence(c); else if (c == 255) { escapeCount = 0; return true; } return false; } private static class Opts { public const byte SupressGoAhead = 3; public const byte Status = 5; public const byte Echo = 1; public const byte TimingMark = 6; public const byte TerminalType = 24; public const byte WindowSize = 31; public const byte TerminalSpeed = 32; public const byte RemoteFlowControl = 33; public const byte LineMode = 34; public const byte EnvironmentVariables = 36; public const byte EndOfSubnegotiation = 240; public const byte NOP = 241; public const byte DataMark = 242; public const byte Break = 243; public const byte Suspend = 244; public const byte AbortOutput = 245; public const byte AreYouThere = 246; public const byte EraseCharacter = 247; public const byte EraseLine = 248; public const byte GoAhead = 249; public const byte Subnegotiation = 250; public const byte Will = 251; public const byte Wont = 252; public const byte Do = 253; public const byte Dont = 254; public const byte Command = 255; } private bool HandleEscapeSequence(byte c) { if (escapeCount + 1 < escapeChars.Length) escapeChars[escapeCount++] = c; switch (escapeChars[0]) { case Opts.Subnegotiation: // subnegotiation if (c == Opts.EndOfSubnegotiation) { escapeCount = -1; return false; } break; case Opts.Do: // do if (escapeCount == 2) { connection.QueueSend(new byte[] { Opts.Command, Opts.Will, c }); escapeCount = -1; } break; case Opts.Dont: // don't if (escapeCount == 2) { connection.QueueSend(new byte[] { Opts.Command, Opts.Wont, c }); // won't escapeCount = -1; } break; case Opts.Command: // interpret as command if (escapeCount > 0) escapeCount--; break; case Opts.EndOfSubnegotiation: // end of subnegotion parameters case Opts.NOP: // NOP case Opts.DataMark: // data mark case Opts.Break: // break case Opts.Suspend: // suspend case Opts.AbortOutput: // abort output case Opts.AreYouThere: // are you there case Opts.EraseCharacter: // erase character case Opts.EraseLine: // erase line case Opts.GoAhead: // go ahead case Opts.Will: // will case Opts.Wont: // won't default: escapeCount = -1; return false; } return true; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MudClient { public abstract class Protocol { protected TerminalState state; protected IConnection connection; public void SetState(TerminalState state) { this.state = state; } public void SetConnection(IConnection connection) { this.connection = connection; } public abstract bool HandleChar(byte c); } } <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 MudClient.MM { public partial class frmChat : Form { public frmChat() { InitializeComponent(); this.act = new UpdateScreenAction(this); } protected override void OnClosing(CancelEventArgs e) { base.OnClosing(e); act.Remove = true; } private UpdateScreenAction act; private MudMaster mud; public void SetMud(MudMaster mudMaster) { lastCount = 0; this.txtHistory.Clear(); this.mud = mudMaster; mud.Reactors.AddExternalScript(act); RefreshText(); } private int lastCount; public void RefreshText() { while (lastCount < mud.Speech.Count) this.txtHistory.AppendText(mud.Speech[lastCount++] + "\r\n"); } private class UpdateScreenAction : BaseReactor { private frmChat owner; public UpdateScreenAction(frmChat owner) : base(Trigger.Speech) { this.owner = owner; } public override void Execute(Trigger triggers, MudMaster owner) { if (this.owner.IsDisposed) this.Remove = true; else this.owner.RefreshText(); } } private void btnSend_Click(object sender, EventArgs e) { SendText(); } private void SendText() { string text = txtMessage.Text; if (string.IsNullOrWhiteSpace(text)) { txtMessage.Text = string.Empty; return; } string prefix = "."; if (rbAuction.Checked) prefix = "auction "; else if (rbGossip.Checked) prefix = "gossip "; else if (rbSay.Checked) prefix = "."; else if (rbWhisper.Checked) { string who = cboWhisperTo.Text; if (!string.IsNullOrEmpty(who)) { prefix = "/" + who.Trim(); } } else if (rbYell.Checked) prefix = "\""; else return; mud.SendText(prefix + text); txtMessage.Text = string.Empty; } } } <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 MudClient.MM { public partial class frmCurrentRoom : Form { private UpdateScreenAction act; public frmCurrentRoom() { InitializeComponent(); act = new UpdateScreenAction(this); } protected override void OnClosing(CancelEventArgs e) { base.OnClosing(e); act.Remove = true; } private MudMaster mud; public void SetMud(MudMaster mudMaster) { this.mud = mudMaster; this.mud.Reactors.AddExternalScript(act); RefreshRoom(); } private void RefreshRoom() { lblExits.Text = null; lblItems.Text = null; lblWho.Text = null; if (mud == null || mud.curCharacter.Location == null) return; var loc = mud.curCharacter.Location; this.Text = loc.Title; lblExits.Text = string.Join(", ", loc.Exits); lblItems.Text = string.Join(", ", loc.ItemInRoom.Items); lblWho.Text = string.Join(", ", loc.NPCInRoom); } private class UpdateScreenAction : BaseReactor { private frmCurrentRoom owner; public UpdateScreenAction(frmCurrentRoom owner) : base(Trigger.RoomCharacters | Trigger.RoomItems) { this.owner = owner; } public override void Execute(Trigger triggers, MudMaster owner) { this.owner.RefreshRoom(); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MudClient.MM { public class Beastiary { private Dictionary<string, NPCType> knownNPCs = new Dictionary<string, NPCType>(); private Dictionary<string, Character> knownPCs = new Dictionary<string, Character>(); public static readonly string[] NPCMoveVerbs = new string[] { " sneaks", " creeps", " oozes", " crawls", " scuttles", " walks", " strides", " stomps", " moves", " shambles", " lopes", " materializes", " flaps", }; public readonly HashSet<string> NPCDeathThroes = new HashSet<string>(); //public static readonly string[] NPCDeathThroes = new string[] //{ // " falls to the ground ", // " falls dead at your feet.", // " dissolves into a puddle ", // " collapses, its ", // " collapses with a ", //}; private static string[] Prefixes = new string[] { "angry", "small", "short", "big", "fat", "fierce", "nasty", "thin", "large", "tall", "happy", }; public IEnumerable<NPCType> GetNpcTypes() { return knownNPCs.Values; } public IEnumerable<Character> GetCharacters() { return knownPCs.Values; } public void SetKnownCharacter(Character character) { if (character.Name == null) return; Character oldChar; if (knownPCs.TryGetValue(character.Name, out oldChar)) { if (oldChar == character) return; character.MergeValues(oldChar); } knownPCs[character.Name] = character; } public NPCType FindOrAdd(string name) { string prefix = null; foreach (var p in Prefixes) { if (name.StartsWith(p)) { prefix = p; name = name.Substring(prefix.Length + 1); break; } } NPCType result; if (!knownNPCs.TryGetValue(name, out result)) { result = new NPCType(); result.Name = name; knownNPCs[name] = result; } return result; } public void ParseWho(MudMaster owner) { for (int i = 0; i < 256; i++) { string line = owner.historicalLines.GetFromEnd(i); if (line == null || line == " ===================" || line == " Current Adventurers") break; string alignment, firstname, lastname, classTitle, guild; Alignment align = 0; int ix = 0; string temp; if (!line.GetNextWord(ref ix, out temp)) continue; switch (temp) { case "Lawful": case "Good": case "Saint": align = Alignment.Good; goto case null; case "Seedy": case "Outlaw": case "Villain": case "FIEND": align = Alignment.Evil; goto case null; case null: alignment = temp; if (!line.GetNextWord(ref ix, out temp)) continue; break; default: align = Alignment.Neutral; alignment = "Neutral"; break; } firstname = temp; bool hasLastName = line.GetNextWord(ref ix, out temp); line.SkipNextSpaces(ref ix); if (!(line.ExpectNextString(ref ix, "- ") || line.ExpectNextString(ref ix, "x "))) hasLastName = false; lastname = hasLastName ? temp : null; int ofIndex = line.IndexOf(" of ", ix); if (ofIndex > 0) { classTitle = line.SubstringRange(ix, ofIndex); guild = line.TrimSubstring(ofIndex + " of ".Length); } else { classTitle = line.TrimSubstring(ix); guild = null; } Character cur; if (!knownPCs.TryGetValue(firstname, out cur)) { cur = new Character(); cur.Name = firstname; knownPCs[firstname] = cur; } cur.LastName = lastname; cur.Guild = guild; cur.Alignment = align; if (cur.Class == null) cur.Class = classTitle; } } public CharacterBase GetPlayingCharacterOrNPC(MudMaster owner, string Name) { Character character; if (knownPCs.TryGetValue(Name, out character)) return character; else { var type = FindOrAdd(Name); return new NPC(type, Name); } } public Character GetAsPlayingCharacter(MudMaster owner, string Name) { knownNPCs.Remove(Name); Character result; if (!knownPCs.TryGetValue(Name, out result)) { result = new Character(); result.Name = Name; knownPCs[Name] = result; } return result; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MudClient { public class ProtocolVT100 : Protocol { bool escaped; int escapeIx; byte[] escapeChars = new byte[256]; public override bool HandleChar(byte c) { if (escaped) { if ((c >= 'A' && c <= 'Z') || c >= 'a' && c <= 'z') { escaped = false; HandleEscapeSeq(c); } else if (c < 32 || c > 127) { escaped = false; return false; } else if (escapeIx + 1 < escapeChars.Length) { escapeChars[escapeIx++] = c; } return true; } else if (c == 27) { escaped = true; return true; } return false; } private int savedRow, savedCol; private bool HandleEscapeSeq(byte c) { if (escapeChars[0] == '[') { switch ((char)c) { case 'H': // line;column case 'f': // line;column int row, col; if (ReadEscapeInt(out col) && c == 'f') col--; ReadEscapeSemicolon(); ReadEscapeInt(out row); state.MoveCursorTo(row, col); break; case 'A': // cursor up if (escapeIx == 1) state.MoveCursorBy(-state.ColumnCount); break; case 'B': // cursor down if (escapeIx == 1) state.MoveCursorBy(state.ColumnCount); break; case 'C': // cursor forward if (escapeIx == 1) state.MoveCursorBy(1); break; case 'D': // cursor back if (escapeIx == 1) state.MoveCursorBy(-1); break; case 's': // save cursor if (escapeIx == 1) { savedRow = state.CursorY; savedCol = state.CursorX; } break; case 'u': // restore cursor if (escapeIx == 1) state.MoveCursorTo(savedRow, savedCol); break; case 'J': // clear screen "2J" int x = 0; if (escapeIx == 1 || ReadEscapeInt(out x)) { switch (x) { case 0: for (int i = state.CursorY; i < state.RowCount; i++) state.EraseLine(i); break; case 1: for (int i = state.CursorY; i >= 0; i--) state.EraseLine(i); break; case 2: for (int i = 0; i < state.RowCount; i++) state.EraseLine(i); break; } } break; case 'K': // erase line //x = 0; //if (escapeIx == 1 || ReadEscapeInt(out x)) //{ // var crow = rows[currentRow]; // switch (x) // { // case 0: // for (int i = currentCol; i < colCount; i++) // crow[i] = 0; // break; // case 1: // for (int i = 0; i < currentCol; i++) // crow[i] = 0; // break; // case 2: // for (int i = 0; i < colCount; i++) // crow[i] = 0; // break; // } //} break; case 'm': // graphics mode do { if (ReadEscapeInt(out x)) { if (x == 0) { state.ForeColor = 7; state.BackColor = 0; } else if (x >= 30 && x <= 37) state.ForeColor = (byte)(x - 30); else if (x >= 40 && x <= 47) state.BackColor = (byte)(x - 40); } } while (ReadEscapeSemicolon()); break; case 'h': // screen mode break; case 'l': // reset mode break; case 'p': // keyboard settings break; default: // unknown escape sequence char escapeIx = 0; return false; } } escapeIx = 0; return true; } private bool EscapeEmpty() { return escapeIx == 1; } private bool ReadEscapeSemicolon() { int ix = escapeIx - 1; if (ix < 0 || escapeChars[ix] != ';') return false; escapeIx--; return true; } private bool ReadEscapeInt(out int result) { result = 0; int mult = 1; int ix = escapeIx - 1; while (ix >= 0 && mult < 1000000) { byte b = escapeChars[ix]; if (b >= '0' && b <= '9') { result += mult * (b - '0'); escapeIx--; ix--; mult *= 10; } else break; } return mult > 1; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MudClient.MM { public class EventReactors { private readonly List<BaseReactor> scripts = new List<BaseReactor>(); public bool Enabled { get; set; } public AutoPickupAction Pickup; public AutoDepositAction Deposit; public AutoBuySellAction BuySell; public AutoHealAction Heal; public AutoBuffAction Buff; public AutoSearchAction Search; public AutoAttackAction Attack; //public AutoSneakAction Sneak; public AutoRestAction Rest; public MoveToAction Move; public AI AI; public EventReactors() { scripts.Clear(); Pickup = new AutoPickupAction(); Deposit = new AutoDepositAction(); BuySell = new AutoBuySellAction(); Heal = new AutoHealAction(); Buff = new AutoBuffAction(); Search = new AutoSearchAction(); Attack = new AutoAttackAction(); //Sneak = new AutoSneakAction(); Rest = new AutoRestAction(); Move = new MoveToAction(); AI = new AI(); scripts.Add(Pickup); scripts.Add(Deposit); scripts.Add(BuySell); scripts.Add(Heal); scripts.Add(Buff); scripts.Add(Search); scripts.Add(Attack); scripts.Add(Rest); //scripts.Add(Sneak); scripts.Add(Move); scripts.Add(AI); Enabled = true; } private Trigger scriptTriggers; public void CheckEvents(MudMaster owner) { if (scriptTriggers == Trigger.None || !Enabled) return; try { for (int i = 0; i < scripts.Count; i++) { var script = scripts[i]; if (((script.TriggerOn & scriptTriggers) != 0)) { if (script.Enabled) script.Execute(scriptTriggers, owner); if (script.Remove) scripts.RemoveAt(i--); } } } finally { scriptTriggers = Trigger.None; } } public void AddTrigger(Trigger trigger) { this.scriptTriggers |= trigger; } public void AddExternalScript(BaseReactor act) { this.scripts.Add(act); } } [Flags] public enum Trigger { None = 0, RoomCharacters = 1, RoomItems = 2, Death = 4, CombatState = 8, HPandMana = 16, Experience = 32, Inventory = 64, Timer = 128, Location = 256, Stats = 512, Map = 1024, Speech = 2048, Buffs = 4096, } public abstract class BaseReactor { public bool Enabled = true; public bool Remove = false; public readonly Trigger TriggerOn; public BaseReactor(Trigger triggerOn) { this.TriggerOn = triggerOn; } public abstract void Execute(Trigger triggers, MudMaster owner); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace MudClient { public class DataLoader : IConnection { private List<Protocol> protocols = new List<Protocol>(); private TerminalState state = new TerminalState(); public DataLoader() { } public void AddProtocols(params Protocol[] protocols) { this.protocols.AddRange(protocols); foreach (var proto in protocols) { proto.SetConnection(this); proto.SetState(state); } } public void ReadData(Stream stream) { byte[] buffer = new byte[1024]; while (true) { int bytes = stream.Read(buffer, 0, buffer.Length); if (bytes <= 0) return; for (int i = 0; i < bytes; i++) { byte b = buffer[i]; foreach (var proto in protocols) { try { if (proto.HandleChar(b)) break; } catch { } } } } } public void FakeCallEventsToAvoidWarnings() { DataReceived(); Disconnected(); throw new NotSupportedException(); } public event Action DataReceived; public event Action Disconnected; void IConnection.QueueSend(byte[] data) { } void IConnection.Disconnect() { } byte[] IConnection.DequeueReceieved() { return null; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MudClient.MM { public class RouteDescription { public Direction direction; public string Barrier; public bool Passable; public bool Hidden; public RouteDescription(Direction direction) { this.direction = direction; } public RouteDescription(string text) { string[] parts = text.Split(' '); Passable = true; if (!Direction.TryParse(parts[parts.Length - 1], out direction)) direction = new Direction(parts[parts.Length - 1], null, 0, 0, 0); if (parts.Contains("closed")) Passable = false; else if (parts.Contains("open")) Passable = true; else if (parts.Contains("secret") || parts.Contains("Secret") || parts.Contains("passage") || parts.Contains("passageway")) Hidden = true; for (int i = parts.Length - 2; i > 0; i--) switch (parts[i]) { case "door": case "gate": Barrier = parts[i]; break; } } public bool Matches(RouteDescription other) { return this.direction == other.direction && Barrier == other.Barrier; } public override string ToString() { if (Barrier != null) { return (Passable ? "open " : "closed ") + Barrier + " " + direction; } else return direction.ToString(); } } public class Route { public RouteDescription Direction; public MapNode ConnectTo; public MapNode ConnectFrom; public Route Inverse; public bool Bashable; public bool Pickable; public string Key; public override string ToString() { if (Direction != null) return Direction.ToString(); return "Route???"; } public void Execute(MudMaster mud) { if (Direction != null && Direction.direction.Shortcut != null) { mud.SendText(Direction.direction.Shortcut + "\r\n"); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MudClient.MM { public struct Coordinate : IEquatable<Coordinate> { public readonly int X; public readonly int Y; public readonly int Z; public Coordinate(int X, int Y, int Z) { this.X = X; this.Y = Y; this.Z = Z; } public override string ToString() { return X + "," + Y + "," + Z; } public override int GetHashCode() { return X + Y * 91 + Z * 65371; // made up numbers, todo, improve the hashing } public override bool Equals(object obj) { return obj is Coordinate && ((Coordinate)obj).Equals(this); } public bool Equals(Coordinate other) { return this.X == other.X && this.Y == other.Y && this.Z == other.Z; } public static Coordinate operator +(Coordinate lhs, Direction rhs) { return new Coordinate(lhs.X + rhs.X, lhs.Y + rhs.Y, lhs.Z + rhs.Z); } public static Direction operator -(Coordinate lhs, Coordinate rhs) { return new Direction(null, null, lhs.X - rhs.X, lhs.Y - rhs.Y, lhs.Z - rhs.Z); } } public struct VirtualCoordinate : IEquatable<VirtualCoordinate> { public readonly Coordinate Value; public readonly int CoordinateSystemID; public VirtualCoordinate(Coordinate Value, int CoordinateSystemID) { this.Value = Value; this.CoordinateSystemID = CoordinateSystemID; } public override string ToString() { return Value.ToString() + "@" + CoordinateSystemID; } public override bool Equals(object obj) { return obj is VirtualCoordinate && ((VirtualCoordinate)obj).Equals(this); } public bool Equals(VirtualCoordinate other) { return this.Value.Equals(other.Value) && this.CoordinateSystemID == other.CoordinateSystemID; } public override int GetHashCode() { return Value.GetHashCode() + CoordinateSystemID * 789241; } public static VirtualCoordinate operator +(VirtualCoordinate lhs, Direction rhs) { return new VirtualCoordinate(lhs.Value + rhs, lhs.CoordinateSystemID); } } public struct Direction : IEquatable<Direction> { public readonly string Name; public readonly string Shortcut; private Coordinate Value; public int X { get { return Value.X; } } public int Y { get { return Value.Y; } } public int Z { get { return Value.Z; } } public Direction(string Name, string Shortcut, int X, int Y, int Z = 0) { this.Name = Name; this.Shortcut = Shortcut ?? Name; this.Value = new Coordinate(X, Y, Z); } public bool Valid { get { return X != 0 || Y != 0 || Z != 0; } } public override bool Equals(object obj) { return obj is Direction && this.Equals((Direction)obj); } public override int GetHashCode() { return X + (Y * 2) + (Z * 4); } public override string ToString() { return Name ?? "none"; } public bool Equals(Direction other) { return other.X == this.X && other.Y == this.Y && other.Z == this.Z; } public static bool operator ==(Direction lhs, Direction rhs) { return lhs.Equals(rhs); } public static bool operator !=(Direction lhs, Direction rhs) { return !lhs.Equals(rhs); } public static Direction operator -(Direction rhs) { return Find(-rhs.X, -rhs.Y, -rhs.Z); } public static Direction Find(int x, int y, int z) { foreach (var dir in Directions) { if (dir.X == x && dir.Y == y && dir.Z == z) return dir; } return new Direction("unknown", null, x, y, z); } public static bool TryParse(string s, out Direction result) { for (int i = 0; i < Directions.Length; i++) { var dir = Directions[i]; if (string.Equals(s, dir.Name, StringComparison.OrdinalIgnoreCase) || string.Equals(s, dir.Shortcut, StringComparison.OrdinalIgnoreCase)) { result = dir; return true; } } foreach (var special in SpecialDirections) { if (string.Equals(s, special.Name, StringComparison.OrdinalIgnoreCase) || string.Equals(s, special.Shortcut, StringComparison.OrdinalIgnoreCase)) { result = special; return true; } } result = new Direction(); return false; } public static Direction here = new Direction("here", null, 0, 0, 0); public static Direction north = new Direction("north", "n", 0, 1, 0); public static Direction south = new Direction("south", "s", 0, -1, 0); public static Direction east = new Direction("east", "e", 1, 0, 0); public static Direction west = new Direction("west", "w", -1, 0, 0); public static Direction northeast = new Direction("northeast", "ne", 1, 1, 0); public static Direction northwest = new Direction("northwest", "nw", -1, 1, 0); public static Direction southeast = new Direction("southeast", "se", 1, -1, 0); public static Direction southwest = new Direction("southwest", "sw", -1, -1, 0); public static Direction up = new Direction("up", "u", 0, 0, 1); public static Direction down = new Direction("down", "d", 0, 0, -1); public static readonly Direction[] Directions = new Direction[] { north, south, east, west, up, down, northeast, northwest, southeast, southwest, }; public static Direction EnterManhole = new Direction("manhole", "enter manhole", 0, 0, -1); public static Direction BorrowSkiff = new Direction("skiff", "borrow skiff", 0, -1, 0); public static Direction Below = new Direction("below", "d", 0, 0, -1); public static Direction Above = new Direction("above", "u", 0, 0, 1); public static Direction Invalidate = new Direction("invalidate", "invalidate", int.MinValue, int.MinValue, int.MinValue); public static readonly Direction[] SpecialDirections = new Direction[] { BorrowSkiff, EnterManhole, Below, Above, }; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MudClient.MM { public class Map { private Dictionary<VirtualCoordinate, MapNode> locByCoord = new Dictionary<VirtualCoordinate, MapNode>(); //private Dictionary<string, List<MapNode>> locByTitle = new Dictionary<string, List<MapNode>>(); private Dictionary<string, List<MapNode>> locByKey = new Dictionary<string, List<MapNode>>(); public readonly Banks banks = new Banks(); private int CurrentCoordinateSystem = 1; private readonly StringBuilder roomKeyBuffer = new StringBuilder(); public void Clear() { locByCoord.Clear(); locByKey.Clear(); CurrentCoordinateSystem++; } public MapNode HandleBlindMove(MudMaster owner, MapNode currentLocation, Direction direction) { if (currentLocation != null) { var newLoc = currentLocation.Location + direction; MapNode newNode; if (locByCoord.TryGetValue(newLoc, out newNode)) return newNode; newNode = new MapNode(owner, null); newNode.Location = newLoc; return newNode; } return null; } public MapNode FindOrMakeLocation(MudMaster owner, string title, MapNode currentLocation, Direction direction) { string roomKey, description; roomKey = GetRoomKeyFromBuffer(owner, title, out description); if (currentLocation != null && direction == Direction.here && currentLocation.RoomKey == roomKey) { currentLocation.LastSeen = DateTime.UtcNow; return currentLocation; } RollingBuffer<string> lines = owner.historicalLines; VirtualCoordinate newCoord; MapNode result; if (currentLocation != null && direction.Valid) { newCoord = currentLocation.Location + direction; if (locByCoord.TryGetValue(newCoord, out result)) { if (result != null && result.RoomKey == roomKey) { result.LastSeen = DateTime.UtcNow; return result; } else newCoord = new VirtualCoordinate(newCoord.Value, CurrentCoordinateSystem++); } } else { newCoord = new VirtualCoordinate(default(Coordinate), -1); } List<MapNode> list; result = FindByTextBuffer(owner, out list, roomKey, description); if (result != null && (newCoord.CoordinateSystemID != result.Location.CoordinateSystemID)) { if (MergeAt(result, newCoord)) owner.Reactors.AddTrigger(Trigger.Map); } else { // create a new node: result = new MapNode(owner, title); result.RoomKey = roomKey; if (newCoord.CoordinateSystemID >= 0) { result.Location = currentLocation.Location + direction; locByCoord[result.Location] = result; } else { result.Location = new VirtualCoordinate(new Coordinate(), CurrentCoordinateSystem++); locByCoord[result.Location] = result; } list.Add(result); if (currentLocation != null && direction != Direction.here) { var matchingExit = currentLocation.Exits.FirstOrDefault(e => e.Direction.direction == direction); if (matchingExit == null) { var newRoute = new Route { ConnectFrom = currentLocation, ConnectTo = result, Direction = new RouteDescription(direction) { Hidden = true }, }; currentLocation.Exits.Add(newRoute); } } owner.Reactors.AddTrigger(Trigger.Map); } ConnectAdjacent(result); result.LastSeen = DateTime.UtcNow; return result; } private string GetLastRoomKeyFromBuffer(MudMaster owner, string title) { string descr; return GetRoomKeyFromBuffer(owner, title, out descr); } private string GetRoomKeyFromBuffer(MudMaster owner, string title, out string description) { roomKeyBuffer.Clear(); roomKeyBuffer.Append(title); string itemLine, whoLine, exitLine; MapNode.ParseRoomIntoSections(owner, title, out description, out itemLine, out whoLine, out exitLine); if (exitLine != null) { var descriptions = MapNode.ParseExits(exitLine); foreach (var desc in descriptions) { if (desc.Hidden) continue; roomKeyBuffer.Append(desc.direction + desc.Barrier); } } return roomKeyBuffer.ToString(); } private MapNode FindByTextBuffer(MudMaster owner, out List<MapNode> list, string roomKey, string description) { if (!locByKey.TryGetValue(roomKey, out list)) { list = new List<MapNode>(); locByKey[roomKey] = list; return null; } foreach (var item in list) { if (item.Description == description) return item; } return null; } public MapNode FindByLocation(VirtualCoordinate coord) { MapNode result; if (locByCoord.TryGetValue(coord, out result)) return result; return null; } private bool MergeAt(MapNode node, VirtualCoordinate newCoord) { if (newCoord.CoordinateSystemID <= 0 || node.Location.CoordinateSystemID == newCoord.CoordinateSystemID) return false; var oldSystem = locByCoord.Values.Where(n => n.Location.CoordinateSystemID == node.Location.CoordinateSystemID).ToList(); var delta = newCoord.Value - node.Location.Value; foreach (var item in oldSystem) { locByCoord.Remove(item.Location); item.Location = new VirtualCoordinate(item.Location.Value + delta, newCoord.CoordinateSystemID); locByCoord[item.Location] = item; } return true; } private void ConnectAdjacent(MapNode node) { foreach (var exit in node.Exits) { exit.ConnectFrom = node; if (exit.ConnectTo == null) { var otherLoc = node.Location + exit.Direction.direction; if (locByCoord.TryGetValue(otherLoc, out exit.ConnectTo)) { foreach (var opp in exit.ConnectTo.Exits) { if (opp.Direction.direction == -exit.Direction.direction) { opp.ConnectTo = node; break; } } } } } } private int SearchForString(string searchFor, RollingBuffer<string> lines, int maxLines) { for (int i = 0; i < maxLines; i++) { if (lines.GetFromEnd(i).StartsWith(searchFor)) return i; } return -1; } public IEnumerable<MapNode> GetAllNodes() { foreach (var pair in this.locByCoord) yield return pair.Value; } public IEnumerable<MapNode> VisitInRadius(MapNode node, int radius, Predicate<MapNode> setNodeCenterCheck = null, Predicate<Route> canMove = null) { var visited = new HashSet<MapNode>(); var queue = new Queue<KeyValuePair<MapNode, int>>(); visited.Add(node); queue.Enqueue(new KeyValuePair<MapNode, int>(node, 0)); while (queue.Count > 0) { var cur = queue.Dequeue(); foreach (var exit in cur.Key.Exits) { var newNode = exit.ConnectTo; if (newNode == null || visited.Contains(newNode)) continue; if (canMove != null && !canMove(exit)) continue; visited.Add(newNode); int dist = cur.Value + 1; if (setNodeCenterCheck != null && setNodeCenterCheck(newNode)) dist = 0; if (dist < radius) queue.Enqueue(new KeyValuePair<MapNode, int>(newNode, dist)); } } return visited; } public IEnumerable<Route> FindRouteReverseOrder(MapNode from, MapNode to, Predicate<Route> canMove = null, int maxDistance = int.MaxValue) { return FindNearestRouteReverseOrder(from, node => node == to, canMove); } public IEnumerable<Route> FindNearestRouteReverseOrder(MapNode from, Predicate<MapNode> to, Predicate<Route> canMove = null, int maxDistance = int.MaxValue) { if (from == null || to(from)) yield break; var hashset = new Dictionary<MapNode, KeyValuePair<MapNode, int>>(); var queue = new Queue<MapNode>(); queue.Enqueue(from); hashset[from] = new KeyValuePair<MapNode, int>(null, 0); while (queue.Count > 0) { var cur = queue.Dequeue(); int dist = hashset[cur].Value + 1; if (dist > maxDistance) continue; foreach (var exit in cur.Exits) { if (exit.ConnectTo == null || hashset.ContainsKey(exit.ConnectTo)) continue; if (canMove != null && !canMove(exit)) continue; hashset[exit.ConnectTo] = new KeyValuePair<MapNode, int>(cur, dist); if (to(exit.ConnectTo)) { // found it: cur = exit.ConnectTo; MapNode next; while ((next = hashset[cur].Key) != null) { yield return next.GetRoute(cur); cur = next; } yield break; } queue.Enqueue(exit.ConnectTo); } } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MudClient.MM { public class AutoPickupAction : BaseReactor { public HashSet<string> PickupItems = new HashSet<string> { "runic", "platinum", "gold", "silver", "copper", }; public AutoPickupAction() : base(Trigger.RoomItems | Trigger.CombatState) { } private int ShouldPickUp(Item item, int available, MudMaster owner) { if (!PickupItems.Contains(item.Name)) return 0; float encRemaining = owner.curCharacter.MaxEncumbrance - owner.curCharacter.Inventory.Encumbrance - 100; int tryPickup = (int)Math.Floor(encRemaining / Math.Max(item.Weight, 1)); return Math.Min(tryPickup, available); } public override void Execute(Trigger triggers, MudMaster owner) { var me = owner.curCharacter; if (me.Resting) return; var here = me.Location; if (here == null) return; foreach (var item in here.ItemInRoom.Items.Concat(here.HiddenItems)) { if (item.Busy) continue; int pickup = ShouldPickUp(item.Item, item.Count, owner); if (pickup > 0) { item.Busy = true; if (item.Item.Type == ItemType.Currency) owner.SendText("get " + pickup + " " + item.Item.Name + "\r\n"); else { for (int i = Math.Min(5, pickup); i > 0; i--) { owner.SendText("get " + item.Item.Name + "\r\n"); } } } } } } public class AutoDepositAction : BaseReactor { public AutoDepositAction() : base(Trigger.Location) { } public override void Execute(Trigger triggers, MudMaster owner) { var me = owner.curCharacter; if (me.Location == null || me.Location.Bank == null) return; if (me.Inventory.Wealth > 0) { owner.SendText("deposit " + me.Inventory.Wealth + "\r\n"); } } } public class AutoRestAction : BaseReactor { private DateTime nextRest; public AutoRestAction() : base(Trigger.Timer) { } public override void Execute(Trigger triggers, MudMaster owner) { var me = owner.curCharacter; if (me.InCombat || me.Resting) return; if (DateTime.UtcNow < nextRest) return; if (me.HPmax - me.HPcur < 4) return; if (me.Location != null && me.Location.IsDangerous(me)) return; nextRest = DateTime.UtcNow.AddSeconds(2); owner.SendText("rest\r\n"); } } //public class AutoSneakAction : BaseReactor //{ // public AutoSneakAction() // : base(Trigger.CombatState | Trigger.Location) // { // } // public override void Execute(Trigger triggers, MudMaster owner) // { // var me = owner.curCharacter; // if (me.Stealth == 0) // return; // if (me.InCombat) // return; // if (me.Sneaking) // return; // if (me.Resting) // return; // if (me.Location == null || me.Location.NPCInRoom.Count > 0) // return; // owner.SendText("sneak\r\n"); // } //} public class AutoSearchAction : BaseReactor { public AutoSearchAction() : base(Trigger.Location) { this.Enabled = false; } public override void Execute(Trigger triggers, MudMaster owner) { var me = owner.curCharacter; if (me.Location == null) return; if (DateTime.UtcNow < me.Location.LastSearch.AddMinutes(10)) return; if (me.InCombat || me.Resting || me.Hidden || me.Sneaking) return; me.Location.LastSearch = DateTime.UtcNow; owner.SendText("search\r\n"); } } public class AutoBuySellAction : BaseReactor { public AutoBuySellAction() : base(Trigger.Location) { } public override void Execute(Trigger triggers, MudMaster owner) { var me = owner.curCharacter; var loc = me.Location; if (loc == null || loc.Shop == null || loc.Shop.ItemsForSale.Items.Count == 0) return; if (!me.Inventory.ShouldConsidateMoney(owner)) return; foreach (var item in loc.Shop.ItemsForSale.Items) { if (item.Cost == 0) { owner.SendText("buy " + item.Item.Name + "\r\nsell " + item.Item.Name + "\r\n"); return; } } } } public class AutoHealAction : BaseReactor { public AutoHealAction() : base(Trigger.HPandMana | Trigger.Timer) { } public override void Execute(Trigger triggers, MudMaster owner) { var me = owner.curCharacter; if (DateTime.UtcNow < me.LastSpellcast.AddMilliseconds(Config.RoundDurationMilliseconds)) { return; } int needed = me.HPmax - me.HPcur; if (needed <= 0) return; if (me.Hidden || me.Sneaking) return; if (me.Location != null && !me.Location.IsDangerous(me)) { if (me.MPcur + me.MPregen * 2 < me.MPmax) return; } foreach (var spell in me.KnownSpells.Where(s => s.Effect == SpellEffect.Heal)) { if (needed < spell.MaxDamage) { continue; } if (!spell.CanUse(owner, me)) { continue; } spell.Use(owner, me); break; } } } public class AutoBuffAction : BaseReactor { public List<string> DesiredBuffs = new List<string>(); public AutoBuffAction() : base(Trigger.Timer) { } public override void Execute(Trigger triggers, MudMaster owner) { var me = owner.curCharacter; if (DateTime.UtcNow < me.LastSpellcast.AddMilliseconds(Config.RoundDurationMilliseconds)) return; if (me.Hidden || me.Sneaking) return; if (owner.curCharacter.MPcur * 2 < owner.curCharacter.MPmax) // don't buff with less than 1/2 mana return; foreach (var buff in owner.curCharacter.CurrentBuffs) { if (buff.IsHarmful) { foreach (var spell in owner.curCharacter.KnownSpells) { if (spell.RemovesBuff == buff) { spell.Use(owner, me); return; } } } } if (me.Resting) return; foreach (var spellName in DesiredBuffs) { var buff = owner.buffs.GetBySpellName(spellName); if (me.CurrentBuffs.Contains(buff)) continue; foreach (var spell in me.KnownSpells) { if (spell.CausesBuff == buff && spell.CanUse(owner, me)) { spell.Use(owner, me); return; } } } } } public class AutoAttackAction : BaseReactor { public AutoAttackAction() : base(Trigger.Timer) { } public override void Execute(Trigger triggers, MudMaster owner) { var me = owner.curCharacter; if (me.Location == null) return; if (DateTime.UtcNow < me.NextCombatCheck) return; if (triggers.HasFlag(Trigger.Timer) && me.InCombat) return; var target = me.CurrentlyAttacking; if (!me.Location.NPCInRoom.Contains(target)) target = null; if (target == null) { int bestExperienceValue = 0; foreach (var npc in me.Location.NPCInRoom) { if (npc.type.AttacksAlignment.HasFlag(me.Alignment)) { if (npc.type.ExperienceValue >= bestExperienceValue) { target = npc; bestExperienceValue = npc.type.ExperienceValue; } } } } if (target == null) return; me.AttackTarget(owner, target); } } public class MoveToAction : BaseReactor { private List<Route> route = new List<Route>(); private MapNode dest; public bool HasRoute { get { return route.Count > 0; } } public MoveToAction() : base(Trigger.Map | Trigger.Location | Trigger.Death) { } public void SetDestination(MudMaster owner, MapNode destination) { Cancel(); this.dest = destination; CalculateRoute(owner); if (route.Count > 0) { Enabled = true; Execute(Trigger.Location, owner); } } public void Cancel() { dest = null; route.Clear(); Enabled = false; } private void CalculateRoute(MudMaster owner) { route.Clear(); route.AddRange( owner.map.FindRouteReverseOrder(owner.curCharacter.Location, dest)); } public override void Execute(Trigger triggers, MudMaster owner) { if (Remove) return; if (triggers.HasFlag(Trigger.Death)) { Cancel(); return; } if (route.Count > 0 && owner.curCharacter.Location != route[route.Count - 1].ConnectFrom) route.Clear(); if (route.Count == 0 || triggers.HasFlag(Trigger.Map)) CalculateRoute(owner); if (route.Count > 0) { route[route.Count - 1].Execute(owner); } else { dest = null; Enabled = false; } } public override string ToString() { var sb = new StringBuilder(); for (int i = route.Count - 1; i >= 0; i--) { sb.Append(route[i].Direction.direction.Shortcut); if (i > 0) sb.Append(" => "); } return sb.ToString(); } } } <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; using System.IO; namespace MudClient { public partial class frmMain : Form { private TerminalManager terminal; private Connection connect; private MM.Config config; public frmMain() { InitializeComponent(); terminal = new TerminalManager(terminalDraw1.GetState(), InvokeDataRecieved); terminal.AddScriptHandlers( new AutoContinue(), new AutoContinue2()); config = new MM.Config(); SetConnectingBusyState(false); } protected override void OnShown(EventArgs e) { base.OnShown(e); MouseWheelRedirector.Enable(true); } private void InvokeDataRecieved() { this.BeginInvoke((MethodInvoker)terminal.HandleDataRecieved); } private void txtInput_TextChanged(object sender, EventArgs e) { } private RollingBuffer<string> sentHistory = new RollingBuffer<string>(100); private int historyPos; private StringBuilder sb = new StringBuilder(); private string historySavedText; private void textBox1_KeyDown(object sender, KeyEventArgs e) { switch (e.KeyCode) { case Keys.Enter: { sb.Append(txtInput.Text); string text = sb.ToString(); sb.AppendLine(); if (!e.Control) { historyPos = 0; if (sentHistory.GetFromEnd(0) != text) sentHistory.Add(text); SendText(); } txtInput.Clear(); e.Handled = true; e.SuppressKeyPress = true; } break; case Keys.Up: if (historyPos < 100) { if (historyPos == 0) { historySavedText = txtInput.Text; } historyPos++; txtInput.Text = sentHistory.GetFromEnd(historyPos - 1); } e.Handled = true; break; case Keys.Down: if (historyPos > 0) { historyPos--; if (historyPos > 0) txtInput.Text = sentHistory.GetFromEnd(historyPos - 1); else txtInput.Text = historySavedText; } e.Handled = true; break; case Keys.Escape: if (!e.Control) { txtInput.Clear(); sb.Clear(); } break; } } private void terminalDraw1_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar < 128) terminal.EnqueueSend(new byte[] { (byte)e.KeyChar }); } private void btnSend_Click(object sender, EventArgs e) { sb.Append(txtInput.Text).AppendLine(); SendText(); txtInput.Clear(); txtInput.Focus(); } private void ReplaceText() { if (sb.Length > 2 && sb[1] == ' ') { switch (sb[0]) { case 'b': sb.Insert(1, "ash"); break; } } } private void SendText() { ReplaceText(); byte[] data = new byte[sb.Length]; for (int i = 0; i < data.Length; i++) data[i] = (byte)sb[i]; sb.Clear(); terminal.EnqueueSend(data); } private void btnLoadConfig_Click(object sender, EventArgs e) { LoadConfig(); } private void btnConnect_Click(object sender, EventArgs e) { if (config.Host == null || config.Port <= 0) { LoadConfig(); } Connect(); } private void btnDisconnect_Click(object sender, EventArgs e) { terminal.CloseLogFile(); connect.Disconnect(); SetConnectingBusyState(false); } private void Disconnect() { SetConnectingBusyState(false); } private void Connect() { txtInput.Select(); terminal.SetLogFile("Log-" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".txt"); connect = new Connection(); connect.Disconnected += OnDisconnected; terminal.SetConnection(connect); if (!string.IsNullOrEmpty(config.Username)) { terminal.AddScriptHandlers(new AutoLogin(config.Username)); } if (!string.IsNullOrEmpty(config.Password)) { terminal.AddScriptHandlers(new AutoLogin(config.Password)); } terminal.AddScriptHandlers(new AutoEnterRealm(), new AutoRunMud()); connect.Connect(config.Host, config.Port); SetConnectingBusyState(true); } private void OnDisconnected() { this.BeginInvoke((MethodInvoker)(() => { SetConnectingBusyState(false); if (connect != null) connect.Disconnected -= OnDisconnected; })); } private void SetConnectingBusyState(bool busy) { btnDisconnect.Enabled = busy; btnConnect.Enabled = !busy; } private void frmMain_FormClosing(object sender, FormClosingEventArgs e) { terminal.FlushLogFiles(); } private void btnCharacter_Click(object sender, EventArgs e) { var frm = new MM.frmCharacterState(); frm.SetMud(terminal.mud); frm.Show(this); } private void btnMap_Click(object sender, EventArgs e) { var frm = new MM.frmMap(); frm.SetMud(terminal.mud); frm.Show(this); } private void btnRoom_Click(object sender, EventArgs e) { var frm = new MM.frmCurrentRoom(); frm.SetMud(terminal.mud); frm.Show(this); } private void btnChat_Click(object sender, EventArgs e) { var frm = new MM.frmChat(); frm.SetMud(terminal.mud); frm.Show(this); } private bool LoadConfig() { using (var dlg = new OpenFileDialog()) { dlg.Filter = "XML|*.xml|All|*.*"; if (dlg.ShowDialog(this) == System.Windows.Forms.DialogResult.OK) { config.Load(dlg.FileName, terminal.mud); return true; } } return false; } private void btnLoadLog_Click(object sender, EventArgs e) { var dlg = new frmLogPlayback(); dlg.SetTerminalManager(terminal); dlg.Show(this); } private void btnAI_Click(object sender, EventArgs e) { var frm = new MM.frmAI(); frm.Initialize(terminal.mud); frm.Show(this); } private void btnLoadMaps_Click(object sender, EventArgs e) { using (var dlg = new OpenFileDialog()) { dlg.Multiselect = true; dlg.Filter = "txt and log|*.txt;*.log|All files|*.*"; if (dlg.ShowDialog(this) == System.Windows.Forms.DialogResult.OK) { var mud = new MM.MudMaster(terminal.mud); mud.Reactors.Enabled = false; var dl = new DataLoader(); dl.AddProtocols( new ProtocolTelnet(), new ProtocolVT100(), mud); foreach (var fileName in dlg.FileNames) { try { using (var file = File.OpenRead(fileName)) { mud.curCharacter.Location = null; dl.ReadData(file); } } catch { } } GC.Collect(2, GCCollectionMode.Forced); } } } } public class AutoContinue : ScriptHandler { public AutoContinue() { this.SearchFor = Encoding.Default.GetBytes("(N)onstop, (Q)uit, or (C)ontinue?"); } public override void Handle(IConnection conn) { conn.QueueSend(new byte[] { (byte)'N' }); } } public class AutoContinue2 : ScriptHandler { public AutoContinue2() { this.SearchFor = Encoding.Default.GetBytes("Hit any key to continue..."); } public override void Handle(IConnection conn) { conn.QueueSend(new byte[] { (byte)' ' }); } } public class AutoLogin : ScriptHandler { private byte[] user; public AutoLogin(string user) { this.RunOnce = true; this.user = Encoding.Default.GetBytes(user + "\r\n"); this.SearchFor = Encoding.Default.GetBytes("Enter your USER-ID and press ENTER.\r\nOtherwise type \"new\":"); } public override void Handle(IConnection conn) { conn.QueueSend(user); user = null; } } public class AutoPassword : ScriptHandler { private byte[] password; public AutoPassword(string password) { this.RunOnce = true; this.password = Encoding.Default.GetBytes(password + "\r\n"); this.SearchFor = Encoding.Default.GetBytes("Enter your password: "); } public override void Handle(IConnection conn) { conn.QueueSend(password); password = null; } } public class AutoRunMud : ScriptHandler { public AutoRunMud() { this.RunOnce = true; this.SearchFor = Encoding.Default.GetBytes("Main System Menu (TOP)\r\nMake your selection"); } public override void Handle(IConnection conn) { conn.QueueSend(Encoding.Default.GetBytes("m\r\n")); } } public class AutoEnterRealm : ScriptHandler { public AutoEnterRealm() { this.RunOnce = true; this.SearchFor = Encoding.Default.GetBytes("[MAJORMUD]:"); } public override void Handle(IConnection conn) { conn.QueueSend(Encoding.Default.GetBytes("e\r\n")); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MudClient.MM { public class MapNode { public static readonly MapNode Empty = new MapNode(); public readonly string Title; public string Description; public string RoomKey; public bool Dark; public List<Route> Exits = new List<Route>(); public Shop Shop; public Bank Bank; public DateTime LastVisit, LastSeen, LastSearch; public HashSet<NPCType> SeenNPCs = new HashSet<NPCType>(); public VirtualCoordinate Location; public readonly List<NPC> NPCInRoom = new List<NPC>(); public readonly List<Character> PCInRoom = new List<Character>(); public readonly Inventory ItemInRoom = new Inventory(); public readonly List<ItemStack> HiddenItems = new List<ItemStack>(); public IEnumerable<CharacterBase> EveryoneInRoom(MudMaster owner) { if (owner.curCharacter.Location == this) yield return owner.curCharacter; foreach (var npc in NPCInRoom) yield return npc; foreach (var pc in PCInRoom) yield return pc; } protected MapNode() { this.Title = string.Empty; this.Description = string.Empty; } public MapNode(MudMaster owner, string title) { if (title == null) return; this.Title = title; foreach (var group in owner.GroupLines(title, "Also here: ", "You notice ", "Obvious exits: ")) { if (group.StartsWith("Obvious exits: ")) { foreach (var desc in ParseExits(group)) { var exit = new Route(); exit.Direction = desc; exit.ConnectFrom = this; this.Exits.Add(exit); } break; } if (title != group) this.Description = group; } ParseContents(owner, title); } public bool ExitsMatch(List<RouteDescription> descriptions) { if (Exits.Count != descriptions.Count) return false; int exitIx = 0; int descIx = 0; while (true) { if (exitIx < Exits.Count) { if (Exits[exitIx].Direction.Hidden) { exitIx++; continue; } if (descIx < descriptions.Count) { if (!descriptions[descIx].Matches(Exits[exitIx].Direction)) { return false; } } } else if (descIx < descriptions.Count) { return false; } else return true; } } public Route GetRoute(MapNode adjacent) { foreach (var exit in Exits) if (exit.ConnectTo == adjacent) return exit; return null; } public CharacterBase FindCharacterByName(string name, MudMaster owner) { if (name == "you" || name == "You" || name == owner.curCharacter.Name) return owner.curCharacter; foreach (Character c in PCInRoom) if (c.Name == name) return c; foreach (NPC npc in NPCInRoom) if (npc.Name == name) return npc; return null; } public override string ToString() { return Title + " : " + string.Join(", ", Exits); } public bool IsDangerous(Character curChar) { return NPCInRoom.Any(npc => npc.type.AttacksAlignment.HasFlag(curChar.Alignment)); } public bool IsDeadly(Character curChar, HashSet<string> avoids) { return NPCInRoom.Any(n => n.type.AttacksAlignment.HasFlag(curChar.Alignment) && avoids.Contains(n.type.Name)); } public static List<RouteDescription> ParseExits(string exitLine) { string[] exits = exitLine.Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries); var descriptions = new List<RouteDescription>(); foreach (string exit in exits) descriptions.Add(new RouteDescription(exit)); return descriptions; } public static void ParseRoomIntoSections( MudMaster owner, string title, out string descriptionLine, out string itemLine, out string whoLine, out string exitLine) { itemLine = null; descriptionLine = null; exitLine = null; whoLine = null; foreach (var group in owner.GroupLines(title, "Also here: ", "You notice ", "Obvious exits: ", " ", "This is the description file")) { if (group.StartsWith("Also here: ")) { whoLine = group.Substring("Also here: ".Length); } else if (group.StartsWith("You notice ")) { itemLine = group.Substring("You notice ".Length); } else if (group.StartsWith(" ")) { descriptionLine = group.Substring(" ".Length); } else if (group.StartsWith("This is the description file")) { descriptionLine = group; } else if (group.StartsWith("Obvious exits: ")) { exitLine = group.Substring("Obvious exits: ".Length); } } } public static bool FindRoomDescription(MudMaster owner, out string roomTitle) { roomTitle = null; int maxI = 0; for (int i = 0; i < 30; i++) { var line = owner.historicalLines.GetFromEnd(i); if (line == null || line.StartsWith("\0\0\0") || line == "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=") { maxI = i - 1; break; } } for (int i = 0; i < maxI; i++) { var line = owner.historicalLines.GetFromEnd(i); if ((line.Length > 4 && line.StartsWith(" ") && line[4] != ' ') || line.StartsWith("This is the description file")) { roomTitle = owner.historicalLines.GetFromEnd(i + 1); return true; } } foreach (string nextLine in new[] { "You notice ", "Also here: ", "Obvious exits: " }) { for (int i = 0; i < maxI; i++) { var line = owner.historicalLines.GetFromEnd(i); if (line.StartsWith(nextLine)) { roomTitle = owner.historicalLines.GetFromEnd(i + 1); return false; } } } return false; } public void ParseContents(MudMaster owner, string title) { NPCInRoom.Clear(); ItemInRoom.Items.Clear(); string descriptionLine, itemLine, whoLine, exitLine; ParseRoomIntoSections(owner, title, out descriptionLine, out itemLine, out whoLine, out exitLine); if (descriptionLine != null) { this.Description = descriptionLine; } if (exitLine != null && exitLine.Contains("secret")) { foreach (var exit in ParseExits(exitLine)) { if (!exit.Hidden) continue; if (Exits.Any(e => e.Direction.direction == exit.direction)) continue; var route = new Route(); route.Direction = exit; route.ConnectFrom = this; Exits.Add(route); } } if (itemLine != null) { string[] parts = itemLine.Split(','); for (int j = 0; j < parts.Length; j++) { string item = parts[j]; if (item.EndsWith(" here.")) item = item.Substring(0, item.Length - " here.".Length); AddItemInRoom(owner, item); } } if (whoLine != null) { string[] parts = whoLine.Split(','); for (int j = 0; j < parts.Length; j++) { string name = parts[j].Trim(); int dotIx = name.IndexOf('.'); if (dotIx > 0) name = name.Substring(0, dotIx).Trim(); AddCharacterInRoom(owner, name); if (dotIx >= 0) break; } } } private CharacterBase AddCharacterInRoom(MudMaster owner, string name) { var character = owner.beastiary.GetPlayingCharacterOrNPC(owner, name); if (character is NPC) { this.SeenNPCs.Add(((NPC)character).type); this.NPCInRoom.Add((NPC)character); } else if (character is Character) { ((Character)character).Location = this; this.PCInRoom.Add((Character)character); } owner.Reactors.AddTrigger(Trigger.RoomCharacters); return character; } public ItemStack AddItemInRoom(MudMaster owner, string item) { var stack = owner.itemary.ParseStack(item); ItemInRoom.Add(stack); owner.Reactors.AddTrigger(Trigger.RoomItems); return stack; } public NPC HandleNPCDeathThroe(MudMaster owner, string line) { if (!owner.beastiary.NPCDeathThroes.Contains(line)) return null; if (line.StartsWith("The ")) line = line.Substring("The ".Length); foreach (var npc in NPCInRoom) { if (line.StartsWith(npc.type.Name)) { this.NPCInRoom.Remove(npc); if (owner.curCharacter.CurrentlyAttacking == npc) owner.curCharacter.CurrentlyAttacking = null; owner.Reactors.AddTrigger(Trigger.RoomCharacters); return npc; } } return null; } public bool ParseNPCState(MudMaster owner, string line) { int endIx; if ((endIx = line.IndexOf(" the room from ")) > 0 || (endIx = line.IndexOf(" the room.")) > 0) { int startIx = 0; if (!(line.ExpectPrevString(ref endIx, " in ") || line.ExpectPrevString(ref endIx, " into "))) { return false; } bool nonProper = line.ExpectNextString(ref startIx, "A ") || line.ExpectNextString(ref startIx, "An "); line = line.SubstringRange(startIx, endIx); bool verbFound = false; foreach (var verb in Beastiary.NPCMoveVerbs) { if (line.EndsWith(verb)) { line = line.Substring(0, line.Length - verb.Length); verbFound = true; break; } } if (verbFound) AddCharacterInRoom(owner, line); return true; } else if (HandleNPCDeathThroe(owner, line) != null) { return true; } else if (line.EndsWith(".")) { string name; Direction dir; NPC who = null; if (SplitNPCMoveLine(line, " just left to the ", out name, out dir)) { var other = owner.map.FindByLocation(this.Location + dir); who = FindNPCByName(name); if (who != null) { this.NPCInRoom.Remove(who); if (owner.curCharacter.CurrentlyAttacking == who) owner.curCharacter.CurrentlyAttacking = null; if (other != null) other.NPCInRoom.Add(who); } owner.Reactors.AddTrigger(Trigger.RoomCharacters); return true; } else if (SplitNPCMoveLine(line, " moves into the room from the ", out name, out dir)) { var other = owner.map.FindByLocation(this.Location + dir); if (other != null) { who = other.FindNPCByName(name); } if (who == null) this.AddCharacterInRoom(owner, name); else NPCInRoom.Add(who); owner.Reactors.AddTrigger(Trigger.RoomCharacters); return true; } } return false; } public bool ParseSearchResult(MudMaster owner, string line) { if (!line.StartsWith("You notice ")) return false; for (int i = 1; i < 10; i++) { string prevline = owner.historicalLines.GetFromEnd(i); if (prevline.StartsWith("\0\0\0")) return false; if (prevline.StartsWith("sea") && "search".StartsWith(prevline)) { HiddenItems.Clear(); foreach (var item in owner.itemary.ParseStacks(line, "You notice ".Length)) { HiddenItems.Add(item); } owner.Reactors.AddTrigger(Trigger.RoomItems); return true; } } return false; } public bool ParseOpen(MudMaster owner, string line) { if (line == "You bashed the door open.") { return true; } else if (line == "Your attempts to bash through fail!") { return true; } else if (line == "You successfully unlocked the door.") { return true; } else if (line == "Your skill fails you this time.") { return true; } else if (line == "The door is now open.") { return true; } else if (line.EndsWith(" damage for bashing the door!")) { } else if (line.EndsWith(" doesn't seem to fit that lock.")) { } else return false; return true; } public bool SplitNPCMoveLine(string line, string searchFor, out string npcName, out Direction dir) { npcName = null; dir = default(Direction); int textIx = line.IndexOf(searchFor); if (textIx < 0) return false; npcName = line.Substring(0, textIx); string dirName = line.Substring(textIx + searchFor.Length); dirName = dirName.Substring(0, dirName.Length - 1); return Direction.TryParse(dirName, out dir); } public NPC FindNPCByName(string name) { var npc = this.NPCInRoom.Where(n => n.Name == name).FirstOrDefault(); if (npc == null) npc = this.NPCInRoom.Where(n => n.type.Name == name).FirstOrDefault(); return npc; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MudClient.MM { public class Itemary { private readonly Dictionary<string, Item> knownItems = new Dictionary<string, Item>(); private readonly Item[] currencyTypes = new Item[6]; public readonly Item Copper, Silver, Gold, Platinum, Runic; public readonly Item Nothing; public Itemary() { Nothing = new Item(); Nothing.Name = "free"; Nothing.Type = ItemType.Currency; Nothing.Cost = 0; Nothing.Weight = 0; knownItems["free"] = Nothing; knownItems["Free"] = Nothing; knownItems["nothing"] = Nothing; knownItems["Nothing"] = Nothing; Copper = new Item(); Copper.Name = "copper"; Copper.Type = ItemType.Currency; Copper.Cost = 1; Copper.Weight = 1 / 3f; knownItems["copper"] = Copper; knownItems["copper farthings"] = Copper; Silver = new Item(); Silver.Name = "silver"; Silver.Type = ItemType.Currency; Silver.Cost = 10; Silver.Weight = 1 / 3f; knownItems["silver"] = Silver; knownItems["silver nobles"] = Silver; Gold = new Item(); Gold.Name = "gold"; Gold.Type = ItemType.Currency; Gold.Cost = 100; Gold.Weight = 1 / 3f; knownItems["gold"] = Gold; knownItems["gold crowns"] = Gold; Platinum = new Item(); Platinum.Name = "platinum"; Platinum.Type = ItemType.Currency; Platinum.Cost = 10000; Platinum.Weight = 1 / 3f; knownItems["platinum"] = Platinum; knownItems["platinum pieces"] = Platinum; Runic = new Item(); Runic.Name = "runic"; Runic.Cost = 1000000; Runic.Weight = 1 / 3f; knownItems["runic"] = Runic; knownItems["runic"] = Runic; currencyTypes = new Item[] { Runic, Platinum, Gold, Silver, Copper, Nothing, }; } public IEnumerable<Item> GetCurrencyTypes() { return currencyTypes; } public IEnumerable<Item> GetItemTypes() { return knownItems.Values; } public ItemStack ConvertToCurrency(int value) { if (value > 0) { foreach (var type in currencyTypes) { if (type.Cost == 1) return new ItemStack(value, type); if (value < type.Cost) continue; if (value % type.Cost == 0) return new ItemStack(value / type.Cost, type); } } return new ItemStack(0, currencyTypes[currencyTypes.Length - 1]); } public IEnumerable<ItemStack> ParseStacks(string line, int startIx) { string itemName; while (line.GetNextUntil(ref startIx, ", ", out itemName) && itemName.Length > 0) { yield return ParseStack(itemName); } if (line.GetNextUntil(ref startIx, "here.", out itemName) || line.GetNextUntil(ref startIx, ".", out itemName)) { yield return ParseStack(itemName); } } public ItemStack ParseStack(string item) { int ix = 0; int quantity = 1; if (item.GetNextInt(ref ix, out quantity)) { item.SkipNextSpaces(ref ix); item = item.Substring(ix); } else quantity = 1; var type = FindOrAdd(item.Trim()); return new ItemStack(quantity, type); } public Item FindOrAdd(string name) { Item result; if (!knownItems.TryGetValue(name, out result) && (name.EndsWith("s") || !knownItems.TryGetValue(name + "s", out result))) { result = new Item(); result.Name = name; knownItems[name] = result; } return result; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace MudClient { public class TerminalManager { public readonly MM.MudMaster mud = new MM.MudMaster(); private List<Protocol> Protocols; private readonly Action InvokeHandleDataRecieved; private readonly TerminalState state; private IConnection connection; public TerminalManager(TerminalState state, Action InvokeHandleDataReceived) { Protocols = new List<Protocol> { new ProtocolLog(), new ProtocolTelnet(), new ProtocolVT100(), new ProtocolScript(), mud, new ProtocolText(), }; this.state = state; foreach (var protocol in Protocols) protocol.SetState(state); this.InvokeHandleDataRecieved = InvokeHandleDataReceived; } public void SetLogFile(string fileName) { foreach (var protocol in Protocols.OfType<ProtocolLog>()) { protocol.SetLogFile(fileName); } } public void CloseLogFile() { foreach (var protocol in Protocols.OfType<ProtocolLog>()) { protocol.SetLogFile(null); } } public void FlushLogFiles() { foreach (var protocol in Protocols.OfType<ProtocolLog>()) { protocol.Flush(); } } public void SetConnection(IConnection connect) { if (connection != null) { connection.DataReceived -= connect_DataReceived; connection = null; state.ScrollLines(state.RowCount); state.MoveCursorTo(0, 0); } connection = connect; foreach (var protocol in Protocols) protocol.SetConnection(connection); connection.DataReceived += connect_DataReceived; } public void AddScriptHandlers(params ScriptHandler[] handlers) { foreach (var protocol in Protocols.OfType<ProtocolScript>()) { foreach (var handler in handlers) protocol.AddScriptHandler(handler); } } public void EnqueueSend(byte[] data) { if (connection != null) connection.QueueSend(data); } private Queue<byte[]> recievedData = new Queue<byte[]>(); void connect_DataReceived() { byte[] data = connection.DequeueReceieved(); lock (recievedData) recievedData.Enqueue(data); InvokeHandleDataRecieved(); } public void HandleDataRecieved() { while (true) { byte[] data; lock (recievedData) { if (recievedData.Count == 0) return; data = recievedData.Dequeue(); } if (data == null) return; HandleBytes(data, 0, data.Length); } } public void HandleBytes(byte[] data, int startIx, int length) { for (int i = 0; i < length; i++) { byte b = data[startIx++]; foreach (var protocol in Protocols) { try { if (protocol.HandleChar(b)) break; } catch (Exception ex) { Console.WriteLine(ex); break; } } } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Drawing; using System.Windows.Forms; namespace MudClient.MM { public class MapDraw : Control { public readonly List<MapNode> Nodes = new List<MapNode>(); public MapNode HighlightedNode; private List<KeyValuePair<Point, MapNode>> drawLocations = new List<KeyValuePair<Point, MapNode>>(); public float scale = 1; private Point center; private PointF translate; public MapDraw() { this.ResizeRedraw = true; this.DoubleBuffered = true; } protected override void OnVisibleChanged(EventArgs e) { base.OnVisibleChanged(e); center = new Point(this.Width / 2, this.Height / 2); } protected override void OnResize(EventArgs e) { base.OnResize(e); center = new Point(this.Width / 2, this.Height / 2); } protected override void OnMouseWheel(MouseEventArgs e) { base.OnMouseWheel(e); TranslateBy(center.X -e.Location.X, center.Y -e.Location.Y); if (e.Delta > 0) scale *= 1.1f; else scale /= 1.1f; TranslateBy(e.Location.X - center.X, e.Location.Y - center.Y); Invalidate(); } public event Action<MapNode> NodeClicked; private Point dragStart; private bool dragging; protected override void OnMouseDown(MouseEventArgs e) { base.OnMouseDown(e); if (e.Button == System.Windows.Forms.MouseButtons.Left) { if (NodeClicked != null) { int bestDiff = int.MaxValue; MapNode bestNode = null; foreach (var loc in drawLocations) { int diff = Math.Abs(e.X - loc.Key.X) + Math.Abs(e.Y - loc.Key.Y); if (diff < bestDiff) { bestDiff = diff; bestNode = loc.Value; } } if (bestNode != null && bestDiff < 20) NodeClicked(bestNode); } } else if (e.Button == System.Windows.Forms.MouseButtons.Right) { dragging = true; dragStart = e.Location; } } private void TranslateBy(int x, int y) { translate.X += x / scale; translate.Y += y / scale; } protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); if (dragging) { if (e.Location != dragStart) { TranslateBy( e.Location.X - dragStart.X, e.Location.Y - dragStart.Y); dragStart = e.Location; Invalidate(); } } } protected override void OnMouseUp(MouseEventArgs e) { base.OnMouseUp(e); if (e.Button == System.Windows.Forms.MouseButtons.Right) { dragging = false; } } private int minX, minY, minZ, maxX, maxY, maxZ; private int width; private int height; private void Precalculate() { minX = int.MaxValue; minY = int.MaxValue; minZ = int.MaxValue; maxX = int.MinValue; maxY = int.MinValue; maxZ = int.MinValue; foreach (var node in Nodes) { var loc = node.Location; minX = Math.Min(minX, loc.Value.X); minY = Math.Min(minY, loc.Value.Y); minZ = Math.Min(minZ, loc.Value.Z); maxX = Math.Max(maxX, loc.Value.X); maxY = Math.Max(maxY, loc.Value.Y); maxZ = Math.Max(maxZ, loc.Value.Z); } minX -= 2; minY -= 2; maxX += 2; maxY += 2; width = this.Width / (maxX - minX); height = this.Height / (maxY - minY); } protected override void OnPaint(PaintEventArgs e) { e.Graphics.Clear(Color.White); Precalculate(); drawLocations.Clear(); foreach (var node in Nodes) { var p1 = GetLocationForCoord(node.Location.Value); drawLocations.Add(new KeyValuePair<Point, MapNode>(p1, node)); foreach (var exit in node.Exits) { Pen pen = ColorLevels[((node.Location.Value.Z % ColorLevels.Length) + ColorLevels.Length) % ColorLevels.Length]; var p2 = GetLocationForCoord(node.Location.Value + exit.Direction.direction); e.Graphics.DrawLine(pen, p1, p2); } } foreach (var node in Nodes) { var loc = GetLocationForCoord(node.Location.Value); e.Graphics.DrawString(node.Title, this.Font, node == HighlightedNode ? Brushes.Red : Brushes.Black, loc); } } private static Pen[] ColorLevels = new Pen[] { Pens.Olive, Pens.Cyan, Pens.Gold, Pens.Blue, Pens.Purple, }; private const double zScale = 0.231; private Point GetLocationForCoord(Coordinate coord) { int x = (coord.X - minX) * width - (int)Math.Round(coord.Z * width * zScale) + (int)translate.X; int y = (maxY - coord.Y) * height + (int)Math.Round(coord.Z * width * zScale) + (int)translate.Y; if (scale != 1) { x = (int)Math.Round((x - center.X) * scale + center.X); y = (int)Math.Round((y - center.Y) * scale + center.Y); } return new Point(x, y); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MudClient.MM { public class DirectionRequest { public Direction Direction; public DirectionRequest NextRequest; public DirectionRequest(Direction direction) { this.Direction = direction; } } public class LookRequest : DirectionRequest { public LookRequest(Direction dir) : base(dir) { } public override string ToString() { return "look " + Direction.ToString(); } } public class MoveRequest : DirectionRequest { public MoveRequest(Direction dir) : base(dir) { } public override string ToString() { return "go " + Direction.ToString(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MudClient.MM { public enum ItemType { Other, Currency, LightSource, Potion, Scroll, Head, Legs, Feet, Hands, Torso, Weapon2H, Weapon1H, Shield, Arms, Back, Waist, Neck, Ears, Wrist, Finger, Worn, Key, } public class Item { public string Name; public ItemType Type; public int Cost; public float Weight; public bool Unique; public string Description; public override string ToString() { return Name; } } public class ItemStack { public Item Item; public int Count; public bool Busy; public float Weight { get { return Count * Item.Weight; } } public int Cost { get { return Count * Item.Cost; } } public ItemStack(int count, Item type) { this.Item = type; this.Count = count; } public override string ToString() { if (Count != 1 || Item.Type == ItemType.Currency) return Count + " " + Item; else return Item.ToString(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MudClient.MM { public class BuffTypes { public List<Buff> buffs = new List<Buff>(); public BuffTypes() { buffs.Add(new Buff { Name = "bless", PartyName = "chant", StartDescription = "You feel lucky!", EndDescription = "The effects of bless wear off!", }); buffs.Add(new Buff { Name = "greater bless", PartyName = "chant", StartDescription = "You feel VERY lucky!", EndDescription = "The effects of greater bless wear off.", }); buffs.Add(new Buff { Name = "protection from evil", StartDescription = "You feel protected from evil!", EndDescription = "You no longer feel protected from evil!", }); buffs.Add(new Buff { Name = "barkskin", StartDescription = "You feel tough!", EndDescription = "The effects of barkskin wear off!", }); buffs.Add(new Buff { Name = "starlight", StartDescription = "You are surrounded by a shimmering light!", EndDescription = "Your starlight spell fades away.", }); buffs.Add(new Buff { Name = "alertness", StartDescription = "You feel perceptive!", EndDescription = "The effects of alertness wear off!", }); buffs.Add(new Buff { Name = "resist cold", StartDescription = "You feel resistant to cold!", EndDescription = "The effects of resist cold wear off!", }); buffs.Add(new Buff { Name = "resist fire", StartDescription = "You feel resistant to fire!", EndDescription = "The effects of resist fire wear off!", }); buffs.Add(new Buff { Name = "resist lightning", StartDescription = "You feel resistant to lightning!", EndDescription = "The effects of resist lightning wear off!", }); buffs.Add(new Buff { Name = "song of valour", StartDescription = "You feel confident!", EndDescription = "The effects of valour wear off!", }); buffs.Add(new Buff { Name = "song of might", StartDescription = "You feel strong!", EndDescription = "Your strength returns to normal.", }); buffs.Add(new Buff { Name = "song of wisdom", StartDescription = "You feel wise!", EndDescription = "Your wisdom returns to normal.", }); buffs.Add(new Buff { Name = "song of brilliance", StartDescription = "You feel smart!", EndDescription = "Your intelligence returns to normal.", }); buffs.Add(new Buff { Name = "song of agility", StartDescription = "You feel agile!", EndDescription = "Your agility returns to normal.", }); buffs.Add(new Buff { Name = "song of beauty", StartDescription = "You feel radiant!", EndDescription = "Your charm returns to normal.", }); buffs.Add(new Buff { Name = "song of life", StartDescription = "You are healing faster!", EndDescription = "The song of life wears off.", }); buffs.Add(new Buff { Name = "song of traveling", StartDescription = "Your load is lightened!", EndDescription = "The effects of song of traveling wear off.", }); buffs.Add(new Buff { Name = "disease", StartDescription = "You are diseased!", EndDescription = "The disease dies down.", IsHarmful = true }); buffs.Add(new Buff { Name = "curse", StartDescription = "You feel unlucky!", EndDescription = "The effects of curse wear off!", IsHarmful = true }); buffs.Add(new Buff { Name = "blindness", StartDescription = "You are blind!", EndDescription = "The effects of the mummy's breath wears off.", IsHarmful = true }); buffs.Add(new Buff { Name = "bleed", StartDescription = "You are bleeding all over the place!", EndDescription = "You stop bleeding.", IsHarmful = true }); buffs.Add(new Buff { Name = "weakness", StartDescription = "You feel weak!", EndDescription = "You feel your strength return.", IsHarmful = true }); buffs.Add(new Buff { Name = "knocked down", StartDescription = "You are flat on your back!", EndDescription = "You get back on your feet.", IsHarmful = true }); } public bool ParseBuffString(MudMaster owner, string line) { foreach (var buff in buffs) { if (line == buff.StartDescription) { owner.curCharacter.CurrentBuffs.Add(buff); owner.Reactors.AddTrigger(Trigger.Buffs); return true; } else if (line == buff.EndDescription) { owner.curCharacter.CurrentBuffs.Remove(buff); owner.Reactors.AddTrigger(Trigger.Buffs); return true; } } return false; } public Buff GetBySpellName(string spellName) { foreach (var buff in buffs) if (buff.Name == spellName) return buff; return null; } } public class Buff { public string Name; public string PartyName; public bool IsHarmful; public string StartDescription, EndDescription; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; namespace MudClient { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.ThreadException += Application_ThreadException; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new frmMain()); } static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e) { File.AppendAllText("exceptionlog.txt", DateTime.Now.ToString("HHmmss") + ": " + e.Exception.ToString() + "\r\n"); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; using System.Threading.Tasks; namespace MudClient { public class TerminalState { private readonly int rowCount, colCount; private List<byte[]> historicalRows = new List<byte[]>(); private List<byte[]> colors = new List<byte[]>(); private byte[][] rows; private int currentRow; private int currentCol; private byte currentColor; public int CursorX { get { return currentCol; } } public int CursorY { get { return currentRow; } } public int RowCount { get { return rowCount; } } public int ColumnCount { get { return colCount; } } public int TotalHistoryRows { get { return historicalRows.Count; } } public TerminalState(int rowCount = 25, int colCount = 80) { this.currentColor = (7 << 3) + (0); this.rowCount = rowCount; this.colCount = colCount; this.rows = new byte[rowCount][]; for (int i = 0; i < rowCount; i++) { var row = new byte[colCount * 2]; this.rows[i] = row; historicalRows.Add(row); } } public byte[] GetRow(int rowIndexFromBottom) { if (rowIndexFromBottom >= historicalRows.Count) return null; if (rowIndexFromBottom < 0) return null; return historicalRows[historicalRows.Count - rowIndexFromBottom - 1]; } public byte ForeColor { get { return (byte)(currentColor & 0x07); } set { currentColor = (byte)((currentColor & 0xF8) | (value & 0x07)); } } public byte BackColor { get { return (byte)(currentColor >> 3); } set { currentColor = (byte)((currentColor & 0xC7) | (value << 3)); } } public Color GetForegroundColor(byte[] row, int column) { return ByteToColor(row[column + row.Length / 2]); } public Color GetBackgroundColor(byte[] row, int column) { return ByteToColor(row[column + row.Length / 2] >> 3); } private Color ByteToColor(int b) { switch (b & 7) { case 0: return Color.Black; case 1: return Color.Red; case 2: return Color.Green; case 3: return Color.Yellow; case 4: return Color.Blue; case 5: return Color.Magenta; case 6: return Color.Cyan; case 7: return Color.White; default: return Color.White; } } public void AppendChar(byte c) { SetChar(currentRow, currentCol, c); } private void SetChar(int currentRow, int currentCol, byte c) { var row = rows[currentRow]; row[currentCol] = c; row[currentCol + colCount] = currentColor; } public void MoveCursorTo(int row, int column) { if (row < 0) row = 0; else if (row >= rowCount) row = rowCount - 1; if (column < 0) column = 0; else if (column >= colCount) column = colCount - 1; SetCursorPos(row, column); } public void MoveCursorToRow(int row) { MoveCursorTo(row, currentCol); } public void MoveCursorToColumn(int column) { MoveCursorTo(currentRow, column); } public void Backspace() { int newRow = currentRow; int newCol = currentCol; newCol--; if (newCol < 0) { if (newRow <= 0) return; newRow--; var row = rows[newRow]; for (newCol = colCount; newCol > 0; newCol--) { if (row[newCol - 1] != 0) break; } if (newCol == colCount) newCol--; } SetCursorPos(newRow, newCol); } public void MoveCursorBy(int count) { int newRow = currentRow; int newCol = currentCol; newCol += count; while (newCol < 0) { newCol += colCount; newRow--; } while (newCol >= colCount) { newCol -= colCount; newRow++; } if (newRow < 0) { newRow = 0; newCol = 0; } else if (newRow >= rowCount) { int scrollBy = newRow - (rowCount - 1); ScrollLines(scrollBy); newRow = rowCount - 1; } SetCursorPos(newRow, newCol); } private void SetCursorPos(int row, int col) { if (row != currentRow || col != currentCol) { InvalidateChar(currentRow, currentCol); currentRow = row; currentCol = col; InvalidateChar(row, col); UpdateCursorPosition(); } } public void ScrollLines(int scrollLineCount) { for (int i = 0; i < scrollLineCount; i++) { historicalRows.Add(new byte[colCount * 2]); } int sourceIx = historicalRows.Count - 1; for (int i = rowCount - 1; i >= 0; i--) { rows[i] = historicalRows[sourceIx--]; } InvalidateScreen(); } public event Action UpdateCursorPosition; public event Action InvalidateScreen; public event Action<int> InvalidateRow; public event Action<int, int> InvalidateChar; public void EraseLine(int row) { if (row >= 0 && row < rowCount) { Array.Clear(rows[row], 0, colCount * 2); } } public void EraseChar(int column, int row) { while (column < 0) { column+= colCount; row--; } while (column > colCount) { column -= colCount; row++; } if (row >= 0 && row < rowCount) rows[row][column] = 0; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MudClient.MM { public class NPCType { public string Name; public string Description; public Alignment AttacksAlignment; public int ExperienceValue; public int MinAttack; public int MaxAttack; public int MinHP; public int MaxHP; public int AttackCount; public int AttackHits; public long TotalHP; public long TotalDamage; public override string ToString() { return Name; } } public class NPC : CharacterBase { public NPCType type; public string Prefix; public int DamageDealt; public override string NameAsTarget { get { if (type != null) return type.Name; else return Name; } } public NPC(NPCType type, string name) { this.type = type; this.Name = name; if (name.Length > type.Name.Length) this.Prefix = name.Substring(0, name.Length - type.Name.Length); } } } <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.Windows.Forms; namespace MudClient.MM { public partial class frmAI : Form { private MudMaster mud; private EventReactors config; public frmAI() { InitializeComponent(); } public void Initialize(MudMaster mud) { this.mud = mud; this.config = mud.Reactors; ConfigToUI(); } private void ConfigToUI() { if (config == null) return; chkAutoAttack.Checked = config.Attack.Enabled; chkAutoPickup.Checked = config.Pickup.Enabled; chkAutoDeposit.Checked = config.Deposit.Enabled; chkAutoConsolidate.Checked = config.BuySell.Enabled; chkAutoRest.Checked = config.Rest.Enabled; chkAutoHeal.Checked = config.Heal.Enabled; chkAutoBuff.Checked = config.Buff.Enabled; chkAutoSearch.Checked = config.Search.Enabled; chkAutoSneak.Checked = config.AI.AutoSneak;//.Sneak.Enabled; chkEnabledAI.Checked = config.AI.Enabled; chkPatrol.Checked = config.AI.AllowedActions.HasFlag(AIPriorities.Patrol); chkSell.Checked = config.AI.AllowedActions.HasFlag(AIPriorities.Sell); chkDeposit.Checked = config.AI.AllowedActions.HasFlag(AIPriorities.Deposit); chkTrain.Checked = config.AI.AllowedActions.HasFlag(AIPriorities.Train); chkFlee.Checked = config.AI.AllowedActions.HasFlag(AIPriorities.Flee); chkRest.Checked = config.AI.AllowedActions.HasFlag(AIPriorities.Rest); chkFight.Checked = config.AI.AllowedActions.HasFlag(AIPriorities.Fight); chkRetreat.Checked = config.AI.AllowedActions.HasFlag(AIPriorities.Retreat); txtEncumbranceSellRatio.Text = config.AI.EncumbranceSellRatio.ToString(); txtBankMinimum.Text = config.AI.BankMinimumDeposit.ToString(); txtFleeRatio.Text = config.AI.HPFleeRatio.ToString(); txtManaRatio.Text = config.AI.ManaRestRatio.ToString(); lstPatrolTargets.Items.Clear(); lstAvoid.Items.Clear(); foreach (var npc in mud.beastiary.GetNpcTypes()) { if (npc.AttacksAlignment != 0) { lstPatrolTargets.Items.Add(npc); lstAvoid.Items.Add(npc); } } for (int i = 0; i < lstPatrolTargets.Items.Count; i++) { var npc = (NPCType)lstPatrolTargets.Items[i]; if (config.AI.IsPatrol(npc.Name)) lstPatrolTargets.SetItemChecked(i, true); if (config.AI.IsAvoid(npc.Name)) lstAvoid.SetItemChecked(i, true); } lstAutoBuff.Items.Clear(); foreach (var buff in mud.buffs.buffs.OrderBy(b => b.Name)) { if (!buff.IsHarmful) lstAutoBuff.Items.Add(buff.Name); } for (int i = 0; i < lstAutoBuff.Items.Count; i++) { var buff = (string)lstAutoBuff.Items[i]; if (config.Buff.DesiredBuffs.Contains(buff)) lstAutoBuff.SetItemChecked(i, true); } lstPickupItems.Items.Clear(); var items = new HashSet<Item>(mud.itemary.GetItemTypes()); items.Remove(mud.itemary.Nothing); foreach (var item in items) if (config.Pickup.PickupItems.Contains(item.Name)) { lstPickupItems.Items.Add(item); lstPickupItems.SetItemChecked(lstPickupItems.Items.Count - 1, true); } foreach (var item in items.OrderBy(i => i.Name)) if (!config.Pickup.PickupItems.Contains(item.Name)) lstPickupItems.Items.Add(item); lstAttacks.Items.Clear(); foreach (var attack in mud.curCharacter.Attacks) { lstAttacks.Items.Add(attack); } } private void SetPriorityAllowed(AIPriorities priority, bool enabled) { if (enabled) config.AI.AllowedActions |= priority; else config.AI.AllowedActions &= ~priority; } private void chkPatrol_CheckedChanged(object sender, EventArgs e) { SetPriorityAllowed(AIPriorities.Patrol, chkPatrol.Checked); } private void chkSell_CheckedChanged(object sender, EventArgs e) { SetPriorityAllowed(AIPriorities.Sell, chkSell.Checked); } private void chkDeposit_CheckedChanged(object sender, EventArgs e) { SetPriorityAllowed(AIPriorities.Deposit, chkDeposit.Checked); } private void chkTrain_CheckedChanged(object sender, EventArgs e) { SetPriorityAllowed(AIPriorities.Train, chkTrain.Checked); } private void chkFlee_CheckedChanged(object sender, EventArgs e) { SetPriorityAllowed(AIPriorities.Flee, chkFlee.Checked); } private void chkRest_CheckedChanged(object sender, EventArgs e) { SetPriorityAllowed(AIPriorities.Rest, chkRest.Checked); } private void chkFight_CheckedChanged(object sender, EventArgs e) { SetPriorityAllowed(AIPriorities.Fight, chkFight.Checked); } private void chkRetreat_CheckedChanged(object sender, EventArgs e) { SetPriorityAllowed(AIPriorities.Retreat, chkRetreat.Checked); } private void chkEnabledAI_CheckedChanged(object sender, EventArgs e) { bool wasEnabled = config.AI.Enabled; config.AI.Enabled = chkEnabledAI.Checked; if (config.AI.Enabled && !wasEnabled) config.AI.Execute(Trigger.Location, mud); } private void txtBankMinimum_TextChanged(object sender, EventArgs e) { int minimum; if (int.TryParse(txtBankMinimum.Text, out minimum) && minimum >= 0) { if (config.AI.BankMinimumDeposit != minimum) { config.AI.BankMinimumDeposit = minimum; config.AI.Execute(Trigger.Inventory, mud); } } } private bool TryParsePercent(TextBox text, out float ratio) { if (!float.TryParse(text.Text, out ratio) || ratio < 0 && ratio > 100f) return false; if (ratio > 1) ratio /= 100f; return true; } private void txtFleeRatio_TextChanged(object sender, EventArgs e) { float minimum; if (TryParsePercent(txtFleeRatio, out minimum)) { if (config.AI.HPFleeRatio != minimum) { config.AI.HPFleeRatio = minimum; config.AI.Execute(Trigger.HPandMana, mud); } } } private void txtEncumbranceSellRatio_TextChanged(object sender, EventArgs e) { float minimum; if (TryParsePercent(txtEncumbranceSellRatio, out minimum)) { if (config.AI.EncumbranceSellRatio != minimum) { config.AI.EncumbranceSellRatio = minimum; config.AI.Execute(Trigger.Inventory, mud); } } } private void txtManaRatio_TextChanged(object sender, EventArgs e) { float minimum; if (TryParsePercent(txtManaRatio, out minimum)) { if (config.AI.ManaRestRatio != minimum) { config.AI.ManaRestRatio = minimum; config.AI.Execute(Trigger.HPandMana, mud); } } } private void lstPatrolTargets_ItemCheck(object sender, ItemCheckEventArgs e) { var npc = (NPCType)lstPatrolTargets.Items[e.Index]; string name = npc.Name; config.AI.SetPatrolTarget(name, e.NewValue == CheckState.Checked, lstAvoid.GetItemChecked(e.Index)); } private void lstAvoid_ItemCheck(object sender, ItemCheckEventArgs e) { var npc = (NPCType)lstPatrolTargets.Items[e.Index]; string name = npc.Name; config.AI.SetPatrolTarget(name, lstPatrolTargets.GetItemChecked(e.Index), e.NewValue == CheckState.Checked); } private void lstAutoBuff_ItemCheck(object sender, ItemCheckEventArgs e) { var buff = (string)lstAutoBuff.Items[e.Index]; if (e.NewValue == CheckState.Checked) { if (!config.Buff.DesiredBuffs.Contains(buff)) config.Buff.DesiredBuffs.Add(buff); } else config.Buff.DesiredBuffs.Remove(buff); } private void lstPickupItems_ItemCheck(object sender, ItemCheckEventArgs e) { var item = (Item)lstPickupItems.Items[e.Index]; if (e.NewValue == CheckState.Checked) config.Pickup.PickupItems.Add(item.Name); else config.Pickup.PickupItems.Remove(item.Name); } private void chkAutoPickup_CheckedChanged(object sender, EventArgs e) { SetReactorEnabled(config.Pickup, chkAutoPickup); } private void chkAutoAttack_CheckedChanged(object sender, EventArgs e) { SetReactorEnabled(config.Attack, chkAutoAttack); } private void chkAutoHeal_CheckedChanged(object sender, EventArgs e) { SetReactorEnabled(config.Heal, chkAutoHeal); } private void chkAutoRest_CheckedChanged(object sender, EventArgs e) { SetReactorEnabled(config.Rest, chkAutoRest); } private void chkAutoConsolidate_CheckedChanged(object sender, EventArgs e) { SetReactorEnabled(config.BuySell, chkAutoConsolidate); } private void chkAutoEquip_CheckedChanged(object sender, EventArgs e) { } private void chkAutoDeposit_CheckedChanged(object sender, EventArgs e) { SetReactorEnabled(config.Deposit, chkAutoDeposit); } private void chkAutoBuff_CheckedChanged(object sender, EventArgs e) { SetReactorEnabled(config.Buff, chkAutoBuff); } private void chkAutoSearch_CheckedChanged(object sender, EventArgs e) { SetReactorEnabled(config.Search, chkAutoSearch); } private void chkAutoSneak_CheckedChanged(object sender, EventArgs e) { config.AI.AutoSneak = chkAutoSneak.Checked; //SetReactorEnabled(config.Sneak, chkAutoSneak); } private void SetReactorEnabled(BaseReactor reactor, CheckBox chkbox) { reactor.Enabled = chkbox.Checked; if (reactor.Enabled) reactor.Execute(Trigger.Timer, mud); } private void btnAttackUp_Click(object sender, EventArgs e) { var attack = lstAttacks.SelectedItem as CombatAction; int ix = mud.curCharacter.Attacks.IndexOf(attack); if (ix < 1) return; mud.curCharacter.Attacks[ix] = mud.curCharacter.Attacks[ix - 1]; mud.curCharacter.Attacks[ix - 1] = attack; ConfigToUI(); lstAttacks.SelectedItem = attack; } private void btnAttackDown_Click(object sender, EventArgs e) { var attack = lstAttacks.SelectedItem as CombatAction; int ix = mud.curCharacter.Attacks.IndexOf(attack); if (ix < 0 || ix >= mud.curCharacter.Attacks.Count - 1) return; mud.curCharacter.Attacks[ix] = mud.curCharacter.Attacks[ix + 1]; mud.curCharacter.Attacks[ix + 1] = attack; ConfigToUI(); lstAttacks.SelectedItem = attack; } private void btnRefresh_Click(object sender, EventArgs e) { ConfigToUI(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MudClient { public class ProtocolScript : Protocol { private readonly byte[] buffer = new byte[8192]; private int bufferPos; private bool[] matchingLastBytes = new bool[256]; private List<ScriptHandler> scripts = new List<ScriptHandler>(); private void UpdateMatchingLastBytes() { Array.Clear(matchingLastBytes, 0, matchingLastBytes.Length); foreach (var script in scripts) matchingLastBytes[script.SearchFor[script.SearchFor.Length - 1]] = true; } public void AddScriptHandler(ScriptHandler script) { scripts.Add(script); UpdateMatchingLastBytes(); } public override bool HandleChar(byte c) { buffer[bufferPos++] = c; if (bufferPos == buffer.Length) bufferPos = 0; if (matchingLastBytes[c]) CheckState(); return false; } private void CheckState() { for (int i = 0; i < scripts.Count; i++) { var script = scripts[i]; if (ScriptMatches(script)) { if (script.RunOnce) { scripts.RemoveAt(i--); UpdateMatchingLastBytes(); } script.Handle(this.connection); } } } private bool ScriptMatches(ScriptHandler script) { var search = script.SearchFor; int pos = bufferPos - 1; for (int i = search.Length - 1; i >= 0; i--, pos--) { if (pos < 0) pos += buffer.Length; if (buffer[pos] != search[i]) { return false; } } return true; } } public abstract class ScriptHandler { public bool RunOnce; public byte[] SearchFor; public abstract void Handle(IConnection conn); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MudClient.MM { public class Party { public List<PartyMember> members = new List<PartyMember>(); public Character Leader; public void ParsePartyBusiness(MudMaster owner, string line) { if (line.EndsWith(" has invited you to follow him.")) { owner.beastiary.GetAsPlayingCharacter(owner, line.Substring(0, line.Length - " has invited you to follow him.".Length)); } else if (line.StartsWith("You are now following ")) { } else if (line.StartsWith("You have invited ") && line.EndsWith(" to follow you.")) { owner.beastiary.GetAsPlayingCharacter(owner, line.SubstringRange("You have invited ".Length, line.Length - " to follow you.".Length)); } else if (line.EndsWith(" started to follow you.")) { } } } public class PartyMember { public Character Who; } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Drawing.Drawing2D; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace MudClient { public partial class TerminalDraw : Control { private VScrollBar scroll; private TerminalState state; private int fontHeight, fontWidth; public TerminalDraw() { InitializeComponent(); scroll = new VScrollBar(); scroll.Dock = DockStyle.Right; this.Controls.Add(scroll); this.DoubleBuffered = true; this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.DoubleBuffer, true); this.BackColor = Color.Black; state = new TerminalState(); state.InvalidateChar += state_InvalidateChar; state.InvalidateRow += state_InvalidateRow; state.InvalidateScreen += state_InvalidateScreen; state.UpdateCursorPosition += state_UpdateCursorPosition; scroll.Scroll += scroll_Scroll; InvalidateAll(); scroll.Value = scroll.Maximum; } void scroll_Scroll(object sender, ScrollEventArgs e) { this.Invalidate(); //scroll.Value = e.NewValue; } protected override void OnClick(EventArgs e) { base.OnClick(e); Focus(); } protected override void OnGotFocus(EventArgs e) { base.OnGotFocus(e); this.Invalidate(); } protected override void OnLostFocus(EventArgs e) { base.OnLostFocus(e); this.Invalidate(); } protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { return false; } protected override bool ProcessDialogChar(char charCode) { return false; } protected override bool ProcessDialogKey(Keys keyData) { return false; } public TerminalState GetState() { return state; } void state_UpdateCursorPosition() { Invalidate(); } protected override void OnResize(EventArgs e) { base.OnResize(e); InvalidateAll(); } void InvalidateAll() { CalculateFont(); int distFromMax = scroll.Maximum - scroll.Value; int thisSize = this.ClientSize.Height; if (thisSize <= 0) thisSize = this.Height; if (thisSize > 0) { scroll.Maximum = state.TotalHistoryRows * fontHeight; scroll.LargeChange = this.ClientSize.Height - fontHeight; scroll.SmallChange = fontHeight; scroll.Value = Math.Max(0, Math.Min(scroll.Maximum - scroll.LargeChange, scroll.Maximum - distFromMax)); } Invalidate(); } void state_InvalidateScreen() { InvalidateAll(); } void state_InvalidateRow(int rowNum) { Invalidate(); } void state_InvalidateChar(int row, int col) { Invalidate(); } private void CalculateFont() { if (fontHeight == 0) { var size = TextRenderer.MeasureText("W", this.Font, new Size(), TextFormatFlags.NoPrefix | TextFormatFlags.NoPadding | TextFormatFlags.NoFullWidthCharacterBreak); fontHeight = size.Height; fontWidth = size.Width / 2; } } protected override void OnPaint(PaintEventArgs pe) { base.OnPaint(pe); if (state == null) return; CalculateFont(); int yoffset = scroll.Maximum - (scroll.Value + scroll.LargeChange); int cursorX = state.CursorX; int cursorY = state.RowCount - state.CursorY; int line = 0; int y = this.Height - (fontHeight * 2) + yoffset; int colCount = state.ColumnCount; Rectangle cursorRect = new Rectangle(); int curPageTop = 0, curPageBottom = 0; while (y + fontHeight > 0) { var row = state.GetRow(line++); if (row == null) break; cursorY--; if (y < this.ClientSize.Height) { if (line == state.RowCount) curPageTop = y; else if (line == 0) curPageBottom = y; for (int i = 0; i < colCount; i++) { byte c = row[i]; if (c >= 32) { byte color = row[i + colCount]; Color foreColor = state.GetForegroundColor(row, i); Color backColor = state.GetBackgroundColor(row, i); if (foreColor == backColor) { if (backColor == Color.White) foreColor = Color.Black; else foreColor = Color.White; } TextRenderer.DrawText( pe.Graphics, CharStrings[c], this.Font, new Point(i * fontWidth, y), foreColor, backColor, TextFormatFlags.NoPrefix | TextFormatFlags.NoPadding); } } if (cursorY == 0) { cursorRect = new Rectangle(cursorX * fontWidth, y, fontWidth, fontHeight); } } y -= fontHeight; } if (!cursorRect.IsEmpty) { pe.Graphics.DrawRectangle(Focused ? Pens.LightGreen : Pens.Orange, cursorRect); } if (curPageTop != 0) pe.Graphics.DrawLine(Pens.Blue, new Point(0, curPageTop), new Point(this.ClientSize.Width, curPageTop)); } public override Font Font { get { return base.Font; } set { fontHeight = 0; base.Font = value; InvalidateAll(); } } private static string[] CharStrings = CreateCharStrings(); private static string[] CreateCharStrings() { byte[] buffer = new byte[1]; string[] result = new string[256]; for (int i = 0; i < result.Length; i++) { buffer[0] = (byte)i; result[i] = Encoding.Default.GetString(buffer); } return result; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MudClient { public static class IStringExtensions { public static bool Equals<t1, t2>(this t1 s1, t2 s2) where t1 : IString where t2 : IString { if (s1.Length != s2.Length) return false; int len = s1.Length; for (int i = 0; i < len; i++) if (s1[i] != s2[i]) return false; return true; } public static bool EqualsIgnoreCase<t1, t2>(this t1 s1, t2 s2) where t1 : IString where t2 : IString { if (s1.Length != s2.Length) return false; int len = s1.Length; for (int i = 0; i < len; i++) { char c1 = s1[i]; char c2 = s2[i]; if (c1 != c2) { if (c1 >= 'A' && c1 <= 'Z') c1 |= (char)0x40; if (c2 >= 'A' && c2 <= 'Z') c2 |= (char)0x40; if (c1 != c2) return false; } } return true; } static IStringExtensions() { char[] result = new char[256]; byte[] buffer = new byte[256]; for (int i = 0; i < buffer.Length; i++) buffer[i] = (byte)i; Encoding.Default.GetChars(buffer, 0, 256, result, 0); byteMapping = result; } public static readonly char[] byteMapping; } public interface IString { int Length { get; } char this[int index] { get; } } public struct NaturalString : IString { private string data; public NaturalString(string value) { this.data = value; } public int Length { get { return data != null ? data.Length : 0; } } public char this[int index] { get { return data[index]; } } public override string ToString() { return data; } } public struct Substring : IString { private string data; private int startIx; private int length; public Substring(string data, int startIx, int length) { this.data = data; this.startIx = startIx; this.length = length; } public int Length { get { return length; } } public char this[int index] { get { return data[index + startIx]; } } public override string ToString() { if (data == null) return string.Empty; return data.Substring(startIx, length); } } public struct PackSubstring : IString { private readonly byte[] data; private readonly int startIx; private readonly int length; public PackSubstring(byte[] data, int startIx, int length) { this.data = data; this.startIx = startIx; this.length = length; } public int Length { get { return length; } } public char this[int index] { get { return IStringExtensions.byteMapping[data[(index + startIx) % data.Length]]; } } public override string ToString() { if (length <= 0) return string.Empty; return Encoding.Default.GetString(data, startIx, length); } } public struct PackString : IString { private readonly byte[] data; public int Length { get { return data != null ? data.Length : 0; } } public char this[int index] { get { return IStringExtensions.byteMapping[data[index]]; } } public PackString(byte[] data) { this.data = data; } public PackString(byte[] data, int Length) { if (Length == 0) { this.data = null; return; } this.data = new byte[Length]; Array.Copy(data, this.data, Length); } public PackString(string s) { if (s == null) data = null; else data = Encoding.Default.GetBytes(s); } public bool Equals(PackString other) { int len = Length; if (len != other.Length) return false; for (int i = 0; i < len; i++) if (data[i] != other.data[i]) return false; return true; } public bool EqualsIgnoreCase(PackString other) { int len = this.Length; if (len != other.Length) return false; for (int i = 0; i < len; i++) { byte c1 = data[i]; byte c2 = other.data[i]; if (c1 != c2) { if (c1 >= 'A' && c1 <= 'Z') c1 |= 0x40; if (c2 >= 'A' && c2 <= 'Z') c2 |= 0x40; if (c1 != c2) return false; } } return true; } public override string ToString() { if (data == null) return string.Empty; return Encoding.Default.GetString(data); } public static implicit operator string(PackString value) { return value.ToString(); } public static implicit operator PackString(string value) { return new PackString(value); } } } <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.Windows.Forms; namespace MudClient.MM { public partial class frmCharacterState : Form { private UpdateScreenAction act; private MudMaster mud; public frmCharacterState() { InitializeComponent(); this.act = new UpdateScreenAction(this); } protected override void OnClosing(CancelEventArgs e) { base.OnClosing(e); act.Remove = true; } public void SetMud(MudMaster mudMaster) { this.mud = mudMaster; mud.Reactors.AddExternalScript(act); RefreshCharacter(); } public void RefreshCharacter() { if (mud == null) return; var c = mud.curCharacter; if (c == null) return; lblName.Text = c.Name + " " + c.LastName; lblRace.Text = c.Race; lblClass.Text = c.Class; lblHits.Text = c.HPcur + "/" + c.HPmax; lblMana.Text = c.MPcur + "/" + c.MPmax; lblStrength.Text = c.Strength.ToString(); lblIntellect.Text = c.Intellect.ToString(); lblWillpower.Text = c.Willpower.ToString(); lblExp.Text = c.Experience + "/" + c.NextLevelExp; lblExpSession.Text = c.FormatSessionExperience(); lblLevel.Text = c.Level.ToString(); lblArmourClass.Text = c.ArmorClass + "/" + c.ArmorAbsorb; lblSpellcasting.Text = c.Spellcasting.ToString(); lblAgility.Text = c.Agility.ToString(); lblHealth.Text = c.Health.ToString(); lblCharm.Text = c.Charm.ToString(); lblLives.Text = c.Lives.ToString(); lblCharacterPoints.Text = c.CharacterPoints.ToString(); lblMagicResist.Text = c.MagicResist.ToString(); lblPerception.Text = c.Perception.ToString(); lblStealth.Text = c.Stealth.ToString(); lblThievery.Text = c.Thievery.ToString(); lblTraps.Text = c.Traps.ToString(); lblTracking.Text = c.Tracking.ToString(); lblMartialArts.Text = c.MartialArts.ToString(); lblBuffs.Text = string.Join("\r\n", c.CurrentBuffs.Select(b => b.Name)); lblEncumbrance.Text = Math.Ceiling(c.Inventory.Encumbrance) + "/" + c.MaxEncumbrance + " - " + c.EncumbranceState; lblHead.Text = c.Inventory[WearSlot.Head].ToStringOrNull(); lblLegs.Text = c.Inventory[WearSlot.Legs].ToStringOrNull(); lblFeet.Text = c.Inventory[WearSlot.Feet].ToStringOrNull(); lblHands.Text = c.Inventory[WearSlot.Hands].ToStringOrNull(); lblTorso.Text = c.Inventory[WearSlot.Torso].ToStringOrNull(); lblWeapon.Text = c.Inventory[WearSlot.Weapon].ToStringOrNull(); lblOffhand.Text = c.Inventory[WearSlot.Offhand].ToStringOrNull(); lblFingerLeft.Text = c.Inventory[WearSlot.LeftFinger].ToStringOrNull(); lblFingerRight.Text = c.Inventory[WearSlot.RightFinger].ToStringOrNull(); lblArms.Text = c.Inventory[WearSlot.Arms].ToStringOrNull(); lblBack.Text = c.Inventory[WearSlot.Back].ToStringOrNull(); lblWristLeft.Text = c.Inventory[WearSlot.LeftWrist].ToStringOrNull(); lblWristRight.Text = c.Inventory[WearSlot.RightWrist].ToStringOrNull(); lblWaist.Text = c.Inventory[WearSlot.Waist].ToStringOrNull(); lblNeck.Text = c.Inventory[WearSlot.Neck].ToStringOrNull(); lblEars.Text = c.Inventory[WearSlot.Ears].ToStringOrNull(); lblWorn.Text = c.Inventory[WearSlot.Worn].ToStringOrNull(); lblInventory.Text = c.Inventory.ToString(); lblWealth.Text = c.Inventory.Wealth.ToString(); lblBalance.Text = c.TotalBankBalances.ToString(); var sb = new StringBuilder("Experience table:\r\n"); for (int i = Math.Max(2, c.Level - 1); i < c.ExperienceTable.Count; i++) { sb.Append(i).Append(" = ").Append(c.ExperienceTable[i]).AppendLine(); } lblExpTable.Text = sb.ToString(); } private class UpdateScreenAction : BaseReactor { private frmCharacterState owner; public UpdateScreenAction(frmCharacterState owner) : base(Trigger.HPandMana | Trigger.Experience | Trigger.Inventory | Trigger.Death | Trigger.Buffs) { this.owner = owner; } public override void Execute(Trigger triggers, MudMaster owner) { this.owner.RefreshCharacter(); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MudClient.MM { public class CombatLog { private List<CombatEntry> history = new List<CombatEntry>(); private static string[] AttackVerbs = new string[] { "lunge", "snap", "flail", "swipe", "swoops", }; private static string[] HitVerbs = new string[] { "whap", "whaps", "whip", "whips", "bite", "bites", "stab", "stabs", "slash", "slashes", "smash", "smashes", "burn", "burns", "freeze", "freezes", "cast", "casts", "tears", }; public bool TryParse(MudMaster owner, string line) { if (string.IsNullOrEmpty(line)) return false; char lastChar = line[line.Length - 1]; switch (lastChar) { case '*': if (line == "*Combat Engaged*") { owner.curCharacter.Resting = false; owner.curCharacter.InCombat = true; owner.curCharacter.NextCombatCheck = DateTime.UtcNow.AddMilliseconds(Config.RoundDurationMilliseconds); history.Add(new CombatEntry(line, owner.curCharacter.Location)); owner.Reactors.AddTrigger(Trigger.CombatState); return true; } else if (line == "*Combat Off*") { owner.curCharacter.InCombat = false; history.Add(new CombatEntry(line, owner.curCharacter.Location)); owner.Reactors.AddTrigger(Trigger.CombatState); return true; } return false; case '!': if (line.EndsWith(" damage!")) { return ParseDamageLine(owner, line); } else if (line.EndsWith(" but you dodge out of the way!") || line.EndsWith(" but you dodge!") || line.EndsWith(" but your armour deflects the blow!")) { ParseEvasion(owner, line); return true; } return false; default: return false; } } private bool ParseHealing(MudMaster owner, string line, int ix, int damage, string verb) { string source, target; ix -= 2; if (!line.GetPrevWord(ref ix, out target)) return false; int targetIx = ix; ix = 0; if (!line.GetNextWord(ref ix, out source)) return false; var loc = owner.curCharacter.Location; if (loc == null) return true; var srcChar = source == "You" ? owner.curCharacter : loc.FindCharacterByName(source, owner); var tgtChar = target == "you" ? owner.curCharacter : loc.FindCharacterByName(target, owner); history.Add(new CombatEntry(line, loc, damage, verb, srcChar, tgtChar)); if (tgtChar != null) { tgtChar.HPcur += damage; if (tgtChar.HPcur > tgtChar.HPmax) tgtChar.HPcur = tgtChar.HPmax; } if (srcChar != null) srcChar.BreakStealth(); if (tgtChar != null) tgtChar.BreakStealth(); if (srcChar == owner.curCharacter && (line.StartsWith("You cast ") || line.StartsWith("You sing "))) { if (line.ExpectPrevString(ref targetIx, " on ")) { string spellName = line.SubstringRange("You cast ".Length, targetIx); var spell = owner.spells.GetByName(spellName); if (spell != null) spell.UpdateSpellData(owner, damage, SpellEffect.Heal, tgtChar); } } return true; } private bool ParseDamage(MudMaster owner, string line, int ix, int damage, string verb) { var curChar = owner.curCharacter; var here = curChar.Location; CharacterBase source = null, target = null; int ix2 = 0; if (line.StartsWith("You ")) { source = owner.curCharacter; ix2 = 4; } else if (line.StartsWith("The ")) { ix2 = 4; } if (source == null && here != null) foreach (var ch in here.EveryoneInRoom(owner)) { if (!string.IsNullOrEmpty(ch.Name) && line.ExpectNextString(ref ix2, ch.Name)) { source = ch; line.GetNextWord(ref ix2, out verb); break; } } int targetIx = -1; if (line.IndexOf(" you ", ix2) >= ix2) { target = owner.curCharacter; } else if (here != null) { foreach (var ch in here.EveryoneInRoom(owner).OrderBy(c => -(c.Name ?? "you").Length)) { if (ch.Name != null && (targetIx = line.IndexOf(ch.Name, ix2)) > 0) { target = ch; break; } } } if (source != null) source.BreakStealth(); if (target != null) { target.BreakStealth(); target.HPcur -= damage; } if (source != null && target != null) { history.Add(new CombatEntry(line, owner.curCharacter.Location, damage, verb, source, target)); if (target == curChar && source is NPC) { ((NPC)source).type.AttacksAlignment |= owner.curCharacter.Alignment; } else if (source == curChar && targetIx > 0) { foreach (string start in YouCastStarts) { if (line.StartsWith(start)) { string temp; targetIx--; line.GetPrevWord(ref targetIx, out temp); string spellName = line.SubstringRange(start.Length, targetIx - 1); var spell = owner.spells.GetByName(spellName); if (spell != null) spell.UpdateSpellData(owner, damage, SpellEffect.Attack, target); break; } } } } return true; } private static readonly string[] YouCastStarts = new string[] { "You cast ", "You sing ", "You fire a " }; private bool ParseDamageLine(MudMaster owner, string line) { int ix = line.Length - " damage!".Length; int damage; string verb; if (line.GetPrevInt(ref ix, out damage) && line.GetPrevWord(ref ix, out verb)) { if (verb == "healing" || verb == "regenerating") { return ParseHealing(owner, line, ix, damage, verb); } else if (verb == "for" || verb == "taking") { return ParseDamage(owner, line, ix, damage, verb); } } return false; } private static void ParseEvasion(MudMaster owner, string line) { int atIndex = line.IndexOf(" at you, "); if (atIndex > 0) { owner.curCharacter.BreakStealth(); if (line.StartsWith("The ")) { string verb, who; if (line.GetPrevWord(ref atIndex, out verb) && line.SkipPrevSpaces(ref atIndex) >= 0) { who = line.SubstringRange("The ".Length, atIndex); var npcTarget = owner.beastiary.FindOrAdd(who); npcTarget.AttacksAlignment |= owner.curCharacter.Alignment; } } } } } public class CombatEntry { public readonly DateTime TimeStamp = DateTime.Now; public string Text; public MapNode location; public int damage; public string verb; public CharacterBase source; public CharacterBase target; public CombatEntry(string text, MapNode location) { this.Text = text; this.location = location; } public CombatEntry(string text, MapNode location, int damage, string verb, CharacterBase source, CharacterBase target) { this.Text = text; this.location = location; this.damage = damage; this.verb = verb; this.source = source; this.target = target; } public override string ToString() { if (verb == null) return Text; if (verb == "healing") return source + " healed " + damage + " on " + target; else return source + " dealt " + damage + " to " + target; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MudClient.MM { public class MudMaster : Protocol { public readonly Map map = new Map(); public readonly Beastiary beastiary = new Beastiary(); public readonly Itemary itemary = new Itemary(); public readonly BuffTypes buffs = new BuffTypes(); public readonly Grimoire spells = new Grimoire(); public readonly CharacterClasses classes = new CharacterClasses(); public Character curCharacter = new Character(); public readonly CombatLog combat = new CombatLog(); private readonly List<Character> Party = new List<Character>(); public readonly List<string> Speech = new List<string>(); public DirectionRequest NextLookOrMove; public EventReactors Reactors = new EventReactors(); public RollingBuffer<string> historicalLines = new RollingBuffer<string>(500); private byte[] buffer = new byte[1024]; private int bufferCount = 0; private MapNode lastParsedLocation; private Mode SpecialMode; private enum Mode { OutOfGame, Normal, Who, TrainStats, Spells, ExpTable, ShopList, LookCharacter, } private System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer(); public MudMaster() { timer.Tick += timer_Tick; timer.Interval = 200; timer.Enabled = false; } public MudMaster(MudMaster shareFrom) { this.map = shareFrom.map; this.beastiary = shareFrom.beastiary; this.itemary = shareFrom.itemary; this.buffs = shareFrom.buffs; this.spells = shareFrom.spells; this.classes = shareFrom.classes; } public override bool HandleChar(byte c) { if (c == '\r' || bufferCount >= buffer.Length) { var line = new PackSubstring(buffer, 0, bufferCount).ToString(); historicalLines.Add(line); bufferCount = 0; try { ParseNewString(line); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } Reactors.CheckEvents(this); } else if (c == 8) // backspace { if (bufferCount > 0) { bufferCount--; } } else if (c != '\n') { buffer[bufferCount++] = c; if (curCharacter.TryParseStatLine(this, buffer, bufferCount)) { if (SpecialMode != Mode.Normal) { HandleEndSpecialMode(); SpecialMode = Mode.Normal; } var line = "\0\0\0" + new PackSubstring(buffer, 0, bufferCount).ToString(); historicalLines.Add(line); bufferCount = 0; Reactors.CheckEvents(this); } } return false; } private void HandleEndSpecialMode() { switch (SpecialMode) { case Mode.OutOfGame: //Console.WriteLine("Clearing looks and moves of " + LooksAndMoves.Count + " items"); curCharacter.Location = null; lastParsedLocation = null; NextLookOrMove = null; timer.Enabled = true; timer.Start(); break; case Mode.Who: NextLookOrMove = null; beastiary.ParseWho(this); break; case Mode.TrainStats: NextLookOrMove = null; break; case Mode.Spells: spells.ParseSpells(this); break; case Mode.ExpTable: curCharacter.ParseExpTable(this); break; case Mode.ShopList: if (curCharacter.Location != null) curCharacter.Location.Shop.ParseItems(this); break; case Mode.LookCharacter: Character.ParseLook(this); break; } } private void ParseNewString(string line) { CategorizeLine(line); } //private string[] ignoredLines = new string[] //{ // "A cheer of many voices can be heard in the distance.", // "Children rush past you hopping around in youthful glee.", // "The awful sound of a drunken chorus echoes through the streets.", // "A voice shouts aloud \"Read the bulletin in the Adventurer's Guild!\"", // "A dog barks off in the distance.", // "The fanatic screams \"Death to those who oppose the Blood God!\"", //}; private string[] cantMoveLines = new string[] { "There is no exit in that direction!", "You have not progressed far enough to go through this exit!", "You have progressed too far to go through this exit!", "You are not permitted in that room!", "You may not go through this exit!", "The gate is closed!", "The door is Closed!", "The door is closed!", "You do not have a room ticket.", "You may not enter that room while in combat.", "You are too heavy to move.", "You can't seem to move anywhere!", }; private Dictionary<string, Direction> SpecialMovements = new Dictionary<string, Direction> { { "You pull open the manhole cover, and slip inside the hole.", Direction.down }, { "You climb into one of the skiffs, and row to Silvermere.", Direction.south }, { "You ring the chime...", Direction.north }, { "You step back, start running to the north, and make a mighty leap!", Direction.north }, { "You step back, start running to the south, and make a mighty leap!", Direction.south }, { "You step back, start running to the east, and make a mighty leap!", Direction.east }, { "You step back, start running to the wast, and make a mighty leap!", Direction.west }, { "Unfortunately, you do not make it, and plummet to the street below!", Direction.Invalidate }, { "You step through the shimmering portal.", Direction.Invalidate }, }; private string[] bbsLines = new string[] { " ÈÍÍ Bye bye now!", " ÈÍÍ Hi there!", }; //public HashSet<string> UncategorizedLines = new HashSet<string>(); private void CategorizeLine(string line) { if (SpecialMode != Mode.Normal) { if (SpecialMode == Mode.OutOfGame && line == "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=") { HandleEndSpecialMode(); SpecialMode = Mode.Normal; curCharacter = new Character(); curCharacter.LastLogin = DateTime.UtcNow; SendText("stat\r\ni\r\nsp\r\n"); // get player name, inventory, spell list } return; } else if (line.StartsWith("\0\0\0")) // already parsed status line { return; } else if (line.Contains(" says:") || line.Contains(" gossips:") || line.Contains(" auctions:") || line.Contains(" whispers:") || (line.EndsWith("\"") && line.Contains("(\"Yelling): \""))) { // ignore the rest of the line Speech.Add(line); Reactors.AddTrigger(Trigger.Speech); } else if (line == "The room is barely visible") { if (lastParsedLocation != null) lastParsedLocation.Dark = true; } else if (line == "The following items are for sale here:") { if (curCharacter.Location != null) { this.SpecialMode = Mode.ShopList; curCharacter.Location.Shop = curCharacter.Location.Shop ?? new Shop(); } } else if (line == "The following is a table of experience for Your character:") { SpecialMode = Mode.ExpTable; } else if (line == "You have the following spells:") { SpecialMode = Mode.Spells; } else if (line == " Current Adventurers") { SpecialMode = Mode.Who; } else if (line == "You will exit after a period of silent meditation.") { timer.Stop(); } else if (line == "Your character has been saved. If you have any comments or suggestions, please") { SpecialMode = Mode.OutOfGame; curCharacter.LastLogout = DateTime.UtcNow; timer.Stop(); } else if (line == " Current Adventurers") { SpecialMode = Mode.Who; } else if (line == " Character Generator") { SpecialMode = Mode.TrainStats; } else if (line == "He is equipped with:") { SpecialMode = Mode.LookCharacter; } else if (line == "You have been killed!") { InvalidateLocation(); if (curCharacter.Lives > 0) curCharacter.Lives--; } else if (line == "You are now resting.") { curCharacter.Resting = true; } else if (line == "Attempting to sneak..." || line == "Sneaking...") { curCharacter.Sneaking = true; } else if (line == "You make a sound as you enter the room!") { curCharacter.BreakStealth(); } else if (line == "Attempting to hide...") { curCharacter.Hidden = true; } else if (line == "Attempting to hide... You don't think you are hidden.") { curCharacter.Hidden = false; } else if (line == "You are blind.") { if (NextLookOrMove != null) { var newLoc = map.HandleBlindMove(this, curCharacter.Location, NextLookOrMove.Direction); if (newLoc != null && curCharacter.Location != newLoc) { curCharacter.Location = newLoc; Reactors.AddTrigger(Trigger.Location); } NextLookOrMove = null; } } // Before this, compare lines equal, after this, compare lines start with/end with else if (line.StartsWith("Obvious exits:")) { HandleRoomDescription(); } else if (line.StartsWith("Willpower: ") && line.Contains("MagicRes: ")) { curCharacter.ParseStats(this, historicalLines); } else if (curCharacter.ParseExpGain(this, line)) { } else if (cantMoveLines.Contains(line) || line.EndsWith("is closed in that direction!") || line.StartsWith("There are no exits ")) { //if (NextLookOrMove != null) // NextLookOrMove = NextLookOrMove.NextRequest; NextLookOrMove = null; } else if (curCharacter.Location != null && curCharacter.Inventory.ParseItemDrop(this, line)) { } else if (curCharacter.Inventory.ParsePickup(this, line)) { } else if (curCharacter.Inventory.ParseGive(this, line)) { } else if (curCharacter.Inventory.ParseInventory(this, line)) { } else if (curCharacter.Inventory.ParseBuySell(this, line)) { } else if (curCharacter.Location != null && curCharacter.Location.ParseNPCState(this, line)) { } else if (curCharacter.Location != null && curCharacter.Location.ParseOpen(this, line)) { } else if (combat.TryParse(this, line)) { } else if (curCharacter.ParseExpLine(this, line)) { } else if (map.banks.ParseBalance(this, line)) { } else if (map.banks.ParseDepositWithdrawal(this, line)) { } else if (curCharacter.ParseTraining(this, line)) { } else if (buffs.ParseBuffString(this, line)) { } else if (curCharacter.Location != null && curCharacter.Location.ParseSearchResult(this, line)) { } else if (line.StartsWith(" -- Following your Party leader ") && line.EndsWith(" --")) { line = line.Substring(" -- Following your Party leader ".Length, line.Length - " -- Following your Party leader ".Length - " --".Length); Direction d; if (Direction.TryParse(line, out d)) { Console.WriteLine("Found follow action, expecting " + d); EnqueueNextMoveOrLook(new MoveRequest(d)); } } else if (bbsLines.Contains(line)) { for (int i = 0; i < 4; i++) historicalLines.RemoveLast(); } else if (CheckMoveOrLookCommand(line)) { } //else //{ // if (UncategorizedLines.Add(line)) // { // } //} } private bool CheckMoveOrLookCommand(string line) { foreach (var move in SpecialMovements) { if (move.Key == line) { EnqueueNextMoveOrLook(new MoveRequest(move.Value)); curCharacter.Resting = false; return true; } } //if (NextLookOrMove == null) { string dir; int ix = line.Length - 1; if (line.GetPrevWord(ref ix, out dir)) { Direction d; string verb; line.GetPrevWord(ref ix, out verb); line.SkipPrevSpaces(ref ix); if (ix < 0 && Direction.TryParse(dir, out d)) { if (verb == null) { //Console.WriteLine("Found move action, expecting " + d + " queuecount = " + LooksAndMoves.Count); EnqueueNextMoveOrLook(new MoveRequest(d)); curCharacter.Resting = false; return true; } else if ("look".StartsWith(verb, StringComparison.OrdinalIgnoreCase)) { //Console.WriteLine("Found look action, expecting " + d + " queuecount = " + LooksAndMoves.Count); EnqueueNextMoveOrLook(new LookRequest(d)); return true; } } } } return false; } private void HandleRoomDescription() { string lastRoomTitle; if (!MapNode.FindRoomDescription(this, out lastRoomTitle)) { if (curCharacter.Location != null) { curCharacter.Location.ParseContents(this, lastRoomTitle); } else { } } else { Direction dir = new Direction(); DirectionRequest act = NextLookOrMove; if (act != null) { NextLookOrMove = null; dir = act.Direction; //Console.WriteLine("Handling " + act + " for " + lastRoomTitle); } else { //Console.WriteLine("missing description for " + lastRoomTitle); } lastParsedLocation = map.FindOrMakeLocation(this, lastRoomTitle, curCharacter.Location, dir); lastParsedLocation.ParseContents(this, lastRoomTitle); if (act is MoveRequest || act == null) { if (curCharacter.Location != null) curCharacter.Location.LastVisit = DateTime.UtcNow; curCharacter.Location = lastParsedLocation; if (curCharacter.Sneaking) { bool foundSneak = false; for (int i = 1; i < 24; i++) //if (historicalLines.GetFromEnd(i) == lastRoomTitle) { string line = historicalLines.GetFromEnd(i - 1); if (line.StartsWith("\0\0\0")) break; if (line == "Sneaking...") { foundSneak = true; break; } } if (!foundSneak) curCharacter.BreakStealth(); } lastParsedLocation.LastVisit = DateTime.UtcNow; Reactors.AddTrigger(Trigger.RoomCharacters | Trigger.RoomItems | Trigger.Location); } } } private void EnqueueNextMoveOrLook(DirectionRequest request) { if (request.Direction == Direction.Invalidate) { InvalidateLocation(); return; } if (NextLookOrMove == null) { NextLookOrMove = request; return; } var cur = NextLookOrMove; while (cur.NextRequest != null) cur = cur.NextRequest; cur.NextRequest = request; } private void InvalidateLocation() { curCharacter.Location = null; lastParsedLocation = null; NextLookOrMove = null; } public void ClearMap() { InvalidateLocation(); map.Clear(); } void timer_Tick(object sender, EventArgs e) { Reactors.AddTrigger(Trigger.Timer); Reactors.CheckEvents(this); } public void SendText(string text) { if (string.IsNullOrEmpty(text)) return; //Console.WriteLine("sending text: " + text); connection.QueueSend(Encoding.Default.GetBytes(text)); } private readonly List<string> groupBuffer = new List<string>(); public IEnumerable<string> GroupLines(string terminator, params string[] sectionStarts) { groupBuffer.Clear(); try { for (int i = 0; i < 20; i++) { var line = this.historicalLines.GetFromEnd(i); groupBuffer.Add(line); if (terminator != null && line.StartsWith(terminator)) { if (groupBuffer.Count > 0) { groupBuffer.Reverse(); yield return string.Join(" ", groupBuffer); } yield return line; break; } foreach (var start in sectionStarts) if (line.StartsWith(start)) { groupBuffer.Reverse(); yield return string.Join(" ", groupBuffer); groupBuffer.Clear(); break; } } } finally { groupBuffer.Clear(); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Runtime.InteropServices; namespace MudClient { public class MouseWheelRedirector : System.Windows.Forms.IMessageFilter { private static MouseWheelRedirector Instance; public static void Enable(bool enabled) { if (enabled) { if (Instance == null) { Instance = new MouseWheelRedirector(); Application.AddMessageFilter(Instance); } } else { if (Instance != null) { Application.RemoveMessageFilter(Instance); Instance = null; } } } private IntPtr activeHwnd; const int WM_MOUSEWHEEL = 0x020A; const int WM_MOUSELEAVE = 0x02A3; const int WM_MOUSEMOVE = 0x0200; [DllImport("user32.dll", CharSet = CharSet.Auto)] static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam); public bool PreFilterMessage(ref Message m) { if (m.Msg == WM_MOUSEMOVE) // WM_MOUSEMOVE { activeHwnd = m.HWnd; } else if (m.Msg == WM_MOUSELEAVE) { if (activeHwnd == m.HWnd) activeHwnd = IntPtr.Zero; } else if (m.Msg == WM_MOUSEWHEEL) // WM_MOUSEWHEEL { if (activeHwnd != IntPtr.Zero) SendMessage(activeHwnd, m.Msg, m.WParam, m.LParam); return true; } return false; } } } <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; using System.IO; namespace MudClient { public partial class frmLogPlayback : Form, IConnection { private const int DefaultBytesPerSecond = 10000; private byte[] data; private int index; private int bytesPerSecond = DefaultBytesPerSecond; private TerminalManager term; private bool CanAdvance { get { return data != null && index < data.Length; } } public frmLogPlayback() { InitializeComponent(); txtBytesPerSecond.Text = bytesPerSecond.ToString(); } protected override void OnShown(EventArgs e) { base.OnShown(e); btnOpenFile.PerformClick(); } public void SetTerminalManager(TerminalManager term) { this.term = term; term.SetConnection(this); } private void btnOpenFile_Click(object sender, EventArgs e) { using (var dlg = new OpenFileDialog()) { dlg.Filter = "txt and log|*.txt;*.log|All files|*.*"; dlg.ValidateNames = true; if (dlg.ShowDialog(this) == DialogResult.OK) { lblFilename.Text = Path.GetFileName(dlg.FileName); data = File.ReadAllBytes(dlg.FileName); index = 0; UpdateRange(); } } } private void btnRestart_Click(object sender, EventArgs e) { index = 0; UpdateRange(); } private void btnStart_Click(object sender, EventArgs e) { timer1.Start(); } private void btnStop_Click(object sender, EventArgs e) { timer1.Stop(); } private void btnAdvance_Click(object sender, EventArgs e) { SendData(bytesPerSecond); } private void btnRunUntil_Click(object sender, EventArgs e) { if (!CanAdvance || string.IsNullOrEmpty(txtRunUntil.Text)) return; byte[] searchFor = Encoding.Default.GetBytes(txtRunUntil.Text); int nextIx = index + 1; while (nextIx < data.Length - searchFor.Length) if (RangesMatch(searchFor, 0, data, nextIx, searchFor.Length)) { SendData(nextIx + searchFor.Length - index); break; } else { nextIx++; } } private bool RangesMatch(byte[] buf1, int buf1Start, byte[] buf2, int buf2Start, int length) { if (buf1Start + length > buf1.Length) return false; if (buf2Start + length > buf2.Length) return false; for (int i = 0; i < length; i++) if (buf1[buf1Start++] != buf2[buf2Start++]) return false; return true; } private void btnNextLine_Click(object sender, EventArgs e) { if (!CanAdvance) return; int nextIx = index + 1; while (nextIx < data.Length && data[nextIx] != '\n') nextIx++; SendData(nextIx - index); } private void btnNextPage_Click(object sender, EventArgs e) { if (!CanAdvance) return; int nextIx = index; for (int i = 0; i < 24; i++) { nextIx++; while (nextIx < data.Length && data[nextIx] != '\n') nextIx++; } SendData(nextIx - index); } private void btnRunToEnd_Click(object sender, EventArgs e) { if (!CanAdvance) return; SendData(data.Length); } private void timer1_Tick(object sender, EventArgs e) { if (!SendData(bytesPerSecond)) { timer1.Stop(); } } private void txtBytesPerSecond_TextChanged(object sender, EventArgs e) { if (!int.TryParse(txtBytesPerSecond.Text, out bytesPerSecond) || bytesPerSecond <= 0) bytesPerSecond = DefaultBytesPerSecond; } private bool SendData(int bytes) { if (data == null || index >= data.Length) return false; if (index + bytes > data.Length) bytes = data.Length - index; if (bytes <= 0) return false; try { term.HandleBytes(data, index, bytes); return true; } finally { index += bytes; UpdateRange(); } } private void UpdateRange() { if (data != null) lblPosition.Text = index + " / " + data.Length; else lblPosition.Text = "No file"; lblPast.Text = null; lblFuture.Text = null; if (data == null || index > data.Length) return; int startIx = Math.Max(0, index - 200); int length = index - startIx; if (length > 0) lblPast.Text = Encoding.Default.GetString(data, startIx, length); startIx = index; length = Math.Min(200, data.Length - startIx); if (length > 0) lblFuture.Text = Encoding.Default.GetString(data, startIx, length); } public void QueueSend(byte[] data) { if (data != null && data.Length > 0 && !this.IsDisposed) txtSent.AppendText(Encoding.Default.GetString(data, 0, data.Length)); } public void Disconnect() { data = null; index = 0; } public void FakeCallEventsToAvoidWarnings() { DataReceived(); Disconnected(); throw new NotSupportedException(); } public event Action DataReceived; public event Action Disconnected; public byte[] DequeueReceieved() { return null; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace MudClient.MM { public class Config { public static int RoundDurationMilliseconds { get { return 5000; } } public string Host { get; set; } public int Port { get; set; } public string Username { get; set; } public string Password { get; set; } public void Load(string fileName, MudMaster owner) { XDocument doc; using (var stream = File.OpenRead(fileName)) { doc = XDocument.Load(stream); } var root = doc.Element("MudChar"); Host = root.Element("host").Value; int temp; if (!int.TryParse(root.Element("port").Value, out temp)) temp = 0; Port = temp; Username = root.Element("username").Value; Password = root.Element("password").Value; owner.Reactors.Buff.DesiredBuffs.AddRange(root.Elements("buff").Select(e => e.Value)); } } }
ee31ee0126aa03a23382c20aeff9f4a293e7c508
[ "Markdown", "C#" ]
48
C#
linknoid/MudClient
e64fe575603b9fab19c5be7962dc4a327a729f45
6b70d41e7a290b6676685c7d7f9b7cfae3acd2a2
refs/heads/master
<file_sep>{% extends 'base.html' %} {% load static %} {% block title %}Profile{% endblock %} {% block content %} <h1>User Profile</h1> <br/><br/> <div class="card mb-3"> <div class="row no-gutters"> <div class="col-md-3"> {% if user_data.profile_pic %} <img src="{{ user_data.profile_pic.url }}" class="card-img"> {% else %} <img src="{% static 'theblog/image/default_profile_pic.jpg' %}" class="card-img m-auto"> {% endif %} </div> <div class="col-md-9"> <div class="card-body"> <h5 class="card-title">{{ user_data.first_name }} {{ user_data.last_name }}</h5> {% if user_data.website_url %} | <a href="{{ user_data.website_url }}">Website</a> {% endif %} {% if user_data.facebook_url %} | <a href="{{ user_data.facebook_url }}">Facebook</a> {% endif %} {% if user_data.twitter_url %} | <a href="{{ user_data.twitter_url }}">Twitter</a> {% endif %} {% if user_data.instagram_url %} | <a href="{{ user_data.instagram_url }}">Instagram</a> {% endif %} {% if user_data.pinterest_url %} | <a href="{{ user_data.pinterest }}">Pinterest</a> {% endif %} </p> <p class="card-text">{{ user_data.bio }}</p> {# <p class="card-text"><small class="text-muted">Last updated at: {{ post.post_date }}</small></p>#} </div> </div> </div> </div> {% endblock %}<file_sep>from ckeditor.fields import RichTextField from django.conf import settings from django.contrib.auth.models import User from django.db import models from django.urls import reverse class Category(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name def get_absolute_url(self): return reverse('home') class Profile(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) bio = models.TextField(max_length=255) profile_pic = models.ImageField(null=True, blank=True, upload_to="images/profile/") facebook_url = models.CharField(max_length=255, null=True, blank=True) twitter_url = models.CharField(max_length=255, null=True, blank=True) instagram_url = models.CharField(max_length=255, null=True, blank=True) pinterest_url = models.CharField(max_length=255, null=True, blank=True) def __str__(self): return str(self.user) class Post(models.Model): title = models.CharField(max_length=255) header_image = models.ImageField(null=True, blank=True, upload_to="images/") title_tag = models.CharField(max_length=255, default="") author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) snippet = models.CharField(max_length=255) body = RichTextField(blank=True, null=True) # body = models.TextField() post_date = models.DateField(auto_now=True) likes = models.ManyToManyField(User, related_name="blog_posts") def total_likes(self): return self.likes.count() def __str__(self): return self.title + ' | ' + str(self.author) def get_absolute_url(self): # print("About_url" + str.id) return reverse('article-detail', args=[str(self.id)]) <file_sep>from django import forms from .models import Post, Category from ckeditor.fields import RichTextFormField # choices = Category.objects.all().values_list('name', 'name') # choice_list = [] # for item in choices: class PostForm(forms.ModelForm): class Meta: model = Post fields = ('title', 'title_tag', 'category', 'body', 'snippet', 'header_image') # Styling widgets = { 'title': forms.TextInput(attrs={'class': 'form-control mb-2', 'placeholder': 'Enter Title'}), 'title_tag': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter Title Tag'}), # 'author': forms.TextInput(attrs={'class': 'form-control', 'value': }), 'category': forms.Select(attrs={'class': 'form-control'}), # 'body': RichTextFormField() 'body': forms.Textarea(attrs={'class': 'form-control'}), 'snippet': forms.TextInput(attrs={'class': 'form-control'}), } class AddCategoryForm(forms.ModelForm): class Meta: model = Category fields = ('name',) widgets = { 'name': forms.TextInput(attrs={'class': 'form-control mb-2', 'placeholder': 'Enter Category'}), } class EditForm(forms.ModelForm): class Meta: model = Post fields = ('title', 'title_tag', 'body') # Styling widgets = { 'title': forms.TextInput(attrs={'class': 'form-control mb-2', 'placeholder': 'Enter Title'}), 'title_tag': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter Title Tag'}), 'body': forms.Textarea(attrs={'class': 'form-control', 'placeholder': 'Enter Your Story'}), } <file_sep>from django.urls import path from . import views from .views import UserRegisterView, UserEditView, PasswordsChangeView, ShowProfilePageView, EditProfilePageView from django.contrib.auth import views as auth_views urlpatterns = [ path('register/', UserRegisterView.as_view(), name="register"), path('edit_profile/', UserEditView.as_view(), name="edit-profile"), # path('password/', auth_views.PasswordChangeView.as_view(template_name='registration/change-password.html')), path('password/', PasswordsChangeView.as_view(template_name='registration/change-password.html')), path('password_success', views.password_success, name='password_success'), path('<int:pk>/profile/', ShowProfilePageView.as_view(), name='show-profile-page') path('<int:pk>/edit_profile_page/', EditProfilePageView.as_view(), name='edit-profile-page') ] <file_sep># Generated by Django 3.2.7 on 2021-09-22 05:25 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('theblog', '0004_category'), ] operations = [ migrations.AddField( model_name='post', name='category', field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to='theblog.category'), preserve_default=False, ), ]
b45e89ce636eaca562afbdcc170f7d9e40ed4860
[ "Python", "HTML" ]
5
HTML
AdeelWajid/simpleblog
ac6d73c052472c6c937476e1533ae1224f33e2de
4c235ce1dfa7d5f5a93cf317c38bd9da57a83a1f
refs/heads/master
<file_sep>// // LoginViewController.swift // ActionVs // // Created by mobkard on 01/03/2016. // Copyright © 2016 <NAME>. All rights reserved. // import UIKit enum ModeToggle{ case Register case Login } class LoginViewContvarler: UIViewController { let defaultManager = DefaultManager.sharedInstance @IBOutlet weak var emailRegistrationTextField: UITextField! @IBOutlet weak var passwordRegistrationTextField: UITextField! @IBOutlet weak var usernameUnderlineLabel: UILabel! @IBOutlet weak var usernameHeightConstraint: NSLayoutConstraint! @IBOutlet weak var emailTopConstraint: NSLayoutConstraint! @IBOutlet weak var triangleCenterConstraint: NSLayoutConstraint! @IBOutlet weak var triangleImageView: UIImageView! @IBOutlet weak var contentScrollView: UIScrollView! @IBOutlet weak var actionButton: StatButton! var tapAnywhereToDismissKeyboard = UITapGestureRecognizer() var modeToggle: ModeToggle = .Register override func viewDidLoad() { super.viewDidLoad() NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name:UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name:UIKeyboardWillHideNotification, object: nil) // Do any additional setup after loading the view. configureViews() } func configureViews(){ tapAnywhereToDismissKeyboard = UITapGestureRecognizer(target: self, action: "tapToDismissKeyboard") tapAnywhereToDismissKeyboard.numberOfTapsRequired = 1 self.view.userInteractionEnabled = true self.view.addGestureRecognizer(tapAnywhereToDismissKeyboard) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func signupTapped(sender: AnyObject) { emailRegistrationTextField.placeholder = "Email" usernameHeightConstraint.constant = 30 emailTopConstraint.constant = 20 triangleCenterConstraint.constant = 0 if modeToggle != .Register{ clearText() } actionButton.setTitle("Sign Up", forState: .Normal) usernameUnderlineLabel.hidden = false UIView.animateWithDuration(0.5, animations: { () -> Void in self.view.layoutIfNeeded() }) modeToggle = .Register } @IBAction func signinTapped(sender: AnyObject) { emailRegistrationTextField.placeholder = "Email or Username" usernameHeightConstraint.constant = 0 emailTopConstraint.constant = 0 if modeToggle != .Login{ clearText() triangleCenterConstraint.constant = triangleCenterConstraint.constant + 101 } actionButton.setTitle("Log In", forState: .Normal) usernameUnderlineLabel.hidden = true UIView.animateWithDuration(0.5, animations: { () -> Void in self.view.layoutIfNeeded() }) modeToggle = .Login } @IBAction func actionTapped(sender: AnyObject) { switch modeToggle{ case .Register: let email = emailRegistrationTextField.text let password = <PASSWORD>RegistrationTextField.text FireBaseManager().registerUser(email!, password: <PASSWORD>!, completion: { (status) in switch status{ case .SUCCESS: let alertController = UIAlertController(title: "Account Created", message: "", preferredStyle: .Alert) let okayAction = UIAlertAction(title: "Okay", style: .Default, handler:{ action in FireBaseManager().authenticateUser(email!, password: <PASSWORD>!, completion: { (status) in switch status{ case .SUCCESS: self.defaultManager.updateEmail(email!) self.defaultManager.updatePassword(<PASSWORD>!) let alertController = UIAlertController(title: "Authenticated", message: "You are now signed in", preferredStyle: .Alert) let okayAction = UIAlertAction(title: "Okay", style: .Default, handler: { (alert) in let mpvc = self.storyboard?.instantiateViewControllerWithIdentifier("MainPageViewController") as! MainPageViewController self.navigationController?.pushViewController(mpvc, animated: true) }) alertController.addAction(okayAction) self.presentViewController(alertController, animated: true, completion: nil) break case .ERROR: let alertController = UIAlertController(title: "Error", message: "There was an error Loggin In, Please check your internet", preferredStyle: .Alert) let okayAction = UIAlertAction(title: "Okay", style: .Default, handler: nil) alertController.addAction(okayAction) self.presentViewController(alertController, animated: true, completion: nil) break } }) }) alertController.addAction(okayAction) self.clearText() self.presentViewController(alertController, animated: true, completion: nil) break case .ERROR: let alertController = UIAlertController(title: "Error", message: "There was an error registering, Please check your internet", preferredStyle: .Alert) let okayAction = UIAlertAction(title: "Okay", style: .Default, handler: nil) alertController.addAction(okayAction) self.presentViewController(alertController, animated: true, completion: nil) break } }) break case .Login: let loginString = emailRegistrationTextField.text! let password = passwordRegistrationTextField.text! let isEmailInput = checkIfEmailInput(loginString) FireBaseManager().authenticateUser(loginString, password: <PASSWORD>, completion: { (status) in switch status{ case .SUCCESS: self.defaultManager.updateEmail(loginString) self.defaultManager.updatePassword(<PASSWORD>) let alertController = UIAlertController(title: "Authenticated", message: "You are now signed in", preferredStyle: .Alert) let okayAction = UIAlertAction(title: "Okay", style: .Default, handler: { (alert) in let mpvc = self.storyboard?.instantiateViewControllerWithIdentifier("MainPageViewController") as! MainPageViewController self.navigationController?.pushViewController(mpvc, animated: true) }) alertController.addAction(okayAction) self.presentViewController(alertController, animated: true, completion: nil) self.clearText() break case .ERROR: let alertController = UIAlertController(title: "Error", message: "There was an error Loggin In, Please check your internet", preferredStyle: .Alert) let okayAction = UIAlertAction(title: "Okay", style: .Default, handler: nil) alertController.addAction(okayAction) self.presentViewController(alertController, animated: true, completion: nil) break } }) break } } @IBAction func closeAction(sender: AnyObject) { self.dismissViewControllerAnimated(true, completion: nil) } func checkIfEmailInput(input: String)-> Bool{ if input.containsString("@"){ return true } return false } func clearText(){ emailRegistrationTextField.text = "" passwordRegistrationTextField.text = "" } func tapToDismissKeyboard(){ emailRegistrationTextField.resignFirstResponder() passwordRegistrationTextField.resignFirstResponder() } func keyboardWillShow(notification:NSNotification){ adjustKeyboardInsetShow(true, notification: notification) } func keyboardWillHide(notification:NSNotification){ adjustKeyboardInsetShow(false, notification: notification) } func adjustKeyboardInsetShow(show:Bool, notification: NSNotification){ let userInfo = notification.userInfo ?? [:] let keyboardFrame:CGRect = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).CGRectValue() let adjustmentHeight = (CGRectGetHeight(keyboardFrame)) * (show ? 1: -1) contentScrollView.contentInset.bottom += adjustmentHeight contentScrollView.scrollIndicatorInsets.bottom += adjustmentHeight } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } <file_sep>// // StatButton.swift // ActionVs // // Created by mobkard on 01/03/2016. // Copyright © 2016 <NAME>. All rights reserved. // import UIKit @IBDesignable class StatButton: UIButton { @IBInspectable var statBorderColor: UIColor = UIColor.whiteColor() { didSet{ layer.borderColor = statBorderColor.CGColor } } @IBInspectable var statBorderWidth:CGFloat = 1.0 { didSet{ layer.borderWidth = statBorderWidth } } @IBInspectable var statCornerRadius:CGFloat = 1.0 { didSet{ layer.cornerRadius = statCornerRadius } } /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code } */ } <file_sep>// // MainPageViewController.swift // MachineVenture // // Created by mobkard on 11/04/2016. // Copyright © 2016 <NAME>. All rights reserved. // import UIKit class MainPageViewController: UIViewController { var defaultManager = DefaultManager.sharedInstance var tField: UITextField? override func viewDidLoad() { super.viewDidLoad() } @IBAction func deleteAccount(sender: AnyObject) { let email = defaultManager.getEmail() let password = defaultManager.getPassword() FireBaseManager().deleteAccount(email, password: password) { (status) in switch status{ case .SUCCESS: self.defaultManager.clearAllDefaults() self.navigationController?.popViewControllerAnimated(true) break case .ERROR: let passwordChangedAlert = UIAlertController(title: "Delete Error", message: "There was an error deleteing your account", preferredStyle: UIAlertControllerStyle.Alert) let okayAction = UIAlertAction(title: "Okay", style: .Default, handler: nil) passwordChangedAlert.addAction(okayAction) self.presentViewController(passwordChangedAlert, animated: true, completion: nil) break } } } @IBAction func changePassword(sender: AnyObject) { func configurationTextField(textField: UITextField!) { textField.placeholder = "New Password" tField = textField tField!.secureTextEntry = true } let alert = UIAlertController(title: "Enter Input", message: "", preferredStyle: UIAlertControllerStyle.Alert) alert.addTextFieldWithConfigurationHandler(configurationTextField) alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler:nil)) alert.addAction(UIAlertAction(title: "Done", style: UIAlertActionStyle.Default, handler:{ (UIAlertAction)in self.changePassword() })) self.presentViewController(alert, animated: true, completion: nil) } func changePassword(){ FireBaseManager().changeUserPassword(self.defaultManager.getEmail(), password: self.defaultManager.getPassword(), newPassword: tField!.text!, completion: { (status) in switch status{ case .SUCCESS: self.defaultManager.updatePassword(self.tField!.text!) let passwordChangedAlert = UIAlertController(title: "Password Changed", message: "", preferredStyle: UIAlertControllerStyle.Alert) let okayAction = UIAlertAction(title: "Okay", style: .Default, handler: nil) passwordChangedAlert.addAction(okayAction) self.presentViewController(passwordChangedAlert, animated: true, completion: nil) break case .ERROR: let passwordChangedAlert = UIAlertController(title: "Password Changed Error", message: "There was an error changing your password", preferredStyle: UIAlertControllerStyle.Alert) let okayAction = UIAlertAction(title: "Okay", style: .Default, handler: nil) passwordChangedAlert.addAction(okayAction) self.presentViewController(passwordChangedAlert, animated: true, completion: nil) break } }) } @IBAction func closeTapped(sender: AnyObject) { self.navigationController?.popViewControllerAnimated(true) self.defaultManager.clearAllDefaults() } } <file_sep>// // FireBaseManager.swift // MachineVenture // // Created by mobkard on 11/04/2016. // Copyright © 2016 <NAME>. All rights reserved. // import UIKit import Firebase enum RegistrationResponse{ case SUCCESS case ERROR } enum AuthenticateResponse{ case SUCCESS case ERROR } enum ChangePasswordResponse{ case SUCCESS case ERROR } enum DeleteAccountResponse{ case SUCCESS case ERROR } class FireBaseManager: NSObject { let rootRef = Firebase(url: "https://glaring-torch-8227.firebaseio.com") func registerUser(email: String, password: String, completion:(status: RegistrationResponse) -> Void){ rootRef.createUser(email, password: <PASSWORD>) { (error: NSError!) in if error == nil{ completion(status: .SUCCESS) }else{ completion(status: .ERROR) } } } func authenticateUser(email: String, password: String, completion:(status: AuthenticateResponse) -> Void){ rootRef.authUser(email, password: <PASSWORD>) { (error, auth) in if error == nil{ completion(status: .SUCCESS) }else{ completion(status: .ERROR) } } } func changeUserPassword(email: String, password: String, newPassword: String, completion:(status: ChangePasswordResponse) -> Void){ rootRef.changePasswordForUser(email, fromOld: password, toNew: newPassword) { (error) in if error == nil{ completion(status: .SUCCESS) }else{ completion(status: .ERROR) } } } func deleteAccount(email: String, password: String, completion:(status: DeleteAccountResponse) -> Void){ rootRef.removeUser(email, password: <PASSWORD>) { (error) in if error == nil{ completion(status: .SUCCESS) }else{ completion(status: .ERROR) } } } } <file_sep>// // DefaultManager.swift // ActionVs // // Created by mobkard on 17/03/2016. // Copyright © 2016 <NAME>. All rights reserved. // import UIKit class DefaultManager: NSObject { static let sharedInstance = DefaultManager() private let USER_ID_CONSTANT = "userID" private let EMAIL_CONSTANT = "email" private let PASSWORD_CONSTANT = "<PASSWORD>" let userDefault = NSUserDefaults.standardUserDefaults() func updatePassword(password: String){ userDefault.setObject(password, forKey: PASSWORD_CONSTANT) } func getPassword() -> String{ let password = userDefault.objectForKey(PASSWORD_CONSTANT) as? String if let password = password{ return password }else{ return "" } } func updateEmail(email: String){ userDefault.setObject(email, forKey: EMAIL_CONSTANT) } func getEmail() -> String{ let email = userDefault.objectForKey(EMAIL_CONSTANT) as? String if let email = email{ return email }else{ return "" } } func clearAllDefaults(){ let appDomain = NSBundle.mainBundle().bundleIdentifier! NSUserDefaults.standardUserDefaults().removePersistentDomainForName(appDomain) } } <file_sep> // // User.swift // MachineVenture // // Created by mobkard on 11/04/2016. // Copyright © 2016 <NAME>. All rights reserved. // import UIKit class User: NSObject { var username = String() var password = String() }
33ab4f4dbd31e419016fa3cda860e44e83edf40c
[ "Swift" ]
6
Swift
imastermark1230/MCV
0b4d94dd3e9420523624dca7c9260af288e545f5
15f245576c60636384a0f958a35997c41202f845
refs/heads/master
<repo_name>nikolaj808/python-tictactoe<file_sep>/README.md # python-tictactoe Tic Tac Toe made using Python and TkInter <file_sep>/main.py from tkinter import * from tkinter import messagebox import random import os import sys ### FUNCTIONS ### board = ['-', '-', '-', '-', '-', '-', '-', '-', '-'] def retry(): btnrow4 = Frame(root, bg="#000000") btnrow4.pack(expand=True, fill=BOTH) labelfinish = Label(btnrow4, text="Re?", font=("Elephant", 72), width=1, bg="#145249", fg="#38B11E", bd=0, relief="ridge", highlightthickness=0) labelfinish.pack(side=LEFT, expand=True, fill=BOTH) byes = Button(btnrow4, text="Yes", font=("Elephant", 72), width=1, bg="#145249", fg="#38B11E", bd=0, relief="ridge", highlightthickness=0, command= lambda: retryButton(1, btnrow4, labelfinish, byes, bno)) byes.pack(side=LEFT, expand=True, fill=BOTH) bno = Button(btnrow4, text="No", font=("Elephant", 72), width=1, bg="#145249", fg="#38B11E", bd=0, relief="ridge", highlightthickness=0, command= lambda: retryButton(0, btnrow4, labelfinish, byes, bno)) bno.pack(side=LEFT, expand=True, fill=BOTH) root.update() def clearBoard(aboard): for i in range(0, 9): board[i] = "-" b1.config(text="") b2.config(text="") b3.config(text="") b4.config(text="") b5.config(text="") b6.config(text="") b7.config(text="") b8.config(text="") b9.config(text="") def checkWin(aboard): if aboard[0] == "X" and aboard[1] == "X" and aboard[2] == "X": return True elif aboard[3] == "X" and aboard[4] == "X" and aboard[5] == "X": return True elif aboard[6] == "X" and aboard[7] == "X" and aboard[8] == "X": return True elif aboard[0] == "X" and aboard[3] == "X" and aboard[6] == "X": return True elif aboard[1] == "X" and aboard[4] == "X" and aboard[7] == "X": return True elif aboard[2] == "X" and aboard[5] == "X" and aboard[8] == "X": return True elif aboard[0] == "X" and aboard[4] == "X" and aboard[8] == "X": return True elif aboard[2] == "X" and aboard[4] == "X" and aboard[6] == "X": return True elif aboard[0] == "O" and aboard[1] == "O" and aboard[2] == "O": return True elif aboard[3] == "O" and aboard[4] == "O" and aboard[5] == "O": return True elif aboard[6] == "O" and aboard[7] == "O" and aboard[8] == "O": return True elif aboard[0] == "O" and aboard[3] == "O" and aboard[6] == "O": return True elif aboard[1] == "O" and aboard[4] == "O" and aboard[7] == "O": return True elif aboard[2] == "O" and aboard[5] == "O" and aboard[8] == "O": return True elif aboard[0] == "O" and aboard[4] == "O" and aboard[8] == "O": return True elif aboard[2] == "O" and aboard[4] == "O" and aboard[6] == "O": return True elif available(aboard) == 0: retry() return False def retryButton(button, btnrow, label, byes, bno): if button == 1: label.pack_forget() byes.pack_forget() bno.pack_forget() btnrow.pack_forget() clearBoard(board) root.update() else: root.quit() def buttonClicked(button): if board[button-1] == '-': board[button-1] = "X" if button == 1: b1.config(text="X") elif button == 2: b2.config(text="X") elif button == 3: b3.config(text="X") elif button == 4: b4.config(text="X") elif button == 5: b5.config(text="X") elif button == 6: b6.config(text="X") elif button == 7: b7.config(text="X") elif button == 8: b8.config(text="X") else: b9.config(text="X") if(checkWin(board)): root.update() retry() root.update() if available(board) > 0: aiPlayGame() def findPlacement(): temp = board for i in range(0, 9): if temp[i] == "-": temp[i] = "O" if checkWin(temp): temp[i] = "-" return i else: temp[i] = "-" for i in range(0, 9): if temp[i] == "-": temp[i] = "X" if checkWin(temp): temp[i] = "-" return i else: temp[i] = "-" return random.randint(0, 8) def aiPlayGame(): while True: placement = findPlacement() if board[placement] == "-": break board[placement] = "O" if placement + 1 == 1: b1.config(text="O") elif placement + 1 == 2: b2.config(text="O") elif placement + 1 == 3: b3.config(text="O") elif placement + 1 == 4: b4.config(text="O") elif placement + 1 == 5: b5.config(text="O") elif placement + 1 == 6: b6.config(text="O") elif placement + 1 == 7: b7.config(text="O") elif placement + 1 == 8: b8.config(text="O") else: b9.config(text="O") if(checkWin(board)): root.update() retry() root.update() def available(origBoard): counter = 0 for i in range(0, 9): if origBoard[i] == "-": counter = counter + 1 return counter ### CREATING THE BOARD ### root = Tk() root.geometry("900x900") root.title("Ultimate Tic Tac Toe") btnrow1 = Frame(root, bg="#000000") btnrow1.pack(expand=True, fill=BOTH) btnrow2 = Frame(root, bg="#000000") btnrow2.pack(expand=True, fill=BOTH) btnrow3 = Frame(root, bg="#000000") btnrow3.pack(expand=True, fill=BOTH) b1 = Button(btnrow1, font=("Elephant", 72), width=1, bg="#000000", fg="white", bd=0, command= lambda: buttonClicked(1)) b1.pack(side=LEFT, expand=True, fill=BOTH) b2 = Button(btnrow1, font=("Elephant", 72), width=1, bg="#000000", fg="white", bd=0, command= lambda: buttonClicked(2)) b2.pack(side=LEFT, expand=True, fill=BOTH) b3 = Button(btnrow1, font=("Elephant", 72), width=1, bg="#000000", fg="white", bd=0, command= lambda: buttonClicked(3)) b3.pack(side=LEFT, expand=True, fill=BOTH) b4 = Button(btnrow2, font=("Elephant", 72), width=1, bg="#000000", fg="white", bd=0, command= lambda: buttonClicked(4)) b4.pack(side=LEFT, expand=True, fill=BOTH) b5 = Button(btnrow2, font=("Elephant", 72), width=1, bg="#000000", fg="white", bd=0, command= lambda: buttonClicked(5)) b5.pack(side=LEFT, expand=True, fill=BOTH) b6 = Button(btnrow2, font=("Elephant", 72), width=1, bg="#000000", fg="white", bd=0, command= lambda: buttonClicked(6)) b6.pack(side=LEFT, expand=True, fill=BOTH) b7 = Button(btnrow3, font=("Elephant", 72), width=1, bg="#000000", fg="white", bd=0, command= lambda: buttonClicked(7)) b7.pack(side=LEFT, expand=True, fill=BOTH) b8 = Button(btnrow3, font=("Elephant", 72), width=1, bg="#000000", fg="white", bd=0, command= lambda: buttonClicked(8)) b8.pack(side=LEFT, expand=True, fill=BOTH) b9 = Button(btnrow3, font=("Elephant", 72), width=1, bg="#000000", fg="white", bd=0, command= lambda: buttonClicked(9)) b9.pack(side=LEFT, expand=True, fill=BOTH) ### THE ACTUAL GAME ### root.mainloop()
c1cc96135f3218988331b42b70c30a1621603a49
[ "Markdown", "Python" ]
2
Markdown
nikolaj808/python-tictactoe
e977814fde6a5b87c2fee15d7078cf971b1fc882
d863ea957ff79cdd21baf1d6bf93073d238a61ff
refs/heads/master
<repo_name>thejibz/graphql-starwars<file_sep>/src/main/java/models/Droid.java package models; public class Droid extends Character { private String primaryFunction; public String getPrimaryFunction() { return primaryFunction; } public void setPrimaryFunction(String primaryFunction) { this.primaryFunction = primaryFunction; } } <file_sep>/src/main/java/models/Human.java package models; import java.util.List; public class Human extends Character { private float height; private List<Starship> starships; public float getHeight() { return height; } public void setHeight(float height) { this.height = height; } public List<Starship> getStarships() { return starships; } public void setStarships(List<Starship> starships) { this.starships = starships; } }
11c3132a023ed1b58e29ce784b22970ac3417504
[ "Java" ]
2
Java
thejibz/graphql-starwars
c46d8c8326423ec7e8ef99f95eecc94c2c6ebe41
ccc859ad9f64e616ca97e9e8e265e20ac595b205
refs/heads/master
<repo_name>joinhandshake/handshake-ios-identifiable-tableview<file_sep>/Identifiable/TableViewController/TableViewController.swift // // TableViewController.swift // Pairing-Feed // // Created by <NAME> on 1/1/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit class TableViewController: UIViewController { var sections = [TableViewSection]() { didSet { registerCells() tableView.reloadData() } } let tableView: UITableView init(style: UITableViewStyle = .grouped) { tableView = UITableView(frame: .zero, style: style) super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() view.addSubview(tableView) tableView.rowHeight = UITableViewAutomaticDimension //Delegation tableView.delegate = self tableView.dataSource = self //Constraints tableView.translatesAutoresizingMaskIntoConstraints = false tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0).isActive = true tableView.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0).isActive = true tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) tableView.reloadData() } private func registerCells() { sections.forEach({ section in section.cellModels.forEach{ tableView.register($0.cellClass, forCellReuseIdentifier: $0.cellIdentifier) } if let header = section.headerCellModel { tableView.register(header.cellClass, forCellReuseIdentifier: header.cellIdentifier) } if let footer = section.footerCellModel { tableView.register(footer.cellClass, forCellReuseIdentifier: footer.cellIdentifier) } }) } } extension TableViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return sections[section].headerCellModel == nil ? 0.00001 : UITableViewAutomaticDimension } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return sections[section].footerCellModel == nil ? 0.00001 : UITableViewAutomaticDimension } func numberOfSections(in tableView: UITableView) -> Int { return sections.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return sections[section].cellModels.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cellModel = sections[indexPath.section].cellModels[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: cellModel.cellIdentifier, for: indexPath) if let cell = cell as? IdentifiableCell { cell.configure(cellModel: cellModel) } return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { //Subclass must override this } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { guard let headerCellModel = sections[section].headerCellModel, let cell = tableView.dequeueReusableCell(withIdentifier: headerCellModel.cellIdentifier) else { return nil } if let cell = cell as? IdentifiableCell { cell.configure(cellModel: headerCellModel) } return cell } func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { guard let footerCellModel = sections[section].footerCellModel, let cell = tableView.dequeueReusableCell(withIdentifier: footerCellModel.cellIdentifier) else { return nil } if let cell = cell as? IdentifiableCell { cell.configure(cellModel: footerCellModel) } return cell } } <file_sep>/Identifiable/TableViewController/TableViewSection.swift // // TableViewSection.swift // Identifiable // // Created by <NAME> on 2/20/18. // Copyright © 2018 Handshake. All rights reserved. // struct TableViewSection { let cellModels: [IdentifiableCellModel] let headerCellModel: IdentifiableCellModel? let footerCellModel: IdentifiableCellModel? init(cellModels: [IdentifiableCellModel], headerCellModel: IdentifiableCellModel? = nil, footerCellModel: IdentifiableCellModel? = nil) { self.cellModels = cellModels self.headerCellModel = headerCellModel self.footerCellModel = footerCellModel } } <file_sep>/Identifiable/Sample/ConversationViewController.swift // // ConversationViewController.swift // Identifiable // // Created by <NAME> on 2/14/18. // Copyright © 2018 Handshake. All rights reserved. // import UIKit class ConversationViewController: TableViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white tableView.separatorStyle = .none tableView.backgroundColor = .white let plainCellModels: [IdentifiableCellModel] = [ PlainCellModel(label: "It’s important to use cocoa butter. It’s the key to more success, why not live smooth? Why live rough? Life is what you make it, so let’s make it. The key is to enjoy life, because they don’t want you to enjoy life."), PlainCellModel(label: "They don’t want us to win. It’s on you how you want to live your life. Everyone has a choice.") ] let messageCellModels: [IdentifiableCellModel] = [ MessageCellModel(name: "Daniel", comment: "The first of the month is coming, we have to get money, we have no choice. It cost money to eat and they don’t want you to eat. They don’t want us to eat.", time: Date()), OtherMessageCellModel(name: "Heather", comment: "Life is what you make it, so let’s make it. You should never complain, complaining is a weak emotion, you got life, we breathing, we blessed.", time: Date()), OtherMessageCellModel(name: "Heather", comment: "A major key, never panic. Don’t panic, when it gets crazy and rough, don’t panic, stay calm.", time: Date()), MessageMetaCellModel(info: "Yesterday at 12:32pm"), MessageCellModel(name: "Daniel", comment: "The first of the month is coming, we have to get money, we have no choice. It cost money to eat and they don’t want you to eat. They don’t want us to eat.", time: Date()), OtherMessageCellModel(name: "Heather", comment: "Life is what you make it, so let’s make it. You should never complain, complaining is a weak emotion, you got life, we breathing, we blessed.", time: Date()), OtherMessageCellModel(name: "Heather", comment: "A major key, never panic. Don’t panic, when it gets crazy and rough, don’t panic, stay calm.", time: Date()) ] let plainSection = TableViewSection(cellModels: plainCellModels) let messagesSection = TableViewSection(cellModels: messageCellModels) sections = [plainSection, messagesSection] } } <file_sep>/Identifiable/Sample/PlainCellModel.swift // // PlainCellModel.swift // Identifiable // // Created by <NAME> on 1/23/18. // Copyright © 2018 Handshake. All rights reserved. // import Foundation struct PlainCellModel: IdentifiableCellModel { //IdentifiableCellModel var cellIdentifier: String = { return String(describing: PlainCell.self) }() var cellClass: AnyClass { return PlainCell.self } //Other properties let labelStr: String init(label: String) { labelStr = label } } <file_sep>/Identifiable/Sample/MessageMetaCell.swift // // MessageMetaCell.swift // Identifiable // // Created by <NAME> on 2/14/18. // Copyright © 2018 Handshake. All rights reserved. // import UIKit class MessageMetaCell: UITableViewCell, IdentifiableCell { let infoLabel: UILabel = { let label = UILabel() label.textColor = .lightGray label.font = UIFont.systemFont(ofSize: 10) label.textAlignment = .center return label }() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) selectionStyle = .none backgroundColor = .white addSubview(infoLabel) installConstraints() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func configure(cellModel: IdentifiableCellModel) { guard let cellModel = cellModel as? MessageMetaCellModel else { return } infoLabel.text = cellModel.infoStr } private func installConstraints() { infoLabel.translatesAutoresizingMaskIntoConstraints = false infoLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 0).isActive = true infoLabel.topAnchor.constraint(equalTo: topAnchor, constant: 0).isActive = true infoLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: 0).isActive = true infoLabel.bottomAnchor.constraint(equalTo: bottomAnchor, constant: 0).isActive = true } } <file_sep>/Identifiable/Sample/MessageCell.swift // // MessageCell.swift // Identifiable // // Created by <NAME> on 1/23/18. // Copyright © 2018 Handshake. All rights reserved. // import UIKit class MessageCell: UITableViewCell, IdentifiableCell { let nameLabel: UILabel = { let label = UILabel() label.textColor = .lightGray label.font = UIFont.systemFont(ofSize: 12) label.textAlignment = .right return label }() let commentTextView: UITextView = { let textView = UITextView() textView.textColor = .white textView.backgroundColor = .blue textView.isScrollEnabled = false textView.isEditable = false textView.font = UIFont.systemFont(ofSize: 14) textView.layer.cornerRadius = 6 return textView }() let timeLabel: UILabel = { let label = UILabel() label.textColor = .lightGray label.font = UIFont.systemFont(ofSize: 10) label.textAlignment = .right return label }() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) selectionStyle = .none backgroundColor = .white addSubview(nameLabel) addSubview(commentTextView) addSubview(timeLabel) installConstraints() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func configure(cellModel: IdentifiableCellModel) { guard let cellModel = cellModel as? MessageCellModel else { return } nameLabel.text = cellModel.nameStr commentTextView.text = cellModel.commentStr timeLabel.text = cellModel.timeStr } private func installConstraints() { nameLabel.translatesAutoresizingMaskIntoConstraints = false commentTextView.translatesAutoresizingMaskIntoConstraints = false timeLabel.translatesAutoresizingMaskIntoConstraints = false nameLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 10).isActive = true nameLabel.topAnchor.constraint(equalTo: topAnchor, constant: 10).isActive = true nameLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -10).isActive = true commentTextView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 40).isActive = true commentTextView.topAnchor.constraint(equalTo: nameLabel.bottomAnchor, constant: 5).isActive = true commentTextView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -10).isActive = true timeLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 10).isActive = true timeLabel.topAnchor.constraint(equalTo: commentTextView.bottomAnchor, constant: 5).isActive = true timeLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -10).isActive = true timeLabel.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -10).isActive = true } } <file_sep>/Identifiable/TableViewController/IdentifiableCell.swift // // IdentifiableCell.swift // Identifiable // // Created by <NAME> on 1/23/18. // Copyright © 2018 Handshake. All rights reserved. // import Foundation protocol IdentifiableCell { func configure(cellModel: IdentifiableCellModel) } protocol IdentifiableCellModel { var cellIdentifier: String { get } var cellClass: AnyClass { get } } <file_sep>/README.md # handshake-ios-identifiable-tableview An example of protocol-oriented programming that drastically simplifies the `cellForRowAtIndexPath` method <file_sep>/Identifiable/Sample/MessageMetaCellModel.swift // // MessageMetaCellModel.swift // Identifiable // // Created by <NAME> on 2/14/18. // Copyright © 2018 Handshake. All rights reserved. // import Foundation public struct MessageMetaCellModel: IdentifiableCellModel { //IdentifiableCellModel var cellIdentifier: String = { return String(describing: MessageMetaCell.self) }() var cellClass: AnyClass { return MessageMetaCell.self } //Other properties let infoStr: String init(info: String) { infoStr = info } } <file_sep>/Identifiable/Sample/OtherMessageCellModel.swift // // OtherMessageCellModel.swift // Identifiable // // Created by <NAME> on 2/14/18. // Copyright © 2018 Handshake. All rights reserved. // import Foundation struct OtherMessageCellModel: IdentifiableCellModel { //IdentifiableCellModel var cellIdentifier: String = { return String(describing: OtherMessageCell.self) }() var cellClass: AnyClass { return OtherMessageCell.self } //Other properties let nameStr: String let commentStr: String let timeStr: String init(name: String, comment: String, time: Date) { nameStr = name commentStr = comment let formatter = DateFormatter() formatter.dateFormat = "dd HH:mm" formatter.calendar = Calendar(identifier: .iso8601) formatter.timeZone = TimeZone(secondsFromGMT: 0) formatter.locale = Locale(identifier: "en_US_POSIX") timeStr = formatter.string(from: time) } } <file_sep>/Identifiable/Sample/PlainCell.swift // // PlainCell.swift // Identifiable // // Created by <NAME> on 1/23/18. // Copyright © 2018 Handshake. All rights reserved. // import UIKit class PlainCell: UITableViewCell, IdentifiableCell { let label: UILabel = { let label = UILabel() label.numberOfLines = 0 return label }() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) selectionStyle = .none backgroundColor = .white addSubview(label) installConstraints() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func configure(cellModel: IdentifiableCellModel) { guard let cellModel = cellModel as? PlainCellModel else { return } label.text = cellModel.labelStr } private func installConstraints() { label.translatesAutoresizingMaskIntoConstraints = false label.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 20).isActive = true label.topAnchor.constraint(equalTo: topAnchor, constant: 10).isActive = true label.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -20).isActive = true label.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -10).isActive = true } }
4abfa26a9ac17333581f1afd93f73f00804856c7
[ "Swift", "Markdown" ]
11
Swift
joinhandshake/handshake-ios-identifiable-tableview
0b12c413ba284bfc36238a1b28b8774ceb5a5335
acd95d9f9c689c27b8de04711c4763f73b300982
refs/heads/main
<file_sep># Lista-Cuadricula_ArelyAF utilizar dos layouts disponibles para hacer un cambio de interfaz, donde se mostrará una lista y el usuario tendrá la opción de cambiar a un diseño de cuadrícula. <NAME> M-200559 4° "A" DISEÑO DE APPS TIADSM ENLACE: https://youtu.be/SuwRuIOl8TQ <file_sep>package com.arelyaf.arelyaguilarfariasm_200559; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.os.Bundle; import android.view.View; import android.widget.Button; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { RecyclerView recyclerView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); recyclerView = findViewById(R.id.recyclerView); Button btnlista, btncuadricula; recyclerView = findViewById(R.id.recyclerView); btnlista = findViewById(R.id.btnlista); btncuadricula = findViewById(R.id.btncuadricula); ArrayList<Productos> productoss = new ArrayList<>(); productoss.add(new Productos(R.drawable.blusa, "Top de malla con bordado de lunares", "$158.00", "Color:\tBlanco\n" + "Estilo:\tBohemio\n" + "Tipo de Estampado:\tLiso\n" + "Detalles:\tBordado, Escamas, Malla en contraste\n" + "Largo:\tNormal\n" + "Temporada:\tVerano\n" + "Tipo:\tTop")); productoss.add(new Productos(R.drawable.blusamorada, "Top con cinturón bajo irregular", "$270.00", "Color:\tMorado\n" + "Estilo:\tElegante\n" + "Tipo de Estampado:\tLiso\n" + "Detalles:\tCinta, asimétrico\n" + "Largo:\tNormal\n" + "Temporada:\tPrimavera/Otoño\n" + "Tipo:\tTop")); productoss.add(new Productos(R.drawable.junpernegro, "Mono sin mangas con dobladillo con cordones en la espalda y ojo de cerradura", "$150.00", "Estilo: deportivo\n" + "De color negro\n" + "Tipo de patrón: liso\n" + "Longitud: larga\n" + "Temporada: primavera / verano\n" + "Tipo: Unitard\n" + "Detalles: Recortar, Cordones, Botón\n" + "Tipo de ajuste: flaco")); productoss.add(new Productos(R.drawable.blusanude, " Blusa con malla escote V", "$200.00", "Color:\tRosa\n" + "Estilo:\tElegante\n" + "Tipo de Estampado:\tLiso\n" + "Detalles:\tTransparente\n" + "Largo:\tNormal\n" + "Temporada:\tVerano\n" + "Tipo:\tTop")); productoss.add(new Productos(R.drawable.pantalonrayado, "Pantalones pitillo de rayas verticales", "$238.00", "Estilo: casual\n" + "Color: blanco y negro\n" + "Tipo de patrón: Rayado\n" + "Longitud: larga\n" + "Temporada: primavera / verano / otoño\n" + "Detalles: Bolsa\n" + "Tipo de ajuste: flaco")); productoss.add(new Productos(R.drawable.pijamaazul, "Pijamas de Mujer Encaje en contraste Liso Sexy", "$250.00", "Estilo:\tSexy\n" + "Color:\tVerde\n" + "Tipo de Estampado:\tLiso\n" + "Tipo:\tConjunto de Pantalones Cortos\n" + "Número de piezas:\tConjunto de 2 piezas\n" + "Detalles:\tEncaje en contraste\n" + "Escote:\tTirantes finos\n" + "Longitud de la Manga:\tsin mangas")); productoss.add(new Productos(R.drawable.vestidoajustado, "Vestido estilo camiseta ajustado de tie dye","$80", "\tMulticolor\n" + "Estilo:\tCasual\n" + "Tipo de Estampado:\tTie-Dye\n" + "Largo:\tShort\n" + "Temporada:\tVerano\n" + "Tipo:\tApretado\n" + "Tipo de ajuste:\tAjustado")); productoss.add(new Productos(R.drawable.vestidoblanco, "Vestido de manga con malla con encaje de espalda abierta con nudo", "$400.00", "Color:\tBlanco\n" + "Estilo:\tSexy\n" + "Tipo de Estampado:\tLiso\n" + "Largo:\tShort\n" + "Temporada:\tPrimavera/Verano\n" + "Tipo:\tA línea")); productoss.add(new Productos(R.drawable.vestidofloral, "Vestido con estampado tropical de puño fruncido de cintura alta", "$160.00", "Color:\tMulticolor\n" + "Estilo:\tBohemio\n" + "Tipo de Estampado:\tTropical\n" + "Largo:\tShort\n" + "Temporada:\tVerano\n" + "Tipo:\tA línea\n" + "Detalles:\tVolante\n" + "Tipo de ajuste:\tRegular")); productoss.add(new Productos(R.drawable.vestidorayas, "Vestido de rayas con encaje", "$120.00", "Color:\tBlanco y Negro\n" + "Estilo:\tSexy, Casual\n" + "Tipo de Estampado:\tA rayas\n" + "Largo:\tShort\n" + "Tipo:\tcamiseta\n" + "Escote:\tcuello redondo")); productoss.add(new Productos(R.drawable.vestidorojo, "Vestido con estampado de margarita", "$300.00", "Color:\tRojo\n" + "Estilo:\tBohemio\n" + "Tipo de Estampado:\tfloral de margarita\n" + "Largo:\tShort\n" + "Temporada:\tVerano\n" + "Tipo:\tA línea\n" + "Detalles:\tCremallera")); productoss.add(new Productos(R.drawable.vestidoverde, "Vestido fruncido de manga con malla aplique con flor", "$420.00", "Color:\tVerde Oscuro\n" + "Estilo:\tGlamour\n" + "Tipo de Estampado:\tLiso\n" + "Largo:\tLargo\n" + "Temporada:\tPrimavera/Verano\n" + "Tipo:\tA línea\n" + "Detalles:\tTransparente, Malla en contraste, Apliques, Tablas, Cremallera")); ProductosAdapter adapter = new ProductosAdapter(this, productoss); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this); GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 2); btnlista.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { recyclerView.setLayoutManager(linearLayoutManager); } }); btncuadricula.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { recyclerView.setLayoutManager(gridLayoutManager); } }); recyclerView.setLayoutManager(gridLayoutManager); recyclerView.setAdapter(adapter); } }
1de97039e6f101d847577f11221972150f1b7dd3
[ "Markdown", "Java" ]
2
Markdown
Arely2409/Lista-Cuadricula_ArelyAF
4f6ea37649943d1b9e9235df37c537ca9656ceb6
5bd089caf0603d49315d433c7d2da0d12951b7e6
refs/heads/master
<file_sep>const electron = require('electron'); const { app, BrowserWindow } = electron; require('electron-reload')(__dirname, { ignored: /temp\/|node_modules\// }); let mainWindow; app.on('ready', () => { let mainWindow = new BrowserWindow({ width: 800, height: 600 }); mainWindow.loadURL('file://'+__dirname+'/app/index.html'); });<file_sep>const path = require('path') import React, { Component } from 'react' import { Map } from 'coloreact' import Hue from './Hue.jsx' import HueSlider from './HueSlider.jsx' import SatSlider from './SatSlider.jsx' import ValSlider from './ValSlider.jsx' const tinycolor = require('tinycolor2') import { connect } from 'react-redux' class ColourArea extends Component { constructor(props) { super(props) this.state = { h: 0, s: 0, v: 0, hex: "#000000" } } render() { this.props.giveColour(this.state.hex) return ( <div className="colour-area"> <div className="colour-area-picker"> <Map x={this.state.s} y={this.state.v} backgroundColor={tinycolor(`hsv(${this.state.h}, 100, 100)`).toHexString()} max={100} onChange={this.handleSaturationValue.bind(this)} className="sat-val-map" pointerStyle={{ color: (this.state.s > 50 || this.state.v < 70) ? 'white' : 'black' }} /> <Hue onHueChange={this.handleHue.bind(this)} hue={this.state.h} className="hue-circle"/> <div className="pseudo-border-hue"/> <div className="pseudo-border-hue2"/> </div> <div className="colours-sliders"> <span className="colour-labels">H: {(this.state.h)}</span> <HueSlider onHueSlide={this.handleHue.bind(this)} hue={this.state.h} className="slider" width={360} height={30}/> <span className="colour-labels">S: {Math.round(this.state.s)}</span> <SatSlider onSatSlide={this.handleSat.bind(this)} hue={this.state.h} sat={this.state.s} val={this.state.v} className="slider" width={360} height={30}/> <span className="colour-labels">V: {Math.round(this.state.v)}</span> <ValSlider onValSlide={this.handleVal.bind(this)} hue={this.state.h} sat={this.state.s} val={this.state.v} className="slider" width={360} height={30}/> </div> <div className="colour-preview" style={{backgroundColor: this.state.hex}}/> <div className="control-buttons"> <div className="control-button"><i className="material-icons">attach_file</i></div> <div className="control-button" onClick={this.handleFileUpload.bind(this)}><i className="material-icons">insert_drive_file</i></div> </div> </div> ) } handleHue(h) { this.setState({h: h, hex: tinycolor(`hsv(${h}, ${this.state.s}%, ${this.state.v}%)`).toHexString()}) } handleSat(s) { this.setState({s: s, hex: tinycolor(`hsv(${this.state.h}, ${s}%, ${this.state.v}%)`).toHexString()}) } handleVal(v) { this.setState({v: v, hex: tinycolor(`hsv(${this.state.h}, ${this.state.s}%, ${v}%)`).toHexString()}) } handleSaturationValue(s, v) { this.setState({ s: s, v: v, hex: tinycolor(`hsv(${this.state.h}, ${s}%, ${v}%)`).toHexString()}) } handleFileUpload() { require('electron').remote.dialog.showOpenDialog({ properties: ['openFile'], filters: [ { name: 'Images', extensions: ['jpg', 'png', 'jpeg'] } ] }, filepath => { this.props.chooseImage(path.normalize(filepath[0]).replace(/\\/g, "/")) }) } } const mapDispatchToProps = dispatch => { return { chooseImage: filepath => dispatch({ type: "OPEN_IMAGE", payload: { imagePath: filepath, sampleRadius: 50 } }), giveColour: hex => dispatch({ type: "GIVE_COLOUR", payload: { colour: hex } }) } } export default connect(null, mapDispatchToProps)(ColourArea)<file_sep>import React, { Component } from 'react'; import { render } from 'react-dom'; import ColourArea from './components/ColourArea.jsx' import UserImage from './components/UserImage.jsx' require("./styles/main.sass"); export default class App extends Component { render() { return( <div className="wrapper"> <UserImage/> <ColourArea/> </div> ); } }<file_sep>const path = require('path') import React, { Component } from 'react'; import { connect } from 'react-redux' const tinycolor = require('tinycolor2') const Jimp = require('jimp') const MAX_WIDTH = 950 const MAX_HEIGHT = 500 class UserImage extends Component { constructor(props) { super(props) this.state = { imagePath: this.props.imagePath, answer: 'transparent' } this.totalH = 0 this.totalS = 0 this.totalV = 0 this.avgH = 0 this.avgS = 0 this.avgV = 0 this.pixCount = 0 } componentWillReceiveProps(props) { console.log('props') if(props.imagePath && props.imagePath != this.props.imagePath ) { this.readAndResizeImage(props.imagePath, img=> { this.sampleImage(img) }) } } render() { console.log(this.state.imagePath) return ( <div className="user-image-wrapper"> <div/> <div className="image-wrapper"> <img src={this.state.imagePath} className="user-image"/> </div> <div className="answer-area"> <div className="colours-compare"> <div className="show-colour" style={{backgroundColor: this.state.answer}}/> <div className="show-colour" style={{backgroundColor: this.state.userColour}}/> </div> <div className="reveal-button" onClick={this.revealAnswer.bind(this)}>Reveal Answer</div> <div className="reset-button control-button" onClick={this.resetSample.bind(this)}><i className="material-icons">replay</i></div> </div> </div> ); } revealAnswer() { if(this.state.imagePath) { var ans = tinycolor(`hsv(${this.avgH}, ${this.avgS}, ${this.avgV})`).toHexString() this.setState({answer: ans, userColour: this.props.userColour}) } } resetSample() { this.readAndResizeImage(this.props.imagePath, img=> { this.sampleImage(img) }) this.setState({answer: 'transparent', userColour: 'transparent'}) } readAndResizeImage(imgpath, cb) { Jimp.read(imgpath, (err, img) => { const imgw = img.bitmap.width const imgh = img.bitmap.height if(imgw <= MAX_WIDTH && imgh <= MAX_HEIGHT) { console.log("smaller") } else if(imgw > MAX_WIDTH || imgh > MAX_HEIGHT) { if(imgw/imgh > MAX_WIDTH/MAX_HEIGHT) { img.resize(MAX_WIDTH) } else if(imgw/imgh<=MAX_WIDTH/MAX_HEIGHT) { img.resize(Jimp.AUTO, MAX_HEIGHT) } } cb(img) }) } sampleImage(img) { console.log('from func', img) var startX = Math.floor(Math.random()*(img.bitmap.width))-this.props.sampleRadius var startY = Math.floor(Math.random()*(img.bitmap.height))-this.props.sampleRadius this.totalH = 0, this.totalS = 0, this.totalV = 0, this.avgH = 0, this.avgS = 0, this.avgV = 0, this.pixCount = 0 console.log(startX, startY, this.props.sampleRadius, this.props.sampleRadius) img.scan(startX, startY, this.props.sampleRadius, this.props.sampleRadius, (x, y, idx) => { if(x == startX || x==startX+this.props.sampleRadius-1 || y==startY || y==startY+this.props.sampleRadius-1) { img.setPixelColor(0xFFFFFFFF, x, y) } else { img.getPixelColor(x, y, (err, hex) => { if(err) throw err if(tinycolor('#'+hex.toString(16)).toHsv().a == 1) { this.totalH += tinycolor('#'+hex.toString(16)).toHsv().h this.totalS += tinycolor('#'+hex.toString(16)).toHsv().s this.totalV += tinycolor('#'+hex.toString(16)).toHsv().v this.pixCount++ } else { console.log("OHHHH", hex) } }) } if(x == startX+this.props.sampleRadius-1 && y == startY+this.props.sampleRadius-1) { this.avgH = this.totalH/this.pixCount this.avgS = this.totalS/this.pixCount this.avgV = this.totalV/this.pixCount console.log("done ", this.totalH, this.totalS, this.totalV) const rand = Math.floor(Math.random()*88888) img.write(path.join(__dirname, "../temp/"+rand+".png"), (err, img) => { this.setState({ imagePath: path.join(__dirname, "../temp/"+rand+".png").replace(/\\/g, "/") }) }) } }) } } const mapStateToProps = state => { return { imagePath: state.imagePath, sampleRadius: state.sampleRadius, userColour: state.colour } } export default connect(mapStateToProps)(UserImage)
8abc5ab899a8ec95c2a9353cc25d715b5eef975b
[ "JavaScript" ]
4
JavaScript
josephsurin/colour-game
dfdcce3aa4e9faa3c66118f6908a2c605bdf3570
219124ad603479976eaf17263791fa5bd7cf1c8f
refs/heads/master
<repo_name>DerrikC/movies_cms<file_sep>/load.php <?php define('ABSPATH', __DIR__); define('ADMIN_PATH', ABSPATH. '/admin'); define('ADMIN_SCRIPT_PATH', ADMIN_PATH. '/scripts'); // echo ABSPATH; // exit; ini_set('display_errors', 1); require_once ABSPATH. '/config/database.php'; require_once ADMIN_SCRIPT_PATH. '/read.php';
7c27ca745a9b5abca4ea6015681a8a921f4612dd
[ "PHP" ]
1
PHP
DerrikC/movies_cms
272a0dfa13944d3045af61e77daf071387485b34
b6eecf9945441c26584cff98be3789e254b3db90
refs/heads/master
<file_sep># blogg blogg description: <br>a simple blog content management system <br>it is under development <br>right now not implemented as MVC (model view control) structure <br>updates will be provided soon todo: - [ ] implement cookie login etc - [ ] implement google auth.. - [ ] social media login - [ ] improve database structure (lot to be done) - [x] improve user interface <file_sep><?php include_once"connect.php"; $query= "SELECT * FROM posts"; $result=$db->query($query) or die('Create db failed query1'); while($row=$result->fetchArray()) {$body=htmlspecialchars_decode($row['body']); echo"title: {$row['title']}<br>body: {$body}<br>authorid: {$row['authorid']}<br> <br>";} $qry=<<<EOD DROP TABLE posts EOD; //$db->exec($qry); ?> <html> <head> <title></title> <script src="http://code.jquery.com/jquery-latest.js"></script> <h2>Test Page</h2> <script src="http://js.nicedit.com/nicEdit-latest.js" type="text/javascript"></script> <script type="text/javascript">bkLib.onDomLoaded(nicEditors.allTextAreas);</script> <table class="form"> <form action="" enctype="multipart/form-data" method="POST"> <tr> <td><textarea rows="10" cols="100" name="3" id="area1" name="content">A long time ago in a galaxy far, far away...</textarea></td> </tr> <tr> <td align="center" style="padding-bottom: 10px;"> <input type="submit" onclick="nicEditors.findEditor('area1').saveContent(); name="update" value="Save Changes"> </td> </tr> </form> </table> <? print_r($_REQUEST); ?> </body> </html><file_sep><?php //echo sqlite_libversion(); print_r(SQLite3::version()); echo "<br>"; echo phpversion(); /* $dbhandle=sqlite3::open('test.db',0666,$error); if(!$dbhandle) die ($error); $stm="CREATE TABLE posts(Id integer PRIMARY KEY,". "Name text UNIQUE NOT NULL"; $OK=sqlite_exec($dbhandle,$stm,$error); if(!$OK) die("cannot execute query. $error"); echo "Datbase [posts] created successfully"; sqlite_close($dbhandle); */ $db=new SQLite3('database') or die('Unable to open database'); $query= <<<EOD CREATE TABLE IF NOT EXISTS users ( username STRING PRIMARY KEY, password STRING) EOD; $db->exec($query) or die('Create db failed'); $user = mysql_real_escape_string($_POST['username']); //$pass = sanitize($_POST['password']); $pass = mysql_real_escape_string($_POST['password']); $user="himanshu";$pass="<PASSWORD>"; $query=<<<EOD INSERT INTO users VALUES('$user','$pass') EOD; $db->exec($query) or die("Unable to add user $user"); $result=$db->query('SELECT * FROM users') or die('Query failed'); while($row=$result->fetchArray()) {echo"User: {$row['username']}\nPassword: {$row['password']}\n";}<file_sep><?php $db=new SQLite3('database') or die('Unable to open database'); $query1= <<<EOD CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY , username STRING NOT NULL , password STRING NOT NULL, lastlogin DATETIME, role INTEGER DEFAULT 0, unique(username) ) EOD; $query2=<<<EOD CREATE TABLE IF NOT EXISTS posts (postid INTEGER PRIMARY KEY, title TEXT NOT NULL, body TEXT NOT NULL, published DATETIME, authorid INTEGER, UNIQUE (postid)) EOD; $query3=<<<EOD CREATE TABLE IF NOT EXISTS tags ( tagname TEXT NOT NULL PRIMARY KEY, list TEXT, unique (tagname)) EOD; $title='hoo'; $body='halalal'; $date='2007-01-01 10:00:00'; $tags="a, b, cddd, dkdk"; $authorid=14; //yyyy-MM-dd HH:mm:ss $query4=<<<EOD INSERT INTO posts(title,body,published,tags,authorid) VALUES('$title','$body','$date','tags','$authorid'); EOD; $db->exec($query1) or die('Create db failed query1'); $db->exec($query2) or die('Create db failed query2'); $db->exec($query3) or die('Create db failed query3'); ?> <file_sep><?php error_reporting(E_ERROR | E_PARSE); session_start(); date_default_timezone_set("Asia/Kolkata"); include_once"connect.php"; if(isset($_SESSION['id'])) { $user=$_SESSION['username']; $result=$db->query("SELECT * FROM users WHERE username='$user'"); while($row = $result->fetchArray()) { $lastlogin=$row['lastlogin']; $role=$row['role']; } echo "<h2 style='float:right;'>User: $user<br> Lastlogin: $lastlogin <br><a href='profile.php'>#</a></h2>"; if(isset($_POST['title'])&&isset($_POST['body'])) { $authorid=$_SESSION['id']; $title=$_POST['title']; $body=$_POST['body']; $body=htmlspecialchars($body); $qry=<<<EOD INSERT INTO posts(postid,title,body) VALUES(NULL,'$title','$body') EOD; $db->exec($qry) or die("that title exists already! <a href='inpost.php'>Back</a>"); $timenow=date('Y-M-d H:m:s'); $qry1=<<<EOD UPDATE posts SET published = '$timenow',authorid='$authorid' WHERE title='$title' EOD; $db->exec($qry1) or die("time can't be set"); $_SESSION['tags']=$_POST['tags']; /* $result=$db->query('SELECT * FROM posts') or die('query to read failed'); while($row=$result->fetchArray()) {echo"postid: {$row['postid']} Title: {$row['title']} body: {$row['body']} published: {$row['published']} authorid: {$row['authorid']} <br>";}*/ echo "see all posts<a href='showpost.php'>HERE</a>"; } }else header("Location: newlogin.php"); //<script type="text/javascript">bkLib.onDomLoaded(nicEditors.allTextAreas);</script> ?> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>editor</title> <script src="http://js.nicedit.com/nicEdit-latest.js" type="text/javascript"></script> <script type="text/javascript"> //<![CDATA[ bkLib.onDomLoaded(function() { elementArray = document.getElementsByClassName("nice-edit"); for (var i = 0; i < elementArray.length; ++i) { nicEditors.editors.push( new nicEditor().panelInstance( elementArray[i] ) ); } }); //]]> </script> <style> td:nth-child(2){ width: 100%; } textarea{ height:200px; } </style> </head> <body> <div align="center"> <h3><br /> <br /> Sabse bekkar editor<br /> <br /> </h3> </div> <table align="center" cellpadding="5"> <form action="" method="post" enctype="multipart/form-data" name="logform" id="logform" > <tr> <td class="style7"><div align="right">title</div></td> <td><input name="title" type="text" id="title" size="30" maxlength="64" required /></td> </tr> <tr> <td class="style7"><div align="right">body:</div></td> <td><textarea style="width:80%;" name="body" type="textarea" id="body" class="nice-edit" size="50" maxlength="100" >body</textarea></td> </tr> <tr> <tr> <td class="style7"><div align="right">tags:</div></td> <td><input style="width:80%;" name="tags" placeholder="Enter Tags seperated by comma" type="textarea" id="tags" size="30" maxlength="100" ></td> </tr> <tr> <td>&nbsp;</td> <td><input name="Submit" type="submit" value="post" /></td> </tr> </form> </table> </body> </html><file_sep><?php //echo sqlite_libversion(); print_r(SQLite3::version()); echo "<br>"; echo phpversion(); date_default_timezone_set("Asia/Kolkata"); echo date_default_timezone_get(); /* $dbhandle=sqlite3::open('test.db',0666,$error); if(!$dbhandle) die ($error); $stm="CREATE TABLE posts(Id integer PRIMARY KEY,". "Name text UNIQUE NOT NULL"; $OK=sqlite_exec($dbhandle,$stm,$error); if(!$OK) die("cannot execute query. $error"); echo "Datbase [posts] created successfully"; sqlite_close($dbhandle); $db=new SQLite3('database') or die('Unable to open database'); $query= <<<EOD CREATE TABLE IF NOT EXISTS users ( username STRING PRIMARY KEY, password STRING) EOD; $db->exec($query) or die('Create db failed'); $user = mysql_real_escape_string($_POST['username']); //$pass = sanitize($_POST['password']); $pass = mysql_real_escape_string($_POST['password']); $query=<<<EOD INSERT INTO users VALUES('$user','$pass') EOD; $db->exec($query) or die("Unable to add user $user"); $result=$db->query('SELECT * FROM users') or die('Query failed'); while($row=$result->fetchArray()) {echo"User: {$row['username']}\nPassword: {$row['password']}\n";} */ include_once"connect.php"; if(isset($_POST['username'])&&isset($_POST['password'])) { $user=mysql_real_escape_string($_POST['username']); $pass=mysql_real_escape_string($_POST['password']); $qry=<<<EOD INSERT INTO users(id,username,password) VALUES(NULL,'$user','$pass') EOD; $db->exec($qry) or die('unable to add user'); $logincheck=0; $result=$db->query("SELECT count(*) as count FROM users WHERE username='$user' AND password='$pass'") or die('query to read failed'); while($row=$result->fetchArray()) {//echo"User: {$row['username']}\nPassword: {$row['password']}\n"; //echo '<br>'.$row['count'].'<br>'; if($row['count']>$logincheck)$logincheck=$row['count']; } echo '<br>'.$logincheck.'<br>'; $timenow=date('Y-M-d H:m:s'); if($logincheck>0) { $qry1=<<<EOD UPDATE users SET lastlogin = '$timenow' WHERE username='$user' EOD; //UPDATE users SET lastlogin = now() WHERE username='$user' $db->exec($qry1) or die("nit");} } $result=$db->query('SELECT * FROM users') or die('query to read failed'); while($row=$result->fetchArray()) {echo"User: {$row['username']} Password: {$row['<PASSWORD>']} id: {$row['id']} lastlogin: {$row['lastlogin']} role: {$row['role']}<br>"; } ?> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Login to your profile</title> </head> <body> <div align="center"> <h3><br /> <br /> Log in to your account here<br /> <br /> </h3> </div> <table align="center" cellpadding="5"> <form action="" method="post" enctype="multipart/form-data" name="logform" id="logform" onsubmit="return validate_form ( );"> <tr> <td class="style7"><div align="right">username</div></td> <td><input name="username" type="text" id="username" size="30" maxlength="64" /></td> </tr> <tr> <td class="style7"><div align="right">Password:</div></td> <td><input name="password" type="<PASSWORD>" id="password" size="30" maxlength="24" /></td> </tr> <tr> <td>&nbsp;</td> <td><input name="Submit" type="submit" value="Login" /></td> </tr> </form> </table> </body> </html><file_sep><?php $sessionsdir = "sessions/"; $output_file = "../display/Output.txt"; if (empty($_SERVER["HTTP_IF_NONE_MATCH"])) { $random_id_length = 10; $rnd_id = crypt(uniqid(rand(),1)); $rnd_id = strip_tags(stripslashes($rnd_id)); $rnd_id = str_replace(".","",$rnd_id); $rnd_id = strrev(str_replace("/","",$rnd_id)); $rnd_id = substr($rnd_id,0,$random_id_length); $etagHeader = $rnd_id; } else { // $etagHeader=trim($_SERVER['HTTP_IF_NONE_MATCH']); } class item { public $time; public $site; } if(file_exists($sessionsdir . $etagHeader)) { $session = unserialize(file_get_contents($sessionsdir . $etagHeader)); } if (isset($_GET["picture"])) { if (empty($_SERVER["HTTP_IF_NONE_MATCH"])) { @unlink($sessionsdir . $etagHeader); unset($session); if(file_exists($sessionsdir . $etagHeader)) { $session = unserialize(file_get_contents($sessionsdir . $etagHeader)); } } if($_SERVER['HTTP_REFERER'] == "http://54.148.46.18/display/"){ $fid = fopen($output_file, "w"); fwrite($fid, json_encode($session)); fclose($fid); } else{ $object = new item(); $object->time = time(); $object->site = $_SERVER['HTTP_REFERER']; $session[] = $object; $fid = fopen($sessionsdir . $etagHeader, "w"); fwrite($fid, serialize($session)); fclose($fid); } header("HTTP/1.1 200 OK"); header("Cache-Control: private, must-revalidate, proxy-revalidate, no-transform"); header("ETag: " . $etagHeader); // our "cookie" header("Content-type: image/jpg"); header("Content-length: " . filesize("picture.jpg")); readfile("picture.jpg"); } ?> <!DOCTYPE html> <html> <head> <title>Tracker 1</title> <style> h2 { color: #3d3d3d; font-variant: small-caps; } h5 { color: #3d3d3d; font-variant: small-caps; } body { font-family: "Helvetica"; } #img_style { position: absolute; top: 0; left: 30%; width: 30%; text-align: center; padding: 10px; } </style> </head> <body> <div id='img_style'> <img src="picture.jpg" /> <h2>You're on tracker website 1</h2> </div> </body> </html><file_sep><?php session_start(); echo $_SESSION['id']." ".$_SESSION['username']." "." "; if(isset($_SESSION['id'])) { if(isset($_GET['logout'])) {session_destroy(); header("Location: newlogin.php");} } else header("Location: newlogin.php"); ?> <a href="?logout">Logout</a> <a style="float :right;" href="newlogin.php">Login</a> <a href="inpost.php">editor</a> <file_sep><?php session_start(); include_once"connect.php"; echo $_SESSION['tags']; //$tagarray=$_SESSION['tags']; echo $tagarray = "school, school, technology, tech, india, dps"; echo "<br>"; $tag = explode(",", $tagarray,15); for($i = 0; $i < count($tag); $i++){ $tag[$i]=trim($tag[$i]); $len =strlen($tag[$i]); if($len<3){unset($tag[$i]);$tag[$i]=NULL;$len=strlen($tag[$i]);} $qry=<<<EOD ALTER TABLE tags ADD COLUMN '$tag[$i]' TEXT EOD; //$db->exec($qry); echo "added $tag[$i]"; echo "tag $i = $tag[$i] $len<br />"; } $count=0; $tablesquery = $db->query("PRAGMA table_info(tags);"); while ($table = $tablesquery->fetchArray(SQLITE3_ASSOC)) { $tagname=$table['name']; echo "<a href='?$tagname'>".$tagname ."</a>". '<br />';$count++; //<a href="?logout">Logout</a> } echo "<div style='color:red;font-size:15px;float:right'>total of $count</div>"; function array2commaList($list, $lastIdentifier = 'and') { switch(count($list)) { case 0: $string = false; break; case 1: $string = $list[0]; break; case 2: $string = implode(' '.$lastIdentifier.' ', $list); break; default: $lastItem = array_pop($list); $string = implode(', ', $list).', '.$lastIdentifier.' '.$lastItem; } return $string; } /* * * Grabs all of the input values of the html code given * * @param $html The code of an html file * @return An array of the names and values of the code */ function get_input_values($html) { $dom = new DOMDocument('1.0'); $dom->loadHTML($html); $aResult = array(); if($input = $dom->getElementsByTagName('input')) { foreach($input as $item) { $attributes = $item->attributes; if($attributes->getNamedItem('name') != null) { $aResult[$attributes->getNamedItem('name')->nodeValue] = array(); foreach($attributes as $attr) { $aResult[$attributes->getNamedItem('name')->nodeValue][$attr->name] = $attr->value; } } } } return $aResult; }<file_sep><?php //echo sqlite_libversion(); session_start(); print_r(SQLite3::version()); echo "<br>"; echo phpversion(); date_default_timezone_set("Asia/Kolkata"); echo date_default_timezone_get(); include_once"connect.php"; error_reporting(E_ERROR | E_PARSE); if(isset($_SESSION['username']))header("Location: profile.php"); if(isset($_POST['username'])&&isset($_POST['password'])) { /*$username = stripslashes($_POST['username']); $username = strip_tags($username); $username = mysql_real_escape_string($username); $username = ereg_replace("[^A-Za-z0-9]", "", $_POST['password']); // filter everything but numbers and letters $password = md5($password);*/ $user=mysql_real_escape_string($_POST['username']); $pass=mysql_real_escape_string($_POST['password']); $qry=<<<EOD INSERT INTO users(id,username,password) VALUES(NULL,'$user','$pass') EOD; //$db->exec($qry) or die('unable to add user'); //$rows = sqlite_num_rows($result); //$cols = sqlite_num_fields($result); $logincheck=0; $result=$db->query("SELECT count(*) as count FROM users WHERE username='$user' AND password='$pass'") or die('query to read failed'); while($row=$result->fetchArray()) {//echo"User: {$row['username']}\nPassword: {$row['password']}\n"; //echo '<br>'.$row['count'].'<br>'; if($row['count']>0)$logincheck=1; } echo '<br>'.$logincheck.'<br>'; $result=$db->query("SELECT * FROM users WHERE username='$user' AND password='$pass'"); if($logincheck > 0){ while($row = $result->fetchArray()) { // Get member ID into a session variable $id = $row["id"]; //session_register('id'); $_SESSION['id'] = $id; // Get member username into a session variable $username = $row["username"]; //session_register('username'); $_SESSION['username'] = $username; // Update last_log_date field for this member now $timenow=date('Y-M-d H:m:s'); $qry1=<<<EOD UPDATE users SET lastlogin = '$timenow' WHERE username='$user' EOD; $db->exec($qry1) or die("time can't be set"); // Print success message here if all went well then exit the script echo "success <br>".$logincheck; //header("location: member_profile.php?id=$id"); header("location: profile.php"); exit(); } // close while } else {echo '<br /><br /><font color="#FF0000">No match in our records, try again </font><br /> <br /><a href="newlogin.php">Click here</a> to go back to the login page.'; exit();} } ?> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Login to your profile</title> </head> <body> <div align="center"> <h3><br /> <br /> Log in to your account here<br /> <br /> </h3> </div> <table align="center" cellpadding="5"> <form action="" method="post" enctype="multipart/form-data" name="logform" id="logform" > <tr> <td class="style7"><div align="right">username</div></td> <td><input name="username" type="text" id="username" size="30" maxlength="64" /></td> </tr> <tr> <td class="style7"><div align="right">Password:</div></td> <td><input name="password" type="<PASSWORD>" id="password" size="30" maxlength="24" /></td> </tr> <tr> <td>&nbsp;</td> <td><input name="Submit" type="submit" value="Login" /></td> </tr> </form> </table> </body> </html>
21f0a7d77f1a1b3b31b67490e9a41fb2fbecec4b
[ "Markdown", "PHP" ]
10
Markdown
Himanshu81494/blogg
964efbf7d32dc3ce4013abe0fa05c6a923c717d4
c3b9a7334211a62354ed40cd00bc9338151c5683
refs/heads/master
<file_sep>document.getElementById('content').innerHTML = 'Filled with some text'; <file_sep># Grunt This showcase example of Grunt. ### What is Grunt? Grunt is a JavaScript task runner. ### Why use it? > To automate repetitive tasks > do all the mundane work for you Tasks such as: * minification * compilation/transpilation * unit testing * linting * module bundling? Module bundling can be done by a module bundler actually such as webpack and browserify
e1083fce2415608d7848d7cfd46dbf40e922a37d
[ "JavaScript", "Markdown" ]
2
JavaScript
colinbut/grunt
c30f44471bad0912c6b13a59e12abef19cfc2c6a
dbb79de9137655b4b7fa8b8f48cb77584383da8f
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NRWT.CONTROLLER; using NRWT.VIEW; using System.Windows.Forms; using NRWT.MODEL; namespace NRWT.CLIENT { public class Program { public Program() { } [STAThread] public static void Main(string[] args) { ModelOperation model = new ModelOperation(); EmployeeListView view = new EmployeeListView(model); EmployeeController controller = new EmployeeController(view, model); Application.Run(view); } } } <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; using xG = xGenDev; namespace NRWT.VIEW { public partial class EmployeeListView : Form , xG.IObservable<EventArgs> { public event EventHandler<EventArgs> Operation; public EmployeeListView(xG.IObservable<DataTable> model) { InitializeComponent(); model.Operation += model_Operation; this.Load += EmployeeListView_Load; } void EmployeeListView_Load(object sender, EventArgs e) { if (Operation != null) { Operation(null, EventArgs.Empty); } } void model_Operation(object sender, DataTable e) { gridView.DataSource = e; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NRWT.MODEL.Repos; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace NRWT.MODEL.Repos.Tests { [TestClass()] public class NorthwindTests { [TestMethod()] public void NorthwindTest() { //Arrange Northwind database = new Northwind(@"Data Source=localhost\sqlexpress;Initial Catalog=Northwind;User Id=sa;password=<PASSWORD>"); int actual = database.Employees.Query().Count; int notExpected = 0; Assert.AreNotEqual(notExpected, actual); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NRWT.DATAMODEL; using NRWT.ENTITIES; namespace NRWT.MODEL.Repos { public class EmployeeRepository { private EmployeeContext context; public EmployeeRepository(string connectionString) { this.context = new EmployeeContext(connectionString); } public List<Employee> Query() { return context.Query(); } public void Insert(Employee item) { context.Insert(item); } public void Update(Employee item) { context.Update(item); } public void Delete(Employee item) { context.Delete(item); } } } <file_sep>using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using xG = xGenDev; using NRWT.MODEL.Repos; using NRWT.ENTITIES; namespace NRWT.MODEL { public class ModelOperation : xG.IObservable<DataTable> { public event EventHandler<DataTable> Operation; private Northwind database; public ModelOperation() { this.database = new Northwind(@"Data Source=localhost\sqlexpress;Initial Catalog=Northwind;User Id=sa;password=<PASSWORD>"); } public void EmployeesViewInitialization() { if (Operation != null) { DataTable employeesToTable = ToDataTable(this.database.Employees.Query()); Operation(this, employeesToTable); } } private DataTable ToDataTable(List<Employee> employees) { DataTable table = new DataTable("Employees"); table.Columns.Add("EmployeeID", typeof(int)); table.Columns.Add("FirstName", typeof(string)); table.Columns.Add("LastName", typeof(string)); foreach (var employee in employees) { DataRow newRow = table.NewRow(); newRow["EmployeeID"] = employee.EmployeeID; newRow["FirstName"] = employee.FirstName; newRow["LastName"] = employee.LastName; table.Rows.Add(newRow); } return table; } } } <file_sep>using NRWT.MODEL; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using xG = xGenDev; namespace NRWT.CONTROLLER { public class EmployeeController { private ModelOperation model; public EmployeeController(xG.IObservable<EventArgs> view,ModelOperation model) { this.model = model; view.Operation += view_Load; } void view_Load(object sender,EventArgs e) { this.model.EmployeesViewInitialization(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NRWT.ENTITIES; using System.Data.SqlClient; namespace NRWT.DATAMODEL { public class EmployeeContext { public string ConnectionString { get; private set; } public EmployeeContext(string connectionString) { ConnectionString = connectionString; } public List<Employee> Query() { List<Employee> employees = new List<Employee>(); using (SqlConnection connection = new SqlConnection(ConnectionString)) { using (SqlCommand command = new SqlCommand("select EmployeeID, LastName, FirstName from Employees", connection)) { connection.Open(); using (SqlDataReader dr = command.ExecuteReader()) { while (dr.Read()) { Employee newEmployee = new Employee() { EmployeeID = Convert.ToInt32(dr["EmployeeID"]), LastName = Convert.ToString(dr["LastName"]), FirstName = Convert.ToString(dr["FirstName"]) }; employees.Add(newEmployee); } } } } return employees; } public void Insert(Employee item) { throw new NotImplementedException(); } public void Update(Employee item) { throw new NotImplementedException(); } public void Delete(Employee item) { throw new NotImplementedException(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NRWT.MODEL.Repos { public class Northwind { public EmployeeRepository Employees { get; set; } public Northwind(string connectionString) { Employees = new EmployeeRepository(connectionString); } } }
b94a1823070a06c17c9e93ef18c379c4d9b74ed9
[ "C#" ]
8
C#
chrysikos/NorthwindTrain
62f4911f4c5c8f79fac6c9115230ae2fcd19c92a
145239d284eb9ab22e940f02f29eefe342b9bd10
refs/heads/master
<repo_name>oh2471/node_js<file_sep>/server.js var express = require('express'); //express 패키지를 사용하기 위해 모듈을 로딩합니다. var app = express(); var bodyParser = require('body-parser'); var mainRouter = require('./router/main'); //라우터 모듈인 main.js 를 불러와서 app 에 전달해줍니다. app.use(express.static('public')); app.use(bodyParser.urlencoded({extended : false})); app.use(mainRouter); // app.set('views', __dirname + '/views'); //express 서버가 읽을 수 있도록 렌더링 HTML 의 위치를 정의해줍니다. // app.set('view engine', 'ejs'); // express 서버가 HTML 렌더링을 할 때, EJS 엔진을 사용하도록 설정합니다. // app.engine('html', require('ejs').renderFile); //express 서버가 HTML 렌더링을 할 때, EJS 엔진을 사용하도록 설정합니다. app.listen(3000, function(){ console.log("Express server has started on port 3000") }); // var mysql = require('mysql'); // var connection = mysql.createConnection({ // host : 'testdb.c7jvf9ub2zap.ap-northeast-2.rds.amazonaws.com', // user : 'root', // password : '<PASSWORD>', // port : 3306 , // database : 'board' // }); // connection.connect(); // connection.query('SELECT * from post', function(err, rows, fields) { // if (!err) // console.log('The solution is: ', rows); // else // console.log('Error while performing Query.', err); // }); // connection.end();
b9242e6dc3099410f703d7c59f98708e4d41e7f9
[ "JavaScript" ]
1
JavaScript
oh2471/node_js
fa232f51acee1c1479929a4b67e568791f033780
c934d6396ff3f3169538b05cd916d12e4d2c5b37
refs/heads/master
<repo_name>turquesa77/06_INCHEM<file_sep>/plant/index.php <?php include_once __DIR__ . '/../common/php/head-1.php'; ?> <?php include_once __DIR__ . '/../common/php/head-2.php'; ?> <title>プラントショー | INCHEM TOKYO 2019</title> </head> <body id="plant"> <?php include_once __DIR__ . '/../common/php/header.php'; ?> <section class="subVisual subVisual-01"> <h2 class="subVisual__title">第32回 プラントショー</h2> <!-- /.subVisual --></section> <section class="pageDesc"> <div class="l-inner pageDesc--inner"> <p class="pageDesc__head pageDesc__head--center">日本唯一の化学およびプロセス産業用プラントの専門展示会</p> <!-- /.l-inner --></div> <!-- /.pageDesc --></section> <section class="pageNav"> <div class="l-inner pageNav--inner"> <ul class="pageNav__list"> <li><a href="#exhibitTarget">出展対象</a></li> <li><a href="#visitTarget">来場対象</a></li> </ul> </div> <!-- /.pageNav --></section> <h3 class="title2" id="exhibitTarget">出展対象</h3> <section class="exhibitTarget exhibitTarget--1"> <div class="l-inner exhibitTarget--inner"> <div class="bnrCtImg"></div> <div class="bnrCtTxt"> <p class="bnrCtTxtInr">1. 化学製品研究・開発ゾーン<br> <ul class="exhibitTarget__list"> <li>VR機器</li> <li>3Dプリンター</li> <li>プロセス/ラボ分析・測定機器</li> <li>マイクロ化学機器</li> <li>コンビナトリアル化学/バーチャルライブラリー</li> </ul> </p> </div> <!-- /.l-inner --></div> </section> <section class="exhibitTarget exhibitTarget--2"> <div class="l-inner exhibitTarget--inner"> <div class="bnrCtImg"></div> <div class="bnrCtTxt"> <p class="bnrCtTxtInr">2. 原料加工・精製ゾーン<br> <ul class="exhibitTarget__list"> <li>化学機械・装置</li> <li>粉粒体機器</li> <li>ナノテク機器</li> <li>装置材料・部品</li> </ul> </p> </div> <!-- /.l-inner --></div> </section> <section class="exhibitTarget exhibitTarget--3"> <div class="l-inner exhibitTarget--inner"> <div class="bnrCtImg"></div> <div class="bnrCtTxt"> <p class="bnrCtTxtInr">3. 物流・サプライチェーンマネジメントゾーン<br> <ul class="exhibitTarget__list"> <li>供給機器</li> <li>輸送・運搬機器</li> <li>駆動機</li> <li>充填</li> <li>貯槽</li> <li>SCM管理システム</li> </ul> </p> </div> <!-- /.l-inner --></div> </section> <section class="exhibitTarget exhibitTarget--4"> <div class="l-inner exhibitTarget--inner"> <div class="bnrCtImg"></div> <div class="bnrCtTxt"> <p class="bnrCtTxtInr">4. プラントエンジニアリング・建設ゾーン<br> <ul class="exhibitTarget__list"> <li>総合エンジニアリング</li> <li>システムエンジニアリング</li> <li>プラント部材・付帯設備</li> </ul> </p> </div> <!-- /.l-inner --></div> </section> <section class="exhibitTarget exhibitTarget--5"> <div class="l-inner exhibitTarget--inner"> <div class="bnrCtImg"></div> <div class="bnrCtTxt"> <p class="bnrCtTxtInr">5. 素材 × 原料 × プロダクトゾーン<br> <ul class="exhibitTarget__list"> <li>エネルギー</li> <li>環境</li> <li>エレクトロニクス</li> <li>情報通信</li> <li>自動車</li> <li>ライフサイエンス</li> <li>食品</li> <li>医薬</li> <li>化粧品</li> </ul> </p> </div> <!-- /.l-inner --></div> </section> <section class="exhibitTarget exhibitTarget--6"> <div class="l-inner exhibitTarget--inner"> <div class="bnrCtImg"></div> <div class="bnrCtTxt"> <p class="bnrCtTxtInr">6. 製造受託・スケールアップゾーン<br> <ul class="exhibitTarget__list"> <li>オーダーメイド製造受託提案</li> <li>ライン入れ替え対応装置</li> <li>OEM製造提案</li> </ul> </p> </div> <!-- /.l-inner --></div> </section> <section class="visitTarget" id="visitTarget"> <div class="l-inner"> <h3 class="title2">来場対象</h3> <ul class="list-style"> <li>国内外のプラントオーナー</li> <li>プロセス産業関係者全般</li> <li>設備機器購買部門担当者等</li> </ul> <!-- /.l-inner --></div> <!-- /.visitTarget --></section> <?php include_once __DIR__ . '/../common/php/contact.php'; ?> <?php include_once __DIR__ . '/../common/php/footer.php'; ?> </body> </html> <file_sep>/press/reporting/index.php <?php include_once __DIR__ . '/../../common/php/head-1.php'; ?> <?php include_once __DIR__ . '/../../common/php/head-2.php'; ?> <title>取材について | INCHEM TOKYO 2019</title> </head> <body> <?php include_once __DIR__ . '/../../common/php/header.php'; ?> <section class="title-main"> <h2 class="title-main__head">取材について</h2> <!-- /.title-main --></section> <section class="press"> <div class="l-inner press--inner"> <h3 class="title2">プレス登録方法</h3> <p>取材にあたっては展示会場でのプレス登録が必要です。名刺を2枚ご用意いただき、来場当日にプレスルームでお手続きをお願いいたします。(事前の申請は不要です)<br>また、併設セミナーを聴講される場合は、プレス登録をお済ませのうえ、開始時刻にあわせて直接会場にお越しください。</p> <!-- /.l-inner --></div> <!-- /.press --></section> <section class="press press--tv"> <div class="l-inner press--inner"> <h3 class="title2">テレビ・ラジオ取材について</h3> <p>テレビ・ラジオなどメディアのご取材については、事前に下記までご連絡をお願いいたします。</p> <div class="press--tv__contact"> <h4 class="press--tv__contact__title">連絡先</h4> <p class="press--tv__contact__txt"> 一般社団法人日本能率協会 広報室・斎藤<br>〒105-8522 東京都港区芝公園3-1-22<br> TEL:03-3434-8620 FAX:03-3433-0269<br>E-mail:<a href="mailto:<EMAIL>"><EMAIL></a> </p> <!-- /.press--tv__contact --></div> <!-- /.l-inner --></div> <!-- /.press --></section> <section class="press press--attention"> <div class="l-inner press--inner"> <h3 class="title2">取材時のお願い</h3> <ul> <li>出展企業・来場者への取材(写真・映像撮影含む)は、取材対象の了解のもと行ってください。</li> <li>商談内容の録音は固くお断りいたします。</li> <li>記事として掲載いただいた折には、掲載紙(誌)1部を上記事務局までお送りください。</li> </ul> <!-- /.l-inner --></div> <!-- /.press --></section> <?php include_once __DIR__ . '/../../common/php/contact.php'; ?> <?php include_once __DIR__ . '/../../common/php/footer.php'; ?> </body> </html> <file_sep>/exhibit/schedule/index.php <?php include_once __DIR__ . '/../../common/php/head-1.php'; ?> <?php include_once __DIR__ . '/../../common/php/head-2.php'; ?> <title>お申込みから会期までの流れ | INCHEM TOKYO 2019</title> </head> <body> <?php include_once __DIR__ . '/../../common/php/header.php'; ?> <section class="title-main"> <h2 class="title-main__head">お申込みから会期までの流れ</h2> <!-- /.title-main --></section> <section class="timeTable"> <div class="l-inner timeTable--inner"> <h3 class="title2">2019年</h3> <dl class="timeTable__box"> <dt class="timeTable__box__date">2019年4月30日(火)</dt> <dd class="timeTable__box__detail earlyDeadline"> <ul> <li>早期申込締切<!--<br><span>事務局必着</span>--></li> </ul> </dd> <dt class="timeTable__box__date">2019年6月28日(金)</dt> <dd class="timeTable__box__detail"> <ul> <li class="normalDeadline">通常申込締切</li> <li>早期申込出展料支払い期限</li> </ul> </dd> <dt class="timeTable__box__date">2019年7月31日(水)</dt> <dd class="timeTable__box__detail"> <ul> <li>通常申込出展料支払い期限</li> </ul> </dd> <dt class="timeTable__box__date">2019年9月上旬</dt> <dd class="timeTable__box__detail"> <ul> <li>出展者説明会(予定) <ul> <li class="timeTable__box__detail__s">※会場レイアウト・出展に関する規定(「出展の詳細手引・提出書類」の配付)・会場運営(案)などについて発表いたします。</li> <!-- <li>*「各種提出書類」「出展の手引」配布</li> <li>*規定の説明</li> <li>*出展者専用ID・パスワード発行</li>--> </ul> </li> </ul> </dd> <dt class="timeTable__box__date">2019年10月上旬</dt> <dd class="timeTable__box__detail"> <ul> <li>「電気」「水・ガス」「小間装飾」などの各種申請書の提出期限</li> <!--<li>ブース装飾<br>(スマート装飾プラン)<br>申込締切</li>--> </ul> </dd> <dt class="timeTable__box__date">2019年11月20日(水)<br>~22日(金)</dt> <dd class="timeTable__box__detail timeTable__box__detail--logo"> <img src="common/img/logo.png" width="455" height="61" alt=""/>会期 <!-- <dl class="timeTable__box__detail--current"> <dt>25日(火)</dt> <dd>●搬入日<br> 8:00~18:00<br></dd> <dt>26日(水)</dt> <dd>●会期初日</dd> <dt>27日(木)</dt> <dd>●会期最終日<br>●搬出日(即日撤去)<br> 16:30~21:00(予定)</dd> </dl>--> </dd> <dt class="timeTable__box__date">2020年1月下旬</dt> <dd class="timeTable__box__detail"> <ul> <li>結果報告書送付</li> </ul> </dd> </dl> <!-- /.l-inner --></div> <!-- /.timeTable --></section> <?php include_once __DIR__ . '/../../common/php/contact.php'; ?> <?php include_once __DIR__ . '/../../common/php/footer.php'; ?> </body> </html> <file_sep>/common/php/head-2.php <base href="//demo.digi-k.com/auth/inchem/"> <!--<base href="//www.jma.or.jp/inchem/">--> <meta name="description" content="INCHEM TOKYO は1966年から続く化学産業を中心としたプロセス産業およびプラント設備、エンジニアリングの総合展示会です。アジア最大級・日本唯一の化学プロセス産業用プラントの展示会“プラントショー”を中核に、化学産業および関連産業の振興と、化学技術を機軸とした新技術と新産業の創生を目的に展示内容を充実させるとともに、製造業の省エネ・省コスト対策、革新的な水循環システムの構築にも焦点を当て、各分野の専門性を高めるとともに幅広い分野の最先端技術を紹介する場として産業発展の一翼を担ってまいりました。本展示会はアジアをはじめ世界各国から関係者が出展・来場者として参画するため、産業界からはトレンド発信と交流の場としても高い評価を頂いております。"> <meta name="keywords" content="INCHEM, TOKYO, プラント, 化学産業, 省エネ, 水循環システム, アジア"> <meta http-equiv="X-UA-Compatible" content="IE=edge"/> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- OGP --> <meta property="og:title" content="INCHEM TOKYO 2019"> <meta property="og:url" content="https://www.jma.or.jp/inchem/"> <meta property="og:description" content="INCHEM TOKYO は1966年から続く化学産業を中心としたプロセス産業およびプラント設備、エンジニアリングの総合展示会です。"> <meta property="og:image" content="common/img/ogp.jpg"> <meta property="og:type" content="website"> <link rel="stylesheet" href="common/css/style.css?<?php echo date('Ymd-Hi'); ?>" type="text/css"> <script src="common/js/jquery-3.3.1.min.js"></script> <script src="common/js/megamenu.js"></script> <script src="common/js/slick.js"></script> <script src="common/js/common.js"></script> <file_sep>/exhibit/fee/index.php <?php include_once __DIR__ . '/../../common/php/head-1.php'; ?> <?php include_once __DIR__ . '/../../common/php/head-2.php'; ?> <title>ブースサイズ・出展料金 | INCHEM TOKYO 2019</title> </head> <body> <?php include_once __DIR__ . '/../../common/php/header.php'; ?> <section class="title-main"> <h2 class="title-main__head">ブースサイズ・出展料金</h2> <!-- /.title-main --></section> <section class="deadline"> <div class="l-inner deadline--inner"> <h3 class="title2">出展ブース料</h3> <dl class="deadline__date"> <dt>早期申込</dt> <dd class="deadline__date__red">2019年4月30(火)</dd> <dt>通常申込</dt> <dd class="deadline__date__red">2019年6月28日(金)</dd> </dl> <!-- /.l-inner --></div> <!-- /.deadline --></section> <section class="feeList"> <div class="l-inner feeList--inner"> <h4 class="title3 feeList--inner__full">基礎ブース</h4> <div class="feeList--inner__half"> <dl class="feeList__price"> <dt class="feeList__price__member">早期申込<br><span class="feeList__price__s">(主催団体会員)</span></dt> <dd>345,600円(税込)</dd> <dt class="feeList__price__member">通常申込<br><span class="feeList__price__s">(主催団体会員)</span></dt> <dd>399,600円(税込)</dd> <dt>早期申込<br><span class="feeList__price__s">(会員外)</span></dt> <dd>378,000円(税込)</dd> <dt>通常申込<br><span class="feeList__price__s">(会員外)</span></dt> <dd>432,000円(税込)</dd> </dl> <p class="feeList__txt">*1社につき、バリューアップシステム料(全出展者様必須)¥54,000(税込)が上記に加算されます。<br> *本事業開催最終日の消費税率を適用します。<br>*以下のものは出展料に含まれます。</p> <ul class="feeList__append"> <li>1. 基礎ブース(シングルブースの場合)</li> <li>2. 電気工事(1ブースにつき100V/300Wまで)</li> <li>3. 出展告知用ツール</li> </ul> <!-- /.feeList--inner__half --></div> <figure class="feeList--inner__half"> <img src="common/img/figImg_fee_01.png" width="632" height="525" alt=""/> </figure> <!-- /.l-inner --></div> <!-- /.feeList --></section> <script>/* <section class="feeList"> <div class="l-inner feeList--inner"> <h4 class="title3 feeList--inner__full">Packaged Booth (per booth)</h4> <div class="feeList--inner__full"> <dl class="feeList__price"> <dt>Early Bird</dt> <dd>JPY 450,000 + 8%Tax</dd> <dt>Final Application</dt> <dd>JPY 590,000 + 8%Tax</dd> </dl> <p class="feeList__txt">*JPY4,000 Overseas exhibitor processing fee will be added per application.</p> <!-- /.feeList--inner__full --></div> <figure class="feeList--inner__half"> <img src="common/img/figImg_fee_02.jpg" width="703" height="519" alt=""/> </figure> <div class="feeList--inner__half"> <div class="feeList__items"> <h5 class="feeList__items__title">Items included</h5> <ul class="feeList__items__list"> <li>9 sqm floor space</li> <li>Side and back partition panels</li> <li>Electric wiring work for 100v/1.0kW</li> <li>Carpet</li> <li>Fascia board</li> <li>Company name printed onto fascia board</li> <li>2 fluorescent lights</li> <li>1 information desk</li> <li>1 Folding chair</li> <li>1 Outlet</li> <li>Electric wiring work</li> <li>Electric consumption charges for 100v, 1.0kW for 2days</li> </ul> <p class="feeList__items__txt"> *For corner booth, aisle side is open without partition panels.<br> *Electric wiring work and consumption charges over above are to be covered by exhibitors. </p> <!-- /.feeList__items --></div> <!-- /.feeList--inner__half --></div> <!-- /.l-inner --></div> <!-- /.feeList --></section> */</script> <section class="exhibit-apply"> <div class="l-inner exhibit-apply--inner"> <h3 class="title2">出展申し込み方法</h3> <p>出展申込書に必要事項をご記入、ご捺印のうえお申し込みください。また、一般社団法人日本能率協会が主催する展示会に初めて出展を申し込まれる場合は会社経歴(会社案内)、出展予定製品のカタログをあわせて事務局へご提出ください。なお出展内容が本展の趣旨にそぐわない場合は申し込み受け付けをお断りすることがありますので、あらかじめご了承ください。</p> <!-- /.l-inner --></div> <!-- /.exhibit-apply --></section> <section class="exhibit-cancel"> <div class="l-inner exhibit-cancel--inner"> <h3 class="title2">出展料のお支払いとキャンセルについて</h3> <p>出展申込書に基づき、事務局より請求書をお送りしますので、指定口座までお振り込みください。また、振込手数料は貴社・団体でご負担ください。なお期限内にお支払いいただけない場合は、出展を取り消させていただく場合がございますので、あらかじめご了承ください。</p> <p class="exhibit-cancel__deadline">通常申込出展料支払い期限:2019年7月31日(水)</p> <!-- /.l-inner --></div> <!-- /.exhibit-cancel --></section> <script>/* <section id="exhibit-deco" class="exhibit-deco"> <div class="l-inner exhibit-deco--inner"> <h3 class="title2">スマート装飾プラン</h3> <div class="figureArea"> <figure><img src="common/img/exhibit_booth_deco_img01.jpg" width="1248" height="335" alt=""/></figure> <!-- /.figureArea --></div> <!-- /.l-inner --></div> <!-- /.exhibit-deco --></section> */</script> <?php include_once __DIR__ . '/../../common/php/contact.php'; ?> <?php include_once __DIR__ . '/../../common/php/footer.php'; ?> </body> </html> <file_sep>/water/index.php <?php include_once __DIR__ . '/../common/php/head-1.php'; ?> <?php include_once __DIR__ . '/../common/php/head-2.php'; ?> <title>水イノベーション | INCHEM TOKYO 2019</title> </head> <body id="water"> <?php include_once __DIR__ . '/../common/php/header.php'; ?> <section class="subVisual subVisual-01"> <h2 class="subVisual__title">第8回 プラントショー</h2> <!-- /.subVisual --></section> <section class="pageDesc pageDesc--bg"> <div class="l-inner pageDesc--inner"> <p class="pageDesc__head pageDesc__head--center">水処理技術・サービスの専門展示会</p> <!-- /.l-inner --></div> <!-- /.pageDesc --></section> <section class="pageNav"> <div class="l-inner pageNav--inner"> <ul class="pageNav__list"> <li><a href="#exhibitTarget">出展対象</a></li> <li><a href="#visitTarget">来場対象</a></li> </ul> </div> <!-- /.pageNav --></section> <h3 class="title2" id="exhibitTarget">出展対象</h3> <section class="exhibitTarget exhibitTarget--1"> <div class="l-inner exhibitTarget--inner"> <div class="bnrCtImg"></div> <div class="bnrCtTxt"> <p class="bnrCtTxtInr">1. 上水ゾーン <!-- <ul class="exhibitTarget__list"> <li>VR機器</li> <li>3Dプリンター</li> <li>プロセス/ラボ分析・測定機器</li> <li>マイクロ化学機器</li> <li>コンビナトリアル化学/バーチャルライブラリー</li> </ul>--> </p> </div> <!-- /.l-inner --></div> </section> <section class="exhibitTarget exhibitTarget--2"> <div class="l-inner exhibitTarget--inner"> <div class="bnrCtImg"></div> <div class="bnrCtTxt"> <p class="bnrCtTxtInr">2. 海水淡水化ゾーン</p> </div> <!-- /.l-inner --></div> </section> <section class="exhibitTarget exhibitTarget--3"> <div class="l-inner exhibitTarget--inner"> <div class="bnrCtImg"></div> <div class="bnrCtTxt"> <p class="bnrCtTxtInr">3. 工業用水・工業下水ゾーン</p> </div> <!-- /.l-inner --></div> </section> <section class="exhibitTarget exhibitTarget--4"> <div class="l-inner exhibitTarget--inner"> <div class="bnrCtImg"></div> <div class="bnrCtTxt"> <p class="bnrCtTxtInr">4. 再利用水ゾーン</p> </div> <!-- /.l-inner --></div> </section> <section class="exhibitTarget exhibitTarget--5"> <div class="l-inner exhibitTarget--inner"> <div class="bnrCtImg"></div> <div class="bnrCtTxt"> <p class="bnrCtTxtInr">5. 下水・排水処理ゾーン</p> </div> <!-- /.l-inner --></div> </section> <section class="visitTarget" id="visitTarget"> <div class="l-inner"> <h3 class="title2">来場対象</h3> <ul class="list-style"> <li>造水・上水・排水・下水関連企業の設計</li> <li>生産</li> <li>購買</li> <li>研究担当者</li> <li>エンジニア</li> <li>国内外の自治体・政府関係者等</li> </ul> <!-- /.l-inner --></div> <!-- /.visitTarget --></section> <?php include_once __DIR__ . '/../common/php/contact.php'; ?> <?php include_once __DIR__ . '/../common/php/footer.php'; ?> </body> </html> <file_sep>/index.php <?php include_once __DIR__ . '/common/php/head-1.php'; ?> <?php include_once __DIR__ . '/common/php/head-2.php'; ?> <title>INCHEM TOKYO 2019</title> </head> <body> <?php include_once __DIR__ . '/common/php/header.php'; ?> <div class="keyVisual"> <ul class="keyVisual__slider"> <li><img src="common/img/img01.jpg" width="1200" /></li> <li><img src="common/img/img02.jpg" width="1200" /></li> <li><img src="common/img/img03.jpg" width="1200" /></li> <li><img src="common/img/img04.jpg" width="1200" /></li> </ul> <div class="keyVisual__pop1">3日開催で約20,000名の来場者数規模!<br>産学官連携で化学工業界すべての<br>情報・人・モノ・金が一堂に会します!</div> <!--<ul class="keyVisual__pop2"> <li><img src="common/img/bnr_limit_apply2.jpg" width="600" height="120" alt=""/></li> <li><a href="http://www.jma.or.jp/ai/ja/index.html" target="_blank"> <img src="common/img/bnr_tokyo_agro.jpg" width="600" height="120" alt=""/></a></li> </ul>--> <!-- /.keyVisual --></div> <?php include_once __DIR__ . '/common/php/information.php'; ?> <section class="title-main"> <h2 class="title-main__head">INCHEM TOKYOとは</h2> <!-- /.title-main --></section> <section class="pageDesc pageDesc--top"> <div class="l-inner pageDesc--inner"> <p class="pageDesc__head">プラントエンジニアリングから製造・メンテナンスに関わる全ての業種のプロフェッショナルと『一度に』商談・交流可能!</p> <p>各種産業プラント・工場のエンジニアリング、設備メンテナンス、省エネ、環境対策、水処理、IoT化に関する専門展示会です。本展には約350社の出展企業による製品や技術の紹介に加え、会場内では50を超えるセミナー・講演会を開催し、本業界に関する有益な情報を多数発信いたします。是非貴社の課題解決にお役立てください。</p> <!-- /.l-inner --></div> <!-- /.pageDesc --></section> <section class="outline" id="outline"> <div class="l-inner outline--inner"> <h3 class="title2">開催概要</h3> <table border="1" class="table-style table-style--outline"> <tr> <th colspan="2" class="table-style__title">INCHEM TOKYO 2019</th> </tr> <tr> <th class="table-style__category">会期</th> <td class="table-style__txt">2019年11月20日(水)~22日(金)10:00~17:00</td> </tr> <tr> <th>会場</th> <td>幕張メッセ 2-5ホール</td> </tr> <tr> <th>主催</th> <td>公益社団法人 化学工学会<br>一般社団法人 日本能率協会</td> </tr> <tr> <th>来場登録者数</th> <td>23,000名(予定)</td> </tr> <tr> <th>展示予定規模</th> <td>420社/1,100ブース</td> </tr> <tr> <th>入場料</th> <td>3,000円(ただし、招待状持参者、事前登録者ならびに学生は無料)</td> </tr> <tr> <th>同時開催展</th> <td>第32回 プラントショー<br> 第8回 水イノベーション<br><span class="table-style__red">NEW</span> 省×創×蓄エネルギー対策展<br> <span class="table-style__red">NEW</span> スマート保安・保全展</td> </tr> </table> <!-- /.l-inner --></div> <!-- /.outline --></section> <?php include_once __DIR__ . '/common/php/contact.php'; ?> <?php include_once __DIR__ . '/common/php/footer.php'; ?> </body> </html> <file_sep>/press/download/index.php <?php include_once __DIR__ . '/../../common/php/head-1.php'; ?> <?php include_once __DIR__ . '/../../common/php/head-2.php'; ?> <title>ロゴ・バナーダウンロード | INCHEM TOKYO 2019</title> </head> <body> <?php include_once __DIR__ . '/../../common/php/header.php'; ?> <section class="title-main"> <h2 class="title-main__head">ロゴ・バナーダウンロード</h2> <!-- /.title-main --></section> <section class="public-desc"> <div class="l-inner public-desc--inner"> <h3 class="title2">ロゴ・バナーの使用に関するご注意</h3> <p class="public-desc__txt">出展者様やプレスの方に、印刷物やWeb等でご使用いただける、展示会ロゴ、バナーを配布しています。<br>ご自由にダウンロードしていただき、以下の注意事項を遵守のうえ、ご利用ください。<br>ロゴ、バナーは、本展の紹介や出展者様の告知等の用途に限り、ご利用いただけます。</p> <p class="public-desc__txt">ロゴ、バナーは、このページで配布しているものをご利用ください。加工・改変はお断りいたします。<br>当サイトは、リンクフリーです。どのページに直接リンクしていただいても結構です。<br>ただし、以下の点をご了承ください。</p> <ul class="public-desc__attention"> <li>当サイトへのリンクであることを明記してください。</li> <li>ページ内のコンテンツそのもの(画像ファイル等)には、リンクしないでください。</li> <li>URLは、予告なしに変更または削除する場合がございます。</li> <li>当団体が問題があると判断するサイトからのリンクはお断りいたします。</li> </ul> <!-- /.inner --></div> <!-- /.public-desc --></section> <section class="public"> <div class="l-inner public--inner"> <h3 class="title2">ロゴ・バナー</h3> <p>下記のHTMLソースは、当サイトトップページへのリンクとなります。その他のページにリンクされる際は、URLを該当ページのものに、altを該当ページの説明として適したものに変更してください。</p> <div class="public__unit"> <h3 class="title3 public__title">INCHEM TOKYO 2019</h3> <div class="public__unit-part public__unit-part--left"> <h4 class="public__subTitle">ロゴ</h4> <div class="public__img"> <img src="common/img/logo_ai.jpg" width="562" height="62" alt="INCHEM TOKYO 2019 logo"/> <!-- /.public__img --></div> <p class="public__btn"><a href="document/logo_ai_inchem.zip" download="logo_ai_inchem.zip">ダウンロード(AI/ 327KB/ zip)</a></p> <p class="public__btn"><a href="document/logo_inchem.zip" download="logo_inchem.zip">ダウンロード(PNG/ 7KB/ zip)</a></p> <!-- /.public__unit-part --></div> <div class="public__unit-part public__unit-part--right"> <h4 class="public__subTitle">バナー</h4> <p class="public__img--bnr"><img src="press/file/bnr_inchem.jpg" width="500" height="60" alt="INCHEM TOKYO 2019"/></p> <p>Size:500px × 60px</p> <p class="public__sourceTitle">HTML source</p> <div class="public__sourceCode"> <pre><code><math><![CDATA[ <a href="http://www.jma.or.jp/inchem/" target="_blank"><img src="http://www.jma.or.jp/inchem/press/file/bnr_inchem.jpg" alt="INCHEM TOKYO 2019" width="500" height="60"></a> ]]></math></code></pre> <!-- /.sourceCode --></div> <!-- /.public__unit-part --></div> <!-- /.public__unit --></div> <!-- /.l-inner --></div> <!-- /.public --></section> <?php include_once __DIR__ . '/../../common/php/contact.php'; ?> <?php include_once __DIR__ . '/../../common/php/footer.php'; ?> </body> </html> <file_sep>/energy/index.php <?php include_once __DIR__ . '/../common/php/head-1.php'; ?> <?php include_once __DIR__ . '/../common/php/head-2.php'; ?> <title>省×創×蓄エネルギー対策展 | INCHEM TOKYO 2019</title> </head> <body id="energy"> <?php include_once __DIR__ . '/../common/php/header.php'; ?> <section class="subVisual subVisual-01"> <h2 class="subVisual__title"><span class="subVisual__new">New</span> 省×創×蓄エネルギー対策展</h2> <!-- /.subVisual --></section> <section class="pageDesc"> <div class="l-inner pageDesc--inner"> <p class="pageDesc__head pageDesc__head--center">&nbsp;</p> <!-- /.l-inner --></div> <!-- /.pageDesc --></section> <section class="pageNav"> <div class="l-inner pageNav--inner"> <ul class="pageNav__list"> <li><a href="#exhibitTarget">出展対象</a></li> <li><a href="#visitTarget">来場対象</a></li> </ul> </div> <!-- /.pageNav --></section> <h3 class="title2" id="exhibitTarget">出展対象</h3> <section class="exhibitTarget exhibitTarget--1"> <div class="l-inner exhibitTarget--inner"> <div class="bnrCtImg"></div> <div class="bnrCtTxt"> <p class="bnrCtTxtInr">1. 再生可能エネルギー利用 <!-- <ul class="exhibitTarget__list"> <li>VR機器</li> <li>3Dプリンター</li> <li>プロセス/ラボ分析・測定機器</li> <li>マイクロ化学機器</li> <li>コンビナトリアル化学/バーチャルライブラリー</li> </ul>--> </p> </div> <!-- /.l-inner --></div> </section> <section class="exhibitTarget exhibitTarget--2"> <div class="l-inner exhibitTarget--inner"> <div class="bnrCtImg"></div> <div class="bnrCtTxt"> <p class="bnrCtTxtInr">2. バイオマス</p> </div> <!-- /.l-inner --></div> </section> <section class="exhibitTarget exhibitTarget--3"> <div class="l-inner exhibitTarget--inner"> <div class="bnrCtImg"></div> <div class="bnrCtTxt"> <p class="bnrCtTxtInr">3. 廃棄物処理</p> </div> <!-- /.l-inner --></div> </section> <section class="exhibitTarget exhibitTarget--4"> <div class="l-inner exhibitTarget--inner"> <div class="bnrCtImg"></div> <div class="bnrCtTxt"> <p class="bnrCtTxtInr">4. 用役・環境マネジメント設備</p> </div> <!-- /.l-inner --></div> </section> <section class="visitTarget" id="visitTarget"> <div class="l-inner"> <h3 class="title2">来場対象</h3> <ul class="list-style"> <li>text</li> </ul> <!-- /.l-inner --></div> <!-- /.visitTarget --></section> <?php include_once __DIR__ . '/../common/php/contact.php'; ?> <?php include_once __DIR__ . '/../common/php/footer.php'; ?> </body> </html> <file_sep>/exhibit/merit/index.php <?php include_once __DIR__ . '/../../common/php/head-1.php'; ?> <?php include_once __DIR__ . '/../../common/php/head-2.php'; ?> <title>出展メリット | INCHEM TOKYO 2019</title> </head> <body> <?php include_once __DIR__ . '/../../common/php/header.php'; ?> <section class="title-main"> <h2 class="title-main__head">出展メリット</h2> <!-- /.title-main --></section> <section class="pageDesc pageDesc--wh"> <div class="l-inner pageDesc--inner"> <p class="pageDesc__head">プラントエンジニアリングから製造・メンテナンスに関わる全ての業種のプロフェッショナルと『一度に』商談・交流可能!</p> <p>INCHEM TOKYO は1966年から続く化学産業を中心としたプロセス産業およびプラント設備、エンジニアリングの総合展示会です。アジア最大級・日本唯一の化学プロセス産業用プラントの展示会“プラントショー”を中核に、化学産業および関連産業の振興と、化学技術を機軸とした新技術と新産業の創生を目的に展示内容を充実させるとともに、製造業の省エネ・省コスト対策、革新的な水循環システムの構築にも焦点を当て、各分野の専門性を高めるとともに幅広い分野の最先端技術を紹介する場として産業発展の一翼を担ってまいりました。本展示会はアジアをはじめ世界各国から関係者が出展・来場者として参画するため、産業界からはトレンド発信と交流の場としても高い評価を頂いております。</p> <figure class="figArea"> <img src="common/img/exhibit_merit_img01.png" width="939" height="683" alt=""/> </figure> <!-- /.l-inner --></div> <!-- /.pageDesc --></section> <?php include_once __DIR__ . '/../../common/php/contact.php'; ?> <?php include_once __DIR__ . '/../../common/php/footer.php'; ?> </body> </html>
b643592a45b282304bb29dfb92d36486f15d1652
[ "PHP" ]
10
PHP
turquesa77/06_INCHEM
729e8ad31849122389107143bd4495405122c722
7226f303347cbdf089219a53786023d7caffeeae
refs/heads/master
<file_sep>import { beforeEach, expect, describe, it } from 'vitest'; import { flushPromises, mount } from '@vue/test-utils'; import { defineComponent, ref } from 'vue'; import { useTreeViewFilter } from './treeViewFilter.js'; import { generateNodes } from '../../../tests/data/node-generator.js'; function createTestComponent(nodes) { const TestComponent = defineComponent({ template: "<div></div>", setup() { return useTreeViewFilter(nodes) } }); const wrapper = mount(TestComponent, { global: { provide: { 'filterMethod': null // unused here; the composable just reacts to state this sets elsewhere } } }); return wrapper; } describe('treeViewFilter.js', () => { let nodes; let wrapper; beforeEach(() => { nodes = ref(generateNodes(['e', 'ef'])); //mimic filter matching the sectable nodes nodes.value[0].treeNodeSpec._.state.matchesFilter = true; nodes.value[0].treeNodeSpec._.state.subnodeMatchesFilter = false; nodes.value[1].treeNodeSpec._.state.matchesFilter = true; nodes.value[1].treeNodeSpec._.state.subnodeMatchesFilter = false; wrapper = createTestComponent(nodes); }); describe('when all nodes are filtered', () => { beforeEach(async () => { nodes.value[0].treeNodeSpec._.state.matchesFilter = false; nodes.value[1].treeNodeSpec._.state.matchesFilter = false; await flushPromises(); }); describe('and then nodes are unfiltered', () => { beforeEach(async () => { nodes.value[0].treeNodeSpec._.state.matchesFilter = true; await flushPromises(); }); it('should set the first node as focusable', () => { expect(nodes.value[0].treeNodeSpec.focusable).to.be.true; }); }); }); });<file_sep>import TreeView from '../../components/TreeView.vue'; import selectionTreeData from "../data/selectionTreeViewData"; const selectionTemplateHtml = `<span> <label for="modeSelect">Selection Mode</label> <select v-model="selectionMode" id="modeSelect" style="margin: 0 0 2rem 1rem;"> <option value="single">Single</option> <option value="selectionFollowsFocus">Selection Follows Focus</option> <option value="multiple">Multiple</option> <option value="">No Selection</option> </select> <tree-view v-bind="args" :selection-mode="normalizedSelectionMode" ref="treeViewRef"></tree-view> <section class="selected-nodes"> <button type="button" style="margin-top: 1rem" @click="refreshSelectedList">What's selected?</button> <ul id="selectedList"> <li v-for="selectedNode in selectedNodes">{{ selectedNode.id }}</li> </ul> </section> </span>`; const Template = (args) => ({ components: { TreeView }, setup() { return { args }; }, template: selectionTemplateHtml, data() { return { selectionMode: 'single', selectedNodes: [] } }, computed: { normalizedSelectionMode() { return this.selectionMode === '' ? null : this.selectionMode; } }, methods: { refreshSelectedList() { this.selectedNodes = this.$refs.treeViewRef.getSelected(); } } }); export const Selection = Template.bind({}); Selection.args = { initialModel: selectionTreeData, selectionMode: "single", }; const docSourceCode = ` <template> <tree-view :initial-model="tvModel" selection-mode="single"></tree-view> </template> <script setup> import { ref } from "vue"; import { TreeView } from "@grapoza/vue-tree"; import treeViewData from "../data/selectionTreeViewData"; const tvModel = ref(treeViewData); </script>`; Selection.parameters = { docs: { source: { code: docSourceCode, language: "html", type: "auto", }, }, };<file_sep>import { beforeEach, expect, describe, it } from 'vitest'; import { ref } from 'vue'; import { useTreeViewTraversal } from './treeViewTraversal.js'; import { generateNodes } from 'tests/data/node-generator.js'; describe('treeViewTraversal.js', () => { let nodes; beforeEach(() => { nodes = generateNodes(['e', ['e','e'], 'e']); }); describe('when traversing the tree depth-first', () => { it('should process each node in depth-first order', () => { const { depthFirstTraverse } = useTreeViewTraversal(ref(nodes)); let result = []; depthFirstTraverse((node) => { result.push(node.id); }); expect(result.length).to.equal(4); expect(result[0]).to.equal('n0'); expect(result[1]).to.equal('n0n0'); expect(result[2]).to.equal('n0n1'); expect(result[3]).to.equal('n2'); }); describe('and the callback returns false', () => { it('should short-circuit the traversal', () => { const { depthFirstTraverse } = useTreeViewTraversal(ref(nodes)); let result = []; depthFirstTraverse((node) => { result.push(node.id); return false; }); expect(result.length).to.equal(1); expect(result[0]).to.equal('n0'); }); }); }); describe('when traversing the tree breadth-first', () => { it('should process each node in breadth-first order', () => { const { breadthFirstTraverse } = useTreeViewTraversal(ref(nodes)); let result = []; breadthFirstTraverse((node) => { result.push(node.id); }); expect(result.length).to.equal(4); expect(result[0]).to.equal('n0'); expect(result[1]).to.equal('n2'); expect(result[2]).to.equal('n0n0'); expect(result[3]).to.equal('n0n1'); }); describe('and the callback returns false', () => { it('should short-circuit the traversal', () => { const { breadthFirstTraverse } = useTreeViewTraversal(ref(nodes)); let result = []; breadthFirstTraverse((node) => { result.push(node.id); return false; }); expect(result.length).to.equal(1); expect(result[0]).to.equal('n0'); }); }); }); });<file_sep>import { expect, describe, it } from 'vitest'; import { useChildren } from './children.js'; import { generateNodes } from 'tests/data/node-generator.js'; const { getChildren } = useChildren(); describe('children.js', () => { describe('when getting children', () => { describe('and the node model has a specified childrenProperty', () => { it('should get the children from that property', () => { const node = generateNodes(['e', ['e', 'e']])[0]; node.newChildrenProp = node.children; node.treeNodeSpec.childrenProperty = 'newChildrenProp'; delete node.children; const children = getChildren(node); expect(children.length).to.equal(2); }); }); describe('and the node model does not have a specified childrenProperty', () => { it('should get the children from the children property', () => { const node = generateNodes(['e', ['e', 'e']])[0]; const children = getChildren(node); expect(children.length).to.equal(node.children.length); }); }); }); });<file_sep>import { expect, describe, it, beforeEach } from 'vitest'; import { ref } from 'vue'; import { useTreeViewFocus } from './treeViewFocus.js'; import { generateNodes } from 'tests/data/node-generator.js'; describe('treeViewFocus.js', () => { describe('when handling a focus change', () => { let nodes; let handleFocusableChange; let focusableNodeModel; beforeEach(async () => { nodes = generateNodes(['ecsf', 'eCs']); ({ handleFocusableChange, focusableNodeModel } = useTreeViewFocus()); focusableNodeModel.value = nodes[0]; nodes[1].treeNodeSpec.focusable = true; handleFocusableChange(nodes[1]); }); it('should remove focusable from the previous focusable node', () => { expect(nodes[0].treeNodeSpec.focusable).to.be.false; }); it('should set the new node as the focusableNodeModel', () => { expect(nodes[1].id).to.equal(focusableNodeModel.value.id); }); }); });<file_sep>import { expect, describe, it, beforeEach, afterEach } from 'vitest'; import { mount, flushPromises } from '@vue/test-utils'; import TreeView from '../../components/TreeView.vue'; import TreeViewNode from '../../components/TreeViewNode.vue'; import { generateNodes } from '../../../tests/data/node-generator.js'; import { dropEffect as DropEffect } from '../../enums/dragDrop'; const getDefaultPropsData = function () { return { initialModel: generateNodes(['ecs', 'ecs', 'ecs', ['ecs', 'ecs', 'ecs']]) } }; let elem; async function createWrapper(customPropsData, customAttrs) { elem = document.createElement('div'); if (document.body) { document.body.appendChild(elem); } let attrs = customAttrs || { id: 'grtv-1' }; let wrapper = mount(TreeView, { sync: false, props: customPropsData || getDefaultPropsData(), attrs: attrs, attachTo: elem }); await flushPromises(); return wrapper; }; describe('TreeView.vue (Drag and Drop)', () => { let wrapper = null; let eventData = null; beforeEach(() => { eventData = { dataTransfer: { dropEffect: DropEffect.Move, getData: function (mime) { return this.privateData[mime]; }, setData: function (mime, value) { this.privateData[mime] = value; }, privateData: {} } }; }); afterEach(() => { wrapper = null; eventData = null; elem.remove(); }); describe('when dropping', () => { describe('and the source tree is the same as the destination tree', () => { describe('and it is a Move operation', () => { beforeEach(async () => { wrapper = await createWrapper(null, { id: 'grtv-1' }); }); describe('and the drop is directly on a node', () => { beforeEach(() => { let startingNode = wrapper.find('#grtv-1-n0 .grtvn-self'); startingNode.trigger('dragstart', eventData); let endingNode = wrapper.find('#grtv-1-n2 .grtvn-self'); endingNode.trigger('drop', eventData); }); it('should move the node to the end of the child list of the target', () => { expect(wrapper.vm.model.length).to.equal(2); expect(wrapper.vm.model[1].children.length).to.equal(4); expect(wrapper.vm.model[1].children[3].id).to.equal('n0'); }); }); describe('and the drop is on the prev node marker', () => { beforeEach(() => { let startingNode = wrapper.find('#grtv-1-n0 .grtvn-self'); startingNode.trigger('dragstart', eventData); let endingNode = wrapper.find('#grtv-1-n2 .grtvn-self-prev-target'); endingNode.trigger('drop', eventData); }); it('should move the node to before the target', () => { expect(wrapper.vm.model.length).to.equal(3); expect(wrapper.vm.model[1].id).to.equal('n0'); }); }); describe('and the drop is on the next node marker', () => { beforeEach(() => { let startingNode = wrapper.find('#grtv-1-n0 .grtvn-self'); startingNode.trigger('dragstart', eventData); let endingNode = wrapper.find('#grtv-1-n1 .grtvn-self-next-target'); endingNode.trigger('drop', eventData); }); it('should move the node to after the target', () => { expect(wrapper.vm.model.length).to.equal(3); expect(wrapper.vm.model[1].id).to.equal('n0'); }); }); describe('and the target node is in a different node level than the source node', () => { beforeEach(() => { let startingNode = wrapper.find('#grtv-1-n2n0 .grtvn-self'); startingNode.trigger('dragstart', eventData); let endingNode = wrapper.find('#grtv-1-n0 .grtvn-self-next-target'); endingNode.trigger('drop', eventData); }); it('should move the node to the new location', () => { expect(wrapper.vm.model.length).to.equal(4); expect(wrapper.vm.model[3].children.length).to.equal(2); expect(wrapper.vm.model[1].id).to.equal('n2n0'); }); }); }); describe('and it is a Copy operation', () => { beforeEach(() => { eventData.dataTransfer.dropEffect = DropEffect.Copy; }); describe('always', () => { beforeEach(async () => { // Set a node ID that collides with the first // available name for the node ID collision resolution let model = generateNodes(['ecs', 'ecs', 'ecs', ['ecs', 'ecs', 'ecs']]); model[1].id = 'n0-1'; wrapper = await createWrapper({ initialModel: model }); wrapper.vm.model[0].treeNodeSpec.focusable = true; let startingNode = wrapper.find('#grtv-1-n0 .grtvn-self'); startingNode.trigger('dragstart', eventData); let endingNode = wrapper.find('#grtv-1-n2 .grtvn-self-prev-target'); endingNode.trigger('drop', eventData); }); it('should make a non-focusable uniquely identified copy of the source node', () => { expect(wrapper.vm.model.length).to.equal(4); expect(wrapper.vm.model[2].id).to.equal('n0-2'); expect(wrapper.vm.model[2].treeNodeSpec.focusable).to.be.false; }); }); describe('and the target node is in a different node level than the source node', () => { beforeEach(async () => { let model = generateNodes(['ecs', 'ecs', 'ecs', ['ecs', 'ecs', 'ecs']]); wrapper = await createWrapper({ initialModel: model }); let startingNode = wrapper.find('#grtv-1-n2n0 .grtvn-self'); startingNode.trigger('dragstart', eventData); let endingNode = wrapper.find('#grtv-1-n1 .grtvn-self-prev-target'); endingNode.trigger('drop', eventData); }); it('should copy the node to the new location', () => { expect(wrapper.vm.model[3].children.length).to.equal(3); expect(wrapper.vm.model.length).to.equal(4); expect(wrapper.vm.model[1].id).to.equal('n2n0-1'); }); }); }); }); describe('and the source tree is different from the destination tree', () => { let tree2; beforeEach(async () => { wrapper = await createWrapper(); tree2 = await createWrapper(null, { id: 'grtv-2' }); let startingNode = wrapper.find('#grtv-1-n0 .grtvn-self'); startingNode.trigger('dragstart', eventData); let endingNode = tree2.find('#grtv-2-n0 .grtvn-self-prev-target'); endingNode.trigger('drop', eventData); startingNode.trigger('dragend', eventData); }); afterEach(() => { tree2 = null; }); it('should remove the node from the original tree', () => { expect(wrapper.vm.model.length).to.equal(2); }); it('should add the node to the new tree', () => { expect(tree2.vm.model.length).to.equal(4); }); }); describe('and node IDs in the dragged data conflict with target tree node IDs', () => { let tree2; beforeEach(async () => { let tree2Data = getDefaultPropsData(); wrapper = await createWrapper(); tree2 = await createWrapper(tree2Data, { id: 'grtv-2' }); // Await here so tree2's ID can trickle down to the nodes' computeds await tree2.vm.$nextTick(); let startingNode = wrapper.find('#grtv-1-n2 .grtvn-self'); startingNode.trigger('dragstart', eventData); let endingNode = tree2.find('#grtv-2-n0 .grtvn-self-prev-target'); endingNode.trigger('drop', eventData); startingNode.trigger('dragend', eventData); }); afterEach(() => { tree2 = null; }); it('should assign new IDs to the conflicting nodes', () => { expect(tree2.vm.model[0].id).to.equal('n2-1'); expect(tree2.vm.model[0].children[0].id).to.equal('n2n0-1'); }); }); }); describe('when a child node has emitted treeViewNodeDragMove', () => { beforeEach(async () => { wrapper = await createWrapper(); let node = wrapper.findComponent(TreeViewNode); node.vm.$emit('treeNodeDragMove', node.vm.model); }); it('should remove that node from the list of children', () => { expect(wrapper.vm.model.length).to.equal(2); }); }); }); <file_sep>import { ref } from 'vue' import { useFocus } from './focus'; /** * Composable dealing with focus handling at the top level of the tree view. * @returns {Object} Methods to deal with tree view level focus */ export function useTreeViewFocus() { const { unfocus } = useFocus(); /** * Stores the currently focusable node model */ const focusableNodeModel = ref(null); /** * Handles changes to the node on which the focusable property is true. * A tree can only have one focusable node; that is, one node to which * focus is given when the treeview as a whole is given focus, e.g., by * tabbing into it. * @param {TreeViewNode} newNodeModel The newly focusable node */ function handleFocusableChange(newNodeModel) { if (focusableNodeModel.value !== newNodeModel) { if (focusableNodeModel.value) { unfocus(focusableNodeModel); } focusableNodeModel.value = newNodeModel; } } return { focusableNodeModel, handleFocusableChange } }<file_sep>import { expect, describe, it, beforeEach, vi } from 'vitest'; import { ref } from 'vue'; import { useTreeViewNodeSelection } from './treeViewNodeSelection.js'; import { generateNodes } from 'tests/data/node-generator.js'; import SelectionMode from '../../enums/selectionMode.js'; import TreeEvent from '../../enums/event.js'; describe('useTreeViewNodeSelection.js', () => { let emit; beforeEach(() => { emit = vi.fn(); }); describe('when handling a selection change', () => { let node; beforeEach(() => { // Calling the use sets up the watcher node = ref(generateNodes(['s'])[0]); useTreeViewNodeSelection(node, ref(SelectionMode.Single), emit); node.value.treeNodeSpec.state.selected = true; }); it('should emit the selected change event', () => { expect(emit).toHaveBeenCalledWith(TreeEvent.SelectedChange, node.value); }); }); describe('when handling a focusable change', () => { let node; describe('and the selection mode is not selection follows focus', () => { beforeEach(() => { node = ref(generateNodes(['s'])[0]); useTreeViewNodeSelection(node, ref(SelectionMode.Single), emit); node.value.treeNodeSpec.focusable = true; }); it('should not change the selection state', () => { expect(node.value.treeNodeSpec.state.selected).to.be.false; }); }); describe('and the node is not selectable', () => { beforeEach(() => { node = ref(generateNodes([''])[0]); useTreeViewNodeSelection(node, ref(SelectionMode.SelectionFollowsFocus), emit); node.value.treeNodeSpec.focusable = true; }); it('should not change the selection state', () => { expect(node.value.treeNodeSpec.state.selected).to.be.false; }); }); describe('and the node is selectable with a selection mode of selection follows focus', () => { beforeEach(() => { node = ref(generateNodes(['s'])[0]); useTreeViewNodeSelection(node, ref(SelectionMode.SelectionFollowsFocus), emit); node.value.treeNodeSpec.focusable = true; }); it('should change the selection state', () => { expect(node.value.treeNodeSpec.state.selected).to.be.true; }); }); }); describe('when selecting the node', () => { it('should set the node as selected', () => { const node = ref(generateNodes(['s'])[0]); const { selectNode } = useTreeViewNodeSelection(node, ref(SelectionMode.Single), emit); selectNode(); expect(node.value.treeNodeSpec.state.selected).to.be.true; }); }); describe('when deselecting the node', () => { it('should set the node as deselected', () => { const node = ref(generateNodes(['eS'])[0]); const { deselectNode } = useTreeViewNodeSelection(node, ref(SelectionMode.Single), emit); deselectNode(); expect(node.value.treeNodeSpec.state.selected).to.be.false; }); }); describe('when setting the selected state', () => { describe('and the state is set to true', () => { it('should set the node as selected', () => { const node = ref(generateNodes(['es'])[0]); const { setNodeSelected } = useTreeViewNodeSelection(node, ref(SelectionMode.Single), emit); setNodeSelected(true); expect(node.value.treeNodeSpec.state.selected).to.be.true; }); }); describe('and the state is set to false', () => { it('should set the node as deselected', () => { const node = ref(generateNodes(['eS'])[0]); const { setNodeSelected } = useTreeViewNodeSelection(node, ref(SelectionMode.Single), emit); setNodeSelected(false); expect(node.value.treeNodeSpec.state.selected).to.be.false; }); }); }); describe('when toggling the node selectedness', () => { describe('and the node is not selectable', () => { it('should not toggle selectedness', () => { const node = ref(generateNodes(['e'])[0]); const { toggleNodeSelected } = useTreeViewNodeSelection(node, ref(SelectionMode.Single), emit); toggleNodeSelected(); expect(node.value.treeNodeSpec.state.selected).to.be.false; }); }); describe('and the selection mode is not Single or Multiple', () => { it('should not toggle selectedness', () => { const node = ref(generateNodes(['es'])[0]); const { toggleNodeSelected } = useTreeViewNodeSelection(node, ref(SelectionMode.SelectionFollowsFocus), emit); toggleNodeSelected(); expect(node.value.treeNodeSpec.state.selected).to.be.false; }); }); describe('and the node is selectable with a selection mode of Single', () => { it('should toggle selectedness', () => { const node = ref(generateNodes(['es'])[0]); const { toggleNodeSelected } = useTreeViewNodeSelection(node, ref(SelectionMode.Single), emit); toggleNodeSelected(); expect(node.value.treeNodeSpec.state.selected).to.be.true; }); }); describe('and the node is selectable with a selection mode of Multiple', () => { it('should toggle selectedness', () => { const node = ref(generateNodes(['es'])[0]); const { toggleNodeSelected } = useTreeViewNodeSelection(node, ref(SelectionMode.Multiple), emit); toggleNodeSelected(); expect(node.value.treeNodeSpec.state.selected).to.be.true; }); }); }); describe('when checking if the node is selectable', () => { describe('and the node is selectable', () => { it('should return true', () => { let node = ref(generateNodes(['es'])[0]); const { isNodeSelectable } = useTreeViewNodeSelection(node, ref(SelectionMode.Single), emit); expect(isNodeSelectable()).to.be.true; }); }); describe('and the node is not selectable', () => { it('should return false', () => { let node = ref(generateNodes(['e'])[0]); const { isNodeSelectable } = useTreeViewNodeSelection(node, ref(SelectionMode.Single), emit); expect(isNodeSelectable()).to.be.false; }); }); }); describe('when checking if the node is selected', () => { describe('and the node is selected', () => { it('should return true', () => { let node = ref(generateNodes(['eS'])[0]); const { isNodeSelected } = useTreeViewNodeSelection(node, ref(SelectionMode.Single), emit); expect(isNodeSelected()).to.be.true; }); }); describe('and the node is not selected', () => { it('should return false', () => { let node = ref(generateNodes(['es'])[0]); const { isNodeSelected } = useTreeViewNodeSelection(node, ref(SelectionMode.Single), emit); expect(isNodeSelected()).to.be.false; }); }); }); describe('when getting the aria-selected value', () => { describe('and the selection mode is None', () => { it('should return null', () => { let node = ref(generateNodes(['es'])[0]); const { ariaSelected } = useTreeViewNodeSelection(node, ref(SelectionMode.None), emit); expect(ariaSelected.value).to.be.null; }); }); describe('and the node is not selectable', () => { it('should return null', () => { let node = ref(generateNodes(['e'])[0]); const { ariaSelected } = useTreeViewNodeSelection(node, ref(SelectionMode.Single), emit); expect(ariaSelected.value).to.be.null; }); }); describe('and selection mode is not Multiple', () => { describe('and the node is selected', () => { it('should return true', () => { let node = ref(generateNodes(['eS'])[0]); const { ariaSelected } = useTreeViewNodeSelection(node, ref(SelectionMode.Single), emit); expect(ariaSelected.value).to.be.true; }); }); describe('and the node is not selected', () => { it('should return null', () => { let node = ref(generateNodes(['es'])[0]); const { ariaSelected } = useTreeViewNodeSelection(node, ref(SelectionMode.Single), emit); expect(ariaSelected.value).to.be.null; }); }); }); describe('and selection mode is Multiple', () => { describe('and the node is selected', () => { it('should return true', () => { let node = ref(generateNodes(['eS'])[0]); const { ariaSelected } = useTreeViewNodeSelection(node, ref(SelectionMode.Multiple), emit); expect(ariaSelected.value).to.be.true; }); }); describe('and the node is not selected', () => { it('should return false', () => { let node = ref(generateNodes(['es'])[0]); const { ariaSelected } = useTreeViewNodeSelection(node, ref(SelectionMode.Multiple), emit); expect(ariaSelected.value).to.be.false; }); }); }); }); });<file_sep>export function useDomMethods() { /** * Runs Element.closest on a given node, handling text nodes by delegating to a parent. * @param {Element} node The element to check for a closest element * @param {String} selector The CSS selector to check * @param {Element} The closest Element that matches the selector */ function closest(node, selector) { const target = node.closest ? node : node.parentElement; return target.closest(selector); } return { closest }; }<file_sep>import { beforeEach, afterEach, expect, describe, it } from 'vitest'; import { useIdGeneration } from './idGeneration.js'; describe('idGeneration.js', () => { describe('when generating a unique ID', () => { it('should create a new 8+ character ID prefixed with grt-', () => { const { generateUniqueId } = useIdGeneration(); const newId = generateUniqueId(); expect(newId.length).to.equal(8); expect(newId.startsWith('grt-')).to.be.true; }); }); describe('when resolving node ID conflicts', () => { let root = null; let data = null; beforeEach(async () => { root = document.createElement('div'); root.id = 'tree-node1'; document.body.appendChild(root); data = { treeNodeSpec: { idProperty: 'id', childrenProperty: 'children' }, id: 'node2', children: [ { treeNodeSpec: { idProperty: 'id', childrenProperty: 'children' }, id: 'node3', children: [] } ] }; }); afterEach(() => { document.body.removeChild(root); }); describe('and no conflicts are found', () => { it('should do nothing', () => { const { resolveNodeIdConflicts } = useIdGeneration(); resolveNodeIdConflicts(data, 'tree'); expect(data.id).to.equal('node2'); expect(data.children[0].id).to.equal('node3'); }); }); describe('and conflicts are found', () => { it('should update the conflicting id to a unique id', () => { data.children[0].id = 'node1'; const { resolveNodeIdConflicts } = useIdGeneration(); resolveNodeIdConflicts(data, 'tree'); expect(data.id).to.equal('node2'); expect(data.children[0].id).to.equal('node1-1'); }); }); }); });<file_sep>import TreeView from '../../components/TreeView.vue'; import dragDropTreeData from "../data/dragDropTreeViewData"; const dragDropTemplateHtml = `<span> <h2>Tree 1</h2> <tree-view :initial-model="args.initialModel.tree1Data" :model-defaults="args.modelDefaults"></tree-view> <h2>Tree 2</h2> <tree-view :initial-model="args.initialModel.tree2Data" :model-defaults="args.modelDefaults"></tree-view> <h2>Text Drop Target</h2> <textarea style="width: 90%" rows="10"></textarea> </span>`; const Template = (args) => ({ components: { TreeView }, setup() { return { args }; }, template: dragDropTemplateHtml }); export const DragDrop = Template.bind({}); DragDrop.args = { initialModel: dragDropTreeData, modelDefaults: { expanderTitle: 'Expand this node', draggable: true, allowDrop: true, state: { expanded: true } } }; const docSourceCode = ` <template> <h2>Tree 1</h2> <tree-view :initial-model="tvModel.tree1Data" :model-defaults="modelDefaults"></tree-view> <h2>Tree 2</h2> <tree-view :initial-model="tvModel.tree2Data" :model-defaults="modelDefaults"></tree-view> <h2>Text Drop Target</h2> <textarea style="width: 90%" rows="10"></textarea> </template> <script setup> import { ref } from "vue"; import { TreeView } from "@grapoza/vue-tree"; import treeViewData from "../data/checkboxesTreeViewData"; const modelDefaults = ref({ expanderTitle: 'Expand this node', draggable: true, allowDrop: true, state: { expanded: true } }); const tvModel = ref(treeViewData); </script>`; DragDrop.parameters = { docs: { source: { code: docSourceCode, language: "html", type: "auto", }, }, };<file_sep>export default [ { id: 'radiobuttons-node1', label: 'My First Node', children: [], treeNodeSpec: { expandable: true, selectable: true, input: { type: 'radio', name: 'radio1', value: 'aValueToSubmit', isInitialRadioGroupValue: true }, state: { expanded: false, selected: false } } }, { id: 'radiobuttons-node2', label: 'My Second Node', children: [ { id: 'radiobuttons-subnode1', label: 'This is a subnode', children: [], treeNodeSpec: { expandable: true, selectable: true, input: { type: 'radio', name: 'radio2', isInitialRadioGroupValue: true }, state: { expanded: false, selected: false } } }, { id: 'radiobuttons-subnode2', label: 'This is a checkable, checked subnode', children: [], treeNodeSpec: { expandable: true, selectable: true, input: { type: 'radio', name: 'radio2' }, state: { expanded: false, selected: false } } } ], treeNodeSpec: { expandable: true, selectable: true, input: { type: 'radio', name: 'radio1' }, state: { expanded: true, selected: false } } } ];<file_sep>import TreeView from '../../components/TreeView.vue'; const Template = (args) => ({ components: { TreeView }, setup() { return { args }; }, template: '<tree-view v-bind="args" />' }); export const SettingDefaults = Template.bind({}); SettingDefaults.args = { initialModel: [ { identifier: "node1", description: "Node with no children" }, { identifier: "node2", description: "Node with a child", children: [ { identifier: "childNode1", description: "A child node" } ] } ], modelDefaults: { idProperty: 'identifier', labelProperty: 'description', state: { expanded: true } } }; const docSourceCode = ` <template> <tree-view :initial-model="tvModel" :model-defaults="modelDefaults"></tree-view> </template> <script setup> import { ref } from "vue"; import { TreeView } from "@grapoza/vue-tree"; const modelDefaults = ref({ idProperty: 'identifier', labelProperty: 'description', state: { expanded: true } }); const tvModel = ref([ { identifier: "node1", description: "Node with no children" }, { identifier: "node2", description: "Node with a child", children: [ { identifier: "childNode1", description: "A child node" } ] } ]); </script>`; SettingDefaults.parameters = { docs: { source: { code: docSourceCode, language: "html", type: "auto", }, }, };<file_sep>import { expect, describe, it, beforeEach, afterEach, vi } from 'vitest'; import { mount, flushPromises } from '@vue/test-utils'; import TreeViewNode from './TreeViewNode.vue'; import { generateNodes } from '../../tests/data/node-generator.js'; import SelectionMode from '../enums/selectionMode'; import TreeEvent from '../../src/enums/event.js'; const getDefaultPropsData = function () { return { ariaKeyMap: { activateItem: [32], // Space selectItem: [13], // Enter focusLastItem: [35], // End focusFirstItem: [36], // Home collapseFocusedItem: [37], // Left expandFocusedItem: [39], // Right focusPreviousItem: [38], // Up focusNextItem: [40], // Down insertItem: [45], // Insert deleteItem: [46] // Delete }, initialModel: generateNodes(['ces'])[0], modelDefaults: {}, depth: 0, treeId: 'tree-id', initialRadioGroupValues: {}, isMounted: false, selectionMode: SelectionMode.Multiple } }; async function createWrapper(customPropsData, slotsData) { var w = mount(TreeViewNode, { sync: false, props: customPropsData || getDefaultPropsData(), slots: slotsData, attachTo: '#root', global: { provide: { filterMethod: null } } }); await w.setProps({ isMounted: true }); return w; } async function triggerKeydown(wrapper, keyCode) { var e = new Event('keydown'); e.keyCode = keyCode; vi.spyOn(e, 'stopPropagation'); vi.spyOn(e, 'preventDefault'); wrapper.vm.$refs.nodeElement.dispatchEvent(e); await wrapper.vm.$nextTick(); return e; } describe('TreeViewNode.vue', () => { let wrapper = null; let root = null; beforeEach(async () => { // Create an element to which the component will be mounted. root = document.createElement('div'); root.id = "root"; document.body.appendChild(root); }); afterEach(() => { wrapper = null; document.body.removeChild(root); }); describe('always', () => { beforeEach(async () => { wrapper = await createWrapper(); }) it('should have an ARIA role of treeitem', () => { expect(wrapper.vm.$refs.nodeElement.attributes.role.value).to.equal('treeitem'); }); it('should have a tabindex of 0 if focusable', async () => { wrapper.vm.model.treeNodeSpec.focusable = true; await wrapper.vm.$nextTick(); expect(wrapper.vm.$refs.nodeElement.attributes.tabindex.value).to.equal('0'); }); it('should have a tabindex of -1 if not focusable', () => { expect(wrapper.vm.$refs.nodeElement.attributes.tabindex.value).to.equal('-1'); }); }); describe('when given a title in the model data for a text node', () => { beforeEach(async () => { wrapper = await createWrapper({ ariaKeyMap: {}, depth: 0, initialModel: { id: 'my-node', label: 'My Node', treeNodeSpec: { title: 'My Title' } }, modelDefaults: {}, treeId: 'tree-id', initialRadioGroupValues: {}, isMounted: false }); }); it('should have a title attribute on the node\'s text', () => { let elem = wrapper.find(`.grtvn-self-text`).element; expect(elem.getAttribute('title')).to.equal('My Title'); }); }); describe('when given a title in the model data for an input node', () => { beforeEach(async () => { let data = getDefaultPropsData(); data.initialModel.treeNodeSpec.title = 'My Title'; wrapper = await createWrapper(data); }); it('should have a title attribute on the node\'s label', () => { let elem = wrapper.find(`.grtvn-self-label`).element; expect(elem.getAttribute('title')).to.equal('My Title'); }); }); describe('when generating element IDs', () => { beforeEach(async () => { wrapper = await createWrapper(); }); it('should have a nodeId made of the tree ID and the model[idPropName] property', () => { expect(wrapper.vm.nodeId).to.equal(wrapper.vm.treeId + '-' + wrapper.vm.model.id); }); it('should have an expanderId made of the node ID and -exp', () => { expect(wrapper.vm.expanderId).to.equal(wrapper.vm.nodeId + '-exp'); }); describe('and the node has an input', () => { it('should have an inputId made of the node ID and -input', () => { expect(wrapper.vm.inputId).to.equal(wrapper.vm.nodeId + '-input'); }); }); }); describe('when there is not an addChildCallback method', () => { let addChildButton = null; beforeEach(async () => { wrapper = await createWrapper({ ariaKeyMap: {}, initialModel: generateNodes(['es'])[0], modelDefaults: {}, depth: 0, treeId: 'tree', initialRadioGroupValues: {}, isMounted: false }); addChildButton = wrapper.find('#' + wrapper.vm.nodeId + '-add-child'); }); it('should not include an add button', async () => { expect(addChildButton.exists()).to.be.false; }); }); describe('when there is an addChildCallback method in the model', () => { let addChildButton = null; beforeEach(async () => { let addChildCallback = () => { return Promise.resolve(null); }; wrapper = await createWrapper({ ariaKeyMap: {}, initialModel: generateNodes(['esa'], '', addChildCallback)[0], modelDefaults: {}, depth: 0, treeId: 'tree', initialRadioGroupValues: {}, isMounted: false }); addChildButton = wrapper.find('#' + wrapper.vm.nodeId + '-add-child'); }); it('should include an add button', async () => { expect(addChildButton.exists()).to.be.true; }); }); describe('when there is an addChildCallback method in the model defaults', () => { let addChildButton = null; beforeEach(async () => { let addChildCallback = () => { return Promise.resolve(null); }; wrapper = await createWrapper({ ariaKeyMap: {}, initialModel: generateNodes(['esa'])[0], modelDefaults: { addChildCallback }, depth: 0, treeId: 'tree', initialRadioGroupValues: {}, isMounted: false }); addChildButton = wrapper.find('#' + wrapper.vm.nodeId + '-add-child'); }); it('should include an add button', async () => { expect(addChildButton.exists()).to.be.true; }); }); describe('when a node\'s model is disabled', () => { beforeEach(async () => { let initialModel = generateNodes(['ces!'])[0]; wrapper = await createWrapper({ ariaKeyMap: {}, initialModel, modelDefaults: {}, depth: 0, treeId: 'tree', initialRadioGroupValues: {}, isMounted: false }); }); it('should have a disabled input', () => { let input = wrapper.find('#' + wrapper.vm.inputId); expect(input.element.disabled).to.be.true; }); }); describe('when a node\'s model is not disabled', () => { beforeEach(async () => { wrapper = await createWrapper(); }); it('should have an enabled input', () => { let input = wrapper.find('#' + wrapper.vm.inputId); expect(input.element.disabled).to.be.false; }); }); describe('when a node\'s model is expandable', () => { describe('and the model has children', () => { beforeEach(async () => { let initialModel = generateNodes(['es', ['es']])[0]; wrapper = await createWrapper({ ariaKeyMap: {}, initialModel, modelDefaults: {}, depth: 0, treeId: 'tree', initialRadioGroupValues: {}, isMounted: false }); }); it('should have an expander', () => { let target = wrapper.find('.grtvn-self-expander'); expect(target.exists()).to.be.true; }); describe('and the model is not expanded', () => { it('should have an aria-expanded attribute set to false', () => { let target = wrapper.find('.grtvn[aria-expanded="false"]'); expect(target.exists()).to.be.true; }); it('should have an aria-hidden attribute set to true on the child list', () => { let target = wrapper.find('.grtvn-children[aria-hidden="true"]'); expect(target.exists()).to.be.true; }); it('should have an aria-expanded attribute value of false', () => { expect(wrapper.vm.$refs.nodeElement.attributes['aria-expanded'].value).to.equal('false'); }); }); describe('and the model is expanded', () => { beforeEach(async () => { let initialModel = generateNodes(['Es', ['es']])[0]; wrapper = await createWrapper({ ariaKeyMap: {}, initialModel, modelDefaults: {}, depth: 0, treeId: 'tree', initialRadioGroupValues: {}, isMounted: false }); }); it('should have an aria-expanded attribute set to true', () => { let target = wrapper.find('.grtvn[aria-expanded="true"]'); expect(target.exists()).to.be.true; }); it('should have an aria-hidden attribute set to false on the child list', () => { let target = wrapper.find('.grtvn-children[aria-hidden="false"]'); expect(target.exists()).to.be.true; }); it('should have an aria-expanded attribute value of true', () => { expect(wrapper.vm.$refs.nodeElement.attributes['aria-expanded'].value).to.equal('true'); }); }); }); describe('and the model does not have children', () => { beforeEach(async () => { let initialModel = generateNodes(['es'])[0]; wrapper = await createWrapper({ ariaKeyMap: {}, initialModel, modelDefaults: {}, depth: 0, treeId: 'tree', initialRadioGroupValues: {}, isMounted: false }); }); it('should not have an expander', () => { let target = wrapper.find('.grtvn-self-expander'); expect(target.exists()).to.be.false; }); }); }); describe('when a node\'s model is not expandable', () => { beforeEach(async () => { let initialModel = generateNodes(['s', ['es']])[0]; wrapper = await createWrapper({ ariaKeyMap: {}, initialModel, modelDefaults: {}, depth: 0, treeId: 'tree', initialRadioGroupValues: {}, isMounted: false }); }); it('should not have an expander', () => { let target = wrapper.find('.grtvn-self-expander'); expect(target.exists()).to.be.false; }); it('should not have an aria-expanded attribute', () => { expect(wrapper.vm.$refs.nodeElement.attributes['aria-expanded']).to.be.undefined; }); }); describe('when selectionMode is null', () => { beforeEach(async () => { let initialModel = generateNodes(['S'])[0]; wrapper = await createWrapper({ ariaKeyMap: {}, initialModel, modelDefaults: {}, depth: 0, treeId: 'tree', initialRadioGroupValues: {}, selectionMode: SelectionMode.None, isMounted: false }); }); it('should not have an aria-selected attribute', () => { expect(wrapper.vm.$refs.nodeElement.attributes['aria-selected']).to.be.undefined; }); }); describe('when model.selectable is false', () => { beforeEach(async () => { let initialModel = generateNodes([''])[0]; wrapper = await createWrapper({ ariaKeyMap: {}, initialModel, modelDefaults: {}, depth: 0, treeId: 'tree', initialRadioGroupValues: {}, selectionMode: SelectionMode.Multiple, isMounted: false }); }); it('should not have an aria-selected attribute', () => { expect(wrapper.vm.$refs.nodeElement.attributes['aria-selected']).to.be.undefined; }); }); describe('when selectionMode is single', () => { describe('and the node is selected', () => { beforeEach(async () => { let initialModel = generateNodes(['S'])[0]; wrapper = await createWrapper({ ariaKeyMap: {}, initialModel, modelDefaults: {}, depth: 0, treeId: 'tree', initialRadioGroupValues: {}, selectionMode: SelectionMode.Single, isMounted: false }); }); it('should have an aria-selected attribute of true', () => { expect(wrapper.vm.$refs.nodeElement.attributes['aria-selected'].value).to.equal('true'); }); }); describe('and the node is not selected', () => { beforeEach(async () => { let initialModel = generateNodes(['s'])[0]; wrapper = await createWrapper({ ariaKeyMap: {}, initialModel, modelDefaults: {}, depth: 0, treeId: 'tree', initialRadioGroupValues: {}, selectionMode: SelectionMode.Single, isMounted: false }); }); it('should not have an aria-selected attribute', () => { expect(wrapper.vm.$refs.nodeElement.attributes['aria-selected']).to.be.undefined; }); }); }); describe('when selectionMode is selectionFollowsFocus', () => { describe('and the node is selected', () => { beforeEach(async () => { let initialModel = generateNodes(['S'])[0]; wrapper = await createWrapper({ ariaKeyMap: {}, initialModel, modelDefaults: {}, depth: 0, treeId: 'tree', initialRadioGroupValues: {}, selectionMode: SelectionMode.SelectionFollowsFocus, isMounted: false }); }); it('should have an aria-selected attribute of true', () => { expect(wrapper.vm.$refs.nodeElement.attributes['aria-selected'].value).to.equal('true'); }); }); describe('and the node is not selected', () => { beforeEach(async () => { let initialModel = generateNodes(['s'])[0]; wrapper = await createWrapper({ ariaKeyMap: {}, initialModel, modelDefaults: {}, depth: 0, treeId: 'tree', initialRadioGroupValues: {}, selectionMode: SelectionMode.SelectionFollowsFocus, isMounted: false }); await wrapper.vm.$nextTick(); }); it('should not have an aria-selected attribute', () => { expect(wrapper.vm.$refs.nodeElement.attributes['aria-selected']).to.be.undefined; }); }); }); describe('when selectionMode is multiple', () => { describe('and the node is selected', () => { beforeEach(async () => { let initialModel = generateNodes(['S'])[0]; wrapper = await createWrapper({ ariaKeyMap: {}, initialModel, modelDefaults: {}, depth: 0, treeId: 'tree', initialRadioGroupValues: {}, selectionMode: SelectionMode.Multiple, isMounted: false }); }); it('should have an aria-selected attribute of true', () => { expect(wrapper.vm.$refs.nodeElement.attributes['aria-selected'].value).to.equal('true'); }); }); describe('and the node is not selected', () => { beforeEach(async () => { let initialModel = generateNodes(['s'])[0]; wrapper = await createWrapper({ ariaKeyMap: {}, initialModel, modelDefaults: {}, depth: 0, treeId: 'tree', initialRadioGroupValues: {}, selectionMode: SelectionMode.Multiple, isMounted: false }); }); it('should have an aria-selected attribute of false', () => { expect(wrapper.vm.$refs.nodeElement.attributes['aria-selected'].value).to.equal('false'); }); }); }); describe('when the node\'s selected state changes', () => { beforeEach(async () => { wrapper = await createWrapper(); wrapper.vm.model.treeNodeSpec.state.selected = true; await wrapper.vm.$nextTick(); }); it('should emit the treeNodeSelectedChange event', () => { expect(wrapper.emitted().treeNodeSelectedChange).to.be.an('array').that.has.length(1); }); }); describe('when idProperty is specified', () => { beforeEach(async () => { wrapper = await createWrapper(); wrapper.vm.model.treeNodeSpec.idProperty = 'label'; await wrapper.vm.$nextTick(); }); it('should have an idPropName matching the idProperty', () => { expect(wrapper.vm.idPropName).to.equal('label'); }); it('should have a nodeId made of the tree ID and the model[idPropName] property', () => { expect(wrapper.vm.nodeId).to.equal(wrapper.vm.treeId + '-' + wrapper.vm.model.label); }); }); describe('when idProperty is not specified', () => { beforeEach(async () => { wrapper = await createWrapper(); wrapper.vm.model.treeNodeSpec.idProperty = null; await wrapper.vm.$nextTick(); }); it('should have an idPropName of id', () => { expect(wrapper.vm.idPropName).to.equal('id'); }); it('should have a nodeId made of the tree ID and the model.id property', () => { expect(wrapper.vm.nodeId).to.equal(wrapper.vm.treeId + '-' + wrapper.vm.model.id); }); }); describe('when the model does not have a property that matches idProperty', () => { beforeEach(async () => { vi.spyOn(console, 'error').mockImplementation(() => { }); wrapper = await createWrapper({ ariaKeyMap: {}, depth: 0, treeId: 'tree', initialModel: { badid: 'asf', label: 'asdf' }, modelDefaults: {}, initialRadioGroupValues: {}, isMounted: false }); }); it('should log an error', () => { expect(console.error.mock.calls[0][0]) .to.equal('initialModel id is required and must be a number or string. Expected prop id to exist on the model.'); }); }); describe('when labelProperty is specified', () => { beforeEach(async () => { wrapper = await createWrapper(); wrapper.vm.model.treeNodeSpec.labelProperty = 'id'; await wrapper.vm.$nextTick(); }); it('should have a labelPropName matching the labelProperty', () => { expect(wrapper.vm.labelPropName).to.equal('id'); }); it('should have a label of the model[labelPropName] property', () => { expect(wrapper.text()).to.equal(wrapper.vm.model.id + ''); }); }); describe('when labelProperty is not specified', () => { beforeEach(async () => { wrapper = await createWrapper(); wrapper.vm.model.treeNodeSpec.labelProperty = null; await wrapper.vm.$nextTick(); }); it('should have a labelPropName of label', () => { expect(wrapper.vm.labelPropName).to.equal('label'); }); it('should have a label of the model.label property', () => { expect(wrapper.text()).to.equal(wrapper.vm.model.label + ''); }); }); describe('when the model does not have a property that matches labelProperty', () => { beforeEach(async () => { vi.spyOn(console, 'error').mockImplementation(() => { }); wrapper = await createWrapper({ ariaKeyMap: {}, depth: 0, treeId: 'tree', initialModel: { id: 'asf', badlabel: 'asdf' }, modelDefaults: {}, initialRadioGroupValues: {}, isMounted: false }); }); it('should log an error', () => { expect(console.error.mock.calls[0][0]) .to.equal('initialModel label is required and must be a string. Expected prop label to exist on the model.'); }); }); describe('when childrenProperty is specified', () => { beforeEach(async () => { let defaultProps = getDefaultPropsData(); wrapper = await createWrapper(Object.assign(defaultProps, { initialModel: generateNodes(['sf', ['s', 's']])[0] })); wrapper.vm.model.treeNodeSpec.childrenProperty = 'children'; await wrapper.vm.$nextTick(); }); it('should have a children property of the expected values', () => { expect(wrapper.vm.model.children.length).to.equal(2); }); }); describe('when given custom classes', () => { const customizations = { classes: { treeViewNode: 'customnodeclass', treeViewNodeSelf: 'customnodeselfclass', treeViewNodeSelfExpander: 'customnodeselfexpanderclass', treeViewNodeSelfExpanded: 'customnodeselfexpandedclass', treeViewNodeSelfExpandedIndicator: 'customnodeselfexpandedindicatorclass', treeViewNodeSelfSelected: 'customnodeselfselectedclass', treeViewNodeSelfSpacer: 'customnodeselfspacerclass', treeViewNodeSelfLabel: 'customnodeselflabelclass', treeViewNodeSelfInput: 'customnodeselfinputclass', treeViewNodeSelfCheckbox: 'customnodeselfcheckboxclass', treeViewNodeSelfRadio: 'customnodeselfradioclass', treeViewNodeSelfText: 'customnodeselftextclass', treeViewNodeSelfAction: 'customnodeselfactionclass', treeViewNodeSelfAddChild: 'customnodeselfaddchildclass', treeViewNodeSelfAddChildIcon: 'customnodeselfaddchildiconclass', treeViewNodeSelfDelete: 'customnodeselfdeleteclass', treeViewNodeSelfDeleteIcon: 'customnodeselfdeleteiconclass', treeViewNodeChildrenWrapper: 'customnodechildrenwrapperclass', treeViewNodeChildren: 'customnodechildrenclass', treeViewNodeLoading: 'customnodeloadingclass' } }; beforeEach(async () => { let initialModel = generateNodes(['cEdS', ['res', 'esa']], "", () => Promise.resolve())[0]; wrapper = await createWrapper({ ariaKeyMap: {}, initialModel, modelDefaults: { customizations }, depth: 0, treeId: 'tree', initialRadioGroupValues: {}, selectionMode: SelectionMode.Single, isMounted: false }); }); it('should add the custom class to the tree view node\'s root element', () => { let target = wrapper.find('.grtvn.' + customizations.classes.treeViewNode); expect(target.exists()).to.be.true; }); it('should add the custom class to the tree view node\'s self element', () => { let target = wrapper.find('.grtvn-self.' + customizations.classes.treeViewNodeSelf); expect(target.exists()).to.be.true; }); it('should add the custom class to the tree view node\'s expander element', () => { let target = wrapper.find('.grtvn-self-expander.' + customizations.classes.treeViewNodeSelfExpander); expect(target.exists()).to.be.true; }); it('should add the custom class to the tree view node\'s expanded element', () => { let target = wrapper.find('.grtvn-self-expanded.' + customizations.classes.treeViewNodeSelfExpanded); expect(target.exists()).to.be.true; }); it('should add the custom class to the tree view node\'s expanded indicator element', () => { let target = wrapper.find('.grtvn-self-expanded-indicator.' + customizations.classes.treeViewNodeSelfExpandedIndicator); expect(target.exists()).to.be.true; }); it('should add the custom class to the tree view node\'s selected element', () => { let target = wrapper.find('.grtvn-self-selected.' + customizations.classes.treeViewNodeSelfSelected); expect(target.exists()).to.be.true; }); it('should add the custom class to the tree view node\'s spacer element', () => { let target = wrapper.find('.grtvn-self-spacer.' + customizations.classes.treeViewNodeSelfSpacer); expect(target.exists()).to.be.true; }); it('should add the custom class to the tree view node\'s label element', () => { let target = wrapper.find('.grtvn-self-label.' + customizations.classes.treeViewNodeSelfLabel); expect(target.exists()).to.be.true; }); it('should add the custom class to the tree view node\'s input element', () => { let target = wrapper.find('.grtvn-self-input.' + customizations.classes.treeViewNodeSelfInput); expect(target.exists()).to.be.true; }); it('should add the custom class to the tree view node\'s checkbox element', () => { let target = wrapper.find('.grtvn-self-checkbox.' + customizations.classes.treeViewNodeSelfCheckbox); expect(target.exists()).to.be.true; }); it('should add the custom class to the tree view node\'s radio button element', () => { let target = wrapper.find('.grtvn-self-radio.' + customizations.classes.treeViewNodeSelfRadio); expect(target.exists()).to.be.true; }); it('should add the custom class to the tree view node\'s text element', () => { let target = wrapper.find('.grtvn-self-text.' + customizations.classes.treeViewNodeSelfText); expect(target.exists()).to.be.true; }); it('should add the custom add child class to the tree view node\'s add child element', () => { let target = wrapper.find('.grtvn-self-action.' + customizations.classes.treeViewNodeSelfAddChild); expect(target.exists()).to.be.true; }); it('should add the custom action class to the tree view node\'s add child element', () => { let target = wrapper.find('.grtvn-self-action.' + customizations.classes.treeViewNodeSelfAddChild + '.' + customizations.classes.treeViewNodeSelfAction); expect(target.exists()).to.be.true; }); it('should add the custom class to the tree view node\'s add child icon element', () => { let target = wrapper.find('.grtvn-self-add-child-icon.' + customizations.classes.treeViewNodeSelfAddChildIcon); expect(target.exists()).to.be.true; }); it('should add the custom delete class to the tree view node\'s delete element', () => { let target = wrapper.find('.grtvn-self-action.' + customizations.classes.treeViewNodeSelfDelete); expect(target.exists()).to.be.true; }); it('should add the custom action class to the tree view node\'s delete element', () => { let target = wrapper.find('.grtvn-self-action.' + customizations.classes.treeViewNodeSelfDelete + '.' + customizations.classes.treeViewNodeSelfAction); expect(target.exists()).to.be.true; }); it('should add the custom class to the tree view node\'s delete icon element', () => { let target = wrapper.find('.grtvn-self-delete-icon.' + customizations.classes.treeViewNodeSelfDeleteIcon); expect(target.exists()).to.be.true; }); it('should add the custom class to the tree view node\'s children wrapper element', () => { let target = wrapper.find('.grtvn-children-wrapper.' + customizations.classes.treeViewNodeChildrenWrapper); expect(target.exists()).to.be.true; }); it('should add the custom class to the tree view node\'s children element', () => { let target = wrapper.find('.grtvn-children.' + customizations.classes.treeViewNodeChildren); expect(target.exists()).to.be.true; }); }); describe('when using slots', () => { describe('and rendering a text node', () => { const customClasses = { treeViewNode: 'customnodeclass' }; beforeEach(async () => { let initialModel = generateNodes([''], "baseId")[0]; wrapper = await createWrapper( { ariaKeyMap: {}, initialModel, modelDefaults: { customizations: { classes: customClasses } }, depth: 0, treeId: 'tree', initialRadioGroupValues: {}, isMounted: false }, { text: '<template #text="props"><span :id="props.model.id" class="text-slot-content"><span class="slot-custom-classes">{{ JSON.stringify(props.customClasses) }}</span></span></template>', } ); }); it('should render the slot template', () => { expect(wrapper.find('.text-slot-content').exists()).to.be.true; }); it('should have model data', () => { expect(wrapper.find('span#baseIdn0.text-slot-content').exists()).to.be.true; }); it('should have custom classes data', () => { expect(wrapper.find('span.slot-custom-classes').text()).to.equal(JSON.stringify(customClasses)); }); }); describe('and rendering a checkbox node', () => { const customClasses = { treeViewNode: 'customnodeclass' }; beforeEach(async () => { let initialModel = generateNodes(['c'], "baseId")[0]; wrapper = await createWrapper( { ariaKeyMap: {}, initialModel, modelDefaults: { customizations: { classes: customClasses } }, depth: 0, treeId: 'tree', initialRadioGroupValues: {}, isMounted: false }, { checkbox: `<template #checkbox="props"> <span :id="props.model.id" class="text-slot-content"> <span class="slot-custom-classes">{{ JSON.stringify(props.customClasses) }}</span> <span class="slot-input-id">{{ props.inputId }}</span> <span class="slot-has-handler">{{ typeof props.checkboxChangeHandler == 'function' }}</span> </span> </template>`, } ); }); it('should render the slot template', () => { expect(wrapper.find('.text-slot-content').exists()).to.be.true; }); it('should get a model property', () => { expect(wrapper.find('span#baseIdn0.text-slot-content').exists()).to.be.true; }); it('should get a customClasses property', () => { expect(wrapper.find('span.slot-custom-classes').text()).to.equal(JSON.stringify(customClasses)); }); it('should get an inputId property', () => { expect(wrapper.find('span.slot-input-id').text()).to.equal('tree-baseIdn0-input'); }); it('should get a checkboxChangeHandler property function', () => { expect(wrapper.find('span.slot-has-handler').text()).to.equal('true'); }); }); describe('and rendering a radiobutton node', () => { const customClasses = { treeViewNode: 'customnodeclass' }; beforeEach(async () => { let initialModel = generateNodes(['R'], "baseId")[0]; wrapper = await createWrapper( { ariaKeyMap: {}, initialModel, modelDefaults: { customizations: { classes: customClasses } }, depth: 0, treeId: 'tree', initialRadioGroupValues: {}, isMounted: false }, { radio: `<template #radio="props"> <span :id="props.model.id" class="text-slot-content"> <span class="slot-custom-classes">{{ JSON.stringify(props.customClasses) }}</span> <span class="slot-input-id">{{ props.inputId }}</span> <span class="slot-has-handler">{{ typeof props.radioChangeHandler == 'function' }}</span> <span class="slot-radio-group-values">{{ JSON.stringify(props.radioGroupValues) }}</span> </span> </template>`, } ); }); it('should render the slot template', () => { expect(wrapper.find('.text-slot-content').exists()).to.be.true; }); it('should get a model property', () => { expect(wrapper.find('span#baseIdn0.text-slot-content').exists()).to.be.true; }); it('should get a customClasses property', () => { expect(wrapper.find('span.slot-custom-classes').text()).to.equal(JSON.stringify(customClasses)); }); it('should get an inputId property', () => { expect(wrapper.find('span.slot-input-id').text()).to.equal('tree-baseIdn0-input'); }); it('should get a radioGroupValues property', () => { expect(wrapper.find('span.slot-radio-group-values').text()).to.equal('{"baseId-rb":"baseIdn0-val"}'); }); it('should get a radioChangeHandler property function', () => { expect(wrapper.find('span.slot-has-handler').text()).to.equal('true'); }); }); describe('and rendering a custom loader message', () => { const customClasses = { treeViewNode: 'customnodeclass' }; beforeEach(async () => { let loadChildrenAsync = () => new Promise(resolve => setTimeout(resolve.bind(null, []), 1000)); let initialModel = generateNodes(['e'], "baseId", null, loadChildrenAsync)[0]; wrapper = await createWrapper( { ariaKeyMap: {}, initialModel, modelDefaults: { customizations: { classes: customClasses } }, depth: 0, treeId: 'tree', initialRadioGroupValues: {}, isMounted: false }, { loading: '<template #loading="props"><span :id="props.model.id" class="loading-slot-content"><span class="slot-custom-classes">{{ JSON.stringify(props.customClasses) }}</span></span></template>', } ); wrapper.find('#' + wrapper.vm.expanderId).trigger('click'); }); it('should render the slot template', () => { expect(wrapper.find('.loading-slot-content').exists()).to.be.true; }); it('should have model data', () => { expect(wrapper.find('span#baseIdn0.loading-slot-content').exists()).to.be.true; }); it('should have custom classes data', () => { expect(wrapper.find('span.slot-custom-classes').text()).to.equal(JSON.stringify(customClasses)); }); }); }); describe('when the node\'s body is clicked', () => { let nodeBody = null; describe('always', () => { beforeEach(async () => { wrapper = await createWrapper(); nodeBody = wrapper.find(`#${wrapper.vm.nodeId} .grtvn-self`); nodeBody.trigger('click'); }); it('should emit the treeNodeClick event', () => { expect(wrapper.emitted().treeNodeClick.length).to.equal(1); }); }); describe('and the node is selectable', () => { beforeEach(async () => { wrapper = await createWrapper(); nodeBody = wrapper.find(`#${wrapper.vm.nodeId} .grtvn-self`); nodeBody.trigger('click'); }); it('should toggle the selected state', () => { expect(wrapper.vm.model.treeNodeSpec.state.selected).to.be.true; }); }); describe('and the node is not selectable', () => { beforeEach(async () => { wrapper = await createWrapper(Object.assign(getDefaultPropsData(), { selectionMode: SelectionMode.None })); nodeBody = wrapper.find(`#${wrapper.vm.nodeId} .grtvn-self`); nodeBody.trigger('click'); }); it('should not toggle the selected state', () => { expect(wrapper.vm.model.treeNodeSpec.state.selected).to.be.false; }); }); }); describe('when the node\'s body is double clicked', () => { let nodeBody = null; beforeEach(async () => { wrapper = await createWrapper(); nodeBody = wrapper.find(`#${wrapper.vm.nodeId} .grtvn-self`); }); it('should emit the treeNodeDblclick event', () => { nodeBody.trigger('dblclick'); expect(wrapper.emitted().treeNodeDblclick.length).to.equal(1); }); }); describe('when the node\'s expander is toggled', () => { let expander = null; describe('always', () => { beforeEach(async () => { wrapper = await createWrapper({ ariaKeyMap: {}, initialModel: generateNodes(['ces', ['ces']])[0], modelDefaults: {}, depth: 0, treeId: 'tree', initialRadioGroupValues: {}, isMounted: false }); expander = wrapper.find('#' + wrapper.vm.expanderId); }); it('should toggle the expanded state', () => { expander.trigger('click'); expect(wrapper.vm.model.treeNodeSpec.state.expanded).to.be.true; }); it('should emit the treeNodeExpandedChange event', async () => { expander.trigger('click'); await wrapper.vm.$nextTick(); expect(wrapper.emitted().treeNodeExpandedChange.length).to.equal(1); }); it('should not emit the treeNodeClick event', () => { expander.trigger('click'); expect(wrapper.emitted().treeNodeClick).to.be.undefined; }); it('should not emit the treeNodeDblclick event', () => { expander.trigger('dblclick'); expect(wrapper.emitted().treeNodeDblclick).to.be.undefined; }); }); describe('and the children should be loaded asynchronously', () => { beforeEach(async () => { let loadChildrenAsync = () => new Promise(resolve => setTimeout(resolve.bind(null, generateNodes(['', ''])), 1000)); let initialModel = generateNodes(['ces'], '', null, loadChildrenAsync)[0]; wrapper = await createWrapper({ ariaKeyMap: {}, initialModel, modelDefaults: {}, depth: 0, treeId: 'tree', initialRadioGroupValues: {}, isMounted: false }); vi.useFakeTimers(); wrapper.find('#' + wrapper.vm.expanderId).trigger('click'); }); afterEach(() => { vi.useRealTimers(); }); describe('and the the loadChildrenAsync Promise has not returned', () => { it('should show the loading area while children load', () => { expect(wrapper.find('.grtvn-loading').exists()).to.be.true; }); }); describe('and the loadChildrenAsync Promise returns', () => { beforeEach(async () => { vi.runAllTimers(); await wrapper.vm.$nextTick(); }); it('should show the children', () => { expect(wrapper.find('.grtvn-loading').exists()).to.be.false; expect(wrapper.findAllComponents(TreeViewNode).length).to.equal(2); }); it('should emit the treeNodeChildrenLoad event', () => { expect(wrapper.emitted().treeNodeChildrenLoad).to.be.an('array').that.has.length(1); }); }); }); }); describe('when the node\'s checkbox is toggled', () => { let checkbox = null; beforeEach(async () => { wrapper = await createWrapper(); checkbox = wrapper.find('#' + wrapper.vm.inputId); }); it('should toggle the input value state', () => { checkbox.setChecked(); expect(wrapper.vm.model.treeNodeSpec.state.input.value).to.be.true; }); it('should emit the treeNodeCheckboxChange event', () => { checkbox.setChecked(); expect(wrapper.emitted().treeNodeCheckboxChange.length).to.equal(1); }); it('should not emit the treeNodeClick event', () => { checkbox.setChecked(); expect(wrapper.emitted().treeNodeClick).to.be.undefined; }); it('should not emit the treeNodeDblclick event', () => { checkbox.trigger('dblclick'); expect(wrapper.emitted().treeNodeDblclick).to.be.undefined; }); }); describe('when a child node\'s checkbox is toggled', () => { let checkbox = null; beforeEach(async () => { wrapper = await createWrapper({ ariaKeyMap: {}, initialModel: generateNodes(['es', ['ces']])[0], modelDefaults: {}, depth: 0, treeId: 'tree', initialRadioGroupValues: {}, isMounted: false }); const childWrapper = wrapper.find('.grtvn-children').findComponent(TreeViewNode); checkbox = childWrapper.find('#' + childWrapper.vm.inputId); }); it('should emit the treeNodeChildCheckboxChange event', () => { checkbox.setChecked(); expect(wrapper.emitted().treeNodeCheckboxChange.length).to.equal(1); }); }); describe('when the node\'s radiobutton is toggled', () => { let radioButton = null; beforeEach(async () => { wrapper = await createWrapper({ ariaKeyMap: {}, initialModel: generateNodes(['res'])[0], modelDefaults: {}, depth: 0, treeId: 'tree', initialRadioGroupValues: {}, isMounted: false }); radioButton = wrapper.find('#' + wrapper.vm.inputId); }); it('should toggle the input value state', () => { radioButton.setChecked(); let model = wrapper.vm.model; expect(wrapper.vm.radioGroupValues[model.treeNodeSpec.input.name]).to.equal(model.treeNodeSpec.input.value); }); it('should emit the treeNodeRadioChange event', () => { radioButton.setChecked(); expect(wrapper.emitted().treeNodeRadioChange.length).to.equal(1); }); it('should not emit the treeNodeClick event', () => { radioButton.setChecked(); expect(wrapper.emitted().treeNodeClick).to.be.undefined; }); it('should not emit the treeNodeDblclick event', () => { radioButton.trigger('dblclick'); expect(wrapper.emitted().treeNodeDblclick).to.be.undefined; }); }); describe('when a node\'s delete button is clicked', () => { let deleteButton = null; describe('and a deleteNodeCallback is not provided', () => { beforeEach(async () => { wrapper = await createWrapper({ ariaKeyMap: {}, initialModel: generateNodes(['es', ['ds']])[0], modelDefaults: {}, depth: 0, treeId: 'tree', initialRadioGroupValues: {}, isMounted: false }); let childNode = wrapper.findAllComponents(TreeViewNode)[0]; deleteButton = wrapper.find('#' + childNode.vm.nodeId + '-delete'); }); it('should emit the treeNodeDelete event', async () => { deleteButton.trigger('click'); await flushPromises(); expect(wrapper.emitted().treeNodeDelete.length).to.equal(1); }); it('should remove the target node from the model', async () => { deleteButton.trigger('click'); await flushPromises(); expect(wrapper.vm.model.children.length).to.equal(0); }); }); describe('and a deleteNodeCallback is provided', () => { describe('and that callback returns true', () => { beforeEach(async () => { wrapper = await createWrapper({ ariaKeyMap: {}, initialModel: generateNodes(['es', ['ds']])[0], modelDefaults: { deleteNodeCallback: () => Promise.resolve(true) }, depth: 0, treeId: 'tree', initialRadioGroupValues: {}, isMounted: false }); let childNode = wrapper.findAllComponents(TreeViewNode)[0]; deleteButton = wrapper.find('#' + childNode.vm.nodeId + '-delete'); }); it('should emit the treeNodeDelete event', async () => { deleteButton.trigger('click'); await flushPromises(); expect(wrapper.emitted().treeNodeDelete.length).to.equal(1); }); it('should remove the target node from the model', async () => { deleteButton.trigger('click'); await flushPromises(); expect(wrapper.vm.model.children.length).to.equal(0); }); }); describe('and that callback returns false', () => { beforeEach(async () => { wrapper = await createWrapper({ ariaKeyMap: {}, initialModel: generateNodes(['es', ['ds']])[0], modelDefaults: { deleteNodeCallback: () => Promise.resolve(false) }, depth: 0, treeId: 'tree', initialRadioGroupValues: {}, isMounted: false }); let childNode = wrapper.findAllComponents(TreeViewNode)[0]; deleteButton = wrapper.find('#' + childNode.vm.nodeId + '-delete'); }); it('should not emit the treeNodeDelete event', async () => { deleteButton.trigger('click'); await flushPromises(); expect(wrapper.emitted().treeNodeDelete).to.be.undefined; }); it('should not remove the target node from the model', async () => { deleteButton.trigger('click'); await flushPromises(); expect(wrapper.vm.model.children.length).to.equal(1); }); }); }); }); describe('when a node\'s add child button is clicked', () => { let addChildButton = null; describe('and the callback resolves to node data', () => { beforeEach(async () => { let addChildCallback = () => { return Promise.resolve({ id: 'newId', label: 'new label' }); }; wrapper = await createWrapper({ ariaKeyMap: {}, initialModel: generateNodes(['esa'], "", addChildCallback)[0], modelDefaults: {}, depth: 0, treeId: 'tree', initialRadioGroupValues: {}, isMounted: false }); addChildButton = wrapper.find('#' + wrapper.vm.nodeId + '-add-child'); }); it('should emit the treeNodeAdd event', async () => { addChildButton.trigger('click'); await flushPromises(); expect(wrapper.emitted().treeNodeAdd.length).to.equal(1); }); it('should pass the new node data to the treeNodeAdd event', async () => { addChildButton.trigger('click'); await flushPromises(); expect(wrapper.emitted().treeNodeAdd[0][0].id).to.equal('newId'); }); it('should add a subnode to the target node from the model', async () => { addChildButton.trigger('click'); await flushPromises(); expect(wrapper.vm.model.children.length).to.equal(1); }); }); describe('and the callback does not resolve to node data', () => { beforeEach(async () => { let addChildCallback = () => { return Promise.resolve(null); }; wrapper = await createWrapper({ ariaKeyMap: {}, initialModel: generateNodes(['esa'], "", addChildCallback)[0], modelDefaults: {}, depth: 0, treeId: 'tree', initialRadioGroupValues: {}, isMounted: false }); addChildButton = wrapper.find('#' + wrapper.vm.nodeId + '-add-child'); }); it('should not emit the treeNodeAdd event', async () => { addChildButton.trigger('click'); await flushPromises(); expect(wrapper.emitted().treeNodeAdd).to.be.undefined; }); it('should add a subnode to the target node from the model', async () => { addChildButton.trigger('click'); await flushPromises(); expect(wrapper.vm.model.children.length).to.equal(0); }); }); }); describe('when there are child nodes', () => { beforeEach(async () => { let defaultProps = getDefaultPropsData(); wrapper = await createWrapper(Object.assign(defaultProps, { initialModel: generateNodes(['es', ['es']])[0] })); }); it('should have an ARIA role of group on the child list', () => { expect(wrapper.find('.grtvn-children').element.attributes.role.value).to.equal('group'); }); }); describe('when not provided with a focusable property on the initial model data', () => { beforeEach(async () => { let initialModel = { id: 'my-node', label: 'My Node', expandable: true }; wrapper = await createWrapper({ ariaKeyMap: {}, depth: 0, initialModel, modelDefaults: {}, treeId: 'tree-id', initialRadioGroupValues: {}, isMounted: false }); }); it('should have a boolean focusable property on the model', () => { expect(wrapper.vm.model.treeNodeSpec.focusable).to.be.a('boolean'); }); }); describe('when focusing via callback', () => { beforeEach(async () => { wrapper = await createWrapper(Object.assign(getDefaultPropsData(), { initialModel: generateNodes(['Es', ['sf']])[0] })); expect(wrapper.vm.model.treeNodeSpec.focusable).to.be.false; const innerNode = wrapper.findAllComponents(TreeViewNode)[0]; innerNode.vm.$emit(TreeEvent.RequestParentFocus); await wrapper.vm.$nextTick(); }); it('should have focusable set to true', () => { expect(wrapper.vm.model.treeNodeSpec.focusable).to.be.true; }); it('should focus the node', () => { expect(wrapper.vm.$refs.nodeElement).to.equal(document.activeElement); }); it('should emit a treeViewNodeAriaFocusableChange event', () => { expect(wrapper.emitted().treeNodeAriaFocusableChange).to.be.an('array').that.has.length(1); expect(wrapper.emitted().treeNodeAriaFocusableChange[0][0]).to.equal(wrapper.vm.model); }); }); describe('when the node self is clicked', () => { beforeEach(async () => { wrapper = await createWrapper(); wrapper.find('.grtvn-self').trigger('click'); await wrapper.vm.$nextTick(); }); it('should have focusable set to true', () => { expect(wrapper.vm.model.treeNodeSpec.focusable).to.be.true; }); }); describe('when selectionMode is not selectionFollowsFocus', () => { beforeEach(async () => { wrapper = await createWrapper(); wrapper.find('.grtvn-self').trigger('click'); await wrapper.vm.$nextTick(); }); it('should have state.selected set to true', () => { expect(wrapper.vm.model.treeNodeSpec.state.selected).to.be.true; }); }); describe('when selectionMode is selectionFollowsFocus', () => { beforeEach(async () => { wrapper = await createWrapper(Object.assign(getDefaultPropsData(), { selectionMode: SelectionMode.SelectionFollowsFocus })); wrapper.find('.grtvn-self').trigger('click'); await wrapper.vm.$nextTick(); }); it('should have state.selected set to true', () => { expect(wrapper.vm.model.treeNodeSpec.state.selected).to.be.true; }); }); describe('when the node gets a keydown', () => { describe('and Shift is pressed', () => { beforeEach(async () => { wrapper = await createWrapper(); var e = new Event('keydown'); e.shift = true; e.keyCode = wrapper.vm.ariaKeyMap.focusPreviousItem[0]; wrapper.vm.$refs.nodeElement.dispatchEvent(e); await wrapper.vm.$nextTick(); }); it('should ignore the keydown', () => { expect(wrapper.emitted().treeNodeAriaRequestPreviousFocus).not.to.exist; }); }); describe('and Alt is pressed', () => { beforeEach(async () => { wrapper = await createWrapper(); var e = new Event('keydown'); e.altKey = true; e.keyCode = wrapper.vm.ariaKeyMap.focusPreviousItem[0]; wrapper.vm.$refs.nodeElement.dispatchEvent(e); await wrapper.vm.$nextTick(); }); it('should ignore the keydown', () => { expect(wrapper.emitted().treeNodeAriaRequestPreviousFocus).not.to.exist; }); }); describe('and Ctrl is pressed', () => { beforeEach(async () => { wrapper = await createWrapper(); var e = new Event('keydown'); e.ctrlKey = true; e.keyCode = wrapper.vm.ariaKeyMap.focusPreviousItem[0]; wrapper.vm.$refs.nodeElement.dispatchEvent(e); await wrapper.vm.$nextTick(); }); it('should ignore the keydown', () => { expect(wrapper.emitted().treeNodeAriaRequestPreviousFocus).not.to.exist; }); }); describe('and the meta key is pressed', () => { beforeEach(async () => { wrapper = await createWrapper(); var e = new Event('keydown'); e.metaKey = true; e.keyCode = wrapper.vm.ariaKeyMap.focusPreviousItem[0]; wrapper.vm.$refs.nodeElement.dispatchEvent(e); await wrapper.vm.$nextTick(); }); it('should ignore the keydown', () => { expect(wrapper.emitted().treeNodeAriaRequestPreviousFocus).not.to.exist; }); }); describe('and an activation key is pressed', () => { describe('and the node has an input', () => { const curWindow = window; afterEach(() => { window = curWindow; }); describe('and the input is enabled', () => { beforeEach(async () => { wrapper = await createWrapper(); window = null; // HACK TODO - Work around for what may be an webidl2js issue in JSDOM usage? Err: Failed to construct 'MouseEvent': member view is not of type Window. await triggerKeydown(wrapper, wrapper.vm.ariaKeyMap.activateItem[0]); }); it('should perform the default action on the node', () => { expect(wrapper.find('input[type="checkbox"]').element.checked).to.be.true; }); }); describe('and the input is disabled', () => { beforeEach(async () => { wrapper = await createWrapper(); wrapper.vm.model.treeNodeSpec.state.input.disabled = true; await triggerKeydown(wrapper, wrapper.vm.ariaKeyMap.activateItem[0]); }); it('should perform no action on the node', () => { expect(wrapper.find('input[type="checkbox"]').element.checked).to.be.false; }); }); describe('and the node is in a custom slot without the standard class applied', () => { beforeEach(async () => { let initialModel = generateNodes(['c'], "baseId")[0]; wrapper = await createWrapper( { ariaKeyMap: { activateItem: [32], // Space }, initialModel, modelDefaults: { }, depth: 0, treeId: 'tree', initialRadioGroupValues: {}, isMounted: false }, { checkbox: `<template #checkbox="props"> <span :id="props.model.id" class="text-slot-content"> <input type="checkbox" :id="props.inputId" /> </span> </template>`, } ); window = null; // HACK TODO - Work around for what may be an webidl2js issue in JSDOM usage? Err: Failed to construct 'MouseEvent': member view is not of type Window. await triggerKeydown(wrapper, wrapper.vm.ariaKeyMap.activateItem[0]); }); it('should perform the default action on the node', () => { expect(wrapper.find('input[type="checkbox"]').element.checked).to.be.true; }); }); }); describe('and the node does not have an input', () => { beforeEach(async () => { let defaultProps = getDefaultPropsData(); wrapper = await createWrapper(Object.assign(defaultProps, { initialModel: generateNodes(['es'])[0] })); await triggerKeydown(wrapper, wrapper.vm.ariaKeyMap.activateItem[0]); }); it('should not fire any custom events', () => { expect(Object.getOwnPropertyNames(wrapper.emitted()).length).to.equal(1); expect(Object.getOwnPropertyNames(wrapper.emitted())[0]).to.equal('keydown'); }); }); }); describe('and the selection key is pressed', () => { describe('and the selectionMode is null', () => { beforeEach(async () => { wrapper = await createWrapper(); wrapper.setProps({ selectionMode: SelectionMode.None }); await wrapper.vm.$nextTick(); await triggerKeydown(wrapper, wrapper.vm.ariaKeyMap.selectItem[0]); await wrapper.vm.$nextTick(); }); it('should not toggle state.selected', () => { expect(wrapper.vm.model.treeNodeSpec.state.selected).to.be.false; }); }); describe('and the selectionMode is not null', () => { beforeEach(async () => { wrapper = await createWrapper(); await wrapper.vm.$nextTick(); await triggerKeydown(wrapper, wrapper.vm.ariaKeyMap.selectItem[0]); await wrapper.vm.$nextTick(); }); it('should toggle state.selected', () => { expect(wrapper.vm.model.treeNodeSpec.state.selected).to.be.true; }); }); }); describe('and an expand focused item key is pressed', () => { describe('and the node is expandable', () => { describe('and the node is not expanded', () => { beforeEach(async () => { let defaultProps = getDefaultPropsData(); wrapper = await createWrapper(Object.assign(defaultProps, { initialModel: generateNodes(['esf', ['s', 's']])[0] })); await triggerKeydown(wrapper, wrapper.vm.ariaKeyMap.expandFocusedItem[0]); }); it('should not expand the node', () => { expect(wrapper.emitted().treeNodeExpandedChange).to.be.an('array').that.has.length(1); expect(wrapper.vm.model.treeNodeSpec.state.expanded).to.be.true; }); }); describe('and the node is expanded', () => { beforeEach(async () => { let defaultProps = getDefaultPropsData(); wrapper = await createWrapper(Object.assign(defaultProps, { initialModel: generateNodes(['Esf', ['s', 's']])[0] })); await triggerKeydown(wrapper, wrapper.vm.ariaKeyMap.expandFocusedItem[0]); }); it('should focus the first child', () => { expect(wrapper.emitted().treeNodeAriaFocusableChange).to.be.an('array').that.has.length(1); expect(wrapper.vm.model.children[0].treeNodeSpec.focusable).to.be.true; }); }); }); describe('and the node is not expandable', () => { beforeEach(async () => { let defaultProps = getDefaultPropsData(); wrapper = await createWrapper(Object.assign(defaultProps, { initialModel: generateNodes(['sf', ['s', 's']])[0] })); await triggerKeydown(wrapper, wrapper.vm.ariaKeyMap.expandFocusedItem[0]); }); it('should ignore the keydown', () => { expect(wrapper.emitted().treeNodeExpandedChange).not.to.exist; }); }); }); describe('and a collapse focused item key is pressed', () => { describe('and the node is expandable', () => { describe('and the node is not expanded', () => { beforeEach(async () => { let defaultProps = getDefaultPropsData(); wrapper = await createWrapper(Object.assign(defaultProps, { initialModel: generateNodes(['Es', ['esf', ['s']]])[0] })); await triggerKeydown(wrapper.findAllComponents(TreeViewNode)[0], wrapper.vm.ariaKeyMap.collapseFocusedItem[0]); await wrapper.vm.$nextTick(); }); it('should focus the parent node', async () => { expect(wrapper.findAllComponents(TreeViewNode)[0].emitted().treeNodeAriaRequestParentFocus).to.be.an('array').that.has.length(1); expect(wrapper.vm.model.treeNodeSpec.focusable).to.be.true; }); }); describe('and the node is expanded', () => { beforeEach(async () => { let defaultProps = getDefaultPropsData(); wrapper = await createWrapper(Object.assign(defaultProps, { initialModel: generateNodes(['Esf', ['es']])[0] })); await triggerKeydown(wrapper, wrapper.vm.ariaKeyMap.collapseFocusedItem[0]); }); it('should collapse the node', () => { expect(wrapper.emitted().treeNodeExpandedChange).to.be.an('array').that.has.length(1); expect(wrapper.vm.model.treeNodeSpec.focusable).to.be.true; }); }); }); describe('and the node is not expandable', () => { beforeEach(async () => { let defaultProps = getDefaultPropsData(); wrapper = await createWrapper(Object.assign(defaultProps, { initialModel: generateNodes(['Es', ['sf']])[0] })); await triggerKeydown(wrapper.findAllComponents(TreeViewNode)[0], wrapper.vm.ariaKeyMap.collapseFocusedItem[0]); }); it('should focus the parent node', () => { expect(wrapper.findAllComponents(TreeViewNode)[0].emitted().treeNodeAriaRequestParentFocus).to.be.an('array').that.has.length(1); expect(wrapper.vm.model.treeNodeSpec.focusable).to.be.true; }); }); }); describe('and a focus first item key is pressed', () => { beforeEach(async () => { wrapper = await createWrapper(); await triggerKeydown(wrapper, wrapper.vm.ariaKeyMap.focusFirstItem[0]); }); it('should emit a treeViewNodeAriaRequestFirstFocus event', () => { expect(wrapper.emitted().treeNodeAriaRequestFirstFocus).to.be.an('array').that.has.length(1); }); }); describe('and a focus last item key is pressed', () => { beforeEach(async () => { wrapper = await createWrapper(); await triggerKeydown(wrapper, wrapper.vm.ariaKeyMap.focusLastItem[0]); }); it('should emit a treeViewNodeAriaRequestLastFocus event', () => { expect(wrapper.emitted().treeNodeAriaRequestLastFocus).to.be.an('array').that.has.length(1); }); }); describe('and a focus previous item key is pressed', () => { beforeEach(async () => { wrapper = await createWrapper(); await triggerKeydown(wrapper, wrapper.vm.ariaKeyMap.focusPreviousItem[0]); }); it('should emit a treeViewNodeAriaRequestPreviousFocus event', () => { expect(wrapper.emitted().treeNodeAriaRequestPreviousFocus).to.be.an('array').that.has.length(1); }); }); describe('and a focus next item key is pressed', () => { beforeEach(async () => { wrapper = await createWrapper(); await triggerKeydown(wrapper, wrapper.vm.ariaKeyMap.focusNextItem[0]); }); it('should emit a treeViewNodeAriaRequestNextFocus event', () => { expect(wrapper.emitted().treeNodeAriaRequestNextFocus).to.be.an('array').that.has.length(1); }); }); describe('and an insert item key is pressed', () => { describe('and there is no addChildCallback defined on the node', () => { beforeEach(async () => { wrapper = await createWrapper(); await triggerKeydown(wrapper, wrapper.vm.ariaKeyMap.insertItem[0]); }); it('should do nothing', () => { expect(wrapper.emitted().treeNodeAdd).not.to.exist; }); }); describe('and there is an addChildCallback defined on the node', () => { beforeEach(async () => { let defaultProps = getDefaultPropsData(); let nodeAddCallback = function () { return Promise.resolve({ id: 100, label: 'labelText' }) }; wrapper = await createWrapper(Object.assign(defaultProps, { initialModel: generateNodes(['sf'], "", nodeAddCallback)[0] })); await triggerKeydown(wrapper, wrapper.vm.ariaKeyMap.insertItem[0]); }); it('should add a child to the current node', () => { expect(wrapper.emitted().treeNodeAdd).to.be.an('array').that.has.length(1); expect(wrapper.vm.model.children.length).to.equal(1); }); }); }); describe('and a delete item key is pressed', () => { describe('and the node is not deletable', () => { beforeEach(async () => { wrapper = await createWrapper(); await triggerKeydown(wrapper, wrapper.vm.ariaKeyMap.deleteItem[0]); }); it('should do nothing', () => { expect(wrapper.emitted().treeNodeDelete).not.to.exist; }); }); describe('and the node is deletable', () => { describe('always', () => { beforeEach(async () => { let defaultProps = getDefaultPropsData(); wrapper = await createWrapper(Object.assign(defaultProps, { initialModel: generateNodes(['Es', ['esdf']])[0] })); await triggerKeydown(wrapper.findAllComponents(TreeViewNode)[0], wrapper.vm.ariaKeyMap.deleteItem[0]); }); it('should delete the current node', () => { // wrapper will emit the event as it bubbles up the tree; the child node // originated it, but is deleted by this point so we can't check it here. expect(wrapper.emitted().treeNodeDelete).to.be.an('array').that.has.length(1); expect(wrapper.vm.model.children.length).to.equal(0); }); }); describe('and the deleted node is the first of multiple siblings', () => { beforeEach(async () => { let defaultProps = getDefaultPropsData(); wrapper = await createWrapper(Object.assign(defaultProps, { initialModel: generateNodes(['Es', ['esdf', 'es']])[0] })); await triggerKeydown(wrapper.findAllComponents(TreeViewNode)[0], wrapper.vm.ariaKeyMap.deleteItem[0]); }); it('should focus the next node', () => { expect(wrapper.vm.model.children[0].treeNodeSpec.focusable).to.be.true; }); }); describe('and the deleted node is not the first of multiple siblings', () => { beforeEach(async () => { let defaultProps = getDefaultPropsData(); wrapper = await createWrapper(Object.assign(defaultProps, { initialModel: generateNodes(['Es', ['es', 'es', 'esdf']])[0] })); await triggerKeydown(wrapper.findAllComponents(TreeViewNode)[2], wrapper.vm.ariaKeyMap.deleteItem[0]); }); it('should focus the previous node', () => { expect(wrapper.vm.model.children[1].treeNodeSpec.focusable).to.be.true; }); }); }); }); describe('and an unhandled key is pressed', () => { let event; beforeEach(async () => { wrapper = await createWrapper(); event = await triggerKeydown(wrapper, 1000); }); it('should do nothing', () => { expect(Object.getOwnPropertyNames(wrapper.emitted()).length).to.equal(1); expect(Object.getOwnPropertyNames(wrapper.emitted())[0]).to.equal('keydown'); expect(event.stopPropagation.mock.calls.length).to.equal(0); expect(event.preventDefault.mock.calls.length).to.equal(0); }); }); }); describe('when setting focusable to the previous node from a child node', () => { let initialModel = null; let defaultProps = getDefaultPropsData(); describe('and the currently focusable node is the first sibling', () => { beforeEach(async () => { initialModel = generateNodes(['Es', ['esf']])[0]; wrapper = await createWrapper(Object.assign(defaultProps, { initialModel })); wrapper.vm.focusPreviousNode(initialModel.children[0]); await wrapper.vm.$nextTick(); }); it('should set this node as focusable', () => { expect(wrapper.vm.model.treeNodeSpec.focusable).to.be.true; }); }); describe('and the previous sibling node is expanded', () => { beforeEach(async () => { initialModel = generateNodes(['Es', ['Es', ['s', 's'], 'sf']])[0]; wrapper = await createWrapper(Object.assign(defaultProps, { initialModel })); wrapper.vm.focusPreviousNode(initialModel.children[1]); await wrapper.vm.$nextTick(); }); it('should set the last child of the previous sibling node as focusable', () => { expect(wrapper.vm.model.children[0].children[1].treeNodeSpec.focusable).to.be.true; }); }); describe('and the previous sibling node is not expanded', () => { beforeEach(async () => { initialModel = generateNodes(['Es', ['es', ['s', 's'], 'sf']])[0]; wrapper = await createWrapper(Object.assign(defaultProps, { initialModel })); wrapper.vm.focusPreviousNode(initialModel.children[1]); await wrapper.vm.$nextTick(); }); it('should set the previous sibling node as focusable', () => { expect(wrapper.vm.model.children[0].treeNodeSpec.focusable).to.be.true; }); }); }); describe('when setting focusable to the next node from a child node', () => { let initialModel = null; let defaultProps = getDefaultPropsData(); describe('and the child is expanded', () => { describe('and its children are not ignored', () => { beforeEach(async () => { initialModel = generateNodes(['Es', ['Esf', ['s', 's'], 's']])[0]; wrapper = await createWrapper(Object.assign(defaultProps, { initialModel })); wrapper.vm.focusNextNode(initialModel.children[0], false); await wrapper.vm.$nextTick(); }); it('should set its first child as focusable', () => { expect(wrapper.vm.model.children[0].children[0].treeNodeSpec.focusable).to.be.true; }); }); describe('and its children are ignored', () => { describe('and it has a next sibling', () => { beforeEach(async () => { initialModel = generateNodes(['Es', ['Esf', ['s', 's'], 's']])[0]; wrapper = await createWrapper(Object.assign(defaultProps, { initialModel })); wrapper.vm.focusNextNode(initialModel.children[0], true); await wrapper.vm.$nextTick(); }); it('should set the next sibling as focusable', () => { expect(wrapper.vm.model.children[1].treeNodeSpec.focusable).to.be.true; }); }); describe('and it does not have a next sibling', () => { beforeEach(async () => { initialModel = generateNodes(['Es', ['Esf', ['s', 's']]])[0]; wrapper = await createWrapper(Object.assign(defaultProps, { initialModel })); wrapper.vm.focusNextNode(initialModel.children[0], true); await wrapper.vm.$nextTick(); }); it('should pass up the chain to this node\'s parent, ignoring children', () => { expect(wrapper.emitted().treeNodeAriaRequestNextFocus).to.be.an('array').that.has.length(1); expect(wrapper.emitted().treeNodeAriaRequestNextFocus[0][1]).to.be.true; }); }); }); }); describe('and the child is not expanded', () => { describe('and it has a next sibling', () => { beforeEach(async () => { initialModel = generateNodes(['Es', ['esf', ['s', 's'], 's']])[0]; wrapper = await createWrapper(Object.assign(defaultProps, { initialModel })); wrapper.vm.focusNextNode(initialModel.children[0], false); await wrapper.vm.$nextTick(); }); it('should set the next sibling as focusable', () => { expect(wrapper.vm.model.children[1].treeNodeSpec.focusable).to.be.true; }); }); describe('and it does not have a next sibling', () => { beforeEach(async () => { initialModel = generateNodes(['Es', ['esf', ['s', 's']]])[0]; wrapper = await createWrapper(Object.assign(defaultProps, { initialModel })); wrapper.vm.focusNextNode(initialModel.children[0], false); await wrapper.vm.$nextTick(); }); it('should pass up the chain to this node\'s parent, ignoring children', () => { expect(wrapper.emitted().treeNodeAriaRequestNextFocus).to.be.an('array').that.has.length(1); expect(wrapper.emitted().treeNodeAriaRequestNextFocus[0][1]).to.be.true; }); }); }); }); describe('when a child node fires a treeNodeClick event', () => { beforeEach(async () => { const defaultProps = getDefaultPropsData(); const initialModel = generateNodes(['es', ['es']])[0]; wrapper = await createWrapper(Object.assign(defaultProps, { initialModel })); wrapper.find('.grtvn-children').findComponent(TreeViewNode).vm.$emit('treeNodeClick'); }); it('should emit a treeNodeClick event', () => { expect(wrapper.emitted('treeNodeClick').length).to.equal(1); }); }); describe('when a child node fires a treeNodeDblclick event', () => { beforeEach(async () => { const defaultProps = getDefaultPropsData(); const initialModel = generateNodes(['es', ['es']])[0]; wrapper = await createWrapper(Object.assign(defaultProps, { initialModel })); wrapper.find('.grtvn-children').findComponent(TreeViewNode).vm.$emit('treeNodeDblclick'); }); it('should emit a treeNodeDblclick event', () => { expect(wrapper.emitted('treeNodeDblclick').length).to.equal(1); }); }); describe('when a child node fires a treeNodeChildCheckboxChange event', () => { beforeEach(async () => { const defaultProps = getDefaultPropsData(); const initialModel = generateNodes(['es', ['es', ['esc']]])[0]; wrapper = await createWrapper(Object.assign(defaultProps, { initialModel })); wrapper.find('.grtvn-children').findComponent(TreeViewNode).vm.$emit('treeNodeChildCheckboxChange', initialModel.children[0], initialModel.children[0].children[0], null); }); it('should emit a treeNodeChildCheckboxChange event', () => { expect(wrapper.emitted('treeNodeChildCheckboxChange').length).to.equal(1); }); }); describe('when a child node fires a treeNodeRadioChange event', () => { beforeEach(async () => { const defaultProps = getDefaultPropsData(); const initialModel = generateNodes(['es', ['es']])[0]; wrapper = await createWrapper(Object.assign(defaultProps, { initialModel })); wrapper.find('.grtvn-children').findComponent(TreeViewNode).vm.$emit('treeNodeRadioChange'); }); it('should emit a treeNodeRadioChange event', () => { expect(wrapper.emitted('treeNodeRadioChange').length).to.equal(1); }); }); describe('when a child node fires a treeNodeExpandedChange event', () => { beforeEach(async () => { const defaultProps = getDefaultPropsData(); const initialModel = generateNodes(['es', ['es']])[0]; wrapper = await createWrapper(Object.assign(defaultProps, { initialModel })); wrapper.find('.grtvn-children').findComponent(TreeViewNode).vm.$emit('treeNodeExpandedChange'); }); it('should emit a treeNodeExpandedChange event', () => { expect(wrapper.emitted('treeNodeExpandedChange').length).to.equal(1); }); }); describe('when a child node fires a treeNodeChildrenLoad event', () => { beforeEach(async () => { const defaultProps = getDefaultPropsData(); const initialModel = generateNodes(['es', ['es']])[0]; wrapper = await createWrapper(Object.assign(defaultProps, { initialModel })); wrapper.find('.grtvn-children').findComponent(TreeViewNode).vm.$emit('treeNodeChildrenLoad'); }); it('should emit a treeNodeChildrenLoad event', () => { expect(wrapper.emitted('treeNodeChildrenLoad').length).to.equal(1); }); }); describe('when a child node fires a treeNodeAdd event', () => { beforeEach(async () => { const defaultProps = getDefaultPropsData(); const initialModel = generateNodes(['es', ['es']])[0]; wrapper = await createWrapper(Object.assign(defaultProps, { initialModel })); wrapper.find('.grtvn-children').findComponent(TreeViewNode).vm.$emit('treeNodeAdd'); }); it('should emit a treeNodeAdd event', () => { expect(wrapper.emitted('treeNodeAdd').length).to.equal(1); }); }); describe('when a child node fires a treeNodeAriaRequestFirstFocus event', () => { beforeEach(async () => { const defaultProps = getDefaultPropsData(); const initialModel = generateNodes(['es', ['es']])[0]; wrapper = await createWrapper(Object.assign(defaultProps, { initialModel })); wrapper.find('.grtvn-children').findComponent(TreeViewNode).vm.$emit('treeNodeAriaRequestFirstFocus'); }); it('should emit a treeNodeAriaRequestFirstFocus event', () => { expect(wrapper.emitted('treeNodeAriaRequestFirstFocus').length).to.equal(1); }); }); describe('when a child node fires a treeNodeAriaRequestLastFocus event', () => { beforeEach(async () => { const defaultProps = getDefaultPropsData(); const initialModel = generateNodes(['es', ['es']])[0]; wrapper = await createWrapper(Object.assign(defaultProps, { initialModel })); wrapper.find('.grtvn-children').findComponent(TreeViewNode).vm.$emit('treeNodeAriaRequestLastFocus'); }); it('should emit a treeNodeAriaRequestLastFocus event', () => { expect(wrapper.emitted('treeNodeAriaRequestLastFocus').length).to.equal(1); }); }); }); <file_sep>import { Canvas, Story } from '@storybook/addon-docs'; import TreeView from '../components/TreeView.vue'; import './css/classbased.css'; import './css/grayscale.css'; import './css/fontawesome.min.css'; import './css/solid.min.css'; <style>{` /* Work around https://github.com/storybookjs/storybook/issues/16188 */ .docs-story > div > div[scale='1'][height] { height: auto; min-height: 20px; } `}</style> # Examples ## A Basic Tree View The most basic use of the tree view consists of giving it some data and letting the tree populate the model with the default tree node properties, which it does by adding a `treeNodeSpec` property to each object in the hierarchy. This can be useful if you have a model and want it in a tree view, and also don't care if the tree view modifies that data. If you don't want the tree view to modify your data at all, you'll need to make a copy first and provide that to the tree view. If you want more control over the model, you can specify `treeNodeSpec` and its properties directly in the data. <a target="_blank" href="assets_data/basicTreeViewData.js">See the Model Data</a> <Canvas> <Story id="examples-treeview--basic" /> </Canvas> ## A Static Tree View If all you need is a static tree (no expanding subnodes) then set the `expandable` property to false for each node. You can then set the `expanded` property through code to hide/show children of a node as needed. The most common case is to always set it to `true` for all nodes. <a target="_blank" href="assets_data/staticTreeViewData.js">See the Model Data</a> <Canvas> <Story id="examples-treeview--static" /> </Canvas> ## Setting Defaults If there are common settings that should be used by all (or even most) nodes, these can be given to the tree in the `modelDefaults` property. This is a great place to customize things like what model props are used for the nodes' labels and whether all nodes are a certain type of input. Note that the expandable node below is expanded by default, as set from `modelDefaults`. The tree below uses the `identifier` and `description` properties of the node objects instead of `id` and `label`, and has all nodes expanded by default. These are set for all nodes at once by using `modelDefaults`. For more info, see [the docs](?path=/docs/grapoza-vue-tree-home--page#default-data). <Canvas> <Story id="examples-treeview--setting-defaults" /> </Canvas> ## Adding and Removing Nodes Any node can be marked as deletable or provide a callback used to create a new child node. To allow a node to have children added, set an `addChildCallback` property on the node's `treeNodeSpec` (or use `modelDefaults` to use the same callback for all nodes). The `addChildCallback` can take the parent node's model data as an argument, and should return a Promise that resolves to the node data to add. To make a node deletable, just set a `deletable` property to `true` in that node's `treeNodeSpec`. You can optionally specify a `deleteNodeCallback` method that accepts the node model to delete as an argument and returns a Promise resoving to a boolean indicating whether to delete that node. <a target="_blank" href="assets_data/addRemoveTreeViewData.js">See the Model Data</a> <Canvas> <Story id="examples-treeview--add-remove" /> </Canvas> ## Checkboxes Support for checkboxes is built into the tree view. To create a checkbox node, specify `input.type = 'checkbox'` on the node's `treeNodeSpec`. To initialize the node as checked, specify `state.input.value = true`. The convenience method `getCheckedCheckboxes` is exposed on the tree component to make it easy to get the checkbox nodes that have been checked. <a target="_blank" href="assets_data/checkboxesTreeViewData.js">See the Model Data</a> <Canvas> <Story id="examples-treeview--checkboxes" /> </Canvas> ## Radiobuttons Support for radio buttons is also built into the tree view. To create a radio button node, specify `input.type = 'radio'` on the node's `treeNodeSpec`, give the node a name using the `input.name` property, and give the node a value using `input.value`. The name will determine the radio button group to which the radio button belongs. To initialize a node as checked set the node's `input.isInitialRadioGroupValue` to `true`. If multiple nodes within a radio button group are specified as `isInitialRadioGroupValue`, the last one in wins. The convenience method `getCheckedRadioButtons` is exposed on the tree component to make it easy to get the radio nodes that have been checked. <a target="_blank" href="assets_data/radiobuttonsTreeViewData.js">See the Model Data</a> <Canvas> <Story id="examples-treeview--radiobuttons" /> </Canvas> ## Selection Any node can be marked as selectable. To set a node's selectability, set a `selectable` property to `true` or `false` (the default) in that node's `treeNodeSpec`. Different selection modes allow different selection behavior, but only affect nodes that are selectable. The convenience method `getSelected` is exposed on the tree component to make it easy to get the nodes that have been selected. For more info see [the docs](?path=/docs/grapoza-vue-tree-home--page#selection-mode). <a target="_blank" href="assets_data/selectionTreeViewData.js">See the Model Data</a> <Canvas> <Story id="examples-treeview--selection" /> </Canvas> ## Slots A tree view has slots available for replacing specific types of nodes. The `text`, `checkbox`, `radio`, `loading-root` and `loading` slots replace the correpsonding types of nodes. For more info, see [the docs](?path=/docs/grapoza-vue-tree-home--page#slots). <a target="_blank" href="assets_data/slotsTreeViewData.js">See the Model Data</a> <Canvas> <Story id="examples-treeview--slots" /> </Canvas> ## Asynchronous Loading Two types of asynchronous loading are available. The first loads the root data for the tree view itself, and the second asynchronously loads child data when a node is expanded. You can load root nodes asynchronously by providing a function to the `loadNodesAsync` property of the tree view. The function should return a Promise that resolves to an array of model data to add as root nodes. You can load child nodes asynchronously by providing a function to the `loadChildrenAsync` property in a node's `treeNodeSpec` (or use `modelDefaults` to use the same method for all nodes). The function can take the parent node's model data as an argument, and should return a Promise that resolves to an array of model data to add as children. <Canvas> <Story id="examples-treeview--async" /> </Canvas> ## Custom Styles Custom styling is achieved through a combination of using the `customizations` property of TreeViewNode data to apply custom styles to parts of nodes, along with a custom `skinStyle` TreeView prop and associated stylesheet. Of course, you could also just write some very specific selectors to override the default styles. For more info, see [the docs](?path=/docs/grapoza-vue-tree-home--page#customizing-the-tree-view). The default styles are applied to all of the other examples on this page (with the exception of the Slots example). There's not much to see there, since the intention is for the user to handle styling the tree view while the component focuses on creating a workable structure. Things generally line up right, but not much more can be said for it. Some simple customizations can be done by applying custom classes to various parts of the tree using the `customizations` property, most likely in the `modelDefaults` parameter of the TreeView component itself. In this example, `customizations.classes.treeViewNodeSelfText` is given a value of `big-text`. The `big-text` class is defined in a classbased.css stylesheet. <a target="_blank" href="assets_css/classbased.css">See the Stylesheet</a> <Canvas> <Story id="examples-treeview--class-customization" /> </Canvas> In the next example, a tree view has been given a `skin-class` prop value of `grayscale`. This effectively swaps out a class named `grtv-default-skin` on the TreeView for the one specified as the `skin-class`. This _completely removes_ the default styling. To provide new styles, a new stylesheet was created based on the default styles (copied right from the browser). This gives complete control of the styling, allowing for easier usage of things like Font Awesome as seen here. <a target="_blank" href="assets_css/grayscale.css">See the Stylesheet</a> <Canvas> <Story id="examples-treeview--skin-customization" /> </Canvas> ## Drag and Drop You can drag a node that has the `draggable` property in a node's `treeNodeSpec` set to `true`. Any node with `allowDrop` set to `true` in the `treeNodeSpec` can accept a drop from any TreeView. <a target="_blank" href="assets_data/dragDropTreeViewData.js">See the Model Data</a> <Canvas> <Story id="examples-treeview--drag-drop" /> </Canvas> ## Filtering You can provide a method by which data should be filtered. Any node for which the method returns `true` or for which a subnode returns `true` will be included in the visual tree. <a target="_blank" href="assets_data/Filtering.js">See the Model Data</a> <Canvas> <Story id="examples-treeview--filtering" /> </Canvas><file_sep>import { watch } from 'vue'; import { useFilter } from './filter.js'; import { useFocus } from '../focus/focus.js'; /** * Composable dealing with filter handling at the top level of the tree view. * @param {Ref<TreeViewNode[]>} treeModel A Ref to the top level model of the tree * @returns {Object} Methods to deal with tree view level filtering */ export function useTreeViewFilter(treeModel) { const { getFilteredNodes } = useFilter(); const { focusFirst } = useFocus(); let needsRefocusing = getFilteredNodes(treeModel).length === 0; // When the filter changes, see if all nodes were removed. // If they were, manually restore focus the next time the filtered list changes. watch(() => getFilteredNodes(treeModel), () => { if (getFilteredNodes(treeModel).length > 0) { if (needsRefocusing) { focusFirst(treeModel, true); } needsRefocusing = false; } else { needsRefocusing = true; } }) return {}; }<file_sep>module.exports = { "stories": [ "../src/**/Home.stories.mdx", "../src/**/*.stories.mdx", "../src/**/*.stories.@(js|jsx|ts|tsx)" ], "addons": [ "@storybook/addon-links", "@storybook/addon-essentials" ], "core": { builder: "webpack5", disableTelemetry: true, }, "framework": "@storybook/vue3", staticDirs: [ // Copy the data used in examples so they can be directly linked from story descriptions { from: '../src/stories/data', to: "assets_data" }, { from: '../src/stories/css', to: 'assets_css' } ], }; <file_sep>import TreeView from '../../components/TreeView.vue'; import treeViewData from '../data/filteringTreeViewData'; const Template = (args) => ({ components: { TreeView }, setup() { return { args }; }, template: `<span> <tree-view v-bind="args" :filter-method="filterMethod" ref="treeViewRef"></tree-view> <section style="margin: 10px 0"> <input v-model="filterText" type='text' id="filter" placeholder="Filter by label text" style="margin-right: 4px" /><button @click="applyFilter">Apply Filter</button> </section> <section class="checked-nodes"> <button type="button" style="margin-top: 1rem" @click="refreshCheckedTvList">What's been checked (checkboxes and radiobuttons)?</button> <ul id="checkedList"> <li v-for="checkedNode in checkedTvNodes">{{ checkedNode.id }}</li> </ul> </section> </span>`, data() { return { checkedTvNodes: [], filterText: "", filterMethod: null } }, methods: { applyFilter() { if (this.filterText === "") { this.filterMethod = null; } else { const lowercaseFilter = this.filterText.toLowerCase(); this.filterMethod = (n) => n.label.toLowerCase().includes(lowercaseFilter); } }, refreshCheckedTvList() { this.checkedTvNodes = [...this.$refs.treeViewRef.getCheckedCheckboxes(), ...this.$refs.treeViewRef.getCheckedRadioButtons()]; } } }); export const Filtering = Template.bind({}); Filtering.args = { initialModel: treeViewData, }; const docsSourceCode = ` <template> <tree-view :initial-model="tvModel"></tree-view> </template> <script setup> import { ref } from "vue"; import { TreeView } from "@grapoza/vue-tree"; import treeViewData from "../data/basicTreeViewData"; const tvModel = ref(treeViewData); </script>`; Filtering.parameters = { docs: { source: { code: docsSourceCode, language: "html", type: "auto", }, }, };<file_sep>import { useFilter } from "./filter/filter.js"; /** * Composable dealing with methods for traversing tree nodes * @param {Ref<TreeViewNode>} treeModel A Ref to the model from which traversals should start * @returns {Object} Methods for traversing tree nodes */ export function useTreeViewTraversal(treeModel) { const { getFilteredChildren, getFilteredNodes } = useFilter(); /** * Traverses the tree breadth-first and performs a callback action against each node. * @param {Function} nodeActionCallback The action to call against each node, taking that node as a parameter */ function breadthFirstTraverse(nodeActionCallback) { traverse(nodeActionCallback, false); } /** * Traverses the tree depth-first and performs a callback action against each node. * @param {Function} nodeActionCallback The action to call against each node, taking that node as a parameter */ function depthFirstTraverse(nodeActionCallback) { traverse(nodeActionCallback, true); } /** * Traverses the tree in the order specified and performs a callback action against each node. * @param {Function} nodeActionCallback The action to call against each node, taking that node as a parameter * @param {Boolean} depthFirst True to search depth-first, false for breadth-first. */ function traverse(nodeActionCallback, depthFirst) { const filteredNodes = getFilteredNodes(treeModel); if (filteredNodes.length === 0) { return; } let nodeQueue = filteredNodes.slice(); let continueCallbacks = true; while (nodeQueue.length > 0 && continueCallbacks !== false) { const current = nodeQueue.shift(); // Push children to the front (depth-first) or the back (breadth-first) const children = getFilteredChildren(current); nodeQueue = depthFirst ? children.concat(nodeQueue) : nodeQueue.concat(children); // Use a return value of false to halt calling the callback on further nodes. continueCallbacks = nodeActionCallback(current); } } return { breadthFirstTraverse, depthFirstTraverse, }; }<file_sep>import { unref } from 'vue'; import { useChildren } from '../children/children.js'; /** * Composable dealing with filter handling on an arbitrary node. * @returns {Object} Methods to deal with filtering of arbitrary nodes */ export function useFilter() { const { getChildren } = useChildren(); function getFilteredChildren(targetNodeModel) { return getFilteredNodes(getChildren(targetNodeModel)); } function getFilteredNodes(targetNodeModels) { return unref(targetNodeModels).filter(c => c.treeNodeSpec?._?.state?.matchesFilter || c.treeNodeSpec?._?.state?.subnodeMatchesFilter); } return { getFilteredChildren, getFilteredNodes, }; }<file_sep>import { expect, describe, it, beforeEach } from 'vitest'; import { ref } from 'vue'; import { useTreeViewConvenienceMethods } from './treeViewConvenienceMethods.js'; import { generateNodes } from '../../tests/data/node-generator.js'; import SelectionMode from '../enums/selectionMode'; describe('treeViewConvenienceMethods.js', () => { describe('when getMatching() is called', () => { let getMatching; describe('and there are nodes present', () => { beforeEach(() => { ({ getMatching } = useTreeViewConvenienceMethods(ref(generateNodes(['es', 'ES', ['es', 'eS']])), ref({}), ref(SelectionMode.Multiple))); }); it('should return nodes matched by the function argument', () => { let nodes = getMatching((nodeModel) => nodeModel.treeNodeSpec.expandable && nodeModel.treeNodeSpec.state.expanded && nodeModel.treeNodeSpec.selectable && nodeModel.treeNodeSpec.state.selected); expect(nodes.length).to.equal(1); }); }); describe('and there are no nodes present', () => { beforeEach(() => { ({ getMatching } = useTreeViewConvenienceMethods(ref([]), ref({}), ref(SelectionMode.Single))); }); it('should return an empty array', () => { let nodes = getMatching(() => true); expect(nodes.length).to.equal(0); }); }); describe('and maxMatches argument is provided (> 0)', () => { beforeEach(() => { ({ getMatching } = useTreeViewConvenienceMethods(ref(generateNodes(['es', 'ES', ['es', 'eS']])), ref({}), ref(SelectionMode.Multiple))); }); it('should return up to maxMatches matches', () => { let nodes = getMatching(() => true, 2); expect(nodes.length).to.equal(2); }); }); }); describe('when getCheckedCheckboxes() is called', () => { let getCheckedCheckboxes; beforeEach(() => { ({ getCheckedCheckboxes } = useTreeViewConvenienceMethods(ref(generateNodes(['ecs', 'eCs', ['eCs', 'ecs']])), ref({}), ref(SelectionMode.Single))); }); it('should return checked checkbox nodes', () => { let nodes = getCheckedCheckboxes(); expect(nodes.length).to.equal(2); }); }); describe('when getCheckedRadioButtons() is called', () => { let getCheckedRadioButtons; beforeEach(() => { let nodes = generateNodes(['ers', 'eRs', ['eRs', 'ers']]); let radioGroupValues = {}; radioGroupValues[nodes[1].treeNodeSpec.input.name] = nodes[1].treeNodeSpec.input.value; radioGroupValues[nodes[1].children[0].treeNodeSpec.input.name] = nodes[1].children[0].treeNodeSpec.input.value; ({ getCheckedRadioButtons } = useTreeViewConvenienceMethods(ref(nodes), ref(radioGroupValues), ref(SelectionMode.Single))); }); it('should return checked radiobutton nodes', () => { let nodes = getCheckedRadioButtons(); expect(nodes.length).to.equal(2); }); }); describe('when findById() is called', () => { let findById; let targetNode; beforeEach(() => { let nodes = generateNodes(['es', 'eS', ['es', 'eS']]); ({ findById } = useTreeViewConvenienceMethods(ref(nodes), ref({}), ref(SelectionMode.Single))); targetNode = nodes[1].children[0]; }); it('should return the node with the given ID', () => { let node = findById(targetNode.id); expect(node.id).to.equal(targetNode.id); }); }); describe('when getSelected() is called', () => { let getSelected; describe('and selection mode is not None', () => { beforeEach(() => { ({ getSelected } = useTreeViewConvenienceMethods(ref(generateNodes(['es', 'eS', ['es', 'eS']])), ref({}), ref(SelectionMode.Multiple))); }); it('should return selected nodes', () => { let nodes = getSelected(); expect(nodes.length).to.equal(2); }); }); describe('and selection mode is None', () => { beforeEach(() => { ({ getSelected } = useTreeViewConvenienceMethods(ref(generateNodes(['es', 'eS', ['es', 'eS']])), ref({}), ref(SelectionMode.None))); }); it('should return an empty array of nodes', () => { let nodes = getSelected(); expect(nodes.length).to.equal(0); }); }); }); describe('when removeById() is called', () => { let nodes; let removeById; beforeEach(() => { nodes = generateNodes(['es', 'es', ['es', 'es']]); ({ removeById } = useTreeViewConvenienceMethods(ref(nodes), ref({}), ref(SelectionMode.Single))); }); it('should remove the node with the given ID', () => { removeById('n1n0'); expect(nodes[1].children.length).to.equal(1); }); it('should return the removed node', () => { let node = removeById('n1n0'); expect(node.id).to.equal('n1n0'); }); describe('and the node is not found', () => { it('should return null', () => { expect(removeById('notfound')).to.be.null; }); }); }); }); <file_sep>import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { ref } from 'vue'; import { useTreeViewNodeFocus } from './treeViewNodeFocus.js'; import { generateNodes } from 'tests/data/node-generator.js'; import TreeEvent from '../../enums/event.js'; const isMountedRef = ref(true); describe('treeViewNodeFocus.js', () => { let nodeElement = null; let emit; beforeEach(() => { // Create an element to use as the node element nodeElement = document.createElement('input') document.body.appendChild(nodeElement); emit = vi.fn(); }); afterEach(() => { document.body.removeChild(nodeElement); }); describe('when handling a focus change', () => { let nodes; beforeEach(async () => { // Calling the use sets up the watcher nodes = generateNodes(['ecsf', 'eCs']); let nodeRef = ref(nodes[1]); useTreeViewNodeFocus(nodeRef, ref(nodeElement), emit, isMountedRef); nodeRef.value.treeNodeSpec.focusable = true; }); it('should emit the treeNodeAriaFocusableChange event', () => { expect(emit).toHaveBeenCalledWith(TreeEvent.FocusableChange, nodes[1]); }); it('should focus the node element', () => { expect(nodeElement).to.equal(document.activeElement); }); }); describe('when focusing a node', () => { it('should set the node as focused', () => { const node = generateNodes(['es'])[0]; const { focusNode } = useTreeViewNodeFocus(ref(node), ref(nodeElement), emit, isMountedRef); focusNode(); expect(node.treeNodeSpec.focusable).to.be.true; }); }); describe('when unfocusing a node', () => { it('should set the node as unfocused', () => { const node = generateNodes(['esf'])[0]; const { unfocusNode } = useTreeViewNodeFocus(ref(node), ref(nodeElement), emit, isMountedRef); unfocusNode(); expect(node.treeNodeSpec.focusable).to.be.false; }); }); describe('when checking if a node is focused', () => { describe('and the node is focusable', () => { it('should return true', () => { const node = generateNodes(['esf'])[0]; const { isFocusedNode } = useTreeViewNodeFocus(ref(node), ref(nodeElement), emit, isMountedRef); expect(isFocusedNode()).to.be.true; }); }); describe('and the node is not focusable', () => { it('should return false', () => { const node = generateNodes(['es'])[0]; const { isFocusedNode } = useTreeViewNodeFocus(ref(node), ref(nodeElement), emit, isMountedRef); expect(isFocusedNode()).to.be.false; }); }); }); describe('when focusing the first child of the node', () => { it('should focus the first node', () => { const node = generateNodes(['Es', ['es', 'esf']])[0]; const { focusFirstChild } = useTreeViewNodeFocus(ref(node), ref(nodeElement), emit, isMountedRef); focusFirstChild(); expect(node.children[0].treeNodeSpec.focusable).to.be.true; }); }); describe('when focusing the last child of the node', () => { it('should focus the last visible child node', () => { const node = generateNodes(['Es', ['esf', 'es']])[0]; const { focusLastChild } = useTreeViewNodeFocus(ref(node), ref(nodeElement), emit, isMountedRef); focusLastChild(); expect(node.children[1].treeNodeSpec.focusable).to.be.true; }); it('should ignore non-expanded child nodes', () => { const node = generateNodes(['Es', ['ecsf', 'eCs', 'ecs', ['ecs']]])[0]; const { focusLastChild } = useTreeViewNodeFocus(ref(node), ref(nodeElement), emit, isMountedRef); focusLastChild(); expect(node.children[2].treeNodeSpec.focusable).to.be.true; }); it('should focus the deepest last node', () => { const node = generateNodes(['Es', ['ecsf', 'eCs', 'Ecs', ['ecs']]])[0]; const { focusLastChild } = useTreeViewNodeFocus(ref(node), ref(nodeElement), emit, isMountedRef); focusLastChild(); expect(node.children[2].children[0].treeNodeSpec.focusable).to.be.true; }); }); describe('when focusing the next node', () => { describe('and the last child node is focused', () => { it('should not change focusableness', () => { const node = generateNodes(['Es', ['ecs', 'eCsf']])[0]; const { focusNextNode } = useTreeViewNodeFocus(ref(node), ref(nodeElement), emit, isMountedRef); focusNextNode(node.children[1]); expect(node.children[1].treeNodeSpec.focusable).to.be.true; }); }); describe('and the current child node does not have any expanded children', () => { it('should set the next sibling node as focusable', () => { const node = generateNodes(['Es', ['ecsf', ['ecs', 'ecs'], 'ecs']])[0]; const { focusNextNode } = useTreeViewNodeFocus(ref(node), ref(nodeElement), emit, isMountedRef); focusNextNode(node.children[0]); expect(node.children[1].treeNodeSpec.focusable).to.be.true; }); }); describe('and the current child node has expanded children', () => { let node; beforeEach(() => { node = generateNodes(['Es', ['Ecsf', ['ecs', 'ecs'], 'ecs']])[0]; }); it('should set the first expanded child node as focusable', () => { const { focusNextNode } = useTreeViewNodeFocus(ref(node), ref(nodeElement), emit, isMountedRef); focusNextNode(node.children[0]); expect(node.children[0].children[0].treeNodeSpec.focusable).to.be.true; }); describe('and the children are explicitly ignored', () => { it('sets the next sibling node as focusable', () => { const { focusNextNode } = useTreeViewNodeFocus(ref(node), ref(nodeElement), emit, isMountedRef); focusNextNode(node.children[0], true); expect(node.children[1].treeNodeSpec.focusable).to.be.true; }); }); }); }); });<file_sep>const events = Object.freeze({ // Root tree state RootNodesLoad: 'treeRootNodesLoad', // Node state Click: 'treeNodeClick', DoubleClick: 'treeNodeDblclick', CheckboxChange: 'treeNodeCheckboxChange', ChildCheckboxChange: 'treeNodeChildCheckboxChange', RadioChange: 'treeNodeRadioChange', ExpandedChange: 'treeNodeExpandedChange', ChildrenLoad: 'treeNodeChildrenLoad', SelectedChange: 'treeNodeSelectedChange', // Focus FocusableChange: 'treeNodeAriaFocusableChange', RequestFirstFocus: 'treeNodeAriaRequestFirstFocus', RequestLastFocus: 'treeNodeAriaRequestLastFocus', RequestParentFocus: 'treeNodeAriaRequestParentFocus', RequestPreviousFocus: 'treeNodeAriaRequestPreviousFocus', RequestNextFocus: 'treeNodeAriaRequestNextFocus', // Hierarchy Add: 'treeNodeAdd', Delete: 'treeNodeDelete', // Drag and Drop DragMove: 'treeNodeDragMove', Drop: 'treeNodeDrop' }); export default events;<file_sep>import { Meta } from '@storybook/addon-docs'; <Meta title="@grapoza vue-tree/Home" /> <style>{` `}</style> # @grapoza/vue-tree [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) [![Build status](https://ci.appveyor.com/api/projects/status/j8d19gt0vh16amhh/branch/master?svg=true)](https://ci.appveyor.com/project/Gregg/vue-tree/branch/master) [![Source](https://img.shields.io/badge/Source-View_on_GithHub-blue?svg=true)](https://github.com/grapoza/vue-tree) vue-tree is a Vue component that implements a Tree View control. Its aim is to provide common tree options in a way that is easy to use and easy to customize. > ⚠️**From version 4.0.0 this component only works with Vue 3 and up. For Vue 2 support, use [version 3.x](https://grapoza.github.io/vue-tree/3.0.4/).** Features include: - Expandable nodes - Checkboxes - Radio buttons - Node selection - Addition and removal of nodes - Slots for node content - Skinning - Asynchronous loading of nodes - Follows ARIA guidelines for treeview accessibility - Drag and drop (single nodes, works between trees) - Filtering For future plans, see the project's [Issues](https://github.com/grapoza/vue-tree/issues) page. ## Installation Install the component with your favorite package manager: ```shell yarn add @grapoza/vue-tree ``` or ```shell npm install --save @grapoza/vue-tree ``` ## Usage If you're using it in a .vue file: ```html <template> <tree-view id="my-tree" :initial-model="dataModel"></tree-view> </template> // Options API <script> import { TreeView } from "@grapoza/vue-tree" export default { components: { TreeView }, data() { return { dataModel: [ { id: "numberOrString", label: "Root Node", children: [ {id: 1, label: "Child Node"}, {id: "node2", label: "Second Child"} ] } ] } } } </script> // Composition API <script setup> import { TreeView } from "@grapoza/vue-tree" const dataModel = ref([ { id: "numberOrString", label: "Root Node", children: [ {id: 1, label: "Child Node"}, {id: "node2", label: "Second Child"} ] } ]) </script> ``` Or, import it into your application: ```javascript import { TreeView } from "@grapoza/vue-tree" Vue.use(TreeView) ``` Then add the component: ```html <tree-view id="my-tree" :initial-model="dataModel"></tree-view> ``` ```javascript export default { data() { return { dataModel: [ { id: "numberOrString", label: "Root Node", children: [ {id: 1, label: "Child Node"}, {id: "node2", label: "Second Child"} ] } ] } } } ``` ## Demos To see it in action, try out the [demos](/docs/examples-treeview--basic#examples). ## Tree Props | Prop | Type | Description | Default value | Required | |:------------------|:---------|:---------------------------------------------------------------------------------------------------|:----------------------------------|:---------| | initialModel | Array | The data model containing [model data](#model-data) | `[]` | | | customAriaKeyMap | Object | An object, the properties of which are arrays to keyCodes for various actions | See [Aria](#setting-key-bindings) | | | loadNodesAsync | Function | A function that is called on mount to asynchronously load [model data](#model-data) | `null` | | | modelDefaults | Object | An object containing defaults for all nodes that do not specify the given properties | `{}` | | | selectionMode | String | How selection should operate (see [Selection Mode](#selection-mode)) | `null` (cannot select nodes) | | | skinClass | String | A class name to apply to the tree that specifies a skin to use (see [Skins](#skins)) | `"grtv-default-skin"` | | | filterMethod | Function | A boolean function against which nodes are evaluated to see if they should be included in the tree | `null` (no filtering) | | ## Selection Mode The `selectionMode` property defines how nodes should be selected within the tree view. Allowed values are `null`, `single`, `selectionFollowsFocus`, and `multiple`. Only nodes with the `selectable` model property set to `true` can be selected. - If `null` (the default) then selection does not occur. - If `single` then one node is selected at a time when the user clicks the node or using the selection keyboard binding (`Enter` by default). - If `selectionFollowsFocus` then selection follows the focusable node within the tree view. - if `multiple` then multiple nodes can be selected when the user clicks each node or using the selection keyboard binding on each node. When clicking on a node, it is only selected if the click target was not interactive (_e.g._, clicking a checkbox or expander won't select the node, but clicking a label will). ## Model Data Model data can be loaded either synchronously through the `initialModel` property or asynchronously through the `loadNodesAsync` property. If both are specified then the data from `initialModel` is overwritten when the `loadNodesAsync` function returns data. The data passed to the tree view's `initialModel` prop or returned from `loadNodesAsync` should be an array of nodes, where each node should have: * Required: A property with a value that will be used as the node's ID (by default the node looks for a property named `id`) * Required: A property with a value that will be used as the node's label (by default the node looks for a property named `label`) * Optional: A property containing any subnodes (by default the node looks for a property named `children`) * Optional: A `treeNodeSpec` property that contains any data about the node's capabilities and its initial state * Optional: Any other data you want on your node The `treeNodeSpec` of the objects in the data model passed to the tree view's `initialModel` property will be updated by the tree view nodes themselves on creation to include missing properties. ```javascript { id: "node0", label: "A checkbox node", children: [], treeNodeSpec: { title: "This will be the value of the node text/label's 'title' attribute.", expandable: true, selectable: false, focusable: true, input: { type: 'checkbox' }, state: { expanded: true, selected: false, input: { value: false, disabled: false } } } }, { otherIdProp: "node1", textProp: "A radio button node", subThings: [], extraIrrelevantData: "February", treeNodeSpec: { idProperty: "otherIdProp", // Customize what model props are checked for the id, label, and children labelProperty: "textProp", childrenProperty: "subThings", expandable: true, selectable: false, input: { type: 'radio', name: 'rbGroup1', // Used as the name attribute for the radio button value: 'thisValue', // Used as the value attribute for the radio button isInitialRadioGroupValue: true // Indicates this should be the initially selected value for the group }, state: { expanded: true, selected: false // No input.value here; to let complex radio button groupings work, state value is // bound to an internal tree-level property. input.disabled, however, is valid here for radio buttons. }, addChildCallback: () => Promise.resolve({ id: '1', label: 'label' }) } } ``` The properties below can be specified for each node. Note that `id`, `label`, and `children` are the default properties nodes look for to get data, but the names of the properties can be overridden using the `treeNodeSpec`. | Prop | Type | Description | Default value | Required | |:---------------------|:----------------|:---------------------------------------------------------------------------|:-----------------------------------|:---------| | id | Number/String | An ID that uniquely identifies this node within the tree | - | Yes | | label | String | The text to show in the tree view | - | Yes | | children | Array<Object\> | The child nodes of this node | `[]` | | | treeNodeSpec | Object | The object containing data about the node's capabilities and initial state | See next table | | The `treeNodeSpec` property contains any data about the node's capabilities and its initial state. This keeps the tree-specific data separate from the data of the model itself. This makes it more convenient to drop data into the tree view as-is, potentially with a `modelDefaults` specified on the tree view to define common values used in the `treeNodeSpec` of every node. | Prop | Type | Description | Default value | Required | |:---------------------|:---------|:------------------------------------------------------------------------------------------|:-----------------------------------|:---------| | idProperty | String | The name of the property with a value that will be used as the node's ID | `id` | | | labelProperty | String | The name of the property with a value that will be used as the node's label | `label` | | | childrenProperty | String | The name of the property with a value that will be used as the node's subnodes | `children` | | | title | String | The text of the node's text or label's title attribute | `null` | | | expandable | Boolean | True to show a toggle for expanding nodes' subnode lists | `true` | | | selectable | Boolean | True to allow the node to be selected | `false` | | | deletable | Boolean | True to allow the node to be deleted | `false` | | | focusable | Boolean | True to make the node the focus when the tree view is focused | See [Aria](#focusable) for details | | | draggable | Boolean | True to make this node draggable | `false` | | | allowDrop | Boolean | True to allow dropping TreeViewNode data onto this node | `false` | | | dataTransferEffectAllowed | String | One of the allowed [effectAllowed](https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer/effectAllowed) values (`copy`, `move`, `copyMove`, or `none`) | `copyMove` | | | expanderTitle | String | The text to use as the title for the expander button | `null` | | | addChildTitle | String | The text to use as the title for the Add Child button | `null` | | | deleteTitle | String | The text to use as the title for the Delete button | `null` | | | input | Object | Contains data specific to the node's `input` element | `null` | | | input.type | String | The type of input; valid values are `checkbox` or `radio` | - | Yes* | | input.name | String | The name attribute of the input; used with `radio` type | `'unspecifiedRadioName'` | | | input.value | String | The value attribute of the input; used with `radio` type | `label`'s value** | | | input.isInitialRadioGroupValue | Boolean | Indicates this should be the initially selected value for the group | `null` | | | state | Object | Contains the current state of the node | - | | | state.expanded | Boolean | True if this node's subnode list is expanded | `false` | | | state.selected | Boolean | True if the node is selected | `false` | | | state.input | Object | Contains any state related to the input field | `{}` for checkbox, otherwise - | | | state.input.value | Boolean | Contains the value of the input | `false` for checkbox, otherwise - | | | state.input.disabled | Boolean | True if the node's input field is disabled | `false` | | | customizations | Object | A [customizations](#customizing-the-tree-view) object | `{}` | | | addChildCallback | Function | An async function that resolves to a new node model (called by the add button). The function can take one argument, the model of the parent node. It should return the model of the new child node. | `null` | | | loadChildrenAsync | Function | An async function that resolves to a node's children (called when the parent is expanded). The function can take one argument, the model of the parent node. It should return the models of the children nodes. | `null` | | | deleteNodeCallback | Function | An async function that resolves to a boolean (called by the delete button). The function can take one argument, the model to delete. It should return a boolean indicating whether to delete the node. | `null` | | \* If `input.type` is not supplied, `input` is forced to `null`. \*\* If `input.value` is not supplied, it defaults to the node's label value replaced with the regular expression `/[\s&<>"'\/]/g, ''` ## Default Data If specified, the `modelDefaults` property of the TreeView will be merged with node model's `treeNodeSpec` data such that any data not explicitly specified for the node will be set to the value from `modelDefaults`. This is useful for situations where all (or most) nodes will use the same values. For instance, in a tree view that is all enabled, collapsed, unchecked checkboxes the user could use a `modelDefaults` of ```javascript { expandable: true, selectable: true, input: { type: 'checkbox', }, state: { expanded: false, selected: false, input: { value: false, disabled: false } } } ``` ## Public Methods | Method | Description | Parameters | Returns | |:-----------------------|:--------------------------------------------|:-----------|:------------------------------------------------------------| | getCheckedCheckboxes | Gets models for checked checkbox nodes | | An `Array<Object>` of models for checked checkbox nodes | | getCheckedRadioButtons | Gets models for checked radio nodes | | An `Array<Object>` of models for checked radio button nodes | | getSelected | Gets models for selected nodes | | An `Array<Object>` of models for selected nodes | | getMatching | Gets models for nodes that match a function | `matcherFunction`: A function that takes a node model and returns a boolean indicating whether that node should be returned. <br/> `maxMatches` The maximum number of matches to return. | An `Array<Object>` of models for matched nodes | ## Events | Event | Description | Handler Parameters | |:----------------------------|:---------------------------------------------------------------|:-----------------------------------------------------------------------| | treeNodeAdd | Emitted when a node is added | `target` The model of the target (child) node <br/> `parent` The model of the parent node | | treeNodeClick | Emitted when a node is clicked | `target` The model of the target node <br/> `event` The original event | | treeNodeDblclick | Emitted when a node is double clicked | `target` The model of the target node <br/> `event` The original event | | treeNodeDelete | Emitted when a node is deleted | `target` The model of the target node | | treeNodeCheckboxChange | Emitted when a node's checkbox emits a change event | `target` The model of the target node <br/> `event` The original event | | treeNodeChildCheckboxChange | Emitted when a child node's checkbox emits a change event | `target` The model of the target node (the parent of the changed node) <br/> `child` The model of changed node <br/> `event` The original event | | treeNodeRadioChange | Emitted when a node's radio button emits a change event | `target` The model of the target node <br/> `event` The original event | | treeNodeExpandedChange | Emitted when a node is expanded or collapsed | `target` The model of the target node | | treeNodeSelectedChange | Emitted when a node is selected or deselected | `target` The model of the target node | | treeNodeChildrenLoad | Emitted when a node's children are done loading asynchronously | `target` The model of the target node | | treeRootNodesLoad | Emitted when the root nodes are done loading asynchronously | | ## CSS Classes The display of the tree view can be customized via CSS using the following classes. Class names are organized in a hierarchy, so a containing node's class is the prefix of its child classes. | Class | Affects | |:---------------------------------------|:---------------------------------------------------------------------------------| | `grtv` | The top-level tree view list | | `grtv-wrapper` | The wrapper div around the list of root nodes and the loading placeholder | | `grtv-loading` | The placeholder shown when root nodes are loading asynchronously | | `grtvn` | A single node's list item | | `grtvn-self-selected` | A selected node | | `grtvn-self` | The div containing the current node's UI | | `grtvn-self-expander` | The button used to expand the children | | `grtvn-self-expanded` | Applied to the expander button when the node is expanded | | `grtvn-self-expanded-indicator` | The `<i>` element containing the expansion indicator | | `grtvn-self-spacer` | An empty spacer to replace fixed-width elements, _e.g._ the expander or checkbox | | `grtvn-self-label` | The label for the checkbox of checkable nodes | | `grtvn-self-input` | Any type of input field within the tree node | | `grtvn-self-checkbox` | The checkbox | | `grtvn-self-radio` | The radio button | | `grtvn-self-text` | The text for a non-input node | | `grtvn-self-action` | The action buttons (e.g., add child or delete) | | `grtvn-self-add-child-icon` | The `<i>` element containing the add child icon | | `grtvn-self-delete-icon` | The `<i>` element containing the delete icon | | `grtvn-self-drop-target` | A node has another node dragged over it and can accept drops | | `grtvn-self-child-drop-target` | A node has another node dragged over its child drop target | | `grtvn-self-sibling-drop-target` | Either the previous or next sibling node drop target | | `grtvn-self-sibling-drop-target-hover` | A node has another node dragged over one of the sibling drop targets | | `grtvn-self-prev-target` | The previous sibling node drop target | | `grtvn-self-next-target` | The next sibling node drop target | | `grtvn-children-wrapper` | The wrapper div around the list of child nodes and the loading placeholder | | `grtvn-children` | The list of child nodes | | `grtvn-loading` | The placeholder shown when child nodes are loading asynchronously | | `grtvn-dragging` | The node is dragged as part of a drag and drop operation | ## Customizing the Tree View ### Customizations Property It's often helpful to be able to make adjustments to the markup or styles for the tree. You can provide an object to the `modelDefaults.customizations` property of the tree to set a customization affecting all nodes, or to the `treeNodeSpec.customizations` property of a single node. Node-specific customizations will override `modelDefault` customizations. A customizations object may have the following properties: | Prop | Type | Description | |:------------------------------------------|:-------|:---------------------------------------------------------------------------------------------| | classes | Object | Properties are classes to add for various parts of a node | | classes.treeViewNode | String | Classes to add to a node's list item | | classes.treeViewNodeSelf | String | Classes to add to the div containing the current node's UI | | classes.treeViewNodeSelfSelected | String | Classes to add to the `grtvn-self` div if the node is selected | | classes.treeViewNodeSelfExpander | String | Classes to add to the button used to expand the children | | classes.treeViewNodeSelfExpanded | String | Classes to add to the expander button when the node is expanded | | classes.treeViewNodeSelfExpandedIndicator | String | Classes to add to the `<i>` element containing the expansion indicator | | classes.treeViewNodeSelfSpacer | String | Classes to add to the fixed-width spacer | | classes.treeViewNodeSelfLabel | String | Classes to add to the label for the checkbox of checkable nodes | | classes.treeViewNodeSelfInput | String | Classes to add to an input field | | classes.treeViewNodeSelfCheckbox | String | Classes to add to the checkbox | | classes.treeViewNodeSelfRadio | String | Classes to add to the radio button | | classes.treeViewNodeSelfText | String | Classes to add to the text for a non-input node | | classes.treeViewNodeSelfAction | String | Classes to add to the action buttons | | classes.treeViewNodeSelfAddChild | String | Classes to add to the add child buttons | | classes.treeViewNodeSelfAddChildIcon | String | Classes to add to the `<i>` element containing the add child icon | | classes.treeViewNodeSelfDelete | String | Classes to add to the delete button | | classes.treeViewNodeSelfDeleteIcon | String | Classes to add to the `<i>` element containing the delete icon | | classes.treeViewNodeChildrenWrapper | String | Classes to add to the wrapper div around the list of child nodes and the loading placeholder | | classes.treeViewNodeChildren | String | Classes to add to the list of child nodes | | classes.treeViewNodeLoading | String | Classes to add to the node children loading placeholder | ### Skins If adding classes isn't enough, the entire default styles of the TreeView can be overridden using the `skinClass` property of the TreeView. When this property is set, the TreeView's default class of `grtv-default-skin` is replaced with your own class name, causing all of the built-in style selectors to not match the tree. Instead, you can create your own stylesheet or modify a copy of the default styles to achieve complete control over the tree styling. ### Slots Sometimes the entire content of a node (_e.g._, the checkbox or text) needs customization beyond what is available through classes. In this case, some slots are available in the TreeView to allow this customization. | Slot Name | Description | Props | |:-------------|:------------------------------------------------------------|:---------------------------------------------------------------------------------------------------| | loading-root | Replaces the span used when loading children asynchronously | | | text | Replaces the span used for non-input content | model - The TreeViewNode's model | | | | customClasses - Any custom classes specified in `treeNodeSpec.customizations` | | checkbox | Replaces the label and content used for checkboxes | model - The TreeViewNode's model | | | | customClasses - Any custom classes specified in `treeNodeSpec.customizations` | | | | inputId - The ID for the input (as generated by the TreeViewNode) | | | | checkboxChangeHandler - The handler for checkbox change events. You should fire this on `change`. | | radio | Replaces the label and content used for radio buttons | model - The TreeViewNode's model | | | | customClasses - Any custom classes specified in `treeNodeSpec.customizations` | | | | inputId - The ID for the input (as generated by the TreeViewNode) | | | | radioChangeHandler - The handler for radio button change events. You should fire this on `change`. | | loading | Replaces the span used when loading children asynchronously | model - The TreeViewNode's model | | | | customClasses - Any custom classes specified in `treeNodeSpec.customizations` | Example usage: ```html <tree-view id="customtree" :initial-model="model"> <template #text="{ model, customClasses }"> <!-- The TreeViewNode's model is available, and built-in classes and overrides are available --> <em :title="model.treeNodeSpec.title" class="grtvn-self-text" :class="customClasses.treeViewNodeSelfText"> {{ model[model.treeNodeSpec.labelProperty] }} </em> </template> <template #checkbox="{ model, customClasses, inputId, checkboxChangeHandler }"> <label :for="inputId" :title="model.treeNodeSpec.title" class="grtvn-self-label" :class="customClasses.treeViewNodeSelfLabel"> <!-- The generated inputId for the node is available --> <input :id="inputId" class="my-awesome-checkbox-class" type="checkbox" :disabled="model.treeNodeSpec.state.input.disabled" v-model="model.treeNodeSpec.state.input.value" @change="checkboxChangeHandler" /> <!-- The TreeViewNode change handler is available --> <em>{{ "Slotted Content for " + model[model.treeNodeSpec.labelProperty] }}</em> </label> </template> </tree-view> ``` ## Asynchronous Loading Child nodes can be loaded asynchronously by providing a method to the `treeNodeSpec.loadChildrenAsync` property of the model. The method will be called when the node is expanded, and the property containing the node's children will be _overwritten_ with the results of the async call. For example, the following could be used as `modelDefaults` that would have every node load children when it was expanded. ```javascript { expandable: true, loadChildrenAsync: (m) => axios.get(`/children/${m.id}`) } ``` The method may accept one argument, which will be the model of the node that has been expanded. It should resolve to an array of child node models. The load method is called once, and after that the children are part of the model and are not reloaded. ## Drag and Drop A user can drag and drop an individual TreeViewNode. A drag only affects the node where the dragging starts, and has nothing to do with any node selection within the tree. To make a node draggable, the node's `treeNodeSpec.draggable` must be `true`. To make a node accept drops, the node's `treeNodeSpec.allowDrop` must be `true`. Both Move and Copy operations are supported. To copy in most browsers hold down the `Ctrl` key while dragging. When dropping a node on another node, there are three areas of the target node where a drop can occur. If dropped at the top of the target node in the shaded area then the node will be inserted before the target. If dropped at the bottom of the target node in the shaded area then the node will be inserted after the target. If dropped directly on the of the target node then the node will be inserted as a child of the target. The drop can occur on a node in the same tree or in a different tree as long as the receiving node allows drops. The drop can also occur anywhere that allows dropping data with the `application/json` or `text/plain` MIME types (_e.g._, a simple text input field or a text editor). When copying a node the newly created node will have its own unique identifier, will not be the currently focusable node even if the source node was the focusable node. When moving a node within the same tree, the actual node is moved within the tree data. If the node is copied within the same tree, any function members of the node data (_e.g._, the addChildCallback) are copied. When a node is moved or copied to a different tree, the node data that passes between trees does not contain any of the functions from the original node data. ## Aria ARIA Accessibility recommendations have been implemented at a basic level. This means keyboard navigation follows ARIA recommendations, but the component has not been tested with a screen reader and, since many screen readers exhibit different behaviors for tree view controls anyway, it would be expected to fail articulation checks in many cases. Additionally, some recommended keyboard controls are not implemented (e.g., Expand All Nodes, Type-ahead Focusing). When using the component, there are only a couple of things you need to know. ### Setting Key Bindings The keys used to navigate the tree view can be customized using the `customAriaKeyMap` prop of the TreeView component. The value of the prop is an object, with each attribute named for a type of action and its value as an Array of integer key codes that trigger that action. | Attribute | Description | Default value | |:--------------------|:-------------------------------------------------------------------------------------------------------|:-------------------------| | activateItem | Triggers the default action for input nodes (generally `click`) | `[32]` (Space) | | selectItem | Selects the currently focused item | `[13]` (Enter) | | focusLastItem | Sets focus to the last visible item in the tree | `[35]` (End) | | focusFirstItem | Sets focus to the first visible item in the tree | `[36]` (Home) | | collapseFocusedItem | Collapses the currently focused item, if expanded; otherwise focuses the parent node if one exists | `[37]` (Left) | | expandFocusedItem | Expands the currently focused item, if collapsed; otherwise focuses the first child node if one exists | `[39]` (Right) | | focusPreviousItem | Focuses the previous visible node* in the tree if one exists. | `[38]` (Up) | | focusNextItem | Focuses the next visible node** in the tree if one exists. | `[40]` (Down) | | insertItem | Fires the callback to add a new node if the callback exists | `[45]` (Insert) | | deleteItem | Deletes the current node, if deletable | `[46]` (Delete) | \* The previous visible node is a)the focused node's previous sibling's last child if visible, b)the previous sibling if it has no children or is collapsed, or c)the parent node. \*\* The next visible node is a)the focused node's first child if one exists and the focused node is expanded, b)the focused node's next sibling if one exists, or c)the focused node's parent's next sibling if one exists. ### Focusable The tree view uses a roaming tab index to maintain focusability in the tree. A node model can specify a `treeNodeSpec.focusable` property of `true` in order for that node to be used as the initial target of keyboard focus within the tree view. If multiple node models specify this then only the first will have `treeNodeSpec.focusable` set to `true` once the tree view is intialized. If no models have it specified then the first selected node in the tree view is given a `treeNodeSpec.focusable` of `true`. If there are no selected nodes then the first node in the tree view is given a `treeNodeSpec.focusable` of `true`. ### More about ARIA Tree Views [WAI-ARIA Authoring Best Practices, Tree View](https://www.w3.org/TR/wai-aria-practices-1.1/#TreeView) ## Filtering If a `filterMethod` property is provided to the treeView then each node will get evaulated against that method, any node for which the function returns `true` or for which a subnode returns `true` will show in the tree view and get included in things like keyboard navigation or focusing. The method takes one parameter, which is the node. For example, to only show nodes with a description including "steve" you could use the method: `(node) => node.label.toLowerCase().includes('steve')`<file_sep>import { dropEffect as DropEffect, targetZone as TargetZone } from '../../enums/dragDrop.js'; import { useObjectMethods } from '../objectMethods.js'; import { useIdGeneration } from '../idGeneration.js' import { useFocus } from '../focus/focus.js'; const { resolveNodeIdConflicts } = useIdGeneration(); const { cheapCopyObject } = useObjectMethods(); const { unfocus } = useFocus(); /** * Composable dealing with drag-and-drop handling at the top level of the tree view. * @param {Ref<TreeViewNode[]>} treeModel A Ref to the top level model of the tree * @param {Ref<string>} uniqueId A Ref to the unique ID for the tree. * @param {Function} findById A function to find a node by ID * @param {Function} removeById A function to remove a node by ID * @returns {Object} Methods to deal with tree view level drag-and-drop */ export function useTreeViewDragAndDrop(treeModel, uniqueId, findById, removeById) { /** * Removes the given node from this node's children * after a drag-and-drop move operation between trees. * @param {Object} node The data for the moved node */ function dragMoveNode(node) { const targetIndex = treeModel.value.indexOf(node); if (targetIndex > -1) { treeModel.value.splice(targetIndex, 1); } } /** * Handles a TreeViewNode getting dropped into this tree. * @param {Object} eventData The data about a drop event */ function drop(eventData) { let node = eventData.droppedModel; if (eventData.isSameTree) { // When dropping within the same tree, move/copy the actual node data. if (eventData.dropEffect === DropEffect.Move) { // Find and remove the actual dropped node from its current position. node = removeById(node[node.treeNodeSpec.idProperty]); // Mark the node as moved within the tree so $_grtvnDnd_onDragend // knows not to remove it. node.treeNodeSpec._.dragMoved = true; } else { let originalNode = findById(node[node.treeNodeSpec.idProperty]); node = cheapCopyObject(originalNode); resolveNodeIdConflicts(node, uniqueId.value); // Force the copied node to not be focusable, in case the dragged node was. unfocus(node); } } else { // Resolve node ID conflicts to prevent duplicate node IDs between existing // nodes in this tree and the copied node. resolveNodeIdConflicts(node, uniqueId.value); } if (node) { // If there's no sibling nodes in the event, use the top level. // Use that to find the target node's index (i.e. the drop location). let siblings = eventData.siblingNodeSet || treeModel.value; let targetIndex = siblings.indexOf(eventData.targetModel); // Add the node into the new position switch (eventData.targetZone) { case TargetZone.Before: siblings.splice(targetIndex, 0, node); break; case TargetZone.After: siblings.splice(targetIndex + 1, 0, node); break; default: siblings.push(node); break; } // Set dragged node's treeNodeSpec.dragging to false node.treeNodeSpec._.dragging = false; } } return { dragMoveNode, drop } } <file_sep>const inputType = Object.freeze({ Checkbox: 'checkbox', RadioButton: 'radio' }); export default inputType;<file_sep>export function useIdGeneration() { /** * Creates an element ID that is unique across the document * @return {string} The generated ID */ function generateUniqueId() { const possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; let newId = 'grt-'; do { newId += possible.charAt(Math.floor(Math.random() * possible.length)); } while (newId.length < 8 || document.getElementById(newId)) return newId; } /** * Checks for and resolves any ID conflicts for the given node. * @param {Object} data The tree node data to check for conflicts * @param {String} treeId The ID of the node's tree */ function resolveNodeIdConflicts(data, treeId) { const idProp = data.treeNodeSpec.idProperty; const nodeId = data[idProp]; const children = data[data.treeNodeSpec.childrenProperty]; // Copy and move need to set a new, unique Node ID. // This is a brute force test to find one that isn't in use. if (document.getElementById(`${treeId}-${nodeId}`)) { let counter = 1; while (document.getElementById(`${treeId}-${nodeId}-${counter}`)) { counter++; } data[idProp] = `${nodeId}-${counter}`; } children.forEach(child => resolveNodeIdConflicts(child, treeId)); }; return { generateUniqueId, resolveNodeIdConflicts }; }<file_sep>import { unref } from 'vue' /** * Composable dealing with expansion on an arbitrary node. * @returns Methods to deal with expansion of an arbitrary node. */ export function useExpansion() { function isExpandable(targetNodeModel) { return unref(targetNodeModel).treeNodeSpec.expandable === true; } function isExpanded(targetNodeModel) { return unref(targetNodeModel).treeNodeSpec.state.expanded === true; } return { isExpandable, isExpanded, }; }<file_sep>import TreeView from '../../components/TreeView.vue'; const Template = (args) => ({ components: { TreeView }, setup() { return { args }; }, template: '<tree-view v-bind="args" />' }); // CLASS BASED CUSTOMIZATIONS ----------------------------------------------------- export const ClassCustomization = Template.bind({}); ClassCustomization.args = { initialModel: [ { id: 'customization-class-rootNode', label: 'Root Node', children: [ { id: 'customization-class-subNode', label: 'Subnode' } ] } ], modelDefaults: { addChildCallback: addChildCallback, customizations: { classes: { treeViewNodeSelf: 'large-line', treeViewNodeSelfText: 'big-text' } } }, }; let classChildCounter = 0; async function addChildCallback(parentModel) { classChildCounter++; return Promise.resolve({ id: `customization-class-child-node${classChildCounter}`, label: `Added Child ${classChildCounter} of ${parentModel.id}`, treeNodeSpec: { deletable: true } }); } const docClassSourceCode = ` <template> <tree-view :initial-model="tvModel" :model-defaults="modelDefaults"></tree-view> </template> <script setup> import { ref } from "vue"; import { TreeView } from "@grapoza/vue-tree"; const tvModel = ref([ { id: 'customization-class-rootNode', label: 'Root Node', children: [ { id: 'customization-class-subNode', label: 'Subnode' } ] } ] ); const modelDefaults = ref({ addChildCallback: addChildCallback, customizations: { classes: { treeViewNodeSelf: 'large-line', treeViewNodeSelfText: 'big-text' } } } ); let classChildCounter = 0; async function addChildCallback(parentModel) { classChildCounter++; return Promise.resolve({ id: \`customization-class- child - node\${ classChildCounter } \`, label: \`Added Child \${ classChildCounter } of \${ parentModel.id }\`, treeNodeSpec: { deletable: true } }); } </script>`; ClassCustomization.parameters = { docs: { source: { code: docClassSourceCode, language: "html", type: "auto", }, }, }; // SKIN BASED CUSTOMIZATIONS ------------------------------------------------------ export const SkinCustomization = Template.bind({}); SkinCustomization.args = { initialModel: [ { id: 'customization-skin-rootNode', label: 'Root Node', children: [ { id: 'customization-skin-subNode', label: 'Subnode' } ] } ], modelDefaults: { addChildCallback: addSkinChildCallback, customizations: { classes: { treeViewNodeSelfExpander: 'action-button', treeViewNodeSelfExpandedIndicator: 'fas fa-chevron-right', treeViewNodeSelfAction: 'action-button', treeViewNodeSelfAddChildIcon: 'fas fa-plus-circle', treeViewNodeSelfDeleteIcon: 'fas fa-minus-circle' } } }, skinClass: 'grayscale' }; let skinChildCounter = 0; async function addSkinChildCallback(parentModel) { skinChildCounter++; return Promise.resolve({ id: `customization-skin-child-node${this.childCounter}`, label: `Added Child ${this.childCounter} of ${parentModel.id}`, treeNodeSpec: { deletable: true } }); } const docSkinSourceCode = ` <template> <tree-view :initial-model="tvModel" :model-defaults="modelDefaults" :skin-class="skinClass"></tree-view> </template> <script setup> import { ref } from "vue"; import TreeView from "../../src/components/TreeView.vue"; const tvModel = ref([ { id: 'customization-skin-rootNode', label: 'Root Node', children: [ { id: 'customization-skin-subNode', label: 'Subnode' } ] } ] ); const modelDefaults = ref({ addChildCallback: addSkinChildCallback, customizations: { classes: { treeViewNodeSelfExpander: 'action-button', treeViewNodeSelfExpandedIndicator: 'fas fa-chevron-right', treeViewNodeSelfAction: 'action-button', treeViewNodeSelfAddChildIcon: 'fas fa-plus-circle', treeViewNodeSelfDeleteIcon: 'fas fa-minus-circle' } } } ); const skinClass - ref("grayscale"); let classChildCounter = 0; async function addChildCallback(parentModel) { classChildCounter++; return Promise.resolve({ id: \`customization-class-child-node\${ this.childCounter } \`, label: \`Added Child \${ this.childCounter } of \${ parentModel.id }\`, treeNodeSpec: { deletable: true } }); } </script>`; SkinCustomization.parameters = { docs: { source: { code: docSkinSourceCode, language: "html", type: "auto", }, }, };<file_sep>import { expect, describe, it, beforeEach, afterEach, vi } from 'vitest'; import { flushPromises, mount } from '@vue/test-utils'; import TreeView from './TreeView.vue'; import TreeViewNode from './TreeViewNode.vue'; import { generateNodes } from '../../tests/data/node-generator.js'; import SelectionMode from '../enums/selectionMode'; async function createWrapper(customPropsData, customAttrs, slotsData) { let wrapper = mount(TreeView, { sync: false, props: customPropsData || { initialModel: [] }, attrs: customAttrs, slots: slotsData }); await flushPromises(); return wrapper; } describe('TreeView.vue', () => { let wrapper = null; afterEach(() => { wrapper = null; }); describe('always', () => { beforeEach(async () => { wrapper = await createWrapper(); }); it('should have a role of tree', () => { expect(wrapper.find('.grtv').element.attributes.role.value).to.equal('tree'); }); }); describe('when on an element with an ID', () => { beforeEach(async () => { wrapper = await createWrapper(null, { id: 'my-id' }); }); it('should have a uniqueId of the root element ID', () => { expect(wrapper.vm.uniqueId).to.equal(wrapper.attributes('id')); }); }); describe('when on an element without an ID', () => { beforeEach(async () => { wrapper = await createWrapper(); }); it('should have an autogenerated uniqueId prefixed with grt-', () => { expect(wrapper.vm.uniqueId).to.be.a('string').and.match(/^grt-/i); }); }); describe('when not passed a skinClass prop', () => { beforeEach(async () => { wrapper = await createWrapper(); }); it('should have a class of grtv-default-skin', () => { expect(wrapper.vm.skinClass).to.equal('grtv-default-skin'); let target = wrapper.find('.grtv-wrapper.grtv-default-skin'); expect(target.exists()).to.be.true; }); }); describe('when passed a skinClass prop', () => { beforeEach(async () => { wrapper = await createWrapper({ skinClass: "my-skin" }); }); it('should have a class of my-skin', () => { expect(wrapper.vm.skinClass).to.equal('my-skin'); let target = wrapper.find('.grtv-wrapper.my-skin'); expect(target.exists()).to.be.true; }); it('should not have a class of grtv-default-skin', () => { let target = wrapper.find('.grtv-wrapper.grtv-default-skin'); expect(target.exists()).to.be.false; }); }); describe('when selectionMode is None', () => { beforeEach(async () => { wrapper = await createWrapper({ initialModel: generateNodes(['es', 'eS', ['es', 'eS']]), selectionMode: SelectionMode.None }); }); it('should not have an aria-multiselectable attribute', () => { expect(wrapper.find('.grtv').element.attributes['aria-multiselectable']).to.be.undefined; }); }); describe('when selectionMode is `single`', () => { beforeEach(async () => { wrapper = await createWrapper({ initialModel: generateNodes(['es', 'eS', ['es', 'eS']]), selectionMode: SelectionMode.Single }); }); it('should have an aria-multiselectable attribute of false', () => { expect(wrapper.find('.grtv').element.attributes['aria-multiselectable'].value).to.equal('false'); }); // TODO Move this to the normalizer tests it('should only keep the selectable=true state for the first node with that in the initial model', () => { expect(wrapper.vm.model[1].treeNodeSpec.state.selected).to.be.true; expect(wrapper.vm.model[1].children[1].treeNodeSpec.state.selected).to.be.false; }); }); describe('when selectionMode is `selectionFollowsFocus`', () => { beforeEach(async () => { wrapper = await createWrapper({ initialModel: generateNodes(['es', 'eS', ['es', 'eS']]), selectionMode: SelectionMode.SelectionFollowsFocus }); }); it('should have an aria-multiselectable attribute of false', () => { expect(wrapper.find('.grtv').element.attributes['aria-multiselectable'].value).to.equal('false'); }); }); describe('when selectionMode is `multiple`', () => { beforeEach(async () => { wrapper = await createWrapper({ initialModel: generateNodes(['es', 'eS', ['es', 'eS']]), selectionMode: SelectionMode.Multiple }); }); it('should have an aria-multiselectable attribute of true', () => { expect(wrapper.find('.grtv').element.attributes['aria-multiselectable'].value).to.equal('true'); }); }); describe('when a function is passed for loadNodesAsync', () => { let loadNodesPromise = null; beforeEach(async () => { vi.useFakeTimers(); loadNodesPromise = new Promise(resolve => setTimeout(resolve.bind(null, generateNodes(['', ''])), 1000)); wrapper = await createWrapper({ loadNodesAsync: () => loadNodesPromise, selectionMode: SelectionMode.Single }); }); afterEach(() => { vi.useRealTimers(); }); describe('and the loadNodesAsync Promise has not returned', () => { it('should display the loading placeholder', () => { expect(wrapper.find('.grtv-loading').exists()).to.be.true; }); describe('and rendering a custom loader message', () => { beforeEach(async () => { wrapper = await createWrapper( { loadNodesAsync: () => loadNodesPromise }, null, { 'loading-root': '<span class="loading-slot-content">custom</span>', } ); }); it('should render the slot template', () => { expect(wrapper.find('.loading-slot-content').exists()).to.be.true; }); }); }); describe('and the loadNodesAsync Promise returns', () => { beforeEach(async () => { vi.runAllTimers(); await wrapper.vm.$nextTick(); }); it('should splice those nodes in as the model', () => { expect(wrapper.find('.grtv-loading').exists()).to.be.false; expect(wrapper.vm.model.length).to.equal(2); }); it('should emit the treeRootNodesLoad event', () => { expect(wrapper.emitted().treeRootNodesLoad).to.be.an('array').that.has.length(1); }); }); }); describe('when calculating the key mappings', () => { describe('and no customizations are provided', () => { beforeEach(async () => { wrapper = await createWrapper(); }); it('should have a key mapping', () => { const keyMap = wrapper.vm.ariaKeyMap; expect(keyMap).to.have.own.property('activateItem'); expect(keyMap).to.have.own.property('selectItem'); expect(keyMap).to.have.own.property('focusLastItem'); expect(keyMap).to.have.own.property('focusFirstItem'); expect(keyMap).to.have.own.property('collapseFocusedItem'); expect(keyMap).to.have.own.property('expandFocusedItem'); expect(keyMap).to.have.own.property('focusPreviousItem'); expect(keyMap).to.have.own.property('focusNextItem'); expect(keyMap).to.have.own.property('insertItem'); expect(keyMap).to.have.own.property('deleteItem'); }); }); describe('and valid customizations are provided', () => { const customKeyMap = { activateItem: [1], selectItem: [2], focusLastItem: [3], focusFirstItem: [4], collapseFocusedItem: [5], expandFocusedItem: [6], focusPreviousItem: [7], focusNextItem: [8], insertItem: [9], deleteItem: [10] }; beforeEach(async () => { wrapper = await createWrapper({ initialModel: [], customAriaKeyMap: customKeyMap }); }); it('should use the custom key mapping', () => { const keyMap = wrapper.vm.ariaKeyMap; expect(keyMap).to.deep.equal(customKeyMap); }); }); describe('and invalid non-array customizations are provided', () => { const customKeyMap = { activateItem: 1 }; beforeEach(async () => { vi.spyOn(console, 'error').mockImplementation(() => { }); // Suppress the [Vue warn] message from hitting test output when the validator fails console.warn = vi.fn(); wrapper = await createWrapper({ initialModel: [], customAriaKeyMap: customKeyMap }); }); it('should log an error', () => { expect(console.error.mock.calls[0][0]) .to.equal('customAriaKeyMap properties must be Arrays of numbers (corresponding to keyCodes); property \'activateItem\' fails check.'); }); }); }); describe('when created without a focusable node specified', () => { describe('and no selected nodes', () => { beforeEach(async () => { wrapper = await createWrapper({ initialModel: generateNodes(['ecs', 'eCs', ['eCs', 'ecs']]), selectionMode: SelectionMode.Multiple }); }); it('should set the first node as focusable', () => { expect(wrapper.vm.model[0].treeNodeSpec.focusable).to.be.true; }); }); describe('and selected nodes', () => { beforeEach(async () => { wrapper = await createWrapper({ initialModel: generateNodes(['ecs', 'eCs', ['eCS', 'ecs']]), selectionMode: SelectionMode.Multiple }); }); it('should set the first selected node as focusable', () => { expect(wrapper.vm.model[1].children[0].treeNodeSpec.focusable).to.be.true; }); }); }); describe('when created with a focusable node specified', () => { describe('always', () => { beforeEach(async () => { wrapper = await createWrapper({ initialModel: generateNodes(['ecs', 'eCsf', ['eCsf', 'ecs']]), selectionMode: SelectionMode.Multiple }); }); it('should keep that node as focusable', () => { expect(wrapper.vm.model[1].treeNodeSpec.focusable).to.be.true; }); it('should set focusble to false for any further nodes', () => { expect(wrapper.vm.model[1].children[0].treeNodeSpec.focusable).to.be.false; }); }); describe('and with a selectionMode of selectionFollowsFocus', () => { describe('and a selectable focusable node', () => { beforeEach(async () => { wrapper = await createWrapper({ initialModel: generateNodes(['ecs', 'eCsf']), selectionMode: SelectionMode.SelectionFollowsFocus }); }); it('should select the focused node', () => { expect(wrapper.vm.model[1].treeNodeSpec.state.selected).to.be.true; }); }); }); }); describe('when a node is getting deleted', () => { describe('and the node is not the currently focusable node', () => { beforeEach(async () => { wrapper = await createWrapper({ initialModel: generateNodes(['ecsf', 'eCs', 'ecs']) }); wrapper.vm.handleNodeDeletion(wrapper.vm.model[1]); }); it('should not change the focusable node', () => { expect(wrapper.vm.model[0].treeNodeSpec.focusable).to.be.true; }); }); describe('and the node is not the last node', () => { beforeEach(async () => { wrapper = await createWrapper({ initialModel: generateNodes(['ecsf', 'eCs', 'ecs']) }); wrapper.vm.handleNodeDeletion(wrapper.vm.model[0]); }); it('should set the next node as focusable', () => { expect(wrapper.vm.model[1].treeNodeSpec.focusable).to.be.true; }); }); describe('and the node is the last node', () => { beforeEach(async () => { wrapper = await createWrapper({ initialModel: generateNodes(['ecs', 'eCs', 'ecsf']) }); wrapper.vm.handleNodeDeletion(wrapper.vm.model[2]); }); it('should set the previous node as focusable', () => { expect(wrapper.vm.model[1].treeNodeSpec.focusable).to.be.true; }); }) }); describe('when selectionMode is Single', () => { beforeEach(async () => { wrapper = await createWrapper({ initialModel: generateNodes(['ecS', 'ecs']), selectionMode: SelectionMode.Single }); }); describe('and a node is already selected', () => { describe('and a new node is selected', () => { beforeEach(async () => { wrapper.vm.model[1].treeNodeSpec.state.selected = true; await wrapper.vm.$nextTick(); }); it('should deselect the previously selected node', () => { expect(wrapper.vm.model[0].treeNodeSpec.state.selected).to.be.false; }); }); }); }); describe('when a node fires a treeNodeClick event', () => { beforeEach(async () => { wrapper = await createWrapper({ initialModel: generateNodes(['es']), selectionMode: SelectionMode.Multiple }); wrapper.findComponent(TreeViewNode).vm.$emit('treeNodeClick'); }); it('should emit a treeNodeClick event', () => { expect(wrapper.emitted('treeNodeClick').length).to.equal(1); }); }); describe('when a node fires a treeNodeDblclick event', () => { beforeEach(async () => { wrapper = await createWrapper({ initialModel: generateNodes(['es']), selectionMode: SelectionMode.Multiple }); wrapper.findComponent(TreeViewNode).vm.$emit('treeNodeDblclick'); }); it('should emit a treeNodeDblclick event', () => { expect(wrapper.emitted('treeNodeDblclick').length).to.equal(1); }); }); describe('when a node fires a treeNodeCheckboxChange event', () => { beforeEach(async () => { wrapper = await createWrapper({ initialModel: generateNodes(['es']), selectionMode: SelectionMode.Multiple }); wrapper.findComponent(TreeViewNode).vm.$emit('treeNodeCheckboxChange'); }); it('should emit a treeNodeCheckboxChange event', () => { expect(wrapper.emitted('treeNodeCheckboxChange').length).to.equal(1); }); }); describe('when a node fires a treeNodeChildCheckboxChange event', () => { beforeEach(async () => { wrapper = await createWrapper({ initialModel: generateNodes(['es']), selectionMode: SelectionMode.Multiple }); wrapper.findComponent(TreeViewNode).vm.$emit('treeNodeChildCheckboxChange'); }); it('should emit a treeNodeChildCheckboxChange event', () => { expect(wrapper.emitted('treeNodeChildCheckboxChange').length).to.equal(1); }); }); describe('when a node fires a treeNodeRadioChange event', () => { beforeEach(async () => { wrapper = await createWrapper({ initialModel: generateNodes(['es']), selectionMode: SelectionMode.Multiple }); wrapper.findComponent(TreeViewNode).vm.$emit('treeNodeRadioChange'); }); it('should emit a treeNodeRadioChange event', () => { expect(wrapper.emitted('treeNodeRadioChange').length).to.equal(1); }); }); describe('when a node fires a treeNodeExpandedChange event', () => { beforeEach(async () => { wrapper = await createWrapper({ initialModel: generateNodes(['es']), selectionMode: SelectionMode.Multiple }); wrapper.findComponent(TreeViewNode).vm.$emit('treeNodeExpandedChange'); }); it('should emit a treeNodeExpandedChange event', () => { expect(wrapper.emitted('treeNodeExpandedChange').length).to.equal(1); }); }); describe('when a node fires a treeNodeChildrenLoad event', () => { beforeEach(async () => { wrapper = await createWrapper({ initialModel: generateNodes(['es']), selectionMode: SelectionMode.Multiple }); wrapper.findComponent(TreeViewNode).vm.$emit('treeNodeChildrenLoad'); }); it('should emit a treeNodeChildrenLoad event', () => { expect(wrapper.emitted('treeNodeChildrenLoad').length).to.equal(1); }); }); describe('when a node fires a treeNodeSelectedChange event', () => { describe('always', () => { beforeEach(async () => { wrapper = await createWrapper({ initialModel: generateNodes(['eS', 'es']), selectionMode: SelectionMode.Multiple }); wrapper.findComponent(TreeViewNode).vm.$emit('treeNodeSelectedChange', wrapper.vm.model[0]); }); it('should emit a treeNodeSelectedChange event', () => { expect(wrapper.emitted('treeNodeSelectedChange').length).to.equal(1); }); }); describe('and the treeview has a selectionMode of `single`', () => { describe('and the target node is selected', () => { beforeEach(async () => { wrapper = await createWrapper({ initialModel: generateNodes(['eS', 'eS', 'es']), selectionMode: SelectionMode.Single }); wrapper.findComponent(TreeViewNode).vm.$emit('treeNodeSelectedChange', wrapper.vm.model[0]); }); it('should deselect other selected nodes', () => { expect(wrapper.vm.model[1].treeNodeSpec.state.selected).to.be.false; }); }); describe('and the target node is not selected', () => { beforeEach(async () => { wrapper = await createWrapper({ initialModel: generateNodes(['es', 'eS', 'es']), selectionMode: SelectionMode.Single }); wrapper.findComponent(TreeViewNode).vm.$emit('treeNodeSelectedChange', wrapper.vm.model[0]); }); it('should not deselect other selected nodes', () => { expect(wrapper.vm.model[1].treeNodeSpec.state.selected).to.be.true; }); }); }); }); describe('when a node fires a treeNodeAdd event', () => { beforeEach(async () => { wrapper = await createWrapper({ initialModel: generateNodes(['es']), selectionMode: SelectionMode.Multiple }); wrapper.findComponent(TreeViewNode).vm.$emit('treeNodeAdd'); }); it('should emit a treeNodeAdd event', () => { expect(wrapper.emitted('treeNodeAdd').length).to.equal(1); }); }); describe('when a node fires a treeNodeDelete event', () => { beforeEach(async () => { wrapper = await createWrapper({ initialModel: generateNodes(['es']), selectionMode: SelectionMode.Multiple }); wrapper.findComponent(TreeViewNode).vm.$emit('treeNodeDelete', wrapper.vm.model[0]); }); it('should emit a treeNodeDelete event', () => { expect(wrapper.emitted('treeNodeDelete').length).to.equal(1); }); it('should delete the child node', () => { expect(wrapper.vm.model.length).to.equal(0); }); }); describe('when a node fires a treeNodeAriaFocusableChange event', () => { beforeEach(async () => { wrapper = await createWrapper({ initialModel: generateNodes(['es']), selectionMode: SelectionMode.Multiple }); wrapper.findComponent(TreeViewNode).vm.$emit('treeNodeAriaFocusableChange', wrapper.vm.model[0]); }); it('should call the focus update handler', () => { expect(wrapper.vm.model[0].treeNodeSpec.focusable).to.be.true; }); }); describe('when a node fires a treeNodeAriaRequestFirstFocus event', () => { beforeEach(async () => { wrapper = await createWrapper({ initialModel: generateNodes(['es']), selectionMode: SelectionMode.Multiple }); wrapper.findComponent(TreeViewNode).vm.$emit('treeNodeAriaRequestFirstFocus'); }); it('should call the focus update handler', () => { expect(wrapper.vm.model[0].treeNodeSpec.focusable).to.be.true; }); }); describe('when a node fires a treeNodeAriaRequestLastFocus event', () => { beforeEach(async () => { wrapper = await createWrapper({ initialModel: generateNodes(['es', 'es']), selectionMode: SelectionMode.Multiple }); wrapper.findComponent(TreeViewNode).vm.$emit('treeNodeAriaRequestLastFocus'); }); it('should call the focus update handler', () => { expect(wrapper.vm.model[1].treeNodeSpec.focusable).to.be.true; }); }); describe('when a node fires a treeNodeAriaRequestPreviousFocus event', () => { beforeEach(async () => { wrapper = await createWrapper({ initialModel: generateNodes(['es', 'efs']), selectionMode: SelectionMode.Multiple }); wrapper.findComponent(TreeViewNode).vm.$emit('treeNodeAriaRequestPreviousFocus', wrapper.vm.model[1]); }); it('should call the focus update handler', () => { expect(wrapper.vm.model[0].treeNodeSpec.focusable).to.be.true; }); }); describe('when a node fires a treeNodeAriaRequestNextFocus event', () => { beforeEach(async () => { wrapper = await createWrapper({ initialModel: generateNodes(['efs', 'es']), selectionMode: SelectionMode.Multiple }); wrapper.findComponent(TreeViewNode).vm.$emit('treeNodeAriaRequestNextFocus', wrapper.vm.model[0], true); }); it('should call the focus update handler', () => { expect(wrapper.vm.model[1].treeNodeSpec.focusable).to.be.true; }); }); describe('when created with nodes that do not contain an explicit id property', () => { it('should fall back to the id property (note: this test is testing implementation [v-for iteration key for nodes] and not functionality)', async () => { const nodes = generateNodes(['es']); nodes[0].treeNodeSpec.idProperty = null; wrapper = await createWrapper({ initialModel: nodes, selectionMode: SelectionMode.Multiple }); expect(wrapper.findComponent(TreeViewNode).exists()).to.be.true; }); }); }); <file_sep>export function useObjectMethods() { /** * Gives a pretty good indication of objectness * @param {Object} obj The thing to check for objectness * @returns {boolean} True if this is probably an Object, false otherwise */ function isProbablyObject(obj) { return obj !== null && typeof obj === 'object' && !Array.isArray(obj); }; /** * Deeply (or deeply enough) copies the given object into a new object. * Note that this is "cheap" as in budget-value, not efficiency. * @param {Object} toCopy The object to copy * @returns {Object} The copy */ function cheapCopyObject(toCopy) { // Use a copy of the source, since the props can be fubar'd by the assigns let target = JSON.parse(JSON.stringify(toCopy)); if (isProbablyObject(target)) { for (const propName of Object.keys(toCopy)) { let srcProp = toCopy[propName]; if (typeof srcProp === 'function') { // Functions are lost on the JSON copy, so snag the original. target[propName] = srcProp; } else if (isProbablyObject(srcProp)) { // Find object properties to deep assign them target[propName] = cheapCopyObject(srcProp); } } } return target; }; return { isProbablyObject, cheapCopyObject }; }<file_sep>import TreeView from '../components/TreeView.vue'; import ExamplesDocs from './Examples.docs.mdx'; // Default export to define the component ===================================== export default { title: 'Examples/TreeView', component: TreeView, argTypes: { initialModel: { description: "The actual tree data", }, skinClass: { description: "A class added to the top-most element; used in CSS selectors for all of the component's styles", }, }, parameters: { controls: { sort: "requiredFirst" }, docs: { page: ExamplesDocs, }, }, }; // Stories ==================================================================== export { Basic } from './definitions/TreeView.Basic'; export { Static } from './definitions/TreeView.Static'; export { SettingDefaults } from './definitions/TreeView.SettingDefaults'; export { Checkboxes } from './definitions/TreeView.Checkboxes'; export { Radiobuttons } from './definitions/TreeView.Radiobuttons'; export { Slots } from './definitions/TreeView.Slots'; export { AddRemove } from './definitions/TreeView.AddRemove'; export { Selection } from './definitions/TreeView.Selection'; export { Async } from './definitions/TreeView.Async'; export { DragDrop } from './definitions/TreeView.DragDrop'; export { Filtering } from './definitions/TreeView.Filtering'; export { ClassCustomization, SkinCustomization } from './definitions/TreeView.Customization';<file_sep>export default [ { id: 'basic-node1', label: 'My First Node', children: [], }, { id: 'basic-node2', label: 'My Second Node', treeNodeSpec: { title: 'My node, and its fantastic title', input: { type: 'checkbox', name: 'checkbox1' }, state: { expanded: true, } }, children: [ { id: 'basic-subnode1', label: 'This is a subnode', children: [], treeNodeSpec: { input: { type: 'radio', name: 'radio1', isInitialRadioGroupValue: true } } }, { id: 'basic-subnode2', label: 'Another Subnode', children: [], treeNodeSpec: { input: { type: 'radio', name: 'radio1' } } }, { id: 'basic-subnode3', label: 'This is a disabled, checked subnode', treeNodeSpec: { input: { type: 'checkbox', name: 'checkbox2' }, state: { input: { value: true, disabled: true } } }, children: [ { id: 'basic-subsubnode1', label: 'An even deeper node', children: [] } ] } ] } ];<file_sep>import { defineConfig } from 'vite' import Vue from '@vitejs/plugin-vue' export default defineConfig({ plugins: [ Vue(), ], test: { coverage: { include: ["src/**/*"], exclude: ["src/stories/**/*", "src/**/*.spec.*"], all: true, statements: 90, }, environment: 'jsdom', restoreMocks: true, }, })<file_sep>import { useTreeViewTraversal } from './treeViewTraversal.js' import { useSelection } from './selection/selection.js'; import InputType from '../enums/inputType.js'; import SelectionMode from '../enums/selectionMode.js'; /** * Composable dealing with convenience methods at the top level of the tree view. * @param {TreeViewNode} treeModel The Ref to the top level model of the tree * @param {Ref<Object>} radioGroupValues The Ref to the tree's radioGroupValues * @param {Ref<SelectionMode>} selectionMode The Ref to the tree's selectionMode * @returns Convenience methods to deal with tree view */ export function useTreeViewConvenienceMethods(treeModel, radioGroupValues, selectionMode) { const { depthFirstTraverse } = useTreeViewTraversal(treeModel); const { isSelectable, isSelected } = useSelection(selectionMode); /** * Gets any nodes matched by the given function. * @param {Function} matcherFunction A function which takes a node as an argument * and returns a boolean indicating a match for some condition * @param {Integer} maxMatches The maximum number of matches to return * @returns {Array<TreeViewNode>} An array of any nodes matched by the given function */ function getMatching(matcherFunction, maxMatches = 0) { let matches = []; if (typeof matcherFunction === 'function') { depthFirstTraverse((current) => { if (matcherFunction(current)) { matches.push(current); return maxMatches < 1 || matches.length < maxMatches; } }); } return matches; } /** * Gets any nodes with checked checkboxes. * @returns {Array<TreeViewNode>} An array of any nodes with checked checkboxes */ function getCheckedCheckboxes() { return getMatching((current) => current.treeNodeSpec.input && current.treeNodeSpec.input.type === InputType.Checkbox && current.treeNodeSpec.state.input.value); } /** * Gets any nodes with checked checkboxes. * @returns {Array<TreeViewNode>} An array of any nodes with checked checkboxes */ function getCheckedRadioButtons() { return getMatching((current) => current.treeNodeSpec.input && current.treeNodeSpec.input.type === InputType.RadioButton && radioGroupValues.value[current.treeNodeSpec.input.name] === current.treeNodeSpec.input.value); } /** * Gets the node with the given ID * @param {String} targetId The ID of the node to find * @returns {TreeViewNode} The node with the given ID if found, or null */ function findById(targetId) { let node = null; if (typeof targetId === 'string') { // Do a quick check to see if it's at the root level node = treeModel.value.find(n => n[n.treeNodeSpec.idProperty] === targetId); if (!node) { depthFirstTraverse((current) => { let children = current[current.treeNodeSpec.childrenProperty]; node = children.find(n => n[n.treeNodeSpec.idProperty] === targetId); if (node) { return false; } }); } } return node; } /** * Gets any selected nodes * @returns {TreeViewNode[]} An array of any selected nodes */ function getSelected() { return selectionMode.value === SelectionMode.None ? [] : getMatching((current) => isSelectable(current) && isSelected(current)); } /** * Removes and returns the node with the given ID * @param {String} targetId The ID of the node to remove * @returns {TreeViewNode} The node with the given ID if removed, or null */ function removeById(targetId) { let node = null; if (typeof targetId === 'string') { // Do a quick check to see if it's at the root level let nodeIndex = treeModel.value.findIndex(n => n[n.treeNodeSpec.idProperty] === targetId); if (nodeIndex > -1) { node = treeModel.value.splice(nodeIndex, 1)[0]; } else { depthFirstTraverse((current) => { // See if this node has a child that matches let children = current[current.treeNodeSpec.childrenProperty]; nodeIndex = children.findIndex(n => n[n.treeNodeSpec.idProperty] === targetId); if (nodeIndex > -1) { node = children.splice(nodeIndex, 1)[0]; return false; } }); } } return node; } return { findById, getCheckedCheckboxes, getCheckedRadioButtons, getMatching, getSelected, removeById, }; }<file_sep>import { unref } from 'vue'; import { effectAllowed as EffectAllowed } from '../enums/dragDrop.js' import InputType from '../enums/inputType'; import { useObjectMethods } from './objectMethods.js'; const { isProbablyObject } = useObjectMethods(); const allowedEffectAllowedValues = [EffectAllowed.Copy, EffectAllowed.Move, EffectAllowed.CopyMove, EffectAllowed.None]; export function useNodeDataNormalizer(model, modelDefaults, radioGroupValues) { /** * Normalizes the data model to the format consumable by TreeViewNode. */ function normalizeNodeData() { if (!model.value.treeNodeSpec) { model.value.treeNodeSpec = {}; } const tns = model.value.treeNodeSpec; assignDefaultProps(unref(modelDefaults), tns); // Set expected properties if not provided if (typeof tns.childrenProperty !== 'string') { tns.childrenProperty = 'children'; } if (typeof tns.idProperty !== 'string') { tns.idProperty = 'id'; } if (typeof tns.labelProperty !== 'string') { tns.labelProperty = 'label'; } if (!Array.isArray(model.value[tns.childrenProperty])) { model.value[tns.childrenProperty] = []; } if (typeof tns.expandable !== 'boolean') { tns.expandable = true; } if (typeof tns.selectable !== 'boolean') { tns.selectable = false; } if (typeof tns.deletable !== 'boolean') { tns.deletable = false; } if (typeof tns.draggable !== 'boolean') { tns.draggable = false; } if (typeof tns.allowDrop !== 'boolean') { tns.allowDrop = false; } if (typeof tns.dataTransferEffectAllowed !== 'string' || !allowedEffectAllowedValues.includes(tns.dataTransferEffectAllowed)) { tns.dataTransferEffectAllowed = EffectAllowed.CopyMove; } if (typeof tns.focusable !== 'boolean') { tns.focusable = false; } if (typeof tns.addChildCallback !== 'function') { tns.addChildCallback = null; } if (typeof tns.deleteNodeCallback !== 'function') { tns.deleteNodeCallback = null; } if (typeof tns.title !== 'string' || tns.title.trim().length === 0) { tns.title = null; } if (typeof tns.expanderTitle !== 'string' || tns.expanderTitle.trim().length === 0) { tns.expanderTitle = null; } if (typeof tns.addChildTitle !== 'string' || tns.addChildTitle.trim().length === 0) { tns.addChildTitle = null; } if (typeof tns.deleteTitle !== 'string' || tns.deleteTitle.trim().length === 0) { tns.deleteTitle = null; } if (tns.customizations == null || typeof tns.customizations !== 'object') { tns.customizations = {}; } if (typeof tns.loadChildrenAsync !== 'function') { tns.loadChildrenAsync = null; } // Internal members tns._ = {}; tns._.dragging = false; normalizeNodeInputData(tns); normalizeNodeStateData(tns); model.value.treeNodeSpec = tns; } /** * Assigns any properties from the source object to the target object * where the target object doesn't already define that property. * @param {Object} source The source object from which properties are read * @param {Object} target The target object into which missing properties are assigned */ function assignDefaultProps(source, target) { // Make sure the defaults is an object if (isProbablyObject(source)) { // Use a copy of the source, since the props can be fubar'd by the assigns const sourceCopy = JSON.parse(JSON.stringify(source)); // Assign existing values into the source Object.assign(sourceCopy, target); for (const propName of Object.keys(source)) { // Functions are lost on the JSON copy, so snag the original. Otherwise, use the merged value. const propValue = typeof source[propName] === 'function' ? source[propName] : sourceCopy[propName]; if (isProbablyObject(propValue)) { // Find object properties to deep assign them target[propName] = target[propName] || {}; assignDefaultProps(propValue, target[propName]); } else if (typeof propValue === 'function' && !target[propName]) { // Find function properties and assign if missing in target. target[propName] = propValue; } else { // Otherwise, copy from the source to the target. target[propName] = propValue; } } } } /** * Normalizes the data model's data related to input element generation. */ function normalizeNodeInputData(tns) { let input = tns.input; // For nodes that are inputs, they must specify at least a type. // Only a subset of types are accepted. if (input === null || typeof input !== 'object' || !Object.values(InputType).includes(input.type)) { tns.input = null; } else { if (typeof input.name !== 'string' || input.name.trim().length === 0) { input.name = null; } if (input.type === InputType.RadioButton) { if (typeof input.name !== 'string' || input.name.trim().length === 0) { input.name = 'unspecifiedRadioName'; } if (typeof input.value !== 'string' || input.value.trim().length === 0) { input.value = model.value[tns.labelProperty].replace(/[\s&<>"'\/]/g, ''); } if (!radioGroupValues.value.hasOwnProperty(input.name)) { radioGroupValues.value[input.name] = ''; } if (input.isInitialRadioGroupValue === true) { radioGroupValues.value[input.name] = input.value; } } } } /** * Normalizes the data model's data related to the node's state. */ function normalizeNodeStateData(tns) { if (tns.state === null || typeof tns.state !== 'object') { tns.state = {}; } if (tns._.state === null || typeof tns._.state !== 'object') { tns._.state = {}; } let state = tns.state; let privateState = tns._.state; // areChildrenLoaded and areChildrenLoading are internal state used with asynchronous child // node loading. Any node with asynchronously loaded children starts as not expanded. privateState.areChildrenLoaded = typeof tns.loadChildrenAsync !== 'function'; privateState.areChildrenLoading = false; if (typeof state.expanded !== 'boolean' || !privateState.areChildrenLoaded) { state.expanded = false; } if (typeof state.selected !== 'boolean') { state.selected = false; } if (tns.input) { if (state.input === null || typeof state.input !== 'object') { state.input = {}; } if (state.input.disabled === null || typeof state.input.disabled !== 'boolean') { state.input.disabled = false; } if (tns.input.type === InputType.Checkbox) { if (typeof state.input.value !== 'boolean') { state.input.value = false; } } } } return { normalizeNodeData }; }<file_sep>--- name: Question about: Ask a question about this project title: '' labels: question assignees: '' --- **When asking a question please include:** - [ ] Version - [ ] Your question - [ ] Anything you may have tried or considered when attempting to answer the question for yourself (if applicable) Questions may not be answered immediately, but should at least be acknowledged within a day or so. <file_sep>export default [ { id: 'slots-node1', label: 'Checkbox Node', children: [], treeNodeSpec: { input: { type: 'checkbox', name: 'checkbox1' }, state: { input: { value: false, disabled: false } } } }, { id: 'slots-node2', label: 'Radiobutton Node', treeNodeSpec: { input: { type: 'radio', name: 'radiobutton1' }, state: { input: { value: false, disabled: false } } } }, { id: 'slots-node3', label: 'Text Node', children: [ { id: 'slots-subnode1', label: 'Checkbox Subnode', treeNodeSpec: { input: { type: 'checkbox', name: 'checkbox2' }, state: { input: { value: false, disabled: false } }, children: [] } } ] }, { id: 'slots-node4', label: 'Text Node with Async Children', children: [], treeNodeSpec: { expandable: true, loadChildrenAsync: (m) => new Promise(() => { }), // Never resolve so the demo node stays up. } } ];<file_sep>export default { tree1Data: [ { id: 'dragdrop1-node1', label: 'Node One', children: [], treeNodeSpec: { addChildCallback: function () { return Promise.resolve({ id: '' + Math.random(), label: 'Added' }); } } }, { id: 'dragdrop1-node2', label: 'Node Two', children: [ { id: 'dragdrop1-subnode1', label: 'Subnode One', children: [] }, { id: 'dragdrop1-subnode2', label: 'Subnode Two', children: [ { id: 'dragdrop1-subsubnode1', label: 'Sub-Subnode 1', children: [] }, { id: 'dragdrop1-subsubnode2', label: 'Sub-Subnode 2', children: [] } ] } ] } ], tree2Data: [ { id: 'dragdrop2-node1', label: 'Node One', children: [], treeNodeSpec: { addChildCallback: function () { return Promise.resolve({ id: '' + Math.random(), label: 'Added' }); } } }, { id: 'dragdrop2-node2', label: 'Node Two', children: [ { id: 'dragdrop2-subnode1', label: 'Subnode One', children: [] }, { id: 'dragdrop2-subnode2', label: 'Subnode Two', children: [ { id: 'dragdrop2-subsubnode1', label: 'Sub-Subnode 1', children: [] }, { id: 'dragdrop2-subsubnode2', label: 'Sub-Subnode 2', children: [] } ] } ] } ] };<file_sep>export default [ { id: 'selection-node1', label: 'My First Node', children: [], treeNodeSpec: { expandable: true, selectable: true, deletable: true, input: { type: 'checkbox', name: 'checkbox1' }, state: { expanded: false, selected: false, input: { value: false, disabled: false } }, addChildCallback: function () { var entry = prompt("Give it a string.", ""); return Promise.resolve(entry ? { id: entry, label: entry, deletable: true, selectable: true } : null); } } }, { id: 'selection-node2', label: 'My Second Node', children: [ { id: 'selection-subnode1', label: 'This is a subnode', children: [], treeNodeSpec: { title: 'Even non-input nodes should get a title.', expandable: true, selectable: true, deletable: true, state: { expanded: false, selected: false } } }, { id: 'selection-subnode2', label: 'This is a checkable, checked subnode', children: [ { id: 'subsubnode1', label: 'An even deeper node', children: [], treeNodeSpec: { expandable: true, selectable: true, state: { expanded: false, selected: false }, addChildCallback: function () { var entry = prompt("Give it a string.", ""); return Promise.resolve(entry ? { id: entry, label: entry, deletable: true, selectable: true } : null); } } } ], treeNodeSpec: { expandable: true, selectable: true, input: { type: 'checkbox', name: 'checkbox3' }, state: { expanded: false, selected: false, input: { value: true, disabled: true } } } } ], treeNodeSpec: { title: 'My second node, and its fantastic title', expandable: true, selectable: true, input: { type: 'checkbox', name: 'checkbox2' }, state: { expanded: true, selected: false, input: { value: false, disabled: false } } } }, { id: 'selection-node3', label: 'My Third Node', children: [ { id: 'subnode31', label: 'This is an expanded subnode', children: [], treeNodeSpec: { expandable: false, selectable: true, deletable: true, state: { expanded: false, selected: false } } } ], treeNodeSpec: { expandable: false, selectable: true, deletable: true, state: { expanded: true, selected: false, input: { value: false, disabled: false } } } } ];<file_sep>export default [ { id: 'addremove-rootNode', label: 'Root Node', treeNodeSpec: { state: { expanded: true, } } } ];<file_sep>import TreeView from '../../components/TreeView.vue'; import treeViewData from '../data/staticTreeViewData'; const Template = (args) => ({ components: { TreeView }, setup() { return { args }; }, template: '<tree-view v-bind="args" />' }); export const Static = Template.bind({}); Static.args = { initialModel: treeViewData, modelDefaults: { expandable: false, state: { expanded: true, } } }; const docsSourceCode = ` <template> <tree-view :initial-model="tvModel" :model-defaults="modelDefaults"></tree-view> </template> <script setup> import { ref } from "vue"; import { TreeView } from "@grapoza/vue-tree"; import treeViewData from "../data/staticTreeViewData"; const modelDefaults = ref({ addChildTitle: 'Add a new child node', deleteTitle: 'Delete this node', expanderTitle: 'Expand this node' }); const tvModel = ref(treeViewData); </script>`; Static.parameters = { docs: { source: { code: docsSourceCode, language: "html", type: "auto", }, }, };<file_sep>import { expect, describe, it, beforeEach, vi } from 'vitest'; import { ref } from 'vue'; import { useTreeViewSelection } from './treeViewSelection.js'; import { generateNodes } from 'tests/data/node-generator.js'; import SelectionMode from '../../enums/selectionMode.js'; import TreeEvent from '../../enums/event.js'; describe('treeViewSelection.js', () => { let nodes; let emit; beforeEach(() => { emit = vi.fn(); }); describe('when selectionMode changes', () => { beforeEach(() => { nodes = generateNodes(['Sf', 'S']); const selectionMode = ref(SelectionMode.Multiple); const focusableNodeModel = ref(nodes[0]); useTreeViewSelection(ref(nodes), selectionMode, focusableNodeModel, emit); selectionMode.value = SelectionMode.Single; }); it('should enforce the selection mode', () => { expect(nodes[0].treeNodeSpec.state.selected).to.be.true; expect(nodes[1].treeNodeSpec.state.selected).to.be.false; }); }); describe('when the focusable node changes', () => { describe('and the selection mode is not selectionFollowsFocus', () => { beforeEach(() => { nodes = generateNodes(['Sf', 's']); const selectionMode = ref(SelectionMode.Single); const focusableNodeModel = ref(nodes[0]); useTreeViewSelection(ref(nodes), selectionMode, focusableNodeModel, emit); focusableNodeModel.value = nodes[1]; }); it('should not deselect nodes that are not the newly focused node', () => { expect(nodes[0].treeNodeSpec.state.selected).to.be.true; }); }); describe('and the selection mode is selectionFollowsFocus', () => { beforeEach(() => { nodes = generateNodes(['Sf', 's']); const selectionMode = ref(SelectionMode.SelectionFollowsFocus); const focusableNodeModel = ref(nodes[0]); useTreeViewSelection(ref(nodes), selectionMode, focusableNodeModel, emit); focusableNodeModel.value = nodes[1]; }); it('should deselect nodes that are not the newly focused node', () => { expect(nodes[0].treeNodeSpec.state.selected).to.be.false; }); }); }); describe('when getting the aria-multiselectable value', () => { describe('and the selection mode is None', () => { it('should return null', () => { nodes = generateNodes(['sf']); const selectionMode = ref(SelectionMode.None); const focusableNodeModel = ref(nodes[0]); const { ariaMultiselectable } = useTreeViewSelection(ref(nodes), selectionMode, focusableNodeModel, emit); expect(ariaMultiselectable.value).to.be.null; }); }); describe('and the selection mode is not Multiple', () => { it('should return false', () => { nodes = generateNodes(['sf']); const selectionMode = ref(SelectionMode.Single); const focusableNodeModel = ref(nodes[0]); const { ariaMultiselectable } = useTreeViewSelection(ref(nodes), selectionMode, focusableNodeModel, emit); expect(ariaMultiselectable.value).to.be.false; }); }); describe('and the selection mode is Multiple', () => { it('should return true', () => { nodes = generateNodes(['sf']); const selectionMode = ref(SelectionMode.Multiple); const focusableNodeModel = ref(nodes[0]); const { ariaMultiselectable } = useTreeViewSelection(ref(nodes), selectionMode, focusableNodeModel, emit); expect(ariaMultiselectable.value).to.be.true; }); }); }); describe('when enforcing the selection mode', () => { describe('and the selection mode is Single', () => { it('should deselect any nodes after the first (depth-first)', () => { nodes = generateNodes(['sf', ['S'], 'S']); const selectionMode = ref(SelectionMode.Single); const focusableNodeModel = ref(nodes[0]); const { enforceSelectionMode } = useTreeViewSelection(ref(nodes), selectionMode, focusableNodeModel, emit); enforceSelectionMode(); expect(nodes[0].treeNodeSpec.state.selected).to.be.false; expect(nodes[0].children[0].treeNodeSpec.state.selected).to.be.true; expect(nodes[1].treeNodeSpec.state.selected).to.be.false; }); describe('and the nodes use a custom ID property', () => { it('should deselect any nodes after the first (depth-first)', () => { nodes = generateNodes(['sf', ['S'], 'S']); nodes[0].newid = nodes[0].id; nodes[0].treeNodeSpec.idProperty = 'newid'; delete nodes[0].id; nodes[0].children[0].newid = nodes[0].children[0].id; nodes[0].children[0].treeNodeSpec.idProperty = 'newid'; delete nodes[0].children[0].id; nodes[1].newid = nodes[1].id; nodes[1].treeNodeSpec.idProperty = 'newid'; delete nodes[1].id; const selectionMode = ref(SelectionMode.Single); const focusableNodeModel = ref(nodes[0]); const { enforceSelectionMode } = useTreeViewSelection(ref(nodes), selectionMode, focusableNodeModel, emit); enforceSelectionMode(); expect(nodes[0].treeNodeSpec.state.selected).to.be.false; expect(nodes[0].children[0].treeNodeSpec.state.selected).to.be.true; expect(nodes[1].treeNodeSpec.state.selected).to.be.false; }); }); }); describe('and the selection mode is Selection Follows Focus', () => { it('should select only the focusable node', () => { nodes = generateNodes(['S', ['S'], 'sf', 'S']); const selectionMode = ref(SelectionMode.SelectionFollowsFocus); const focusableNodeModel = ref(nodes[1]); const { enforceSelectionMode } = useTreeViewSelection(ref(nodes), selectionMode, focusableNodeModel, emit); enforceSelectionMode(); expect(nodes[0].treeNodeSpec.state.selected).to.be.false; expect(nodes[0].children[0].treeNodeSpec.state.selected).to.be.false; expect(nodes[1].treeNodeSpec.state.selected).to.be.true; expect(nodes[2].treeNodeSpec.state.selected).to.be.false; }); }); }); describe('when handling node selected changes', () => { it('should emit the selected change event', () => { nodes = generateNodes(['Sf', 's']); const selectionMode = ref(SelectionMode.Single); const focusableNodeModel = ref(nodes[0]); const { handleNodeSelectedChange } = useTreeViewSelection(ref(nodes), selectionMode, focusableNodeModel, emit); nodes[0].treeNodeSpec.state.selected = false; handleNodeSelectedChange(nodes[0]); expect(emit).toHaveBeenCalledWith(TreeEvent.SelectedChange, nodes[0]); }); describe('and the selection mode is Single and the node is selected', () => { it('should deselect any other nodes', () => { nodes = generateNodes(['Sf', 's']); const selectionMode = ref(SelectionMode.Single); const focusableNodeModel = ref(nodes[0]); const { handleNodeSelectedChange } = useTreeViewSelection(ref(nodes), selectionMode, focusableNodeModel, emit); nodes[1].treeNodeSpec.state.selected = true; handleNodeSelectedChange(nodes[1]); expect(nodes[0].treeNodeSpec.state.selected).to.be.false; }); }); }); });<file_sep>import { expect, describe, it } from 'vitest'; import { useSelection } from './selection.js'; import { generateNodes } from 'tests/data/node-generator.js'; const { select, deselect, setSelected, isSelectable, isSelected } = useSelection(); describe('selection.js', () => { describe('when selecting a node', () => { it('should set the node as selected', () => { const node = generateNodes(['es'])[0]; select(node); expect(node.treeNodeSpec.state.selected).to.be.true; }); }); describe('when deselecting a node', () => { it('should set the node as deselected', () => { const node = generateNodes(['eS'])[0]; deselect(node); expect(node.treeNodeSpec.state.selected).to.be.false; }); }); describe('when setting the selected state', () => { describe('and the state is set to true', () => { it('should set the node as selected', () => { const node = generateNodes(['es'])[0]; setSelected(node, true); expect(node.treeNodeSpec.state.selected).to.be.true; }); }); describe('and the state is set to false', () => { it('should set the node as deselected', () => { const node = generateNodes(['eS'])[0]; setSelected(node, false); expect(node.treeNodeSpec.state.selected).to.be.false; }); }); }); describe('when checking if a node is selectable', () => { describe('and the node is selectable', () => { it('should return true', () => { let node = generateNodes(['es'])[0]; expect(isSelectable(node)).to.be.true; }); }); describe('and the node is not selectable', () => { it('should return false', () => { let node = generateNodes(['e'])[0]; expect(isSelectable(node)).to.be.false; }); }); }); describe('when checking if a node is selected', () => { describe('and the node is selected', () => { it('should return true', () => { let node = generateNodes(['eS'])[0]; expect(isSelected(node)).to.be.true; }); }); describe('and the node is not selected', () => { it('should return false', () => { let node = generateNodes(['es'])[0]; expect(isSelected(node)).to.be.false; }); }); }); });<file_sep># Contributing to vue-tree Thank you for your interest in contributing to the vue-tree component. What follows is a set of guidelines for contributors who intend to make changes for incorporation into the [grapoza/vue-tree](https://github.com/grapoza/vue-tree) repository. ## Just need to report an issue? If you notice a problem with vue-tree but don't have the means to submit a patch yourself, you can still contribute to the success of the project by [filing an issue](https://github.com/grapoza/vue-tree/issues). Be sure to include all of the requested information, and if possible provide a reproduction of the issue. You can also submit an issue if you just have a question about the component. If you do this, please be sure to label your issue with **question** (this will be done for you if you use the Question template). ## Want to contribute a fix or implement a feature? Great! Here are the things you'll need to know in order to start hacking on the project. While this should cover the general flow, feel free to reach out if anything isn't clear or you have any questions which are not covered here. Before starting on any fix, make sure the issue itself is documented in the [issues list](https://github.com/grapoza/vue-tree/issues). ### Grab the code You can start by forking the [grapoza/vue-tree](https://github.com/grapoza/vue-tree) repository and cloning that fork. If you're unfamiliar with forks, take a look at [GitHub's instructions on how to fork a repository](https://help.github.com/articles/fork-a-repo/). You'll do any development on your own fork and then issue a PR when you're ready for your code to undergo review. ### Get set up Prerequisites: - [Yarn](https://yarnpkg.com/) (latest) Once you have the prerequisites and a local clone of the repository, open a shell to the root of the cloned repo and run `yarn` to install the packages. Once that's done, you can use `yarn build` to build. Other scripts are available in `package.json` for things like running tests or building documentation. ### Implement changes The three main things you'll update are the code, the tests, and the documentation. How you choose to make these updates is up to you. When your changes are pushed and ready for a PR the expectation is that all changes to these areas are done. #### Make your code changes There isn't a huge amount of code in a small library like vue-tree, however some code has been split out to simplify how much code you'll need to sift through to make your changes. For instance, most code related to implementing the ARIA recomendations for accessibile tree views is split into composables used by the main component .vue files. (Note: Some of the composables are a bit kludgy due to porting from Vue 2 mixins.) If you find yourself writing a sizable amount of code for something that may benefit from such a split, bring it up in the conversation for the issue you're working on. This project includes an `.editorconfig` which should help with basic formatting. In addition to these few rules, keep the [Vue Style Guide](https://vuejs.org/style-guide/) in mind when making changes to the components. #### Update the tests Unit tests are written as Vitest specs. The spec files are split into separate files based on broad concerns. Each component has a main spec file containing tests for top level concerns like defaults and property usage. Further separation may be done if the size of a test file becomes burdensome (_e.g._, customizations and interactions are tested in separate files for the TreeViewNode component). If you feel like your changes may benefit from their own test file, bring it up in the conversation for the issue you're working on. The specs are organized in a fairly standard hierarchy. Each test file should have one outermost `describe` for the component (or the part of the component under test). Within that, another level of `describe`s outline the scenario under test. This may be a top-level `describe` with more specific `describe`s nested inside it. These top-level `describe`s should start with "when" in their descriptions. Nested `describe`s should start with "and" in their descriptions. Finally, `it` is used for the actual test and should start with "should" in their descriptions. For example: ```javascript describe('myComponent', () => { describe('when beeping', () => { describe('and booping', () => { it('should beep-boop', () => { }); }); describe('and not booping', () => { it('should not beep-boop', () => { }); }); }); }); ``` When writing tests, it's often required to have node data to test with. There's a helper method available in `tests/data/node-generator.js` that can help with creating various nodes for testing. See existing tests and the comment in that file for examples of how to craft test node data. In addition to unit tests, the Storybook documentation pages can run locally and provide a way to both document and test changes. You can run `yarn storybook` to start the site. If your changes would make sense with a demonstration, go ahead and add to the demos on this site. #### Update the documentation Documentation is created using [Storybook](https://storybook.js.org/). `package.json` includes the `build-storybook-docs` script to build documentation and the `storybook-docs` script to run a a preview of the site for testing. The `src/stories` folder contains the sources you'll edit when making changes or additions to the documentation, and only the sources in this folder get comitted. ### Submit your changes Once you've made your changes, added tests, and updated the documentation as needed, create a pull request and fill out the information requested. <file_sep>import { beforeEach, expect, describe, it, vi } from 'vitest'; import { ref } from 'vue'; import { useTreeViewNodeChildren } from './treeViewNodeChildren.js'; import { generateNodes } from '../../../tests/data/node-generator.js'; import TreeEvent from '../../enums/event.js'; let emit; describe('treeViewNodeChildren.js', () => { beforeEach(() => { emit = vi.fn(); }); describe('when checking if child nodes are loaded', () => { describe('and the child nodes are supplied statically', () => { it('should return true', () => { const node = ref(generateNodes(['es'])[0]); const { areChildrenLoaded } = useTreeViewNodeChildren(node, emit); expect(areChildrenLoaded.value).to.be.true; }); }); describe('and the child nodes are supplied via an async loader', () => { const asyncLoader = async () => Promise.resolve(generateNodes(['es'])); describe('and the children have been loaded', () => { it('should return true', () => { const node = ref(generateNodes([''], '', null, asyncLoader)[0]); node.value.treeNodeSpec._.state.areChildrenLoaded = true; const { areChildrenLoaded } = useTreeViewNodeChildren(node, emit); expect(areChildrenLoaded.value).to.be.true; }); }); describe('and the children have not been loaded', () => { it('should return false', () => { const node = ref(generateNodes([''], '', null, asyncLoader)[0]); node.value.treeNodeSpec._.state.areChildrenLoaded = false; const { areChildrenLoaded } = useTreeViewNodeChildren(node, emit); expect(areChildrenLoaded.value).to.be.false; }); }); }); }); describe('when checking if children are loading', () => { describe('and the children are loading', () => { it('should return true', () => { const node = ref(generateNodes(['es'])[0]); node.value.treeNodeSpec._.state.areChildrenLoading = true; const { areChildrenLoading } = useTreeViewNodeChildren(node, emit); expect(areChildrenLoading.value).to.be.true; }); }); describe('and the children are not loading', () => { it('should return false', () => { const node = ref(generateNodes(['es'])[0]); node.value.treeNodeSpec._.state.areChildrenLoading = false; const { areChildrenLoading } = useTreeViewNodeChildren(node, emit); expect(areChildrenLoading.value).to.be.false; }); }); }); describe('when getting children', () => { describe('and a children property name is specified', () => { it('should return the value of the given property', () => { const node = ref(generateNodes(['es', ['es', 'es']])[0]); node.value.children2 = node.children; delete node.value.children; node.value.treeNodeSpec.childrenProperty = 'children2'; const { children } = useTreeViewNodeChildren(node, emit); expect(children.value).to.equal(node.children2); }); }); describe('and a children property name is not specified', () => { it('should return the value of the `children` property', () => { const node = ref(generateNodes(['es', ['es', 'es']])[0]); delete node.value.treeNodeSpec.childrenProperty; const { children } = useTreeViewNodeChildren(node, emit); expect(children.value).to.equal(node.value.children); }); }); }); describe('when checking if a node has children', () => { describe('and the node has no children', () => { it('should return false', () => { const node = ref(generateNodes(['es'])[0]); const { hasChildren } = useTreeViewNodeChildren(node, emit); expect(hasChildren.value).to.be.false; }); }); describe('and the node has children', () => { it('should return true', () => { const node = ref(generateNodes(['es', ['es', 'es']])[0]); const { hasChildren } = useTreeViewNodeChildren(node, emit); expect(hasChildren.value).to.be.true; }); }); }); describe('when checking if the node may have children', () => { describe('and the node has children', () => { it('should return true', () => { const node = ref(generateNodes(['es', ['es', 'es']])[0]); const { mayHaveChildren } = useTreeViewNodeChildren(node, emit); expect(mayHaveChildren.value).to.be.true; }); }); describe('and the node does not have children', () => { it('should return false', () => { const node = ref(generateNodes(['es'])[0]); const { mayHaveChildren } = useTreeViewNodeChildren(node, emit); expect(mayHaveChildren.value).to.be.false; }); }); describe('and the nodes children are not loaded yet', () => { it('should return true', () => { const node = ref(generateNodes([''], '', null, () => Promise.resolve({}))[0]); node.value.treeNodeSpec._.state.areChildrenLoaded = false; const { mayHaveChildren } = useTreeViewNodeChildren(node, emit); expect(mayHaveChildren.value).to.be.true; }); }); }); describe('when loading children', () => { describe('and children are already loaded', () => { it('should not modify the children list', async () => { const node = ref(generateNodes([''], '', null, async () => Promise.resolve(generateNodes(['es'])))[0]); node.value.treeNodeSpec._.state.areChildrenLoaded = true; const { children, loadChildren } = useTreeViewNodeChildren(node, emit); await loadChildren(); expect(children.value).toHaveLength(0); }); }); describe('and children are currently loading', () => { it('should not modify the children list', async () => { const node = ref(generateNodes([''], '', null, async () => Promise.resolve(generateNodes(['es'])))[0]); node.value.treeNodeSpec._.state.areChildrenLoading = true; const { children, loadChildren } = useTreeViewNodeChildren(node, emit); await loadChildren(); expect(children.value).toHaveLength(0); }); }); describe('and the async loader returns children', () => { it('should set the node children to the async loader method result', async () => { const node = ref(generateNodes([''], '', null, async () => Promise.resolve(generateNodes(['es'])))[0]); const { children, loadChildren } = useTreeViewNodeChildren(node, emit); await loadChildren(); expect(children.value).toHaveLength(1); }); it('should emit the children loaded event', async () => { const node = ref(generateNodes([''], '', null, async () => Promise.resolve(generateNodes(['es'])))[0]); const { children, loadChildren } = useTreeViewNodeChildren(node, emit); await loadChildren(); expect(emit).toHaveBeenCalledWith(TreeEvent.ChildrenLoad, node.value); }); }); describe('and the async loader does not return children', () => { it('should not set the node children', async () => { const node = ref(generateNodes([''], '', null, async () => Promise.resolve([]))[0]); const { children, loadChildren } = useTreeViewNodeChildren(node, emit); await loadChildren(); expect(children.value).toHaveLength(0); }); }); }); describe('when adding a child node', () => { describe('and the callback returns a child node', () => { it('should modify the children list', async () => { const node = ref(generateNodes(['es'], null, async () => Promise.resolve(generateNodes(['es'])[0]))[0]); const { children, addChild } = useTreeViewNodeChildren(node, emit); await addChild(); expect(children.value).toHaveLength(1); }); it('should emit the children added event', async () => { const node = ref(generateNodes(['es'], null, async () => Promise.resolve(generateNodes(['es'])[0]))[0]); const { children, addChild } = useTreeViewNodeChildren(node, emit); await addChild(); expect(emit).toHaveBeenCalledWith(TreeEvent.Add, children.value[0], node.value); }); }); describe('and the callback does not return a node', () => { it('should not modify the children list', async () => { const node = ref(generateNodes(['es'], null, async () => Promise.resolve(null))[0]); const { children, addChild } = useTreeViewNodeChildren(node, emit); await addChild(); expect(children.value).toHaveLength(0); }); }); }); describe('when deleting a child node', () => { it('should remove the child from the children list', () => { const node = ref(generateNodes(['es', ['es', 'es']])[0]); const { children, deleteChild } = useTreeViewNodeChildren(node, emit); const deletedNode = children.value[0]; deleteChild(deletedNode); expect(children.value).toHaveLength(1); }); it('should emit the removal event', () => { const node = ref(generateNodes(['es', ['es', 'es']])[0]); const { children, deleteChild } = useTreeViewNodeChildren(node, emit); const deletedNode = children.value[0]; deleteChild(deletedNode); expect(emit).toHaveBeenCalledWith(TreeEvent.Delete, deletedNode); }); }); });<file_sep>export { default as TreeView } from "../src/components/TreeView.vue";<file_sep>const mimeType = Object.freeze({ Json: 'application/json', PlainText: 'text/plain', TreeViewNode: 'application/x-grapoza-treeviewnode' }); export default mimeType;<file_sep>export default [ { id: 'static-node1', label: 'My First Node', children: [], }, { id: 'static-node2', label: 'My Second Node', children: [ { id: 'static-subnode1', label: 'This is a subnode', children: [], }, { id: 'static-subnode2', label: 'This is another subnode', children: [ { id: 'static-subsubnode1', label: 'An even deeper node', children: [], } ], } ], } ];<file_sep>import { expect, describe, it, beforeEach } from 'vitest'; import { ref } from 'vue'; import { useNodeDataNormalizer } from './nodeDataNormalizer.js'; import { generateNodes } from '../../tests/data/node-generator.js'; describe('nodeDataNormalizer.js', () => { describe('when given minimal model data', () => { let model; beforeEach(() => { model = { id: 'my-node', label: 'My Node' }; const { normalizeNodeData } = useNodeDataNormalizer(ref(model), {}, ref({})); normalizeNodeData(); }); it('should normalize model data', () => { expect(model.id).to.equal('my-node'); expect(model.label).to.equal('My Node'); expect(model.treeNodeSpec.title).to.be.null; expect(model.treeNodeSpec.expandable).to.be.true; expect(model.treeNodeSpec.selectable).to.be.false; expect(model.treeNodeSpec.deletable).to.be.false; expect(model.treeNodeSpec.state).to.exist; expect(model.treeNodeSpec.state.expanded).to.be.false; expect(model.treeNodeSpec.state.selected).to.be.false; expect(model.treeNodeSpec.input).to.be.null; expect(model.treeNodeSpec.state.input).to.not.exist; }); }); describe('when given default model data', () => { let model; beforeEach(() => { model = { id: 'my-node', label: 'My Node', treeNodeSpec: { expandable: true } }; const modelDefaults = { expandable: false, selectable: true, state: { selected: true } }; const { normalizeNodeData } = useNodeDataNormalizer(ref(model), modelDefaults, ref({})); normalizeNodeData(); }); it('should incorporate the default data into the model for unspecified properties', () => { expect(model.treeNodeSpec.selectable).to.be.true; expect(model.treeNodeSpec.state.selected).to.be.true; }); it('should use the model\'s data over the default data for specified properties', () => { expect(model.treeNodeSpec.expandable).to.be.true; }); }); describe('when given a name in the model data for an input node', () => { describe('and it is a non-radio button input', () => { describe('and that name is not a string', () => { let model; beforeEach(() => { model = generateNodes(['ces'])[0]; model.treeNodeSpec.input.name = 42; const { normalizeNodeData } = useNodeDataNormalizer(ref(model), {}, ref({})); normalizeNodeData(); }); it('should set the name to null', () => { expect(model.treeNodeSpec.input.name).to.be.null; }); }); describe('and that trimmed name is an empty string', () => { let model; beforeEach(() => { model = generateNodes(['ces'])[0]; model.treeNodeSpec.input.name = ' '; const { normalizeNodeData } = useNodeDataNormalizer(ref(model), {}, ref({})); normalizeNodeData(); }); it('should set the name to null', () => { expect(model.treeNodeSpec.input.name).to.be.null; }); }); }); describe('and it is a radio button input', () => { let model; beforeEach(() => { model = generateNodes(['r'])[0]; }); describe('and that name is not a string', () => { beforeEach(() => { model.treeNodeSpec.input.name = 42; const { normalizeNodeData } = useNodeDataNormalizer(ref(model), {}, ref({})); normalizeNodeData(); }); it('should set the name to unspecifiedRadioName', () => { expect(model.treeNodeSpec.input.name).to.equal('unspecifiedRadioName'); }); }); describe('and that trimmed name is an empty string', () => { beforeEach(() => { model.treeNodeSpec.input.name = ' '; const { normalizeNodeData } = useNodeDataNormalizer(ref(model), {}, ref({})); normalizeNodeData(); }); it('should set the name to null', () => { expect(model.treeNodeSpec.input.name).to.equal('unspecifiedRadioName'); }); }); }); }); describe('when given a value in the model data for an input node', () => { describe('and it is a radio button input', () => { let model; beforeEach(() => { model = generateNodes(['r'])[0]; model.label = 'A \'Label\' & <Thing>/ "Stuff"'; }); describe('and that value is not a string', () => { beforeEach(() => { model.treeNodeSpec.input.value = 42; const { normalizeNodeData } = useNodeDataNormalizer(ref(model), {}, ref({})); normalizeNodeData(); }); it('should set the value to the label value, minus disallowed characters', () => { expect(model.treeNodeSpec.input.value).to.equal('ALabelThingStuff'); }); }); describe('and that trimmed value is an empty string', () => { beforeEach(() => { model.treeNodeSpec.input.value = ' '; const { normalizeNodeData } = useNodeDataNormalizer(ref(model), {}, ref({})); normalizeNodeData(); }); it('should set the value to the label value, minus disallowed characters', () => { expect(model.treeNodeSpec.input.value).to.equal('ALabelThingStuff'); }); }); }); }); describe('when given an input model with no input state specified', () => { let model; beforeEach(() => { model = generateNodes(['c'])[0]; model.treeNodeSpec.state.input = null; const { normalizeNodeData } = useNodeDataNormalizer(ref(model), {}, ref({})); normalizeNodeData(); }); it('should default the disabled state to false', () => { expect(model.treeNodeSpec.state.input.disabled).to.be.false; }); describe('and the input is a checkbox', () => { it('should set the value of the input to false', () => { expect(model.treeNodeSpec.state.input.value).to.be.false; }); }); }); describe('when given empty action titles', () => { let model; beforeEach(() => { model = generateNodes(['c'])[0]; model.treeNodeSpec.expanderTitle = ''; model.treeNodeSpec.addChildTitle = ''; model.treeNodeSpec.deleteTitle = ''; const { normalizeNodeData } = useNodeDataNormalizer(ref(model), {}, ref({})); normalizeNodeData(); }); it('should set the title properties to null', () => { expect(model.treeNodeSpec.expanderTitle).to.be.null; expect(model.treeNodeSpec.addChildTitle).to.be.null; expect(model.treeNodeSpec.deleteTitle).to.be.null; }); }); });<file_sep># vue-tree vue-tree is a Vue component that implements a Tree View control. Its aim is to provide common tree options in a way that is easy to use and easy to customize. [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) [![Build status](https://ci.appveyor.com/api/projects/status/j8d19gt0vh16amhh/branch/master?svg=true)](https://ci.appveyor.com/project/Gregg/vue-tree/branch/master) ## Full Documentation See the full documentation over at the [project's Github Pages](https://grapoza.github.io/vue-tree/). This includes information on how to use and configure the tree view, features (both existing and planned) as well as some demos. ## Installation Install the component with your favorite package manager: ```shell yarn add @grapoza/vue-tree ``` or ```shell npm install --save @grapoza/vue-tree ``` The default import from this package is the components from the .vue files. In addition to this, pre-compiled versions of the Tree View component and CSS are also available in the package but you will need to reference them manually from your own project. ## Usage If you're using it in a .vue file: ```html <template> <tree-view id="my-tree" :initial-model="dataModel"></tree-view> </template> // Options API <script> import { TreeView } from "@grapoza/vue-tree" export default { components: { TreeView }, data() { return { dataModel: [ { id: "numberOrString", label: "Root Node", children: [ {id: 1, label: "Child Node"}, {id: "node2", label: "Second Child"} ] } ] } } } </script> // Composition API <script setup> import { TreeView } from "@grapoza/vue-tree" const dataModel = ref([ { id: "numberOrString", label: "Root Node", children: [ {id: 1, label: "Child Node"}, {id: "node2", label: "Second Child"} ] } ]) </script> ``` Or, import it into your application: ```javascript import { TreeView } from "@grapoza/vue-tree" Vue.use(TreeView) ``` Then add the component: ```html <tree-view id="my-tree" :initial-model="dataModel"></tree-view> ``` ```javascript export default { data() { return { dataModel: [ {id: "numberOrString", label: "Root Node", children: [ {id: 1, label: "Child Node"}, {id: "node2", label: "Second Child"}] }] } } } ``` <file_sep>import { computed, unref, watch } from 'vue' import { useTreeViewTraversal } from '../treeViewTraversal.js' import { useSelection } from './selection.js'; import SelectionMode from '../../enums/selectionMode.js'; import TreeEvent from '../../enums/event'; /** * Composable dealing with selection handling at the top level of the tree view. * @param {Ref<TreeViewNode[]>} treeModel A Ref to the top level model of the tree * @param {Ref<SelectionMode>} selectionMode A Ref to the selection mode in use for the tree. * @param {Ref<TreeViewNode>} focusableNodeModel A Ref to the currently focusable node model for the tree * @param {Function} emit The TreeView's emit function, used to emit selection events on the tree's behalf * @returns {Object} Methods to deal with tree view level selection */ export function useTreeViewSelection(treeModel, selectionMode, focusableNodeModel, emit) { const { depthFirstTraverse } = useTreeViewTraversal(treeModel); const { deselect, isSelectable, isSelected, select } = useSelection(selectionMode); watch(selectionMode, enforceSelectionMode); watch(focusableNodeModel, (node) => { if (unref(selectionMode) === SelectionMode.SelectionFollowsFocus) { exclusivelySelectNode(node); } }); /** * @returns The value for the tree's aria-multiselectable attribute */ const ariaMultiselectable = computed(() => { // If there's no selectionMode, return null so aria-multiselectable isn't included. // Otherwise, return either true or false as the attribute's value. return selectionMode.value === SelectionMode.None ? null : selectionMode.value === SelectionMode.Multiple; }); /** * Enforces the selection mode for the tree, ensuring only the expected * node or nodes are selected. */ function enforceSelectionMode() { if (unref(selectionMode) === SelectionMode.Single) { enforceSingleSelectionMode(); } else if (unref(selectionMode) === SelectionMode.SelectionFollowsFocus) { enforceSelectionFollowsFocusMode(); } } /** * Enforce single selection mode by deselecting anything except * the first (by depth-first) selected node. */ function enforceSingleSelectionMode() { // For single selection mode, only allow one selected node. let alreadyFoundSelected = false; depthFirstTraverse((node) => { if (node.treeNodeSpec.state && isSelected(node)) { if (alreadyFoundSelected) { deselect(node); } else { alreadyFoundSelected = true; } } }); } function enforceSelectionFollowsFocusMode() { // Make sure the actual focusable item is selected if the mode changes, and deselect all others depthFirstTraverse((node) => { let idPropName = node.treeNodeSpec.idProperty; let focusableIdPropName = focusableNodeModel.value.treeNodeSpec.idProperty; if (node[idPropName] === focusableNodeModel.value[focusableIdPropName]) { if (isSelectable(node)) { select(node); } } else if (isSelected(node)) { deselect(node); } }); } /** * For single selection mode, unselect any other selected node. * For selectionFollowsFocus mode for TreeView, selection state is handled in * the focus watcher in treeViewNodeSelection.js. * In all cases this emits treeNodeSelectedChange for the node parameter. * @param {TreeViewNode} node The node for which selection changed */ function handleNodeSelectedChange(node) { if (unref(selectionMode) === SelectionMode.Single && isSelected(node)) { exclusivelySelectNode(node); } emit(TreeEvent.SelectedChange, node); } /** * Given a node that should remain selected, deselect another selected node. * This is used only when one node at a time can be selected (Single/SelectionFollowsFocus). * @param {TreeViewNode} node The node that should remain selected */ function exclusivelySelectNode(node) { const nodeId = node[node.treeNodeSpec.idProperty]; depthFirstTraverse((current) => { if (isSelected(current) && current[current.treeNodeSpec.idProperty] !== nodeId) { deselect(current); return false; } return true; }); } return { ariaMultiselectable, enforceSelectionMode, handleNodeSelectedChange, } }<file_sep>import { beforeEach, expect, describe, it, vi } from 'vitest'; import { flushPromises, mount } from '@vue/test-utils'; import { defineComponent, ref } from 'vue'; import { useTreeViewNodeFilter } from './treeViewNodeFilter.js'; import { generateNodes } from '../../../tests/data/node-generator.js'; import TreeEvent from '../../enums/event.js'; let emit; function createTestComponent(node, filterMethod) { const TestComponent = defineComponent({ template: "<div></div>", setup() { return useTreeViewNodeFilter(node, emit) } }); const wrapper = mount(TestComponent, { global: { provide: { 'filterMethod': filterMethod } } }); return wrapper; } function setChildFilteredState(child, forNode, forSubnodes) { // The composable only filters for the current node; in a real tree, each node would have its own watch. // Simulate the subnodes states here. child.treeNodeSpec._.state.matchesFilter = forNode; child.treeNodeSpec._.state.subnodeMatchesFilter = forSubnodes; } describe('treeViewNodeFilter.js', () => { let node; let wrapper; beforeEach(() => { emit = vi.fn(); }); describe('when the filterMethod is set', () => { describe('always', () => { beforeEach(async () => { node = ref(generateNodes(['fe', ['e', 's']])[0]); wrapper = createTestComponent(node, (n) => n.treeNodeSpec.expandable); setChildFilteredState(node.value.children[0], true, false); setChildFilteredState(node.value.children[1], false, false); await flushPromises(); }); it('should set isFilteringEnabled to true', () => { expect(wrapper.vm.isFilteringEnabled).to.be.true; }); it('should only include subnodes included in the filter in filteredChildren', () => { expect(wrapper.vm.filteredChildren.length).to.equal(1); expect(wrapper.vm.filteredChildren[0].id).to.equal('n0n0'); }); }); describe('and the node matches the filter', () => { beforeEach(async () => { node = ref(generateNodes(['fe', ['e', 's']])[0]); wrapper = createTestComponent(node, (n) => n.treeNodeSpec.expandable); await flushPromises(); }); it('should set filterIncludesNode to true', () => { expect(wrapper.vm.filterIncludesNode).to.be.true; }); }); describe('and the node does not match the filter', () => { beforeEach(async () => { node = ref(generateNodes(['fe', ['e', 's']])[0]); wrapper = createTestComponent(node, (n) => n.treeNodeSpec.selectable); await flushPromises(); }); describe('and the node has filtered children', () => { beforeEach(async () => { setChildFilteredState(node.value.children[0], true, false); await flushPromises(); }); it('should set filterIncludesNode to true', () => { expect(wrapper.vm.filterIncludesNode).to.be.true; }); }); describe('and the node has no filtered children', () => { beforeEach(async () => { setChildFilteredState(node.value.children[0], false, false); setChildFilteredState(node.value.children[1], false, false); await flushPromises(); }); it('should set filterIncludesNode to false', () => { expect(wrapper.vm.filterIncludesNode).to.be.false; }); }); }); describe('and children are loaded', () => { describe('and the node has filtered children', () => { beforeEach(async () => { node = ref(generateNodes(['fe', ['e']])[0]); wrapper = createTestComponent(node, (n) => n.treeNodeSpec.expandable); setChildFilteredState(node.value.children[0], true, false); await flushPromises(); }); it('should set mayHaveFilteredChildren to true', () => { expect(wrapper.vm.mayHaveFilteredChildren).to.be.true; }); }); describe('and the node has no filtered children', () => { beforeEach(async () => { node = ref(generateNodes(['fe', ['e']])[0]); wrapper = createTestComponent(node, (n) => n.treeNodeSpec.expandable); setChildFilteredState(node.value.children[0], false, false); await flushPromises(); }); it('should set mayHaveFilteredChildren to false', () => { expect(wrapper.vm.mayHaveFilteredChildren).to.be.false; }); }); }); describe('and children are not loaded', () => { beforeEach(async () => { node = ref(generateNodes(['fe'])[0]); node.value.treeNodeSpec.loadChildrenAsync = () => { }; node.value.treeNodeSpec._.state.areChildrenLoaded = false; wrapper = createTestComponent(node, (n) => n.treeNodeSpec.expandable); await flushPromises(); }); it('should set mayHaveFilteredChildren to true', () => { expect(wrapper.vm.mayHaveFilteredChildren).to.be.true; }); }); describe('and the node changes to not match the filter', () => { beforeEach(async () => { node = ref(generateNodes(['fe'])[0]); wrapper = createTestComponent(node, (n) => n.treeNodeSpec.expandable); await flushPromises(); node.value.treeNodeSpec.expandable = false; await flushPromises(); }); it('should set the node as not matching the filter', () => { expect(node.value.treeNodeSpec._.state.matchesFilter).to.be.false; }); describe('and it is the focused node', () => { it('should emit the requestFirstFocus event', () => { expect(emit).toHaveBeenCalledWith(TreeEvent.RequestFirstFocus, true); }); }); }); describe('and the node changes to match the filter', () => { beforeEach(async () => { node = ref(generateNodes(['f'])[0]); wrapper = createTestComponent(node, (n) => n.treeNodeSpec.expandable); await flushPromises(); node.value.treeNodeSpec.expandable = true; await flushPromises(); }); it('should set the node as matching the filter', () => { expect(node.value.treeNodeSpec._.state.matchesFilter).to.be.true; }); }); }); describe('when the filterMethod is not set', () => { beforeEach(async () => { node = ref(generateNodes(['fe', ['e', 's']])[0]); wrapper = createTestComponent(node, null); // The composable only filters for the current node; in a real tree, each node would have it's own watch. // Simulate the subnodes states here. node.value.children[0].treeNodeSpec._.state.matchesFilter = true; node.value.children[0].treeNodeSpec._.state.subnodeMatchesFilter = false; node.value.children[1].treeNodeSpec._.state.matchesFilter = false; node.value.children[1].treeNodeSpec._.state.subnodeMatchesFilter = false; await flushPromises(); }); it('should set isFilteringEnabled to false', () => { expect(wrapper.vm.isFilteringEnabled).to.be.false; }); }); });<file_sep>import { computed, watch } from 'vue'; import { useExpansion } from './expansion.js'; import { useTreeViewNodeChildren } from '../children/treeViewNodeChildren.js'; import { useTreeViewNodeFilter } from '../filter/treeViewNodeFilter.js'; import TreeEvent from '../../enums/event.js'; /** * Composable dealing with expansion handling at the tree view node. * @param {Ref<TreeViewNode>} nodeModel A Ref to the model of the node * @param {Function} emit The TreeViewNode's emit function, used to emit selection events on the node's behalf * @returns {Object} Methods to deal with tree view node level expansion */ export function useTreeViewNodeExpansion(nodeModel, emit) { const { isExpandable, isExpanded, } = useExpansion(); const { loadChildren, } = useTreeViewNodeChildren(nodeModel, emit); const { mayHaveFilteredChildren, } = useTreeViewNodeFilter(nodeModel, emit); const ariaExpanded = computed(() => canExpand.value ? isNodeExpanded() : null); const canExpand = computed(() => { return isNodeExpandable() && mayHaveFilteredChildren.value; }); watch(() => nodeModel.value.treeNodeSpec.state.expanded, async function () { emit(TreeEvent.ExpandedChange, nodeModel.value); // If children need to be loaded asynchronously, load them. if (isNodeExpanded()) { await loadChildren(); } }); function isNodeExpandable() { return isExpandable(nodeModel); } function isNodeExpanded() { return isExpanded(nodeModel); } function collapseNode() { if (canExpand.value && isNodeExpanded()) { nodeModel.value.treeNodeSpec.state.expanded = false; return true; } return false; } function expandNode() { if (canExpand.value && !isNodeExpanded()) { nodeModel.value.treeNodeSpec.state.expanded = true; return true; } return false; } function toggleNodeExpanded() { return isNodeExpanded() ? collapseNode() : expandNode(); } return { ariaExpanded, canExpand, collapseNode, expandNode, isNodeExpandable, isNodeExpanded, toggleNodeExpanded, }; }
d07c587e882169a4d46b4231aeb3422a2a32c18a
[ "JavaScript", "Markdown" ]
54
JavaScript
grapoza/vue-tree
387b8c2baa37c5dc560d43e48bcd49c2388fcd00
de4431a0bf9ea4a8bc92e88fff73da2ef9618b56
refs/heads/master
<file_sep>ROOT_DIR=$1 for d in $ROOT_DIR/*; do ln -vs "`pwd`/tools/SkAVG" "`pwd`/$d/" ln -vs "`pwd`/tools/config_2.txt" "`pwd`/$d/config.txt" ln -vs "`pwd`/tools/calc_rdf_avg" "`pwd`/$d/calc_rdf" done <file_sep># # Monte carlo simulation for Ising model # Author: <NAME> <<EMAIL>> # # import random import math import itertools #SEED = 7777 #random.seed(SEED) class Lattice(object): """ 2-D lattice """ size = 0 energy = 0 _lattice = [] _dictionary = [] _all_coordinate = [] def __init__(self, lattice_size): self.size = lattice_size self._dictionary = (-1, 1) self.randomize() self.total_energy() ## cross product to get all coordinate self._all_coordinate = list(itertools.product(range(self.size), range(self.size))) def randomize(self): """ Randomize lattice >>> len(t._lattice) 10 >>> len(t._lattice[0]) 10 """ # initialize, clear lattice self._lattice = [] for n in range(self.size): self._lattice.append([ random.choice(self._dictionary) for x in range(self.size) ]) def total_energy(self): """ Return total energy of lattice """ e = 0.0 for pos in self._all_coordinate: e += sum(self[pos] * self.get_nb_values(pos)) self.energy = e return e def energy_difference(self, position): """ Return energy change between two configuration that differ only by one spin (on position 'position') """ delta = 2 * self[position] * sum(self.get_nb_values(position)) return delta def total_magnetization(self, per_spin = False): """ Return total magnetization """ M = sum([ self[pos] for pos in self._all_coordinate ]) if per_spin: M = M / float(self.size**2) return M def flip_spin(self, position, random=False): """ Flip spin on 'position' Return new spin value """ if random: position = self.get_random_spin_position() self[position] *= -1 return self[position] def get_nb_position(self, position): """ Return neigbours spin value in the format of tuple: (top, right, down, left) >>> n = lattice.get_nb_position((0,0)) >>> n == (1, 1, self.size - 1, self.size - 1) """ order = (self._get_top, self._get_right, self._get_down, self._get_left) return tuple([ fun(position) for fun in order ]) def get_nb_values(self, position): """ Return value of neigbours spins around position """ position = self.get_nb_position(position) values = tuple([ self[pos] for pos in position ]) return values def get_random_spin_position(self): """ Return random spin position """ try: random_position = random.choice(list(self._all_coordinate)) except: from pdb import set_trace;set_trace() ############################## Breakpoint ############################## return random_position ## get positions def _get_left(self, cp): return ((cp[0] - 1) % self.size, cp[1]) def _get_right(self, cp): return ((cp[0] + 1) % self.size, cp[1]) def _get_top(self, cp): return (cp[0], (cp[1] + 1) % self.size) def _get_down(self, cp): return (cp[0], (cp[1] - 1) % self.size) ## for containers def __getitem__(self, key): try: return self._lattice[key[0]][key[1]] except: from pdb import set_trace;set_trace() ############################## Breakpoint ############################## def __setitem__(self, key, value): self._lattice[key[0]][key[1]] = value def __delitem(self, key): self._lattice[key[0]][key[1]] = None def __contains__(self, key): x = key[0] y = key[1] size = self.size - 1 if x > 0 and x < size and y > 0 and y < size: return True else: return False def copy(self): import copy data = copy.copy(self._lattice) dictionary = copy.copy(self._dictionary) self._lattice = None self._dictionary = [] try: c = copy.copy(self) c._lattice = data c._dictionary = dictionary finally: self._lattice = data self._dictionary = dictionary return c class MC(object): ## MC config sweeps = 0 eq_time = 0 # lattice lattice_size = 0 lattice_size_sq = 0 lattice = [] ## physical constants _T = None J = 1 ## improvments, precompute exp vector _exp = [0]*9 ## stats acceptance = 0 def __init__(self, size, T, sweeps, eq_time = 0): """ @parms size - size of lattice T - temperature sweeps - number of sweeps eq_time - equilibrium time """ self.lattice_size = size self.lattice_size_sq = size**2 self.T = T self.lattice = Lattice(size) self.lattice.energy *= self.J self.sweeps = sweeps self.eq_time = eq_time @property def T(self): return self._T @T.setter def T(self, value): self._T = value ## precomputate exponential values for given temperatur self._exp[0] = 1 self._exp[4] = math.exp( (-1.0/self._T)*4 ) self._exp[8] = math.exp( (-1.0/self._T)*8 ) def _step(self): """ One step Flip random spin and check energy difference if is lower than 0, accept, otherwise compute exp(-dE/kbT) and check Return if accept or reject new configuration """ spin_pos = self.lattice.get_random_spin_position() deltaE = self.J * self.lattice.energy_difference(spin_pos) accept = False if deltaE < 0: accept = True else: r = random.random() if r <= self._exp[deltaE]: accept = True if accept: ## flip spin self.lattice.energy += deltaE self.lattice.flip_spin(spin_pos) return accept def run(self): """ Run simulation """ magnetization_vector = [] energy_vector = [] for sweep in xrange(self.sweeps): for i in xrange(self.lattice_size_sq): step = self._step() self.acceptance += int(step) ## if sweep >= self.eq_time: magnetization_vector.append(self.lattice.total_magnetization()) energy_vector.append(self.lattice.energy) return { 'magnetization': magnetization_vector, 'energy': energy_vector } ## for doc test #if __name__ == "__main__": # import doctest # doctest.testmod(extraglobals={'lattice': Lattice(10)}) <file_sep>import os import sys import numpy as np from scipy import constants as const import argparse as arg import glob from lib.tools import f_avg, f_avg2, f_cv2, avg_dict, save_dict_to_csv parser = arg.ArgumentParser(description="Process files") parser.add_argument('--config-file', help="Config file", dest="cfile") parser.add_argument('-file', help="Input file", type=str, dest="file") parser.add_argument('-rdir', help="Result dir", type=str, default=".") parser.add_argument('-f', help="From temp", default=0.0, type=float) parser.add_argument('-t', help="To: temp", default=None, type=float) parser.add_argument('-ac', help="Autocorrelation step", default=1, type=int) parser.add_argument('-fs', help="From step", default=0, type=int) parser.add_argument('-N', help="Number of monomers", type=int) parser.add_argument('--exclude', action='append', help="Exclude temperature", default=[], type=list) parser.add_argument('-setup', default=[''], type=list) parser.add_argument('-prefix', default='', type=str) parser.add_argument('-double', default=False, action='store_true') parser.add_argument('-e2e', default=False, action='store_true') parser.add_argument('-c', default=False, action='store_true') result = parser.parse_args() parser = result FROM_TEMP = result.f TO_TEMP = result.t EXCLUDED_TEMP = result.exclude NUMBER_OF_MONOMERS = result.N AC_STEP = result.ac FROM_STEP = result.fs RESULT_DIR = result.rdir SETUP_NAME = result.setup PREFIX = result.prefix FILES = {} try: config_file = result.cfile execfile(config_file) except: print "Can't read config file" AC_STEP = AC_STEP if AC_STEP > 0 else 1 ########## print config print "config_file:", config_file print "FROM_TEMP:", FROM_TEMP print "TO_TEMP:", TO_TEMP print "FROM_STEP:", FROM_STEP print "EXCLUDED_TEMP:", EXCLUDED_TEMP print "AUTOCORRELATION:", AC_STEP print "NUMBER_OF_MONOMERS:", NUMBER_OF_MONOMERS print "FILES:", FILES ######################### ### process files data_e = {} t_data_e = {} data_rg = {} t_data_rg = {} t_data_rg_others = {} data_e2e = {} t_data_e2e = {} dirs = [] files = [] print "Found files" f = result.file valid_file = False for s in SETUP_NAME: if s in f: valid_file = True break if not valid_file: sys.exit(1) csv_basename = f.replace("/", "_") if FILES: fk = FILES.keys() for x in fk: if x in f: FROM_STEP = FILES[x]['from_step'] print "FROM_STEP for file %s: %d" % (f, FROM_STEP) try: data = np.loadtxt(f, delimiter=';', skiprows=0) temp_list = set() for line in data: #sl = line.split(';') temp = float(line[1]) temp_list.add(temp) step = float(line[0]) if (temp <= FROM_TEMP) or \ (TO_TEMP and temp > TO_TEMP) or \ (EXCLUDED_TEMP and temp in EXCLUDED_TEMP): continue if not (step % AC_STEP == 0) or step < FROM_STEP: continue e = float(line[-1]) e2e = float(line[-2])**2 rg = float(line[2]) try: if step in t_data_e[temp]: t_data_e[temp][step].append(e / float(2)) else: t_data_e[temp][step] = [e / float(2)] except Exception, exception: t_data_e[temp] = {step: [e / float(2)]} try: if step in t_data_rg[temp]: t_data_rg[temp][step].append(rg) else: t_data_rg[temp][step] = [rg] except: t_data_rg[temp] = {step: [rg]} try: if step in t_data_e2e[temp]: t_data_e2e[temp][step].append(e2e) else: t_data_e2e[temp][step] = [e2e] except: t_data_e2e[temp] = {step: [e2e]} print "Process:", f, ",".join(map(str, temp_list)) del data except Exception, e: print "Fail to process:", f, e error_e = [] error_rg = [] data_e = avg_dict(t_data_e) data_rg = avg_dict(t_data_rg) data_e2e = avg_dict(t_data_e2e) for k,v in data_e.iteritems(): del v[v.index(max(v))] del v[v.index(min(v))] data_e[k] = v error_e.append((k, np.std(v)/np.math.sqrt(len(v)))) for k,v in data_rg.iteritems(): del v[v.index(max(v))] del v[v.index(min(v))] data_rg[k] = v error_rg.append((k, np.std(v)/np.math.sqrt(len(v)))) temp = data_e.keys() temp.sort() e = [] e2 = [] rg = [] e2e = [] for k,v in data_e.iteritems(): print "E", k, len(v) e.append((k, f_avg(v))) e2.append((k, f_avg2(v))) for k,v in data_rg.iteritems(): rg.append((k, f_avg(v))) e2e.append((k, f_avg(data_e2e[k]))) ## sort e.sort(key = lambda x: x[0]) e2.sort(key = lambda x: x[0]) rg.sort(key = lambda x: x[0]) e2e.sort(key = lambda x: x[0]) error_e.sort(key = lambda x: x[0]) error_rg.sort(key = lambda x: x[0]) error_e = map(lambda x: x[1], error_e) error_rg = map(lambda x: x[1], error_rg) #print "\n".join(map(str, error_e)) #print "\n".join(map(str, error_rg)) e = map(lambda x: x[1], e) e2 = map(lambda x: x[1], e2) rg = map(lambda x: x[1], rg) e2e = map(lambda x: x[1], e2e) cv = f_cv2(data_e, NUMBER_OF_MONOMERS) #cv = map(lambda x: x, f_cv(e, e2, temp)) try: os.mkdir(RESULT_DIR) except: pass e_all = RESULT_DIR + "/" + PREFIX + "e_all.csv" rg_all = RESULT_DIR + "/" + PREFIX + "rg_all.csv" cv_all = RESULT_DIR + "/" + PREFIX + "cv_all.csv" if not parser.c: csv_e = open(e_all, "a+") csv_rg = open(rg_all, "a+") csv_cv = open(cv_all, "a+") else: csv_e = sys.stdout csv_rg = sys.stdout csv_cv = sys.stdout print "E" csv_e.writelines([ "%f;%f\n" % (temp[x], e[x]) for x in range(len(temp)) ]) if not parser.c: csv_e.close() print "RG" csv_rg.writelines([ "%f;%f\n" % (temp[x], rg[x]) for x in range(len(temp)) ]) if not parser.c: csv_rg.close() print "CV" csv_cv.writelines([ "%f;%f\n" % (temp[x], cv[x]) for x in range(len(temp)) ]) if not parser.c: csv_cv.close() print "Save:", e_all, cv_all, rg_all <file_sep>#!/bin/bash ##obliczanie RDF ls *.xyz | xargs -i ./Sk3D 1 {} config.txt cat *.sff >> out.all ./Sk3D 2 out.all<file_sep>""" Main MC class for Monte Carlo simulation Author: <NAME> <<EMAIL>> """ from lib import Box, Chain, Lattice, Polymer, tools import kyotocabinet as kb import logging import numpy as np import settings import sys import time class MC(object): start_step = None stop_step = None current_step = None box = None current_state = None stop_simulation = False hdfTable = None # # STATES START = 0 STOP = 100 def __init__(self, steps, obj=None, start_step=0): self.start_step = start_step self.current_step = start_step self.stop_step = steps if isinstance(obj, Box): # # when box is loaded from file self.box = obj Lattice.box_size = obj.box_size settings.BOX_SIZE = obj.box_size elif isinstance(obj, Chain): self.box = Box(settings.BOX_SIZE, localT=settings.LOCAL_T) self.box.add_chain(obj) elif isinstance(obj, list): self.box = Box(settings.BOX_SIZE, localT=settings.LOCAL_T) for c in obj: self.box.add_chain(c) # # load some specific settings Lattice.NEIGHBOURS_POSITION = tools.load_file(settings.ROOT_DIR + "neighbours.dump", {}) if self.box.localT in settings.EXP_TABLES: settings.EXP_TABLE = settings.EXP_TABLES[self.box.localT] else: settings.EXP_TABLE = tools.load_file(settings.ROOT_DIR + \ settings.FILES_TEMPLATE['exp'] % self.box.localT, {}) settings.EXP_TABLES[self.box.localT] = settings.EXP_TABLE def prepare_db(self): """ Prepare database to store values """ db_filename = settings.BASE_DIR + "/" + "database.kch" self.db = kb.DB() if not self.db.open(db_filename, kb.DB.OWRITER | kb.DB.OCREATE): print >> sys.stderr, "open error:" + str(self.db.error()) sys.exit(1) print "DB:", db_filename def change_stop_step(self, stop_step): """ Set new value of stop step, need for FOPT alghoritm """ self.stop_step = stop_step logging.info("New value of stop_step: %d" % stop_step) if self.stop_simulation: logging.info("Set False to stop simulation") self.stop_simulation = False def change_current_step(self, current_step): """ Set new value of current step, need for prevent dead lock on MPI """ # if current_step != self.current_step: self.current_step = current_step # logging.debug("New value of current_step: %d" % self.current_step) def set_stop_simulation(self): self.stop_simulation = True logging.info("Set stop simulation") def run(self): """ Run Monte Carlo simulation """ self.start_step = self.start_step + settings.DELTA_STEP print "="*10 print "Local T:", self.box._localT print "BOX size:", self.box.box_size print "Lattice size:", Lattice.box_size, "/", self.box.lattice.box_size print "Number of chains:", len(self.box.chain_list) print "Rank:", settings.RANK, "/", settings.SIZE print "Logging file:", settings.DIRS['log'] + settings.EXPERIMENT_NAME + ".log" print "BASE_DIR:", settings.BASE_DIR print "Dirs:" for name, dir_name in settings.DIRS.items(): print " ", name, ":", dir_name print "=" * 10 print "SETTINGS:" print "\tMC steps:", settings.MC_STEPS print "\t\tMC start_step:", self.start_step print "\t\tMC stop_step:", self.stop_step print "\tFREQ_SWAP:", settings.FREQ_SWAP print "\tFREQ_COLLECT", settings.FREQ_COLLECT print "\tPERFORM_SWAP:", settings.PERFORM_SWAP print "\tFREQ_DATA:", settings.FREQ_DATA print "\tFREQ_CALC:", settings.FREQ_CALC print "\tFREQ_SNAPSHOT:", settings.FREQ_SNAPSHOT print "\tFREQ_ATHERMAL:", settings.FREQ_ATHERMAL print "\tFREQ_COOLING:", settings.FREQ_COOLING print "\tPT:", settings.PT print "\tPT_MODULE:", settings.PT_MODULE print "\tFOPT:", settings.FOPT print "="*10 print "Chains" m_set = set() for c in range(len(self.box.chain_list)): print "\t%d: %s" % (c, "".join([ m.name for m in self.box.chain_list[c].chain ])) for m in self.box.chain_list[c].chain: m_set.add((m.name, str(m.interaction_table))) print "\tMonomers:" for m in m_set: print "\t %s: %s" % (m[0], m[1]) print "="*10 # # mc step step_time = 0.0 # self.prepare_hdf_table() self.prepare_db() settings.FREQ_COLLECT = settings.FREQ_COLLECT + settings.FREQ_ATHERMAL + settings.FREQ_COOLING settings.FREQ_COLLECT2 = settings.FREQ_ATHERMAL + settings.FREQ_COOLING # # second is used in parallel tempering where we want # # to switch between temperatures after athermal # # but we want to not collect first part of data # ## start simulations simulation_time = time.time() xrange_chains = [None] * self.box.number_of_chains for c in self.box.chain_list: xrange_chains[c.idx] = xrange(c._total_length / 8) # # MOVES ch = Polymer.Chain break_move = [ch.PULL_MOVE, ch.PULL_MOVE, ch.B_SNAKE, ch.E_SNAKE] # break_move = [] m = (ch.B_ROTATE, ch.E_ROTATE, ch.S_ROTATE, ch.B_SNAKE, ch.E_SNAKE) m_len = len(m) b_len = len(break_move) # # variables acceptance_ratio = dict(zip(ch.TYPE_OF_MOVE, [0] * len(ch.TYPE_OF_MOVE))) reject_ratio = acceptance_ratio.copy() total_acceptance = 0 total_reject = 0 # step file step_file = open(settings.DIRS['calc'] + "step", "w+") # # MC SWEEP while loop while self.current_step < self.stop_step and not self.stop_simulation: # print settings.PT_MODULE.rank if settings.PT else 0, 'step', step step = self.current_step if settings.TIME: start_time = time.time() move_name = "" settings.CURRENT_STEP = self.current_step # # step environment changes like athermal heating and linear cooling if (step < settings.FREQ_ATHERMAL or settings.LOCAL_T < 0.0) and not self.box.athermal_state: logging.info("Launch athermal mode for %d" % settings.FREQ_ATHERMAL) self.box.athermal_state = True elif step >= settings.FREQ_ATHERMAL and self.box.athermal_state: if self.box.athermal_state: delta_time = time.time() - simulation_time logging.info("Switch off athermal state on %d (time: %f)" % (step, delta_time)) # end of athermal state, if we use parallel tempering, try to find lowest # enery configuration in replicas and run every replica from it self.box.athermal_state = False move = False accept = 0 reject = 0 for rr_chain in range(self.box.number_of_chains): if self.box.number_of_chains == 1: chain = self.box.chain_list[0] else: chain_idx = np.random.randint(0, self.box.number_of_chains) chain = self.box.chain_list[chain_idx] move_time = 0.0 # for rr_chain in xrange_chains[chain.idx]: for rr_chain in [1]: if settings.TIME: start_move = time.time() if settings.TIME: m_time = time.time() # random move move_idx = np.random.randint(0, b_len) type_of_move = break_move[move_idx] move = chain.move(type_of_move) if settings.TIME: m_time = time.time() - m_time if settings.TIME: move_time += m_time if settings.TIME: stop_move = time.time() logging.info("Move %s: %f" % (chain.move_name, stop_move - start_move)) if move: acceptance_ratio[chain.move_name] += 1 total_acceptance += 1 accept += 1 else: total_reject += 1 reject_ratio[chain.move_name] += 1 reject += 1 if settings.TIME: move_name = chain.move_name if settings.DEBUG: print chain.move_name, move if settings.TIME: print step, time.time() - start_time, 'acc', accept, 'rej', reject, 'move_time_avg', move_time # # performe some saves rare_save = False if step <= settings.FREQ_COLLECT: rare_save = (step % settings.RARE_SAVE == 0) if settings.TIME: chain_move_time = time.time() if (step % 10000) == 0: step_file.write("%d\n" % step) step_file.flush() # save some data if (step >= settings.FREQ_COLLECT and (step % settings.FREQ_SNAPSHOT) == 0) or rare_save: self.db["jmol_%d" % step ] = self.box.jmol_snapshot_string() if (step >= settings.FREQ_COLLECT and (step % settings.FREQ_CALC) == 0): for chain in self.box.chain_list: chain.calculate_values() val = [step, self.box._localT] + chain.last_values self.db["values_%d" % step ] = val # ## swap if settings.PERFORM_SWAP: if step >= settings.FREQ_COLLECT2 and settings.PT and ((step + 1) % settings.FREQ_SWAP) == 0: self.box.swap() data_file = settings.DIRS['calc'] + settings.FILES_TEMPLATE['pt_hist'] % (settings.RANK) tools.save_file(data_file, self.box.temperature_history) if settings.TIME: stop_time = time.time() delta_move_time = chain_move_time - start_time logging.info("%s;%f;%d" % (move_name, delta_move_time, move)) # # END of simulation block # # increment step counter step += 1 self.current_step += 1 if step == self.stop_step: # # last step of simulation, we check feedback if settings.PERFORM_SWAP and settings.PT and settings.FOPT: logging.info("Perform Feedback optimization") settings.PT_MODULE.calculate_round_trip() ################################## simulation_time = time.time() - simulation_time # data_file_name = settings.FILES['data'] % (step) # tools.save_file(data_file_name, self.box) # jmol_file = settings.FILES['model'] % (step) # self.box.jmol_snapshot(jmol_file) self.db['jmol_%d' % step ] = self.box.jmol_snapshot_string() # self.values_tbl.flush() # # save remaning values # for k,v in values_to_save.iteritems(): # f = values_files[k] # f.writelines(v) # f.close() # # save histograms if settings.PERFORM_SWAP and settings.PT: settings.PT_MODULE.save_histograms() print "="*5, "Rank", settings.RANK, "of", settings.SIZE, "="*5 print "Total time:", simulation_time print "Rank:", settings.RANK print "Steps:", self.stop_step print "Chains:", len(self.box.chain_list) for chain in self.box.chain_list: print "\tChain: %s" % chain print "\t Min Energy:", chain.min_energy print "\t Min Rg:", chain.min_rg for i in range(len(Chain.TYPE_OF_MOVE)): print "\t +%s: %d" % (chain.TYPE_OF_MOVE[i], chain.MOVE_STATS[i]) print "Total accepted: ", total_acceptance print "Total reject: ", total_reject print "Acceptance move:" for k, v in acceptance_ratio.iteritems(): print " +%s: %s" % (str(k), str(v)) print "Reject move:" for k, v in reject_ratio.iteritems(): print " +%s: %s" % (str(k), str(v)) print "Temperature: ", self.box._localT print "="*10 <file_sep>#!/bin/bash #$ -cwd #$ -m bes #$ -M <EMAIL> #$ -V #$ -j y #$ -notify #$ -pe mpich2 4 MY_HOST="`hostname`" MY_DATE="`date`" MY_LOG_DIR="${JOB_ID}_log" mkdir $MY_LOG_DIR export SGE_STDOUT_PATH=$SGE_CWD_PATH/$MY_LOG_DIR/${JOB_NAME}.o${JOB_ID} export SGE_STDERR_PATH=$SGE_CWD_PATH/$MY_LOG_DIR/${JOB_NAME}.e${JOB_ID} echo "Running on $MY_HOST at $MY_DATE" echo "Running environment:" env echo "=======================================" echo "PE_HOSTFILE file:" cat $PE_HOSTFILE echo "=======================================" echo JOB_NAME="$JOB_NAME" echo JOB_ID="$JOB_ID" echo QUEUE="$QUEUE" echo SGE_CWD_PATH=$SGE_CWD_PATH echo PATH=$PATH echo NSLOTS=$NSLOTS echo SGE_STDIN_PATH=$SGE_STDIN_PATH echo SGE_STDOUT_PATH=$SGE_STDOUT_PATH echo SGE_STDERR_PATH=$SGE_STDERR_PATH echo SGE_O_HOST=$SGE_O_HOST echo SGE_O_PATH=$SGE_O_PATH echo MPICH_HOME=$MPICH_HOME echo MY_TEST=$MY_TEST echo "================================================================" #INITIAL_CONFIGURATION="`pwd`/17_box_999999.dump" #INITIAL_CONFIGURATION="`pwd`/experiment/exp5_0/const_t_1_14_32_32_32_5/data/box_900000.dump" #echo INITIAL_CONFIGURATION="$INITIAL_CONFIGURATION" mpiexec -n $NSLOTS python ../code/intraglobular/src/tools/jmol_files_sort.py -r experiment -e exp8d -d exp8d_xyz echo "STOP on `date`" post_process.sh $JOB_ID $MY_LOG_DIR <file_sep>""" Definition of monomers for HP Model """ from lib.Monomer import Monomer class TypeH(Monomer): name = "H" interaction_table = {'H': -1, 'P': 0} class TypeP(Monomer): name = "P" interaction_table = {'H': 0, 'P': 0} <file_sep>import os import sys from mpi4py import MPI root_dir = sys.argv[1] comm = MPI.COMM_WORLD rank = comm.Get_rank() size = comm.Get_size() dirs = [ os.path.realpath(root_dir + "/" + o) for o in os.listdir(root_dir) ] dirs_len = len(dirs) chunk_len = dirs_len / size print "="*10 print "Total dirs", dirs_len print "Chunk len", chunk_len print "Rank", rank print "Size", size print "="*10 if rank == size - 1: dirs = dirs[chunk_len*rank:] else: dirs = dirs[chunk_len*rank: chunk_len*rank + chunk_len] for d in dirs: os.chdir(d) try: print "Run calc_rdf in", d os.system("./calc_rdf") except: print "Problem in", d <file_sep># # Author: <NAME> <<EMAIL>> # Define experiments # from lib import Polymer, tools from lib.Experiment import Experiment from lib.monomers import MonomersMJ import bio import settings SEQUENCE_DB = { 'seq1': ("L"*10+"K"*10)*12, 'seq2': ("L"*10+"K"*10)*12, 'seq3': ("L"*10+"N"*10)*12, # Lys + Asn 'seq4': ("G"*10 + "Y"*10) * 12 # Gly (hydrophobic) - Tyr (hydrophylic) } class ExperimentMJa(Experiment): name = "mj240a" box_size = (240, 240, 240) length = 240 global_tag = 113 seq = 'seq1' freq = { 'mc_steps': 40000000, 'collect': 10000000, 'snapshot': 1000, 'calc': 100, 'data': 100, 'pt': 200, 'athermal': 1000000, 'cooling': 0 } def init(self): self.epsilon = 1 self.prepare_chain() settings.BASE_DIR = self.get_base_dir() settings.EXPERIMENTAL_ROOT_DIR = settings.BASE_DIR if settings.CREATE_DIR_STRUCTURE: tools.create_dir(settings.BASE_DIR) def prepare_chain(self): length = self.length chain_seq = bio.prepare_sequence(bio.seq1_3(SEQUENCE_DB[self.seq]), MonomersMJ) self.chain_seq = Polymer.Chain(chain_seq) return self.chain_seq def c1_setup(self): name = "c1" self._setup(name, 0.5, 40.0, 100, swap = False) self.set_collect(**self.freq) settings.PERFORM_SWAP = False return (name, self.chain_seq) def c2_setup(self): name = "c2" self._setup(name, 20.0, 40.0, 200, swap = False) self.set_collect(**self.freq) settings.PERFORM_SWAP = False return (name, self.chain_seq) def c3_setup(self): name = "c3" self.temp_list = [50.0, 100.0, 200.0, 500.0, 1000.0, 2000.0] self._setup(name, 50.0, 2000.0, 200, swap = False) self.set_collect(**self.freq) settings.PERFORM_SWAP = False return (name, self.chain_seq) class ExperimentMJb(Experiment): name = "mj240b" box_size = (240, 240, 240) length = 240 global_tag = 118 seq = 'seq3' freq = { 'mc_steps': 40000000, 'collect': 10000000, 'snapshot': 1000, 'calc': 100, 'data': 100, 'pt': 200, 'athermal': 1000000, 'cooling': 0 } def init(self): self.epsilon = 1 self.prepare_chain() settings.BASE_DIR = self.get_base_dir() settings.EXPERIMENTAL_ROOT_DIR = settings.BASE_DIR if settings.CREATE_DIR_STRUCTURE: tools.create_dir(settings.BASE_DIR) def prepare_chain(self): length = self.length chain_seq = bio.prepare_sequence(bio.seq1_3(SEQUENCE_DB[self.seq]), MonomersMJ) self.chain_seq = Polymer.Chain(chain_seq) return self.chain_seq def c1_setup(self): name = "c1" self._setup(name, 0.5, 40.0, 100, swap = False) self.set_collect(**self.freq) settings.PERFORM_SWAP = False return (name, self.chain_seq) class ExperimentMJc(ExperimentMJb): name = "mjGlyTyr" box_size = (240, 240, 240) length = 240 global_tag = 119 seq = 'seq4' class Experiment3MTS(Experiment): name = "3mts" box_size = (64, 64, 64) length = 64 global_tag = 118 seq = 'GEVEYLCDYKKIREQEYYLVKWRGYPDSESTWEPRQNLKCVRILKQFHKDLERELLRRHHRSKT' freq = { 'mc_steps': 40000000, 'collect': 10000000, 'snapshot': 1000, 'calc': 100, 'data': 100, 'pt': 200, 'athermal': 1000000, 'cooling': 0 } def init(self): self.epsilon = 1 self.prepare_chain() settings.BASE_DIR = self.get_base_dir() settings.EXPERIMENTAL_ROOT_DIR = settings.BASE_DIR if settings.CREATE_DIR_STRUCTURE: tools.create_dir(settings.BASE_DIR) def prepare_chain(self): length = self.length chain_seq = bio.prepare_sequence(bio.seq1_3(self.seq), MonomersMJ) self.chain_seq = Polymer.Chain(chain_seq) return self.chain_seq def c1_setup(self): name = "c1" self._setup(name, 0.5, 40.0, 100, swap = False) self.set_collect(**self.freq) settings.PERFORM_SWAP = False return (name, self.chain_seq) def c2_setup(self): name = "c2" self._setup(name, 40, 100.0, 100, swap = False) self.set_collect(**self.freq) settings.PERFORM_SWAP = False return (name, self.chain_seq) <file_sep>mv $1*.log $2/ mv *.*.*$1 $2/ mv *.*.po$1 $2/ $HOME/bin/notify.sh $1 echo "JOB $JOB_NAME FINISHED $1 `date`" >> $HOME/job_finished <file_sep>import numpy as np from scipy.interpolate import Rbf, InterpolatedUnivariateSpline from scipy.interpolate import interp1d import os from matplotlib import rc from matplotlib import pyplot as plt import argparse as arg rc('text', usetex=True) rc('font', family='serif') parser = arg.ArgumentParser(description="Plot SK graph") parser.add_argument('-f', default='') parser.add_argument('-legend', default='') parser.add_argument('-ymove', default=10.0, type=float) parser.add_argument('-title', default='') parser.add_argument('-on_line', default=False, action='store_true') parser.add_argument('-legend_prefix', default='') parser.add_argument('-png', default='', type=str) parser = parser.parse_args() if "," in parser.f: files = parser.f.split(",") files.sort() data_list = [] for f in files: print f if os.path.isfile(f): data_list.append(np.loadtxt(f, delimiter=";", skiprows=1)) x = data_list[0][:,0] legend = parser.legend.split(";") if ";" in parser.legend else [] titles = parser.title.split(";") plot_list = [] plt_idx = 1 xi = np.linspace(min(x), max(x), 100) for d in data_list: plt.subplot(len(data_list)/2, 2, plt_idx) plt.xticks(x, [ "%.2f" % k for k in x ]) plt.xlim( min(x), max(x) ) plt.ylim(0.0, 1.0) for z in range(1,d.shape[1]): #yi = InterpolatedUnivariateSpline(x, d[:,z])(xi) y = d[:,z] f = interp1d(x, y, kind='cubic') plt.plot(xi, f(xi)) plt_idx += 1 plt.show() <file_sep>import sys import tables import numpy as np import argparse as arg parser = arg.ArgumentParser(description='dump') parser.add_argument('-f', help='File') parser.add_argument('-jmol', action='store_true', default=False) parser.add_argument('-node', default='') parser.add_argument('-csv', action='store_true', default=False) parser.add_argument('-o') parser = parser.parse_args() h5file = tables.openFile(parser.f, 'r') dataset = h5file.getNode(parser.node) if parser.csv: output_file = open(parser.o, 'w+') output_file.writelines("%s\n" % ";".join(dataset.description._v_names)) data = dataset.read() output_file.writelines([ "%s\n" % ";".join(map(str, x )) for x in data ]) output_file.close() print "Wrote %d lines" % len(data) <file_sep>#!/usr/bin/python import argparse as arg import re import kyotocabinet as kb import sys parser = arg.ArgumentParser(description="Dump KCH") parser.add_argument('f', help='File') parser.add_argument('-f', help='File') parser.add_argument('-delimiter', help='Delimiter', default=';') parser.add_argument('-o', help='Output file') parser.add_argument('-csv', help='Output as csv', action='store_true') parser.add_argument('-jmol', help='Output as jmol', action='store_true') parser.add_argument('-d', help='Output dir for files', default='.') parser.add_argument('-k', help='Key prefix', default='') parser.add_argument('-regex', help='Regexp prefix', default='') parser.add_argument('-get', help='Get value', default='') parser.add_argument('-c', help='Output on console', action="store_true") parser.add_argument('-repair', help='Repair DB', action='store_true') parser = parser.parse_args() delimiter = parser.delimiter db = kb.DB() print "Open database %d" % db.open(parser.f, db.OREADER) if parser.k != '': values = db.match_prefix(parser.k) print "match values: %d" % len(values) elif parser.get != '': if parser.jmol: values = [parser.get] else: values = [db[parser.get]] elif parser.regex != '': values = db.match_regex(parser.regex) if parser.csv: output_file = sys.stdout if parser.c else open(parser.o, "w+") idx = 0 for v in values: line = "%s\n" % delimiter.join(map(str, eval(db[v]))) output_file.writelines(line) idx += 1 output_file.close() print "Stored %d values" % idx elif parser.jmol: idx = 0 for v in values: if parser.o: output_file = open(parser.o, "w+") elif parser.d: output_file = open(parser.d + "/" + v + ".jmol", "w+") t = eval(db[v]) output_file.write(str(len(t)) + "\n\n"); for z in t: line = "%s\n" % " ".join(map(str, z)) output_file.writelines(line) output_file.close() print "wrote", output_file elif parser.repair: l = db.match_prefix('') print "Values: %d" % len(l) db.close() output_file.close() else: values.sort(key = lambda x: re.match(".*(\d+).*",x).groups()[0]) print values[-1] <file_sep>class DummyMonomer(object): position = (0,0,0) type = '' neighbours_list = set() nb_list = [] nb_types = [] nb_types_count = {} on_interface = False nb_count = 0 def __init__(self, pos, type, nb): self.position = pos self.type = type self.neighbours_list = set(nb) self.nb_types = [] self.nb_types_count = {} self.nb_list = [] def __str__(self): return "%s %d %d %d" % (self.type, self.position[0], self.position[1], self.position[2]) def __repr__(self): return str(self.__str__()) <file_sep>import sys sys.path += ['/home/teodor/Documents/UAM/Studia magisterskie/Praca magisterska/Workspace/intraglobular/src'] from lib import tools import cPickle, gzip import os from mpi4py import MPI print "Calculate for set of experiments" print "root_dir exp_name, setup_name, mc_steps, debug" exp_name = sys.argv[2] root_dir = sys.argv[1] setup_name= sys.argv[3] mc_steps = int(sys.argv[4]) debug = eval(sys.argv[5]) if len(sys.argv) == 6 else False comm = MPI.COMM_WORLD rank = comm.Get_rank() size = comm.Get_size() print "Rank:", rank, "size", size dirs = [ o for o in os.listdir(root_dir) if exp_name in o ] d = len(dirs)/size mpi_dir = dirs[d*rank:d*rank+d] for dir in mpi_dir: if debug: print "read dir", dir box_dir = root_dir + "/" + dir + "/" + setup_name + "/data" out_file = open("%s_%s.rdf" % (dir, setup_name), "w+") file_list = [ o for o in os.listdir(box_dir) if int(o.replace('.dump','').split('_')[1]) >= mc_steps ] for box_file in file_list: if debug: print " read file",box_file box = tools.load_file(box_dir + "/" +box_file) for c in box.chain_list: out_file.writelines(["%s\n" % ";".join(map(str, c.calculate_rdf2()))]) out_file.close() <file_sep>from Lattice import Lattice from monomers import * class Monomer(object): """ Single monomer object """ _position = (0, 0, 0) _open = (0, 0, 0) next_direction = None ## from this monomer to the next one neighbours_position = [] neighbours_open_position = [] energy = 0 name = None interaction_table = {} chain = None prev_monomer = None next_monomer = None def __init__(self): if self.name is None: raise NotImplementedError() if self.name == '_s': raise Exception("_s is reserved name for solvent!") def get_position(self): return self._position def set_position(self, value): refresh_nb = False self.next_direction = None if self._position != value: refresh_nb = True self._position = tuple(value) if refresh_nb: self.neighbours_position = Lattice.get_neighbours(tuple(value)) position = property(get_position, set_position) def get_open_position(self): return self._open def set_open_position(self, value): refresh_nb = False if self._open != value: refresh_nb = True self._open = tuple(value) if refresh_nb: self.neighbours_open_position = Lattice.get_neighbours_open(tuple(value)) open_position = property(get_open_position, set_open_position) def __str__(self): return "Monomer type: %s, position: (%s)" % (self.name, ",".join(map(str, self._position))) ## Monomer types for Experiment4 and Experiment8 class TypeC(Monomer): name = "C" interaction_table = {'C': -1, 'O': -0.1} class TypeO(Monomer): name = 'O' interaction_table = {'O': -1, 'C': -0.1} class TypeA(Monomer): name = "A" # interaction_table = {'A': 0, 'B': 1, '_s': 0} interaction_table = {'A': 0, 'B': 1, '_s': 0} class TypeB(Monomer): name = "B" #interaction_table = {'A': 1, 'B': 0, '_s': 0} ## old one interaction_table = {'A': 1, 'B': 0, '_s': 1} class TypeC2(Monomer): name = "C" interaction_table = {'C': -1, 'O': 0} class TypeO2(Monomer): name = 'O' interaction_table = {'O': -1, 'C': 0} ## class TypeA2(Monomer): name = "A2" interaction_table = {'A2': 0, 'B2': 1, '_s': 0 } class TypeB2(Monomer): name = "B2" interaction_table = {'A2': 1, 'B2': 0, '_s': 1 } <file_sep># Implementation of Needleman/Wunsch # # <NAME> <<EMAIL> at g<EMAIL>> # # import sys import os import numpy as np ## AA functional groups SEQ1 = "acdefghiklmnopqrstuvwy-x" # all AA SEQ1_HP = "acfgilmpuvw" # hydrop SEQ1_P = "dehknqrsty" # polar SEQ1_ACID = "cdet" # acid AA SEQ1_BASIC = "hlr" # basic AA SEQ1_AROMATIC = "fhwy" # aromatic AA SEQ1_ALIPHATIC = "ilv" # aliphatic AA F_GROUPS = [SEQ1_HP, SEQ1_P, SEQ1_ACID, SEQ1_BASIC, SEQ1_AROMATIC, SEQ1_ALIPHATIC] BLAST_DIR="blast_matrices" try: seq1 = sys.argv[1].lower() seq2 = sys.argv[2].lower() except: print "Sequence alignment using Needleman/Wunsch technique" print "Usage:" print "\tseq1 seq2 matrix" print "" sys.exit(1) m = len(seq1) n = len(seq2) ## const MATCH = 2 GROUP_MATCH = 1 ## if residue is in the same functional group GAP = -2 ## penalty MISMATCH = -1 ## H = np.zeros((m+1, n+1)) trace = np.zeros((m+1, n+1)) bifurcation = np.zeros((m+1, n+1)) def match(s1, s2): if s1 == s2: return MATCH else: #for group in F_GROUPS: # if s1 in group and s2 in group: # return GROUP_MATCH return MISMATCH def print_matrix(row, col, matrix): print " "," ".join(map(lambda x: str(x).center(6), row)) for lidx in range(len(matrix)): print col[lidx-1]," ".join(map(lambda x: str(x).center(6), matrix[lidx])) max_point = (0,0) max_score = 0 for i in range(1, m+1): for j in range(1, n+1): s1 = H[i-1][j-1] + match(seq1[i-1], seq2[j-1]) s2 = H[i][j-1] + GAP ## insert s3 = H[i-1][j] + GAP ## delete v = [s1, s2, s3] max_v = max(v) H[i][j] = max_v trace[i][j] = v.index(max_v) #bifurcation[i][j] = set([ v.index(max_v), v[1:].index(max_v), v[2:].index(max_v) ]) bifurcation[i][j] = max([ v.count(max_v) for x in v ]) if H[i][j] >= max_score: max_point = (i, j) max_score = H[i][j] print "="*10 print "H matrix" H = H.transpose() print_matrix(seq1, seq2,H) print "-"*10 print "Trace matrix" print "0 - diagonal, 1.0 - top, 2.0 - left" trace = trace.transpose() print_matrix(seq1, seq2, trace) print "-"*10 print "Bifurcation" print_matrix(seq1, seq2, bifurcation.transpose()) ## trace i = m j = n H = H.transpose() alignmentA = '' alignmentB = '' scoring = 0 path = [] trace = trace.transpose() while (i > 0 and j > 0): t = trace[i][j] s1 = seq1[i-1] s2 = seq2[j-1] path.append((i,j)) if t == 0.0: alignmentA = s1 + alignmentA alignmentB = s2 + alignmentB i -= 1 j -= 1 elif t == 2.0: ## delete in seq2 alignmentA = s1 + alignmentA alignmentB = '-' + alignmentB i -= 1 else: ## inser in seq2 alignmentA = '-' + alignmentA alignmentB = s2 + alignmentB j -= 1 scoring += H[i][j] while i > 0: alignmentA = s1 + alignmentA alignmentB = '-' + alignmentB i -= 1 while j > 0: alignmentA = '-' + alignmentA alignmentB = seq2[j] + alignmentB j -= 1 alignmentA = list(alignmentA) alignmentB = list(alignmentB) #alignmentA.reverse() #alignmentB.reverse() sco = [] for idx in range(len(alignmentA)): s1 = alignmentA[idx] s2 = alignmentB[idx] for f in F_GROUPS: if s1 in f and s2 in f: sco.append('+') break else: sco.append('-') break print "A:", "".join(alignmentA) print "B:", "".join(alignmentB) print 'M:', "".join(sco) print "Scoring:", scoring print "Path:", path <file_sep>#!/bin/bash echo Compress files START_DIR=$1 EXP_NAME=$2 ## exp4, exp4b DIR=$3 ## models, data <file_sep>''' Created on 1 Nov 2011 @author: teodor ''' import itertools import logging import math import random from mpi4py import MPI import numpy as np # import bigfloat from math import exp import settings import tools import numpy import time class Lattice(object): """ FCC lattice """ DIRECTION = [ (-1, 0, -1), (1, 0, 1), (-1, 0, 1), (1, 0, -1), (0, 1, -1), (0, -1, 1), (0, 1, 1), (0, -1, -1), (-1, 1, 0), (1, -1, 0), (-1, -1, 0), (1, 1, 0) ] XZ_DIRECTION = [ 0, 1, 2, 3 ] YZ_DIRECTION = [ 4, 5, 6, 7 ] XY_DIRECTION = [ 8, 9, 10, 11 ] # # get index of turn direction # # 0 -> 1 # # 1 -> 0 TURN_DIRECTION = [1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10] # # cache NEIGHBOURS_POSITION = {} NEIGHBOURS_OPEN_POSITION = {} ROTATION_WAYS = {} box_size = (0, 0, 0) coordinate = None number_of_points = 0 z = 12 # number of neighbours neighbour_distance = 2 def __init__(self, size): self.box_size = size self.number_of_points = (size[0] * size[1] * size[2]) / 2 @classmethod def is_valid_coordinate(cls, c): return ((sum(c) % 2) == 0) @classmethod def get_neighbours(cls, position): """ @position: tuple @type: int - 1 -- bc positions, 2 - open positions Return list of position of neighbours """ nb_open_positions = cls.DIRECTION + np.array(position) nb_positions = nb_open_positions % cls.box_size nb_positions = [ tuple(x) for x in nb_positions ] return nb_positions @classmethod def get_neighbours_open(cls, position): nb_open_positions = cls.DIRECTION + np.array(position) nb_open_positions = [ tuple(x) for x in nb_open_positions ] return nb_open_positions @classmethod def is_neighbour(cls, a, b): """ Is position a neighbour of position b """ # nb_list = cls.get_neighbours(b) # return a in nb_list diff = np.array(a) - np.array(b) # diff = list(diff) # if diff.count(1) == 2 and diff.count(0) == 1: # return True diff = diff.dot(diff) if diff == cls.neighbour_distance: return True return False @classmethod def get_coordinate(cls, current_position, direction): """ Return new coordinate, from current_position in some direction Applied periodic boundary conditions @tuple current_position: tuple - current position @int direction: - direction to move DIRECTION [x][y][z] 0: -1 0 -1 1: 1 0 1 2: -1 0 1 3: 1 0 -1 4: 0 1 -1 5: 0 -1 1 6: 0 1 1 7: 0 -1 -1 8: -1 1 0 9: 1 -1 0 10: -1 -1 0 11: 1 1 0 """ bs = cls.box_size # # size of box coordinate = tuple((np.array(current_position) + np.array(cls.DIRECTION[direction])) % bs) return coordinate @classmethod def get_open_coordinate(cls, current_position, direction): coordinate = tuple(np.array(current_position) + np.array(cls.DIRECTION[direction])) return coordinate @classmethod def convert_to_open_coordinate(cls, prev_position, converted_position): """ @tuple prev_position: @tuple converted_position: Convert periodic bounduary condition to open one """ difference = tools.array_diff(converted_position, prev_position) # distance = tuple(map(lambda x: cmp(x, 0), difference)) # distance_length = tools.dot(distance,distance) # if distance_length > 2: # import ipdb;ipdb.set_trace() #============ BREAKPOINT ============# direction = cls.get_direction(tuple(map(lambda x: cmp(x, 0), difference))) return cls.get_open_coordinate(prev_position, direction) @classmethod def convert_to_periodic_coordinate(cls, position): """ Convert coordinate to periodic coordinate """ print "box_size", cls.box_size return tuple(map(lambda x, box_size: x % box_size, position, cls.box_size)) @classmethod def get_direction(cls, vector): """ Return direction of given vector or exception """ return cls.DIRECTION.index(tuple(map(lambda x: cmp(x, 0), vector))) @classmethod def get_square_distance(cls, monomer_a, monomer_b): """ Return distance^2 between monomers. """ distance = np.array(monomer_b) - np.array(monomer_a) distance = distance.dot(distance) return distance <file_sep>import sys import itertools print "jmol_file box_size solvent_symbol" input_jmol = sys.argv[1] box_size = int(sys.argv[2]) symbol = sys.argv[3] r = range(0, box_size) coordinate = set([ k for k in itertools.product(r,r,r) if sum(k) % 2 == 0 ]) jmol_coordinate = set(map(lambda x: tuple(map(float, x.split(" ")[1:])), open(input_jmol, "r").readlines()[2:])) diff = coordinate.difference(jmol_coordinate) output_jmol = open(input_jmol, 'a+') for cr in diff: line = "%s %f %f %f\n" % (symbol, cr[0], cr[1], cr[2]) output_jmol.write(line) output_jmol.close(0) <file_sep>// Copyright 2013 <EMAIL> (<NAME>) // Draft implementation of Viterbi algorithm with backpointers // and the four categories for rare word. // // Usage: // viterbi_bp_enh word.count test_case // // Returns: // For each word in the test_case return the word and the tag. // #include <string> #include <fstream> #include <iostream> #include <map> #include <sstream> #include <vector> #include <set> #include <deque> #include <algorithm> #include <cstdio> #include "langlib.h" using namespace std; int main(int argc, char **argv) { fstream wordCount(argv[1], fstream::in); map<string, map<string, int> > wordTags; // Count(y->x) map<string, int> unigrams; map<string, map<string, int> > bigrams; map<string, map<string, map<string, int> > > trigrams; set<string> tags; tags.insert("I-GENE"); tags.insert("O"); string line, token, token1, token2, token3, word, event; int wCount; while (getline(wordCount, line)) { stringstream lineStream(line); lineStream >> wCount; lineStream >> event; if (event == "WORDTAG") { lineStream >> token; lineStream >> word; wordTags[token][word] = wCount; //cout << "\t" << line << endl; //cout << "wordTags[" << token << "][" << word << "] " << wCount << endl; } else if (event == "1-GRAM") { lineStream >> token; unigrams[token] = wCount; } else if (event == "2-GRAM") { lineStream >> token; lineStream >> token1; bigrams[token][token1] = wCount; } else if (event == "3-GRAM") { lineStream >> token; lineStream >> token1; lineStream >> token2; trigrams[token][token1][token2] = wCount; } } wordCount.close(); // Calculates emission parameters. map<string, map<string, double> > epsilon; map<string, map<string, int> >::iterator it; map<string, int>::iterator it2; double value = 0.0; for (it = wordTags.begin(); it != wordTags.end(); ++it) { for (it2 = it->second.begin(); it2 != it->second.end(); it2++) { value = static_cast<double>(it2->second) / static_cast<double>(unigrams[it->first]); epsilon[it2->first][it->first] = value; //cout << "e[" << it2->first << "][" << it->first << "] " << value << endl; } } // Calculates q parameters. map<string, map<string, map<string, double> > > q; map<string, map<string, map<string, double> > >::iterator qIt; map<string, map<string, map<string, int> > >::iterator triIt; string yn2, yn1, yn; for (triIt = trigrams.begin(); triIt != trigrams.end(); triIt++) { yn2 = triIt->first; for (it = triIt->second.begin(); it != triIt->second.end(); it++) { yn1 = it->first; for (it2 = it->second.begin(); it2 != it->second.end(); it2++) { yn = it2->first; double c = it2->second; q[yn][yn2][yn1] = c / static_cast<double>(bigrams[yn2][yn1]); } } } // Reads input sentences. vector< vector<string>* > sentences; vector<string> *tmpSentence = new vector<string>; fstream inputDev(argv[2], fstream::in); while (getline(inputDev, word)) { if (word == "") { sentences.push_back(tmpSentence); tmpSentence = new vector<string>; } else { tmpSentence->push_back(word); } } // Calculates pi and backpointers // Viterbi algorithm implementation map<int, map<string, map<string, double> > > pi; // pi(k, u, v); map<int, map<string, map<string, string> > > bp; // bp(k, u, v); vector<string> resultsTag; set<string> *uSet = NULL; set<string> *vSet = NULL; set<string> *wSet = NULL; set<string> singleTag; singleTag.insert("*"); set<string>::iterator uSetIt, vSetIt, wSetIt; string maxToken, xk; double maxValue; map<string, double> *emissionParam; double piScale = 1000.0; pi[0]["*"]["*"] = piScale*1.0; for (int sIdx = 0; sIdx < sentences.size(); sIdx++) { vector<string> *sentence = sentences[sIdx]; resultsTag.clear(); resultsTag.resize(sentence->size()+1); fill(resultsTag.begin(), resultsTag.begin()+sentence->size(), ""); // Iterates over sentence. for (int k = 1; k <= sentence->size(); k++) { // Word. xk = sentence->at(k-1); // Define sets. uSet = (k < 2) ? &singleTag : &tags; vSet = &tags; wSet = (k < 3) ? &singleTag : &tags; // cout << "----DEBUG k=" << k << ": \"" << xk << "\" --------" << endl; // Emission parameter. if (epsilon.count(xk) > 0) { emissionParam = &epsilon[xk]; } else { // RARE string rareToken = getRareToken(xk); //cout << rareToken << " for " << xk << endl; emissionParam = &epsilon[rareToken]; } double emissionValue = 0.0; for (uSetIt = uSet->begin(); uSetIt != uSet->end(); uSetIt++) { for (vSetIt = vSet->begin(); vSetIt != vSet->end(); vSetIt++) { wSetIt = wSet->begin(); maxToken = "O"; if (emissionParam->count(*vSetIt) > 0) emissionValue = emissionParam->at(*vSetIt); else emissionValue = 0.0; maxValue = piScale*pi[k-1][maxToken][*uSetIt] * q[*vSetIt][maxToken][*uSetIt] * emissionValue; value = 0.0; for (; wSetIt != wSet->end(); wSetIt++) { value = piScale*pi[k-1][*wSetIt][*uSetIt] * q[*vSetIt][*wSetIt][*uSetIt] * emissionValue; if (value > maxValue) { maxValue = value; maxToken = *wSetIt; } /* printf("### pi cal for (%d, %s, %s) ###\n", k, (*uSetIt).c_str(), (*vSetIt).c_str()); printf("pi[%d][%s][%s] = %e\n", k-1, (*wSetIt).c_str(), (*uSetIt).c_str(), (double) pi[k-1][*wSetIt][*uSetIt]); printf("q[%s][%s][%s] = %e\n", (*vSetIt).c_str(), (*wSetIt).c_str(), (*uSetIt).c_str(), q[*vSetIt][*wSetIt][*uSetIt]); printf("em[%s][%s] = %e\n", xk.c_str(), (*vSetIt).c_str(), emissionValue); printf("maxValue: %e, value: %e, maxToken: %s\n\n", maxValue, value, maxToken.c_str()); */ } pi[k][*uSetIt][*vSetIt] = maxValue; bp[k][*uSetIt][*vSetIt] = maxToken; } } } // Backtrace for sentence. // Fill last two tags. maxValue = 0.0; yn1 = ""; // tag n-1 yn = ""; // last tag int n = sentence->size(); for (uSetIt = tags.begin(); uSetIt != tags.end(); uSetIt++) { for (vSetIt = tags.begin(); vSetIt != tags.end(); vSetIt++) { value = pi[n][*uSetIt][*vSetIt] * q["STOP"][*uSetIt][*vSetIt]; if (value > maxValue) { maxValue = value; yn = *vSetIt; yn1 = *uSetIt; } } } resultsTag[n] = yn; resultsTag[n-1] = yn1; // Fill the rest tags. for (int k = n-2; k >= 1; k--) { resultsTag[k] = bp[k+2][resultsTag[k+1]][resultsTag[k+2]]; } for (int k = 0; k < n; ++k) { cout << sentence->at(k) << " " << resultsTag[k+1] << endl; } cout << "\n"; } // Finished of processing sentence return 0; } <file_sep>from lib.tools import load_file from lib.Box import Box import sys print "Basic information in Box file" print "<box_file_name>" f_box = sys.argv[1] box = load_file(f_box) print "Box size", box.box_size print "Number of chains", len(box.chain_list) print "Local T", box.localT <file_sep># Implementation of Smith Waterman alghoritm for sequence local alignment # # <NAME> <<EMAIL> at <EMAIL>> # # Based on http://en.wikipedia.org/wiki/Smith%E2%80%93Waterman_algorithm#cite_note-Altshul1986-1 # # # import sys import os import numpy as np ## AA functional groups SEQ1 = "acdefghiklmnopqrstuvwy-x" # all AA SEQ1_HP = "acfgilmpuvw" # hydrop SEQ1_P = "dehknqrsty" # polar SEQ1_ACID = "cdet" # acid AA SEQ1_BASIC = "hlr" # basic AA SEQ1_AROMATIC = "fhwy" # aromatic AA SEQ1_ALIPHATIC = "ilv" # aliphatic AA F_GROUPS = [SEQ1_HP, SEQ1_P, SEQ1_ACID, SEQ1_BASIC, SEQ1_AROMATIC, SEQ1_ALIPHATIC] BLAST_DIR="blast_matrices" try: seq1 = sys.argv[1].lower() seq2 = sys.argv[2].lower() matrix_group = sys.argv[3] except: print "Sequence alignment using Smith-Waterman algorithm" print "Usage:" print "\tseq1 seq2 matrix" print "\tmatrix: simple|BLAST" print "" print "BLAST:" print "|".join(os.listdir(BLAST_DIR)) sys.exit(1) m = len(seq1) n = len(seq2) ## const MATCH = 2 GROUP_MATCH = MATCH*2 ## if residue is in the same functional group MISMATCH = -4 ## penalty ## def match(s1, s2): if s1 == s2: return MATCH else: for group in F_GROUPS: if s1 in group and s2 in group: return GROUP_MATCH return MISMATCH H = np.zeros((m+1, n+1)) trace = np.zeros((m+1, n+1)) max_score = 0 max_point = (0,0) ## starting point of backtracking for i in range(1, m+1): for j in range(1, m+1): s1 = H[i-1][j] + MISMATCH # up s2 = H[i][j-1] + MISMATCH # down s3 = H[i-j][j-1] + match(seq1[i-1], seq2[j-1]) # diag v = [0, s1, s2, s3] H[i][j] = max(v) trace[i][j] = v.index(H[i][j]) if H[i][j] >= max_score: max_point = (i, j) max_score = H[i][j] alseq1, alseq2 = [],[] ## Backtracking, follow path stored in :trace i,j = max_point while trace[i][j] != 0: ## indicates end of path point = trace[i][j] if point == 3: ## diagonal alseq1.append(seq1[i-1]) alseq2.append(seq2[j-1]) i, j = i-1, j-1 elif point == 2: ## down alseq1.append('-') alseq2.append(seq2[j-1]) j -= 1 elif point == 1: ## up alseq1.append(seq1[i-1]) alseq2.append('-') i -= 1 alseq1.reverse() alseq2.reverse() print "seq1:", seq1 print "seq2:", seq2 print "="*10 print "seq1:", "".join(alseq1) print "seq2:", "".join(alseq2) <file_sep>#!/bin/bash CURRENT_PATH="`pwd`" CODE="$HOME/code/intraglobular/src" cd $CODE git pull find -name "*.so" | while read a; do ./compile_file.sh "$a"; done cd $CURRENT_PATH <file_sep>from lib import Box, Chain, tools from lib import tools import os import sys try: box_file = sys.argv[2] xyz_file = sys.argv[3] cmd = sys.argv[1] except: print "Convert box to xyz and vs." print "box2xyz|xyz2box box_file xyz_file" print "For xyz2box also: (box_size) and <localT>" if cmd is "xyz2box": box_size = eval(sys.argv[4]) localT = float(sys.argv[5]) xyz = open(os.path.realpath(xyz_file)).readlines()[2:] elif cmd is "box2xyz": b = tools.load_file(box_file) b.jmol_snapshot(xyz_file) <file_sep>""" Definition of monomers for HP Model for temp = 36 """ from lib.Monomer import Monomer epsilon = 10**-23 class TypeH(Monomer): name = "H" interaction_table = {'H': -epsilon, 'P': 0} class TypeP(Monomer): name = "P" interaction_table = {'H': 0, 'P': 0} <file_sep># <NAME> <<EMAIL>> # Define experiments from lib import Polymer, tools from lib.Experiment import Experiment from lib.MonomerExp8e import TypeC as TypeC05 from lib.MonomerExp8e import TypeO as TypeO05 from lib.Monomer import TypeC, TypeO import lib.MonomerExp8e as MLib import settings class Experiment9(Experiment): name = "multichain1" box_size = (240, 240, 240) length = 240 global_tag = 112 freq = { 'mc_steps': 40000000, 'collect': 15000000, 'snapshot': 1000, 'calc': 100, 'data': 1, 'pt': 100, 'swap': 200, 'athermal': 100000 } def init(self): self.epsilon = 1 self.prepare_chain() settings.BASE_DIR = self.get_base_dir() settings.EXPERIMENTAL_ROOT_DIR = settings.BASE_DIR if settings.CREATE_DIR_STRUCTURE: tools.create_dir(settings.BASE_DIR) def const_setup(self): """ Experiment using parallel tempering, with linear temperature function """ settings.COLLECT = 0 settings.PERFORM_SWAP = False name = "const" self._setup(name, 1, 14, 2) self.set_collect(**self.freq) return (name, self.chain_seq) def prepare_chain(self): length = self.length co_block = 20 one_block = 10 self.chain_seq = Polymer.Chain([ TypeO() if (x % co_block) < one_block else TypeC() for x in range(length)]) return self.chain_seq def c21_setup(self): name = "c21" self.temp_list = [2.266667, 2.9, 3.2166665, 3.533333, 4.800000, 4.9575, 5.115, 5.2725, 5.43, 5.745, 6.066667, 6.7, 7.333333, 8.600000, 11.13, 12.40] self._setup(name, 2.27, 8.96, 360, swap = False) self.set_collect(**self.freq) settings.PERFORM_SWAP = False return (name, self.chain_seq) def fopt_setup(self): name = "fopt_1" self.freq['mc_steps'] = 1000 self.freq['collect'] = 0 self.freq['athermal'] = 0 self.freq['data'] = 5000000 self.freq['calc'] = 5000000 self.freq['snapshot'] = 5000000 self._setup(name, 1.0, 10.0, 320, swap = True) self.set_collect(**self.freq) settings.PERFORM_SWAP = True settings.FOPT = True return (name, self.chain_seq) class Experiment901M(Experiment9): name = "multichain901M" length = 64 box_size = (64, 64, 64) freq = { 'mc_steps': 1000000, 'collect': 100, 'snapshot': 1000, 'calc': 100, 'data': 1, 'pt': 200, 'athermal': 500000 } def prepare_chain(self): length = self.length co_block = 20 one_block = 10 self.chain_seq = [ Polymer.Chain([ TypeO() if (x % co_block) < one_block else TypeC() for x in range(length)]) for x in range(20) ] return self.chain_seq <file_sep>from Monomer import Monomer class TypeA(Monomer): name = "A" interaction_table = {'A': 0, 'B': 0.5, '_s': 0} class TypeB(Monomer): name = 'B' interaction_table = {'A': 0.5, 'B': 0, '_s': 0.5} <file_sep>import os import argparse as arg import glob import shutil parser = arg.ArgumentParser(description="Process files") parser.add_argument('--config-file', help="Config file", dest="cfile") parser.add_argument('-r', help='Root dir where experiment is stored', type=str) parser.add_argument('-e', help='Experiment name', default='', type=str) parser.add_argument('-s', help="Setup name, eg. m7", default="", type=list) parser.add_argument('-o', help="Output dir", default="", type=str) parser.add_argument('-new', help="Output file with new files", default=None) result = parser.parse_args() ROOT_DIR = result.r EXP_NAME = exp_name = result.e SETUP_NAME = result.s OUTPUT_DIR = result.o try: config_file = result.cfile execfile(config_file) except: print "Can't read config file" exp_name = EXP_NAME ########## print config print "exp_name:", exp_name print "setup_name:", SETUP_NAME print "config_file:", config_file ######################### tmp_s = ROOT_DIR.split('/') csv_basename = exp_name exp_dirs = [ "%s/%s" % (ROOT_DIR, d) for d in os.listdir(ROOT_DIR) if os.path.isdir(ROOT_DIR + "/" + d) and exp_name in d ] print "Found dirs" print "\t\n".join(exp_dirs) dirs = [] files = [] for d in exp_dirs: for s in SETUP_NAME: dd = [ "%s/%s" % (d, o) for o in os.listdir(d) if os.path.isdir(d + "/" + o) and s in o] dirs.extend(dd) for d in dirs: for p in glob.glob(d + "/calc/*calc_*.csv"): if os.path.exists(p): files.append(p) else: files_list = [ d + "/" + f for f in os.listdir(d) if 'calc' in f and not os.path.isdir(d+"/"+f) ] if files_list is not []: files.extend(files_list) print "Create dir", OUTPUT_DIR try: os.mkdir(OUTPUT_DIR) except: print OUTPUT_DIR, "exists" output_new_file = None if result.new: output_new_file = open(result.new,"w+") for f in files: output_file = "_".join(f.replace(ROOT_DIR + "/", "").split("/")) output_path = OUTPUT_DIR + "/" + output_file if not os.path.exists(output_path): print f, "copy to", output_path shutil.copy(f, output_path) if output_new_file: output_new_file.writelines(output_path + "\n") else: print f, "skip" <file_sep>## ## Author: <NAME> ## ## Compute autocorrelation function ## import sys data = [ int(d) for d in open(sys.argv[1]) ] data_norm = [ d/float(len(data)) for d in data ] data_avg = sum(data_norm)/float(len(data_norm)) time = range(16) chi = [] K = len(data_norm) for t in time: print t normalization_factor = 1 / (K - t) for s in range(K-t) <file_sep>// Copyright 2013 <EMAIL> (<NAME>) // Use several groups for rare words (<5) // - NUMERIC for numeric values // - ALL_CAPITALS for all capital letters // - LAST_CAPITAL ends with capital letter // - RARE for all other cases // #include "langlib.h" #include <string> using namespace std; string getRareToken(string token) { bool allCapitals = true; for (int i = 0; i < token.length(); i++) { // at least one numeric character if (token[i] >= 48 && token[i] <= 57) { return "NUMERIC"; } // Check if all letters are capital. if (token[i] < 65 || token[i] > 90) allCapitals = false; } if (allCapitals) return "ALL_CAPITALS"; char lastChar = token[token.length()-1]; if (lastChar >= 65 && lastChar <= 90) return "LAST_CAPITAL"; return "_RARE_"; } <file_sep>#!/bin/bash print "out_avg_dir return_dir" find $1 -name "out.avg" | while read a; do cp -v "$a" "$2/`echo $a | cut -f2 -d'/'`_`basename $a`"; done <file_sep>#rdir="Exp8F_01/clusters/exp8f0_1_0/c1_240_240_240_0/models/" #out="Exp8F_01/clusters/clusters_exp8f0_1_0_c1_240_240_240_0" echo "input_dir" "output_file" "start_range:stop_range" rdir="$1" out="$2" start_range="`echo $3 | cut -f1 -d:`" stop_range="`echo $3 | cut -f2 -d:`" cmd="print ' '.join(map(str, range($start_range, $stop_range+1000, 1000)))" range="`python -c \"$cmd\"`" echo $rdir $out $start_range $stop_range echo $cmd for f in $range; do python tools/calculate_clusters.py -f "${rdir}/jmol_${f}.jmol" -step -box 240,240,240 >> $out; done <file_sep>SEQ1 = "acdefghiklmnopqrstuvwy-x" SEQ1_HP = "acfgilmpuvw" SEQ1_P = "dehknqrsty" SEQ1_ACID = "cdet" SEQ1_BASIC = "hlr" SEQ1_AROMATIC = "fhwy" SEQ1_ALIPHATIC = "ilv" SEQ3 = ['Ala', 'Cys', 'Asp', 'Glu', 'Phe', 'Gly', 'His', 'Ile', 'Lys', 'Leu', 'Met', 'Asn', 'Pyl', 'Pro', 'Gln', 'Arg', 'Ser', 'Thr', 'Sec', 'Val', 'Trp', 'Tyr', '---', 'UNK'] seq1to3 = dict(zip(SEQ1, SEQ3)) seq3to1 = dict(zip(SEQ3, SEQ1)) def chunk(l, n): """ Return chunks of string """ return (l[i:i+n] for i in xrange(0, len(l), n)) def seq1_3(seq1): seq1 = seq1.lower() return [ seq1to3[x] if seq1to3.has_key(x) else seq1to3['x'] for x in seq1 ] def seq3_1(seq3): if not isinstance(seq3, list): if len(seq3) % 3: raise Exception('It is not valid 3-letter sequence') seq3 = [ x.title() for x in chunk(seq3, 3) ] return [ seq3to1[x] if seq3to1.has_key(x) else seq3to1['UNK'] for x in seq3 ] def prepare_sequence(sequence_code, library): """ Return valid Monomer object sequence, base on one letere sequence code @string sequence_code: one letter sequence @Monomer library: module with Monomers class that are used for build sequence return @list """ monomer_sequence = [] for s in sequence_code: m_obj = getattr(library, 'Type%s' % s) monomer_sequence.append(m_obj()) return monomer_sequence class PDBFile(object): """ Object represents PDB file """ pass <file_sep>import numpy as np from matplotlib import pyplot as plt import mc #from scipy import constants ## temperature list ## from 1.9 to 4.0 with step 0.01 T_list = np.arange(1.5, 3.5, 0.01) lattice_size = 25 sq_size = float(lattice_size ** 2) eq_time = 100 ## time (in sweeps) when systems goes into equilibrium meassure_time = eq_time/20 ## avoid autocorrelation avg_number = None sim = mc.MC(size = lattice_size, sweeps=5000, T = T_list[0], eq_time = eq_time) magnetization_avg = [] energy_avg = [] for T in T_list: print T sim.T = T results = sim.run() #magnetization = map(lambda x: x / float(lattice_size**2), results['magnetization']) magnetization = results['magnetization'][0::meassure_time] if not avg_number: avg_number = float(len(magnetization) * sq_size) #file = open("data/M-T_%.2f.csv" % T, "w+") #file.writelines(["%d\n" % m for m in magnetization ]) #file.close() #energy = results['energy'][eq_time:] ## compute monte carlo average magnetization for given temperature magnetization_avg.append(abs(sum(magnetization))/avg_number) #plt.plot([ m/avg_number for m in magnetization ]) #plt.show() #energy_avg.append(sum(energy)/float(len(energy)*sq_size)) plt.title('Magnetization for N = %d' % lattice_size) plt.ylabel('<M>') plt.xlabel('T') plt.plot(T_list, magnetization_avg) plt.show() <file_sep>ctags -R --exclude=experiment . <file_sep>#python /opt/local/Library/Frameworks/Python.framework/Versions/2.6/bin/pycscope.py find . -name '*.py' | grep -v "migrations" > cscope.files cscope -b -q -T <file_sep>#!/bin/bash NAME=$2 ROOT=$1 tail -n1 $ROOT*/${NAME}*/calc/calc_*.csv for f in $ROOT*/${NAME}*/*.kch; do echo $f; python -c "import kyotocabinet as kb; db = kb.DB(); db.open('${f}', db.OREADER); print '\n'.join(db.match_prefix(''));" | tail -n 1 done <file_sep>// Copyright 2013 <EMAIL> (<NAME>) // // Calculates the frequency of words and replace the rarest with // special word _RARE_. // #include <iostream> #include <fstream> #include <string> #include <map> #include <cstdio> #include <sstream> using namespace std; int main(int argc, char **argv) { int rareCount = 5; fstream wordsFile(argv[1], fstream::in); map<string, int> wordFreq; string line; string token; string tag; while (wordsFile.good()) { getline(wordsFile, line); stringstream lineStream(line); getline(lineStream, token, ' '); if (wordFreq.count(token) == 0) wordFreq[token] = 1; else wordFreq[token]++; } wordsFile.clear(); wordsFile.seekg(0); while (wordsFile.good()) { getline(wordsFile, line); stringstream lineStream(line); getline(lineStream, token, ' '); getline(lineStream, tag, ' '); if (wordFreq[token] < rareCount) cout << "_RARE_ " << tag << endl; else cout << line << endl; } wordsFile.close(); return 0; } <file_sep>import sys from lib import tools import cPickle, gzip import os box_dir = sys.argv[1] out_file = sys.argv[2] out_file = open(out_file, 'w+') for box_file in os.listdir(box_dir): box = tools.load_file(box_dir + "/" +box_file) for c in box.chain_list: out_file.writelines(["%s\n" % ";".join(map(str, c.calculate_rdf()))]) out_file.close() <file_sep>// Copyright 2013 <EMAIL> (<NAME>) // // #ifndef LANGLIB_H_ #define LANGLIB_H_ #include <string> using namespace std; string getRareToken(string token); #endif /* LANGLIB_H_ */ <file_sep>## ## compile file INPUT_PY="$1" INPUT_C="`echo $1 | cut -f1 -d'.'`.c" OUTPUT_SO="`echo $1 | cut -f1 -d'.'`.so" echo "INPUT_PY=$INPUT_PY" echo "INPUT_C=$INPUT_C" echo "OUTPUT_SO=$OUTPUT_SO" rm $INPUT_C rm $OUTPUT_SO cython $INPUT_PY -o $INPUT_C gcc -shared -pthread -fPIC -fwrapv -O3 -Wall -fno-strict-aliasing -I${PYTHON_INCLUDE} -o $OUTPUT_SO $INPUT_C <file_sep># # Author: <NAME> <<EMAIL>> # Define experiments # from lib import Polymer, tools from lib.Experiment import Experiment from lib.Monomer import TypeA, TypeB import settings class Experiment2008(Experiment): name = "exp2008" box_size = (64, 64, 64) length = 64 global_tag = 113 freq = { 'mc_steps': 10000000, 'collect': 0, 'snapshot': 100, 'calc': 10, 'data': 100, 'pt': 200, 'athermal': 1000000, 'cooling': 0 } def init(self): self.epsilon = 1 self.prepare_chain() settings.BASE_DIR = self.get_base_dir() settings.EXPERIMENTAL_ROOT_DIR = settings.BASE_DIR if settings.CREATE_DIR_STRUCTURE: tools.create_dir(settings.BASE_DIR) def prepare_chain(self): length = self.length co_block = length / 4 one_block = length / 8 self.chain_seq = Polymer.Chain([ TypeA() if (x % co_block ) < one_block else TypeB() for x in range(length) ]) return self.chain_seq def c1_setup(self): name = "c1" self._setup(name, 1.2, 12, 100, swap = False) self.set_collect(**self.freq) settings.PERFORM_SWAP = False return (name, self.chain_seq) <file_sep>''' Settings for simulation @author: <NAME> <<EMAIL>> It is a global settings file, for each experiment some values can be modified inside experiment class (especialy FREQ values) ''' import os DEBUG = False PROFILER = False TIME = False LOGGING = False ## Simulation settings MIN_T = None MAX_T = None LOCAL_T = None EPSILON = 1 BOX_SIZE = None MC_STEPS = 100000 EXPERIMENT_NAME = "" EXPERIMENT_ROOT_NAME = "" EXPERIMENT_COPY = 0 ## dirs CREATE_DIR_STRUCTURE = True EXPERIMENT_DIR = "experiment/" BASE_DIR = os.getcwdu() ROOT_DIR = os.getcwdu() + "/" + EXPERIMENT_DIR EXPERIMENTAL_ROOT_DIR = None TEMP_TABLE = "" DIRS = { "cache": "cache/", "model": "models/", "log": "logs/", "data": "data/", "calc": "calc/" } FILES = { 'log_file': 'logging.log', 'lattice' : 'fcc.dump', 'temp_cfg': 'temperatures.cfg' } FILES_TEMPLATE = { "exp": "exp_%f.dump", "data": "box_%d.dump", "calc": "calc_%s.csv", "model": "jmol_%d.jmol", "pt_hist": "pt_temp_%d.data" } ## cache table for exponential values in given local_t EXP_TABLE = {} EXP_TABLES = {} ## settings MC_MODULE = None BOX_MODULE = None LATTICE_MODULE = None PT_MODULE = None MPI = True PT = False FOPT = False RANK = 0 TAG = 0 SIZE = 1 SIZE_VECTOR = [0] PERFORM_SWAP = False CONFORMATION_EXCHANGE = False SYSTEM_ID = 0 CURRENT_STEP = 0 DELTA_STEP = 0 ## calculation frequency FREQ_COLLECT = int(MC_STEPS/2.0) FREQ_CALC = 100 # calculate values every nth step FREQ_SNAPSHOT = 1000 # do xyz snapshot every nth step FREQ_DATA = 1000 # dump configuration every nth step FREQ_SWAP = 100 # perform swap every nth step FREQ_GC = 1000 # perform garbage collection FREQ_ATHERMAL = 500000 # perform athermal state for nth steps FREQ_COOLING = 100 # perform linear cooling for nth steps FREQ_COLLECT = FREQ_COLLECT + FREQ_ATHERMAL + FREQ_COOLING FREQ_COLLECT2 = FREQ_ATHERMAL + FREQ_COOLING # # second is used in parallel tempering where we want # # to switch between temperatures after athermal # # but we want to not collect first part of data RARE_SAVE = 50000 # save data in some rare steps JMOL_SCALE = 1.0 ### scale for jmol # scale jmol xyz snapshot K_CONST = 1.3806504e-23 <file_sep>import numpy as np from matplotlib import pyplot as plt from matplotlib import rc import os import argparse as arg rc('text', usetex=True) rc('font', family='serif') parser = arg.ArgumentParser(description="Plot SK graph") parser.add_argument('-f', default='') parser.add_argument('-legend', default='') parser.add_argument('-ymove', default=10.0, type=float) parser.add_argument('-d', default='.') parser.add_argument('-title', default='') parser.add_argument('-on_line', default=False, action='store_true') parser.add_argument('-legend_prefix', default='') parser.add_argument('-png', default='', type=str) parser.add_argument('-xrange', default='', type=str) parser.add_argument('-arrow', default='') parser = parser.parse_args() if parser.d != ".": files = os.listdir(parser.d) else: files = [parser.f] parser.d = "" files.sort() data_list = [] for f in files: print f dir = parser.d + "/" if parser.d else "" if os.path.isfile(dir + f): data_list.append(np.loadtxt(dir + f)) x = data_list[0][:,0] min_x = min(x) max_x = max(x) if parser.xrange: max_x = float(parser.xrange) plt.xlim(min(x), max_x) plt.xlim( (min_x, max_x) ) legend = parser.legend.split(";") if ';' in parser.legend else [] #ll = [ "%s%s" % (parser.legend_prefix, x) for x in legend ] #legend = ll plot_list = [] scale_idx = 0 if legend: data_list = data_list[0:len(data_list)] for d in data_list: y = d[:,1] * np.math.pow(10, scale_idx) plot_list.append(plt.semilogy(x, y)) scale_idx += 1 print scale_idx plt.title(parser.title) plt.xlabel('k') plt.ylabel('S(k)') idx = 0 if legend: if parser.on_line: for l in legend: plt.annotate(l, xy= ((max_x - min_x)/2, np.math.pow(11, idx) + 0.5)) idx += 1 else: plt.legend(plot_list[0:len(legend)], legend, 'upper right') #if parser.arrow: # arrow_position = [ tuple([ float(z) for z in x.split(",")]) for x in parser.arrow.split(";") ] # for pos in arrow_position: if parser.png: plt.savefig(parser.png) else: plt.show() <file_sep>import sys import numpy as np input_file = open(sys.argv[1], "r") in_lines = input_file.readlines() last_symbol = '' return_dict = {} table = [] tmp = [] for l in in_lines: try: value = float(l) tmp.append(value) except: key = l.replace("\n", "") if key != "": if key not in return_dict: return_dict[key] = [] if tmp != []: table.append(tmp[:]) tmp = [key] else: tmp = [key] last_symbol = key table.append(tmp[:]) keys = [] for l in table: keys.append(l[0]) keys.insert(0, '') table.insert(0, keys) tmp_table = [] for x in range(1, len(table)): tmp_table.append(table[x][1:]) tab = np.array(tmp_table) ta = [] for row in range(len(tab)): tt = [] tt.extend(list(tab[:,row][0:row])) tt.extend(list(tab[row][row:])) ta.append(tt) np.savetxt('output_mj', ta, delimiter=';', fmt="%.4f") for l in ta: row = zip(keys[1:], l) print ",".join(map(lambda x: "'%s': %.4f" % x, row)) <file_sep>import sys import kyotocabinet as kb db = kb.DB() db.open(sys.argv[1], db.OREADER) m = db.match_prefix(sys.argv[2]) m.sort(key=lambda x: x.split('_')[1]) print m[-1] <file_sep>""" Main file for starting experiment Author: <NAME> <<EMAIL>> """ #import pyximport; pyximport.install() import datetime import logging import sys import os from mpi4py import MPI import settings from lib import tools from lib.Lattice import Lattice from lib.Box import Box from main import MC import hotshot import signal ## experiment name defince ## package:experiment_class.experiment_setup ## Exp8:Experiment8.c1 -> exp8.py class Experiment8 method c1_setup #### logging issue if "." in sys.argv[1]: tmp_ex_name = sys.argv[1].split(":") ex_module = tmp_ex_name[0].lower() ex_name = tmp_ex_name[1].split(".") else: ex_name = sys.argv[1].split(':') ex_module = 'experiment' try: job_id = str(os.environ['JOB_ID']) except KeyError: job_id = '' try: job_name = str(os.environ['JOB_NAME']) except KeyError: job_name = '' rank_idx = str(MPI.COMM_WORLD.Get_rank()) rank_idx = "%s_%s_%s_%s_%s" % (sys.argv[1].replace(':','_'), job_name, job_id, rank_idx, datetime.datetime.today().strftime("%Y-%m-%dT%H%M")) x = logging.getLogger() x.setLevel(logging.DEBUG) h = logging.FileHandler(rank_idx + "_log.log") x.addHandler(h) ### # pre-settings ## command to run try: cmd = sys.argv[2] except: cmd = "" valid_cmd = ['clean', 'run', 'start', 'start-box-file', 'continue'] if cmd not in valid_cmd: print "Available commands:" for v in valid_cmd: print " - %s" % v sys.exit(1) logging.debug('Run with command: %s' % cmd) if not cmd in ["run", "start-box-file"]: settings.CREATE_DIR_STRUCTURE = False if cmd in ['continue', 'start']: settings.EXPERIMENT_COPY = int(sys.argv[3]) settings.CREATE_DIR_STRUCTURE = True ## run settings for experiment, it will set something in settings.py m = __import__(ex_module) experiment_object = getattr(m, ex_name[0])() #### PROFILE PROFILER_MC_FILE = "profile_mc" PROFILER_SETUP_FILE = "profile_setup" if settings.PROFILER: prof_mc = hotshot.Profile(PROFILER_MC_FILE) prof_setup = hotshot.Profile(PROFILER_SETUP_FILE) try: experiment_setup = getattr(experiment_object, ex_name[1] + "_setup") if settings.PROFILER: (name, chain) = prof_setup.runcall(experiment_setup) else: (name, chain) = experiment_setup() settings.TEMP_TABLE = name + "_temperatures.cfg" except KeyError, e: print "Can't run method", ex_name[1]+"_setup" print "Available methods:" for key,val in experiment_object.__class__.__dict__.iteritems(): print " ", key print e sys.exit(1) ## handle system signals def handle_12(signum, frame): logging.shutdown() tools.save_file(settings.ROOT_DIR + "neighbours.dump", Lattice.NEIGHBOURS_POSITION) for k,v in settings.EXP_TABLES.iteritems(): tools.save_file(settings.ROOT_DIR + settings.FILES_TEMPLATE['exp'] % k, settings.EXP_TABLES[k]) signal.signal(12, handle_12) try: mc = None if cmd == 'clean': for dir in settings.DIRS.values(): tools.clean_dir(dir) elif cmd == 'run': if settings.PROFILER: print "RUN in PROFILER MODE" print "MC Steps: 100" print "PROFILER_MC_FILE:", PROFILER_MC_FILE print "PROFILER_SETUP_FILE:", PROFILER_SETUP_FILE mc = MC(steps = 100, obj = chain) settings.MC_MODULE = mc try: temp = float(sys.argv[-1]) print "Set temp:", temp settings.LOCAL_T = temp mc.box._localT = temp except: pass prof_mc.runcall(mc.run) prof_mc.close() else: temp = settings.LOCAL_T try: temp = float(sys.argv[-1]) print "Set temp:", temp settings.LOCAL_T = temp except: pass mc = MC(steps = settings.MC_STEPS, obj = chain) if not temp: mc.box._localT = temp settings.MC_MODULE = mc mc.run() elif cmd == 'start': ## start from some configuration print "start start_step temp box_file" start_step = int(sys.argv[4]) temp = float(sys.argv[5]) if "jmol" in sys.argv[6]: box = Box(settings.BOX_SIZE, localT = temp) box.add_chain(chain) box.load_jmol_conf(sys.argv[6]) else: box = tools.load_file(sys.argv[6]) box.localT = temp mc = MC(steps = settings.MC_STEPS, obj = box) settings.MC_MODULE = mc mc.run() elif cmd == "start-box-file": box_file = sys.argv[3] try: start_step = int(sys.argv[4]) print "Start step: ", start_step except: start_step = 0 box = tools.load_file(box_file) box.localT = settings.LOCAL_T mc = MC(steps = settings.MC_STEPS+start_step, obj = box, start_step = start_step) settings.MC_MODULE = mc if settings.PROFILER: import hotshot prof = hotshot.Profile(PROFILER_MC_FILE) prof.runcall(mc.run) prof.close() else: mc.run() elif cmd == 'continue': # continue from some configuration #start_step = int(sys.argv[3]) #temp = float(sys.argv[4]) max_step = max([ int(o.replace('.dump','').split('_')[-1]) for o in os.listdir(settings.DIRS['data']) ]) logging.info("Start from step: %d" % max_step) box_file_name = settings.DIRS['data'] + settings.FILES_TEMPLATE['data'] % (max_step) logging.debug("Box file name: %s" % box_file_name) box = tools.load_file(box_file_name) if not box: raise Exception("Box not found !") mc = MC(steps = settings.MC_STEPS, obj = box, start_step = max_step) settings.MC_MODULE = mc mc.run() logging.shutdown() for k,v in settings.EXP_TABLES.iteritems(): tools.save_file(settings.ROOT_DIR + settings.FILES_TEMPLATE['exp'] % k, settings.EXP_TABLES[k]) #tools.save_file(settings.ROOT_DIR + "neighbours.dump", Lattice.NEIGHBOURS_POSITION) #tools.save_file(settings.ROOT_DIR + settings.FILES_TEMPLATE['exp'] % mc.box.localT, settings.EXP_TABLE) except KeyboardInterrupt: ## stop on Ctrl+C logging.shutdown() for k,v in settings.EXP_TABLES.iteritems(): tools.save_file(settings.ROOT_DIR + settings.FILES_TEMPLATE['exp'] % k, settings.EXP_TABLES[k]) #tools.save_file(settings.ROOT_DIR + "neighbours.dump", Lattice.NEIGHBOURS_POSITION) #tools.save_file(settings.ROOT_DIR + settings.FILES_TEMPLATE['exp'] % mc.box.localT, settings.EXP_TABLE) <file_sep>from Monomer import Monomer class TypeC(Monomer): name = "C" interaction_table = {'C': -1, 'O': -0.5} class TypeO(Monomer): name = 'O' interaction_table = {'O': -1, 'C': -0.5} class TypeC02(Monomer): name = "C" interaction_table = {'C': -1, 'O': -0.2} class TypeO02(Monomer): name = "O" interaction_table = {'O': -1, 'C': -0.2} class TypeC03(Monomer): name = "C" interaction_table = {'C': -1, 'O': -0.3} class TypeO03(Monomer): name = "O" interaction_table = {'O': -1, 'C': -0.3} class TypeC04(Monomer): name = "C" interaction_table = {'C': -1, 'O': -0.4} class TypeO04(Monomer): name = "O" interaction_table = {'O': -1, 'C': -0.4} class TypeC06(Monomer): name = "C" interaction_table = {'C': -1, 'O': -0.6} class TypeO06(Monomer): name = "O" interaction_table = {'O': -1, 'C': -0.6} class TypeC07(Monomer): name = "C" interaction_table = {'C': -1, 'O': -0.7} class TypeO07(Monomer): name = "O" interaction_table = {'O': -1, 'C': -0.7} class TypeC08(Monomer): name = "C" interaction_table = {'C': -1, 'O': -0.8} class TypeO08(Monomer): name = "O" interaction_table = {'O': -1, 'C': -0.8} class TypeC09(Monomer): name = "C" interaction_table = {'C': -1, 'O': -0.9} class TypeO09(Monomer): name = "O" interaction_table = {'O': -1, 'C': -0.9} class TypeC10(Monomer): name = "C" interaction_table = {'C': -1.0, 'O': -1.0} class TypeO10(Monomer): name = "O" interaction_table = {'O': -1.0, 'C': -1.0} <file_sep> from matplotlib import pyplot as plt import mc #from scipy import constants # box size Box_size = range(5, 21) T_c = 2.269 eq_time = 1000 ## time (in sweeps) when systems goes into equilibrium meassure_time = eq_time/20 ## avoid autocorrelation magnetization_avg = [] energy_avg = [] for lattice_size in Box_size: print lattice_size sq_size = float(lattice_size ** 2) sim = mc.MC(size = lattice_size, sweeps=4000, T = T_c, eq_time = eq_time) results = sim.run() #magnetization = map(lambda x: x / float(lattice_size**2), results['magnetization']) magnetization = results['magnetization'][0::meassure_time] #file = open("data/M-T_%.2f.csv" % T, "w+") #file.writelines(["%d\n" % m for m in magnetization ]) #file.close() #energy = results['energy'][eq_time:] ## compute monte carlo average magnetization for given temperature magnetization_avg.append(abs(sum(magnetization))/float(len(magnetization)*sq_size)) #energy_avg.append(sum(energy)/float(len(energy)*sq_size)) del sim plt.title('Magnetization for T = %.2f' % T_c) plt.ylabel('<M>') plt.xlabel('Lattice size') plt.plot(Box_size, magnetization_avg) plt.show() <file_sep>// Copyright 2013 <EMAIL> (<NAME>) // Calculates emission parameters for words and tags. // // Usage: // emission word.count test_case // // Returns: // For each word in the test_case return the word and the tag. // #include <string> #include <fstream> #include <iostream> #include <map> #include <string> #include <sstream> #include <vector> using namespace std; int main(int argc, char **argv) { fstream wordCount(argv[1], fstream::in); map<string, map<string, int> > wordTags; // Count(y->x) map<string, int> unigrams; // Count(y) string line, token, word, event; int wCount; while(getline(wordCount, line)) { stringstream lineStream(line); lineStream >> wCount; lineStream >> event; if (event == "WORDTAG") { lineStream >> token; lineStream >> word; wordTags[token][word] = wCount; } else if (event == "1-GRAM") { lineStream >> token; unigrams[token] = wCount; } } wordCount.close(); map<string, map<string, double> > epsilon; map<string, string> bestTag; map<string, map<string, int> >::iterator it; map<string, int>::iterator it2; double value = 0.0; for (it = wordTags.begin(); it != wordTags.end(); ++it) { for (it2 = it->second.begin(); it2 != it->second.end(); ++it2) { value = (double) it2->second / (double) unigrams[it->first]; epsilon[it2->first][it->first] = value; } } fstream inputDev(argv[2], fstream::in); map<string, double>::iterator it3; while(getline(inputDev, word)) { token = ""; value = 0.0; if(word == "\n" || word == "" || word == " "){ cout << word << endl; } else if (epsilon.count(word) > 0) { for (it3 = epsilon[word].begin(); it3 != epsilon[word].end(); ++it3) { if (it3->second > value) { token = it3->first; value = it3->second; } } cout << word << " " << token << endl; } else { for (it3 = epsilon["_RARE_"].begin(); it3 != epsilon["_RARE_"].end(); ++it3) { if (it3->second > value) { token = it3->first; value = it3->second; } } cout << word << " " << token << endl; } } return 0; } <file_sep># # Monte carlo simulation for Polymer on lattice # Author: <NAME> <<EMAIL>> # # import random import math #SEED = 7777 #random.seed(SEED) class Monomer(object): _position = (0,0,0) id = '' _interaction_table = {} neighbours_table = [] @property def position(self) return self._position @position.setter def position(self, value): pass def get_interaction(self, monomer): return self._interaction_table[monomer.id] class A(Monomer): id = 'A' class Lattice(object): """ 3-D lattice, cubic """ box_size = 0 p_size = 0 energy = 0 _polymer_chain = [] def __init__(self, box_size, polymer_chain_size): self.box_size = box_size self.size = polymer_chain_size self.randomize() def randomize(self): """ Randomize polymer """ ## pick random starting position pos = [ random.randrange(0, self.size) for tmp in range(3) ] number_units = 1 while number_units < self.size: ## pickup random position nb_pos = self.neighbours(pos, random.randrange(6)) print nb_pos if nb_pos in self._polymer_chain: continue self._polymer_chain.append(nb_pos) pos = nb_pos[:] number_units += 1 def neighbours(self, position, number): positions = (self._get_left_x, self._get_right_x, self._get_top_y, self._get_down_y, self._get_top_z, self._get_down_z) return positions[number](position) def snapshot(self): """ Return snapshot of configuration to RasMol format """ file = open('snapshot', 'w+') file.writelines("%d\n\n" % len(self._polymer_chain)) [ file.writelines("C %s\n" % (" ".join(map(str, self._polymer_chain[idx])))) for idx in range(len(self._polymer_chain)) ] file.close() ## get positions def _get_left_x(self, cp): return ((cp[0] - 1) % self.box_size, cp[1], cp[2]) def _get_right_x(self, cp): return ((cp[0] + 1) % self.box_size, cp[1], cp[2]) def _get_top_y(self, cp): return (cp[0], (cp[1] + 1) % self.box_size, cp[2]) def _get_down_y(self, cp): return (cp[0], (cp[1] - 1) % self.box_size, cp[2]) def _get_top_z(self, cp): return (cp[0], cp[1], (cp[2] + 1) % self.box_size) def _get_down_z(self, cp): return (cp[0], cp[1], (cp[2] - 1) % self.box_size) class MC(object): ## MC config sweeps = 0 ## physical constants _T = None ## improvments, precompute exp vector _exp = [0]*9 ## stats acceptance = 0 def __init__(self, size, polymer_size, T, sweeps): """ @parms size - size of box polymer_size - size of polymer chain T - temperature sweeps - number of sweeps """ self.lattice_size = size self.polymer_size = polymer_size self.lattice_size_sq = size**3 self.T = T self.lattice = Lattice(size, polymer_size) self.sweeps = sweeps @property def T(self): return self._T @T.setter def T(self, value): self._T = value def _step(self): """ One step Return if accept or reject new configuration """ pass def run(self): """ Run simulation """ pass mc = MC(50, 30, 1, 100) mc.lattice.snapshot() ## for doc test #if __name__ == "__main__": # import doctest # doctest.testmod(extraglobals={'lattice': Lattice(10)}) <file_sep>## compute autocorrelation ## <NAME> <<EMAIL>> ## import sys import numpy as np from matplotlib import pyplot as plt try: file_name = sys.argv[1] eq_steps = int(sys.argv[2]) time = int(sys.argv[3]) column = int(sys.argv[4]) except: print "Generate autocorrelation" print "file_name, mc_steps, ac_time, column, output file" print "\tmc_steps - where is the point of equilibrium" print "\tac_time - autocorrelation measure time" print "\tcolumn - which column need to be measure" output_file = None try: output_file = sys.argv[5] except: output_file = None data = [ float(x.replace(",",".").split(';')[column]) for x in open(file_name).readlines() if int(x.replace(",",".").split(";")[0]) >= eq_steps ] l_data = len(data) var_data = np.var(data) mean_data = np.mean(data) ret = [] if output_file: out_f = open(output_file, 'w+') for t in range(time): norm = 1.0/(l_data - t) tmp = norm*sum([ (data[x] - mean_data)*(data[x+t] - mean_data) for x in range(l_data - t)]) ret.append(tmp) ret = np.array(ret) ret = ret / ret[0] plt.plot(ret) plt.show() if output_file: out_f.writelines([ "%f\n" % x for x in ret ]) <file_sep>''' Created on 1 Nov 2011 @author: teodor ''' import itertools import logging import math import random from mpi4py import MPI import numpy as np #import bigfloat from math import exp import settings import tools import numpy import time from lib.Polymer import Chain from lib.Lattice import Lattice class Box(object): box_size = (0,0,0) chain_list = [] fixed_objects = [] number_of_chains = 0 lattice = None total_energy = 0.0 athermal_state = False temperature_history = [] acceptation_count = 0 ## statistic information _localT = -1.0 def __init__(self, box_size, localT = 0.0): """ @tuple box_size @float localT Main class for Box """ self.box_size = box_size self.chain_list = [] self.disabled_chains = None self.localT = localT # global set for Lattice argh! Lattice.box_size = box_size self.lattice = Lattice(box_size) if self.box_size == (0,0,0) or not self.lattice: raise Exception("Problem with BOX initializing") def get_localT(self): return self._localT def set_localT(self, value): self._localT = value ## do some other fancy stuff Box._locaT = value self.temperature_history.append(value) ## move to chain for chain in self.chain_list: chain.temperature_history.append(value) ## load new value of exp if value in settings.EXP_TABLES: settings.EXP_TABLE = settings.EXP_TABLES[value] logging.info('change exp_table %f ' % value) else: settings.EXP_TABLE = tools.load_file(settings.ROOT_DIR + \ settings.FILES_TEMPLATE['exp'] % value, {}) settings.EXP_TABLES[value] = settings.EXP_TABLE logging.info('load new exp_table %f' % value) logging.info("Set temperature to: %f" % value) localT = property(get_localT, set_localT) ######################################################################### def random_strategy(self, chain): """ Put chain in random mode """ random_point = tuple(map(lambda x: x/2, self.box_size)) while self.is_occupied(random_point) or not Lattice.is_valid_coordinate(random_point): random_point = tuple([ random.randrange(0, self.box_size[x]) for x in range(3) ]) if __debug__: logging.info("Chain start point: %d, %d, %d" % random_point) f_monomer = chain.chain[0] f_monomer.position = random_point f_monomer._open = random_point chain[0] = f_monomer for idx in range(1, chain._total_length): prev_monomer = chain.chain[idx - 1] monomer = chain.chain[idx] not_found = True direction_list = range(0, Lattice.z) direction_list_idx = Lattice.z while not_found: try: direction_idx = random.randrange(0, direction_list_idx) except: return False direction = direction_list[direction_idx] pos = Lattice.get_coordinate(prev_monomer._position, direction) open_pos = Lattice.get_open_coordinate(prev_monomer._open, direction) if pos in chain.positions_list or \ (self.number_of_chains > 1 and self.is_occupied(pos)): not_found = True direction_list.remove(direction) direction_list_idx -= 1 else: not_found = False monomer.position = pos monomer.open_position = open_pos #monomer.next_direction = None prev_monomer.next_monomer = monomer prev_monomer.next_direction = direction chain[idx] = monomer chain.chain[idx-1] = prev_monomer ## rebuild directions for idx in range(1, chain._total_length): p = chain.chain[idx - 1] m = chain.chain[idx] d = p.neighbours_position.index(m._position) p.next_direction = d chain.chain[idx - 1].next_direction = d chain.chain[-1].next_direction = 0 if __debug__: logging.info('Chain inside box, length=%d' % chain.length) return chain def greedy_strategy(self, chain): """ Put chain in the box based on a greedy strategy """ random_point = tuple(map(lambda x: x/2, self.box_size)) while self.is_occupied(random_point) or not Lattice.is_valid_coordinate(random_point): random_point = tuple([ random.randrange(0, self.box_size[x]) for x in range(3) ]) f_monomer0 = chain.chain[0] f_monomer0.position = random_point f_monomer0._open = random_point chain[0] = f_monomer0 next_direction = random.randrange(0, Lattice.z) f_monomer1 = chain.chain[1] f_monomer1.position = Lattice.get_coordinate(random_point, next_direction) f_monomer1._open = Lattice.get_open_coordinate(random_point, next_direction) chain[1] = f_monomer1 chain[0].next_direction = next_direction pos_list = [f_monomer0._position, f_monomer1._position] direction_list = range(0, Lattice.z) for idx in range(2, chain._total_length): prev_monomer = chain.chain[idx - 1] monomer = chain.chain[idx] min_energy = self.calculate_chain_energy(chain) min_pos = None min_open_pos = None min_dir = 0 np.random.shuffle(direction_list) last_valid_pos = None last_valid_open_pos = None for dir in direction_list: pos = Lattice.get_coordinate(prev_monomer._position, dir) open_pos = Lattice.get_open_coordinate(prev_monomer._open, dir) if pos in chain.positions_list or \ (self.number_of_chains > 1 and self.is_occupied(pos)) or \ pos in pos_list: pass else: last_valid_pos = pos last_valid_open_pos = open_pos monomer.position = pos monomer._open = open_pos chain[idx] = monomer m_e = self.calculate_chain_energy(chain, slice=[0, idx+1]) if min_energy > m_e: min_energy = m_e min_pos = pos min_open_pos = open_pos min_dir = dir monomer.position = min_pos if min_pos else last_valid_pos monomer._open = min_open_pos if min_open_pos else last_valid_open_pos chain[idx] = monomer prev_monomer.next_direction = min_dir chain[idx - 1] = prev_monomer ## rebuild directions for idx in range(1, chain._total_length): p = chain.chain[idx - 1] m = chain.chain[idx] d = p.neighbours_position.index(m._position) p.next_direction = d chain.chain[idx - 1].next_direction = d if __debug__: logging.info("Greedy strategy, chain with min energy: %f" % \ self.calculate_chain_energy(chain)) return chain def add_chain(self, chain, new = True): """ @Polymer chain: chain object @boolean new: is this a new chain? Add chain to the box """ #random_point = self.lattice.get_random_point() chain.box = self chain.idx = self.number_of_chains self.chain_list.append(chain) self.number_of_chains += 1 if new == True: """ New virgin chain, need to update position of every monomer """ chain_inside = False while not chain_inside: return_chain = self.random_strategy(chain) if return_chain is False: chain_inside = False print "Put again" else: chain_inside = True chain = return_chain #chain = self.greedy_strategy(chain) """ Only add chain to the chain_list, without update monomer positions """ chain.valid_chain() ## update energy of every chain in the box, also every monomer has own energy self.global_energy_update() print "Chain in box with energy", chain.total_energy return len(self.chain_list) - 1 def rebuild_direction(self, chain): ## rebuild directions for idx in range(1, chain._total_length): p = chain.chain[idx - 1] m = chain.chain[idx] d = p.neighbours_position.index(m._position) p.next_direction = d chain.chain[idx - 1].next_direction = d chain.chain[-1].next_direction = 0 return chain def refresh_chains(self): """ Refresh chain positions_list and direction list """ for chain in self.chain_list: monomer0 = chain.chain[0] for idx in range(1, chain._total_length): pass def remove_chain(self, chain): chain_idx = tools.index(self.chain_list, chain) del self.chain_list[chain_idx] self.number_of_chains -= 1 def accept(self, energy_change, new_position = None): """ @float energy_change: change of energy @tuple new_position: new position of monomer Check if change of energy is acceptable (according to current temperature) Accept if energy_change is below """ localT = float(self._localT) return_value = False ## first check if momoner doesn't overlap if new_position != None: if self.is_occupied(new_position): return False if localT <= 0.0 or self.athermal_state is True: return_value = True elif energy_change <= 0.0: return_value = True else: ## cache of exp function #logging.debug("Energy change: %f" % (energy_change)) #if settings.EXP_TABLE.has_key(energy_change): # exp_value = settings.EXP_TABLE[energy_change] #else: if settings.EXP_TABLE.has_key(localT): if settings.EXP_TABLE[localT].has_key(energy_change): exp_value = settings.EXP_TABLE[localT][energy_change] else: exp_value = exp((-1*energy_change) / localT) settings.EXP_TABLE[localT][energy_change] = exp_value else: exp_value = exp((-1*energy_change) / localT) settings.EXP_TABLE[localT] = { energy_change: exp_value} # settings.EXP_TABLE[energy_change] = exp_value ## monte carlo acceptance r = numpy.random.random() if r < exp_value: return_value = True if return_value == True: self.acceptation_count += 1 return return_value def is_occupied(self, position, exclude_chain = None): """ @tuple position: position to check @Polymer exclude_chain: chain which should not be checked Check if given :position: is occupied more than once by some monomers """ if position is None: return False if isinstance(position, set): for chain in self.chain_list: if chain is exclude_chain: continue if position.issubset(set(chain.positions_list)): return True else: for chain in self.chain_list: if chain is exclude_chain: continue if position in chain.positions_list: return True return False def global_energy_update(self, exclude_chains = []): """ Iterate over every chain in box and update its energy """ self.total_energy = 0.0 for chain_idx in range(self.number_of_chains): if chain_idx in exclude_chains: continue chain_energy = self.calculate_chain_energy(self.chain_list[chain_idx]) self.chain_list[chain_idx].total_energy = chain_energy self.total_energy += chain_energy ## we also update energy of box, why not def update_chain_energy(self, chain): """ @Polymer chain: chain of monomers Iterate over chain and update energy of every monomer in chain """ chain.total_energy = self.calculate_chain_energy(chain) # / 2.0 ## cause we calculate energies twice return chain def calculate_chain_energy(self, chain, slice=[]): """ @Chain chain: chain of monomers @list slice: [start, stop] slice of polymer chain """ total_energy = 0.0 if slice != []: start = slice[0] stop = slice[1] else: start = 0 stop = chain._total_length for monomer_idx in xrange(start,stop): energy = self.calculate_monomer_energy(chain.chain[monomer_idx]) chain.chain[monomer_idx].energy = energy total_energy += energy chain.total_energy = total_energy return total_energy def calculate_monomer_energy(self, monomer, exclude_positions = None): """ @Monomer monomer: monomer object @tuple|list exclude_positions: list of exclude positions Calculate energy around :monomer on position :monomer So we take into account :monomers around this one and use interaction_table to get total energy. Exclude positions, if we want to exclude from list of interacted monomres, some positions that we now they should not be consider as an occupied Eg. in movement, we should not take into account old position of :monomer if we try to calculate new energy """ # find monomer on this position # if monomer is an Monomer object, we don't search for it if isinstance(exclude_positions, tuple): exclude_positions = [exclude_positions] if exclude_positions: neighbours = [ nb for nb in monomer.neighbours_position if nb not in exclude_positions ] else: neighbours = monomer.neighbours_position ## save positions of neighbours, but we don't know if on each of them there is a monomer neighbours = set(neighbours) solvent_positions = Lattice.z neighbours_interaction_energy = [] for chain in self.chain_list: #monomers_idx = filter(None, map(lambda x: chain.positions_list.index(x) if x in neighbours else None, chain.positions_list)) #neighbours_interaction_energy += map(lambda x: chain.chain[x].interaction_table[chain.chain[x].name], monomers_idx) check_positions = set(chain.positions_list).intersection(neighbours) neighbours_interaction_energy += [ monomer.interaction_table[x.name] for x in chain.chain if x._position in check_positions ] solvent_positions -= len(neighbours_interaction_energy) ## calculate energy E = 0.0 E += sum(neighbours_interaction_energy) if solvent_positions > 0 and monomer.interaction_table.has_key('_s'): if monomer.interaction_table['_s'] != 0.0: E += solvent_positions*monomer.interaction_table['_s'] return E def get_box(self): """ Return list of chains in box, valid for send via MPI """ ret = [] for c in self.chain_list: pos = [ m._position for m in c.chain ] open_pos = [ m._open for m in c.chain ] ret.append( (pos, open_pos)) return ret def update_box(self, conformations): """ """ for idx in range(len(conformations)): pos, open_pos = conformations[idx] chain = self.chain_list[idx] for i in range(chain._total_length): chain[i].position = pos[i] chain[i]._open = open_pos[i] chain.positions_list = pos chain = self.rebuild_direction(chain) chain.valid_chain() self.chain_list[idx] = chain def swap(self): """ Swap box according to PT algorithm """ if not settings.PT: return False pt = settings.PT_MODULE pt_rank = pt.rank pt.switch_count += 1 pt.comm.Barrier() if pt_rank == 0: ## only rank = 0, master node time_start = time.time() ## get temperature and energy from every child nodes swapT = np.zeros(pt.size) swapE = np.zeros(pt.size) self.global_energy_update() swapT[0] = self._localT swapE[0] = self.total_energy # swap_table index = 1 # message format: # rank, step, localT, energy while index < pt.size: status = MPI.Status() val = pt.recv(rank = MPI.ANY_SOURCE, tag = settings.TAG, status = status) source = status.Get_source() if len(val) == 3 and source != 0: swapT[source] = val[1] swapE[source] = val[2] index += 1 tmp = [0]*pt.size for i in range(pt.size): for j in range(pt.size): if pt.temp_list[i] == swapT[j] or \ ((pt.temp_list[i] >= swapT[j] - 0.00001) and \ (pt.temp_list[i] <= swapT[j] + 0.00001)): tmp[i] = j break ## swap random configuration rank_vector = np.random.permutation(pt.size) for rank_vector_idx in range(1, pt.size): swap = False selected_rank = tmp[rank_vector[rank_vector_idx]] if swapE[selected_rank] <= swapE[selected_rank-1]: swap = True if __debug__: logging.debug('energy[%d]:%f <= energy[%d]:%d' % (selected_rank, swapE[selected_rank], selected_rank-1, swapE[selected_rank-1])) else: r = np.random.random() value = ( (1.0/swapT[selected_rank - 1]) - (1.0/swapT[selected_rank])) value *= (swapE[selected_rank] - swapE[selected_rank - 1]) exp_value = math.exp(-1*value) if r < exp_value: swap = True if swap: tmpT = swapT[selected_rank] if __debug__: logging.info("%d: Swap temp, to %f from %d on step %d" % (settings.RANK, swapT[selected_rank - 1], selected_rank, settings.CURRENT_STEP)) swapT[selected_rank] = swapT[selected_rank-1] swapT[selected_rank-1] = tmpT ## FOPT pt.switch_histogram[rank_vector_idx - 1] += 1 for ii in range(pt.size): for jj in range(pt.size): if pt.temp_list[ii] == swapT[jj] or \ ((pt.temp_list[ii] >= swapT[jj] - 0.00001) and \ (pt.temp_list[ii] <= swapT[jj] + 0.00001)): tmp[ii] = jj break ## FOPT, swaped tmpUpDown = 0 for i in range(pt.size): tmpUpDown = pt.up_down_tab[i] if (swapT[i] == pt.temp_list[pt.size - 1]) or \ ((swapT[i] <= pt.temp_list[pt.size - 1] + 0.00001) and \ (swapT[i] >= pt.temp_list[pt.size - 1] - 0.00001)): pt.up_down_tab[i] = 2 if (swapT[i] == pt.temp_list[0]) or \ ((swapT[i] <= pt.temp_list[0] + 0.00001) and \ (swapT[i] >= pt.temp_list[0] - 0.00001)): pt.up_down_tab[i] = 1 if pt.up_down_tab[i] !=0 and tmpUpDown != pt.up_down_tab[i]: pt.round_trip[i] += 1 for i in range(pt.size): if pt.up_down_tab[i] == 1: pt.up_histogram[i] += 1 if pt.up_down_tab[i] == 2: pt.down_histogram[i] += 1 # predict if any of replicas is at the end of simulation # if CURRENT_STEP + FREQ_SWAP >= settings.MC_MODULE.stop_step #tmp_step = swapStep[:] #tmp_step += settings.FREQ_SWAP #check = filter(lambda x: x < settings.MC_MODULE.stop_step, tmp_step) #if len(check) != pt.size: # max_current_step = max(swapStep) # current_step = 1 # logging.info("Some of nodes are too fast...") # settings.MC_MODULE.set_stop_simulation() #else: # current_step = -1 # synchronization current_step between replicas, send max value ## send new values for i in range(1, pt.size): data = (pt.rank, swapT[i], -1) pt.send(data, rank = i, tag = settings.TAG) if swapT[0] != 0.0: self.localT = swapT[0] settings.LOCAL_T = swapT[0] else: pass time_delta = time.time() - time_start if __debug__: logging.info("Swap time: %f" % time_delta) else: self.global_energy_update() ## send data to 0-node data = (pt.rank, self._localT, self.total_energy) pt.send(data, rank = 0, tag = settings.TAG) ## send ## get new value of temperature from 0-node status = MPI.Status() send_by, temperature, energy = pt.recv(rank = 0, tag = settings.TAG, status = status) if temperature != 0.0: self.localT = temperature settings.LOCAL_T = temperature if __debug__:logging.debug('%d: Set temperature to: %f from %d' % (settings.RANK, temperature, send_by)) #self.global_energy_update() else: #logging.debug('temperature == 0.0!!') pass ## temperature histogram for i in range(pt.size): if (self._localT == pt.temp_list[i]) or \ ((self._localT <= pt.temp_list[i] + 0.00001) and \ (self._localT >= pt.temp_list[i] - 0.00001)): pt.temperature_histogram[i] += 1 ### def jmol_snapshot(self, file_name): """ Return current state of box in xyz file format """ f = open(file_name, "w+") coordinates = [] for chain in self.chain_list: for monomer in chain.chain: coordinates.append([monomer.name] + list(np.array(monomer._open)*settings.JMOL_SCALE)) f.writelines(["%d\n\n" % len(coordinates)]) f.writelines([ "%s %s\n" % (d[0], " ".join(map(str, d[1:]))) for d in coordinates ]) f.close() def jmol_snapshot_hdf(self, hdfTbl, hdfSet, set_name): coordinates = [] for chain in self.chain_list: idx = 0 for m in chain.chain: coordinates.append([idx] + list(m._open)) idx+=1 scipy_array = coordinates hdfTbl.createArray(hdfSet, set_name, scipy_array, set_name) def jmol_snapshot_string(self): """ Return current state of box in xyz file format """ coordinates = [] for chain in self.chain_list: for monomer in chain.chain: coordinates.append([monomer.name ] + list(monomer._open)) return coordinates def load_jmol_conf(self, file_name, number_of_chains=1): """ Load chain configuration from JMOL file @string file_name: Name of jmol file @dict map_dict: dict with Monomer class @int number_of_chains: number of chains in jmol file """ f = open(file_name, "r+") data = f.readlines() header = int(data[0]) coordinate_data = map(lambda x: x.split(" "), data[2:]) chains = [] for chain_idx in range(number_of_chains): chain_seq = [] slice_coordinate = coordinate_data[chain_idx * header:] self.chain_list[chain_idx].positions_list = [] for c_idx in range(len(slice_coordinate)): c = slice_coordinate[c_idx] crr = tuple(map(lambda x: float(x)/settings.JMOL_SCALE, tuple(c[1:]))) print "Load", crr self.chain_list[chain_idx].chain[c_idx]._open = crr self.chain_list[chain_idx].chain[c_idx].position = Lattice.convert_to_periodic_coordinate(crr) self.chain_list[chain_idx].positions_list.append(self.chain_list[chain_idx].chain[c_idx]._position) self.chain_list[chain_idx] = self.rebuild_direction(self.chain_list[chain_idx]) <file_sep>import os import logging import settings from lib import Polymer, tools from lib.Box import Box, Lattice from lib.mpi import PT from lib.Monomer import TypeA, TypeB, TypeA2, TypeB2 from lib import Monomer class Experiment(object): current_exp_name = None box_size = None temp_list = None def __init__(self): settings.BOX_SIZE = self.box_size Lattice.box_size = self.box_size self.init() def get_base_dir(self, extra = None): """ Build base structure """ exp_dir_name = "%s_%d" % (self.name, settings.RANK) dir = "%s/%s%s/%s" % (os.getcwdu(), settings.EXPERIMENT_DIR, exp_dir_name, extra if extra else "") ## sometimes we need a copy of experiment, additional one will be put in _1, _2 dirs return dir def create_dir_structure(self, name, index = None): """ @name string: name of dir above base_dir @make_copy int: index of dir, if exists create max(index)+1 Create dir structure """ if index != None: base_dir = self.get_base_dir() if settings.CREATE_DIR_STRUCTURE: while os.path.exists(base_dir + (name + "_%d" % index)): max_index = max([ int(p.split('_')[-1]) for p in os.listdir(base_dir) if name in p ]) index = max_index + 1 name_with_index = (name + "_%d") % index settings.BASE_DIR = self.get_base_dir(name_with_index) else: settings.BASE_DIR = self.get_base_dir(name) for name,dir in settings.DIRS.iteritems(): settings.DIRS[name] = settings.BASE_DIR + "/" + settings.DIRS[name] if settings.CREATE_DIR_STRUCTURE: tools.create_dir(settings.DIRS[name]) def update_settings_files(self): """ Update FILES dict in settings """ for name, dir in settings.FILES_TEMPLATE.iteritems(): if settings.DIRS.has_key(name) and settings.FILES_TEMPLATE.has_key(name): settings.FILES[name] = settings.DIRS[name] + settings.FILES_TEMPLATE[name] def _setup(self, name, min_t, max_t, tag, swap = False): """ Setup experiment @string name: name of experiment @float min_t: min temperature @float max_t: max temperature @int tag: tag for mpi communication @bool swap: perform swap? """ settings.EXPERIMENT_NAME = name settings.EXPERIMENT_ROOT_NAME = self.name settings.PERFORM_SWAP = swap PT.min_temp = settings.MIN_T = min_t PT.max_temp = settings.MAX_T = max_t if self.temp_list is None: self.pt = PT() else: self.pt = PT(self.temp_list) if self.pt.size > 0: settings.PT = True settings.LOCAL_T = self.pt.get_temperature() logging.info("Local T: %f" % settings.LOCAL_T) settings.TAG = self.global_tag + tag settings.DELTA_STEP = 0 settings.PT_MODULE = self.pt self.create_dir_structure("%s_%d_%d_%d" % ((name, ) + self.box_size), settings.EXPERIMENT_COPY) self.update_settings_files() self.current_exp_name = name temp_file = "%stemperature" % settings.EXPERIMENTAL_ROOT_DIR if not os.path.exists(temp_file): temp_file_mode = "w+" else: temp_file_mode = "a+" open(temp_file, temp_file_mode).writelines("%s;%f\n" % (name, settings.LOCAL_T)) def set_collect(self, mc_steps, collect, calc, data = None, snapshot = None, pt = 200, athermal=500000, cooling = 0): if collect is False: collect = mc_steps*2 elif collect is None: collect = self.freq['collect'] if calc is False: calc = mc_steps*2 elif calc is None: calc = self.freq['calc'] if data is False: data = mc_steps*2 elif data is None: data = self.freq['data'] if snapshot is False: snapshot = mc_steps*2 elif snapshot is None: snapshot = self.freq['snapshot'] if pt is False: pt = mc_steps * 2 elif pt is None: pt = self.freq['pt'] if athermal is False: athermal = 0 elif athermal is None: athermal = self.freq['athermal'] if cooling is False: cooling = 0 elif cooling is None: cooling = self.freq['cooling'] settings.MC_STEPS = mc_steps settings.FREQ_COLLECT = collect settings.FREQ_DATA = data settings.FREQ_SNAPSHOT = snapshot settings.FREQ_CALC = calc settings.FREQ_SWAP = pt settings.FREQ_ATHERMAL = athermal settings.FREQ_COOLING = cooling <file_sep>from lib.Monomer import Monomer class TypeCys(Monomer): name = "Cys" interaction_table = { 'Cys': -5.4400,'Met': -4.9900,'Phe': -5.8000,'Ile': -5.5000,'Leu': -5.8300,'Val': -4.9600,'Trp': -4.9500,'Tyr': -4.1600,'Ala': -3.5700,'Gly': -3.1600,'Thr': -3.1100,'Ser': -2.8600,'Asn': -2.5900,'Gln': -2.8500,'Asp': -2.4100,'Glu': -2.2700,'His': -3.6000,'Arg': -2.5700,'Lys': -1.9500,'Pro': -3.0700 } class TypeIle(Monomer): name = "Ile" interaction_table = { 'Cys': -5.5000,'Met': -6.0200,'Phe': -6.8400,'Ile': -6.5400,'Leu': -7.0400,'Val': -6.0500,'Trp': -5.7800,'Tyr': -5.2500,'Ala': -4.5800,'Gly': -3.7800,'Thr': -4.0300,'Ser': -3.5200,'Asn': -3.2400,'Gln': -3.6700,'Asp': -3.1700,'Glu': -3.2700,'His': -4.1400,'Arg': -3.6300,'Lys': -3.0100,'Pro': -3.7600 } class TypeSer(Monomer): name = "Ser" interaction_table = { 'Cys': -2.8600,'Met': -3.0300,'Phe': -4.0200,'Ile': -3.5200,'Leu': -3.9200,'Val': -3.0500,'Trp': -2.9900,'Tyr': -2.7800,'Ala': -2.0100,'Gly': -1.8200,'Thr': -1.9600,'Ser': -1.6700,'Asn': -1.5800,'Gln': -1.4900,'Asp': -1.6300,'Glu': -1.4800,'His': -2.1100,'Arg': -1.6200,'Lys': -1.0500,'Pro': -1.5700 } class TypeVal(Monomer): name = "Val" interaction_table = { 'Cys': -4.9600,'Met': -5.3200,'Phe': -6.2900,'Ile': -6.0500,'Leu': -6.4800,'Val': -5.5200,'Trp': -5.1800,'Tyr': -4.6200,'Ala': -4.0400,'Gly': -3.3800,'Thr': -3.4600,'Ser': -3.0500,'Asn': -2.8300,'Gln': -3.0700,'Asp': -2.4800,'Glu': -2.6700,'His': -3.5800,'Arg': -3.0700,'Lys': -2.4900,'Pro': -3.3200 } class TypeGly(Monomer): name = "Gly" interaction_table = { 'Cys': -3.1600,'Met': -3.3900,'Phe': -4.1300,'Ile': -3.7800,'Leu': -4.1600,'Val': -3.3800,'Trp': -3.4200,'Tyr': -3.0100,'Ala': -2.3100,'Gly': -2.2400,'Thr': -2.0800,'Ser': -1.8200,'Asn': -1.7400,'Gln': -1.6600,'Asp': -1.5900,'Glu': -1.2200,'His': -2.1500,'Arg': -1.7200,'Lys': -1.1500,'Pro': -1.8700 } class TypeGln(Monomer): name = "Gln" interaction_table = { 'Cys': -2.8500,'Met': -3.3000,'Phe': -4.1000,'Ile': -3.6700,'Leu': -4.0400,'Val': -3.0700,'Trp': -3.1100,'Tyr': -2.9700,'Ala': -1.8900,'Gly': -1.6600,'Thr': -1.9000,'Ser': -1.4900,'Asn': -1.7100,'Gln': -1.5400,'Asp': -1.4600,'Glu': -1.4200,'His': -1.9800,'Arg': -1.8000,'Lys': -1.2900,'Pro': -1.7300 } class TypePro(Monomer): name = "Pro" interaction_table = { 'Cys': -3.0700,'Met': -3.4500,'Phe': -4.2500,'Ile': -3.7600,'Leu': -4.2000,'Val': -3.3200,'Trp': -3.7300,'Tyr': -3.1900,'Ala': -2.0300,'Gly': -1.8700,'Thr': -1.9000,'Ser': -1.5700,'Asn': -1.5300,'Gln': -1.7300,'Asp': -1.3300,'Glu': -1.2600,'His': -2.2500,'Arg': -1.7000,'Lys': -0.9700,'Pro': -1.7500 } class TypeLys(Monomer): name = "Lys" interaction_table = { 'Cys': -1.9500,'Met': -2.4800,'Phe': -3.3600,'Ile': -3.0100,'Leu': -3.3700,'Val': -2.4900,'Trp': -2.6900,'Tyr': -2.6000,'Ala': -1.3100,'Gly': -1.1500,'Thr': -1.3100,'Ser': -1.0500,'Asn': -1.2100,'Gln': -1.2900,'Asp': -1.6800,'Glu': -1.8000,'His': -1.3500,'Arg': -0.5900,'Lys': -0.1200,'Pro': -0.9700 } class TypeThr(Monomer): name = "Thr" interaction_table = { 'Cys': -3.1100,'Met': -3.5100,'Phe': -4.2800,'Ile': -4.0300,'Leu': -4.3400,'Val': -3.4600,'Trp': -3.2200,'Tyr': -3.0100,'Ala': -2.3200,'Gly': -2.0800,'Thr': -2.1200,'Ser': -1.9600,'Asn': -1.8800,'Gln': -1.9000,'Asp': -1.8000,'Glu': -1.7400,'His': -2.4200,'Arg': -1.9000,'Lys': -1.3100,'Pro': -1.9000 } class TypePhe(Monomer): name = "Phe" interaction_table = { 'Cys': -5.8000,'Met': -6.5600,'Phe': -7.2600,'Ile': -6.8400,'Leu': -7.2800,'Val': -6.2900,'Trp': -6.1600,'Tyr': -5.6600,'Ala': -4.8100,'Gly': -4.1300,'Thr': -4.2800,'Ser': -4.0200,'Asn': -3.7500,'Gln': -4.1000,'Asp': -3.4800,'Glu': -3.5600,'His': -4.7700,'Arg': -3.9800,'Lys': -3.3600,'Pro': -4.2500 } class TypeAla(Monomer): name = "Ala" interaction_table = { 'Cys': -3.5700,'Met': -3.9400,'Phe': -4.8100,'Ile': -4.5800,'Leu': -4.9100,'Val': -4.0400,'Trp': -3.8200,'Tyr': -3.3600,'Ala': -2.7200,'Gly': -2.3100,'Thr': -2.3200,'Ser': -2.0100,'Asn': -1.8400,'Gln': -1.8900,'Asp': -1.7000,'Glu': -1.5100,'His': -2.4100,'Arg': -1.8300,'Lys': -1.3100,'Pro': -2.0300 } class TypeMet(Monomer): name = "Met" interaction_table = { 'Cys': -4.9900,'Met': -5.4600,'Phe': -6.5600,'Ile': -6.0200,'Leu': -6.4100,'Val': -5.3200,'Trp': -5.5500,'Tyr': -4.9100,'Ala': -3.9400,'Gly': -3.3900,'Thr': -3.5100,'Ser': -3.0300,'Asn': -2.9500,'Gln': -3.3000,'Asp': -2.5700,'Glu': -2.8900,'His': -3.9800,'Arg': -3.1200,'Lys': -2.4800,'Pro': -3.4500 } class TypeAsp(Monomer): name = "Asp" interaction_table = { 'Cys': -2.4100,'Met': -2.5700,'Phe': -3.4800,'Ile': -3.1700,'Leu': -3.4000,'Val': -2.4800,'Trp': -2.8400,'Tyr': -2.7600,'Ala': -1.7000,'Gly': -1.5900,'Thr': -1.8000,'Ser': -1.6300,'Asn': -1.6800,'Gln': -1.4600,'Asp': -1.2100,'Glu': -1.0200,'His': -2.3200,'Arg': -2.2900,'Lys': -1.6800,'Pro': -1.3300 } class TypeLeu(Monomer): name = "Leu" interaction_table = { 'Cys': -5.8300,'Met': -6.4100,'Phe': -7.2800,'Ile': -7.0400,'Leu': -7.3700,'Val': -6.4800,'Trp': -6.1400,'Tyr': -5.6700,'Ala': -4.9100,'Gly': -4.1600,'Thr': -4.3400,'Ser': -3.9200,'Asn': -3.7400,'Gln': -4.0400,'Asp': -3.4000,'Glu': -3.5900,'His': -4.5400,'Arg': -4.0300,'Lys': -3.3700,'Pro': -4.2000 } class TypeHis(Monomer): name = "His" interaction_table = { 'Cys': -3.6000,'Met': -3.9800,'Phe': -4.7700,'Ile': -4.1400,'Leu': -4.5400,'Val': -3.5800,'Trp': -3.9800,'Tyr': -3.5200,'Ala': -2.4100,'Gly': -2.1500,'Thr': -2.4200,'Ser': -2.1100,'Asn': -2.0800,'Gln': -1.9800,'Asp': -2.3200,'Glu': -2.1500,'His': -3.0500,'Arg': -2.1600,'Lys': -1.3500,'Pro': -2.2500 } class TypeArg(Monomer): name = "Arg" interaction_table = { 'Cys': -2.5700,'Met': -3.1200,'Phe': -3.9800,'Ile': -3.6300,'Leu': -4.0300,'Val': -3.0700,'Trp': -3.4100,'Tyr': -3.1600,'Ala': -1.8300,'Gly': -1.7200,'Thr': -1.9000,'Ser': -1.6200,'Asn': -1.6400,'Gln': -1.8000,'Asp': -2.2900,'Glu': -2.2700,'His': -2.1600,'Arg': -1.5500,'Lys': -0.5900,'Pro': -1.7000 } class TypeTrp(Monomer): name = "Trp" interaction_table = { 'Cys': -4.9500,'Met': -5.5500,'Phe': -6.1600,'Ile': -5.7800,'Leu': -6.1400,'Val': -5.1800,'Trp': -5.0600,'Tyr': -4.6600,'Ala': -3.8200,'Gly': -3.4200,'Thr': -3.2200,'Ser': -2.9900,'Asn': -3.0700,'Gln': -3.1100,'Asp': -2.8400,'Glu': -2.9900,'His': -3.9800,'Arg': -3.4100,'Lys': -2.6900,'Pro': -3.7300 } class TypeGlu(Monomer): name = "Glu" interaction_table = { 'Cys': -2.2700,'Met': -2.8900,'Phe': -3.5600,'Ile': -3.2700,'Leu': -3.5900,'Val': -2.6700,'Trp': -2.9900,'Tyr': -2.7900,'Ala': -1.5100,'Gly': -1.2200,'Thr': -1.7400,'Ser': -1.4800,'Asn': -1.5100,'Gln': -1.4200,'Asp': -1.0200,'Glu': -0.9100,'His': -2.1500,'Arg': -2.2700,'Lys': -1.8000,'Pro': -1.2600 } class TypeAsn(Monomer): name = "Asn" interaction_table = { 'Cys': -2.5900,'Met': -2.9500,'Phe': -3.7500,'Ile': -3.2400,'Leu': -3.7400,'Val': -2.8300,'Trp': -3.0700,'Tyr': -2.7600,'Ala': -1.8400,'Gly': -1.7400,'Thr': -1.8800,'Ser': -1.5800,'Asn': -1.6800,'Gln': -1.7100,'Asp': -1.6800,'Glu': -1.5100,'His': -2.0800,'Arg': -1.6400,'Lys': -1.2100,'Pro': -1.5300 } class TypeTyr(Monomer): name = "Tyr" interaction_table = { 'Cys': -4.1600,'Met': -4.9100,'Phe': -5.6600,'Ile': -5.2500,'Leu': -5.6700,'Val': -4.6200,'Trp': -4.6600,'Tyr': -4.1700,'Ala': -3.3600,'Gly': -3.0100,'Thr': -3.0100,'Ser': -2.7800,'Asn': -2.7600,'Gln': -2.9700,'Asp': -2.7600,'Glu': -2.7900,'His': -3.5200,'Arg': -3.1600,'Lys': -2.6000,'Pro': -3.1900 } <file_sep>''' @author: teodor ''' import tools import random import time from mpi4py import MPI import numpy as np import settings import logging import numpy as np import os class PT(object): comm = None rank = 0 size = 0 name = None min_temp = 0.0 max_temp = 0.0 number_of_nodes = 1 temp_list = [] temp_delta = 0.0 _stepT = 0.0 current_temperature_range = None down_histogram = [] up_histogram = [] up_down_tab = [] round_trip = [] switch_histogram = [] switch_count = 0 ## world_list = {} def __init__(self, temp_list = None): self.comm = MPI.COMM_WORLD self.rank = self.comm.Get_rank() self.size = self.comm.Get_size() self.down_histogram = np.zeros(self.size) self.up_histogram = np.zeros(self.size) self.up_down_tab = np.zeros(self.size) self.temperature_histogram = np.zeros(self.size) self.round_trip = np.zeros(self.size) self.switch_histogram = np.zeros(self.size) self.switch_count = 0 ## initialize random generator ## each of replics need own seed if not settings.DEBUG and not settings.PROFILER: new_seed = time.time() * (self.rank if self.rank > 1 else 1) + self.rank np.random.seed(int(new_seed)) random.seed(int(new_seed)) ## build linear temp list if self.size > 1: self.temp_delta = (self.max_temp - self.min_temp) / float(self.size) if self.temp_delta == 0.0: self.temp_delta = 1.0/float(self.size) else: self.temp_delta = 0.1 # build linear temp list if temp_list: self.temp_list = temp_list else: self.load_temp_table() if __debug__: logging.info("Temp delta: %f" % self.temp_delta) if __debug__: logging.info("Temp list: [%s]" % ",".join(map(str, self.temp_list))) settings.RANK = self.rank settings.SIZE = self.size settings.SIZE_VECTOR = range(self.size) self.world_list = dict(zip(range(self.size), range(self.size))) if __debug__: logging.info('world [%s]' % ",".join(map(str, self.world_list))) def get_temperature(self, rank = None): if not rank: rank = self.rank if len(self.temp_list) == 0 and (self.min_temp - self.max_temp) == 0: return self.min_temp temp_range = self.temp_list[rank] return temp_range def load_temp_table(self): temp_file = settings.ROOT_DIR + "/%s_%s_temperatures_%d.cfg" % (settings.EXPERIMENT_ROOT_NAME, settings.EXPERIMENT_NAME, self.size) self._stepT = 0 try: temp_lines = open(temp_file, 'r').readlines() if temp_lines == []: raise Exception() self._stepT = len(temp_lines) self.temp_list = map(float, temp_lines[-1].split(';')) except: if self.size > 1: delta_temp = self.max_temp - self.min_temp delta_temp /= float((self.size - 1)) else: delta_temp = 0.1 self.temp_list = [ self.min_temp + i*delta_temp for i in range(self.size) ] self._stepT = 1 if self.rank == 0: temp_cfg = open(temp_file, "w+") logging.info("Save init temp table to file %s" % temp_cfg) temp_cfg.writelines(";".join(map(str, self.temp_list))) temp_cfg.writelines("\n") temp_cfg.close() logging.info("Read temp_list: %s" % str(self.temp_list)) logging.info("StepT: %d" % self._stepT) def calculate_round_trip(self): correct = True if self.rank == 0: for i in range(self.size): if self.round_trip[i] < (self._stepT + 2): logging.info('correct _false %s' % str(self.round_trip)) correct = False break if correct: tmpUpDown = np.zeros(self.size) tmpTemp = np.zeros(self.size) for i in range(self.size): tmpUpDown[i] = \ self.up_histogram[i]/(self.up_histogram[i]+ self.down_histogram[i]) tmpTemp[i] = self.temp_list[i] tmpTemp = self.generate_new_temp_table(tmpTemp, tmpUpDown) temp_file = settings.ROOT_DIR + "/%s_%s_temperatures_%d.cfg" % (settings.EXPERIMENT_ROOT_NAME, settings.EXPERIMENT_NAME, self.size) temp_file_f = open(temp_file, 'a') l = ";".join(map(str, tmpTemp)) logging.info("Round trip: %s" % l) temp_file_f.writelines(l) temp_file_f.writelines("\n") temp_file_f.close() for i in range(1, self.size): self.send(settings.MC_MODULE.stop_step, rank = i, tag = settings.TAG+5) else: # need to do more simulation, # change of stop_step on MC object, # also send this new value to other replics new_mc_stop_step = settings.MC_MODULE.stop_step + settings.MC_STEPS settings.MC_MODULE.change_stop_step(new_mc_stop_step) for i in range(1, self.size): self.send(new_mc_stop_step, rank = i, tag = settings.TAG+5) else: status = MPI.Status() new_stop_mc = self.recv(0, tag = settings.TAG+5, status = status) logging.info("%d: Set new stop mc value to: %d" % (settings.RANK, new_stop_mc)) settings.MC_MODULE.change_stop_step(new_stop_mc) def save_histograms(self): """ Save histograms that are used for calculate FOPT """ if self.rank == 0: output_switch = "%sSwitch_%d.hst" % (settings.DIRS['calc'], self._stepT) output_updown = "%sUpDown_%d.hst" % (settings.DIRS['calc'], self._stepT) output_round_trip = "%sRoundTrip_%d.hst" % (settings.DIRS['calc'], self._stepT) output_switch = open(output_switch, "w+") output_updown_f = open(output_updown, "w+") output_round_trip_f = open(output_round_trip, "w+") output_files = [output_switch, output_updown_f, output_round_trip_f] tmpTrip = 0.0 for i in range(self.size): if i < self.size-1: l = "%d;%f;%f\n" % (i, self.temp_list[i], self.switch_histogram[i]/float(self.switch_count)) output_switch.writelines(l) l = "%d;%f;%f\n" % (i, self.temp_list[i], self.up_histogram[i]/float(self.up_histogram[i] + self.down_histogram[i])) output_updown_f.writelines(l) if self.round_trip[i] != 0: tmpTrip = self.round_trip[i] / 2.0 l = "%d;%f;%f;%f\n" % (i, self.temp_list[i], tmpTrip, (settings.MC_MODULE.stop_step - settings.MC_MODULE.start_step)/float(tmpTrip)) output_round_trip_f.writelines(l) else: l = "%d;%f;0.00;0.00\n" % (i, self.temp_list[i]) output_round_trip_f.writelines(l) for output in output_files: output.close() ### save histograms of temperature output_temp_histogram = "%sTemp_%d_%d.hst" % (settings.DIRS['calc'], self.rank, self._stepT) output_temp_histogram_f = open(output_temp_histogram, "a+") for i in range(self.size): l = "%d;%d;%f;%f\n" % (self.rank, i, self.temp_list[i], self.temperature_histogram[i]/float(self.switch_count)) output_temp_histogram_f.writelines("\n") output_temp_histogram_f.close() def send(self, data, rank, tag): """ Send data to the given rank with tag """ #print 'send', data, rank, tag return self.comm.send(data, dest=rank, tag=tag) def recv(self, rank, tag, status): #print 'recv', rank, tag data = self.comm.recv(source = rank, tag = tag, status = status) return data def _new_eta(self, hist, temp): eta = np.zeros(self.size) for i in range(self.size - 1): line_derivative = (hist[i+1] - hist[i])/(float(temp[i+1] - temp[i])) eta[i] = np.sqrt( np.fabs(line_derivative)/(temp[i+1] - temp[i])) return eta def _integrate(self, x, y): return sum([ y[i]*(x[i+1] - x[i]) for i in range(len(x) - 1) ]) def _get_kt(self, temp, eta, k): M = float(k) / float(self.size - 1) sum = 0.0 i = 0 while sum < M - 0.0001: sum += eta[i]*(temp[i+1] - temp[i]) i += 1 return temp[i] - (sum - M)/eta[i-1] def _normalize_y(self, x, y): c = 1.0/self._integrate(x, y) return c * y def _new_temps(self, temp, eta): new_temp = [0.0] * self.size new_temp[0] = temp[0] for k in range(1, self.size - 1): new_temp[k] = self._get_kt(temp, eta, k) new_temp[self.size - 1] = temp[self.size - 1] return new_temp def generate_new_temp_table(self, temp, hist): eta = self._new_eta(hist, temp) eta = self._normalize_y(temp, eta) temp = self._new_temps(temp, eta) return temp def conformation_exchange(self, current_replica): """ Get conformation @tuple current_replica: (total_energy, conformations, rank) """ message_tag = 7 current_replica.append(self.rank) if self.rank == 0: ## master node, gather all information about conformations time_start = time.time() index = 1 datas = { current_replica[0]: current_replica } while index < self.size: status = MPI.Status() energy, chain_list, source = self.recv(rank = MPI.ANY_SOURCE, tag = settings.TAG + message_tag, status = status) source = status.Get_source() print "Get from: ", source if source != 0: datas[energy] = (energy, chain_list, source) index += 1 # check which of conformation is in lowest energy state min_energy = min(datas.keys()) conformation = datas[min_energy] print "Conformations on replicas:" for e,c in datas.iteritems(): print "%d: Energy: %f" % (c[2], e) print "Found conformation with energy: %f on replica: %d" % (min_energy, conformation[2]) # send to other # tuple: (total_energy, conformations, rank) for i in range(1, self.size): self.send(conformation, rank = i, tag = settings.TAG + message_tag) return conformation[1] else: self.send(current_replica, rank = 0, tag = settings.TAG + message_tag) ## status = MPI.Status() energy, conformation, source = self.recv(rank = 0, tag = settings.TAG + message_tag, status = status) print "%d: Get conformation with energy: %f" % (self.rank, energy) return conformation <file_sep>import os import sys import numpy as np from scipy import constants as const import argparse as arg import glob from lib.tools import f_avg, f_avg2, f_cv2, avg_dict, save_dict_to_csv parser = arg.ArgumentParser(description="Process files") parser.add_argument('--config-file', help="Config file", dest="cfile") parser.add_argument('-r', help='Root dir where experiment is stored', type=str, default='') parser.add_argument('-er', help='Root dir where files are stored', type=str, default='') parser.add_argument('-e', help='Experiment name', default='', type=str) parser.add_argument('-s', help="Setup name, eg. m7", default="", type=list) parser.add_argument('-f', help="From temp", default=0.0, type=float) parser.add_argument('-t', help="To: temp", default=None, type=float) parser.add_argument('-ac', help="Autocorrelation step", default=1, type=int) parser.add_argument('-fs', help="From step", default=0, type=int) parser.add_argument('-N', help="Number of monomers", type=int) parser.add_argument('--exclude', action='append', help="Exclude temperature", default=[], type=list) parser.add_argument('--csvplot', help="Create only cvs files for plot", default=False, action='store_true') parser.add_argument('--csv', help="Save partial csv files for each temperature", default=False, action='store_true') parser.add_argument('--csv-dir', help="Where to save partial csv files", default="", dest="csv_dir") result = parser.parse_args() root_dir = result.r ex_root_dir = result.er EXP_NAME = exp_name = result.e SETUP_NAME = result.s FROM_TEMP = result.f TO_TEMP = result.t EXCLUDED_TEMP = result.exclude NUMBER_OF_MONOMERS = result.N CREATE_CSV = result.csvplot PARTIAL_CSV = result.csv CSV_DIR = result.csv_dir AC_STEP = result.ac FROM_STEP = result.fs try: config_file = result.cfile execfile(config_file) except: print "Can't read config file" if not CREATE_CSV: from matplotlib import pyplot as plt exp_name = EXP_NAME ########## print config print "root_dir:", root_dir print "exp_name:", exp_name print "setup_name:", SETUP_NAME print "config_file:", config_file print "FROM_TEMP:", FROM_TEMP print "TO_TEMP:", TO_TEMP print "FROM_STEP:", FROM_STEP print "EXCLUDED_TEMP:", EXCLUDED_TEMP print "AUTOCORRELATION:", AC_STEP print "NUMBER_OF_MONOMERS:", NUMBER_OF_MONOMERS print "CREATE_CSV:", CREATE_CSV print "PARTIAL_CSV:", PARTIAL_CSV ######################### ### process files data_e = {} t_data_e = {} data_rg = {} t_data_rg = {} t_data_rg_others = {} data_e2e = {} t_data_e2e = {} tmp_s = root_dir.split('/') csv_basename = exp_name dirs = [] files = [] if not ex_root_dir: exp_dirs = [ "%s/%s" % (root_dir, d) for d in os.listdir(root_dir) if os.path.isdir(root_dir + "/" + d) and exp_name in d ] print "Found dirs" print "\t\n".join(exp_dirs) for d in exp_dirs: for s in SETUP_NAME: dd = [ "%s/%s" % (d, o) for o in os.listdir(d) if os.path.isdir(d + "/" + o) and s in o] dirs.extend(dd) for d in dirs: for p in glob.glob(d + "/calc/*calc_*.csv"): if os.path.exists(p): files.append(p) else: files_list = [ d + "/" + f for f in os.listdir(d) if 'calc' in f and not os.path.isdir(d+"/"+f) ] if files_list is not []: files.extend(files_list) else: for p in glob.glob(ex_root_dir + "/*.csv"): if os.path.exists(p): files.append(p) else: files_list = [ ex_root_dir + "/" + f for f in os.listdir(ex_root_dir) if 'calc' in f and not os.path.isdir(d + "/" + f) ] if files_list is not []: files.extend(files_list) print "Found files" print "\n".join(files) for f in files: try: data = np.loadtxt(f, delimiter=';', skiprows=0) # data = open(f).readlines()[1:] ## half of data #data = data[len(data)/2:] temp_list = set() for line in data: #sl = line.split(';') temp = float(line[1]) temp_list.add(temp) step = float(line[0]) if (temp <= FROM_TEMP) or \ (TO_TEMP and temp > TO_TEMP) or \ (EXCLUDED_TEMP and temp in EXCLUDED_TEMP): continue if not (step % AC_STEP == 0) or step < FROM_STEP: continue e = float(line[-1]) e2e = float(line[-2])**2 rg = float(line[2]) try: if step in t_data_e[temp]: t_data_e[temp][step].append(e / float(2)) else: t_data_e[temp][step] = [e / float(2)] except Exception, exception: t_data_e[temp] = {step: [e / float(2)]} try: if step in t_data_rg[temp]: t_data_rg[temp][step].append(rg) else: t_data_rg[temp][step] = [rg] except: t_data_rg[temp] = {step: [rg]} try: if step in t_data_e2e[temp]: t_data_e2e[temp][step].append(e2e) else: t_data_e2e[temp][step] = [e2e] except: t_data_e2e[temp] = {step: [e2e]} print "Process:", f, ",".join(map(str, temp_list)) del data except: print "Fail to process:", f error_e = [] error_rg = [] ## save pure csv to files temp_exp_name.csv if PARTIAL_CSV: if not os.path.isdir(CSV_DIR): os.makedirs(CSV_DIR) csv_rg_file = "rg_" + exp_name + ".csv" csv_e_file = "e_" + exp_name + ".csv" temps = t_data_rg.keys() temps.sort() for temp in temps: rg_file = "%s/%f_%s" % (CSV_DIR, temp, csv_rg_file) e_file = "%s/%f_%s" % (CSV_DIR, temp, csv_e_file) save_dict_to_csv(t_data_rg[temp], rg_file) save_dict_to_csv(t_data_e[temp], e_file) data_e = avg_dict(t_data_e) data_rg = avg_dict(t_data_rg) data_e2e = avg_dict(t_data_e2e) for k,v in data_e.iteritems(): del v[v.index(max(v))] del v[v.index(min(v))] data_e[k] = v error_e.append((k, np.std(v)/np.math.sqrt(len(v)))) for k,v in data_rg.iteritems(): del v[v.index(max(v))] del v[v.index(min(v))] data_rg[k] = v error_rg.append((k, np.std(v)/np.math.sqrt(len(v)))) temp = data_e.keys() temp.sort() e = [] e2 = [] rg = [] e2e = [] for k,v in data_e.iteritems(): print "E", k, len(v) e.append((k, f_avg(v))) e2.append((k, f_avg2(v))) for k,v in data_rg.iteritems(): rg.append((k, f_avg(v))) e2e.append((k, f_avg(data_e2e[k]))) ## sort e.sort(key = lambda x: x[0]) e2.sort(key = lambda x: x[0]) rg.sort(key = lambda x: x[0]) e2e.sort(key = lambda x: x[0]) error_e.sort(key = lambda x: x[0]) error_rg.sort(key = lambda x: x[0]) error_e = map(lambda x: x[1], error_e) error_rg = map(lambda x: x[1], error_rg) #print "\n".join(map(str, error_e)) #print "\n".join(map(str, error_rg)) e = map(lambda x: x[1], e) e2 = map(lambda x: x[1], e2) rg = map(lambda x: x[1], rg) e2e = map(lambda x: x[1], e2e) cv = f_cv2(data_e, NUMBER_OF_MONOMERS) #cv = map(lambda x: x, f_cv(e, e2, temp)) csv_e = open("e_" + csv_basename + ".csv", "w+") csv_rg = open("rg_" + csv_basename + ".csv", "w+") csv_cv = open("cv_" + csv_basename + ".csv", "w+") if CREATE_CSV: csv_e.writelines([ "%f;%f\n" % (temp[x], e[x]) for x in range(len(temp)) ]) csv_e.close() csv_rg.writelines([ "%f;%f\n" % (temp[x], rg[x]) for x in range(len(temp)) ]) csv_rg.close() csv_cv.writelines([ "%f;%f\n" % (temp[x], cv[x]) for x in range(len(temp)) ]) csv_cv.close() #for idx in range(len(temp)): # print temp[idx], e[idx], error_e[idx], rg[idx], error_rg[idx] #print "\n".join(map(str, temp[5:])) #temp_ticks = [1.0, 3.0, 4.0, 5.0, 7.0, 15.0, 30.0] temp_ticks = temp if not CREATE_CSV: fg1 = plt.figure(1, figsize=(8.5, 5)) fg1.subplots_adjust(hspace=0.5) plt.subplot(311) plt.xticks(temp_ticks) plt.title('E*/n vs T*') plt.xlabel('T*') plt.ylabel('E*/n') #plt.xscale('log') plt.grid(b=True) #plt.errorbar(temp, map(lambda x: float(x)/NUMBER_OF_MONOMERS, e), yerr=error_e, figure=fg1) #plt.errorbar(temp, e, yerr=error_e, figure=fg1) plt.plot(temp, map(lambda x: float(x), e), 'x-', figure=fg1) #fg2 = plt.figure(2, figsize=(8.5, 5)) plt.subplot(312) plt.xticks(temp_ticks) plt.title('Rg^2 vs T*') plt.xlabel('T*') plt.ylabel('Rg^2') #plt.xscale('log') plt.grid(b=True) plt.errorbar(temp, rg, yerr=error_rg, figure=fg1) #plt.plot(temp, map(lambda x: float(x), rg), 'x-', figure=fg2) #fg3 = plt.figure(3, figsize=(8.5, 5)) plt.subplot(313) plt.xticks(temp_ticks) plt.xlabel('T*') plt.title('Cv vs T*') plt.ylabel('Cv') #plt.xscale('log') plt.grid(b=True) #temp = [ t for t in temp if t <= 15.0 ] plt.plot(temp, cv[0:len(temp)], 'x-', figure=fg1) plt.show() #plt.show() #fg1.savefig('e_err_graph.png') #fg2.savefig('rg_err_graph.png') #fg3.savefig('cv_err_graph.png') <file_sep>''' Created on 2 Nov 2011 @author: <NAME> <<EMAIL>> ''' import copy import itertools import logging import numpy as np import random #from random import randrange from numpy.random import randint as randrange from lib.Lattice import Lattice from lib.Monomer import Monomer import settings import time class Chain(object): """ Polymer sequence of PolymerBlocks """ ## private _total_length = 0 positions_list = [] _tmp = {} ## public chain = [] _monomer_types = set() _chain_structure = {} box = None total_energy = 0 name = "" idx = 0 # last_values = None TYPE_OF_MOVE = ['begin_rotate', 'end_rotate','segment_rotate', 'end_snake', 'begin_snake', 'pull_move'] MOVE_STATS = [0,0,0,0,0,0] B_ROTATE = 0 E_ROTATE = 1 S_ROTATE = 2 E_SNAKE = 3 B_SNAKE = 4 PULL_MOVE = 5 MOVE_INSIDE = [ B_ROTATE, E_ROTATE, S_ROTATE, ] MOVE_ONE_STEP = [ E_SNAKE, B_SNAKE, PULL_MOVE ] temperature_history = [] move_name = None type_of_move = None ## simple stats min_energy = 0.0 min_rg = 0.0 def __init__(self, chain_sequence, name=""): self.chain = chain_sequence self._total_length = len(chain_sequence) self.name = name if self.name == "": self.name = [ x.name for x in chain_sequence ][0:10] self.positions_list = [] for m in self.chain: self.positions_list.append(m._position) self._monomer_types.add(m.name) self.name = name if self.name == "": self.name = "".join([ x for x in self._monomer_types ][0:10]) if settings.DEBUG or settings.PROFILER: random.seed(1) np.random.seed(1) def move(self, type_of_move): """ @int type_of_move: type of move, if -1 then it is random, otherwise you can put values from TYPE_OF_MOVE """ #type_of_move = self.PULL_MOVE self.move_name = self.TYPE_OF_MOVE[type_of_move] self.type_of_move = type_of_move ## performe move #fnc = getattr(self, self.move_name) #value = fnc() if type_of_move == self.B_ROTATE: value = self.begin_rotate() elif type_of_move == self.E_ROTATE: value = self.end_rotate() elif type_of_move == self.S_ROTATE: value = self.segment_rotate() elif type_of_move == self.E_SNAKE: value = self.end_snake() elif type_of_move == self.B_SNAKE: value = self.begin_snake() elif type_of_move == self.PULL_MOVE: value = self.pull_move() if value: self.MOVE_STATS[type_of_move] += 1 return value def valid_chain(self, assertion=True): """ Check if chain is valid """ if self._total_length != len(self.chain): raise Exception("Length is not correct") ## check next_direction """ for x in xrange(0, self._total_length - 1): curr = self.chain[x] next_m = self.chain[x+1] if curr.neighbours_position[curr.next_direction] != next_m._position: raise Exception("Problem with next_direction for %d" % x ) """ build_position_list = [ x._position for x in self.chain ] if build_position_list != self.positions_list: raise Exception('Chain positions_list problem') first_distance = np.array(self.chain[0]._open) - np.array(self.chain[1]._open) first_distance = first_distance.dot(first_distance) if first_distance != Lattice.neighbour_distance: raise Exception("Distance not valid, should be: %f, but is %f" % (Lattice.neighbour_distance, first_distance)) for idx in range(1, self._total_length - 1): prev_monomer = self.chain[idx-1] curr_monomer = self.chain[idx] distance = np.array(prev_monomer._open) - np.array(curr_monomer._open) distance = distance.dot(distance) if first_distance != distance: raise Exception("Distance between (%d, %d, %d) and (%d, %d, %d) is not correct: %f for idx: %d" % (prev_monomer._open + curr_monomer._open + (distance,idx))) if prev_monomer.neighbours_position[prev_monomer.next_direction] != curr_monomer._position: raise Exception("Problem with next_direction for %d" % (idx-1)) ## check if it is SAW ## build position_list of all occupied place ## check if every position appear only once on the list positions_list = [] for c in self.box.chain_list: positions_list += c.positions_list max_count = max([ positions_list.count(e) for e in positions_list ]) if max_count > 1: raise Exception("SAW problem!") return True def get_direction(self, monomer_b, monomer_a): """ Return direction between two monomers, use to avoid some moves End point: b Start point: a """ if not isinstance(monomer_a, Monomer): monomer_a = self[monomer_a] if not isinstance(monomer_b, Monomer): monomer_b = self[monomer_b] vector = np.array(monomer_b._open) - np.array(monomer_a._open) try: direction = Lattice.get_direction(tuple(vector)) except Exception, e: #logging.debug("get_direction for (%d, %d, %d) - (%d, %d, %d): (%d, %d, %d)" % (monomer_b._open, monomer_a._open, vector)) raise e return direction def end_rotate(self, monomer_idx = None): """ rotate with begin """ random_direction = randrange(0, Lattice.z) new_position = self.chain[-2].neighbours_position[random_direction] if self.box.is_occupied(new_position) or new_position in self.positions_list: #logging.info("Reject rotate; position: (%d, %d, %d) is occupied" % (new_position)) return False monomer = self.chain[-1] # copy old_position = monomer._position old_open_position = monomer._open old_next_direction = self.chain[-2].next_direction old_energy = self.total_energy self.chain[-1].position = new_position self.chain[-1]._open = Lattice.get_open_coordinate(self.chain[-2]._open, random_direction) self.chain[-2].next_direction = random_direction self.positions_list[-1] = new_position perform_move = True new_energy = None dE = None if self.box.athermal_state == False: new_energy = self.box.calculate_chain_energy(self) dE = new_energy - old_energy if self.box.accept(dE, None): perform_move = True else: perform_move = False if perform_move: if not new_energy: new_energy = self.box.calculate_chain_energy(self) self.total_energy = new_energy else: monomer.position = old_position monomer._open = old_open_position self.chain[-2].next_direction = old_next_direction self.chain[-1] = monomer self.positions_list[-1] = old_position self.total_energy = old_energy return perform_move def begin_rotate(self, monomer_idx = None): """ rotate with begin """ random_direction = randrange(0, Lattice.z) #new_position = Lattice.get_coordinate(self.chain[1]._position, random_direction) new_position = self.chain[1].neighbours_position[random_direction] if self.box.is_occupied(new_position) or new_position in self.positions_list: #logging.info("Reject rotate; position: (%d, %d, %d) is occupied" % (new_position)) return False new_monomer = self.chain[0] old_position = self.chain[0]._position old_open_position = self.chain[0]._open old_next_direction = self.chain[0].next_direction old_energy = self.total_energy self.chain[0].position = new_position self.chain[0]._open = Lattice.get_open_coordinate(self.chain[1]._open, random_direction) self.chain[0].next_direction = Lattice.TURN_DIRECTION[random_direction] self.positions_list[0] = new_position perform_move = True new_energy = None if self.box.athermal_state == False: new_energy = self.box.calculate_chain_energy(self) dE = new_energy - old_energy if self.box.accept(dE, None): perform_move = True else: perform_move = False if perform_move: if not new_energy: new_energy = self.box.calculate_chain_energy(self) self.total_energy = new_energy else: new_monomer.position = old_position new_monomer._open = old_open_position new_monomer.next_direction = old_next_direction self.chain[0] = new_monomer self.positions_list[0] = old_position # restore old energy self.total_energy = old_energy return perform_move def begin_snake(self, monomer_idx = None): return self._snake(0) def end_snake(self, monomer_idx = None): return self._snake(1) def _snake(self, move_type): """ Snake move """ #direction_to_choice = range(0, Lattice.z) if settings.DEBUG: self.valid_chain() if move_type == 0: monomer = self.chain[0] elif move_type == 1: monomer = self.chain[-1] #random new position random_direction = randrange(0, Lattice.z) new_position = monomer.neighbours_position[random_direction] open_position = Lattice.get_open_coordinate(monomer._open, random_direction) if self.box.is_occupied(new_position) or new_position in self.positions_list: return False # copy old_position_list = self.positions_list[:] old_open_position_list = [ x._open for x in self.chain ] old_next_direction_list = [ x.next_direction for x in self.chain ] old_energy = self.total_energy self.positions_list = [] """ Update position of monomers in chain (copy) """ if move_type == 0: # left self.positions_list = [new_position] for idx in range(1, self._total_length): self.chain[idx].position = old_position_list[idx - 1] self.chain[idx]._open = old_open_position_list[idx - 1] self.chain[idx].next_direction = old_next_direction_list[idx - 1] self.positions_list += old_position_list[0: self._total_length - 1] self.chain[0].position = new_position self.chain[0]._open = open_position self.chain[0].next_direction = self.box.lattice.TURN_DIRECTION[random_direction] elif move_type == 1: # right for idx in range(0, self._total_length - 1): self.chain[idx].position = old_position_list[idx + 1] self.chain[idx]._open = old_open_position_list[idx + 1] self.chain[idx].next_direction = old_next_direction_list[idx + 1] self.chain[-1].position = new_position self.chain[-1]._open = open_position self.chain[-2].next_direction = random_direction self.positions_list = old_position_list[1:] + [new_position] new_energy = self.box.calculate_chain_energy(self) dE = new_energy - old_energy if dE <= 0.0 or self.box.athermal_state: if settings.DEBUG: self.valid_chain() self.total_energy = new_energy return True elif self.box.accept(dE, None): if settings.DEBUG: self.valid_chain() self.total_energy = new_energy return True else: for idx in xrange(self._total_length): self.chain[idx].position = old_position_list[idx] self.chain[idx]._open = old_open_position_list[idx] self.chain[idx].next_direction = old_next_direction_list[idx] self.positions_list = old_position_list[:] self.total_energy = old_energy if settings.DEBUG: self.valid_chain() return False def segment_rotate(self, monomer_idx = None): """ @Monomer|int monomer: monomer or monomer_idx on chain_list Rotate :monomer """ if monomer_idx is None: monomer_idx = randrange(0, self._total_length - 1) if monomer_idx == 0 or monomer_idx == self._total_length - 1: #logging.debug("Tried to rotate monomer of id: %d which is in the end of polymer chain. It doesn't make sense" % monomer_idx) return False if monomer_idx + 1 >= self._total_length: return False prev_monomer = self.chain[monomer_idx - 1] rotate_monomer = self.chain[monomer_idx] next_monomer = self.chain[monomer_idx + 1] ## we can chouse only position from this set common_neighbours_positions = set(prev_monomer.neighbours_position).intersection(next_monomer.neighbours_position) number_of_positions = len(common_neighbours_positions) if number_of_positions == 0: return False new_position = list(common_neighbours_positions)[randrange(0, number_of_positions)] if not new_position or len(new_position) != 3: if __debug__: logging.debug("New_position %s:" % str(new_position)) return False try: direction = prev_monomer.neighbours_position.index(new_position) except Exception, e: if __debug__: logging.error("Reject segment, error in direction, (%d, %d, %d)" % (new_position)) return False open_position = Lattice.get_open_coordinate(prev_monomer._open, direction) if self.box.is_occupied(new_position): #logging.debug("Reject segment; Position: (%d, %d, %d) is occupied" % (new_position)) return False # make copy of old monomer old_position = rotate_monomer._position old_open_position = rotate_monomer._open old_prev_next_direction = self.chain[monomer_idx - 1].next_direction old_next_direction = rotate_monomer.next_direction old_energy = self.total_energy self.chain[monomer_idx].position = new_position self.chain[monomer_idx]._open = open_position self.chain[monomer_idx].next_direction = self.chain[monomer_idx].neighbours_position.index(next_monomer._position) self.chain[monomer_idx - 1].next_direction = prev_monomer.neighbours_position.index(new_position) self.positions_list[monomer_idx] = new_position new_energy = self.box.calculate_chain_energy(self) #print self.total_energy - current_energy + new_energy, self.total_energy dE = new_energy - old_energy accept = False if dE <= 0.0 or self.box.athermal_state: accept = True elif self.box.accept(dE, new_position): accept = True if accept: #self.valid_chain() self.total_energy = new_energy return True else: # revert self.chain[monomer_idx].position = old_position self.positions_list[monomer_idx] = old_position self.chain[monomer_idx]._open = old_open_position self.chain[monomer_idx - 1].next_direction = old_prev_next_direction self.chain[monomer_idx].next_direction = old_next_direction self.total_energy = old_energy return False def pull_move(self, monomer_idx = None): """ Pull move, <NAME>, <NAME>, <NAME> """ ## flags valid_configuration = False if settings.DEBUG: self.valid_chain() #if monomer_idx is None: monomer_idx = randrange(0, self._total_length - 1) ## two special cases at the begin/end case = 3 old_energy = self.total_energy is_occupied = self.box.is_occupied is_neighbour = self.box.lattice.is_neighbour ## trials with optimization last_affected_idx = 0 # case # 0 - left # 1 - right # 3 - inside # 0 - right # 1 - left #mod_pos = 0 if monomer_idx == 0: ## left dir_1 = randrange(0, Lattice.z) dir_2 = randrange(0, Lattice.z) pos_1 = self.chain[0].neighbours_position[dir_1] pos_2 = self.box.lattice.get_coordinate(pos_1, dir_2) if is_occupied(pos_1) or is_occupied(pos_2): return False #if not is_neighbour(pos_1, pos_2): # return False m1 = self.chain[0] m2 = self.chain[1] open_pos_1 = self.box.lattice.get_open_coordinate(m1._open, dir_1) open_pos_2 = self.box.lattice.get_open_coordinate(open_pos_1, dir_2) old_position_list = self.positions_list[:] #old_monomer_position = [ m._position for m in self.chain ] old_monomer_position = old_position_list old_monomer_open_position = [ m._open for m in self.chain ] old_monomer_next_direction = [ m.next_direction for m in self.chain ] m1.position = pos_2 m1._open = open_pos_2 m2.position = pos_1 m2._open = open_pos_1 ## old energy #self[0] = m1 m1.chain = self self.chain[0] = m1 self.positions_list[0] = m1._position #self[1] = m2 m2.chain = self self.chain[1] = m2 self.positions_list[1] = m2._position #mod_pos = 2 for idx in xrange(2, self._total_length): i_monomer = self.chain[idx] p_monomer = self.chain[idx - 1] diff = np.array(i_monomer._open) - np.array(p_monomer._open) diff = diff.dot(diff) if diff == 2: p_monomer.next_direction = p_monomer.neighbours_position.index(i_monomer._position) break #mod_pos += 1 i_monomer.position = old_monomer_position[idx - 2] i_monomer._open = old_monomer_open_position[idx - 2] i_monomer.next_direction = old_monomer_next_direction[idx - 2] #self[idx] = i_monomer i_monomer.chain = self self.chain[idx] = i_monomer self.positions_list[idx] = i_monomer._position last_affected_idx = idx self.chain[0].next_direction = self.chain[0].neighbours_position.index(self.chain[1]._position) self.chain[1].next_direction = self.chain[1].neighbours_position.index(self.chain[2]._position) case = 0 if settings.DEBUG: self.valid_chain() elif monomer_idx == self._total_length - 1: ## right dir_1 = randrange(0, Lattice.z) dir_2 = randrange(0, Lattice.z) pos_1 = self.chain[-1].neighbours_position[dir_1] pos_2 = self.box.lattice.get_coordinate(pos_1, dir_2) if is_occupied(pos_1) or is_occupied(pos_2): return False open_pos_1 = self.box.lattice.get_open_coordinate(self.chain[-1]._open, dir_1) open_pos_2 = self.box.lattice.get_open_coordinate(open_pos_1, dir_2) old_position_list = self.positions_list[:] #old_monomer_position = [ m._position for m in self.chain ] old_monomer_position = old_position_list old_monomer_open_position = [ m._open for m in self.chain ] old_monomer_next_direction = [ m.next_direction for m in self.chain ] m1 = self.chain[-1] m2 = self.chain[-2] m1.position = pos_2 m1._open = open_pos_2 m2.position = pos_1 m2._open = open_pos_1 #mod_pos = 2 for idx in xrange(self._total_length - 2, -1, -1): i_monomer = self.chain[idx] n_monomer = self.chain[idx+1] diff = np.array(i_monomer._open) - np.array(n_monomer._open) diff = diff.dot(diff) if diff == 2: i_monomer.next_direction = i_monomer.neighbours_position.index(n_monomer._position) break #mod_pos += 1 i_monomer.position = old_monomer_position[idx + 2] i_monomer._open = old_monomer_open_position[idx + 2] i_monomer.next_direction = old_monomer_next_direction[idx + 2] #self[idx] = i_monomer i_monomer.chain = self self.chain[idx] = i_monomer self.positions_list[idx] = i_monomer._position last_affected_idx = idx case = 1 self.chain[-2].next_direction = self.chain[-2].neighbours_position.index(self.chain[-1]._position) self.chain[-1].next_direction = 0 if settings.DEBUG: self.valid_chain() if case == 3: prev_monomer = self.chain[monomer_idx - 1] monomer = self.chain[monomer_idx] next_monomer = self.chain[monomer_idx + 1] random_neighbour_prev = randrange(0, Lattice.z) #if self.box.is_occupied(prev_monomer.neighbours_position[random_neighbour_prev]): # return False #L can be adjenct to i-1 or i+1, randomly choose sub_case = randrange(0, 2) ## 0 - right, 1 - left if sub_case == 0: L_position = next_monomer.neighbours_position[random_neighbour_prev] L_open_position = Lattice.get_open_coordinate(next_monomer._open, random_neighbour_prev) Lnext_direction = self.box.lattice.get_neighbours(L_position).index(next_monomer._position) elif sub_case == 1: L_position = prev_monomer.neighbours_position[random_neighbour_prev] L_open_position = Lattice.get_open_coordinate(prev_monomer._open, random_neighbour_prev) Lprev_direction = self.box.lattice.get_neighbours(L_position).index(prev_monomer._position) C_position = monomer.neighbours_position[random_neighbour_prev] C_open_position = Lattice.get_open_coordinate(monomer._open, random_neighbour_prev) diff = np.array(L_position) - np.array(C_position) diff = diff.dot(diff) if diff != 2: return False if is_occupied(L_position): return False if is_occupied(C_position): if (sub_case == 0 and C_position != prev_monomer._position) or (sub_case == 1 and C_position != next_monomer._position): return False # old_energy #old_energy = self.box.calculate_chain_energy(self) # direction L->C C_nb = self.box.lattice.get_neighbours(C_position) CL_direction = C_nb.index(L_position) LC_direction = self.box.lattice.TURN_DIRECTION[CL_direction] # save old position list old_position_list = self.positions_list[:] #old_monomer_position = [ m._position for m in self.chain ] old_monomer_position = old_position_list old_monomer_open_position = [ m._open for m in self.chain ] old_monomer_next_direction = [ m.next_direction for m in self.chain ] if (sub_case == 0 and prev_monomer._position == C_position) or \ (sub_case == 1 and next_monomer._position == C_position): valid_configuration = True monomer.position = L_position monomer._open = L_open_position if sub_case == 0: monomer.next_direction = Lnext_direction elif sub_case == 1: monomer.next_direction = LC_direction #self[monomer_idx] = monomer monomer.chain = self self.chain[monomer_idx] = monomer self.positions_list[monomer_idx] = monomer._position if sub_case == 0: prev_monomer.position = C_position prev_monomer._open = C_open_position prev_monomer.next_direction = CL_direction #self[monomer_idx - 1] = prev_monomer prev_monomer.chain = self self.chain[monomer_idx - 1] = prev_monomer self.positions_list[monomer_idx - 1] = prev_monomer._position elif sub_case == 1: if not valid_configuration: next_monomer.position = C_position next_monomer._open = C_open_position next_monomer.next_direction = self.box.lattice.TURN_DIRECTION[random_neighbour_prev] #self[monomer_idx + 1] = next_monomer next_monomer.chain = self self.chain[monomer_idx + 1] = next_monomer self.positions_list[monomer_idx + 1] = next_monomer._position prev_monomer.next_direction = random_neighbour_prev #self[monomer_idx - 1] = prev_monomer prev_monomer.chain = self self.chain[monomer_idx - 1] = prev_monomer self.positions_list[monomer_idx - 1] = prev_monomer._position #mod_pos = 2 if not valid_configuration: if sub_case == 0: ## right for j in xrange(monomer_idx - 2, -1, -1): j_monomer = self.chain[j] i_monomer = self.chain[j+1] diff = np.array(j_monomer._open) - np.array(i_monomer._open) diff = diff.dot(diff) if diff == 2: j_monomer.next_direction = j_monomer.neighbours_position.index(i_monomer._position) break #mod_pos += 1 j_monomer.position = old_monomer_position[j+2] j_monomer._open = old_monomer_open_position[j+2] j_monomer.next_direction = j_monomer.neighbours_position.index(i_monomer._position) #self[j] = j_monomer j_monomer.chain = self self.chain[j] = j_monomer self.positions_list[j] = j_monomer._position elif sub_case == 1: for j in xrange(monomer_idx + 2, self._total_length): j_monomer = self.chain[j] i_monomer = self.chain[j-1] diff = np.array(j_monomer._open) - np.array(i_monomer._open) diff = diff.dot(diff) if diff == 2: i_monomer.next_direction = i_monomer.neighbours_position.index(j_monomer._position) break #mod_pos += 1 j_monomer.position = old_monomer_position[j-2] j_monomer._open = old_monomer_open_position[j-2] i_monomer.next_direction = i_monomer.neighbours_position.index(j_monomer._position) #self[j] = j_monomer j_monomer.chain = self self.chain[j] = j_monomer self.positions_list[j] = j_monomer._position if settings.DEBUG: self.valid_chain() ## end move procedure # old_energy, emergency case new_energy = self.box.calculate_chain_energy(self) dE = new_energy - old_energy accept_move = False if dE <= 0.0 or self.box.athermal_state: accept_move = True else: accept_move = self.box.accept(dE, None) if accept_move is True: self.total_energy = new_energy #self.positions_list = [ m._position for m in self.chain ] self.box.global_energy_update([self.idx]) #f = open("mod_pos_%d" % self._total_length, "w+") #f.write("%d\n" % mod_pos) #f.close() #self.valid_chain() else: ## revert if case == 3: if sub_case == 0: monomer_list = xrange(0, monomer_idx+2) elif sub_case == 1: monomer_list = xrange(monomer_idx-1, self._total_length) elif case == 0: monomer_list = xrange(0, self._total_length) elif case == 1: ## monomer_list = xrange(0, self._total_length) #monomer_list = changed_monomer_idx for idx in monomer_list: m = self.chain[idx] old_pos = old_monomer_position[idx] old_dir = old_monomer_next_direction[idx] if m._position != old_pos or m.next_direction != old_dir: m.position = old_monomer_position[idx] m._open = old_monomer_open_position[idx] m.next_direction = old_monomer_next_direction[idx] #self[idx] = m m.chain = self self.chain[idx] = m self.positions_list[idx] = m._position #self.positions_list = old_position_list[:] self.total_energy = old_energy #self.valid_chain() return accept_move def get_length(self): return self._total_length def set_length(self, value): """ Prevent change of chain length """ raise Exception("Chain length cannot be modified") length = property(get_length, set_length) def get_chain_structure(self): """ Return chain structure """ if not self._chain_structure: group_idx = 0 last_type = self.chain[0].name self._chain_structure = { "%s_%d" % (last_type, group_idx): [0,0] } for idx in range(1, self._total_length): key = <KEY> (self.chain[idx-1].name, group_idx) new_key = <KEY> (self.chain[idx].name, group_idx + 1) if self.chain[idx].name != self.chain[idx-1].name: self._chain_structure[key][1] = idx self._chain_structure[new_key] = [idx,0] group_idx += 1 self._chain_structure[key][1] = self._total_length - 1 return self._chain_structure chain_structure = property(get_chain_structure) def get_monomer_types(self): if self._monomer_types != set(): self._monomer_types = set([ m.name for m in self.chain ]) return self._monomer_types monomer_types = property(get_monomer_types) ########### Calculations #################### def get_values_file_header(self): if self.monomer_types == set(): self.monomer_types.update([ m.name for m in self.chain ]) return [ "rg_global" ] + map(lambda x: "rg_%s" % x, list(self.monomer_types)) + ['distance', 'total_energy'] def rg(self, type=None): """ @self self: self of polymer Calculate radius of gyration (actually square) for single self """ if type: monomer_positions = [ np.array(x._open) for x in self.chain if x.name == type ] else: monomer_positions = [ np.array(x._open) for x in self.chain ] center_of_mass = list(np.average(monomer_positions, axis=0)) #reduce(lambda p1, p2: p1 + p2, monomer_positions) / float(len(monomer_positions)) ret = sum([ np.dot(pos-center_of_mass, pos-center_of_mass) for pos in monomer_positions ]) / float(len(monomer_positions)) """ ret = sum([ math.pow(sum(map(lambda x: x**2, map(lambda z,p: z-p, pos, center_of_mass))),2) for pos in self._tmp['monomer_positions'] ]) for pos in self._tmp['monomer_positions']: distance = tools.array_diff(pos, center_of_mass) ret += math.pow(sum(map(lambda x: x**2, distance)), 2) """ return float(ret) def center_of_mass(self, monomer_type = None, positions_list = None): """ @string|None monomer_type: Type of monomer, to calculate center of mass for its groups Return center of mass """ if positions_list: monomer_positions = np.array(positions_list) else: if monomer_type: monomer_positions = [ np.array(x._open) for x in self.chain if x.name == monomer_type ] else: monomer_positions = [ np.array(x._open) for x in self.chain if x.name == monomer_type ] center_of_mass = list(np.average(monomer_positions, axis=0)) #reduce(lambda p1, p2: p1 + p2, monomer_positions) / float(len(monomer_positions)) #ret = map(lambda x: float(x) / self._total_length, reduce(lambda p1, p2: map(lambda x,y: x+y, p1, p2), monomer_positions)) return center_of_mass def calculate_center_of_mass(self): """ Return center of mass for global and of each of groups in multiblock copolymer """ monomer_groups = self.chain_structure ret = [self.center_of_mass()] for group, v in monomer_groups.iteritems(): positions = self.positions_list[v[0]:v[1]] cmm = self.center_of_mass(positions_list = positions) ret += [cmm] return ret def end_to_end_distance(self): """ Return normalized distance between two vectors """ first_monomer = np.array(self.chain[0]._open) last_monomer = np.array(self.chain[-1]._open) distance = last_monomer - first_monomer distance = distance.dot(distance) return distance def end_to_end_vector(self): """ Return end-to-end vector """ first_monomer = np.array(self.chain[0]._open) last_monomer = np.array(self.chain[-1]._open) return last_monomer - first_monomer def calculate_values(self): """ Save results to file, increment counter """ self.valid_chain() if self.monomer_types == set(): self._monomer_types = set([ m.name for m in self.chain ]) rg = [self.rg()] # + [ self.rg(t) for t in self.monomer_types ] #distance = self.end_to_end_distance() #self.total_energy = self.box.calculate_chain_energy(self) self.last_values = rg + [self.total_energy] if self.min_energy > self.total_energy: self.min_energy = self.total_energy if self.min_rg > rg[0]: self.min_rg = rg[0] return True def calculate_rdf(self, monomer_type=None): """ Calculate Radial Distribution Function in the range of 0->box_size + 1 from the center of mass Histogram """ maxbin = 1000 dr = float(min(self.box.box_size)/float(maxbin)) ## bin width hist = [0] * (maxbin+1) monomer_positions = [ np.array(m._open) for m in self.chain if monomer_type == None or m.name == monomer_type ] cmm = reduce(lambda p1, p2: p1 + p2, monomer_positions) / float(self._total_length) ## center of mass diff = [ np.math.sqrt((m - cmm).dot(m - cmm)) for m in monomer_positions ] bins = filter(lambda x: x <= maxbin, [ int(np.ceil(x/dr)) for x in diff ]) hist = [ bins.count(x) for x in range(maxbin) ] return hist ## calculate for each of monomer_position """ for particle in self.chain: center_of_mass = np.array(particle._open) monomer_positions = [ x - center_of_mass for x in chain] square = [ sum(map(lambda x: x**2, x)) for x in monomer_positions ] for i in len(shells): count = len(filter(lambda x: x >= i - 0.25 and x < x + 0.25, square)) shells[i] += count ## # http://www.physics.emory.edu/~weeks/idl/gofr2.html shells /= len(chain) shells = [ shells[i] / (4*np.pi* (i**2)*0.5) for i in range(len(shells)) ] """ def calculate_rdf2(self, monomer_type=None): """ Calculate Radial Distribution Function in the range of 0->box_size + 1 from the center of mass """ monomer_positions = [ np.array(m._open) for m in self.chain if monomer_type == None or m.name == monomer_type ] cmm = reduce(lambda p1, p2: p1 + p2, monomer_positions) / float(self._total_length) ## center of mass diff = [ np.math.sqrt((m - cmm).dot(m - cmm)) for m in monomer_positions ] return diff def calculate_rdf_mean(self, monomer_type=None): """ Calculate average """ monomer_positions = [ np.array(m._open) for m in self.chain if monomer_type == None or m.name == monomer_type ] ### so we calculate diff between each pair of monomers, not only difference between cmm and monomers monomer_positions_product = list(itertools.product(monomer_positions, monomer_positions)) diff = map(lambda x: x[0].dot(x[1]), monomer_positions_product) return diff def __getitem__(self, key): """ Return monomer """ if isinstance(key, tuple): return self.chain[self.positions_list.index(key)] return self.chain[key] def __setitem__(self, key, value): """ Set monomer in chain """ value.chain = self self.chain[key] = value self.positions_list[key] = value._position <file_sep>from matplotlib import pyplot as plt import mc from scipy import constants Temp = 2.0 sim = mc.MC(size=10, sweeps=50000, T = Temp, eq_time = 100) results = sim.run() magnetization = map(lambda x: x / float(sim.lattice_size_sq), results['magnetization'][0::150]) energy = map(lambda x: x / float(sim.lattice_size_sq), results['energy'][0::150]) plt.figure(1) plt.subplot(211) plt.title('Magnetization per spin for T=%f' % Temp) plt.ylabel('<M>') plt.plot(magnetization, '.') plt.subplot(212) plt.title('Energy per spin') plt.xlabel('MC Sweeps') plt.ylabel('Energy/NN') plt.plot(energy) plt.show() <file_sep>#!/bin/bash if [ "X$1" == "X" ] || [ "X$2" == "X" ] || [ "X$3" == "X" ]; then echo "Usage:" echo -e "\t./`basename $0` root_path experiment_name out_dir path_to_get" exit 1 fi EXP_PATH="$1" EXPERIMENT_NAME="$2" OUT="$3" PATH_TO_GET="$4" find $EXP_PATH -name $EXPERIMENT_NAME find $EXP_PATH -name $EXPERIMENT_NAME | while read a; do PREFIX="`echo $a | cut -f2 -d'/'`" echo "PREFIX: $PREFIX" cp -vv $a/$PATH_TO_GET "$EXPERIMENT_NAME/${PREFIX}_`basename ${PATH_TO_GET}`" done <file_sep>import os import sys import shutil import argparse as arg from mpi4py import MPI parser = arg.ArgumentParser(description="Sort jmol files for calculate structure factor") parser.add_argument('-r', help="Experiment root dir") parser.add_argument('-e', help="Experiment name") parser.add_argument('-d', help='Destination root folder') parser.add_argument('-c', help='Config file') parser.add_argument('-eq', help='Equilibrium step', default=0, type=int) parser.add_argument('-s', help='Autocorrelation step', default=1, type=int) result = parser.parse_args() root_dir = result.r exp_name = result.e dest_dir = result.d from_step = result.eq s = result.s try: config_file = result.c execfile(config_file) except: print "Can't read config file", config_file print "Root dir", root_dir print "Exp name", exp_name print "Dest dir", dest_dir print 'Equilibrium step', from_step print 'AC step', s print "Config file", config_file if not os.path.isdir(dest_dir) and not os.path.exists(dest_dir): os.makedirs(dest_dir) ## ## Get list of calc_.csv files ## exp_dirs = [ root_dir + "/" + d for d in os.listdir(root_dir) if os.path.isdir(root_dir + "/" + d) and exp_name in d ] dirs = [] files = [] for d in exp_dirs: dd = [ d+"/"+o for o in os.listdir(d) if os.path.isdir(d + "/" + o) ] dirs.extend(dd) for d in dirs: if os.path.exists(d + "/calc/calc_.csv"): files.append((d, d + "/calc/calc_.csv")) else: files_list = [ (d, d + "/" + f) for f in os.listdir(d) if 'calc' in f and not os.path.isdir(d+"/"+f) ] if files_list is not []: files.extend(files_list) comm = MPI.COMM_WORLD rank = comm.Get_rank() size = comm.Get_size() print "Total exp dirs", len(files) if size > 0: files_len = len(files) chunk_len = files_len / size print "Rank", rank, "Size", size, "From", chunk_len*rank, "to", chunk_len*rank + chunk_len if rank == size -1: files = files[chunk_len*rank:] else: files = files[chunk_len*rank:chunk_len*rank + chunk_len] temp_set = set() for dir, calc_file in files: data = open(calc_file).readlines()[1:] for line in data: sl = line.split(";") temp = float(sl[1]) temp_set.add(temp) step = float(sl[0]) if step < from_step: continue if step % s != 0: continue tmp_exp_name = dir.split("/")[-1] jmol_path = "%s/models/jmol_%d.jmol" % (dir, step) output_dir = "%s/%f" % (dest_dir, temp) output_path = "%s/%s_jmol_%d.xyz" % (output_dir, tmp_exp_name, step) if not os.path.isdir(output_dir): os.makedirs(output_dir) try: if not os.path.exists(output_path): shutil.copy(jmol_path, output_path) print "Copy", jmol_path,"to", output_path else: print "File exists", output_path except: print "File not found", jmol_path print "Temp set", temp_set <file_sep># <NAME> <<EMAIL>> # Define experiments # Article from 2011 from lib import Polymer, tools from lib.Monomer import TypeC, TypeO from lib.MonomerExp8e import TypeC as TypeC05 from lib.MonomerExp8e import TypeO as TypeO05 import lib.MonomerExp8e as MLib from lib.Experiment import Experiment import settings class Experiment8(Experiment): box_size = (128, 128, 128) name = "exp8" length = 240 global_tag = 80 freq = { 'mc_steps': 1000000, 'pt': 100, 'calc': 100, 'snapshot': 100, 'data': 100, 'collect': 0, 'athermal': 0 } def init(self): self.epsilon = 1 self.prepare_chain() settings.BASE_DIR = self.get_base_dir() settings.EXPERIMENTAL_ROOT_DIR = settings.BASE_DIR if settings.CREATE_DIR_STRUCTURE: tools.create_dir(settings.BASE_DIR) settings.MC_STEPS = self.freq['mc_steps'] settings.COLLECT = self.freq['collect'] def prepare_chain(self): length = self.length co_block = 20 one_block = 10 self.chain_seq = Polymer.Chain([ TypeO() if (x % co_block) < one_block else TypeC() for x in range(length) ]) return self.chain_seq def c1_setup(self): self.freq['mc_steps'] = 5000000 #self.temp_list = [0.1, 5.0, 10.0, 20.0, 40.0, 60.0, 80.0, 100.0] name = "c_t_0.1_2.0" self._setup(name, 0.1, 2.0, 3, swap = False) self.set_collect(**self.freq) settings.PERFORM_SWAP = False return (name, self.chain_seq) def c2_setup(self): name = "c_t_2.0_4.0" self._setup(name, 2.0, 4.0, 5, swap = False) self.set_collect(**self.freq) settings.PERFORM_SWAP = False return (name, self.chain_seq) def mpi1_setup(self): """ """ settings.PERFORM_SWAP = True self.temp_list = [1.0, 5.0, 10.0, 20.0, 40.0, 60.0, 80.0, 100.0] name = "mpi_t_1_100" self._setup(name, 1, 100, 2, swap = True) self.set_collect(**self.freq) return (name, self.chain_seq) def mpi4_setup(self): """ """ self.freq['mc_steps'] = 5000000 self.freq['collect'] = 0 self.freq['pt'] = 100 self.freq['data'] = 10000 self.freq['calc'] = 100 self.freq['snapshot'] = 10000 settings.PERFORM_SWAP = True name = "mpi4_t_1_30" self._setup(name, 1, 100, 2, swap = True) self.set_collect(**self.freq) return (name, self.chain_seq) def mpi2_setup(self): settings.COLLECT = 0 settings.PERFORM_SWAP = True name = "mpi2_t_0.5_4" self._setup(name, 0.5, 4, 20, swap = True) self.set_collect(**self.freq) return (name, self.chain_seq) def mpi3_setup(self): """ """ settings.PERFORM_SWAP = True name = "mpi3_t_14_30" self._setup(name, 14, 30, 30, swap = True) self.set_collect(**self.freq) return (name, self.chain_seq) class Experiment8b(Experiment8): box_size = (240, 240, 240) name = "exp8b" freq = { 'mc_steps': 2500000, 'pt': 100, 'calc': 10, 'snapshot': 10, 'data': 10, 'collect': 1000, 'athermal': 100, 'cooling': 100 } def m1_setup(self): self.temp_list = [0.01, 0.1, 1, 10.0] name = "m1" self._setup(name, 0.01, 2.0, 30, swap = True) self.set_collect(**self.freq) settings.PERFORM_SWAP = True return (name, self.chain_seq) def m2_setup(self): name = "m2" self._setup(name, 0.5, 1.0, 150, swap = True) self.set_collect(**self.freq) settings.PERFORM_SWAP = True return (name, self.chain_seq) class Experiment8c(Experiment8b): box_size = (240, 240, 240) name = "exp8c" freq = { 'mc_steps': 50000, 'pt': 100, 'calc': 100, 'snapshot': 100, 'data': 100, 'collect': 2000, 'athermal': 100, 'cooling': 10 } def m4_setup(self): settings.PERFORM_SWAP = True name = "m4" self._setup(name, 0.1, 2.0, 100, swap = True) self.set_collect(**self.freq) settings.PERFORM_SWAP = True return (name, self.chain_seq) def m5_setup(self): settings.PERFORM_SWAP = True name = "m5" self._setup(name, 0.5, 2.0, 150, swap = True) self.set_collect(**self.freq) settings.PERFORM_SWAP = True return (name, self.chain_seq) def m6_setup(self): settings.PERFORM_SWAP = True name = "m6" self._setup(name, 0.70, 0.80, 160, swap = True) self.set_collect(**self.freq) return (name, self.chain_seq) def m8_setup(self): settings.PERFORM_SWAP = True name = "m8" self.temp_list = [0.96, 0.9750, 0.98, 0.99, 0.97] self._setup(name, 0.96, 1.0, 160, swap = True) self.set_collect(**self.freq) return (name, self.chain_seq) def m7_setup(self): name = "m7" #self.temp_list = [3.0, 6.0, 7.0, 10.0] self.temp_list = tools.get_list('3.0;3.72716356307;3.8919300086;4.03248996656;4.45029462142;6.32773712706;7.4997732507;8.22677940102;8.76063872225;9.15603842045;9.49544613272;10.0') self._setup(name, 3.0, 10.0, 210, swap = True) self.set_collect(**self.freq) settings.PERFORM_SWAP = True return (name, self.chain_seq) def m9_setup(self): name = "m9" self._setup(name, 1.8, 3.0, swap = True) self.set_collect(**self.freq) settings.PERFORM_SWAP = True return (name, self.chain_seq) def m10_setup(self): name = "m10" self.temp_list = tools.get_list('0.5;0.682184978051;0.822181459851;0.933994546054;1.45231087169;1.84849481007;2.0892410826;2.18968649677;2.37318753997;2.57764955147;2.78018156317;3.0') self._setup(name, 0.5, 3.0, 220, swap = True) self.set_collect(**self.freq) settings.PERFORM_SWAP = True return (name, self.chain_seq) def m13_setup(self): name = "m13" self.temp_list = tools.get_list('2.0;2.12560282997;2.28684203686;2.54750669268;2.92985687666;3.37317931562;3.63022478269;3.74963892554;3.80798716489;4.16663724091;4.43233034752;4.89163854788;5.23490450547;5.50684521542;5.85620322367;6.0') self._setup(name, 2.0, 6.0, 240, swap = True) self.set_collect(**self.freq) settings.PERFORM_SWAP = True return (name, self.chain_seq) def c16_setup(self): name = "c16" self.temp_list = tools.get_list('2.0;2.12560282997;2.28684203686;2.54750669268;2.92985687666;3.37317931562;3.63022478269;3.74963892554;3.80798716489;4.16663724091;4.43233034752;4.89163854788;5.23490450547;5.50684521542;5.85620322367;6.0;7.0;8.0;10.0;15.0') self._setup(name, 2.0, 6.0, 240, swap = False) self.set_collect(**self.freq) settings.PERFORM_SWAP = False return (name, self.chain_seq) def c17_setup(self): name = "c17" self._setup(name, 3.74963892554, 3.74963892554, 250, swap = False) self.set_collect(**self.freq) settings.PERFORM_SWAP = False return (name, self.chain_seq) def m12_setup(self): name = "m12" self._setup(name, 2.78, 3.1, 230, swap = True) self.set_collect(**self.freq) settings.PERFORM_SWAP = True return (name, self.chain_seq) def pt1_setup(self): name = "pt1" self.freq['mc_steps'] = 10000 self.freq['collect'] = 0 self.freq['athermal'] = 0 self.freq['data'] = 5000000 self.freq['calc'] = 5000000 self.freq['snapshot'] = 5000000 self._setup(name, 0.5, 3.0, 300, swap = True) self.set_collect(**self.freq) settings.PERFORM_SWAP = True settings.FOPT = True return (name, self.chain_seq) def pt2_setup(self): name = "pt2" self.freq['mc_steps'] = 10000 self.freq['collect'] = 0 self.freq['athermal'] = 0 self.freq['data'] = 5000000 self.freq['calc'] = 5000000 self.freq['snapshot'] = 5000000 self._setup(name, 3.0, 10.0, 320, swap = True) self.set_collect(**self.freq) settings.PERFORM_SWAP = True settings.FOPT = True return (name, self.chain_seq) def pt3_setup(self): name = "pt3" self.freq['mc_steps'] = 1000 self.freq['collect'] = 0 self.freq['athermal'] = 0 self.freq['data'] = 5000000 self.freq['calc'] = 5000000 self.freq['snapshot'] = 5000000 self._setup(name, 2.0, 10.0, 330, swap = True) self.set_collect(**self.freq) settings.PERFORM_SWAP = True settings.FOPT = True return (name, self.chain_seq) def c6_setup(self): settings.PERFORM_SWAP = False name = "c6" self._setup(name, 0.70, 0.80, 160, swap = False) settings.PERFORM_SWAP = False self.set_collect(**self.freq) return (name, self.chain_seq) def c7_setup(self): settings.PERFORM_SWAP = False name = "c7" self._setup(name, 0.8, 2.0, 150, swap = False) self.set_collect(**self.freq) settings.PERFORM_SWAP = False return (name, self.chain_seq) def c8_setup(self): settings.PERFORM_SWAP = False name = "c8" self.temp_list = [ 0.6, 1.0, 2.0, 10.0 ] self._setup(name, 0.8, 2.0, 190, swap = False) self.set_collect(**self.freq) settings.PERFORM_SWAP = False return (name, self.chain_seq) def c9_setup(self): name = "c9" self._setup(name, 0.6, 1.1, 200, swap = False) self.set_collect(**self.freq) settings.PERFORM_SWAP = False return (name, self.chain_seq) def c10_setup(self): name = "c10" self._setup(name, 0.45, 0.55, 210, swap = False) self.set_collect(**self.freq) settings.PERFORM_SWAP = False return (name, self.chain_seq) def c11_setup(self): name = "c11" self._setup(name, 3.0, 3.0, 210, swap = False) self.set_collect(**self.freq) settings.PERFORM_SWAP = False return (name, self.chain_seq) def c12_setup(self): name = "c12" self.temp_list = [0.9750, 1.0, 0.850, 0.90 ] self._setup(name, 3.0, 3.0, 210, swap = False) self.set_collect(**self.freq) settings.PERFORM_SWAP = False return (name, self.chain_seq) def c13_setup(self): name = "c13" self._setup(name, 0.8750, 1.0, 210, swap = False) self.set_collect(**self.freq) settings.PERFORM_SWAP = False return (name, self.chain_seq) def c14_setup(self): name = "c14" self._setup(name, 3.0, 6.0, 220, swap = False) self.set_collect(**self.freq) settings.PERFORM_SWAP = False return (name, self.chain_seq) def c15_setup(self): name = "c15" self._setup(name, 0.5, 3.0, 230, swap = False) self.set_collect(**self.freq) settings.PERFORM_SWAP = False return (name, self.chain_seq) def c20_setup(self): name = "c20" self.temp_list = [ 2.266667, 2.90, 3.533333, 4.16, 4.80, 5.43, 6.066667, 6.7, 7.333333, 7.96 ] self._setup(name, 2.27, 7.96, 350, swap = False) self.set_collect(**self.freq) settings.PERFORM_SWAP = False return (name, self.chain_seq) def c21_setup(self): name = "c21" self.temp_list = [ 2.266667, 2.9, 3.2166665, 3.533333, 4.800000, 4.9575, 5.115, 5.2725, 5.43, 5.745, 6.066667, 6.7, 7.333333, 8.600000, 11.13, 12.40 ] self._setup(name, 2.27, 8.96, 360, swap = False) self.set_collect(**self.freq) settings.PERFORM_SWAP = False return (name, self.chain_seq) class Experiment8d(Experiment8c): box_size = (240, 240, 240) name = "exp8d" freq = { 'mc_steps': 10000000, 'pt': 200, 'calc': 100, 'snapshot': 100, 'data': 1000, 'collect': 1000000, 'athermal': 1000000, 'cooling': 0 } class Experiment8e(Experiment8c): box_size = (240, 240, 240) name = "exp8e" length = 120 freq = { 'mc_steps': 2000000, 'pt': 100, 'calc': 100, 'snapshot': 100, 'data': 100, 'collect': 5000, 'athermal': 10000, 'cooling': 0 } class Experiment8g(Experiment8c): """ For epsilon = 0.5 """ box_size = (240, 240, 240) name = "exp8g0_5" length = 240 freq = { 'mc_steps': 40000000, 'pt': 100, 'calc': 100, 'snapshot': 100, 'data': 100, 'collect': 20000000, 'athermal': 5000000, 'cooling': 0 } def prepare_chain(self): length = self.length co_block = 20 one_block = 10 self.chain_seq = Polymer.Chain([ TypeO05() if (x % co_block) < one_block else TypeC05() for x in range(length) ]) return self.chain_seq def c1_setup(self): name = "c1" self._setup(name, 1.0, 20.0, 250, swap = False) self.set_collect(**self.freq) settings.PERFORM_SWAP = False return (name, self.chain_seq) def m1_setup(self): name = "m1" self._setup(name, 1.0, 20.0, 259, swap = True) self.set_collect(**self.freq) settings.PERFORM_SWAP = True return (name, self.chain_seq) def c2_setup(self): name = "c2" self._setup(name, 1.0, 3.0, 291, swap = False) self.set_collect(**self.freq) settings.PERFORM_SWAP = False return (name, self.chain_seq) def c3_setup(self): name = "c3" self._setup(name, 1.0, 7.0, 270, swap = False) self.set_collect(**self.freq) settings.PERFORM_SWAP = False return (name, self.chain_seq) def c4_setup(self): name = "c4" self._setup(name, 5.0, 8.0, 280, swap = False) self.set_collect(**self.freq) settings.PERFORM_SWAP = False return (name, self.chain_seq) def m16_setup(self): name = "m16" self.temp_list = tools.get_list('2.0;2.93869324227;3.07217225203;3.30758457056;3.94316528763;4.29872503277;4.52461320786;5.58411715289;6.17418580166;6.79175962589;7.56188084477;8.53862159296;8.94672367604;9.45417046881;9.85630466154;10.0') self._setup(name, 2.0, 10.0, 240, swap = True) self.set_collect(**self.freq) settings.PERFORM_SWAP = True return (name, self.chain_seq) def c20_setup(self): name = "c20" self.temp_list = [ 2.27, 2.90, 3.53, 4.16, 4.80, 5.43, 6.07, 6.7, 7.33, 7.96 ] self._setup(name, 2.27, 7.96, 350, swap = False) self.set_collect(**self.freq) settings.PERFORM_SWAP = False return (name, self.chain_seq) def c21_setup(self): name = "c21" self.temp_list = [ 2.266667, 3.533333, 4.800000, 6.066667, 7.333333, 8.600000 ] self._setup(name, 2.27, 8.96, 360, swap = False) self.set_collect(**self.freq) settings.PERFORM_SWAP = False return (name, self.chain_seq) class Experiment8f(Experiment8g): box_size = (240, 240, 240) name = "exp8f0_1" length = 240 freq = { 'mc_steps': 40000000, 'pt': 100, 'calc': 100, 'snapshot': 100, 'data': 1000, 'collect': 10000000, 'athermal': 1000000, 'cooling': 0 } def prepare_chain(self): length = self.length co_block = 20 one_block = 10 self.chain_seq = Polymer.Chain([ TypeO() if (x % co_block) < one_block else TypeC() for x in range(length) ]) return self.chain_seq class Experiment801(Experiment8g): box_size = (240, 240, 240) name = "exp8g0_1" length = 240 freq = { 'mc_steps': 40000000, 'pt': 100, 'calc': 100, 'snapshot': 1000, 'data': 1000, 'collect': 10000000, 'athermal': 1000000, 'cooling': 0 } def prepare_chain(self): length = self.length co_block = 20 one_block = 10 self.chain_seq = Polymer.Chain([ TypeO() if (x % co_block) < one_block else TypeC() for x in range(length) ]) return self.chain_seq class Experiment480a(Experiment8g): box_size = (240, 240, 240) name = "exp480a_05" length = 480 freq = { 'mc_steps': 10000000, 'pt': 100, 'calc': 100, 'snapshot': 100, 'data': 1000, 'collect': 1000000, 'athermal': 1000000, 'cooling': 0 } def prepare_chain(self): length = self.length co_block = 20 one_block = 10 self.chain_seq = Polymer.Chain([ TypeO05() if (x % co_block) < one_block else TypeC05() for x in range(length) ]) return self.chain_seq class Experiment802(Experiment8c): """ For epsilon = 0.2 """ box_size = (240, 240, 240) name = "exp8g0_2" length = 240 freq = { 'mc_steps': 40000000, 'pt': 100, 'calc': 100, 'snapshot': 1000, 'data': 100, 'collect': 10000000, 'athermal': 1000000, 'cooling': 0 } def prepare_chain(self): length = self.length co_block = 20 one_block = 10 self.chain_seq = Polymer.Chain([ MLib.TypeO02() if (x % co_block) < one_block else MLib.TypeC02() for x in range(length) ]) return self.chain_seq def c1_setup(self): name = "c1" self._setup(name, 1.0, 20.0, 250, swap = False) self.set_collect(**self.freq) settings.PERFORM_SWAP = False return (name, self.chain_seq) class Experiment803(Experiment8c): """ For epsilon = 0.3 """ box_size = (240, 240, 240) name = "exp8g0_3" length = 240 freq = { 'mc_steps': 40000000, 'pt': 100, 'calc': 100, 'snapshot': 1000, 'data': 100, 'collect': 10000000, 'athermal': 1000000, 'cooling': 0 } def prepare_chain(self): length = self.length co_block = 20 one_block = 10 self.chain_seq = Polymer.Chain([ MLib.TypeO03() if (x % co_block) < one_block else MLib.TypeC03() for x in range(length) ]) return self.chain_seq def c1_setup(self): name = "c1" self._setup(name, 1.0, 20.0, 250, swap = False) self.set_collect(**self.freq) settings.PERFORM_SWAP = False return (name, self.chain_seq) class Experiment804(Experiment8c): """ For epsilon = 0.4 """ box_size = (240, 240, 240) name = "exp8g0_4" length = 240 freq = { 'mc_steps': 40000000, 'pt': 100, 'calc': 100, 'snapshot': 1000, 'data': 100, 'collect': 20000000, 'athermal': 1000000, 'cooling': 0 } def prepare_chain(self): length = self.length co_block = 20 one_block = 10 self.chain_seq = Polymer.Chain([ MLib.TypeO04() if (x % co_block) < one_block else MLib.TypeC04() for x in range(length) ]) return self.chain_seq def c1_setup(self): name = "c1" self.temp_list = [ 2.27, 3.53, 4.80, 6.07, 7.33, 8.60, 9.87, 11.13, 12.40, 13.67, 14.93, 16.20, 17.47, 18.73, 20.0, 21.0] self._setup(name, 2.27, 21.0, 250, swap = False) self.set_collect(**self.freq) settings.PERFORM_SWAP = False return (name, self.chain_seq) class Experiment805(Experiment8c): """ For epsilon = 0.5 """ box_size = (240, 240, 240) name = "exp8g0_5" length = 240 freq = { 'mc_steps': 40000000, 'pt': 100, 'calc': 100, 'snapshot': 1000, 'data': 100, 'collect': 20000000, 'athermal': 1000000, 'cooling': 0 } def prepare_chain(self): length = self.length co_block = 20 one_block = 10 self.chain_seq = Polymer.Chain([ MLib.TypeO02() if (x % co_block) < one_block else MLib.TypeC02() for x in range(length) ]) return self.chain_seq def c1_setup(self): name = "c1" self._setup(name, 1.0, 20.0, 250, swap = False) self.set_collect(**self.freq) settings.PERFORM_SWAP = False return (name, self.chain_seq) class Experiment806(Experiment8c): """ For epsilon = 0.6 """ box_size = (240, 240, 240) name = "exp8g0_6" length = 240 freq = { 'mc_steps': 40000000, 'pt': 100, 'calc': 100, 'snapshot': 100, 'data': 100, 'collect': 10000000, 'athermal': 1000000, 'cooling': 0 } def prepare_chain(self): length = self.length co_block = 20 one_block = 10 self.chain_seq = Polymer.Chain([ MLib.TypeO06() if (x % co_block) < one_block else MLib.TypeC06() for x in range(length) ]) return self.chain_seq def c1_setup(self): name = "c1" self._setup(name, 1.0, 20.0, 250, swap = False) self.set_collect(**self.freq) settings.PERFORM_SWAP = False return (name, self.chain_seq) class Experiment807(Experiment8c): """ For epsilon = 0.7 """ box_size = (240, 240, 240) name = "exp8g0_7" length = 240 freq = { 'mc_steps': 40000000, 'pt': 100, 'calc': 100, 'snapshot': 100, 'data': 100, 'collect': 10000000, 'athermal': 1000000, 'cooling': 0 } def prepare_chain(self): length = self.length co_block = 20 one_block = 10 self.chain_seq = Polymer.Chain([ MLib.TypeO07() if (x % co_block) < one_block else MLib.TypeC07() for x in range(length) ]) return self.chain_seq def c1_setup(self): name = "c1" self._setup(name, 1.0, 20.0, 250, swap = False) self.set_collect(**self.freq) settings.PERFORM_SWAP = False return (name, self.chain_seq) class Experiment808(Experiment8c): """ For epsilon = 0.8 """ box_size = (240, 240, 240) name = "exp8g0_8" length = 240 freq = { 'mc_steps': 40000000, 'pt': 100, 'calc': 100, 'snapshot': 100, 'data': 100, 'collect': 10000000, 'athermal': 1000000, 'cooling': 0 } def prepare_chain(self): length = self.length co_block = 20 one_block = 10 self.chain_seq = Polymer.Chain([ MLib.TypeO08() if (x % co_block) < one_block else MLib.TypeC08() for x in range(length) ]) return self.chain_seq def c1_setup(self): name = "c1" self._setup(name, 1.0, 20.0, 250, swap = False) self.set_collect(**self.freq) settings.PERFORM_SWAP = False return (name, self.chain_seq) class Experiment809(Experiment8c): """ For epsilon = 0.9 """ box_size = (240, 240, 240) name = "exp8g0_9" length = 240 freq = { 'mc_steps': 40000000, 'pt': 100, 'calc': 100, 'snapshot': 100, 'data': 100, 'collect': 20000000, 'athermal': 1000000, 'cooling': 0 } def prepare_chain(self): length = self.length co_block = 20 one_block = 10 self.chain_seq = Polymer.Chain([ MLib.TypeO09() if (x % co_block) < one_block else MLib.TypeC09() for x in range(length) ]) return self.chain_seq def c1_setup(self): name = "c1" self._setup(name, 1.0, 20.0, 250, swap = False) self.set_collect(**self.freq) settings.PERFORM_SWAP = False return (name, self.chain_seq) class Experiment810(Experiment8c): """ For epsilon = 1.0 """ box_size = (240, 240, 240) name = "exp8g0_10" length = 240 freq = { 'mc_steps': 40000000, 'pt': 100, 'calc': 100, 'snapshot': 100, 'data': 100, 'collect': 20000000, 'athermal': 1000000, 'cooling': 0 } def prepare_chain(self): length = self.length co_block = 20 one_block = 10 self.chain_seq = Polymer.Chain([ MLib.TypeO10() if (x % co_block) < one_block else MLib.TypeC10() for x in range(length) ]) return self.chain_seq def c1_setup(self): name = "c1" self._setup(name, 1.0, 20.0, 250, swap = False) self.set_collect(**self.freq) settings.PERFORM_SWAP = False return (name, self.chain_seq) <file_sep>#!/bin/bash DIR="$1" OUT="$2" for f in $DIR/*.jmol; do jmol -n -w "JPG:$2/$f.jpg" $f done <file_sep>#!/bin/bash FILE=$1 COL=$2 TEMPLATE=" set term x11; set datafile separator \";\"; plot '$FILE' using 1:$COL with lp " echo $TEMPLATE | gnuplot --persist <file_sep># <NAME> <<EMAIL>> # Define experiments from lib import Polymer, tools from lib.mpi import PT from lib.Monomer import TypeC, TypeO from lib.Experiment import Experiment import logging import settings class Experiment4(Experiment): """ DOI 10.1002/pssb.200880252 """ box_size = (64, 64, 64) name = "exp4" length = 64 epsilon = 1 chain_seq = None global_tag = 4 freq = { 'pt': 200, 'calc': 100, 'snapshot': 1000, 'data': 1000000, 'collect': 0, 'mc_steps': 1000000 } def init(self): self.epsilon = 1 self.prepare_chain() settings.BASE_DIR = self.get_base_dir() settings.EXPERIMENTAL_ROOT_DIR = settings.BASE_DIR if settings.CREATE_DIR_STRUCTURE: tools.create_dir(settings.BASE_DIR) settings.MC_STEPS = 10000000 settings.COLLECT = 0 def prepare_chain(self): length = self.length co_block = length / 2 one_block = length / 4 from lib.Monomer import TypeA, TypeB self.chain_seq = Polymer.Chain([ TypeA() if (x % co_block) < one_block else TypeB() for x in range(length)]) return self.chain_seq def athermal_setup(self): """ Athermal experiment 1 """ self.freq['calc'] = 10000 self.freq['data'] = 1000000 self.freq['snapshot'] = 1000 self.set_collect(**self.freq) PT.min_temp = settings.MIN_T = -1.0 PT.max_temp = settings.MAX_T = -1.0 self.pt = PT() name = "ath" self.current_exp_name = name self.create_dir_structure("%s_%d_%d_%d" % ((name,) + self.box_size), settings.EXPERIMENT_COPY) ## Configure temperature settings.LOCAL_T = -1.0 logging.info("Local T: %f" % settings.LOCAL_T) self.update_settings_files() return (self.current_exp_name, self.chain_seq) def const_setup(self): """ Experiment using parallel tempering, with linear temperature function """ name = "const_t_1_14" self._setup(name, 1, 14, 2) self.set_collect( **{'mc_steps': 1000000, 'collect': 0, 'calc': 1, 'data': 1000000, 'snapshot': 10000, 'pt': False}) return (name, self.chain_seq) def mpit_setup(self): """ """ settings.PERFORM_SWAP = True name = "mpi_t_1_14" self._setup(name, 1, 14, 2, swap = True) self.set_collect(**self.freq) return (name, self.chain_seq) def mpit2_setup(self): settings.COLLECT = 0 settings.PERFORM_SWAP = True name = "mpi2_t_1_14" self._setup(name, 1, 14, 20, swap = True) self.set_collect(**self.freq) return (name, self.chain_seq) class Experiment5(Experiment4): """ """ box_size = (64, 64, 64) name = "exp5" length = 64 global_tag = 5 freq = { 'mc_steps': 1000000, 'pt': 200, 'calc': 100, 'snapshot': 1000, 'data': 1000000, 'collect': 0 } def athermal_setup(self): return super(Experiment5, self).athermal_setup() def const_setup(self): """ Experiment using parallel tempering, with linear temperature function """ settings.COLLECT = 0 settings.PERFORM_SWAP = False name = "const_t_1_14" self._setup(name, 1, 14, 2) self.set_collect(**self.freq) return (name, self.chain_seq) def mpi_setup(self): settings.COLLECT = 0 settings.PERFORM_SWAP = True name = "mpi_t_0.1_1.8" self._setup(name, 0.1, 1.8, 88, True) self.set_collect(**self.freq) return (name, self.chain_seq) def mpi2_setup(self): settings.COLLECT = 0 settings.PERFORM_SWAP = True name = "mpi_t_2_4.5" self._setup(name, 2.0, 4.5, 99, True) self.set_collect(**self.freq) return (name, self.chain_seq) class Experiment6(Experiment5): box_size = (16, 16, 16) name = "exp6" length = 64 global_tag = 7 freq = { 'mc_steps': 1000000, 'pt': 200, 'calc': 10, 'snapshot': 1000, 'data': 1000000, 'collect': 0 } class Experiment7(Experiment5): box_size = (32, 32, 32) name = "exp7" length = 64 global_tag = 71 freq = { 'mc_steps': 1000000, 'pt': 200, 'calc': 1, 'snapshot': 1, 'data': 1, 'collect': 0, 'athermal': 0 } class Experiment8(Experiment5): box_size = (128, 128, 128) name = "exp8" length = 240 global_tag = 80 freq = { 'mc_steps': 5000000, 'pt': 100, 'calc': 100, 'snapshot': 1000, 'data': 1000000, 'collect': 0 } def prepare_chain(self): length = self.length co_block = 20 one_block = 10 self.chain_seq = Polymer.Chain([ TypeO() if (x % co_block) < one_block else TypeC() for x in range(length) ]) return self.chain_seq def mpi1_setup(self): """ """ settings.PERFORM_SWAP = True self.temp_list = [1.0, 5.0, 10.0, 20.0, 40.0, 60.0, 80.0, 100.0] name = "mpi_t_1_100" self._setup(name, 1, 100, 2, swap = True) self.set_collect(**self.freq) return (name, self.chain_seq) def mpi4_setup(self): """ """ self.freq['mc_steps'] = 5000000 self.freq['collect'] = 0 self.freq['pt'] = 100 self.freq['data'] = 1000000 self.freq['calc'] = 100 self.freq['snapshot'] = 10000 settings.PERFORM_SWAP = True name = "mpi4_t_1_30" self._setup(name, 1, 100, 2, swap = True) self.set_collect(**self.freq) return (name, self.chain_seq) def mpi2_setup(self): settings.COLLECT = 0 settings.PERFORM_SWAP = True name = "mpi2_t_0.5_4" self._setup(name, 0.5, 4, 20, swap = True) self.set_collect(**self.freq) return (name, self.chain_seq) def mpi3_setup(self): """ """ settings.PERFORM_SWAP = True name = "mpi3_t_14_30" self._setup(name, 14, 30, 30, swap = True) self.set_collect(**self.freq) return (name, self.chain_seq) class Experiment9(Experiment7): name = "exp9_valid" box_size = (32, 32, 32) length = 64 global_tag = 112 freq = { 'mc_steps': 2500000, 'collect': 500000, 'snapshot': 1000, 'calc': 100, 'data': 1000000, 'pt': 100 } def prepare_chain(self): length = self.length co_block = 16 one_block = 8 from lib.Monomer import TypeA, TypeB self.chain_seq = Polymer.Chain([ TypeA() if (x % co_block) < one_block else TypeB() for x in range(length)]) return self.chain_seq class Experiment10(Experiment9): name = "exp10" box_size = (32, 32, 32) length = 64 global_tag = 113 freq = { 'mc_steps': 500000, 'collect': 0, 'snapshot': 1000, 'calc': 100, 'data': 1000000, 'pt': 100 } def prepare_chain(self): length = self.length co_block = 16 one_block = 8 from lib.MonomerExp9 import TypeA, TypeB self.chain_seq = Polymer.Chain([ TypeA() if (x % co_block) < one_block else TypeB() for x in range(length)]) return self.chain_seq class HPExperiment(Experiment): name = "hp64" protein_sequence = "HHHHHHHHHHHHPHPHPPHHPPHHPPHPPHHPPHHPPHPPHHPPHHPPHPHPHHHHHHHHHHHH" box_size = (32,32,32) length = 64 global_tag = 15 freq = { 'mc_steps': 1000000, 'collect': 0, 'snapshot': 1000, 'calc': 10, 'data': 1000000, 'pt': 100 } def prepare_chain(self): m = __import__('lib') monomer_sequence = [] for s in self.protein_sequence: m_obj = getattr(m, 'Type%s' % s) monomer_sequence.append(m_obj()) self.chain_seq = Polymer.Chain(monomer_sequence, name="hp64") print self.name, "Protein sequence", self.protein_sequence return self.chain_seq def init(self): self.epsilon = 1 self.prepare_chain() settings.BASE_DIR = self.get_base_dir() settings.EXPERIMENTAL_ROOT_DIR = settings.BASE_DIR if settings.CREATE_DIR_STRUCTURE: tools.create_dir(settings.BASE_DIR) def athermal_setup(self): name = "ath" self._setup(name, -1.0, -1.0, 10) self.set_collect(**self.freq) return (name, self.chain_seq) def mpi1_setup(self): name = "mpi1" self._setup(name, 1, 30, 10, swap = True) self.set_collect(**self.freq) settings.PERFORM_SWAP = True return (name, self.chain_seq) def mpi2_setup(self): name = "mpi1_30_100" self._setup(name, 30, 100, 11, swap = True) self.freq['mc_steps'] = 5000000 self.freq['calc'] = 100 self.freq['data'] = 1000000 self.freq['snapshot'] = 5000 self.freq['pt'] = 1000 self.set_collect(**self.freq) settings.PERFORM_SWAP = True return (name, self.chain_seq) def mpi3_setup(self): name = "mpi1_15_45" self._setup(name, 15.0, 45.0, 11, swap = True) self.freq['mc_steps'] = 5000000 self.freq['calc'] = 100 self.freq['data'] = 1000000 self.freq['snapshot'] = 5000 self.freq['pt'] = 1000 self.set_collect(**self.freq) settings.PERFORM_SWAP = True return (name, self.chain_seq) def mpi1130_setup(self): name = "mpi1_11_30" self._setup(name, 11.0, 30.0, 15, swap = True) self.freq['mc_steps'] = 2500000 self.freq['calc'] = 100 self.freq['data'] = 1000000 self.freq['snapshot'] = 1000 self.freq['pt'] = 500 self.set_collect(**self.freq) settings.PERFORM_SWAP = True return (name, self.chain_seq) class ProteinExperiment1(Experiment): name = "3MTS" protein_sequence = 'GEVEYLCDYKKIREQEYYLVKWRGYPDSESTWEPRQNLKCVRILKQFHKDLERELLRRHHRSKT' box_size = (32,32,32) length = 64 global_tag = 10 chain_seq = None def prepare_chain(self): import bio sequence = bio.seq1_3(self.protein_sequence) monomer_sequence = [] m = __import__('lib') for s in sequence: m_obj = getattr(m, 'Type%s' % s) monomer_sequence.append(m_obj()) self.chain_seq = Polymer.Chain(monomer_sequence) print self.name,"Protein sequence", self.protein_sequence return self.chain_seq def init(self): self.epsilon = 1 self.prepare_chain() settings.BASE_DIR = self.get_base_dir() settings.EXPERIMENTAL_ROOT_DIR = settings.BASE_DIR if settings.CREATE_DIR_STRUCTURE: tools.create_dir(settings.BASE_DIR) settings.MC_STEPS = 10000000 settings.COLLECT = 0 def const_setup(self): settings.COLLECT = settings.MC_STEPS / 2 settings.PERFORM_SWAP = False name = "const_t_1_14" self._setup(name, 1, 14, 2) self.set_collect(settings.MC_STEPS, settings.COLLECT, 100, 1000, 100, False) return (name, self.chain_seq) def athermal_setup(self): """ Athermal """ settings.MC_STEPS = 1000000 settings.FREQ_CALC = settings.FREQ_SNAPSHOT = settings.FREQ_DATA = 10000 name = "ath" self._setup(name, -1, -1, 11) return (name, self.chain_seq) <file_sep>## Techniki symulacyjne ## <NAME> <<EMAIL>> ## ## 19.10.2011 ## import math from matplotlib import pyplot as plt import numpy as np dt = (2*math.pi) / 2000 omega_dt = dt omega_dt_sq = omega_dt**2 x0 = 1.0 v0 = 0.001 x1 = x0 - v0*dt K = 5000 sim_vec = [x0, x1] for k in range(1, K ): value = float(2 - omega_dt_sq) * sim_vec[k] - sim_vec[k-1] sim_vec.append(value) plt.plot(np.sin(np.arange(0, K+1)*(2*math.pi/2000)+0.5*math.pi)) plt.plot(sim_vec) plt.legend(["Analytic", "MD"]) plt.title("MD vs analytic solution for model of harmonic oscilator") plt.show() <file_sep>import re import sys import argparse as arg from lib.Lattice import Lattice import numpy as np from __init__ import DummyMonomer parser = arg.ArgumentParser(description="Calculate clusters") parser.add_argument('-f', help="JMOL file", dest='file') parser.add_argument('-tar', help='TAR file', dest='tar', action='store_true') parser.add_argument('-scale', help='Rescale coordinates', default = -1, type=float) parser.add_argument('-fs', help='For TAR/KC, from step', default=0, type=int) parser.add_argument('-es', help='For TAR/KC, to step', default=0, type=int) parser.add_argument('-fss', help='For TAR, step increment', default=100, type=int) parser.add_argument('-output_file', type=str) parser.add_argument('-box', help='Box size', required=True) parser.add_argument('-jmol', help='Generate JMOL file', action='store_true') parser.add_argument('-nr', help='Return number of clusters', action='store_true') parser.add_argument('-step', help='Return step;number of clusters', action='store_true') parser.add_argument('-re' ) parser.add_argument('-interface', help='Calculate interface', action='store_true') parser.add_argument('-kch', help='Calculate from KyotoCabinet database', default="") parser.add_argument('-d', help='JMOL dir', default='') parser.add_argument('-jmol_list', help='JMOL list file') parser.add_argument('-avg', action='store_true') parser = parser.parse_args() file = parser.file scale = parser.scale if parser.scale > -1 else 1 box_size = map(int, parser.box.split(",")) Lattice.box_size = box_size avg_dict = {} total_count = 0 def process(file, step=None, output_file=None): if isinstance(file, str): f = open(file) else: f = file try: line = f.readlines() nr = int(line[0].replace("\n", "")) except: print line sys.exit(1) data = np.loadtxt(file, dtype=str, skiprows=1) #data = f.readlines()[1:] point_monomer = {} monomer_list = [] position_set = set() if parser.scale == -1 and "." in data[0]: print "Atom position are float, please set -scale parameter to rescale them!" sys.exit(1) for line in data: #tmp = line.replace("\n","").split(" ") type = line[0] ll = map(float, line[1:]) x = int(ll[0] * scale) y = int(ll[1] * scale) z = int(ll[2] * scale) position = (x, y, z) m = DummyMonomer(position, type, Lattice.get_neighbours(tuple(position))) point_monomer[position] = m monomer_list.append(m) position_set.add(position) return point_monomer, monomer_list, position_set def create_valid_lists(list): point_monomer = {} monomer_list = [] position_set = set() for line in list: type = line[0] ll = np.array(line[1:])*scale position = tuple(ll) m = DummyMonomer(position, type, Lattice.get_neighbours(tuple(position))) point_monomer[position] = m monomer_list.append(m) position_set.add(position) return point_monomer, monomer_list, position_set def process_data(point_monomer, monomer_list, position_set, output_file=None, step=None): surface_bulk = {} clusters_list = {} interface_monomers = set() interface_monomers_count = 0 ## build of neighbour list for m in monomer_list: m.nb_list = m.neighbours_list.intersection(position_set) m.nb_types = [ point_monomer[x].type for x in m.nb_list ] m.nb_count = len(m.nb_list) clusters_list[m.type] = [] ## count how many neighbours is in given type if m.nb_types.count(m.type) != len(m.nb_types): m.on_interface = True if m not in interface_monomers: interface_monomers_count += 1 interface_monomers.add(m) ## assign monomers to cluster for m in monomer_list: c_list = clusters_list[m.type] found_cluster = False for cluster in c_list: if cluster.intersection(m.nb_list): cluster.add(m.position) found_cluster = True if found_cluster == False: c_list.append(set([m.position])) #for c in clusters_list.values(): # print len(c) # print sum([ len(x) for x in c ]) ## join clusters together taken = None def dfs(node, index): taken[index] = True ret = node for i, item in enumerate(l): if not taken[i] and not ret.isdisjoint(item): ret.update(dfs(item, i)) return ret def merge_all(k): ret = [] for i, node in enumerate(k): if not taken[i]: ret.append(list(dfs(node,i ))) return ret for t in clusters_list: l = clusters_list[t] taken = [False]*len(l) clusters_list[t] = merge_all(l) if parser.jmol: for t, c in clusters_list.iteritems(): for x in c: print len(x) print for s in x: print t,s[0]/2.0,s[1]/2.0,s[2]/2.0 elif parser.nr: cluster_count = 0 for t, c in clusters_list.iteritems(): cluster_count += len(c) if output_file: output_file.write("%d\n" % cluster_count) print cluster_count elif parser.step: cluster_count = 0 for t, c in clusters_list.iteritems(): cluster_count += len(c) if parser.avg: if cluster_count in avg_dict: avg_dict[cluster_count] += 1 else: avg_dict[cluster_count] = 0 total_count += 1 if step: if output_file: output_file.write("%d;%d;%d\n" % (step, cluster_count, interface_monomers_count)) else: print "%d;%d;%d" % (step, cluster_count, interface_monomers_count) else: if output_file: output_file.write("%s;%d\n" % (re.match(r'.*jmol_(\d+)\.jmol', file).groups()[0], cluster_count)) else: print "%s;%d" % (re.match(r'.*jmol_(\d+)\.jmol', file).groups()[0], cluster_count) elif parser.interface: inner_contacts = 0 outer_contacts = 0 cluster_count = 0 for t,c in clusters_list.iteritems(): cluster_count += len(c) print "%d;%d" % (cluster_count, interface_monomers_count) if parser.tar: pattern = re.compile(r".*_(\d+).*$") import tarfile tarFile = tarfile.open(file) members = tarFile.getmembers() output_file = open(parser.output_file, "w+") if parser.fs > 0: step = parser.fs mm = 0 for m in members: mt = int(re.match(pattern, m.path).groups()[0]) if mt > step: f = tarFile.extractfile(m) point_monomer, monomer_list, position_set = process(f) process_data(point_monomer, monomer_list, position_set, step=mt, output_file = output_file) mm += 1 elif parser.file: point_monomer, monomer_list, position_set = process(parser.file) process_data(point_monomer, monomer_list, position_set) elif parser.kch != "": import kyotocabinet as kb db = kb.DB() if not db.open(parser.kch, db.OREADER|db.ONOLOCK): print "ERROR" sys.exit(1) else: print "Open", parser.kch output_file = open(parser.output_file, "w+") jmols = [ (x, "jmol_%d" % x) for x in range(parser.fs, parser.es, parser.fss) ] for step, jmol in jmols: data = eval(db[jmol]) if data: point_monomer, monomer_list, position_set = create_valid_lists(data) process_data(point_monomer, monomer_list, position_set, output_file = output_file, step = step) output_file.flush() #print "Process file", jmol output_file.close() elif parser.d != "": import os files = os.listdir(parser.d) file_list = [] idx = 0 output_file = open(parser.output_file, "w+") jmols = [ (x, "%s/jmol_%d.jmol" % (parser.d, x)) for x in range(parser.fs, parser.es, parser.fss) ] idx = len(jmols) print "%d files" % idx for step, jmol in jmols: try: point_monomer, monomer_list, position_set = process(jmol) process_data(point_monomer, monomer_list, position_set, output_file = output_file, step = step) output_file.flush() except: continue elif parser.jmol_list != "" and parser.kch != "": jmols = [ x.replace("\n", "") for x in open(parser.jmol_list, "r").readlines() ] jmols = [ (int(x.split("_")[1]), x) for x in jmols ] for step, jmol in jmols: try: data = eval(db[jmol]) if data: point_monomer, monomer_list, position_set = create_valid_lists(data) process_data(point_monomer, monomer_list, position_set, output_file = output_file, step = step) output_file.flush() except: pass else: point_monomer, monomer_list, position_set = create_valid_lists(file) process_data(point_monomer, monomer_list, position_set) <file_sep>import sys import itertools def bcc(n): product = itertools.product(range(n), range(n), range(n)) return [ c for c in product if (c[0] + c[1] + c[2]) % 2 != 0 ] def fcc(n): product = itertools.product(range(n), range(n), range(n)) return [ c for c in product if (c[0] + c[1] + c[2]) % 2 == 0 ] def sc(n): product = itertools.product(range(n), range(n), range(n)) return list(product) type = sys.argv[1] n = int(sys.argv[2]) file = open(sys.argv[3], "w+") scale = float(sys.argv[4]) if len(sys.argv) > 4 else 1 select = {"sc": sc, "bcc": bcc, "fcc": fcc } data = select[type](n) file.writelines("%d\n\n" % len(data)) file.writelines([ "C %s\n" % (" ".join(map(str, map(lambda x: x*scale, d)))) for d in data ]) file.close() <file_sep>import os import sys from matplotlib import pyplot as plt from matplotlib import rc import numpy as np rc('text', usetex=True) rc('font', family='serif') print "Plot (x,y) some column" print "file.csv column" import argparse as arg parser = arg.ArgumentParser(description="Plot column") parser.add_argument('file', help='File') parser.add_argument('-f', help='File', dest='file') parser.add_argument('-n', help='Column', dest='column', type=int) parser.add_argument('-multi', help='Multi variable', action='store_true') parser.add_argument('-d', help='Delimeter', type=str, default=';') parser.add_argument('-xticks', help='Use first column as xticks', action='store_true') parser.add_argument('-yticks', help='Use first column as yticks', action='store_true') parser.add_argument('-title', help='Title', default='') parser.add_argument('-xlabel', default='') parser.add_argument('-ylabel', default='') parser.add_argument('-legend', default='') parser.add_argument('-s', default='-x', type=str) parser.add_argument('-yscale', default=1.0, type=float) parser.add_argument('-png', default='', type=str) parser = parser.parse_args() file = parser.file column = parser.column multi = parser.multi delimiter = parser.d if "," in file: files = file.split(",") else: files = [file] data = [] for f in files: data.append(np.loadtxt(f, delimiter=delimiter)) #lines.sort(0) def process_lines(lines): print "Multi" out = {} for k,l in lines: if k in out: out[k].append(l) else: out[k] = [l] x_val = [] y_val = [] x_val = out.keys() x_val.sort() for k in x_val: y_val.append(np.average(out[k])) return (x_val, y_val) #max_idx = y_val.index(max(y_val)) #del y_val[max_idx] #del x_val[max_idx] #max_idx = y_val.index(max(y_val)) #del y_val[max_idx] #del x_val[max_idx] plot_list = [] for d in data: lines = d[:,[0, column]] x_val, y_val = process_lines(lines) if parser.yscale != 1.0: y_val = map(lambda x: x / parser.yscale, y_val) if parser.xticks: plt.xticks(x_val, ["%.2f" % x for x in x_val ]) if parser.yticks: plt.yticks(y_val, ["%.2f" % y for y in y_val ]) plot_list.append(plt.plot(x_val, y_val, parser.s)) plt.title(parser.title) plt.xlabel(parser.xlabel) plt.ylabel(parser.ylabel) if parser.legend and ";" in parser.legend: l = parser.legend.split(';') plt.legend(plot_list, l) if parser.png: plt.savefig(parser.png) else: plt.show() #open(file+"_out", "w+").writelines(map(lambda x: "%s\n" % str(x), lines)) <file_sep>#!/bin/bash EXP_NAME=$1 if [ "X$EXP_NAME" != "X" ]; then rm *$EXP_NAME fi find code -name *.pyc -delete <file_sep>import hotshot.stats import sys file_name = sys.argv[1] stats = hotshot.stats.load(file_name) stats.dump_stats(file_name+"_stats") <file_sep>""" Average every rwo """ import sys import numpy as np print "file_in col" file_in = sys.argv[1] col = int(sys.argv[2]) f_data = [ map(float, x.split(";")) for x in open(file_in, "r+").readlines() ] avg_data = [ [x[0], np.average(x[col:])] for x in f_data ] out = open(file_in + "_avg", "w+") <file_sep>from Box import * from Lattice import * from Monomer import * from Polymer import * <file_sep>#!/bin/bash #echo OK | mail -s "JOB: $1 FINISHED" <EMAIL> $HOME/bin/xsend.py <EMAIL> "JOB: $1 FINISHED" <file_sep>''' @author: <NAME> <<EMAIL>> ''' import os import cPickle, gzip import logging import bisect import numpy as np def interaction_table_to_dict(file_name): """ Return amino acids interaction table """ return_dict = {} lines = [ l.strip("\n").strip().split(" ") for l in open(file_name, "r").readlines() ] aa_list = lines[0] for line in lines[1:]: return_dict[line[0]] = dict(zip(aa_list, map(float, line[1:len(line)-1]))) return return_dict def build_monomers(file_name): """ Build monomers, based on interaction table """ class_template = """ class %s(Monomer): name = "%s" interaction_table = %s \n\n """ interaction_dict = interaction_table_to_dict(file_name) if os.path.exists(file_name): answer = raw_input('File extists, overwrite [Y/N] ? ') if answer == 'N': return False class_file = open('Monomer.py', 'w+') for key in interaction_dict.keys(): cls_name = "Type%s" % key table = interaction_dict[key] string = class_template % (cls_name, key, str(table)) class_file.writelines(string) class_file.close() def create_dir(file_name): try: os.makedirs(os.path.dirname(file_name)) return True except OSError, e: dir_path = os.path.dirname(file_name) if dir_path and not os.path.exists(os.path.dirname(file_name)): raise e elif not os.path.exists(file_name): raise e def load_file(file_name, default=None): try: v = cPickle.load(gzip.open(os.path.realpath(file_name), "rb")) print "Open:",os.path.realpath(file_name), "Type:", type(v) return v except Exception, e: logging.debug(e) return default def save_file(file_name, obj): return cPickle.dump(obj=obj, file=gzip.open(file_name, "wb", compresslevel=3), protocol=2) #return cPickle.dump(obj = obj, file = open(file_name, "wb"), protocol = 2) def clean_dir(dir_name): for the_file in os.listdir(dir_name): file_path = os.path.join(dir_name, the_file) try: if os.path.isfile(file_path): os.unlink(file_path) except Exception, e: print e def array_diff(array_a, array_b): """ Return value difference for two arrays """ return map(lambda x,y: x - y, array_a, array_b) def dot(vector_a, vector_b = None): """ Dot products of two vectors """ if vector_b == None: vector_b = (0,0,0) distance = array_diff(vector_a, vector_b) return sum(map(lambda x: x**2, distance)) def index(list_object, item): """ Locate the leftmost value exactly equal to x """ i = bisect.bisect_left(list_object, item) if i != len(list_object) and list_object[i] == item: return i raise ValueError def generate_one_xyz_file(path): files = os.listdir(path) jmol_files = filter(lambda x: "_" in x, files) jmol_files.sort(key = lambda x: int(x.split("_")[2].split(".")[0])) def chunk(l, n): return (l[i:i+n] for i in xrange(0, len(l), n)) def get_column(data, column): return [ float(x.split(';')[column]) for x in data ] def f_avg(column): return np.average(column) def f_avg2(column): return np.average(map(lambda x: x**2, column)) def f_cv(e, e2, temp): ret = [] for idx in range(len(temp)): val = (1/(temp[idx]**2)) * (e2[idx] - (e[idx]**2)) ret.append(val) return ret def f_cv2(data_e, N): ret = [] for temp, e in data_e.iteritems(): avg_e = np.average(data_e[temp]) avg_e2 = avg_e*avg_e tmp = (np.average([ np.math.pow((data_e[temp][x]), 2) for x in range(len(data_e[temp])) ]) - avg_e2) / (N*(temp**2)) ret.append( (temp, tmp)) print ret ret.sort(key = lambda x: x[0] ) print ret r = [ x[1] for x in ret ] return r def avg_dict(input): """ Return for given temp, list of steps (if more than one, do average) """ ret = {} for temp in input.keys(): step_list = input[temp] step_keys = step_list.keys() step_keys.sort() for step in step_keys: t = input[temp][step] if temp in ret: ret[temp].append(np.average(t)) else: ret[temp] = [np.average(t)] return ret def save_dict_to_csv(input_dict, csv_name): """ Save internal dicts to csv files """ f = open(csv_name, "w+") lines = [] steps = input_dict.keys() steps.sort() for step in steps: lines.append("%d;%s\n" % (step, ";".join(map(str, input_dict[step])))) f.writelines(lines) def get_list(csv, delimiter=';', data_type=float): l = map(data_type, csv.split(delimiter)) return l <file_sep># Calculate structure factor # Based on average over time configurations import os import sys import numpy as np from matplotlib import pyplot as plt import itertools import cPickle print "xyz_dir, output, box_size, segment" xyz_dir = sys.argv[1] output = sys.argv[2] box_size = float(sys.argv[3]) segment = sys.argv[4] files = [ "%s/%s" % (xyz_dir, o) for o in os.listdir(xyz_dir) ] k_min = 2*np.pi/box_size #k_max = 2*np.pi/np.math.sqrt(2) k_max = 3.0 ## read files data_files = [] for f in files: d = open(f).readlines()[2:] data_files.append([ np.array(map(float, x.split(" ")[1:4])) for x in d if x.startswith(segment) ]) ## na = 32.0 k_range = np.arange(k_min, k_max, 0.5) print "len k", len(k_range) k_vec = [ np.array(x) for x in itertools.product(k_range, k_range, k_range) ] print "len k_vec", len(k_vec) ## Sk = [] for data_idx in range(len(data_files[0:1000])): sk = [] data = data_files[data_idx] print "Process",files[data_idx] for k in k_vec: v1 = 0.0 v2 = 0.0 for rm in data: v1 += np.cos(k.dot(rm)) v2 += np.sin(k.dot(rm)) val = (v1**2) + (v2**2) sk.append(val) Sk.append(sk) Sk = np.average(Sk, 0) cPickle.dump(obj=Sk, file=open('sk_out', 'wb'), protocol=2) <file_sep># # Author: <NAME> <<EMAIL>> # Define experiments # from lib import Polymer, tools from lib.Experiment import Experiment import lib.monomers.MonomerExpHP as MonomerExpHP import lib.monomers.MonomerExpHP36 as MonomerExpHP36 import bio import settings # Sequence from Table II # Phys. Rev. E 84 031934 (2011) DOI: 10.1103/PhysRevE.84.031934 SEQUENCE_DB = { "3d1": "PPHHHHHPPPHHPPPPPHHPPPHPPPPPPHPHPPPHPPHPPHPPPPPHPPPPHHPHHPPHPPHP", "3d2": "PPHPHPPHPPHHHPHHHHPPHHHPPPPHPHPPPHPHPPPHPHPPPPPHPHPPHPHPPPHPPHPP", "3d3": "HPHHPPHHPHPPPPPHHHPHHHHPPHPPHPHHPPPHPHPPHHHPHHPHPPPPPHHHHHHHHPPP", "3d4": "HPPHHPPHPPHPHPPHPPPPHPPPPPPHPHPHHHPPHPHPPPHPHPPHHPPHPPHPPHPHHHPH", "3d5": "HPPPHHPPHPHPPPHPPPHPHHPPPHHPHPHHPHPPHPPPHPPHPHHHPPHPPHPPHHHPHHHH", "3d6": "HPPHHPHHHHPPPPPPHHPPHPPPPHHPPPHPPHPHHPHPPPPHHPPPPHPPPPPHPPPPHPHH", "3d7": "PPPPHPPPHPPPHHHHPHHPPPPPHPPHPHHPHPHPPPPPHPPPPPPPPPPHHHHPPPPHHPPH", "3d8": "PPPHHHPPHPHPPHPPHHPPPHPPHPPHHPHPPPHPPPPPPPHPHHHPHHHHHPPHHPPPHPPH", "3d9": "HPPHPPHHHPPPPHPHPPPHPHHPHHHHHPPPPHPHPHPPPPHPHPPPHHPHPPPPHPPHHPHP", "3d10": "PPHPPHPPHHHPPPHPHPPHPPHPPPPPPHPPHHHPPHPPHPPHPHPPPPPPHHHPPPPPHPHP" } class ExperimentHP(Experiment): name = "hp_3d1" box_size = (64, 64, 64) length = 64 global_tag = 113 freq = { 'mc_steps': 5000000, 'collect': 100, 'snapshot': 100, 'calc': 10, 'data': 100, 'pt': 200, 'athermal': 10000, 'cooling': 0 } def init(self): self.epsilon = 1 self.prepare_chain() settings.BASE_DIR = self.get_base_dir() settings.EXPERIMENTAL_ROOT_DIR = settings.BASE_DIR if settings.CREATE_DIR_STRUCTURE: tools.create_dir(settings.BASE_DIR) def prepare_chain(self): length = self.length chain_seq = bio.prepare_sequence(SEQUENCE_DB['3d1'], MonomerExpHP) self.chain_seq = Polymer.Chain(chain_seq) return self.chain_seq def c1_setup(self): name = "c1" self._setup(name, 0.5, 10.0, 100, swap = False) self.set_collect(**self.freq) settings.PERFORM_SWAP = False return (name, self.chain_seq) def c2_setup(self): name = "c2" self._setup(name, 0.01, 5.0, 200, swap = False) self.set_collect(**self.freq) settings.PERFORM_SWAP = False return (name, self.chain_seq) def m1_setup(self): name = "m1" self._setup(name, 0.5, 5.0, 101, swap = True) self.set_collect(**self.freq) settings.PERFORM_SWAP = True return (name, self.chain_seq) class ExperimentHP36(ExperimentHP): def prepare_chain(self): length = self.length chain_seq = bio.prepare_sequence(SEQUENCE_DB['3d1'], MonomerExpHP36) self.chain_seq = Polymer.Chain(chain_seq) return self.chain_seq if __name__ == "__main__": print ExperimentHP <file_sep>#!/bin/bash COMMENT="$1" git commit -am "$COMMENT" git push
d3779b561d678527521392a3923a1205d6609d6b
[ "Python", "C++", "Shell" ]
79
Shell
jkrajniak/science
03f0fab0292bce10bb03dbbfa40cc680890fd34b
f45e3cf811a6e6cd07dd50436c33929028919aad
refs/heads/master
<file_sep># SB-ITS This package implements effieicnt screening methods of predictive biomarkers for individual treatment selection via optimal discovery procedure, as proposed by the following papers. <NAME>. and <NAME>. (2020). Efficient Screening of Predictive Biomarkers for Individual Treatment Selection. *Biometrics*, to appear (https://arxiv.org/abs/1905.01582) Functions are implemented in HTEODP-bin-function.R and HTEODP-surv-function.R available in the repository. # Binary response Install R function and demo data. ```{r} load("Example-Data-bin.RData") source("HTEODP-bin-function.R") ``` Also install `qvalue' package used for comparison. ```{r} if (!requireNamespace("BiocManager", quietly = TRUE)) install.packages("BiocManager") BiocManager::install("qvalue") library(qvalue) ``` Apply the proposed method. (n: sample size; p: the number of candidate biomarkers) Input of `HTE.ODP.bin` - `Y`: n-dimensional vector of binary response variables (1 or 0) - `X`: (n,p)-matrix of biomarkers - `Z`: (n,q)-matrix of adjutment covariates, where q is the number of covariates - `PS`: n-dimensional vector of propensity scores - `Tr`: n-dimensional vector of treatment indicators (1 or -1) - `L`: number of knots (default is 100) - `alpha.set`: vector of nominal FDR values - `approx`: ODP-N is applied if `T`, and ODP-P is applied if `F` - `maxitr`: maximum number of iterations in EM algorithm (default us 100) Output of `HTE.ODP.bin` - `SV`: list of significant biomarkers - `Pi`: esitmated probability of null - `PP`: estimated point mass probabilities for non-null distribution - `Est`: (n,2)-matrix of point estimates and standard errors - `knots`: set of knots ```{r} alpha.set <- c(0.05, 0.1, 0.15, 0.2) fit.N <- HTE.ODP.bin(Y, X, Z, Tr, PS, L=200, alpha.set=alpha.set, approx=T, maxitr=300) fit.P <- HTE.ODP.bin(Y, X, Z, Tr, PS, L=200, alpha.set=alpha.set, approx=F, maxitr=300) ``` Significant biomarkers ```{r} SV.N <- fit.N$SV SV.P <- fit.P$SV ``` q-value method ```{r} p <- dim(X)[2] Stat <- fit.N$Est # summary statistics PV1 <- 2*( 1-pnorm( abs(Stat[,1]/Stat[,2]) ) ) PV2 <- c() for(k in 1:p){ f1 <- glm(Y[Tr==1]~X[Tr==1,k]+Z[Tr==1,], family="binomial") f2 <- glm(Y[Tr==-1]~X[Tr==-1,k]+Z[Tr==-1,], family="binomial") a1 <- summary(f1)$coefficients[2,1] - summary(f2)$coefficients[2,1] a2 <- sqrt( summary(f1)$coefficients[2,2]^2 + summary(f2)$coefficients[2,2]^2 ) PV2[k] <- 2*( 1-pnorm(abs(a1/a2)) ) } qv1 <- list() qv2 <- list() for(k in 1:4){ qv1[[k]] <- (1:p)[ qvalue(PV1,fdr=alpha.set[k])$significant ] qv2[[k]] <- (1:p)[ qvalue(PV2,fdr=alpha.set[k])$significant ] } ``` Summary of the results ```{r} SV <- list(SV.N, SV.P, qv1, qv2) # list of significant biomarkers from the four methods NS <- matrix(NA, 4, 4) # number of significant TP <- matrix(NA, 4, 4) # number of true positives dimnames(NS)[[1]] <- dimnames(TP)[[1]] <- c("ODP.N", "ODP.P", "qvalue1", "qvalue2") dimnames(NS)[[2]] <- dimnames(TP)[[2]] <- paste0("FDR=",alpha.set) for(j in 1:4){ NS[j,] <- as.numeric(lapply(SV[[j]], length)) for(k in 1:4){ TP[j,k] <- length(intersect(SV[[j]][[k]], Ind)) } } FP <- NS - TP # number of false positives ``` # Survival response Install R function and demo data. ```{r} load("Example-Data-surv.RData") source("HTEODP-surv-function.R") ``` Apply the proposed method. (n: sample size; p: the number of candidate biomarkers) In addition to the input of `HTE.ODP.bin`, `HTE.ODP.surv` requires `Event`. - `Event`: n-dimensional vector of event indicator (1: event; 0: censored) Output of `HTE.ODP.surv` is the same as `HTE.ODP.bin`. ```{r} alpha.set <- c(0.05, 0.1, 0.15, 0.2) fit.N <- HTE.ODP.surv(Y, Event, X, Z, Tr, PS, L=200, alpha.set=alpha.set, approx=T, maxitr=300) fit.P <- HTE.ODP.surv(Y, Event, X, Z, Tr, PS, L=200, alpha.set=alpha.set, approx=F, maxitr=300) ``` q-value method ```{r} p <- dim(X)[2] Stat <- fit.N$Est PV1 <- 2*( 1-pnorm( abs(Stat[,1]/Stat[,2]) ) ) PV2 <- c() for(k in 1:p){ f1 <- coxph( Surv(Y[Tr==1],Event[Tr==1])~X[Tr==1,k]+Z[Tr==1,] ) f2 <- coxph( Surv(Y[Tr==-1],Event[Tr==-1])~X[Tr==-1,k]+Z[Tr==-1,] ) a1 <- summary(f1)$coefficients[1] - summary(f2)$coefficients[1] a2 <- sqrt( summary(f1)$coefficients[1,3]^2 + summary(f2)$coefficients[1,3]^2 ) PV2[k] <- 2*( 1-pnorm(abs(a1/a2)) ) } qv1 <- list() qv2 <- list() for(k in 1:4){ qv1[[k]] <- (1:p)[ qvalue(PV1,fdr=alpha.set[k])$significant ] qv2[[k]] <- (1:p)[ qvalue(PV2,fdr=alpha.set[k])$significant ] } ``` <file_sep>###### Binary response ###### # Y: binary response variable (1 or 0) # X: biomarkers # Z: adjutment covariate # PS: propensity score # Tr: treatment indicator (1 or -1) # L: number of knots HTE.ODP.bin=function(Y, X, Z, Tr, PS=NULL, L=100, alpha.set=NULL, approx=F, maxitr=100){ p <- dim(X)[2] # number of biomarkers n <- dim(X)[1] # number of samples s <- dim(Z)[2] # number of adjutment covariates if( is.null(Z) ){ s <- 0 } if( is.null(alpha.set) ){ alpha.set <- c(0.05,0.1,0.15,0.2) } if( is.null(PS) ){ PS <- rep(1,n) } ww <- 2*( Tr*PS + (1-Tr)/2 ) ww <- ( (1/ww) / mean(1/ww) )^(-1) # normalization # Summary stat Est <- matrix(NA, p, 2) NP <- matrix(NA, p, s+1) # estimtes of nuisance parameters for(k in 1:p){ u1 <- Tr*X[,k] u2 <- Tr*Z if( is.null(Z)==F ){ fit <- glm(Y~-1+Tr+u1+u2, family="binomial", weights=1/ww) } if( is.null(Z)==T ){ fit <- glm(Y~-1+Tr+u1, family="binomial", weights=1/ww) } Est[k,] <- summary(fit)$coefficients[2,1:2] NP[k,] <- summary(fit)$coefficients[-2,1] } # knots ran <- range(Est[,1]) a.set <- seq(ran[1], ran[2], length=L) a.set <- subset(a.set,a.set!=0) L <- length(a.set) # Initial values of unknown parameters Pi <- 0.5 PP <- rep(1/L,L) # Estimation (approximation method) if(approx==T){ hbeta <- Est[,1] hsig <- Est[,2] for(itr in 1:maxitr){ par <- c(Pi,PP) d0 <- dnorm(hbeta, 0, hsig) d1 <- matrix(NA, p, L) for(k in 1:L){ d1[,k] <- dnorm(hbeta, a.set[k], hsig) } md1 <- apply(t(d1)*PP, 2, sum) Pw <- t(t(d1)*PP)/md1 Pz <- (Pi*d0) / (Pi*d0+(1-Pi)*md1) Pi <- mean(Pz) PPw <- (1-Pz)*Pw PP <- apply(PPw, 2, sum) / sum(PPw) dd <- sqrt( sum(( c(Pi,PP)-par )^2) ) / sqrt(sum(par^2)) if(dd < 10^(-5) ){ break } } ODP <- md1/d0 } # Estimation (plug-in method) if(approx==F){ tt <- apply(Y/ww*Tr*X, 2, sum) if( is.null(Z)==F ){ mat <- Tr*cbind(1, Z) } if( is.null(Z)==T ){ mat <- Tr*rep(1,n) } ad <- mat%*%t(NP) XT <- Tr*X PL <- function(beta){ val <- apply(log(1+exp(ad+XT*beta))/ww, 2, sum) return( tt*beta-val ) } for(itr in 1:maxitr){ par <- c(Pi,PP) L0 <- PL(0) L1 <- matrix(NA, p, L) for(k in 1:L){ L1[,k] <- PL(a.set[k]) } PL1 <- t(log(PP)+t(L1)) sPL1 <- PL1 - apply(PL1, 1, max) Pw <- exp(sPL1) / apply(exp(sPL1), 1, sum) ratio <- exp(L1-L0) c <- (1-Pi)/Pi*apply(PP*t(ratio), 2, sum) Pz <- 1/(1+c) Pi <- mean(Pz) PPw <- (1-Pz)*Pw PP <- apply(PPw,2,sum) / sum(PPw) dd <- sqrt( sum(( c(Pi,PP)-par )^2) ) / sqrt(sum(par^2)) if(dd < 10^(-3) ){ break } } ODP <- apply(PP*t(ratio), 2, sum) } # Optimal discovery procedure Lam <- sort(ODP,decreasing=T) FDR <- function(lam){ mean(Pz[ODP>=lam]) } fdr=c() for(r in 1:p){ fdr[r] <- FDR(Lam[r]) } M <- length(alpha.set) SV=list() for(k in 1:M){ op.lam <- tail(Lam[fdr<alpha.set[k]], 1) SV[[k]] <- (1:p)[ODP>=op.lam] } names(SV)=paste0("FDR=",alpha.set) # Summary Res <- list(SV=SV, Pi=Pi, PP=PP, Est=Est, knots=a.set) return(Res) }
b7119b09bbe1d468a3a54e72d852700139953273
[ "Markdown", "R" ]
2
Markdown
sshonosuke/SB-ITS
c9d2403de3ac9cc93f9c5cc9cf04e7a46cd65086
70870f76ad867e82109e8109069c4d6e016c10af
refs/heads/master
<repo_name>9Nama/docker_server<file_sep>/Gemfile source "https://rubygems.org" gem "firehose", github: 'firehoseio/firehose', "~> 1.4.0-rc3" gem "rainbows", "~> 4.4.3" gem "sprockets"
066f90c565588034d955a1001178c7b711ec2a64
[ "Ruby" ]
1
Ruby
9Nama/docker_server
3ce5607fdd9f60eb37ee600bdb79a254f95fa3d0
13d05ed6cbefd577cfcda08d7034aadea8a7fe09
refs/heads/master
<repo_name>timfirmin/playtopay<file_sep>/DB.DM/DPOWN/2. Views/Backload/DPOWN.DM_USAGE_CATEGORIES_VW.sql CREATE OR REPLACE FORCE VIEW DM_USAGE_CATEGORIES_VW AS SELECT CODE, DESCRIPTION, rtrim(LTRIM(translate(CODE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(DESCRIPTION,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0)) delim_row FROM DMOWN.USAGE_CATEGORIES; <file_sep>/DB.DM/DPOWN/2. Views/Backload/DPOWN.DM_PS_MEMBERS_IN_DIST_VW.sql CREATE OR REPLACE FORCE VIEW DM_PS_MEMBERS_IN_DIST_VW AS SELECT MEMBERSHIP_ID, MEMBER_DISTRIBUTION_SUMM_ID, trim(to_char(MEMBERSHIP_ID,9999999999))||''|| trim(to_char(MEMBER_DISTRIBUTION_SUMM_ID,9999999999)) delim_row FROM DMOWN.PS_MEMBERS_IN_DIST; <file_sep>/DB.DM/DPOWN/2. Views/Backload/DPOWN.DM_ROYALTY_LINE_TRANSFER_VW.sql CREATE OR REPLACE FORCE VIEW DM_ROYALTY_LINE_TRANSFER_VW AS SELECT ROYALTY_LINE_TRANSFER_ID, ADJUSTMENT_REASON_ID, TRANSFERRED_BY_USER_ID, CANCELLED_FLG, TRANSFERRED_DT, STATEMENT_VISIBLE_FLG, RECIPIENT_ADJ_REASON_ID, trim(to_char(ROYALTY_LINE_TRANSFER_ID,9999999999))||''|| trim(to_char(ADJUSTMENT_REASON_ID,9999999999))||''|| trim(to_char(TRANSFERRED_BY_USER_ID,9999999999))||''|| rtrim(LTRIM(translate(CANCELLED_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| to_char(TRANSFERRED_DT,'YYYY-MM-DD HH24:MI:SS')||''|| rtrim(LTRIM(translate(STATEMENT_VISIBLE_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(RECIPIENT_ADJ_REASON_ID,9999999999)) delim_row FROM DMOWN.ROYALTY_LINE_TRANSFER; <file_sep>/DB.DM/DPOWN/2. Views/Backload/DPOWN.DM_MEMBERSHIP_TYPE_VW.sql CREATE OR REPLACE FORCE VIEW DM_MEMBERSHIP_TYPE_VW AS SELECT MEMBERSHIP_TYPE_ID, DESCRIPTION, MEMBERSHIP_PRIORITY, RECORD_STATUS, trim(to_char(MEMBERSHIP_TYPE_ID,9999999999))||''|| rtrim(LTRIM(translate(DESCRIPTION,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(MEMBERSHIP_PRIORITY,99))||''|| rtrim(LTRIM(translate(RECORD_STATUS,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0)) delim_row FROM DMOWN.MEMBERSHIP_TYPE; <file_sep>/DB.DM/DPOWN/2. Views/Backload/DPOWN.DM_MEMBER_DISTRIBUTION_SUMM_VW.sql CREATE OR REPLACE FORCE VIEW DM_MEMBER_DISTRIBUTION_SUMM_VW AS SELECT MEMBER_DISTRIBUTION_SUMM_ID, MEMBERSHIP_ID, DISTRIBUTION_ID, STATEMENT_RUN_ID, NON_TAXABLE_AMT, TAXABLE_AMT, Q_ACCOUNT_AMT, DEDUCTION_AMT, VATABLE_AMT, MCPS_UK_ROYALTY_AMT, MCPS_NON_UK_ROYALTY_AMT, PAYMENT_SOC_NBR, trim(to_char(MEMBER_DISTRIBUTION_SUMM_ID,9999999999))||''|| trim(to_char(MEMBERSHIP_ID,9999999999))||''|| trim(to_char(DISTRIBUTION_ID,9999999999))||''|| trim(to_char(STATEMENT_RUN_ID,9999999999))||''|| trim(to_char(NON_TAXABLE_AMT,99999999999.99))||''|| trim(to_char(TAXABLE_AMT,99999999999.99))||''|| trim(to_char(Q_ACCOUNT_AMT,99999999999.99))||''|| trim(to_char(DEDUCTION_AMT,99999999999.99))||''|| trim(to_char(VATABLE_AMT,99999999999.99))||''|| trim(to_char(MCPS_UK_ROYALTY_AMT,99999999999.99))||''|| trim(to_char(MCPS_NON_UK_ROYALTY_AMT,99999999999.99))||''|| rtrim(LTRIM(translate(PAYMENT_SOC_NBR,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0)) delim_row FROM DMOWN.MEMBER_DISTRIBUTION_SUMM; <file_sep>/DB.DM/DPOWN/2. Views/DPOWN.DM_DIGITAL_PERFORMANCES_VW.sql CREATE OR REPLACE FORCE VIEW DM_DIGITAL_PERFORMANCES_VW AS SELECT /*+ PARALLEL(dipe,16) */ ID, INVO_INVOICE_NUMBER, DIWO_DISTRIBUTED_WORK_ID, INTERESTED_PARTY_1, INTERESTED_PARTY_2, INTERESTED_PARTY_3, INTERESTED_PARTY_4, ALBUM_TITLE, RELEASE_DT, ARTIST_NAME, FOREIGN_WORK_IDENTIFIER, NUMBER_OF_TRACKS, PERFORMANCE_DT, PERFORMANCE_QUANTITY, USCA_CODE, ISRC, CATALOGUE_NUMBER, DN_DISPENSABLE_DT, dipe.CREATED_DTM, CREATED_BY_APUS_ID, dipe.UPDATED_DTM, UPDATED_BY_APUS_ID, ICE_WORK_STATUS, PUBLISHER_SONG_CODE, UDWO_ID, PERFORMANCE_END_DT, trim(to_char(ID))||''|| trim(to_char(INVO_INVOICE_NUMBER,999999999999))||''|| trim(to_char(DIWO_DISTRIBUTED_WORK_ID,9999999999))||''|| rtrim(LTRIM(translate(INTERESTED_PARTY_1,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(INTERESTED_PARTY_2,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(INTERESTED_PARTY_3,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(INTERESTED_PARTY_4,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(ALBUM_TITLE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| to_char(RELEASE_DT,'YYYY-MM-DD HH24:MI:SS')||''|| rtrim(LTRIM(translate(ARTIST_NAME,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(FOREIGN_WORK_IDENTIFIER,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(NUMBER_OF_TRACKS,999999))||''|| to_char(PERFORMANCE_DT,'YYYY-MM-DD HH24:MI:SS')||''|| trim(to_char(PERFORMANCE_QUANTITY,9999999999))||''|| rtrim(LTRIM(translate(USCA_CODE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(ISRC,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(CATALOGUE_NUMBER,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| to_char(DN_DISPENSABLE_DT,'YYYY-MM-DD HH24:MI:SS')||''|| to_char(dipe.CREATED_DTM,'YYYY-MM-DD HH24:MI:SS')||''|| trim(to_char(CREATED_BY_APUS_ID,9999999999))||''|| to_char(dipe.UPDATED_DTM,'YYYY-MM-DD HH24:MI:SS')||''|| trim(to_char(UPDATED_BY_APUS_ID,9999999999))||''|| trim(to_char(ICE_WORK_STATUS,99))||''|| rtrim(LTRIM(translate(PUBLISHER_SONG_CODE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(UDWO_ID,9999999999))||''|| to_char(PERFORMANCE_END_DT,'YYYY-MM-DD HH24:MI:SS') delim_row FROM DMOWN.DIGITAL_PERFORMANCES PARTITION (P_DIPE_CURR) dipe CROSS JOIN DPOWN.P2P_DM_EXTRACT_CONTROL exctl WHERE exctl.EXTRACTED_TO_BI_Y IS NULL AND ((dipe.CREATED_DTM > exctl.EXTRACT_START_DTM) OR (dipe.UPDATED_DTM > exctl.EXTRACT_START_DTM)); <file_sep>/DB.DM/DPOWN/2. Views/Backload/DPOWN.DM_INVOICES_AUD_VW.sql CREATE OR REPLACE FORCE VIEW DM_INVOICES_AUD_VW AS SELECT INVOICE_NUMBER, DELETION_DTM, DELETED_BY_APUS_ID, DELETION_COMMENT, CREATED_DTM, trim(to_char(INVOICE_NUMBER,999999999999))||''|| to_char(DELETION_DTM,'YYYY-MM-DD HH24:MI:SS')||''|| trim(to_char(DELETED_BY_APUS_ID,9999999999))||''|| rtrim(LTRIM(translate(DELETION_COMMENT,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| to_char(CREATED_DTM,'YYYY-MM-DD HH24:MI:SS') delim_row FROM DMOWN.INVOICES_AUD; <file_sep>/DB.DM/DPOWN/Testing/P2P_DM_EXTRACT_UTILITY.sql SET SERVEROUTPUT ON DECLARE l_date DATE; BEGIN l_date := dpown.p2p_dm_extract_utility.get_extract_start_dtm; DBMS_OUTPUT.PUT_LINE('DATE='||TO_CHAR(l_date,'dd/mm/yyyy hh24:mi:ss')); END; / SET SERVEROUTPUT ON SET TIMING ON DECLARE l_date DATE; BEGIN l_date := dpown.p2p_dm_extract_utility.get_extract_end_dtm; DBMS_OUTPUT.PUT_LINE('DATE='||TO_CHAR(l_date,'dd/mm/yyyy hh24:mi:ss')); END; / SELECT * FROM dpown.p2p_dm_extract_control --WHERE extracted_to_bi_y IS NULL ORDER BY extract_id DESC; SET SERVEROUTPUT ON SET TIMING ON BEGIN dpown.p2p_dm_extract_utility.initialise_extract; END; / BEGIN dpown.p2p_dm_extract_utility.set_changes_extracted (p_extract_id => 76); END; / SET SERVEROUTPUT ON DECLARE l_rows_extracted NUMBER; BEGIN p2p_dm_extract_utility.extract_data_file(p_table_name => 'DM_INVOICES', p_extract_id => 4, p_thread => NULL, p_rows_extracted => l_rows_extracted); dbms_output.put_line('rows='||l_rows_extracted ); END; / SET SERVEROUTPUT ON DECLARE l_rows_extracted NUMBER; BEGIN p2p_dm_extract_utility.extract_data_file(p_table_name => 'DM_CAE', p_extract_id => 4, p_thread => NULL, p_rows_extracted => l_rows_extracted); dbms_output.put_line('rows='||l_rows_extracted ); END; /<file_sep>/DB.DM/DPOWN/2. Views/Backload/DPOWN.DM_CODA_ACCOUNT_VW.sql CREATE OR REPLACE FORCE VIEW DM_CODA_ACCOUNT_VW AS SELECT CODA_ACCOUNT_ID, LEVEL_ONE_ELEMENT_CODE, LEVEL_TWO_ELEMENT_CODE, ACCOUNT_NAME, DELETED_DT, EXTRACT_DT, LEVEL_THREE_ELEMENT_CODE, LEVEL_FOUR_ELEMENT_CODE, LEVEL_FIVE_ELEMENT_CODE, COMPANY_CODE, trim(to_char(CODA_ACCOUNT_ID,9999999999))||''|| rtrim(LTRIM(translate(LEVEL_ONE_ELEMENT_CODE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(LEVEL_TWO_ELEMENT_CODE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(ACCOUNT_NAME,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| to_char(DELETED_DT,'YYYY-MM-DD HH24:MI:SS')||''|| to_char(EXTRACT_DT,'YYYY-MM-DD HH24:MI:SS')||''|| rtrim(LTRIM(translate(LEVEL_THREE_ELEMENT_CODE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(LEVEL_FOUR_ELEMENT_CODE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(LEVEL_FIVE_ELEMENT_CODE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(COMPANY_CODE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0)) delim_row FROM DMOWN.CODA_ACCOUNT WHERE CODA_ACCOUNT_ID IN ( SELECT DISTINCT COAC_ID FROM DMOWN.USAGE_GROUP_CODA_ACCOUNTS ) ; + <file_sep>/DB.DM/DPOWN/2. Views/Backload/DPOWN.DM_PERFORMANCE_VW.sql CREATE OR REPLACE FORCE VIEW DM_PERFORMANCE_VW AS SELECT /*+ PARALLEL(perf, 16) */ perf.PERFORMANCE_ID, DIST_WORK_IN_REP_POST_ID, BROADCAST_REGION_ID, DURATION, INTERESTED_PARTY_1, INTERESTED_PARTY_2, INTERESTED_PARTY_3, INTERESTED_PARTY_4, PERFORMANCE_DT, PERFORMANCE_END_DT, PRODUCTION_HEADER, STATION_CODE, PS_OLD_PERFORMANCE_ID, USAGE_CLASSIFICATION, PRODUCTION_ID, EPISODE_TITLE, AUTO_CLAIM_FLG, PERFORMANCE_QTY, CATALOGUE_NUMBER, trim(to_char(perf.PERFORMANCE_ID))||''|| trim(to_char(DIST_WORK_IN_REP_POST_ID,9999999999))||''|| trim(to_char(BROADCAST_REGION_ID,9999999999))||''|| trim(to_char(DURATION,999999999))||''|| rtrim(LTRIM(translate(INTERESTED_PARTY_1,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(INTERESTED_PARTY_2,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(INTERESTED_PARTY_3,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(INTERESTED_PARTY_4,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| to_char(PERFORMANCE_DT,'YYYY-MM-DD HH24:MI:SS')||''|| to_char(PERFORMANCE_END_DT,'YYYY-MM-DD HH24:MI:SS')||''|| rtrim(LTRIM(translate(PRODUCTION_HEADER,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(STATION_CODE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(PS_OLD_PERFORMANCE_ID))||''|| rtrim(LTRIM(translate(USAGE_CLASSIFICATION,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(PRODUCTION_ID,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(EPISODE_TITLE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(AUTO_CLAIM_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(PERFORMANCE_QTY,9999999999))||''|| rtrim(LTRIM(translate(CATALOGUE_NUMBER,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0)) delim_row FROM DMOWN.PERFORMANCE perf JOIN (SELECT /*+ PARALLEL(rotr044, 16) */ PERFORMANCE_ID FROM DMOWN.ROYALTY_TRANSACTION PARTITION (P_ROTR_044_CURR) rotr044 WHERE (DN_DISPENSABLE_DT IS NOT NULL AND MEMBER_DISTRIBUTION_SUMM_ID IS NULL) OR (DN_DISPENSABLE_DT IS NULL) UNION SELECT /*+ PARALLEL(rotr052, 16) */ PERFORMANCE_ID FROM DMOWN.ROYALTY_TRANSACTION PARTITION (P_ROTR_052_CURR) rotr052 WHERE (DN_DISPENSABLE_DT IS NOT NULL AND MEMBER_DISTRIBUTION_SUMM_ID IS NULL) OR (DN_DISPENSABLE_DT IS NULL) ) rotr ON (perf.PERFORMANCE_ID = rotr.PERFORMANCE_ID); <file_sep>/DB.DM/DPOWN/2. Views/DPOWN.DM_DIGITAL_TRANSACTIONS_VW.sql CREATE OR REPLACE FORCE VIEW DM_DIGITAL_TRANSACTIONS_VW AS SELECT /*+ PARALLEL(ditr,16) */ ID, CAE_NBR, DIPE_ID, IRHG_INVO_INVOICE_NUMBER, IRHG_RIHG_CODE, AMOUNT, INV_CCY_AMOUNT, MEMB_ID, MEMBER_SHARE, IRHG_RIGHT_TYPE, DN_FULLY_PAID_AT_DIST_ID, DN_DISPENSABLE_DT, ditr.CREATED_DTM, CREATED_BY_APUS_ID, ditr.UPDATED_DTM, UPDATED_BY_APUS_ID, REMA_ID, DN_MEMB_SUB_PARTITION_KEY AS THREAD_NO, PAYMENT_SOC_NBR, IPI_SOC_NBR, DN_ON_BEHALF_OF_SOC_NBR, REVERSED_BY_DITR_ID, REVERSAL_OF_DITR_ID, ADJUSTMENT_OF_DITR_ID, DN_MOVED_FROM_MEMB_ID, PENDING_ADJUSTMENT_Y, trim(to_char(ID))||''|| rtrim(LTRIM(translate(CAE_NBR,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(DIPE_ID))||''|| trim(to_char(IRHG_INVO_INVOICE_NUMBER,999999999999))||''|| rtrim(LTRIM(translate(IRHG_RIHG_CODE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(AMOUNT,999999999999999999.9999))||''|| trim(to_char(INV_CCY_AMOUNT,999999999999999999.9999))||''|| trim(to_char(MEMB_ID,9999999999))||''|| trim(to_char(MEMBER_SHARE,9999999999.99999))||''|| rtrim(LTRIM(translate(IRHG_RIGHT_TYPE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(DN_FULLY_PAID_AT_DIST_ID,9999999999))||''|| to_char(DN_DISPENSABLE_DT,'YYYY-MM-DD HH24:MI:SS')||''|| to_char(ditr.CREATED_DTM,'YYYY-MM-DD HH24:MI:SS')||''|| trim(to_char(CREATED_BY_APUS_ID,9999999999))||''|| to_char(ditr.UPDATED_DTM,'YYYY-MM-DD HH24:MI:SS')||''|| trim(to_char(UPDATED_BY_APUS_ID,9999999999))||''|| trim(to_char(REMA_ID,99999999999))||''|| trim(to_char(DN_MEMB_SUB_PARTITION_KEY,9999))||''|| rtrim(LTRIM(translate(PAYMENT_SOC_NBR,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(IPI_SOC_NBR,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(DN_ON_BEHALF_OF_SOC_NBR,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(REVERSED_BY_DITR_ID))||''|| trim(to_char(REVERSAL_OF_DITR_ID))||''|| trim(to_char(ADJUSTMENT_OF_DITR_ID))||''|| trim(to_char(DN_MOVED_FROM_MEMB_ID,9999999999))||''|| rtrim(LTRIM(translate(PENDING_ADJUSTMENT_Y,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0)) delim_row FROM DMOWN.DIGITAL_TRANSACTIONS PARTITION (P_DITR_044_CURR) ditr CROSS JOIN DPOWN.P2P_DM_EXTRACT_CONTROL exctl WHERE exctl.EXTRACTED_TO_BI_Y IS NULL AND ((ditr.CREATED_DTM > exctl.EXTRACT_START_DTM) OR (ditr.UPDATED_DTM > exctl.EXTRACT_START_DTM)) UNION ALL SELECT /*+ PARALLEL(ditr,16) */ ID, CAE_NBR, DIPE_ID, IRHG_INVO_INVOICE_NUMBER, IRHG_RIHG_CODE, AMOUNT, INV_CCY_AMOUNT, MEMB_ID, MEMBER_SHARE, IRHG_RIGHT_TYPE, DN_FULLY_PAID_AT_DIST_ID, DN_DISPENSABLE_DT, ditr.CREATED_DTM, CREATED_BY_APUS_ID, ditr.UPDATED_DTM, UPDATED_BY_APUS_ID, REMA_ID, DN_MEMB_SUB_PARTITION_KEY AS THREAD_NO, PAYMENT_SOC_NBR, IPI_SOC_NBR, DN_ON_BEHALF_OF_SOC_NBR, REVERSED_BY_DITR_ID, REVERSAL_OF_DITR_ID, ADJUSTMENT_OF_DITR_ID, DN_MOVED_FROM_MEMB_ID, PENDING_ADJUSTMENT_Y, trim(to_char(ID))||''|| rtrim(LTRIM(translate(CAE_NBR,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(DIPE_ID))||''|| trim(to_char(IRHG_INVO_INVOICE_NUMBER,999999999999))||''|| rtrim(LTRIM(translate(IRHG_RIHG_CODE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(AMOUNT,999999999999999999.9999))||''|| trim(to_char(INV_CCY_AMOUNT,999999999999999999.9999))||''|| trim(to_char(MEMB_ID,9999999999))||''|| trim(to_char(MEMBER_SHARE,9999999999.99999))||''|| rtrim(LTRIM(translate(IRHG_RIGHT_TYPE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(DN_FULLY_PAID_AT_DIST_ID,9999999999))||''|| to_char(DN_DISPENSABLE_DT,'YYYY-MM-DD HH24:MI:SS')||''|| to_char(ditr.CREATED_DTM,'YYYY-MM-DD HH24:MI:SS')||''|| trim(to_char(CREATED_BY_APUS_ID,9999999999))||''|| to_char(ditr.UPDATED_DTM,'YYYY-MM-DD HH24:MI:SS')||''|| trim(to_char(UPDATED_BY_APUS_ID,9999999999))||''|| trim(to_char(REMA_ID,99999999999))||''|| trim(to_char(DN_MEMB_SUB_PARTITION_KEY,9999))||''|| rtrim(LTRIM(translate(PAYMENT_SOC_NBR,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(IPI_SOC_NBR,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(DN_ON_BEHALF_OF_SOC_NBR,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(REVERSED_BY_DITR_ID))||''|| trim(to_char(REVERSAL_OF_DITR_ID))||''|| trim(to_char(ADJUSTMENT_OF_DITR_ID))||''|| trim(to_char(DN_MOVED_FROM_MEMB_ID,9999999999))||''|| rtrim(LTRIM(translate(PENDING_ADJUSTMENT_Y,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0)) delim_row FROM DMOWN.DIGITAL_TRANSACTIONS PARTITION (P_DITR_052_CURR) ditr CROSS JOIN DPOWN.P2P_DM_EXTRACT_CONTROL exctl WHERE exctl.EXTRACTED_TO_BI_Y IS NULL AND ((ditr.CREATED_DTM > exctl.EXTRACT_START_DTM) OR (ditr.UPDATED_DTM > exctl.EXTRACT_START_DTM)); <file_sep>/DB.DM/DPOWN/1. Tables/Default Data Scripts/DPOWN.P2P_DM_EXTRACT_CONTROL.sql DECLARE l_extract_dtm DATE := TO_DATE('01011900','ddmmyyyy'); BEGIN DELETE FROM dpown.p2p_dm_extract_control WHERE extract_id = 0; INSERT INTO dpown.p2p_dm_extract_control (extract_id, created_dtm, updated_dtm, extract_start_dtm, extract_end_dtm, extracted_to_bi_y) VALUES (0, SYSDATE, NULL, l_extract_dtm, l_extract_dtm, 'Y'); COMMIT; END; / <file_sep>/DB.DM/DPOWN/2. Views/Backload/DPOWN.DM_ROYALTY_TRANSACTION_VW.sql CREATE OR REPLACE FORCE VIEW DM_ROYALTY_TRANSACTION_VW AS SELECT /*+ PARALLEL(rotr,16) */ ROYALTY_TRANSACTION_ID, MEMBERSHIP_ID, ROYALTY_TRANSACTION_TYPE_ID, ADJ_CREATED_BY_USER_ID, ADJ_TO_ROYALTY_TRANSACTION_ID, ADJUSTMENT_REASON_ID, ALLOCATION_ID, BROADCAST_REGION_ID, BY_ROYALTY_LINE_TRANSFER_ID, CAE_ID, DC_STATEMENT_RUN_ID, DISTRIBUTED_WORK_ID, DYNAMIC_HOLD_ID, MEMBER_DISTRIBUTION_SUMM_ID, PERFORMANCE_ID, RECIP_DEDUCT_CODA_ACCOUNT_ID, REPERTOIRE_POSTING_ID, TO_ROYALTY_LINE_TRANSFER_ID, USAGE_GROUP_ID, DROPPED_FLG, POSTED_DT, STATEMENT_VISIBLE_FLG, STATEMENTED_FLG, TEMPORARY_FLG, ACTION_DT, ACTIONED_FLG, ADJ_PAY_NEXT_MINI_FLG, ADJUSTMENT_SEQUENCE_NBR, COMPOSER_NAME, DURATION, EF_IND, FIXED_POINT_RECONCILED_FLG, GROSS_AMT, HGH_INT_DT, INTERESTED_PARTY_1, INTERESTED_PARTY_2, INTERESTED_PARTY_3, INTERESTED_PARTY_4, ISWC, MEMBER_SHARE, PERIOD_END_DT, PERFORMANCE_DT, PERFORMANCE_QTY, POINTS, PROCESS_STAGE, PRODUCTION_HEADER, PS_ADJUST_ROYALTY_FLG, RECIPROCAL_DEDUCTION_AMT, RYTY_TRANS_COMMENT, SEND_TO_HGH_INT_FLG, STATION_CODE, TUNECODE, UNNOTIFIED_FLG, WID, WORK_TITLE, USAGE_CLASSIFICATION, DISTRIBUTION_CATEGORY, LABEL, ISAN, WARSAW_FLG, DN_DISPENSABLE_DT, DN_MEMB_SUB_PARTITION_KEY AS THREAD_NO, RIGHT_TYPE, IPI_SOC_NBR, ON_BEHALF_OF_SOC_NBR, PAYMENT_SOC_NBR, PRODUCTION_MUSIC_YN, MCMC_CATEGORY, DEDUCTION_AMT, SOURCE_USAGE_IP_PAYMENT_ID, BLANKET_DEDUCTION_RATE_PCT, CREATED_BY_APUS_ID, UPDATED_DTM, UPDATED_BY_APUS_ID, TRIM(TO_CHAR(ROYALTY_TRANSACTION_ID))||''|| TRIM(TO_CHAR(MEMBERSHIP_ID,9999999999))||''|| TRIM(TO_CHAR(ROYALTY_TRANSACTION_TYPE_ID,9999999999))||''|| TRIM(TO_CHAR(ADJ_CREATED_BY_USER_ID,9999999999))||''|| TRIM(TO_CHAR(ADJ_TO_ROYALTY_TRANSACTION_ID))||''|| TRIM(TO_CHAR(ADJUSTMENT_REASON_ID,9999999999))||''|| TRIM(TO_CHAR(ALLOCATION_ID,9999999999))||''|| TRIM(TO_CHAR(BROADCAST_REGION_ID,9999999999))||''|| TRIM(TO_CHAR(BY_ROYALTY_LINE_TRANSFER_ID,9999999999))||''|| TRIM(TO_CHAR(CAE_ID,9999999999))||''|| TRIM(TO_CHAR(DC_STATEMENT_RUN_ID,9999999999))||''|| TRIM(TO_CHAR(DISTRIBUTED_WORK_ID,9999999999))||''|| TRIM(TO_CHAR(DYNAMIC_HOLD_ID,9999999999))||''|| TRIM(TO_CHAR(MEMBER_DISTRIBUTION_SUMM_ID,9999999999))||''|| TRIM(TO_CHAR(PERFORMANCE_ID))||''|| TRIM(TO_CHAR(RECIP_DEDUCT_CODA_ACCOUNT_ID,9999999999))||''|| TRIM(TO_CHAR(REPERTOIRE_POSTING_ID,9999999999))||''|| TRIM(TO_CHAR(TO_ROYALTY_LINE_TRANSFER_ID,9999999999))||''|| TRIM(TO_CHAR(USAGE_GROUP_ID,9999999999))||''|| RTRIM(LTRIM(TRANSLATE(DROPPED_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| TO_CHAR(POSTED_DT,'YYYY-MM-DD HH24:MI:SS')||''|| RTRIM(LTRIM(TRANSLATE(STATEMENT_VISIBLE_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(STATEMENTED_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(TEMPORARY_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| TO_CHAR(ACTION_DT,'YYYY-MM-DD HH24:MI:SS')||''|| RTRIM(LTRIM(TRANSLATE(ACTIONED_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(ADJ_PAY_NEXT_MINI_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| TRIM(TO_CHAR(ADJUSTMENT_SEQUENCE_NBR,999))||''|| RTRIM(LTRIM(TRANSLATE(COMPOSER_NAME,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| TRIM(TO_CHAR(DURATION,999999999))||''|| RTRIM(LTRIM(TRANSLATE(EF_IND,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(FIXED_POINT_RECONCILED_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| TRIM(TO_CHAR(GROSS_AMT,99999999999.99))||''|| TO_CHAR(HGH_INT_DT,'YYYY-MM-DD HH24:MI:SS')||''|| RTRIM(LTRIM(TRANSLATE(INTERESTED_PARTY_1,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(INTERESTED_PARTY_2,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(INTERESTED_PARTY_3,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(INTERESTED_PARTY_4,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(ISWC,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| TRIM(TO_CHAR(MEMBER_SHARE,9999999999.99999))||''|| TO_CHAR(PERIOD_END_DT,'YYYY-MM-DD HH24:MI:SS')||''|| TO_CHAR(PERFORMANCE_DT,'YYYY-MM-DD HH24:MI:SS')||''|| TRIM(TO_CHAR(PERFORMANCE_QTY,999999999))||''|| TRIM(TO_CHAR(POINTS,999999999999.999))||''|| RTRIM(LTRIM(TRANSLATE(PROCESS_STAGE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(PRODUCTION_HEADER,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(PS_ADJUST_ROYALTY_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| TRIM(TO_CHAR(RECIPROCAL_DEDUCTION_AMT,99999999999.99))||''|| RTRIM(LTRIM(TRANSLATE(RYTY_TRANS_COMMENT,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(SEND_TO_HGH_INT_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(STATION_CODE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(TUNECODE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(UNNOTIFIED_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(WID,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(WORK_TITLE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(USAGE_CLASSIFICATION,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(DISTRIBUTION_CATEGORY,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(LABEL,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(ISAN,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(WARSAW_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| TO_CHAR(DN_DISPENSABLE_DT,'YYYY-MM-DD HH24:MI:SS')||''|| TRIM(TO_CHAR(DN_MEMB_SUB_PARTITION_KEY,9999))||''|| RTRIM(LTRIM(TRANSLATE(RIGHT_TYPE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(IPI_SOC_NBR,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(ON_BEHALF_OF_SOC_NBR,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(PAYMENT_SOC_NBR,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(PRODUCTION_MUSIC_YN,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(MCMC_CATEGORY,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| TRIM(TO_CHAR(DEDUCTION_AMT,99999999999.99))||''|| TRIM(TO_CHAR(SOURCE_USAGE_IP_PAYMENT_ID,999999999999))||''|| TRIM(TO_CHAR(BLANKET_DEDUCTION_RATE_PCT,9999999.9999))||''|| TRIM(TO_CHAR(CREATED_BY_APUS_ID,9999999999))||''|| TO_CHAR(UPDATED_DTM,'YYYY-MM-DD HH24:MI:SS')||''|| TRIM(TO_CHAR(UPDATED_BY_APUS_ID,9999999999)) delim_row FROM DMOWN.ROYALTY_TRANSACTION PARTITION (P_ROTR_044_CURR) rotr WHERE (rotr.DN_DISPENSABLE_DT IS NOT NULL AND rotr.MEMBER_DISTRIBUTION_SUMM_ID IS NULL) OR (rotr.DN_DISPENSABLE_DT IS NULL) UNION ALL SELECT /*+ PARALLEL(rotr,16) */ ROYALTY_TRANSACTION_ID, MEMBERSHIP_ID, ROYALTY_TRANSACTION_TYPE_ID, ADJ_CREATED_BY_USER_ID, ADJ_TO_ROYALTY_TRANSACTION_ID, ADJUSTMENT_REASON_ID, ALLOCATION_ID, BROADCAST_REGION_ID, BY_ROYALTY_LINE_TRANSFER_ID, CAE_ID, DC_STATEMENT_RUN_ID, DISTRIBUTED_WORK_ID, DYNAMIC_HOLD_ID, MEMBER_DISTRIBUTION_SUMM_ID, PERFORMANCE_ID, RECIP_DEDUCT_CODA_ACCOUNT_ID, REPERTOIRE_POSTING_ID, TO_ROYALTY_LINE_TRANSFER_ID, USAGE_GROUP_ID, DROPPED_FLG, POSTED_DT, STATEMENT_VISIBLE_FLG, STATEMENTED_FLG, TEMPORARY_FLG, ACTION_DT, ACTIONED_FLG, ADJ_PAY_NEXT_MINI_FLG, ADJUSTMENT_SEQUENCE_NBR, COMPOSER_NAME, DURATION, EF_IND, FIXED_POINT_RECONCILED_FLG, GROSS_AMT, HGH_INT_DT, INTERESTED_PARTY_1, INTERESTED_PARTY_2, INTERESTED_PARTY_3, INTERESTED_PARTY_4, ISWC, MEMBER_SHARE, PERIOD_END_DT, PERFORMANCE_DT, PERFORMANCE_QTY, POINTS, PROCESS_STAGE, PRODUCTION_HEADER, PS_ADJUST_ROYALTY_FLG, RECIPROCAL_DEDUCTION_AMT, RYTY_TRANS_COMMENT, SEND_TO_HGH_INT_FLG, STATION_CODE, TUNECODE, UNNOTIFIED_FLG, WID, WORK_TITLE, USAGE_CLASSIFICATION, DISTRIBUTION_CATEGORY, LABEL, ISAN, WARSAW_FLG, DN_DISPENSABLE_DT, DN_MEMB_SUB_PARTITION_KEY AS THREAD_NO, RIGHT_TYPE, IPI_SOC_NBR, ON_BEHALF_OF_SOC_NBR, PAYMENT_SOC_NBR, PRODUCTION_MUSIC_YN, MCMC_CATEGORY, DEDUCTION_AMT, SOURCE_USAGE_IP_PAYMENT_ID, BLANKET_DEDUCTION_RATE_PCT, CREATED_BY_APUS_ID, UPDATED_DTM, UPDATED_BY_APUS_ID, TRIM(TO_CHAR(ROYALTY_TRANSACTION_ID))||''|| TRIM(TO_CHAR(MEMBERSHIP_ID,9999999999))||''|| TRIM(TO_CHAR(ROYALTY_TRANSACTION_TYPE_ID,9999999999))||''|| TRIM(TO_CHAR(ADJ_CREATED_BY_USER_ID,9999999999))||''|| TRIM(TO_CHAR(ADJ_TO_ROYALTY_TRANSACTION_ID))||''|| TRIM(TO_CHAR(ADJUSTMENT_REASON_ID,9999999999))||''|| TRIM(TO_CHAR(ALLOCATION_ID,9999999999))||''|| TRIM(TO_CHAR(BROADCAST_REGION_ID,9999999999))||''|| TRIM(TO_CHAR(BY_ROYALTY_LINE_TRANSFER_ID,9999999999))||''|| TRIM(TO_CHAR(CAE_ID,9999999999))||''|| TRIM(TO_CHAR(DC_STATEMENT_RUN_ID,9999999999))||''|| TRIM(TO_CHAR(DISTRIBUTED_WORK_ID,9999999999))||''|| TRIM(TO_CHAR(DYNAMIC_HOLD_ID,9999999999))||''|| TRIM(TO_CHAR(MEMBER_DISTRIBUTION_SUMM_ID,9999999999))||''|| TRIM(TO_CHAR(PERFORMANCE_ID))||''|| TRIM(TO_CHAR(RECIP_DEDUCT_CODA_ACCOUNT_ID,9999999999))||''|| TRIM(TO_CHAR(REPERTOIRE_POSTING_ID,9999999999))||''|| TRIM(TO_CHAR(TO_ROYALTY_LINE_TRANSFER_ID,9999999999))||''|| TRIM(TO_CHAR(USAGE_GROUP_ID,9999999999))||''|| RTRIM(LTRIM(TRANSLATE(DROPPED_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| TO_CHAR(POSTED_DT,'YYYY-MM-DD HH24:MI:SS')||''|| RTRIM(LTRIM(TRANSLATE(STATEMENT_VISIBLE_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(STATEMENTED_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(TEMPORARY_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| TO_CHAR(ACTION_DT,'YYYY-MM-DD HH24:MI:SS')||''|| RTRIM(LTRIM(TRANSLATE(ACTIONED_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(ADJ_PAY_NEXT_MINI_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| TRIM(TO_CHAR(ADJUSTMENT_SEQUENCE_NBR,999))||''|| RTRIM(LTRIM(TRANSLATE(COMPOSER_NAME,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| TRIM(TO_CHAR(DURATION,999999999))||''|| RTRIM(LTRIM(TRANSLATE(EF_IND,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(FIXED_POINT_RECONCILED_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| TRIM(TO_CHAR(GROSS_AMT,99999999999.99))||''|| TO_CHAR(HGH_INT_DT,'YYYY-MM-DD HH24:MI:SS')||''|| RTRIM(LTRIM(TRANSLATE(INTERESTED_PARTY_1,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(INTERESTED_PARTY_2,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(INTERESTED_PARTY_3,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(INTERESTED_PARTY_4,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(ISWC,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| TRIM(TO_CHAR(MEMBER_SHARE,9999999999.99999))||''|| TO_CHAR(PERIOD_END_DT,'YYYY-MM-DD HH24:MI:SS')||''|| TO_CHAR(PERFORMANCE_DT,'YYYY-MM-DD HH24:MI:SS')||''|| TRIM(TO_CHAR(PERFORMANCE_QTY,999999999))||''|| TRIM(TO_CHAR(POINTS,999999999999.999))||''|| RTRIM(LTRIM(TRANSLATE(PROCESS_STAGE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(PRODUCTION_HEADER,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(PS_ADJUST_ROYALTY_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| TRIM(TO_CHAR(RECIPROCAL_DEDUCTION_AMT,99999999999.99))||''|| RTRIM(LTRIM(TRANSLATE(RYTY_TRANS_COMMENT,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(SEND_TO_HGH_INT_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(STATION_CODE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(TUNECODE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(UNNOTIFIED_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(WID,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(WORK_TITLE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(USAGE_CLASSIFICATION,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(DISTRIBUTION_CATEGORY,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(LABEL,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(ISAN,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(WARSAW_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| TO_CHAR(DN_DISPENSABLE_DT,'YYYY-MM-DD HH24:MI:SS')||''|| TRIM(TO_CHAR(DN_MEMB_SUB_PARTITION_KEY,9999))||''|| RTRIM(LTRIM(TRANSLATE(RIGHT_TYPE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(IPI_SOC_NBR,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(ON_BEHALF_OF_SOC_NBR,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(PAYMENT_SOC_NBR,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(PRODUCTION_MUSIC_YN,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(MCMC_CATEGORY,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| TRIM(TO_CHAR(DEDUCTION_AMT,99999999999.99))||''|| TRIM(TO_CHAR(SOURCE_USAGE_IP_PAYMENT_ID,999999999999))||''|| TRIM(TO_CHAR(BLANKET_DEDUCTION_RATE_PCT,9999999.9999))||''|| TRIM(TO_CHAR(CREATED_BY_APUS_ID,9999999999))||''|| TO_CHAR(UPDATED_DTM,'YYYY-MM-DD HH24:MI:SS')||''|| TRIM(TO_CHAR(UPDATED_BY_APUS_ID,9999999999)) delim_row FROM DMOWN.ROYALTY_TRANSACTION PARTITION (P_ROTR_052_CURR) rotr WHERE (rotr.DN_DISPENSABLE_DT IS NOT NULL AND rotr.MEMBER_DISTRIBUTION_SUMM_ID IS NULL) OR (rotr.DN_DISPENSABLE_DT IS NULL); <file_sep>/DB.DM/DPOWN/2. Views/Backload/DPOWN.DM_CASHING_OUT_HISTORY_VW.sql CREATE OR REPLACE FORCE VIEW DM_CASHING_OUT_HISTORY_VW AS SELECT CASHING_OUT_HISTORY_ID, CASHING_OUT_GROUP_ID, CREATED_BY_USER_ID, LAST_UPDATED_BY_USER_ID, CASHED_OUT_DT, CASHING_OUT_NBR, CREATED_DT, FORECAST_REPORT_FLG, GROSS_DISTRIBUTABLE_AMT, NET_DISTRIBUTABLE_AMT, PROCESS_STAGE, ADDITIONAL_REVENUE_AMT, ADMINISTRATION_CHARGE_AMT, FIXED_POINT_VALUE, LAST_UPDATED_DT, LEDGER_BALANCE_AMT, RECIPROCAL_DEDUCTION_AMT, RESERVE_AMT, SUB_PUBLISHER_DEDUCTION_AMT, SUB_PUBLISHER_DEDUCTION_PCT, TRUE_POINT_VALUE, PUBLISHER_POINT_VALUE, trim(to_char(CASHING_OUT_HISTORY_ID,9999999999))||''|| trim(to_char(CASHING_OUT_GROUP_ID,9999999999))||''|| trim(to_char(CREATED_BY_USER_ID,9999999999))||''|| trim(to_char(LAST_UPDATED_BY_USER_ID,9999999999))||''|| to_char(CASHED_OUT_DT,'YYYY-MM-DD HH24:MI:SS')||''|| trim(to_char(CASHING_OUT_NBR,99))||''|| to_char(CREATED_DT,'YYYY-MM-DD HH24:MI:SS')||''|| rtrim(LTRIM(translate(FORECAST_REPORT_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(GROSS_DISTRIBUTABLE_AMT,99999999999.99))||''|| trim(to_char(NET_DISTRIBUTABLE_AMT,99999999999.99))||''|| rtrim(LTRIM(translate(PROCESS_STAGE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(ADDITIONAL_REVENUE_AMT,99999999999.99))||''|| trim(to_char(ADMINISTRATION_CHARGE_AMT,99999999999.99))||''|| trim(to_char(FIXED_POINT_VALUE,9999999999999.9999))||''|| to_char(LAST_UPDATED_DT,'YYYY-MM-DD HH24:MI:SS')||''|| trim(to_char(LEDGER_BALANCE_AMT,99999999999.99))||''|| trim(to_char(RECIPROCAL_DEDUCTION_AMT,99999999999.99))||''|| trim(to_char(RESERVE_AMT,99999999999.99))||''|| trim(to_char(SUB_PUBLISHER_DEDUCTION_AMT,99999999999.99))||''|| trim(to_char(SUB_PUBLISHER_DEDUCTION_PCT,999999.999))||''|| trim(to_char(TRUE_POINT_VALUE,9999999999999.9999))||''|| trim(to_char(PUBLISHER_POINT_VALUE,9999999999999.9999)) delim_row FROM DMOWN.CASHING_OUT_HISTORY; <file_sep>/DB.DM/DPOWN/2. Views/Backload/DPOWN.DM_INVOICES_VW.sql CREATE OR REPLACE FORCE VIEW DM_INVOICES_VW AS SELECT INVOICE_NUMBER, CCY_UNIT_CODE, LIBO_CODE, TERR_ISO_CODE, SOURCE_SYSTEM, CCY_EXCHANGE_RATE, CURA_ID, INVO_INVOICE_NUMBER_ADJUSTED, PAID_DT, STATUS, INVOICE_TYPE, AMOUNT, INV_CCY_AMOUNT, USGP_ID, SETY_CODE, CIF_INVOICE_NUMBER, CREATED_DTM, CREATED_BY_APUS_ID, UPDATED_DTM, UPDATED_BY_APUS_ID, LICENSEE_NUMBER, DN_AMOUNT, DN_INV_CCY_AMOUNT, DN_FIRST_AVAIL_DIST_ID, PRTY_CODE, INVF_FILE_NUMBER, COPIED_Y, ADJ_FROM_LICENSING_BODY, DN_GEMA_LICENSEE_NUMBER, RECEIVED_FILENAME, DN_STMT_USAGE_DESC, DN_DIPE_PERFORMANCE_START_DT, DN_DIPE_PERFORMANCE_END_DT, DED_RULE_EFFECTIVE_DT, DN_CIIC_FILE_NAME, ON_BEHALF_OF_SOC_NBR, LABEL_CHANNEL, EXCLUDE_FROM_COPY_Y, TRADING_NAME, ETL_CONTROL_ID, RLTR_ID, SERVICE_INFORMATION, trim(to_char(INVOICE_NUMBER,999999999999))||''|| rtrim(LTRIM(translate(CCY_UNIT_CODE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(LIBO_CODE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(TERR_ISO_CODE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(SOURCE_SYSTEM,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(CCY_EXCHANGE_RATE,9999999999.999999))||''|| trim(to_char(CURA_ID,9999999999))||''|| trim(to_char(INVO_INVOICE_NUMBER_ADJUSTED,999999999999))||''|| to_char(PAID_DT,'YYYY-MM-DD HH24:MI:SS')||''|| rtrim(LTRIM(translate(STATUS,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(INVOICE_TYPE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(AMOUNT,999999999999999999.9999))||''|| trim(to_char(INV_CCY_AMOUNT,999999999999999999.9999))||''|| trim(to_char(USGP_ID,9999999999))||''|| rtrim(LTRIM(translate(SETY_CODE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(CIF_INVOICE_NUMBER,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| to_char(CREATED_DTM,'YYYY-MM-DD HH24:MI:SS')||''|| trim(to_char(CREATED_BY_APUS_ID,9999999999))||''|| to_char(UPDATED_DTM,'YYYY-MM-DD HH24:MI:SS')||''|| trim(to_char(UPDATED_BY_APUS_ID,9999999999))||''|| rtrim(LTRIM(translate(LICENSEE_NUMBER,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(DN_AMOUNT,999999999999999999.9999))||''|| trim(to_char(DN_INV_CCY_AMOUNT,999999999999999999.9999))||''|| trim(to_char(DN_FIRST_AVAIL_DIST_ID,9999999999))||''|| rtrim(LTRIM(translate(PRTY_CODE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(INVF_FILE_NUMBER,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(COPIED_Y,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(ADJ_FROM_LICENSING_BODY,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(DN_GEMA_LICENSEE_NUMBER,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(RECEIVED_FILENAME,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(DN_STMT_USAGE_DESC,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| to_char(DN_DIPE_PERFORMANCE_START_DT,'YYYY-MM-DD HH24:MI:SS')||''|| to_char(DN_DIPE_PERFORMANCE_END_DT,'YYYY-MM-DD HH24:MI:SS')||''|| to_char(DED_RULE_EFFECTIVE_DT,'YYYY-MM-DD HH24:MI:SS')||''|| rtrim(LTRIM(translate(DN_CIIC_FILE_NAME,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(ON_BEHALF_OF_SOC_NBR,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(LABEL_CHANNEL,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(EXCLUDE_FROM_COPY_Y,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(TRADING_NAME,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(ETL_CONTROL_ID,9999999999999))||''|| trim(to_char(RLTR_ID,9999999999))||''|| rtrim(LTRIM(translate(SERVICE_INFORMATION,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0)) delim_row FROM DMOWN.INVOICES; <file_sep>/DB.DM/DPOWN/Dev Support/dm_extract_data_files_DM_INVOICES.SQL set serveroutput ON DECLARE l_source_batch_id varchar2(7) := '001'; l_row_cnt number; l_start_dtm date; l_end_dtm date; l_exec_time number; e_file_write_error EXCEPTION; PRAGMA EXCEPTION_INIT (e_file_write_error, -29285); PROCEDURE extract_data (p_view varchar2, p_source_batch_id varchar2, p_thread number) IS BEGIN l_start_dtm := SYSDATE; dpown.dm_extract_utility.extract_data_file(p_view, p_source_batch_id, p_thread, l_row_cnt); l_end_dtm := SYSDATE; l_exec_time := ROUND(24 * 60 * 60 * (l_end_dtm - l_start_dtm)); dbms_output.put_line(p_view ||'-'||p_thread||' - NO OF ROWS = '||l_row_cnt || ' - TIME taken '|| l_exec_time || ' secs'); EXCEPTION WHEN e_file_write_error THEN dbms_output.put_line(p_view||'-'||p_thread||' - FAILURE'); END extract_data; BEGIN extract_data('DM_INVOICES', l_source_batch_id, NULL); END; / <file_sep>/DB.DM/DPOWN/2. Views/Backload/DPOWN.DM_REPERTOIRE_POSTING_VW.sql CREATE OR REPLACE FORCE VIEW DM_REPERTOIRE_POSTING_VW AS SELECT REPERTOIRE_POSTING_ID, USAGE_GROUP_ID, CASHING_OUT_GROUP_ID, COPIED_REPERTOIRE_POSTING_ID, FILE_RECEIVED_DT, PERIOD_START_DT, PROCESS_STAGE, REPERTOIRE_CODE, BATCH_NBR, D_TOTAL_ACTUAL_AMT, D_TOTAL_POINTS, LOGICAL_DELETE_DT, PERIOD_END_DT, TOTAL_NUM_ROTRS, CPYR_CHECK_SHARE_STATUS, CPCO_CONTEXT_ID, USAGE_GROUP_SURR_ID, HELD_Y, MCPS_LAST_FREE_DATE, RIGHT_TYPE, DIBC_CONTEXT_ID, LINV_ID, ON_BEHALF_OF_SOC_NBR, ETL_CONTROL_ID, trim(to_char(REPERTOIRE_POSTING_ID,9999999999))||''|| trim(to_char(USAGE_GROUP_ID,9999999999))||''|| trim(to_char(CASHING_OUT_GROUP_ID,9999999999))||''|| trim(to_char(COPIED_REPERTOIRE_POSTING_ID,9999999999))||''|| to_char(FILE_RECEIVED_DT,'YYYY-MM-DD HH24:MI:SS')||''|| to_char(PERIOD_START_DT,'YYYY-MM-DD HH24:MI:SS')||''|| rtrim(LTRIM(translate(PROCESS_STAGE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(REPERTOIRE_CODE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(BATCH_NBR,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(D_TOTAL_ACTUAL_AMT,99999999999.99))||''|| trim(to_char(D_TOTAL_POINTS,999999999999999.999))||''|| to_char(LOGICAL_DELETE_DT,'YYYY-MM-DD HH24:MI:SS')||''|| to_char(PERIOD_END_DT,'YYYY-MM-DD HH24:MI:SS')||''|| trim(to_char(TOTAL_NUM_ROTRS))||''|| rtrim(LTRIM(translate(CPYR_CHECK_SHARE_STATUS,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(CPCO_CONTEXT_ID,999999999999))||''|| trim(to_char(USAGE_GROUP_SURR_ID,999999999999))||''|| rtrim(LTRIM(translate(HELD_Y,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| to_char(MCPS_LAST_FREE_DATE,'YYYY-MM-DD HH24:MI:SS')||''|| rtrim(LTRIM(translate(RIGHT_TYPE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(DIBC_CONTEXT_ID,999999999999))||''|| trim(to_char(LINV_ID,9999999999))||''|| rtrim(LTRIM(translate(ON_BEHALF_OF_SOC_NBR,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(ETL_CONTROL_ID,9999999999)) delim_row FROM DMOWN.REPERTOIRE_POSTING; <file_sep>/DB.DM/DPOWN/2. Views/Backload/DPOWN.DM_CURRENCY_VW.sql CREATE OR REPLACE FORCE VIEW DM_CURRENCY_VW AS SELECT CURRENCY_ID, COUNTRY, UNIT_DESCRIPTION, UNIT_CODE, MIN_PAYMENT_THRESHOLD_VALUE, trim(to_char(CURRENCY_ID,9999999999))||''|| rtrim(LTRIM(translate(COUNTRY,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(UNIT_DESCRIPTION,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(UNIT_CODE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(MIN_PAYMENT_THRESHOLD_VALUE,99999999999.99)) delim_row FROM DMOWN.CURRENCY; <file_sep>/DB.DM/DPOWN/2. Views/DPOWN.DM_PERFORMANCE_VW.sql CREATE OR REPLACE FORCE VIEW DM_PERFORMANCE_VW AS SELECT /*+ PARALLEL(perf,16) */ PERFORMANCE_ID, DIST_WORK_IN_REP_POST_ID, BROADCAST_REGION_ID, DURATION, INTERESTED_PARTY_1, INTERESTED_PARTY_2, INTERESTED_PARTY_3, INTERESTED_PARTY_4, PERFORMANCE_DT, PERFORMANCE_END_DT, PRODUCTION_HEADER, STATION_CODE, PS_OLD_PERFORMANCE_ID, USAGE_CLASSIFICATION, PRODUCTION_ID, EPISODE_TITLE, AUTO_CLAIM_FLG, PERFORMANCE_QTY, CATALOGUE_NUMBER, trim(to_char(PERFORMANCE_ID))||''|| trim(to_char(DIST_WORK_IN_REP_POST_ID,9999999999))||''|| trim(to_char(BROADCAST_REGION_ID,9999999999))||''|| trim(to_char(DURATION,999999999))||''|| rtrim(LTRIM(translate(INTERESTED_PARTY_1,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(INTERESTED_PARTY_2,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(INTERESTED_PARTY_3,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(INTERESTED_PARTY_4,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| to_char(PERFORMANCE_DT,'YYYY-MM-DD HH24:MI:SS')||''|| to_char(PERFORMANCE_END_DT,'YYYY-MM-DD HH24:MI:SS')||''|| rtrim(LTRIM(translate(PRODUCTION_HEADER,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(STATION_CODE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(PS_OLD_PERFORMANCE_ID))||''|| rtrim(LTRIM(translate(USAGE_CLASSIFICATION,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(PRODUCTION_ID,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(EPISODE_TITLE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(AUTO_CLAIM_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(PERFORMANCE_QTY,9999999999))||''|| rtrim(LTRIM(translate(CATALOGUE_NUMBER,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0)) delim_row FROM DMOWN.PERFORMANCE perf CROSS JOIN DPOWN.P2P_DM_EXTRACT_CONTROL exctl JOIN DMOWN.REPERTOIRE_POSTING repo ON (repo.REPERTOIRE_POSTING_ID = perf.DIST_WORK_IN_REP_POST_ID) WHERE exctl.EXTRACTED_TO_BI_Y IS NULL AND repo.FILE_RECEIVED_DT > exctl.EXTRACT_START_DTM; <file_sep>/DB.DM/DPOWN/2. Views/Backload/DPOWN.DM_USAGE_GROUP_CODA_ACCOUNT_VW.sql CREATE OR REPLACE FORCE VIEW DM_USAGE_GROUP_CODA_ACCOUNT_VW AS SELECT USGP_ID, ON_BEHALF_OF_SOC_NBR, UGCA_TYPE, COAC_ID, CREATED_DTM, CREATED_BY_APUS_ID, UPDATED_DTM, UPDATED_BY_APUS_ID, trim(to_char(USGP_ID,9999999999))||''|| rtrim(LTRIM(translate(ON_BEHALF_OF_SOC_NBR,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(UGCA_TYPE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(COAC_ID,9999999999))||''|| to_char(CREATED_DTM,'YYYY-MM-DD HH24:MI:SS')||''|| trim(to_char(CREATED_BY_APUS_ID,9999999999))||''|| to_char(UPDATED_DTM,'YYYY-MM-DD HH24:MI:SS')||''|| trim(to_char(UPDATED_BY_APUS_ID,9999999999)) delim_row FROM DMOWN.USAGE_GROUP_CODA_ACCOUNTS; <file_sep>/DB.DM/DPOWN/2. Views/Backload/DPOWN.DM_DEDUCTIONS_VW.sql CREATE OR REPLACE FORCE VIEW DM_DEDUCTIONS_VW AS SELECT /*+ PARALLEL(DEDU,16) */ ID, DETY_CODE, DITR_ID, AMOUNT, INV_CCY_AMOUNT, ROUNDING_APPORTIONMENT_Y, TAXABLE_AMOUNT, INV_CCY_TAXABLE_AMOUNT, DN_FULLY_PAID_AT_DIST_ID, DN_DISPENSABLE_DT, UPDATED_BY_APUS_ID, UPDATED_DTM, CREATED_BY_APUS_ID, CREATED_DTM, DN_DITR_MEMB_SUB_PARTITION_KEY AS THREAD_NO, DN_DITR_PAYMENT_SOC_NBR, DEDUCTION_RATE_PCT, trim(to_char(ID))||''|| rtrim(LTRIM(translate(DETY_CODE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(DITR_ID))||''|| trim(to_char(AMOUNT,999999999999999999.9999))||''|| trim(to_char(INV_CCY_AMOUNT,999999999999999999.9999))||''|| rtrim(LTRIM(translate(ROUNDING_APPORTIONMENT_Y,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(TAXABLE_AMOUNT,999999999999999999.9999))||''|| trim(to_char(INV_CCY_TAXABLE_AMOUNT,999999999999999999.9999))||''|| trim(to_char(DN_FULLY_PAID_AT_DIST_ID,9999999999))||''|| to_char(DN_DISPENSABLE_DT,'YYYY-MM-DD HH24:MI:SS')||''|| trim(to_char(UPDATED_BY_APUS_ID,9999999999))||''|| to_char(UPDATED_DTM,'YYYY-MM-DD HH24:MI:SS')||''|| trim(to_char(CREATED_BY_APUS_ID,9999999999))||''|| to_char(CREATED_DTM,'YYYY-MM-DD HH24:MI:SS')||''|| trim(to_char(DN_DITR_MEMB_SUB_PARTITION_KEY,9999))||''|| rtrim(LTRIM(translate(DN_DITR_PAYMENT_SOC_NBR,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(DEDUCTION_RATE_PCT,9999999.9999)) delim_row FROM DMOWN.DEDUCTIONS PARTITION (P_DEDU_044_CURR) DEDU WHERE DEDU.DN_DISPENSABLE_DT IS NULL UNION ALL SELECT /*+ PARALLEL(DEDU,16) */ ID, DETY_CODE, DITR_ID, AMOUNT, INV_CCY_AMOUNT, ROUNDING_APPORTIONMENT_Y, TAXABLE_AMOUNT, INV_CCY_TAXABLE_AMOUNT, DN_FULLY_PAID_AT_DIST_ID, DN_DISPENSABLE_DT, UPDATED_BY_APUS_ID, UPDATED_DTM, CREATED_BY_APUS_ID, CREATED_DTM, DN_DITR_MEMB_SUB_PARTITION_KEY AS THREAD_NO, DN_DITR_PAYMENT_SOC_NBR, DEDUCTION_RATE_PCT, trim(to_char(ID))||''|| rtrim(LTRIM(translate(DETY_CODE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(DITR_ID))||''|| trim(to_char(AMOUNT,999999999999999999.9999))||''|| trim(to_char(INV_CCY_AMOUNT,999999999999999999.9999))||''|| rtrim(LTRIM(translate(ROUNDING_APPORTIONMENT_Y,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(TAXABLE_AMOUNT,999999999999999999.9999))||''|| trim(to_char(INV_CCY_TAXABLE_AMOUNT,999999999999999999.9999))||''|| trim(to_char(DN_FULLY_PAID_AT_DIST_ID,9999999999))||''|| to_char(DN_DISPENSABLE_DT,'YYYY-MM-DD HH24:MI:SS')||''|| trim(to_char(UPDATED_BY_APUS_ID,9999999999))||''|| to_char(UPDATED_DTM,'YYYY-MM-DD HH24:MI:SS')||''|| trim(to_char(CREATED_BY_APUS_ID,9999999999))||''|| to_char(CREATED_DTM,'YYYY-MM-DD HH24:MI:SS')||''|| trim(to_char(DN_DITR_MEMB_SUB_PARTITION_KEY,9999))||''|| rtrim(LTRIM(translate(DN_DITR_PAYMENT_SOC_NBR,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(DEDUCTION_RATE_PCT,9999999.9999)) delim_row FROM DMOWN.DEDUCTIONS PARTITION (P_DEDU_052_CURR) DEDU WHERE DEDU.DN_DISPENSABLE_DT IS NULL <file_sep>/DB.DM/DPOWN/2. Views/Backload/DPOWN.DM_ADJUSTMENT_REASON_VW.sql CREATE OR REPLACE FORCE VIEW DM_ADJUSTMENT_REASON_VW AS SELECT ADJUSTMENT_REASON_ID, ADJUSTMENT_CODE, DESCRIPTION, RECORD_STATUS, INTERNAL_USE_ONLY_FLG, trim(to_char(ADJUSTMENT_REASON_ID,9999999999))||''|| rtrim(LTRIM(translate(ADJUSTMENT_CODE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(DESCRIPTION,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(RECORD_STATUS,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(INTERNAL_USE_ONLY_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0)) delim_row FROM DMOWN.ADJUSTMENT_REASON; <file_sep>/DB.DM/DPOWN/2. Views/Backload/DPOWN.DM_USAGE_GROUP_SUMM_VW.sql CREATE OR REPLACE FORCE VIEW DM_USAGE_GROUP_SUMM_VW AS SELECT USAGE_GROUP_SUMM_ID, DESCRIPTION, E_F_CATEGORY_CODE, RECORD_STATUS, USAGE_GROUP_SUMM_PRIORITY, trim(to_char(USAGE_GROUP_SUMM_ID,9999999999))||''|| rtrim(LTRIM(translate(DESCRIPTION,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(E_F_CATEGORY_CODE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(RECORD_STATUS,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(USAGE_GROUP_SUMM_PRIORITY,99)) delim_row FROM DMOWN.USAGE_GROUP_SUMM; <file_sep>/DB.DM/DPOWN/Dev Support/DPOWN.DIM_CONTRIBUTOR.sql DECLARE does_not_exist EXCEPTION; PRAGMA EXCEPTION_INIT (does_not_exist, -942); BEGIN EXECUTE IMMEDIATE 'DROP TABLE PRBI_AGG.DIM_CONTRIBUTOR'; EXCEPTION WHEN does_not_exist THEN NULL; END; / CREATE TABLE prbi_agg.dim_contributor (contributor_key number(12) NOT NULL, contributor_name varchar2(100 char) NOT NULL) TABLESPACE prbi_st_broad_bd_a; CREATE UNIQUE INDEX prbi_agg_dimc_pk ON prbi_agg.dim_contributor(contributor_key) TABLESPACE prbi_st_broad_bi_a; ALTER TABLE prbi_agg.dim_contributor ADD (CONSTRAINT prbi_agg_dimc_pk PRIMARY KEY (contributor_key)); INSERT INTO prbi_agg.dim_contributor (contributor_key, contributor_name) SELECT DISTINCT fuc.contributor_key, cont.NAME FROM prbi_agg.fact_usage_contributor fuc JOIN prbi_staging.contributors cont ON (fuc.contributor_key = cont.surr_id); COMMIT; <file_sep>/DB.DM/DPOWN/2. Views/DPOWN.DM_DEDUCTIONS_VW.sql CREATE OR REPLACE FORCE VIEW DM_DEDUCTIONS_VW AS SELECT /*+ PARALLEL(DEDU,16) */ ID, DETY_CODE, DITR_ID, AMOUNT, INV_CCY_AMOUNT, ROUNDING_APPORTIONMENT_Y, TAXABLE_AMOUNT, INV_CCY_TAXABLE_AMOUNT, DN_FULLY_PAID_AT_DIST_ID, DN_DISPENSABLE_DT, UPDATED_BY_APUS_ID, dedu.UPDATED_DTM, CREATED_BY_APUS_ID, dedu.CREATED_DTM, DN_DITR_MEMB_SUB_PARTITION_KEY AS THREAD_NO, DN_DITR_PAYMENT_SOC_NBR, DEDUCTION_RATE_PCT, trim(to_char(ID))||''|| rtrim(LTRIM(translate(DETY_CODE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(DITR_ID))||''|| trim(to_char(AMOUNT,999999999999999999.9999))||''|| trim(to_char(INV_CCY_AMOUNT,999999999999999999.9999))||''|| rtrim(LTRIM(translate(ROUNDING_APPORTIONMENT_Y,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(TAXABLE_AMOUNT,999999999999999999.9999))||''|| trim(to_char(INV_CCY_TAXABLE_AMOUNT,999999999999999999.9999))||''|| trim(to_char(DN_FULLY_PAID_AT_DIST_ID,9999999999))||''|| to_char(DN_DISPENSABLE_DT,'YYYY-MM-DD HH24:MI:SS')||''|| trim(to_char(UPDATED_BY_APUS_ID,9999999999))||''|| to_char(dedu.UPDATED_DTM,'YYYY-MM-DD HH24:MI:SS')||''|| trim(to_char(CREATED_BY_APUS_ID,9999999999))||''|| to_char(dedu.CREATED_DTM,'YYYY-MM-DD HH24:MI:SS')||''|| trim(to_char(DN_DITR_MEMB_SUB_PARTITION_KEY,9999))||''|| rtrim(LTRIM(translate(DN_DITR_PAYMENT_SOC_NBR,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(DEDUCTION_RATE_PCT,9999999.9999)) delim_row FROM DMOWN.DEDUCTIONS PARTITION (P_DEDU_044_CURR) DEDU CROSS JOIN DPOWN.P2P_DM_EXTRACT_CONTROL EXCTL WHERE EXCTL.EXTRACTED_TO_BI_Y IS NULL AND ((DEDU.CREATED_DTM > EXCTL.EXTRACT_START_DTM) OR (DEDU.UPDATED_DTM > EXCTL.EXTRACT_START_DTM)) UNION ALL SELECT /*+ PARALLEL(DEDU,16) */ ID, DETY_CODE, DITR_ID, AMOUNT, INV_CCY_AMOUNT, ROUNDING_APPORTIONMENT_Y, TAXABLE_AMOUNT, INV_CCY_TAXABLE_AMOUNT, DN_FULLY_PAID_AT_DIST_ID, DN_DISPENSABLE_DT, UPDATED_BY_APUS_ID, dedu.UPDATED_DTM, CREATED_BY_APUS_ID, dedu.CREATED_DTM, DN_DITR_MEMB_SUB_PARTITION_KEY AS THREAD_NO, DN_DITR_PAYMENT_SOC_NBR, DEDUCTION_RATE_PCT, trim(to_char(ID))||''|| rtrim(LTRIM(translate(DETY_CODE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(DITR_ID))||''|| trim(to_char(AMOUNT,999999999999999999.9999))||''|| trim(to_char(INV_CCY_AMOUNT,999999999999999999.9999))||''|| rtrim(LTRIM(translate(ROUNDING_APPORTIONMENT_Y,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(TAXABLE_AMOUNT,999999999999999999.9999))||''|| trim(to_char(INV_CCY_TAXABLE_AMOUNT,999999999999999999.9999))||''|| trim(to_char(DN_FULLY_PAID_AT_DIST_ID,9999999999))||''|| to_char(DN_DISPENSABLE_DT,'YYYY-MM-DD HH24:MI:SS')||''|| trim(to_char(UPDATED_BY_APUS_ID,9999999999))||''|| to_char(dedu.UPDATED_DTM,'YYYY-MM-DD HH24:MI:SS')||''|| trim(to_char(CREATED_BY_APUS_ID,9999999999))||''|| to_char(dedu.CREATED_DTM,'YYYY-MM-DD HH24:MI:SS')||''|| trim(to_char(DN_DITR_MEMB_SUB_PARTITION_KEY,9999))||''|| rtrim(LTRIM(translate(DN_DITR_PAYMENT_SOC_NBR,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(DEDUCTION_RATE_PCT,9999999.9999)) delim_row FROM DMOWN.DEDUCTIONS PARTITION (P_DEDU_052_CURR) DEDU CROSS JOIN DPOWN.P2P_DM_EXTRACT_CONTROL EXCTL WHERE EXCTL.EXTRACTED_TO_BI_Y IS NULL AND ((DEDU.CREATED_DTM > EXCTL.EXTRACT_START_DTM) OR (DEDU.UPDATED_DTM > EXCTL.EXTRACT_START_DTM)); <file_sep>/DB.DM/DPOWN/2. Views/Backload/DPOWN.DM_LICENSING_BODIES_VW.sql CREATE OR REPLACE FORCE VIEW DM_LICENSING_BODIES_VW AS SELECT CODE, NAME, CREATED_DTM, CREATED_BY_APUS_ID, UPDATED_DTM, UPDATED_BY_APUS_ID, TRANSACTIONAL_YN, rtrim(LTRIM(translate(CODE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(NAME,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| to_char(CREATED_DTM,'YYYY-MM-DD HH24:MI:SS')||''|| trim(to_char(CREATED_BY_APUS_ID,9999999999))||''|| to_char(UPDATED_DTM,'YYYY-MM-DD HH24:MI:SS')||''|| trim(to_char(UPDATED_BY_APUS_ID,9999999999))||''|| rtrim(LTRIM(translate(TRANSACTIONAL_YN,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0)) delim_row FROM DMOWN.LICENSING_BODIES; <file_sep>/DB.DM/DPOWN/5. Privileges/PRIVILEGES.SQL BEGIN FOR PRM IN (WITH user_allocation AS (SELECT 'DP_SQLSSIS' AS new_perm, 'EXECUTE' AS permission FROM dual) SELECT permission, new_perm, USER AS UDScheme, object_name AS table_name FROM all_objects CROSS JOIN user_allocation WHERE owner = USER AND object_type IN ('PACKAGE')) LOOP EXECUTE IMMEDIATE 'GRANT '|| PRM.permission ||' on ' || PRM.udScheme || '.' || PRM.table_name || ' TO '|| PRM.new_perm ||''; END LOOP; END; /<file_sep>/DB.DM/DPOWN/2. Views/Backload/DPOWN.DM_USAGE_GROUP_VW.sql CREATE OR REPLACE FORCE VIEW DM_USAGE_GROUP_VW AS SELECT USAGE_GROUP_ID, TO_DROP_CODA_ACCOUNT_ID, USAGE_GROUP_SUMM_ID, USAGE_GROUP_TYPE_ID, DESCRIPTION, EF_IND, MIN_CASHED_OUT_LINE_AMT, POA_FLG, RECORD_STATUS, SATELLITE_CABLE_FLG, SHOW_STATEMENT_DETAIL_FLG, SOURCE_DOCUMENT_FLG, TAXABLE_FLG, USAGE_GROUP_CODE, ADMIN_RATE_AMT, ADMIN_RATE_PCT, INSTEAD_OF, MASTER_USAGE_GROUP_ID, USAGE_GROUP_SUMM_REPORTS_ID, SOURCED_FROM_PRS_REP_Y, DN_UGS_DESCRIPTION, STMT_USING_INVOICE_DESC_Y, MCPS_COMMISSION_SET_CODE, MCPS_SOURCE_TYPE, trim(to_char(USAGE_GROUP_ID,9999999999))||''|| trim(to_char(TO_DROP_CODA_ACCOUNT_ID,9999999999))||''|| trim(to_char(USAGE_GROUP_SUMM_ID,9999999999))||''|| trim(to_char(USAGE_GROUP_TYPE_ID,9999999999))||''|| rtrim(LTRIM(translate(DESCRIPTION,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(EF_IND,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(MIN_CASHED_OUT_LINE_AMT,99999999999.99))||''|| rtrim(LTRIM(translate(POA_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(RECORD_STATUS,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(SATELLITE_CABLE_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(SHOW_STATEMENT_DETAIL_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(SOURCE_DOCUMENT_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(TAXABLE_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(USAGE_GROUP_CODE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(ADMIN_RATE_AMT,99999999999.99))||''|| trim(to_char(ADMIN_RATE_PCT,99999.99))||''|| rtrim(LTRIM(translate(INSTEAD_OF,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(MASTER_USAGE_GROUP_ID,9999999999))||''|| trim(to_char(USAGE_GROUP_SUMM_REPORTS_ID,9999999999))||''|| rtrim(LTRIM(translate(SOURCED_FROM_PRS_REP_Y,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(DN_UGS_DESCRIPTION,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(STMT_USING_INVOICE_DESC_Y,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(MCPS_COMMISSION_SET_CODE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(MCPS_SOURCE_TYPE,999)) delim_row FROM DMOWN.USAGE_GROUP; <file_sep>/DB.DM/DPOWN/2. Views/Backload/DPOWN.DM_DISTRIBUTION_VW.sql CREATE OR REPLACE FORCE VIEW DM_DISTRIBUTION_VW AS SELECT DISTRIBUTION_ID, DISTRIBUTION_TYPE_ID, CREATED_BY_USER_ID, LAST_UPDATED_BY_USER_ID, CREATED_DT, DISTRIBUTION_CODE, PROCESS_STAGE, START_DT, ARCHIVE_FLG, END_DT, LAST_UPDATED_DT, LEGACY_DISTRIBUTION_CODE, TAX_POINT_DT, PS_MDS_PROC_COMPLETE_FLG, PS_LEL_PROC_COMPLETE_FLG, PS_MIT_PROC_COMPLETE_FLG, PS_AST_PROC_COMPLETE_FLG, PS_CVT_PROC_COMPLETE_FLG, PS_PRP_PROC_COMPLETE_FLG, PS_CGS_PROC_COMPLETE_FLG, PS_CLL_PROC_COMPLETE_FLG, PS_CPL_PROC_COMPLETE_FLG, PS_STM_PROC_COMPLETE_FLG, PS_GLD_PROC_COMPLETE_FLG, PS_INT_PROC_COMPLETE_FLG, PS_STM_FILE_COMPLETE_FLG, PS_MDS_PROGRESS_FLG, PS_STM_PROGRESS_FLG, EFFECTIVE_DT, PROCESS_LIFELINES_IN_MINI_YN, PS_PEL_PROGRESS_FLG, DISTCNT_BACO_ID, PS_START_DTM, PS_END_DTM, PEL_PARTITION_KEYS_SET_Y, PRE_STATEMENT_BACKUP_YN, PS_FINREC_PROGRESS_FLG, ROTR_PARTITION_KEYS_SET_Y, EXPORT_WIDS_TO_ICE_Y, trim(to_char(DISTRIBUTION_ID,9999999999))||''|| trim(to_char(DISTRIBUTION_TYPE_ID,9999999999))||''|| trim(to_char(CREATED_BY_USER_ID,9999999999))||''|| trim(to_char(LAST_UPDATED_BY_USER_ID,9999999999))||''|| to_char(CREATED_DT,'YYYY-MM-DD HH24:MI:SS')||''|| rtrim(LTRIM(translate(DISTRIBUTION_CODE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(PROCESS_STAGE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| to_char(START_DT,'YYYY-MM-DD HH24:MI:SS')||''|| rtrim(LTRIM(translate(ARCHIVE_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| to_char(END_DT,'YYYY-MM-DD HH24:MI:SS')||''|| to_char(LAST_UPDATED_DT,'YYYY-MM-DD HH24:MI:SS')||''|| rtrim(LTRIM(translate(LEGACY_DISTRIBUTION_CODE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| to_char(TAX_POINT_DT,'YYYY-MM-DD HH24:MI:SS')||''|| rtrim(LTRIM(translate(PS_MDS_PROC_COMPLETE_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(PS_LEL_PROC_COMPLETE_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(PS_MIT_PROC_COMPLETE_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(PS_AST_PROC_COMPLETE_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(PS_CVT_PROC_COMPLETE_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(PS_PRP_PROC_COMPLETE_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(PS_CGS_PROC_COMPLETE_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(PS_CLL_PROC_COMPLETE_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(PS_CPL_PROC_COMPLETE_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(PS_STM_PROC_COMPLETE_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(PS_GLD_PROC_COMPLETE_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(PS_INT_PROC_COMPLETE_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(PS_STM_FILE_COMPLETE_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(PS_MDS_PROGRESS_FLG))||''|| trim(to_char(PS_STM_PROGRESS_FLG))||''|| to_char(EFFECTIVE_DT,'YYYY-MM-DD HH24:MI:SS')||''|| rtrim(LTRIM(translate(PROCESS_LIFELINES_IN_MINI_YN,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(PS_PEL_PROGRESS_FLG))||''|| trim(to_char(DISTCNT_BACO_ID,9999999999))||''|| to_char(PS_START_DTM,'YYYY-MM-DD HH24:MI:SS')||''|| to_char(PS_END_DTM,'YYYY-MM-DD HH24:MI:SS')||''|| rtrim(LTRIM(translate(PEL_PARTITION_KEYS_SET_Y,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(PRE_STATEMENT_BACKUP_YN,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(PS_FINREC_PROGRESS_FLG))||''|| rtrim(LTRIM(translate(ROTR_PARTITION_KEYS_SET_Y,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(EXPORT_WIDS_TO_ICE_Y,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0)) delim_row FROM DMOWN.DISTRIBUTION; <file_sep>/DB.DM/DPOWN/2. Views/Backload/DPOWN.DM_P2P_DM_EXTRACT_CONTROL_VW.sql CREATE OR REPLACE FORCE VIEW DM_P2P_DM_EXTRACT_CONTROL_VW AS SELECT EXTRACT_ID, CREATED_DTM, UPDATED_DTM, EXTRACT_START_DTM, EXTRACT_END_DTM, EXTRACTED_TO_BI_Y, trim(to_char(EXTRACT_ID,999999999999))||''|| to_char(CREATED_DTM,'YYYY-MM-DD HH24:MI:SS')||''|| to_char(UPDATED_DTM,'YYYY-MM-DD HH24:MI:SS')||''|| to_char(EXTRACT_START_DTM,'YYYY-MM-DD HH24:MI:SS')||''|| to_char(EXTRACT_END_DTM,'YYYY-MM-DD HH24:MI:SS')||''|| rtrim(LTRIM(translate(EXTRACTED_TO_BI_Y,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0)) delim_row FROM DPOWN.P2P_DM_EXTRACT_CONTROL; <file_sep>/DB.DM/DPOWN/2. Views/Backload/DPOWN.DM_REP_REQUEST_HIST_PLIST_VW.sql CREATE OR REPLACE FORCE VIEW DM_REP_REQUEST_HIST_PLIST_VW AS SELECT ID, REP_REQUEST_HIST_ID, CHAR_VALUE, NUMERIC_VALUE, trim(to_char(ID,9999999999))||''|| trim(to_char(REP_REQUEST_HIST_ID))||''|| rtrim(LTRIM(translate(CHAR_VALUE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(NUMERIC_VALUE)) delim_row FROM DMOWN.REP_REQUEST_HIST_PLIST; <file_sep>/DB.DM/DMOWN/5. Privileges/PRIVILEGES.sql -- PRE-DISTRIBUTION GRANT SELECT ON DMOWN.ADJUSTMENT_REASON TO DPOWN WITH GRANT OPTION; GRANT SELECT ON DMOWN.BROADCAST_REGION TO DPOWN WITH GRANT OPTION; GRANT SELECT ON DMOWN.CAE TO DPOWN WITH GRANT OPTION; GRANT SELECT ON DMOWN.CASHING_OUT_GROUP TO DPOWN WITH GRANT OPTION; GRANT SELECT ON MEMOWN.COUNTRY TO DPOWN WITH GRANT OPTION; GRANT SELECT ON DMOWN.CURRENCY TO DPOWN WITH GRANT OPTION; GRANT SELECT ON DMOWN.DEDUCTIONS TO DPOWN WITH GRANT OPTION; GRANT SELECT ON DMOWN.DEDUCTION_TYPES TO DPOWN WITH GRANT OPTION; GRANT SELECT ON DMOWN.DIGITAL_TRANSACTIONS TO DPOWN WITH GRANT OPTION; GRANT SELECT ON DMOWN.DIGITAL_PERFORMANCES TO DPOWN WITH GRANT OPTION; GRANT SELECT ON DMOWN.DISTRIBUTED_WORK TO DPOWN WITH GRANT OPTION; GRANT SELECT ON DMOWN.DISTRIBUTION TO DPOWN WITH GRANT OPTION; GRANT SELECT ON DMOWN.DISTRIBUTION_TYPE TO DPOWN WITH GRANT OPTION; GRANT SELECT ON DMOWN.INVOICES TO DPOWN WITH GRANT OPTION; GRANT SELECT ON DMOWN.INVOICES_AUD TO DPOWN WITH GRANT OPTION; GRANT SELECT ON DMOWN.INVOICE_LEGAL_EARNER_LINES TO DPOWN WITH GRANT OPTION; GRANT SELECT ON DMOWN.LICENSING_BODIES TO DPOWN WITH GRANT OPTION; GRANT SELECT ON DMOWN.MEMBER_DISTRIBUTION_SUMM TO DPOWN WITH GRANT OPTION; GRANT SELECT ON MEMOWN.MEMBERSHIP TO DPOWN WITH GRANT OPTION; GRANT SELECT ON DMOWN.MEMBERSHIP_TYPE TO DPOWN WITH GRANT OPTION; GRANT SELECT ON DMOWN.PERFORMANCE TO DPOWN WITH GRANT OPTION; GRANT SELECT ON DMOWN.PRODUCT_TYPES TO DPOWN WITH GRANT OPTION; GRANT SELECT ON DMOWN.PS_MEMBERS_IN_DIST TO DPOWN WITH GRANT OPTION; GRANT SELECT ON DMOWN.REPERTOIRE_POSTING TO DPOWN WITH GRANT OPTION; GRANT SELECT ON DMOWN.ROYALTY_LINE_TRANSFER TO DPOWN WITH GRANT OPTION; GRANT SELECT ON DMOWN.ROYALTY_TRANSACTION TO DPOWN WITH GRANT OPTION; GRANT SELECT ON DMOWN.SERVICE_TYPES TO DPOWN WITH GRANT OPTION; GRANT SELECT ON DMOWN.SOCIETY TO DPOWN WITH GRANT OPTION; GRANT SELECT ON DMOWN.USAGE_CATEGORIES TO DPOWN WITH GRANT OPTION; GRANT SELECT ON DMOWN.USAGE_GROUP TO DPOWN WITH GRANT OPTION; GRANT SELECT ON DMOWN.USAGE_GROUP_SUMM TO DPOWN WITH GRANT OPTION; GRANT SELECT ON DMOWN.USAGE_GROUP_TYPE TO DPOWN WITH GRANT OPTION; -- CODA GRANT SELECT ON DMOWN.CASHING_OUT_GROUP TO DPOWN WITH GRANT OPTION; GRANT SELECT ON DMOWN.DISTRIBUTION TO DPOWN WITH GRANT OPTION; GRANT SELECT ON DMOWN.CASHING_OUT_HISTORY TO DPOWN WITH GRANT OPTION; GRANT SELECT ON DMOWN.REPERTOIRE_POSTING TO DPOWN WITH GRANT OPTION; GRANT SELECT ON DMOWN.COPY_CASH_DETAILS TO DPOWN WITH GRANT OPTION; GRANT SELECT ON DMOWN.USAGE_GROUP TO DPOWN WITH GRANT OPTION; GRANT SELECT ON DMOWN.USAGE_GROUP_CODA_ACCOUNTS TO DPOWN WITH GRANT OPTION; GRANT SELECT ON DMOWN.REP_REQUEST_HIST_PLIST TO DPOWN WITH GRANT OPTION; GRANT SELECT ON DMOWN.CODA_ACCOUNT TO DPOWN WITH GRANT OPTION; GRANT SELECT ON DMOWN.DISTRIBUTION_TYPE TO DPOWN WITH GRANT OPTION; GRANT SELECT ON DMOWN.DISTRIBUTED_WORK TO DPOWN WITH GRANT OPTION; <file_sep>/DB.DM/DPOWN/2. Views/Backload/DPOWN.DM_SOCIETY_VW.sql CREATE OR REPLACE FORCE VIEW DM_SOCIETY_VW AS SELECT SOCIETY_ID, NEW_SOCIETY_FLG, SOCIETY_ACRONYM, SOCIETY_NAME, SOCIETY_NBR, EXTRACT_DT, STATUS_FLG, DANDM_SOURCE_SOCIETY_Y, PROCESSING_TX_ON_BEHALF_OF_Y, DANDM_SOURCE_DISPLAY_SEQUENCE, trim(to_char(SOCIETY_ID,9999999999))||''|| rtrim(LTRIM(translate(NEW_SOCIETY_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(SOCIETY_ACRONYM,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(SOCIETY_NAME,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(SOCIETY_NBR,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| to_char(EXTRACT_DT,'YYYY-MM-DD HH24:MI:SS')||''|| rtrim(LTRIM(translate(STATUS_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(DANDM_SOURCE_SOCIETY_Y,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(PROCESSING_TX_ON_BEHALF_OF_Y,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(DANDM_SOURCE_DISPLAY_SEQUENCE,99)) delim_row FROM DMOWN.SOCIETY; <file_sep>/DB.DM/DPOWN/2. Views/Backload/DPOWN.DM_DEDUCTION_TYPES_VW.sql CREATE OR REPLACE FORCE VIEW DM_DEDUCTION_TYPES_VW AS SELECT CODE, NAME, DETY_TYPE, APPORTIONMENT_SOURCE, DERIVE_FROM_GROSS_OR_NET, INCURS_VAT_YN, TAXABLE_YN, CREATED_DTM, CREATED_BY_APUS_ID, UPDATED_DTM, UPDATED_BY_APUS_ID, DISPLAY_SEQ, BLANKET_ONLY_Y, VATABLE_YN, rtrim(LTRIM(translate(CODE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(NAME,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(DETY_TYPE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(APPORTIONMENT_SOURCE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(DERIVE_FROM_GROSS_OR_NET,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(INCURS_VAT_YN,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(TAXABLE_YN,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| to_char(CREATED_DTM,'YYYY-MM-DD HH24:MI:SS')||''|| trim(to_char(CREATED_BY_APUS_ID,9999999999))||''|| to_char(UPDATED_DTM,'YYYY-MM-DD HH24:MI:SS')||''|| trim(to_char(UPDATED_BY_APUS_ID,9999999999))||''|| trim(to_char(DISPLAY_SEQ,99))||''|| rtrim(LTRIM(translate(BLANKET_ONLY_Y,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(VATABLE_YN,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0)) delim_row FROM DMOWN.DEDUCTION_TYPES; <file_sep>/DB.DM/DPOWN/2. Views/Backload/DPOWN.DM_DISTRIBUTED_WORK_VW.sql CREATE OR REPLACE FORCE VIEW DM_DISTRIBUTED_WORK_VW AS SELECT DISTRIBUTED_WORK_ID, WORK_TITLE, WID, ISWC, TUNECODE, ICE_WORK_KEY, trim(to_char(DISTRIBUTED_WORK_ID,9999999999))||''|| rtrim(LTRIM(translate(WORK_TITLE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(WID,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(ISWC,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(TUNECODE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(ICE_WORK_KEY,99999999999)) delim_row FROM DMOWN.DISTRIBUTED_WORK; <file_sep>/DB.DM/DPOWN/2. Views/Backload/DPOWN.DM_COPY_CASH_DETAILS_VW.sql CREATE OR REPLACE FORCE VIEW DM_COPY_CASH_DETAILS_VW AS SELECT COCA_ID, CREATED_BY, CREATED_DTM, PENDING_BY, PENDING_DTM, PROCESSED_BY, PROCESSED_DTM, PROCESS_STAGE, COPY_POST_YN, ROLLUP_TRANSACTIONS_YN, CASH_OUT_YN, CASHING_OUT_GROUP_TYPE_ID, FIXED_POINT_VALUE, GROSS_DISTRIBUTABLE_AMT, RESERVE_AMT, LEDGER_BALANCE_AMT, ADDITIONAL_REVENUE_AMT, SUB_PUBLISHER_DEDUCTION_AMT, BATCH_CONTROL_ID, CASHING_OUT_GROUP_ID, CASHING_OUT_HISTORY_ID, FIXED_POINT_RECON_YN, RECONCILIATION_TYPE, FORECAST_REPORT_DTM, EXCLUDE_DURATIONS_FLG, FORECAST_ADJUSTMENT_VALUE, PRODUCTION_HEADER, CP_EXCLUDE_SHARE_CHECK_Y, RIGHT_TYPE, ON_BEHALF_OF_SOC_NBR, trim(to_char(COCA_ID))||''|| trim(to_char(CREATED_BY))||''|| to_char(CREATED_DTM,'YYYY-MM-DD HH24:MI:SS')||''|| trim(to_char(PENDING_BY))||''|| to_char(PENDING_DTM,'YYYY-MM-DD HH24:MI:SS')||''|| trim(to_char(PROCESSED_BY))||''|| to_char(PROCESSED_DTM,'YYYY-MM-DD HH24:MI:SS')||''|| rtrim(LTRIM(translate(PROCESS_STAGE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(COPY_POST_YN,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(ROLLUP_TRANSACTIONS_YN,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(CASH_OUT_YN,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(CASHING_OUT_GROUP_TYPE_ID,9999999999))||''|| trim(to_char(FIXED_POINT_VALUE,9999999999999.9999))||''|| trim(to_char(GROSS_DISTRIBUTABLE_AMT,99999999999.99))||''|| trim(to_char(RESERVE_AMT,99999999999.99))||''|| trim(to_char(LEDGER_BALANCE_AMT,99999999999.99))||''|| trim(to_char(ADDITIONAL_REVENUE_AMT,99999999999.99))||''|| trim(to_char(SUB_PUBLISHER_DEDUCTION_AMT,99999999999.99))||''|| trim(to_char(BATCH_CONTROL_ID,9999999999))||''|| trim(to_char(CASHING_OUT_GROUP_ID,9999999999))||''|| trim(to_char(CASHING_OUT_HISTORY_ID,9999999999))||''|| rtrim(LTRIM(translate(FIXED_POINT_RECON_YN,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(RECONCILIATION_TYPE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| to_char(FORECAST_REPORT_DTM,'YYYY-MM-DD HH24:MI:SS')||''|| rtrim(LTRIM(translate(EXCLUDE_DURATIONS_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(FORECAST_ADJUSTMENT_VALUE,99999999999.99))||''|| rtrim(LTRIM(translate(PRODUCTION_HEADER,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(CP_EXCLUDE_SHARE_CHECK_Y,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(RIGHT_TYPE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(ON_BEHALF_OF_SOC_NBR,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0)) delim_row FROM DMOWN.COPY_CASH_DETAILS; <file_sep>/DB.DM/DPOWN/2. Views/Backload/DPOWN.DM_DIGITAL_PERFORMANCES_VW.sql CREATE OR REPLACE FORCE VIEW DM_DIGITAL_PERFORMANCES_VW AS SELECT /*+ PARALLEL(dipe,16) */ ID, INVO_INVOICE_NUMBER, DIWO_DISTRIBUTED_WORK_ID, INTERESTED_PARTY_1, INTERESTED_PARTY_2, INTERESTED_PARTY_3, INTERESTED_PARTY_4, ALBUM_TITLE, RELEASE_DT, ARTIST_NAME, FOREIGN_WORK_IDENTIFIER, NUMBER_OF_TRACKS, PERFORMANCE_DT, PERFORMANCE_QUANTITY, USCA_CODE, ISRC, CATALOGUE_NUMBER, DN_DISPENSABLE_DT, CREATED_DTM, CREATED_BY_APUS_ID, UPDATED_DTM, UPDATED_BY_APUS_ID, ICE_WORK_STATUS, PUBLISHER_SONG_CODE, UDWO_ID, PERFORMANCE_END_DT, trim(to_char(ID))||''|| trim(to_char(INVO_INVOICE_NUMBER,999999999999))||''|| trim(to_char(DIWO_DISTRIBUTED_WORK_ID,9999999999))||''|| rtrim(LTRIM(translate(INTERESTED_PARTY_1,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(INTERESTED_PARTY_2,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(INTERESTED_PARTY_3,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(INTERESTED_PARTY_4,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(ALBUM_TITLE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| to_char(RELEASE_DT,'YYYY-MM-DD HH24:MI:SS')||''|| rtrim(LTRIM(translate(ARTIST_NAME,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(FOREIGN_WORK_IDENTIFIER,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(NUMBER_OF_TRACKS,999999))||''|| to_char(PERFORMANCE_DT,'YYYY-MM-DD HH24:MI:SS')||''|| trim(to_char(PERFORMANCE_QUANTITY,9999999999))||''|| rtrim(LTRIM(translate(USCA_CODE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(ISRC,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(CATALOGUE_NUMBER,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| to_char(DN_DISPENSABLE_DT,'YYYY-MM-DD HH24:MI:SS')||''|| to_char(CREATED_DTM,'YYYY-MM-DD HH24:MI:SS')||''|| trim(to_char(CREATED_BY_APUS_ID,9999999999))||''|| to_char(UPDATED_DTM,'YYYY-MM-DD HH24:MI:SS')||''|| trim(to_char(UPDATED_BY_APUS_ID,9999999999))||''|| trim(to_char(ICE_WORK_STATUS,99))||''|| rtrim(LTRIM(translate(PUBLISHER_SONG_CODE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(UDWO_ID,9999999999))||''|| to_char(PERFORMANCE_END_DT,'YYYY-MM-DD HH24:MI:SS') delim_row FROM DMOWN.DIGITAL_PERFORMANCES PARTITION (P_DIPE_CURR) dipe WHERE dipe.DN_DISPENSABLE_DT is null; <file_sep>/DB.DM/DPOWN/Testing/dm_extract_load_ddl.sql SET SERVEROUTPUT ON BEGIN DPOWN.dm_extract_load_ddl.gen_source_view (p_source_schema => 'DMOWN', p_table_name => 'INVOICES', p_view_schema => 'DPOWN'); DPOWN.dm_extract_load_ddl.gen_ext_datasrc_ddl (p_source_schema => 'DMOWN', p_table_name => 'INVOICES'); DPOWN.dm_extract_load_ddl.gen_ext_tab_ddl (p_source_schema => 'DMOWN', p_table_name => 'INVOICES', p_exttbl_schema => 'Staging'); DPOWN.dm_extract_load_ddl.gen_stg_pkg_ddl (p_source_schema => 'DMOWN', p_table_name => 'INVOICES', p_stgpkg_schema => 'Staging'); DPOWN.dm_extract_load_ddl.gen_cln_pkg_ddl (p_source_schema => 'DMOWN', p_table_name => 'INVOICES', p_clnpkg_schema => 'Clean'); END; / <file_sep>/DB.DM/DMOWN/1. Tables/DMOWN.ROYALTY_TRANSACTION.ADD_BI_AUDIT.sql PROMPT ALTER TABLE DMOWN.ROYALTY_TRANSACTION ADD BI AUDIT COLUMNS ALTER TABLE DMOWN.ROYALTY_TRANSACTION ADD ( BI_AUDIT_CREATED_ID NUMBER(12) NULL, BI_AUDIT_UPDATED_ID NUMBER(12) NULL ); <file_sep>/DB.DM/DPOWN/Dev Support/dp_sqlssis.extract_data.sql SET SERVEROUTPUT ON DECLARE PROCEDURE extract_data (p_table_name VARCHAR2, p_thread NUMBER) IS l_row_cnt NUMBER; l_start_dtm DATE; l_end_dtm DATE; l_exec_time NUMBER; BEGIN l_start_dtm := SYSDATE; p2p_extract_utility.extract_data_file(p_table_name => p_table_name, p_source_batch_id => '0', p_thread => p_thread, p_rows_extracted => l_row_cnt); l_end_dtm := SYSDATE; --l_exec_time := ROUND(24 * 60 * 60 * (l_end_dtm - l_start_dtm)); --dbms_output.put_line(p_table_name ||' - No of rows = '||l_row_cnt || ' - Time taken '|| l_exec_time || ' secs'); dbms_output.put_line(p_table_name ||' - No of rows = '||l_row_cnt); END extract_data; BEGIN --extract_data('DIM_BROADCASTER' , NULL); --extract_data('DIM_FILE' , NULL); --extract_data('DIM_MUSIC_ORIGIN' , NULL); --extract_data('DIM_PRODUCTION' , NULL); --extract_data('DIM_THIRD_PARTY_TREE' , NULL); --extract_data('DIM_TRANSMISSION_STATUS' , NULL); --extract_data('DIM_USAGE_DISTRIBUTION_CODE', NULL); --extract_data('DIM_USAGE_OF_WORK_STATUS' , NULL); --extract_data('DIM_WORK' , NULL); --extract_data('FACT_USAGE_OF_WORK_WL' , NULL); --extract_data('FACT_USAGE_OF_WORK_PL' , 12); extract_data('FACT_WORK_OWNERSHIP_IP', NULL); END; / /* DIM_BROADCASTER - No of rows = 1902 - Time taken 0 secs DIM_FILE - No of rows = 498540 - Time taken 19 secs DIM_MUSIC_ORIGIN - No of rows = 129 - Time taken 1 secs DIM_PRODUCTION - No of rows = 1662516 - Time taken 115 secs DIM_THIRD_PARTY_TREE - No of rows = 2938 - Time taken 1 secs DIM_TRANSMISSION_STATUS - No of rows = 33 - Time taken 0 secs DIM_USAGE_DISTRIBUTION_CODE - No of rows = 6687 - Time taken 0 secs DIM_USAGE_OF_WORK_STATUS - No of rows = 311 - Time taken 0 secs DIM_WORK - No of rows = 2953015 - Time taken 171 secs FACT_USAGE_OF_WORK 1 - No of rows = 3031042 - Time taken 308 secs FACT_USAGE_OF_WORK 2 - No of rows = 2793230 - Time taken 668 secs FACT_USAGE_OF_WORK 3 - No of rows = 5470275 - Time taken 1327 secs FACT_USAGE_OF_WORK 4 - No of rows = 3444082 - Time taken 937 secs FACT_USAGE_OF_WORK 5 - No of rows = 3371415 - Time taken 960 secs FACT_USAGE_OF_WORK 6 - No of rows = 6263142 - Time taken 1459 secs FACT_USAGE_OF_WORK 7 - No of rows = 4144627 - Time taken 1221 secs FACT_USAGE_OF_WORK 8 - No of rows = 4233422 - Time taken 1240 secs FACT_USAGE_OF_WORK 9 - No of rows = 14692993 - Time taken 2459 secs FACT_USAGE_OF_WORK 10 - No of rows = 5097757 - Time taken 1321 secs FACT_USAGE_OF_WORK 11 - No of rows = 2538080 - Time taken 886 secs FACT_USAGE_OF_WORK 12 - No of rows = 5426801 - Time taken 1343 secs */<file_sep>/DB.DM/DPOWN/2. Views/Backload/DPOWN.DM_DISTRIBUTION_TYPE_VW.sql CREATE OR REPLACE FORCE VIEW DM_DISTRIBUTION_TYPE_VW AS SELECT DISTRIBUTION_TYPE_ID, DESCRIPTION, RECORD_STATUS, trim(to_char(DISTRIBUTION_TYPE_ID,9999999999))||''|| rtrim(LTRIM(translate(DESCRIPTION,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(RECORD_STATUS,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0)) delim_row FROM DMOWN.DISTRIBUTION_TYPE; <file_sep>/DB.DM/DPOWN/2. Views/Backload/DPOWN.DM_INVOICE_LEGAL_EARNER_LIN_VW.sql CREATE OR REPLACE FORCE VIEW DM_INVOICE_LEGAL_EARNER_LIN_VW AS SELECT /*+ PARALLEL(ilel,16) */ ID, ILEL_TYPE, IRHG_INVO_INVOICE_NUMBER, IRHG_RIHG_CODE, IRHG_RIGHT_TYPE, AMOUNT, INV_CCY_AMOUNT, STATUS, TAXABLE_AMOUNT, INV_CCY_TAXABLE_AMOUNT, MEMB_ID, STATEMENT_RUN_ID, DN_FULL_DP_INV_CCY_AMOUNT, INCLUDES_ROUNDING_Y, DN_DITR_MEMB_ID, DN_FULLY_PAID_AT_DIST_ID, DN_FIRST_PRESENTED_AT_DIST_ID, DN_DIST_ID_LE_PAID_AT, DN_DISPENSABLE_DT, ilel.UPDATED_DTM, UPDATED_BY_APUS_ID, ilel.CREATED_DTM, CREATED_BY_APUS_ID, DN_DITR_MEMB_SUB_PARTITION_KEY, PAYMENT_SOC_NBR, VATABLE_AMOUNT, INV_CCY_VATABLE_AMOUNT, trim(to_char(ID,9999999999))||''|| rtrim(LTRIM(translate(ILEL_TYPE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(IRHG_INVO_INVOICE_NUMBER,999999999999))||''|| rtrim(LTRIM(translate(IRHG_RIHG_CODE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(IRHG_RIGHT_TYPE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(AMOUNT,999999999999999999.9999))||''|| trim(to_char(INV_CCY_AMOUNT,999999999999999999.9999))||''|| rtrim(LTRIM(translate(STATUS,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(TAXABLE_AMOUNT,999999999999999999.9999))||''|| trim(to_char(INV_CCY_TAXABLE_AMOUNT,999999999999999999.9999))||''|| trim(to_char(MEMB_ID,9999999999))||''|| trim(to_char(STATEMENT_RUN_ID,9999999999))||''|| trim(to_char(DN_FULL_DP_INV_CCY_AMOUNT))||''|| rtrim(LTRIM(translate(INCLUDES_ROUNDING_Y,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(DN_DITR_MEMB_ID,9999999999))||''|| trim(to_char(DN_FULLY_PAID_AT_DIST_ID,9999999999))||''|| trim(to_char(DN_FIRST_PRESENTED_AT_DIST_ID,9999999999))||''|| trim(to_char(DN_DIST_ID_LE_PAID_AT,9999999999))||''|| to_char(DN_DISPENSABLE_DT,'YYYY-MM-DD HH24:MI:SS')||''|| to_char(ilel.UPDATED_DTM,'YYYY-MM-DD HH24:MI:SS')||''|| trim(to_char(UPDATED_BY_APUS_ID,9999999999))||''|| to_char(ilel.CREATED_DTM,'YYYY-MM-DD HH24:MI:SS')||''|| trim(to_char(CREATED_BY_APUS_ID,9999999999))||''|| trim(to_char(DN_DITR_MEMB_SUB_PARTITION_KEY,9999))||''|| rtrim(LTRIM(translate(PAYMENT_SOC_NBR,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(VATABLE_AMOUNT,999999999999999999.9999))||''|| trim(to_char(INV_CCY_VATABLE_AMOUNT,999999999999999999.9999)) delim_row FROM DMOWN.INVOICE_LEGAL_EARNER_LINES PARTITION (P_ILEL_044_CURR) ilel WHERE ilel.DN_DISPENSABLE_DT IS NULL UNION ALL SELECT /*+ PARALLEL(ilel,16) */ ID, ILEL_TYPE, IRHG_INVO_INVOICE_NUMBER, IRHG_RIHG_CODE, IRHG_RIGHT_TYPE, AMOUNT, INV_CCY_AMOUNT, STATUS, TAXABLE_AMOUNT, INV_CCY_TAXABLE_AMOUNT, MEMB_ID, STATEMENT_RUN_ID, DN_FULL_DP_INV_CCY_AMOUNT, INCLUDES_ROUNDING_Y, DN_DITR_MEMB_ID, DN_FULLY_PAID_AT_DIST_ID, DN_FIRST_PRESENTED_AT_DIST_ID, DN_DIST_ID_LE_PAID_AT, DN_DISPENSABLE_DT, ilel.UPDATED_DTM, UPDATED_BY_APUS_ID, ilel.CREATED_DTM, CREATED_BY_APUS_ID, DN_DITR_MEMB_SUB_PARTITION_KEY, PAYMENT_SOC_NBR, VATABLE_AMOUNT, INV_CCY_VATABLE_AMOUNT, trim(to_char(ID,9999999999))||''|| rtrim(LTRIM(translate(ILEL_TYPE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(IRHG_INVO_INVOICE_NUMBER,999999999999))||''|| rtrim(LTRIM(translate(IRHG_RIHG_CODE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(IRHG_RIGHT_TYPE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(AMOUNT,999999999999999999.9999))||''|| trim(to_char(INV_CCY_AMOUNT,999999999999999999.9999))||''|| rtrim(LTRIM(translate(STATUS,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(TAXABLE_AMOUNT,999999999999999999.9999))||''|| trim(to_char(INV_CCY_TAXABLE_AMOUNT,999999999999999999.9999))||''|| trim(to_char(MEMB_ID,9999999999))||''|| trim(to_char(STATEMENT_RUN_ID,9999999999))||''|| trim(to_char(DN_FULL_DP_INV_CCY_AMOUNT))||''|| rtrim(LTRIM(translate(INCLUDES_ROUNDING_Y,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(DN_DITR_MEMB_ID,9999999999))||''|| trim(to_char(DN_FULLY_PAID_AT_DIST_ID,9999999999))||''|| trim(to_char(DN_FIRST_PRESENTED_AT_DIST_ID,9999999999))||''|| trim(to_char(DN_DIST_ID_LE_PAID_AT,9999999999))||''|| to_char(DN_DISPENSABLE_DT,'YYYY-MM-DD HH24:MI:SS')||''|| to_char(ilel.UPDATED_DTM,'YYYY-MM-DD HH24:MI:SS')||''|| trim(to_char(UPDATED_BY_APUS_ID,9999999999))||''|| to_char(ilel.CREATED_DTM,'YYYY-MM-DD HH24:MI:SS')||''|| trim(to_char(CREATED_BY_APUS_ID,9999999999))||''|| trim(to_char(DN_DITR_MEMB_SUB_PARTITION_KEY,9999))||''|| rtrim(LTRIM(translate(PAYMENT_SOC_NBR,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(VATABLE_AMOUNT,999999999999999999.9999))||''|| trim(to_char(INV_CCY_VATABLE_AMOUNT,999999999999999999.9999)) delim_row FROM DMOWN.INVOICE_LEGAL_EARNER_LINES PARTITION (P_ILEL_052_CURR) ilel WHERE ilel.DN_DISPENSABLE_DT IS NULL; <file_sep>/DB.DM/DPOWN/2. Views/Backload/DPOWN.DM_CASHING_OUT_GROUP_VW.sql CREATE OR REPLACE FORCE VIEW DM_CASHING_OUT_GROUP_VW AS SELECT CASHING_OUT_GROUP_ID, CASHING_OUT_GROUP_TYPE_ID, CREATED_BY_USER_ID, DISTRIBUTION_ID, FPV_REC_CASHING_OUT_GROUP_ID, LAST_UPDATED_BY_USER_ID, CREATED_DT, PROCESS_STAGE, CASHING_OUT_GROUP_CODE, LAST_UPDATED_DT, FPV_REC_DT, RIGHT_TYPE, DN_ON_BEHALF_OF_SOC_NBR, trim(to_char(CASHING_OUT_GROUP_ID,9999999999))||''|| trim(to_char(CASHING_OUT_GROUP_TYPE_ID,9999999999))||''|| trim(to_char(CREATED_BY_USER_ID,9999999999))||''|| trim(to_char(DISTRIBUTION_ID,9999999999))||''|| trim(to_char(FPV_REC_CASHING_OUT_GROUP_ID,9999999999))||''|| trim(to_char(LAST_UPDATED_BY_USER_ID,9999999999))||''|| to_char(CREATED_DT,'YYYY-MM-DD HH24:MI:SS')||''|| rtrim(LTRIM(translate(PROCESS_STAGE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(CASHING_OUT_GROUP_CODE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| to_char(LAST_UPDATED_DT,'YYYY-MM-DD HH24:MI:SS')||''|| to_char(FPV_REC_DT,'YYYY-MM-DD HH24:MI:SS')||''|| rtrim(LTRIM(translate(RIGHT_TYPE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(DN_ON_BEHALF_OF_SOC_NBR,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0)) delim_row FROM DMOWN.CASHING_OUT_GROUP; <file_sep>/DB.DM/DMOWN/2. Sequences/BI_AUDIT_SEQ.sql DROP SEQUENCE DMOWN.BI_AUDIT_SEQ; CREATE SEQUENCE DMOWN.BI_AUDIT_SEQ START WITH 1 MAXVALUE 999999999999 MINVALUE 1 NOCACHE GLOBAL; CREATE OR REPLACE PUBLIC SYNONYM BI_AUDIT_SEQ FOR DMOWN.BI_AUDIT_SEQ; GRANT SELECT ON DMOWN.BI_AUDIT_SEQ TO DM_APP_BATCH; GRANT SELECT ON DMOWN.BI_AUDIT_SEQ TO DM_APP_USER; <file_sep>/DB.DM/DPOWN/1. Tables/DPOWN.P2P_DM_EXTRACT_CONTROL.sql DECLARE does_not_exist EXCEPTION; PRAGMA EXCEPTION_INIT (does_not_exist, -2289); BEGIN EXECUTE IMMEDIATE 'DROP SEQUENCE DPOWN.P2P_DM_ECTL_SEQ'; EXCEPTION WHEN does_not_exist THEN NULL; END; / CREATE SEQUENCE DPOWN.P2P_DM_ECTL_SEQ MINVALUE 1 MAXVALUE 999999999999 START WITH 1 INCREMENT BY 1 NOCACHE ORDER; DECLARE does_not_exist EXCEPTION; PRAGMA EXCEPTION_INIT (does_not_exist, -942); BEGIN EXECUTE IMMEDIATE 'DROP TABLE DPOWN.P2P_DM_EXTRACT_CONTROL'; EXCEPTION WHEN does_not_exist THEN NULL; END; / CREATE TABLE DPOWN.P2P_DM_EXTRACT_CONTROL ( EXTRACT_ID NUMBER(12) NOT NULL, CREATED_DTM DATE NOT NULL, UPDATED_DTM DATE, EXTRACT_START_DTM DATE NOT NULL, EXTRACT_END_DTM DATE NOT NULL, EXTRACTED_TO_BI_Y VARCHAR2(1 BYTE) ) TABLESPACE DMOWN_MD_A ; CREATE UNIQUE INDEX DPOWN.P2P_DM_ECTL_PK ON DPOWN.P2P_DM_EXTRACT_CONTROL ( EXTRACT_ID ) TABLESPACE DMOWN_MI_A; ALTER TABLE DPOWN.P2P_DM_EXTRACT_CONTROL ADD ( CONSTRAINT P2P_DM_ECTL_PK PRIMARY KEY ( EXTRACT_ID ) USING INDEX DPOWN.P2P_DM_ECTL_PK ENABLE VALIDATE ); <file_sep>/DB.DM/DPOWN/Dev Support/dm_extract_data_files.SQL set serveroutput ON DECLARE l_source_batch_id varchar2(7) := '001'; l_row_cnt number; l_start_dtm date; l_end_dtm date; l_exec_time number; e_file_write_error EXCEPTION; PRAGMA EXCEPTION_INIT (e_file_write_error, -29285); PROCEDURE extract_data (p_view varchar2, p_source_batch_id varchar2, p_thread number) IS BEGIN l_start_dtm := SYSDATE; dpown.dm_extract_utility.extract_data_file(p_view, p_source_batch_id, p_thread, l_row_cnt); l_end_dtm := SYSDATE; l_exec_time := ROUND(24 * 60 * 60 * (l_end_dtm - l_start_dtm)); dbms_output.put_line(p_view ||'-'||p_thread||' - NO OF ROWS = '||l_row_cnt || ' - TIME taken '|| l_exec_time || ' secs'); EXCEPTION WHEN e_file_write_error THEN dbms_output.put_line(p_view||'-'||p_thread||' - FAILURE'); END extract_data; BEGIN extract_data('DM_BROADCAST_REGION', l_source_batch_id, NULL); extract_data('DM_CAE', l_source_batch_id, NULL); extract_data('DM_CURRENCY', l_source_batch_id, NULL); extract_data('DM_DISTRIBUTION', l_source_batch_id, NULL); extract_data('DM_INVOICES', l_source_batch_id, NULL); extract_data('DM_LICENSING_BODIES', l_source_batch_id, NULL); extract_data('DM_MEMBERSHIP_TYPE', l_source_batch_id, NULL); extract_data('DM_PRODUCT_TYPES', l_source_batch_id, NULL); extract_data('DM_SERVICE_TYPES', l_source_batch_id, NULL); extract_data('DM_SOCIETY', l_source_batch_id, NULL); extract_data('DM_USAGE_CATEGORIES', l_source_batch_id, NULL); extract_data('DM_USAGE_GROUP', l_source_batch_id, NULL); extract_data('DM_USAGE_GROUP_SUMM', l_source_batch_id, NULL); extract_data('DM_USAGE_GROUP_TYPE', l_source_batch_id, NULL); extract_data('DM_ADJUSTMENT_REASON', l_source_batch_id, NULL); extract_data('DM_CASHING_OUT_GROUP', l_source_batch_id, NULL); extract_data('DM_MEMBER_DISTRIBUTION_SUMM', l_source_batch_id, NULL); extract_data('DM_PERFORMANCE', l_source_batch_id, NULL); extract_data('DM_PS_MEMBERS_IN_DIST', l_source_batch_id, NULL); extract_data('DM_REPERTOIRE_POSTING', l_source_batch_id, NULL); extract_data('DM_ROYALTY_LINE_TRANSFER', l_source_batch_id, NULL); extract_data('DM_ROYALTY_TRANSACTION', l_source_batch_id, NULL); extract_data('DM_DIGITAL_TRANSACTIONS', l_source_batch_id, NULL); extract_data('MEM_COUNTRY', l_source_batch_id, NULL); extract_data('MEM_MEMBERSHIP', l_source_batch_id, NULL); END; / <file_sep>/DB.DM/DPOWN/2. Views/Backload/DPOWN.DM_DELETED_INVOICES_VW.sql CREATE OR REPLACE FORCE VIEW DM_DELETED_INVOICES_VW AS SELECT INVOICE_NUMBER, DELETION_DTM, DELETED_BY_APUS_ID, DELETION_COMMENT, inva.CREATED_DTM, trim(to_char(INVOICE_NUMBER,999999999999))||''|| to_char(DELETION_DTM,'YYYY-MM-DD HH24:MI:SS')||''|| trim(to_char(DELETED_BY_APUS_ID,9999999999))||''|| rtrim(LTRIM(translate(DELETION_COMMENT,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| to_char(inva.CREATED_DTM,'YYYY-MM-DD HH24:MI:SS') delim_row FROM DMOWN.INVOICES_AUD inva CROSS JOIN DPOWN.P2P_DM_EXTRACT_CONTROL exctl WHERE exctl.EXTRACTED_TO_BI_Y IS NULL AND inva.DELETION_DTM IS NOT NULL AND inva.DELETION_DTM > exctl.EXTRACT_START_DTM; <file_sep>/DB.DM/DPOWN/Dev Support/DPOWN.FACT_USAGE_CONTRIBUTOR.sql DECLARE does_not_exist EXCEPTION; PRAGMA EXCEPTION_INIT (does_not_exist, -942); BEGIN EXECUTE IMMEDIATE 'DROP TABLE PRBI_AGG.FACT_USAGE_CONTRIBUTOR'; EXCEPTION WHEN does_not_exist THEN NULL; END; / CREATE TABLE PRBI_AGG.FACT_USAGE_CONTRIBUTOR (contributor_key NUMBER(12) NOT NULL, -- degen dim usage_header_id NUMBER(12) NOT NULL, usage_detail_id NUMBER(12) NOT NULL, cue_id NUMBER(12) NOT NULL, role_type_code VARCHAR2(5 CHAR) NOT NULL) TABLESPACE prbi_st_broad_bd_a; -- work level insert INSERT /*+ append */ INTO PRBI_AGG.FACT_USAGE_CONTRIBUTOR (contributor_key, usage_header_id, usage_detail_id, cue_id, role_type_code) SELECT /*+ parallel */ uc.cont_surr_id, fuow.usage_header_id uh_surr_id, fuow.usage_detail_id ud_surr_id, 0 cc_surr_id, NVL(uc.rt_code,0) role_type_code FROM fact_usage_of_work_wl fuow JOIN prbi_staging.usage_contributors uc ON (fuow.usage_detail_id = uc.ud_surr_id); COMMIT; -- prod level insert INSERT /*+ append */ INTO prbi_agg.fact_usage_contributor (contributor_key, usage_header_id, usage_detail_id, cue_id, role_type_code) SELECT /*+ parallel */ avc.cont_surr_id, fuow.usage_header_id uh_surr_id, 0 ud_surr_id, fuow.cue_id, NVL(avc.rt_code,0) role_type_code FROM fact_usage_of_work_pl fuow JOIN prbi_staging.audio_visual_contributors avc ON (fuow.cue_id = avc.cc_surr_id); COMMIT; CREATE INDEX prbi_agg_fuc_contk ON prbi_agg.fact_usage_contributor(contributor_key) TABLESPACE prbi_st_broad_bi_a; <file_sep>/DB.DM/DPOWN/Dev Support/dm_extract_DDL.sql SET SERVEROUTPUT ON BEGIN -- Source Views DPOWN.dm_extract_load_ddl.gen_source_view (p_source_schema => 'DMOWN', p_table_name => 'BROADCAST_REGION', p_view_schema => 'DPOWN'); DPOWN.dm_extract_load_ddl.gen_source_view (p_source_schema => 'DMOWN', p_table_name => 'CAE', p_view_schema => 'DPOWN'); DPOWN.dm_extract_load_ddl.gen_source_view (p_source_schema => 'DMOWN', p_table_name => 'CURRENCY', p_view_schema => 'DPOWN'); DPOWN.dm_extract_load_ddl.gen_source_view (p_source_schema => 'DMOWN', p_table_name => 'DISTRIBUTION', p_view_schema => 'DPOWN'); DPOWN.dm_extract_load_ddl.gen_source_view (p_source_schema => 'DMOWN', p_table_name => 'INVOICES', p_view_schema => 'DPOWN'); DPOWN.dm_extract_load_ddl.gen_source_view (p_source_schema => 'DMOWN', p_table_name => 'LICENSING_BODIES', p_view_schema => 'DPOWN'); DPOWN.dm_extract_load_ddl.gen_source_view (p_source_schema => 'DMOWN', p_table_name => 'MEMBERSHIP_TYPE', p_view_schema => 'DPOWN'); DPOWN.dm_extract_load_ddl.gen_source_view (p_source_schema => 'DMOWN', p_table_name => 'PRODUCT_TYPES', p_view_schema => 'DPOWN'); DPOWN.dm_extract_load_ddl.gen_source_view (p_source_schema => 'DMOWN', p_table_name => 'SERVICE_TYPES', p_view_schema => 'DPOWN'); DPOWN.dm_extract_load_ddl.gen_source_view (p_source_schema => 'DMOWN', p_table_name => 'SOCIETY', p_view_schema => 'DPOWN'); DPOWN.dm_extract_load_ddl.gen_source_view (p_source_schema => 'DMOWN', p_table_name => 'USAGE_CATEGORIES', p_view_schema => 'DPOWN'); DPOWN.dm_extract_load_ddl.gen_source_view (p_source_schema => 'DMOWN', p_table_name => 'USAGE_GROUP', p_view_schema => 'DPOWN'); DPOWN.dm_extract_load_ddl.gen_source_view (p_source_schema => 'DMOWN', p_table_name => 'USAGE_GROUP_SUMM', p_view_schema => 'DPOWN'); DPOWN.dm_extract_load_ddl.gen_source_view (p_source_schema => 'DMOWN', p_table_name => 'USAGE_GROUP_TYPE', p_view_schema => 'DPOWN'); DPOWN.dm_extract_load_ddl.gen_source_view (p_source_schema => 'DMOWN', p_table_name => 'ADJUSTMENT_REASON', p_view_schema => 'DPOWN'); DPOWN.dm_extract_load_ddl.gen_source_view (p_source_schema => 'DMOWN', p_table_name => 'CASHING_OUT_GROUP', p_view_schema => 'DPOWN'); DPOWN.dm_extract_load_ddl.gen_source_view (p_source_schema => 'DMOWN', p_table_name => 'MEMBER_DISTRIBUTION_SUMM', p_view_schema => 'DPOWN'); DPOWN.dm_extract_load_ddl.gen_source_view (p_source_schema => 'DMOWN', p_table_name => 'PERFORMANCE', p_view_schema => 'DPOWN'); DPOWN.dm_extract_load_ddl.gen_source_view (p_source_schema => 'DMOWN', p_table_name => 'PS_MEMBERS_IN_DIST', p_view_schema => 'DPOWN'); DPOWN.dm_extract_load_ddl.gen_source_view (p_source_schema => 'DMOWN', p_table_name => 'REPERTOIRE_POSTING', p_view_schema => 'DPOWN'); DPOWN.dm_extract_load_ddl.gen_source_view (p_source_schema => 'DMOWN', p_table_name => 'ROYALTY_LINE_TRANSFER', p_view_schema => 'DPOWN'); DPOWN.dm_extract_load_ddl.gen_source_view (p_source_schema => 'DMOWN', p_table_name => 'ROYALTY_TRANSACTION', p_view_schema => 'DPOWN'); DPOWN.dm_extract_load_ddl.gen_source_view (p_source_schema => 'DMOWN', p_table_name => 'DIGITAL_TRANSACTIONS', p_view_schema => 'DPOWN'); DPOWN.dm_extract_load_ddl.gen_source_view (p_source_schema => 'DMOWN', p_table_name => 'DISTRIBUTION_TYPE', p_view_schema => 'DPOWN'); DPOWN.dm_extract_load_ddl.gen_source_view (p_source_schema => 'MEMOWN', p_table_name => 'COUNTRY', p_view_schema => 'DPOWN'); DPOWN.dm_extract_load_ddl.gen_source_view (p_source_schema => 'MEMOWN', p_table_name => 'MEMBERSHIP', p_view_schema => 'DPOWN'); END; / -- BROADCAST_REGION BEGIN DPOWN.dm_extract_load_ddl.gen_ext_datasrc_ddl (p_source_schema => 'DMOWN', p_table_name => 'BROADCAST_REGION'); DPOWN.dm_extract_load_ddl.gen_ext_tab_ddl (p_source_schema => 'DMOWN', p_table_name => 'BROADCAST_REGION', p_exttbl_schema => 'Staging'); DPOWN.dm_extract_load_ddl.gen_stg_pkg_ddl (p_source_schema => 'DMOWN', p_table_name => 'BROADCAST_REGION', p_stgpkg_schema => 'Staging'); DPOWN.dm_extract_load_ddl.gen_cln_pkg_ddl (p_source_schema => 'DMOWN', p_table_name => 'BROADCAST_REGION', p_clnpkg_schema => 'Clean'); END; / -- CAE BEGIN DPOWN.dm_extract_load_ddl.gen_ext_datasrc_ddl (p_source_schema => 'DMOWN', p_table_name => 'CAE'); DPOWN.dm_extract_load_ddl.gen_ext_tab_ddl (p_source_schema => 'DMOWN', p_table_name => 'CAE', p_exttbl_schema => 'Staging'); DPOWN.dm_extract_load_ddl.gen_stg_pkg_ddl (p_source_schema => 'DMOWN', p_table_name => 'CAE', p_stgpkg_schema => 'Staging'); DPOWN.dm_extract_load_ddl.gen_cln_pkg_ddl (p_source_schema => 'DMOWN', p_table_name => 'CAE', p_clnpkg_schema => 'Clean'); END; / -- CURRENCY BEGIN DPOWN.dm_extract_load_ddl.gen_ext_datasrc_ddl (p_source_schema => 'DMOWN', p_table_name => 'CURRENCY'); DPOWN.dm_extract_load_ddl.gen_ext_tab_ddl (p_source_schema => 'DMOWN', p_table_name => 'CURRENCY', p_exttbl_schema => 'Staging'); DPOWN.dm_extract_load_ddl.gen_stg_pkg_ddl (p_source_schema => 'DMOWN', p_table_name => 'CURRENCY', p_stgpkg_schema => 'Staging'); DPOWN.dm_extract_load_ddl.gen_cln_pkg_ddl (p_source_schema => 'DMOWN', p_table_name => 'CURRENCY', p_clnpkg_schema => 'Clean'); END; / -- DISTRIBUTION BEGIN DPOWN.dm_extract_load_ddl.gen_ext_datasrc_ddl (p_source_schema => 'DMOWN', p_table_name => 'DISTRIBUTION'); DPOWN.dm_extract_load_ddl.gen_ext_tab_ddl (p_source_schema => 'DMOWN', p_table_name => 'DISTRIBUTION', p_exttbl_schema => 'Staging'); DPOWN.dm_extract_load_ddl.gen_stg_pkg_ddl (p_source_schema => 'DMOWN', p_table_name => 'DISTRIBUTION', p_stgpkg_schema => 'Staging'); DPOWN.dm_extract_load_ddl.gen_cln_pkg_ddl (p_source_schema => 'DMOWN', p_table_name => 'DISTRIBUTION', p_clnpkg_schema => 'Clean'); END; / -- INVOICES BEGIN DPOWN.dm_extract_load_ddl.gen_ext_datasrc_ddl (p_source_schema => 'DMOWN', p_table_name => 'INVOICES'); DPOWN.dm_extract_load_ddl.gen_ext_tab_ddl (p_source_schema => 'DMOWN', p_table_name => 'INVOICES', p_exttbl_schema => 'Staging'); DPOWN.dm_extract_load_ddl.gen_stg_pkg_ddl (p_source_schema => 'DMOWN', p_table_name => 'INVOICES', p_stgpkg_schema => 'Staging'); DPOWN.dm_extract_load_ddl.gen_cln_pkg_ddl (p_source_schema => 'DMOWN', p_table_name => 'INVOICES', p_clnpkg_schema => 'Clean'); END; / -- LICENSING_BODIES BEGIN DPOWN.dm_extract_load_ddl.gen_ext_datasrc_ddl (p_source_schema => 'DMOWN', p_table_name => 'LICENSING_BODIES'); DPOWN.dm_extract_load_ddl.gen_ext_tab_ddl (p_source_schema => 'DMOWN', p_table_name => 'LICENSING_BODIES', p_exttbl_schema => 'Staging'); DPOWN.dm_extract_load_ddl.gen_stg_pkg_ddl (p_source_schema => 'DMOWN', p_table_name => 'LICENSING_BODIES', p_stgpkg_schema => 'Staging'); DPOWN.dm_extract_load_ddl.gen_cln_pkg_ddl (p_source_schema => 'DMOWN', p_table_name => 'LICENSING_BODIES', p_clnpkg_schema => 'Clean'); END; / -- MEMBERSHIP_TYPE BEGIN DPOWN.dm_extract_load_ddl.gen_ext_datasrc_ddl (p_source_schema => 'DMOWN', p_table_name => 'MEMBERSHIP_TYPE'); DPOWN.dm_extract_load_ddl.gen_ext_tab_ddl (p_source_schema => 'DMOWN', p_table_name => 'MEMBERSHIP_TYPE', p_exttbl_schema => 'Staging'); DPOWN.dm_extract_load_ddl.gen_stg_pkg_ddl (p_source_schema => 'DMOWN', p_table_name => 'MEMBERSHIP_TYPE', p_stgpkg_schema => 'Staging'); DPOWN.dm_extract_load_ddl.gen_cln_pkg_ddl (p_source_schema => 'DMOWN', p_table_name => 'MEMBERSHIP_TYPE', p_clnpkg_schema => 'Clean'); END; / -- PRODUCT_TYPES BEGIN DPOWN.dm_extract_load_ddl.gen_ext_datasrc_ddl (p_source_schema => 'DMOWN', p_table_name => 'PRODUCT_TYPES'); DPOWN.dm_extract_load_ddl.gen_ext_tab_ddl (p_source_schema => 'DMOWN', p_table_name => 'PRODUCT_TYPES', p_exttbl_schema => 'Staging'); DPOWN.dm_extract_load_ddl.gen_stg_pkg_ddl (p_source_schema => 'DMOWN', p_table_name => 'PRODUCT_TYPES', p_stgpkg_schema => 'Staging'); DPOWN.dm_extract_load_ddl.gen_cln_pkg_ddl (p_source_schema => 'DMOWN', p_table_name => 'PRODUCT_TYPES', p_clnpkg_schema => 'Clean'); END; / -- SERVICE_TYPES BEGIN DPOWN.dm_extract_load_ddl.gen_ext_datasrc_ddl (p_source_schema => 'DMOWN', p_table_name => 'SERVICE_TYPES'); DPOWN.dm_extract_load_ddl.gen_ext_tab_ddl (p_source_schema => 'DMOWN', p_table_name => 'SERVICE_TYPES', p_exttbl_schema => 'Staging'); DPOWN.dm_extract_load_ddl.gen_stg_pkg_ddl (p_source_schema => 'DMOWN', p_table_name => 'SERVICE_TYPES', p_stgpkg_schema => 'Staging'); DPOWN.dm_extract_load_ddl.gen_cln_pkg_ddl (p_source_schema => 'DMOWN', p_table_name => 'SERVICE_TYPES', p_clnpkg_schema => 'Clean'); END; / -- SOCIETY BEGIN DPOWN.dm_extract_load_ddl.gen_ext_datasrc_ddl (p_source_schema => 'DMOWN', p_table_name => 'SOCIETY'); DPOWN.dm_extract_load_ddl.gen_ext_tab_ddl (p_source_schema => 'DMOWN', p_table_name => 'SOCIETY', p_exttbl_schema => 'Staging'); DPOWN.dm_extract_load_ddl.gen_stg_pkg_ddl (p_source_schema => 'DMOWN', p_table_name => 'SOCIETY', p_stgpkg_schema => 'Staging'); DPOWN.dm_extract_load_ddl.gen_cln_pkg_ddl (p_source_schema => 'DMOWN', p_table_name => 'SOCIETY', p_clnpkg_schema => 'Clean'); END; / -- USAGE_CATEGORIES BEGIN DPOWN.dm_extract_load_ddl.gen_ext_datasrc_ddl (p_source_schema => 'DMOWN', p_table_name => 'USAGE_CATEGORIES'); DPOWN.dm_extract_load_ddl.gen_ext_tab_ddl (p_source_schema => 'DMOWN', p_table_name => 'USAGE_CATEGORIES', p_exttbl_schema => 'Staging'); DPOWN.dm_extract_load_ddl.gen_stg_pkg_ddl (p_source_schema => 'DMOWN', p_table_name => 'USAGE_CATEGORIES', p_stgpkg_schema => 'Staging'); DPOWN.dm_extract_load_ddl.gen_cln_pkg_ddl (p_source_schema => 'DMOWN', p_table_name => 'USAGE_CATEGORIES', p_clnpkg_schema => 'Clean'); END; / -- USAGE_GROUP BEGIN DPOWN.dm_extract_load_ddl.gen_ext_datasrc_ddl (p_source_schema => 'DMOWN', p_table_name => 'USAGE_GROUP'); DPOWN.dm_extract_load_ddl.gen_ext_tab_ddl (p_source_schema => 'DMOWN', p_table_name => 'USAGE_GROUP', p_exttbl_schema => 'Staging'); DPOWN.dm_extract_load_ddl.gen_stg_pkg_ddl (p_source_schema => 'DMOWN', p_table_name => 'USAGE_GROUP', p_stgpkg_schema => 'Staging'); DPOWN.dm_extract_load_ddl.gen_cln_pkg_ddl (p_source_schema => 'DMOWN', p_table_name => 'USAGE_GROUP', p_clnpkg_schema => 'Clean'); END; / -- USAGE_GROUP_SUMM BEGIN DPOWN.dm_extract_load_ddl.gen_ext_datasrc_ddl (p_source_schema => 'DMOWN', p_table_name => 'USAGE_GROUP_SUMM'); DPOWN.dm_extract_load_ddl.gen_ext_tab_ddl (p_source_schema => 'DMOWN', p_table_name => 'USAGE_GROUP_SUMM', p_exttbl_schema => 'Staging'); DPOWN.dm_extract_load_ddl.gen_stg_pkg_ddl (p_source_schema => 'DMOWN', p_table_name => 'USAGE_GROUP_SUMM', p_stgpkg_schema => 'Staging'); DPOWN.dm_extract_load_ddl.gen_cln_pkg_ddl (p_source_schema => 'DMOWN', p_table_name => 'USAGE_GROUP_SUMM', p_clnpkg_schema => 'Clean'); END; / -- USAGE_GROUP_TYPE BEGIN DPOWN.dm_extract_load_ddl.gen_ext_datasrc_ddl (p_source_schema => 'DMOWN', p_table_name => 'USAGE_GROUP_TYPE'); DPOWN.dm_extract_load_ddl.gen_ext_tab_ddl (p_source_schema => 'DMOWN', p_table_name => 'USAGE_GROUP_TYPE', p_exttbl_schema => 'Staging'); DPOWN.dm_extract_load_ddl.gen_stg_pkg_ddl (p_source_schema => 'DMOWN', p_table_name => 'USAGE_GROUP_TYPE', p_stgpkg_schema => 'Staging'); DPOWN.dm_extract_load_ddl.gen_cln_pkg_ddl (p_source_schema => 'DMOWN', p_table_name => 'USAGE_GROUP_TYPE', p_clnpkg_schema => 'Clean'); END; / -- ADJUSTMENT_REASON EXAMPLE BEGIN DPOWN.dm_extract_load_ddl.gen_ext_datasrc_ddl (p_source_schema => 'DMOWN', p_table_name => 'ADJUSTMENT_REASON'); DPOWN.dm_extract_load_ddl.gen_ext_tab_ddl (p_source_schema => 'DMOWN', p_table_name => 'ADJUSTMENT_REASON', p_exttbl_schema => 'Staging'); DPOWN.dm_extract_load_ddl.gen_stg_pkg_ddl (p_source_schema => 'DMOWN', p_table_name => 'ADJUSTMENT_REASON', p_stgpkg_schema => 'Staging'); DPOWN.dm_extract_load_ddl.gen_cln_pkg_ddl (p_source_schema => 'DMOWN', p_table_name => 'ADJUSTMENT_REASON', p_clnpkg_schema => 'Clean'); END; / -- CASHING_OUT_GROUP BEGIN DPOWN.dm_extract_load_ddl.gen_ext_datasrc_ddl (p_source_schema => 'DMOWN', p_table_name => 'CASHING_OUT_GROUP'); DPOWN.dm_extract_load_ddl.gen_ext_tab_ddl (p_source_schema => 'DMOWN', p_table_name => 'CASHING_OUT_GROUP', p_exttbl_schema => 'Staging'); DPOWN.dm_extract_load_ddl.gen_stg_pkg_ddl (p_source_schema => 'DMOWN', p_table_name => 'CASHING_OUT_GROUP', p_stgpkg_schema => 'Staging'); DPOWN.dm_extract_load_ddl.gen_cln_pkg_ddl (p_source_schema => 'DMOWN', p_table_name => 'CASHING_OUT_GROUP', p_clnpkg_schema => 'Clean'); END; / -- MEMBER_DISTRIBUTION_SUMM BEGIN DPOWN.dm_extract_load_ddl.gen_ext_datasrc_ddl (p_source_schema => 'DMOWN', p_table_name => 'MEMBER_DISTRIBUTION_SUMM'); DPOWN.dm_extract_load_ddl.gen_ext_tab_ddl (p_source_schema => 'DMOWN', p_table_name => 'MEMBER_DISTRIBUTION_SUMM', p_exttbl_schema => 'Staging'); DPOWN.dm_extract_load_ddl.gen_stg_pkg_ddl (p_source_schema => 'DMOWN', p_table_name => 'MEMBER_DISTRIBUTION_SUMM', p_stgpkg_schema => 'Staging'); DPOWN.dm_extract_load_ddl.gen_cln_pkg_ddl (p_source_schema => 'DMOWN', p_table_name => 'MEMBER_DISTRIBUTION_SUMM', p_clnpkg_schema => 'Clean'); END; / -- PERFORMANCE BEGIN DPOWN.dm_extract_load_ddl.gen_ext_datasrc_ddl (p_source_schema => 'DMOWN', p_table_name => 'PERFORMANCE'); DPOWN.dm_extract_load_ddl.gen_ext_tab_ddl (p_source_schema => 'DMOWN', p_table_name => 'PERFORMANCE', p_exttbl_schema => 'Staging'); DPOWN.dm_extract_load_ddl.gen_stg_pkg_ddl (p_source_schema => 'DMOWN', p_table_name => 'PERFORMANCE', p_stgpkg_schema => 'Staging'); DPOWN.dm_extract_load_ddl.gen_cln_pkg_ddl (p_source_schema => 'DMOWN', p_table_name => 'PERFORMANCE', p_clnpkg_schema => 'Clean'); END; / -- PS_MEMBERS_IN_DIST BEGIN DPOWN.dm_extract_load_ddl.gen_ext_datasrc_ddl (p_source_schema => 'DMOWN', p_table_name => 'PS_MEMBERS_IN_DIST'); DPOWN.dm_extract_load_ddl.gen_ext_tab_ddl (p_source_schema => 'DMOWN', p_table_name => 'PS_MEMBERS_IN_DIST', p_exttbl_schema => 'Staging'); DPOWN.dm_extract_load_ddl.gen_stg_pkg_ddl (p_source_schema => 'DMOWN', p_table_name => 'PS_MEMBERS_IN_DIST', p_stgpkg_schema => 'Staging'); DPOWN.dm_extract_load_ddl.gen_cln_pkg_ddl (p_source_schema => 'DMOWN', p_table_name => 'PS_MEMBERS_IN_DIST', p_clnpkg_schema => 'Clean'); END; / -- REPERTOIRE_POSTING BEGIN DPOWN.dm_extract_load_ddl.gen_ext_datasrc_ddl (p_source_schema => 'DMOWN', p_table_name => 'REPERTOIRE_POSTING'); DPOWN.dm_extract_load_ddl.gen_ext_tab_ddl (p_source_schema => 'DMOWN', p_table_name => 'REPERTOIRE_POSTING', p_exttbl_schema => 'Staging'); DPOWN.dm_extract_load_ddl.gen_stg_pkg_ddl (p_source_schema => 'DMOWN', p_table_name => 'REPERTOIRE_POSTING', p_stgpkg_schema => 'Staging'); DPOWN.dm_extract_load_ddl.gen_cln_pkg_ddl (p_source_schema => 'DMOWN', p_table_name => 'REPERTOIRE_POSTING', p_clnpkg_schema => 'Clean'); END; / -- ROYALTY_LINE_TRANSFER BEGIN DPOWN.dm_extract_load_ddl.gen_ext_datasrc_ddl (p_source_schema => 'DMOWN', p_table_name => 'ROYALTY_LINE_TRANSFER'); DPOWN.dm_extract_load_ddl.gen_ext_tab_ddl (p_source_schema => 'DMOWN', p_table_name => 'ROYALTY_LINE_TRANSFER', p_exttbl_schema => 'Staging'); DPOWN.dm_extract_load_ddl.gen_stg_pkg_ddl (p_source_schema => 'DMOWN', p_table_name => 'ROYALTY_LINE_TRANSFER', p_stgpkg_schema => 'Staging'); DPOWN.dm_extract_load_ddl.gen_cln_pkg_ddl (p_source_schema => 'DMOWN', p_table_name => 'ROYALTY_LINE_TRANSFER', p_clnpkg_schema => 'Clean'); END; / -- ROYALTY_TRANSACTION BEGIN DPOWN.dm_extract_load_ddl.gen_ext_datasrc_ddl (p_source_schema => 'DMOWN', p_table_name => 'ROYALTY_TRANSACTION'); DPOWN.dm_extract_load_ddl.gen_ext_tab_ddl (p_source_schema => 'DMOWN', p_table_name => 'ROYALTY_TRANSACTION', p_exttbl_schema => 'Staging'); DPOWN.dm_extract_load_ddl.gen_stg_pkg_ddl (p_source_schema => 'DMOWN', p_table_name => 'ROYALTY_TRANSACTION', p_stgpkg_schema => 'Staging'); DPOWN.dm_extract_load_ddl.gen_cln_pkg_ddl (p_source_schema => 'DMOWN', p_table_name => 'ROYALTY_TRANSACTION', p_clnpkg_schema => 'Clean'); END; / -- DIGITAL_TRANSACTIONS BEGIN DPOWN.dm_extract_load_ddl.gen_ext_datasrc_ddl (p_source_schema => 'DMOWN', p_table_name => 'DIGITAL_TRANSACTIONS'); DPOWN.dm_extract_load_ddl.gen_ext_tab_ddl (p_source_schema => 'DMOWN', p_table_name => 'DIGITAL_TRANSACTIONS', p_exttbl_schema => 'Staging'); DPOWN.dm_extract_load_ddl.gen_stg_pkg_ddl (p_source_schema => 'DMOWN', p_table_name => 'DIGITAL_TRANSACTIONS', p_stgpkg_schema => 'Staging'); DPOWN.dm_extract_load_ddl.gen_cln_pkg_ddl (p_source_schema => 'DMOWN', p_table_name => 'DIGITAL_TRANSACTIONS', p_clnpkg_schema => 'Clean'); END; / -- COUNTRY BEGIN DPOWN.dm_extract_load_ddl.gen_ext_datasrc_ddl (p_source_schema => 'MEMOWN', p_table_name => 'COUNTRY'); DPOWN.dm_extract_load_ddl.gen_ext_tab_ddl (p_source_schema => 'MEMOWN', p_table_name => 'COUNTRY', p_exttbl_schema => 'Staging'); DPOWN.dm_extract_load_ddl.gen_stg_pkg_ddl (p_source_schema => 'MEMOWN', p_table_name => 'COUNTRY', p_stgpkg_schema => 'Staging'); DPOWN.dm_extract_load_ddl.gen_cln_pkg_ddl (p_source_schema => 'MEMOWN', p_table_name => 'COUNTRY', p_clnpkg_schema => 'Clean'); END; / -- MEMBERSHIP BEGIN DPOWN.dm_extract_load_ddl.gen_ext_datasrc_ddl (p_source_schema => 'MEMOWN', p_table_name => 'MEMBERSHIP'); DPOWN.dm_extract_load_ddl.gen_ext_tab_ddl (p_source_schema => 'MEMOWN', p_table_name => 'MEMBERSHIP', p_exttbl_schema => 'Staging'); DPOWN.dm_extract_load_ddl.gen_stg_pkg_ddl (p_source_schema => 'MEMOWN', p_table_name => 'MEMBERSHIP', p_stgpkg_schema => 'Staging'); DPOWN.dm_extract_load_ddl.gen_cln_pkg_ddl (p_source_schema => 'MEMOWN', p_table_name => 'MEMBERSHIP', p_clnpkg_schema => 'Clean'); END; / <file_sep>/DB.DM/DPOWN/2. Views/Backload/DPOWN.DM_CAE_VW.sql CREATE OR REPLACE FORCE VIEW DM_CAE_VW AS SELECT CAE_ID, BUSINESS_INDICATOR_ID, LINK_CAE_ID, SEPARATE_ACCOUNT_LINK_CAE_ID, CAE_NBR, EXTRACT_DT, NEW_PRS_MEMBER_FLG, PRS_FLG, COMMENTS, DELETED_DT, ENTRY_TYPE, NAME, PROFESSIONAL_NAME_FLG, PS_PRS_INSCRIPTION_CHG_FLG, ROLE, SEPARATE_ACCOUNT_FLG, SOURCE_LAST_UPDATED_BY, SOURCE_LAST_UPDATED_DT, SOURCE_LAST_UPDATED_TIME, SOURCE_PREVIOUS_UPDATED_DT, SUISA_CREATE_DT, YEAR_OF_BIRTH, YEAR_OF_DEATH, PS_PENDING_RT_FLG, PS_CAE_DLTD_MEM_NOT_DLTD_FLG, PS_EXTENDED_NAME_CHANGE_FLG, PS_NEW_RT_MEMBERSHIP_ID, PS_OLD_RT_MEMBERSHIP_ID, PS_MEMBERSHIP_INTEGRITY_FLG, PS_MEMBERSHIP_ID, PS_NAME_CHANGE_FLG, PS_ROLE_MISMATCH_FLG, PS_CAE_CURR_MEM_TERM_FLG, PS_CAE_OLD_MEM_CURR_FLG, PS_BIRTH_DT_MISMATCH_FLG, PS_DEATH_DT_MISMATCH_FLG, PS_CAE_DCSD_MEM_NOT_DCSD_FLG, PS_CAE_NOT_DCSD_MEM_DCSD_FLG, DUMMY_LINK_CAE_ID, IPI_STATUS, NEW_MCPS_MEMBER_FLG, MCPS_FLG, PS_MCPS_INSCRIPTION_CHG_FLG, TRIM(TO_CHAR(CAE_ID,9999999999))||''|| TRIM(TO_CHAR(BUSINESS_INDICATOR_ID,9999999999))||''|| TRIM(TO_CHAR(LINK_CAE_ID,9999999999))||''|| TRIM(TO_CHAR(SEPARATE_ACCOUNT_LINK_CAE_ID,9999999999))||''|| RTRIM(LTRIM(TRANSLATE(CAE_NBR,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| TO_CHAR(EXTRACT_DT,'YYYY-MM-DD HH24:MI:SS')||''|| RTRIM(LTRIM(TRANSLATE(NEW_PRS_MEMBER_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(PRS_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(COMMENTS,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(DELETED_DT,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(ENTRY_TYPE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(NAME,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(PROFESSIONAL_NAME_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(PS_PRS_INSCRIPTION_CHG_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(ROLE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(SEPARATE_ACCOUNT_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(SOURCE_LAST_UPDATED_BY,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(SOURCE_LAST_UPDATED_DT,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(SOURCE_LAST_UPDATED_TIME,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(SOURCE_PREVIOUS_UPDATED_DT,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(SUISA_CREATE_DT,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(YEAR_OF_BIRTH,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(YEAR_OF_DEATH,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(PS_PENDING_RT_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(PS_CAE_DLTD_MEM_NOT_DLTD_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(PS_EXTENDED_NAME_CHANGE_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| TRIM(TO_CHAR(PS_NEW_RT_MEMBERSHIP_ID,9999999999))||''|| TRIM(TO_CHAR(PS_OLD_RT_MEMBERSHIP_ID,9999999999))||''|| RTRIM(LTRIM(TRANSLATE(PS_MEMBERSHIP_INTEGRITY_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| TRIM(TO_CHAR(PS_MEMBERSHIP_ID,9999999999))||''|| RTRIM(LTRIM(TRANSLATE(PS_NAME_CHANGE_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(PS_ROLE_MISMATCH_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(PS_CAE_CURR_MEM_TERM_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(PS_CAE_OLD_MEM_CURR_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(PS_BIRTH_DT_MISMATCH_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(PS_DEATH_DT_MISMATCH_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(PS_CAE_DCSD_MEM_NOT_DCSD_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(PS_CAE_NOT_DCSD_MEM_DCSD_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| TRIM(TO_CHAR(DUMMY_LINK_CAE_ID,9999999999))||''|| TRIM(TO_CHAR(IPI_STATUS,9))||''|| RTRIM(LTRIM(TRANSLATE(NEW_MCPS_MEMBER_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(MCPS_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| RTRIM(LTRIM(TRANSLATE(PS_MCPS_INSCRIPTION_CHG_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0)) delim_row FROM DMOWN.CAE; <file_sep>/DB.DM/DPOWN/Dev Support/P2P_EXTRACT_UTILITY.sql DECLARE batch_id VARCHAR2(255); BEGIN P2P_EXTRACT_UTILITY.GET_BATCH_TO_EXTRACT(batch_id); dbms_output.put_line('batch='||batch_id); END; / DECLARE l_rows_extracted NUMBER; BEGIN p2p_extract_utility.extract_data_file(p_table_name => 'DIM_THIRD_PARTY_TREE', p_source_batch_id => '458', p_thread => NULL, p_rows_extracted => l_rows_extracted); dbms_output.put_line('rows='||l_rows_extracted ); END; / DECLARE l_rows_extracted NUMBER; BEGIN p2p_extract_utility.extract_data_file(p_table_name => 'FACT_USAGE_OF_WORK', p_source_batch_id => '294', p_thread => 1, p_rows_extracted => l_rows_extracted); dbms_output.put_line('rows='||l_rows_extracted ); END; /<file_sep>/DB.DM/DPOWN/2. Views/Backload/DPOWN.MEM_MEMBERSHIP_VW.sql CREATE OR REPLACE FORCE VIEW MEM_MEMBERSHIP_VW AS SELECT MEMBERSHIP_ID, MEMBERSHIP_TYPE_ID, CAE_ID, D_TAX_COUNTRY_ID, INDIRECT_AFF_SOC_ID, RECIPROCAL_DEDUCTION_ID, SERVICE_BAND_ID, SOCIETY_ID, SOCIETY_TAX_TYPE_ID, STATEMENT_OPTION_ID, DECEASED_FLG, NAME, RECORD_STATUS, CODA_ACCOUNT_ID, DECEASED_DT, DISTRIBUTION_CHECK_FLG, EEA_FLG, RETAINED_RIGHTS_COMMENT, MEMBERSHIP_COMMENT, IS_MEMBER_OF_STAFF_FLG, POA_FLG, Q_ACCOUNT_FLG, RECEIVE_NLR_FLG, RIGHTS_RETAINED_FLG, SEVEN_YEAR_CASE_DT, SOLE_TRADER_FLG, SUS_ACC_HGH_INT_FLG, TAX_CERTIFICATE_NBR, TAX_EXEMPTION_END_DT, BIRTH_DT, TAX_EXEMPTION_FULL_PART_FLG, TAX_EXEMPTION_START_DT, VAT_NUMBER, SUS_ACC_EX_CSH_OUT_FLG, EXCLUDE_FROM_MINI_FLG, MINI_PYMT_THRESHOLD, SUSACTFR_REQD_FLG, DEPARTMENT_ID, REFERENCE_ONLY_FLG, PRE_JMD_SOURCE, VAT_NUMBER_MCPS, MCPS_TAX_CERT_NBR, MCPS_TAX_EXEMPTION_END_DT, MCPS_TAX_EXEMPTION_FP_FLG, MCPS_TAX_EXEMPTION_START_DT, PAY_PEL_IN_INVOICE_CURRENCY_YN, REAPPORTION_PEL_EARNINGS_Y, DN_CAE_NBR, BANKRUPT_Y, LOAN_FOR_MEMBERSHIP_FEE_Y, WAIVE_MEMBERSHIP_FEE_Y, ARTIST_NAME, BAND_NAME, BUSINESS_INDICATOR_ID, EFFECTIVE_DT, VAT_NUMBER_AFFILIATE, VAT_NUMBER_MCPS_AFFILIATE, SUB_PARTITION_KEY, MAX_FILESIZE_GB, RETURN_TO_PRS_Y, MCTA_TARIFF, MCPS_MIN_PAYMENT, MCPS_LIBRARY_PUBLISHER_Y, MCPS_NON_MEMBER_Y, MCPS_ACCEPT_PRINT_DT, D_MCPS_TAX_COUNTRY_ID, MCPS_MEMBER_TYPE, PRS_INDIRECT_MEMBER_Y, MCPS_CODA_ACCOUNT_ID, MCPS_RECIPROCAL_DEDUCTION_ID, MCPS_SOCIETY_TAX_TYPE_ID, MCPS_EXCLUDE_FROM_MINI_FLG, MCPS_MINI_PYMT_THRESHOLD, COLLATING_PAYEE_CAE_NBR, SUS_ACC_STD_WRITE_OFF_Y, trim(to_char(MEMBERSHIP_ID,9999999999))||''|| trim(to_char(MEMBERSHIP_TYPE_ID,9999999999))||''|| trim(to_char(CAE_ID,9999999999))||''|| trim(to_char(D_TAX_COUNTRY_ID,9999999999))||''|| trim(to_char(INDIRECT_AFF_SOC_ID,9999999999))||''|| trim(to_char(RECIPROCAL_DEDUCTION_ID,9999999999))||''|| trim(to_char(SERVICE_BAND_ID,9999999999))||''|| trim(to_char(SOCIETY_ID,9999999999))||''|| trim(to_char(SOCIETY_TAX_TYPE_ID,9999999999))||''|| trim(to_char(STATEMENT_OPTION_ID,9999999999))||''|| rtrim(LTRIM(translate(DECEASED_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(NAME,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(RECORD_STATUS,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(CODA_ACCOUNT_ID,9999999999))||''|| to_char(DECEASED_DT,'YYYY-MM-DD HH24:MI:SS')||''|| rtrim(LTRIM(translate(DISTRIBUTION_CHECK_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(EEA_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(RETAINED_RIGHTS_COMMENT,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(MEMBERSHIP_COMMENT,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(IS_MEMBER_OF_STAFF_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(POA_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(Q_ACCOUNT_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(RECEIVE_NLR_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(RIGHTS_RETAINED_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| to_char(SEVEN_YEAR_CASE_DT,'YYYY-MM-DD HH24:MI:SS')||''|| rtrim(LTRIM(translate(SOLE_TRADER_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(SUS_ACC_HGH_INT_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(TAX_CERTIFICATE_NBR,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| to_char(TAX_EXEMPTION_END_DT,'YYYY-MM-DD HH24:MI:SS')||''|| to_char(BIRTH_DT,'YYYY-MM-DD HH24:MI:SS')||''|| rtrim(LTRIM(translate(TAX_EXEMPTION_FULL_PART_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| to_char(TAX_EXEMPTION_START_DT,'YYYY-MM-DD HH24:MI:SS')||''|| rtrim(LTRIM(translate(VAT_NUMBER,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(SUS_ACC_EX_CSH_OUT_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(EXCLUDE_FROM_MINI_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(MINI_PYMT_THRESHOLD,99999999999.99))||''|| rtrim(LTRIM(translate(SUSACTFR_REQD_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(DEPARTMENT_ID,9999999999))||''|| rtrim(LTRIM(translate(REFERENCE_ONLY_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(PRE_JMD_SOURCE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(VAT_NUMBER_MCPS,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(MCPS_TAX_CERT_NBR,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| to_char(MCPS_TAX_EXEMPTION_END_DT,'YYYY-MM-DD HH24:MI:SS')||''|| rtrim(LTRIM(translate(MCPS_TAX_EXEMPTION_FP_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| to_char(MCPS_TAX_EXEMPTION_START_DT,'YYYY-MM-DD HH24:MI:SS')||''|| rtrim(LTRIM(translate(PAY_PEL_IN_INVOICE_CURRENCY_YN,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(REAPPORTION_PEL_EARNINGS_Y,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(DN_CAE_NBR,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(BANKRUPT_Y,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(LOAN_FOR_MEMBERSHIP_FEE_Y,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(WAIVE_MEMBERSHIP_FEE_Y,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(ARTIST_NAME,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(BAND_NAME,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(BUSINESS_INDICATOR_ID,9999999999))||''|| to_char(EFFECTIVE_DT,'YYYY-MM-DD HH24:MI:SS')||''|| rtrim(LTRIM(translate(VAT_NUMBER_AFFILIATE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(VAT_NUMBER_MCPS_AFFILIATE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(SUB_PARTITION_KEY,9999))||''|| trim(to_char(MAX_FILESIZE_GB,999999.9999))||''|| rtrim(LTRIM(translate(RETURN_TO_PRS_Y,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(MCTA_TARIFF,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(MCPS_MIN_PAYMENT,9999999999999.99))||''|| rtrim(LTRIM(translate(MCPS_LIBRARY_PUBLISHER_Y,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(MCPS_NON_MEMBER_Y,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| to_char(MCPS_ACCEPT_PRINT_DT,'YYYY-MM-DD HH24:MI:SS')||''|| trim(to_char(D_MCPS_TAX_COUNTRY_ID,9999999999))||''|| rtrim(LTRIM(translate(MCPS_MEMBER_TYPE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(PRS_INDIRECT_MEMBER_Y,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(MCPS_CODA_ACCOUNT_ID,9999999999))||''|| trim(to_char(MCPS_RECIPROCAL_DEDUCTION_ID,9999999999))||''|| trim(to_char(MCPS_SOCIETY_TAX_TYPE_ID,9999999999))||''|| rtrim(LTRIM(translate(MCPS_EXCLUDE_FROM_MINI_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(MCPS_MINI_PYMT_THRESHOLD,99999999999.99))||''|| rtrim(LTRIM(translate(COLLATING_PAYEE_CAE_NBR,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(SUS_ACC_STD_WRITE_OFF_Y,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0)) delim_row FROM MEMOWN.MEMBERSHIP; <file_sep>/DB.DM/DPOWN/2. Views/Backload/DPOWN.DM_BROADCAST_REGION_VW.sql CREATE OR REPLACE FORCE VIEW DM_BROADCAST_REGION_VW AS SELECT BROADCAST_REGION_ID, BROADCAST_REGION_CODE, DESCRIPTION, STATION_CODE, ACTIVE_YN, trim(to_char(BROADCAST_REGION_ID,9999999999))||''|| rtrim(LTRIM(translate(BROADCAST_REGION_CODE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(DESCRIPTION,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(STATION_CODE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(ACTIVE_YN,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0)) delim_row FROM DMOWN.BROADCAST_REGION; <file_sep>/DB.DM/DPOWN/2. Views/Backload/DPOWN.MEM_COUNTRY_VW.sql CREATE OR REPLACE FORCE VIEW MEM_COUNTRY_VW AS SELECT COUNTRY_ID, DESCRIPTION, FPA_FLG, ISO_CODE, RECORD_STATUS, TELEPHONE_STD, TIS_CODE, trim(to_char(COUNTRY_ID,9999999999))||''|| rtrim(LTRIM(translate(DESCRIPTION,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(FPA_FLG,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(ISO_CODE,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(RECORD_STATUS,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| rtrim(LTRIM(translate(TELEPHONE_STD,'x'||CHR(9)||CHR(10)||CHR(13),'x'),'  '||CHR(0)),'  '||CHR(0))||''|| trim(to_char(TIS_CODE,9999)) delim_row FROM MEMOWN.COUNTRY;
ffa3ae8dc0b864000b506fa8b35becf448efd329
[ "SQL" ]
54
SQL
timfirmin/playtopay
01eba8a62b2d1e940468e7090a9e86a044d74e98
2918aa0b205565b05a186aef1be29750b70a73c3
refs/heads/master
<repo_name>wfschmitt/rhost<file_sep>/app/controllers/rhost/posts_controller.rb module Rhost class PostsController < Rhost::ApplicationController before_action { params[:id] && @post = Post.find(params[:id]) } def index @posts = Post.order(:created_at => :desc) end def new @post = Post.new end def create @post = Post.new(safe_params) set_publication_date if @post.save redirect_to edit_post_path(@post) else render 'new' end end def update set_publication_date if @post.update(safe_params) redirect_to edit_post_path(@post) else render 'edit' end end def destroy @post.destroy redirect_to posts_path end private def safe_params params.require(:post).permit(:title, :slug, :markdown) end def set_publication_date if params[:publish] && @post.draft? @post.published_at = Time.now elsif params[:unpublish] && @post.published? @post.published_at = nil end end end end <file_sep>/lib/rhost/view_helpers.rb module Rhost module ViewHelpers end end <file_sep>/rhost.gemspec require_relative "./lib/rhost/version" Gem::Specification.new do |s| s.name = "rhost" s.version = Rhost::VERSION s.authors = ["<NAME>"] s.email = ["<EMAIL>"] s.homepage = "http://adamcooke.io" s.licenses = ['MIT'] s.summary = "A complete blogging engine for Rails applications" s.description = "A complete engine for managing blog posts and presenting them in your Rails applications." s.files = Dir["{app,config,db,doc,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.md"] s.add_dependency "rails", ">= 4.2.3", "< 5.0" s.add_dependency "jquery-rails", ">= 4.0", "< 5" s.add_dependency "coffee-rails", ">= 4.1", "< 5" s.add_dependency "sass-rails", ">= 5.0", "< 6" s.add_dependency "uglifier", ">= 2.7", "< 3" s.add_development_dependency 'sqlite3', '~> 1.3' end <file_sep>/app/models/rhost/post.rb module Rhost class Post < ActiveRecord::Base validates :title, :presence => true validates :slug, :presence => true, :uniqueness => true before_validation do if self.title.is_a?(String) && self.slug.blank? self.slug = self.title.parameterize end end def published? !!self.published_at end def draft? self.published_at.nil? end end end <file_sep>/lib/rhost/engine.rb module Rhost class Engine < Rails::Engine isolate_namespace Rhost initializer 'rhost.initialize' do |app| # # Add migrations from Rhost to the application # config.paths["db/migrate"].expanded.each do |expanded_path| app.config.paths["db/migrate"] << expanded_path end # # Load view helpers for the base application # ActiveSupport.on_load(:action_view) do require 'rhost/view_helpers' ActionView::Base.send :include, Rhost::ViewHelpers end end def self.mounted_path if route = Rails.application.routes.routes.select { |r| r.app == self or r.app.try(:app) == self }.first route.path.spec.to_s end end end end <file_sep>/README.md # Rhost Rhost will be a Rails blogging engine (inspired by Ghost). The engine will be installable into any Rails application and provide an interface to write and manage blog posts. The Rails application can then use the provided helpers & tools to create the public-facing views for their blog. It's ideal when you need to integrate your blog with your existing websites & views. This is still a work in progress so please check back again soon. <file_sep>/test/config/routes.rb Rails.application.routes.draw do mount Rhost::Engine => "/rhost" end <file_sep>/db/migrate/20150710152542_create_posts.rb class CreatePosts < ActiveRecord::Migration def change create_table :rhost_posts do |t| t.string :uuid, :title, :slug, :status t.text :markdown, :html t.boolean :featured, :default => false t.boolean :page, :default => false t.string :meta_title, :meta_description t.integer :author_id t.string :author_type t.datetime :published_at t.timestamps null: false end end end <file_sep>/app/helpers/rhost/application_helper.rb module Rhost module ApplicationHelper def rhost_version "Rhost #{Rhost::VERSION}" end def form_errors_for(form, field, options = {}) if errors = form.object.errors[field] content_tag :p, errors.to_sentence, {:style => "color:red"}.merge(options) end end end end <file_sep>/config/routes.rb Rhost::Engine.routes.draw do resources :posts, :except => [:show] root :to => 'posts#index' end <file_sep>/lib/rhost.rb require 'coffee-rails' require 'sass-rails' require 'jquery-rails' require 'rhost/engine'
ad0565df36156f9e1c867d5e952de172fc0d9d92
[ "Markdown", "Ruby" ]
11
Ruby
wfschmitt/rhost
ab57ebca04d47a76d444d067d39e57e7d42e94ef
048ed18290639eda9e7cfeb0b0b344a7b3856e90
refs/heads/master
<file_sep><?php require_once dirname(__FILE__) . '/../config.php'; try { $dbh = new PDO("mysql:host=$config->servername;dbname=$config->dbname", $config->dbusername, $config->dbpassword); // set the PDO error mode to exception $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e) { echo "Connection to database failed: " . $e->getMessage(); } ?> <file_sep><?php include('view/header.php'); require_once 'view/allArticles.php'; ?> <div class="col-md-12"> <div class="col-md-8"> <?php printAllArticles(2); ?> </div> <div class="col-md-4"> <div class="row"> <div class="haut-article"> </div> <div class="box-droite"> <h4>Dernières recettes</h4> <a><i class="fa fa-caret-right" aria-hidden="true"></i> Raviolis chinois grillés à la poêle</a><br /> <a><i class="fa fa-caret-right" aria-hidden="true"></i> Linguines à la ratatouille</a><br /> <a><i class="fa fa-caret-right" aria-hidden="true"></i> Farfalles au pesto et à la banane flambée</a><br /> </div> <div class="separator-box-droite"> </div> <div class="box-droite"> <h4>Recettes populaires</h4> <a><i class="fa fa-caret-right" aria-hidden="true"></i> Raviolis chinois grillés à la poêle</a><br /> <a><i class="fa fa-caret-right" aria-hidden="true"></i> Linguines à la ratatouille</a><br /> <a><i class="fa fa-caret-right" aria-hidden="true"></i> Farfalles au pesto et à la banane flambée</a><br /> </div> </div> </div> </div> <?php include('view/footer.php');?> </div> </body> </html><file_sep><?php require dirname(__FILE__) . '/../controller/classes.php'; $main = new Menu('main'); //opening menu tags echo '<nav class="navbar navbar-default"> <div class="container-fluid"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="' . $config->getSiteURL() . '"><i class="fa fa-home fa-5" aria-hidden="true"></i></a> </div><!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse"> <ul class="nav navbar-nav">'; //creating menu links foreach($main->getItems() as $menuItem){ if ($config->mod_rewrite){ if(isset($_GET['idArticle']) && $_GET['idArticle'] == $menuItem->getArticleID()) echo '<li class="active"><a href="' .$config->getSiteURL() . '/article/' . $menuItem->getArticleID() . '">' . $menuItem->getTitle() . '</a></li>'; else echo '<li><a href="' . $config->getSiteURL() . '/article/' . $menuItem->getArticleID() . '">' . $menuItem->getTitle() . '</a></li>'; } else{ if(isset($_GET['idArticle']) && $_GET['idArticle'] == $menuItem->getArticleID()) echo '<li class="active"><a href="' . $config->getSiteURL() . '/controller/get_article.php?idArticle=' . $menuItem->getArticleID() . '">' . $menuItem->getTitle() . '</a></li>'; else echo '<li><a href="' . $config->getSiteURL() . '/controller/get_article.php?idArticle=' . $menuItem->getArticleID() . '">' . $menuItem->getTitle() . '</a></li>'; } } //closing tags echo '</ul> </div><!-- /.navbar-collapse --> </div><!-- /.container-fluid --> </nav>'; ?> <!-- <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></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 role="separator" class="divider"></li> <li><a href="#">Separated link</a></li> <li role="separator" class="divider"></li> <li><a href="#">One more separated link</a></li> </ul> </li> --><file_sep><?php class Config{ private static $config = null; public $sitename = 'Disco nunu'; public $subTitle = 'Simple CMS for blogs'; public $salt = <PASSWORD>'; public $folder = 'disconunu'; public $servername = "localhost"; public $dbusername = "root"; public $dbpassword = ""; public $dbname = "disconunu"; public $mod_rewrite = true; private function __construct(){ } public static function getConfig(){ if(is_null(self::$config)) self::$config = new Config(); return self::$config; } public function getSiteURL(){ return "http://".$_SERVER['SERVER_NAME'] . '/' . $this->folder; } } $config = Config::getConfig(); ?> <file_sep><?php require_once 'classes.php'; require_once dirname(__FILE__) . '/../config.php'; include(dirname(__FILE__) . '/../view/header.php'); function loadMenu($menuTitle){ return new Menu($menuTitle); } ?> <file_sep><?php function selectArticle($idArticle){ require 'dbConnect.php'; $stmt = $dbh->prepare("SELECT * FROM ARTICLE WHERE id = :idArticle"); $stmt->bindParam(':idArticle', $idArticle); if($stmt->execute()){ return $stmt->fetch(PDO::FETCH_ASSOC); } else{ return false; } } function selectArticleRange($limit1,$limit2){ require 'dbConnect.php'; $stmt = $dbh->prepare("SELECT * FROM ARTICLE ORDER BY id DESC LIMIT " . $limit1 . " , " . $limit2); if($stmt->execute()){ return $stmt->fetchAll(PDO::FETCH_ASSOC); } else{ return false; } } function selectAllArticles(){ require 'dbConnect.php'; $stmt = $dbh->prepare("SELECT * FROM ARTICLE"); $stmt->bindParam(':idArticle', $idArticle); if($stmt->execute()){ return $stmt->fetchAll(PDO::FETCH_ASSOC); } else{ return false; } } function selectUser($idUser){ require 'dbConnect.php'; $stmt = $dbh->prepare("SELECT username,email FROM USER WHERE UserID = :idUser"); $stmt->bindParam(':idUser', $idUser); if($stmt->execute()){ return $stmt->fetch(PDO::FETCH_ASSOC); } else{ return false; } } function selectMenu($menuName){ require 'dbConnect.php'; $stmt = $dbh->prepare("SELECT * FROM MENU WHERE title = :menuName"); $stmt->bindParam(':menuName', $menuName); if($stmt->execute()){ return $stmt->fetch(PDO::FETCH_ASSOC); } else{ return false; } } function selectMenuItems($idMenu){ require 'dbConnect.php'; $stmt = $dbh->prepare("SELECT * FROM MENUITEM WHERE idMenu = :idMenu"); $stmt->bindParam(':idMenu', $idMenu); if($stmt->execute()){ return $stmt->fetchAll(PDO::FETCH_ASSOC); } else{ return false; } } ?><file_sep> <?php function salt() { require_once dirname(__FILE__) . '/../config.php'; return $config->salt; } function insertNewUser($username,$password,$email){ require 'dbConnect.php'; $password = hash('sha256',salt() . $password); $stmt = $dbh->prepare("INSERT INTO USER (username, password, email) VALUES (:username, :password, :email)"); $stmt->bindParam(':username', $username); $stmt->bindParam(':password', $password); $stmt->bindParam(':email', $email); return $stmt->execute(); } function insertNewArticle($title,$content,$userID,$links){ require 'dbConnect.php'; $stmt = $dbh->prepare("INSERT INTO ARTICLE (title, content, dateArticle , userID, links) VALUES (:title, :content, NOW() , :userID, :links)"); $stmt->bindParam(':title', $title); $stmt->bindParam(':content', $content); $stmt->bindParam(':userID', $userID); $stmt->bindParam(':links', $links); return $stmt->execute(); } ?><file_sep><?php require_once dirname(__FILE__) . '/../config.php'; ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <link rel="stylesheet" href="<?php echo $config->getSiteURL(); ?>/css/style.css"> <link rel="stylesheet" href="<?php echo $config->getSiteURL(); ?>/css/font-awesome.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> </head> <div class="custom-container"> <div id="header"> <div style="float:left;"> <a href="<?php echo $config->getSiteURL();?>"><img src="<?php echo $config->getSiteURL();?>/images/logo.jpg" id="logo" alt="logo"/></a> </div> <div class="titles"> <h1><?php echo $config->sitename . ' '; ?>administrator page</h1> </div> </div> <body> </body> </div> </html><file_sep><?php function getArticlePage($limit1,$limit2){ $tab = selectArticleRange($limit1,$limit2); $tabObjects = array(); for($i=0;$i<count($tab);$i++){ $tabObjects[$i] = new Article($tab[$i]['id']); } return $tabObjects; } function numberOfArticles(){ return count(selectAllArticles()); } ?> <file_sep>Disconunu Little CMS for blogs, simple websites WORK IN PROGRESS<file_sep><?php require_once dirname(__FILE__) . '/../config.php'; include(dirname(__FILE__) . '/../view/header.php'); ?> <body> <?php function showArticle($idArticle){ $article = new Article($idArticle); if($article->getTitle() != ''){ //opening tags echo '<html> <div class="col-md-12"> <div class="col-md-9"> <div class="row"> <div class="haut-article"> </div>'; //show article title echo '<h2>' . $article->getTitle() . '</h2>'; //print content $toShow = preg_split('/<cut-article>/', $article->getContent()); for($i=0;$i<count($toShow);$i++){ echo $toShow[$i]; } //print article footer echo '<div class="bas-article" style=" margin-top: 10px; padding: 0; background-color: black; width: 100%; height: 50px;"> <p style="color:white; float:right;margin:10px">By ' . $article->getAuthor() . ' | ' . $article->getArticleDate() . '</p>'; //closing tags echo '</div></div></div> <div class="col-md-3"> <div class="row"> </div> </div> </div></html>'; } else{ echo '<div style="height:500px;"><h3>Error: couldn\'t find requested article!</h3></div>'; } } if(isset($_GET['idArticle'])){ $idArticle = $_GET['idArticle']; showArticle($idArticle); } else{ echo "You should choose an article to read."; } include(dirname(__FILE__) . '/../view/footer.php'); ?> </body> </html><file_sep><?php function printAllArticles($articlePerPage){ require_once 'view/article.php'; require_once dirname(__FILE__) . '/../controller/getArticlePage.php'; $total = numberOfArticles(); $numberOfPages = ceil($total/$articlePerPage); if(isset($_GET['page'])) $page = $_GET['page']; else $page = 1; $limit1 = ($page - 1) * $articlePerPage; $articles = getArticlePage($limit1,$articlePerPage); foreach ($articles as $article) { printArticle($article->getIdArticle()); } echo '<ul class="pagination">'; for ($j = 1 ; $j <= $numberOfPages ; $j++) { if($j == $page) echo '<li class="active"><a href="?page=' . $j . '">' . $j . '</a></li>'; else echo '<li><a href="?page=' . $j . '">' . $j . '</a></li>'; } echo '</ul>'; } ?><file_sep><?php require dirname(__FILE__) . '/../dbUtil/select.php'; require dirname(__FILE__) . '/../dbUtil/insert.php'; class User { private $userID; private $username; private $email; function __construct($UserID){ $data = selectUser($UserID); $this->userID = $UserID; $this->username = $data['username']; $this->email= $data['email']; } public function getUserID() { return $this->userID; } public function getUsername() { return $this->username; } public function getEmail() { return $this->email; } } class Article { private $idArticle; private $title; private $content; private $dateArticle; private $author; private $links; function __construct($idArticle){ $data = selectArticle($idArticle); $this->idArticle = $idArticle; $this->title = $data['title']; $this->content= $data['content']; $this->dateArticle = $data['dateArticle']; $author = new User($data['userID']); $this->author = $author->getUsername(); $this->links = $data['links']; } public function getIdArticle() { return $this->idArticle; } public function getTitle() { return $this->title; } public function getContent() { return $this->content; } public function getArticleDate() { return $this->dateArticle; } public function getAuthor() { return $this->author; } public function getLinks() { return $this->links; } } class MenuItem { private $id; private $idMenu; private $title; private $idArticle; function __construct($data){ $this->id = $data['id']; $this->idMenu = $data['idMenu']; $this->title = $data['title']; $this->idArticle = $data['idArticle']; } public function getID() { return $this->id; } public function getMenuID() { return $this->idMenu; } public function getTitle() { return $this->title; } public function getArticleID() { return $this->idArticle; } public function getArticle() { return selectArticle($this->idArticle); } } class Menu { private $id; private $title; private $items = array(); function __construct($title){ $data = selectMenu($title); $this->idMenu = $data['id']; $this->title = $title; $items = selectMenuItems($this->idMenu); for($i=0;$i<count($items);$i++){ $this->items[$i] = new MenuItem($items[$i]); } } public function getID() { return $this->idMenu; } public function getTitle() { return $this->title; } public function getItems() { return $this->items; } } ?><file_sep><?php //require dirname(__FILE__) . '/../config.php'; /* Prints an article */ function printArticle($idArticle){ $config = Config::getConfig(); $article = new Article($idArticle); //opening tags echo '<html> <div class="row"> <div class="haut-article"> </div>'; //show article title echo '<h2>' . $article->getTitle() . '</h2>'; //print content $toShow = preg_split('/<cut-article>/', $article->getContent()); echo $toShow[0]; //print 'read more' button if($config->mod_rewrite == false) $address = $config->getSiteURL() . '/controller/get_article.php?idArticle='. $idArticle; else $address = $config->getSiteURL() . '/article/'. $idArticle; echo '<a href="'. $address. '"><button type="button" class="btn btn-secondary">Read more</button></a>'; //print article footer echo '<div class="bas-article" style=" margin-top: 10px; padding: 0; background-color: black; width: 100%; height: 50px;"> <p style="color:white; float:right;margin:10px">By ' . $article->getAuthor() . ' | ' . $article->getArticleDate() . '</p>'; //closing tags echo '</div></div></html>'; } ?>
e2b0073e5d5ea83550fd2d9e2c96bdf7406d89cf
[ "Markdown", "PHP" ]
14
PHP
daymwk/disconunu
36a976ca313e87334cf8862b150ef0d7ab59db10
a7d4f9ed362bb0622f5ec3ccb931a39c920a200f
refs/heads/master
<file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link id="easyuiTheme" rel="stylesheet" type="text/css" href="__PUBLIC__/themes/bootstrap/easyui.css" /> <link rel="stylesheet" type="text/css" href="__PUBLIC__/themes/icon.css" /> <script type="text/javascript" src="__PUBLIC__/js/jquery-1.8.0.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/jquery.easyui.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/admin.js" charset="utf-8"></script> <!-- <script type="text/javascript" charset="utf-8"> var datagrid = $('#datagrid_user'); var isClickOk = true; function edit(id) { $.ajax({ url: '__APP__/User/getUserById', data: {id: id}, dataType: 'json', success: function (rows) { $('#_username').val(rows.name); $("input[name='member_id']").val(rows.member_id); $('#_phone_number').val(rows.phone_number); $('#_identity_card').val(rows.identity_card); } }); $('#editDlg').dialog('open').dialog('setTitle', '修改用户信息'); } function initpsw(num) { $('#_user_id').val(num); $('#initpswDlg').dialog('open').dialog('setTitle', '确定要重置密码?'); } function initpsw_ok() { $('#initpswForm').form('submit', { url: "__APP__/User/initPwd", dataType: 'json', onSubmit: function () { $.messager.alert('操作提示', '重置后的密码是:<PASSWORD>', 'info'); return true; } }); $('#datagrid_user').datagrid('reload'); $('#initpswDlg').dialog('close'); } function exportData() { var rows = $('#datagrid_user').datagrid('getChecked'); var ids = []; for (var i = 0; i < rows.length; i++) { ids.push(rows[i].user_id); } var str = ids.join(','); var href = '__APP__/User/export?idstr='+str; location.href=href; } function _search() { $('#datagrid_user').datagrid('loadData', { total: 0, rows: [] }); $('#datagrid_user').datagrid('load', dj.serializeObject($('#searchForm'))); } function cleanSearch() { $('#datagrid_user').datagrid('load', {}); $('#searchForm input').val(''); } function edit_ok() { $.messager.defaults = { ok: "确定", cancel: "取消" }; $.messager.confirm('Confirm', '您确定修改?', function (r) { if (r) { $('#editForm').form('submit', { url: "__APP__/User/edit", dataType: 'json', onSubmit: function () { if ($('#editForm').form('validate')) { datagrid.datagrid('loadData', { total: 0, rows: [] }); datagrid.datagrid('load'); $.messager.alert('操作提示', '修改信息成功!', 'info'); return true; } else { $.messager.alert('操作提示', '信息填写不完整!', 'error'); return false; } } }); $('#datagrid_user').datagrid('reload'); $('#editDlg').dialog('close'); } }); } function formatOper(val,row,index){ var str= '<a href="javascript:void(0);" onclick="edit('+row.member_id+')">修改</a>'; return str; } function formatsex(val,row,index){ return (row.sex==1)?"女":"男"; } function formatphone(val,row,index){ return row.user_id; } function formataddress(val,row,index){ return row.address1+''+row.address2+''+row.address3; } </script> --> <title>后台管理</title> </head> <style> .stage{ position:absolute; top:0; bottom:0; left:0; right:0; background:rgba(0,0,0,0.2); display:none; } .form{ position:absolute; top:50%; left:50%; transform: translate(-50%,-50%); padding:10px; background: #fff; } .close{ position:absolute; cursor: pointer; top:0; right:0; transform: translate(50%,-50%); width:14px; height:14px; text-align: center; line-height:14px; border-radius: 100%; background:gray; } </style> <body> <div> <form action="<?php echo U('User/index');?>" method="get"> <div style="float:left"> <select name="chaxun" id=""> <option value="1">所属酒店</option> <option value="2">昵称</option> <option value="3">备注</option> </select> </div> <div style="float:left"> <input type="text" name="hotel" > </div> <div> <input type="submit" value="搜索"> </div> </form> </div> <div> <table border="1" cellpadding="1" cellspacing="1" width="100%" align="center"> <thead> <tr> <th >ID</th> <th>所属酒店</th> <th>昵称</th> <th>姓名</th> <th>性别</th> <th >手机号</th> <th >拥有积分</th> <th>备注</th> </tr> <?php if(is_array($list)): $i = 0; $__LIST__ = $list;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$vo): $mod = ($i % 2 );++$i;?><tr> <td ><?php echo ($vo["id"]); ?></td> <td><?php echo ($vo["hn"]); ?></td> <td><?php echo ($vo["nickname"]); ?></td> <td><?php echo ($vo["un"]); ?></td> <td> <?php if($vo["gender"] == male): ?>男 <?php elseif($vo["gender"] == female): ?>女 <?php else: ?>保密<?php endif; ?> </td> <td ><?php echo ($vo["up"]); ?></td> <td ><?php echo ($vo["score"]); ?></td> <td><center> <?php echo ($vo["mark"]); ?> <button class="btn" onclick="edit(<?php echo ($vo["id"]); ?>)">修改</button></center> <div class="stage com_<?php echo ($vo["id"]); ?>"> <div class="form"> <form action="<?php echo U('User/editcom');?>?id=<?php echo ($vo["id"]); ?>" method="post"> 修改备注:<input type="text" name="comment"> <input type="submit" value="修改"> </form> <span class="close">&times;</span> </div> </div> </td> </tr><?php endforeach; endif; else: echo "" ;endif; ?> </thead> </table> <!-- <div id="toolbar" style="padding:5px;"> <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-print" plain="true" onclick="">导出csv</a> <form id="searchForm" style="display:inline-block;*display:inline;zoom:1;"> <input name="search" placeholder="标题或内容" data-options="prompt:'请输入搜索内容',searcher:''" class="easyui-validatebox textbox" style="width: 180px; vertical-align: middle;" /> <input name="hiddenid" id="hiddenid" type="hidden" /> <a href="javascript:void(0);" class="easyui-linkbutton" plain="true" onclick="_search();">搜索</a> </form> </div> --> </div> <!-- 修改用户信息的表单 --> <!-- <div id="editDlg" class="easyui-dialog" style="width: 450px; height: 300px; padding: 10px 20px" closed="true" buttons="#editDlgBtn" data-options="modal:true" > <form id="editForm" method="post"> <input type="hidden" name="user_id" value="" /> <table width="350" border="0"> <tr> <td width="150" align="right"> 用户姓名: </td> <td width="250"> <input name="name" id="_username" class="easyui-validatebox textbox"/> </td> <input type="hidden" name="member_id" id="_memberid" /> </tr> <tr> <td align="right"> 手机号: </td> <td> <input name="phone_number" id="_phone_number" class="easyui-validatebox textbox" /> </td> </tr> --> <!-- <tr> <td align="right"> 身份证号: </td> <td> <input name="identity_card" id="_identity_card" class="easyui-validatebox textbox" /> </td> </tr> --> <!-- </table> </form> </div> --> <!-- 密码重置 --> <!-- 修改用户信息的表单 --> <!-- <div id="initpswDlg" class="easyui-dialog" style="width: 400px; height: 300px; padding: 10px 20px" closed="true" buttons="#initpswDlgBtn" data-options="modal:true"> <form id="initpswForm" method="post"> <input type="hidden" name="user_id" id="_user_id" value="" /> 重置密码为:<PASSWORD>. </form> </div> --> <!-- 修改户信息的按钮,被Jquery设置,当没被调用的时候不显示 --> <!-- <div id="initpswDlgBtn"> <a href="#" class="easyui-linkbutton" iconcls="icon-ok" onclick="initpsw_ok()">确认</a> <a href="#" class="easyui-linkbutton" iconcls="icon-cut" onclick="javascript:$('#initpswDlg').dialog('close')">取消</a> </div> --> <!-- 修改户信息的按钮,被Jquery设置,当没被调用的时候不显示 --> <!-- <div id="editDlgBtn"> <a href="#" id="addSaveBooktimecode" class="easyui-linkbutton" iconcls="icon-ok" onclick="edit_ok()">确认</a> <a href="#" class="easyui-linkbutton" iconcls="icon-cut" onclick="javascript:$('#editDlg').dialog('close')">取消</a> </div> --> <script type="text/javascript"> function edit(id) { $('.com_'+id).fadeIn('1000'); } $('.close').click(function(){ $('.stage').fadeOut('1000'); }) </script> </body> </html><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html> <html lang="en"> <head> <script type="text/javascript" src="__PUBLIC__/js/jquery-1.8.0.min.js"></script> <meta charset="UTF-8"> <title>Document</title> </head> <body> <h1>我的订单</h1> <div > <form action="<?php echo U('Store/orders');?>" method="get"> <div style="float:left"> <select name="chaxun" id=""> <option value="1">订单编号</option> <option value="2">联系电话</option> </select> </div> <div style="float:left"> <input type="text" name="find" > </div> <div> <input type="submit" value="搜索"> </div> </form> </div> <table border="1" cellpadding="1" cellspacing="1" width="100%" align="center"> <tr> <th>订单编号</th> <th>商品图片</th> <th>数量</th> <th>单价</th> <th>联系人</th> <th>联系电话</th> <th>联系地址</th> <th>总计</th> <th>订单状态</th> </tr> <?php if(is_array($list)): $i = 0; $__LIST__ = $list;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$vo): $mod = ($i % 2 );++$i;?><tr> <td><?php echo ($vo["ordernum"]); ?></td> <td><img src="<?php echo ($vo["iname"]); ?>" alt=""></td> <td><?php echo ($vo["qty"]); ?></td> <td><?php echo ($vo["price"]); ?></td> <td><?php echo ($vo["lname"]); ?></td> <td><?php echo ($vo["phone"]); ?></td> <td><?php echo ($vo["address"]); ?></td> <td><?php echo ($vo["allprice"]); ?></td> <td> <?php if($vo["status"] == 0): ?>未发货 <?php elseif($vo["status"] == 1): ?>已发货 <?php elseif($vo["status"] == 2): ?>已完成 <?php else: ?>已失效<?php endif; ?> </td> </tr><?php endforeach; endif; else: echo "" ;endif; ?> </table> </body> </html><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE HTML> <html> <head> <meta http-equiv=Content-Type content="text/html; charset=utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content=""> <meta http-equiv="description" content="easyui示例项目"> <title>住了酒店后台管理系统</title> <link id="easyuiTheme" rel="stylesheet" type="text/css" href="__PUBLIC__/themes/bootstrap/easyui.css"> <link rel="stylesheet" type="text/css" href="__PUBLIC__/themes/icon.css"> <script type="text/javascript" src="__PUBLIC__/js/jquery-1.8.0.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/jquery.easyui.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/admin.js" charset="utf-8"></script> </head> <body class="easyui-layout"> <div data-options="region:'north',href:'__APP__/Layout/north',border : false," id="top_image" style="height:65px;overflow:hidden;"></div> <div id="layoutMenu" data-options="region:'west',title:'主菜单',href:'__APP__/Layout/west',iconCls:'icon-dhcd'" split="true" style="width:210px;overflow: hidden;"></div> <div data-options="region:'center',title:'',href:'__APP__/Layout/center'" style="overflow: hidden;"></div> </body> </html><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html> <html lang="en"> <head> <script type="text/javascript" src="__PUBLIC__/js/jquery-1.8.0.min.js"></script> <script type="text/javascript" src="__PUBLIC__/layer/layer.js"></script> <style> #stage{ display:none; position:fixed; top:0; bottom:0; left:0; right:0; background:rgba(0,0,0,0.5); } #forms{ position:absolute; top:50%; left:50%; transform: translate(-50%,-50%); padding:10px; background: #fff; } #close{ position:absolute; cursor: pointer; top:0; right:0; transform: translate(50%,-50%); width:14px; height:14px; text-align: center; line-height:14px; border-radius: 100%; background:rgba(0,250,250,0.7) } </style> <meta charset="UTF-8"> <link href="__PUBLIC__/css/store.css" rel="stylesheet" type="text/css" /> <title>Document</title> </head> <body> <div > <table border="1" width="100%" align="center" class="normalTab"> <tr> <th>联系姓名</th> <th>联系电话</th> <th>地址详情</th> <th>备注</th> <th>操作</th> </tr> <?php if(is_array($list)): $i = 0; $__LIST__ = $list;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$vo): $mod = ($i % 2 );++$i;?><tr> <td><?php echo ($vo["linkman"]); ?></td> <td><?php echo ($vo["phone"]); ?></td> <td><?php echo ($vo["address"]); ?></td> <td><?php echo ($vo["remark"]); ?></td> <td> <?php if(($vo["operate"] == 2)): ?><button class="deny" bh="<?php echo ($vo["id"]); ?>">默认地址</button> <?php else: ?><button class="deny" bh="<?php echo ($vo["id"]); ?>">普通地址</button><?php endif; ?> </td> </tr><?php endforeach; endif; else: echo "" ;endif; ?> </table> <center> <div id="stage"> <div id="forms"> <form action="<?php echo U('Store/addaddress');?>" method="post" onsubmit="return check()" > <table> <tr> <th>联系姓名:</th> <td><input type="text" class="name" name="name" /> <span class="lm"></span> </td> </tr> <tr> <th>联系电话:</th> <td><input type="text" class="phone" name="phone" /> <span class="lxd"></span> </td> </tr> <tr> <th>送货地址:</th> <td> <input type="text" class="address" name="address" placeholder="请填写详细地址"> <span class="xxadd"></span> </td> </tr> <tr> <th>备&nbsp;&nbsp;注:</th> <td><input type="text" placeholder="如公司、家" class="weier" name="mark"> </td> </tr> </table> <div class="bottom"> <input type="submit" value="立即添加" class="checkInSuccesss"> </div> <span id="close">&times;</span> </form> </div> </div> <div> <button id="btn">添加地址</button> </div> </center> </div> <script> $('#btn').click(function(){ $('#stage').css('display','block') }) $('#close').click(function(){ $('#stage').css('display','none') }) $('.jiesuan').click(function(){ layer.msg('已生成订单'); window.location.href="<?php echo U('Store/orders');?>" }) function check() { if ($('.name').val() == '') { layer.msg('请输入姓名'); setTimeout(function(){ $('.name').focus(); }); return false; }else if($('.phone').val()==''){ layer.msg('请输入电话'); setTimeout(function(){ $('.phone').focus(); }); return false; }else if($('.address').val() == ''){ layer.msg('请输入地址'); setTimeout(function(){ $('.address').focus(); }); return false; } } $('.deny').click(function(){ if ($(this).text() == '普通地址') { $(this).text('默认地址'); window.location.reload(); }else{ $(this).text('普通地址'); window.location.reload(); } var id = $(this).attr('bh'); $.ajax({ type:'get', url:"<?php echo U('Store/mo');?>"+'?id='+id, }) }); </script> </body> </html><file_sep><?php class OrderAction extends Action { public function index() { // var_dump($_SESSION); // var_dump($_REQUEST); $what = array(); if ($_REQUEST['chaxun'] == 1) { if (!empty($_REQUEST['hotel'])) { $what['users.phone_number'] = array('like','%'.$_REQUEST['hotel'].'%'); } } $list = M('orders')->join('users ON users.id = orders.user_id')->join('hotels ON hotels.id = orders.hotel_id')->join('rooms ON rooms.id = orders.room_id')->where($what)->field('orders.*,users.nickname,hotels.name,rooms.display_name,rooms.price,users.phone_number,users.score')->select(); // var_dump($list); $this->assign('list',$list); $this->display('order'); } public function surecheck() { if (IS_AJAX) { $id = $_POST['id']; if (empty($id)) { $this->error('失败,请重试'); exit; }else{ $one = $_POST['id']; $two = M('orders')->field('user_id,hotel_id')->where(array('id'=>$one))->find();//查询会员的id和入住酒店的id $tt = $two['user_id']; $three = M('users')->field('score,hotel_id')->where(array("id"=>$tt))->find();//查询会员的积分和所属酒店的id if ($two['hotel_id'] == $three['hotel_id']) //如果相等说明A会员在A酒店 { $aa['score'] = $three['score'] +10;//那么A会员积分加10 $bb = M('users')->where(array('id'=>$tt))->save($aa);//用setinc方法不起作用 $cc = M('hotel_admin')->field('credit')->where(array('hotel_id'=>$three['hotel_id']))->find();//查询所属酒店的积分 $dd['credit'] = $cc['credit']-10;//把酒店积分减去10 $ee = M('hotel_admin')->where(array('hotel_id'=>$three['hotel_id']))->save($dd); }else{//如果不相等说明A会员在B酒店,B酒店减30个积分,a酒店加10积分,不管A会员在哪个酒店入住都会加10积分 $ff['score'] = $three['score'] +10;//那么A会员积分加10 $gg = M('users')->where(array('id'=>$tt))->save($ff);//用setinc方法不起作用 $hh = M('hotel_admin')->field('credit')->where(array('hotel_id'=>$three['hotel_id']))->find();//查询会员所属酒店的积分然后加10 $ii['credit'] = $hh['credit']+10; $jj = M('hotel_admin')->where(array('hotel_id'=>$three['hotel_id']))->save($ii); $kk = M('hotel_admin')->field('credit')->where(array('hotel_id'=>$two['hotel_id']))->find();//查询会员入住酒店的积分然后减30 $ll['credit'] = $kk['credit']-30; $mm = M('hotel_admin')->where(array('hotel_id'=>$two['hotel_id']))->save($ll); //往score表增加记录 $nn['score_num'] = 30; $nn['hotelId'] = $three['hotel_id']; $nn['contributor'] = $two['hotel_id']; $nn['score_date'] = date('Y-m-d H:i:s'); $oo = M('score')->add($nn); } $data['id'] = $id; $data['check_in'] = 1; $row = M('orders')->data($data)->save(); if ($row !== false) { $this->ajaxReturn($row); }else{ $this->ajaxReturn('2'); } } } } public function delorder() { $id = $_POST['id']; $row = M('orders')->field('order_status')->where(array('id'=>$id))->find(); if ($row['order_status'] == 'finshed') { $result = M('orders')->where(array('id'=>$id))->delete(); if ($result !== false && $result !== 0) { $this->ajaxReturn($result); }else{ $this->ajaxReturn('false'); } }else{ $this->ajaxReturn('false'); } } public function mask() { if (IS_POST) { if (empty($_POST['mask'])) { $this->error('请输入备注信息'); } $data['id'] = $_GET['id']; $data['remark'] = $_POST['mask']; $row = M('orders')->data($data)->save(); if ($row !== false) { $this->success('修改成功'); }else{ $this->error('修改失败'); } }else{ $this->redirect(U('Order/index')); } } //退款订单 public function refund() { $what = "(r.order_id = o.id and o.user_id = u.id)"; if ($_REQUEST['chaxun'] == 1) { if (!empty($_REQUEST['hotel'])) { $what.="and (u.phone_number like '%".$_REQUEST['hotel']."%')"; } } $list = M('refunds')->field('r.*,u.nickname,u.phone_number')->table('refunds r,users u,orders o')->where($what)->select(); // var_dump($list); $this->assign('list',$list); $this->display(); } public function tuikuan() { if (IS_AJAX) { $id = $_POST['id']; $one = M('refunds')->field('status')->where(array('id'=>$id))->find(); if ($one['status'] != 'agree') { $this->ajaxReturn('-1'); }else{ $data['status'] = 'refund'; $two = M('refunds')->where(array('id'=>$id))->save($data); if ($two !== false) { $pup['refund_id'] = $id; $pup['status'] = 'refund'; $pup['created_at'] = date('Y-m-d H:i:s'); $pup['updated_at'] = date('Y-m-d H:i:s'); $bob = M('refund_records')->add($pup); $this->ajaxReturn($two); }else{ $this->ajaxReturn('-1'); } } } } public function agree() { if (IS_AJAX) { $id = $_POST['id']; $one = M('refunds')->field('order_id')->where(array('id'=>$id))->find(); if ($one) { $two = M('orders')->field('order_status,refund')->where(array('id'=>$one['order_id']))->find(); if ($two['order_status'] == 'success' && $two['refund'] == 1) { $data['status'] = 'agree'; $three = M('refunds')->where(array('id'=>$id))->save($data); if ($three !== false) { $pup['refund_id'] = $id; $pup['status'] = 'agree'; $pup['created_at'] = date('Y-m-d H:i:s'); $pup['updated_at'] = date('Y-m-d H:i:s'); $bob = M('refund_records')->add($pup); $this->ajaxReturn($three); }else{ $this->ajaxReturn('-2'); } }else{ $this->ajaxReturn('-1'); } }else{ $this->ajaxReturn('false'); } } } public function refuse() { if (IS_AJAX) { $id = $_POST['id']; $one = M('refunds')->field('status')->where(array('id'=>$id))->find(); if ($one['status'] !== 'apply') { $this->ajaxReturn('-1'); }else{ $data['status'] = 'reject'; $two = M('refunds')->where(array('id'=>$id))->save($data); if ($two !== false) { $pup['refund_id'] = $id; $pup['status'] = 'reject'; $pup['created_at'] = date('Y-m-d H:i:s'); $pup['updated_at'] = date('Y-m-d H:i:s'); $bob = M('refund_records')->add($pup); $this->ajaxReturn($two); }else{ $this->ajaxReturn('-2'); } } } } public function editcom() { if (IS_POST) { if (empty($_POST['mask'])) { $this->error('请输入备注'); exit; } $id=$_GET['id']; $data['remark'] = $_POST['mask']; $row = M('refunds')->where(array('id'=>$id))->save($data); if ($row !== false) { $this->success('修改成功'); }else{ $this->error('修改失败'); } }else{ $this->redirect(U('Order/refund')); } } //未入住订单 public function onorder() { // var_dump($_REQUEST); $what = "(check_in = '0')"; if ($_REQUEST['chaxun'] == 1) { if (!empty($_REQUEST['hotel'])) { $what.="and (users.phone_number like '%".$_REQUEST['hotel']."%')"; } } $list = M('orders')->join('users ON users.id = orders.user_id')->join('hotels ON hotels.id = orders.hotel_id')->join('rooms ON rooms.id = orders.room_id')->where($what)->field('orders.*,users.nickname,hotels.name,rooms.display_name,rooms.price,users.phone_number')->select(); // var_dump($list); $this->assign('list',$list); $this->display(); } //已入住订单 public function payorder() { $what = "(check_in = '1')"; if ($_REQUEST['chaxun'] == 1) { if (!empty($_REQUEST['hotel'])) { $what.="and (users.phone_number like '%".$_REQUEST['hotel']."%')"; } } $list = M('orders')->join('users ON users.id = orders.user_id')->join('hotels ON hotels.id = orders.hotel_id')->join('rooms ON rooms.id = orders.room_id')->where($what)->field('orders.*,users.nickname,hotels.name,rooms.display_name,rooms.price,users.phone_number')->select(); $this->assign('list',$list); $this->display(); } public function getAllOrder() { $o =D("Order_rooms"); $u = D("Hotel_admin"); $m = D("members"); import("ORG.Util.Page"); //导入分页类 $page=$_POST["page"]? $_POST["page"] :1; $rows=$_POST["rows"]? $_POST["rows"] :30; $sort=$_POST["sort"]? $_POST["sort"] :'reservation_id'; $order=$_POST["order"] ? $_POST["order"] :'desc'; $search=$_POST["search"]; $flag =$_POST["flag"]; $start_time = $_POST["start_time"]; $end_time = $_POST["end_time"]; $type = $_GET["type"]; //var_dump($type); //if($sort=='orderid') $sort='reservation_id'; //if($sort=='user_id') $sort='order_rooms.member_id'; //dump($order); if($search!=null&&$search!=""){ //$condition['invalid_flag'] = 1; $condition['m.phone_number']=array('like','%'.$search.'%'); // $condition['m.member_name']=array('like','%'.$search.'%'); // $condition['_logic']='OR'; } if($start_time!=null&&$start_time!=""){ $condition['start_time']=array('like','%'.$start_time.'%'); } if($end_time!=null&&$end_time!=""){ $condition['end_time']=array('like','%'.$end_time.'%'); } /*if(!empty($type)){ if($type=='payorder'){ $condition['state']='已付款'; }elseif($type=='onorder'){ $condition['state']='配送中'; } $order = 'DESC'; }*/ // if($search!=null&&$search!=""){ // $arr[]=" u.user_id like '%".$search."%' OR u.user_name like '%".$search."%'"; // } // if($state!=null&&$state!=""){ // $arr[]= " state = '".$state."' "; // } // if($sdate!=null&&$sdate!=""){ // $arr[]= " send_date like '%".$sdate."%'"; // } // if($orderdate!=null&&$orderdate!=""){ // $arr[]= " order_date like '%".$orderdate."%'"; // } // if(!empty($type)){ // if($type=='payorder'){ // $arr[]= " state = '已付款' AND check_flag = 1"; // }elseif($type=='onorder'){ // $arr[]= " state = '配送中' AND check_flag = 1"; // } // } // $where['_string'] = implode(' AND ', $arr); // $where['invalid_flag'] = 1; // $w['invalid_flag'] = 1; //var_dump($where['_string']); $username=$_SESSION["username"]; $con['name'] = $username; //$admin_id = $_SESSION["admin_id"]; //$con['admin_id'] = $admin_id; if($_SESSION["permission"] == 0){ $HotelId = $u->where($con)->getField('hotel_id'); $condition['order_rooms.hotel_id'] = $HotelId; } if(!empty($type)){ if($type=='payorder'){ $condition['flag']='1'; }else if($type=='onorder'){ $condition['flag']='0'; } $order = 'DESC'; }else{ if($flag!=null&&$flag!=""){ $condition['flag']=$flag; }else{ $condition['flag'] = array('neq',2); } } $count = $o->join('Members m ON m.member_id = Order_rooms.member_id')->join('Hotels h ON h.hotel_id = Order_rooms.hotel_id')->join('rooms r ON r.type_id = order_rooms.type_id')->where($condition)->count(); $list = $o->join('Members m ON m.member_id = Order_rooms.member_id')->join('Hotels h ON h.hotel_id = Order_rooms.hotel_id')->join('rooms r ON r.type_id = order_rooms.type_id')->where($condition)->page($page,$rows)->order(array($sort=>$order))->select(); // if(!empty($where['_string'])){ // $count = $n->relation(true)->join('df_user u ON u.user_id = df_order.user_id')->where($where)->count(); //计算总数 // $list = $n->relation(true) // ->join('df_user u ON u.user_id = df_order.user_id') // ->where($where)->page($page,$rows)->order(array($sort=>$order))->select(); // }else{ // $count = $n->relation(true)->join('df_user u ON u.user_id = df_order.user_id')->where($w)->count(); //计算总数 // $list = $n->relation(true) // ->join('df_user u ON u.user_id = df_order.user_id') // ->page($page,$rows)->order(array($sort=>$order))->where($w)->select(); // } //echo $n->getLastSql(); //var_dump($_GET); $result['total'] = $count; $result['rows'] = $list; exit(json_encode($result)); } // public function getAllOrder() { // $n =D("Order_rooms"); // import("ORG.Util.Page"); //导入分页类 // $page=$_POST["page"]? $_POST["page"] :1; // $rows=$_POST["rows"]? $_POST["rows"] :30; // $sort=$_POST["sort"]? $_POST["sort"] :'order_id'; // $order=$_POST["order"] ? $_POST["order"] :'desc'; // $search=$_POST["search"]; // $state =$_POST["state"]; // $sdate = $_POST["sdate"]; // $orderdate = $_POST["orderdate"]; // $type = $_GET["type"]; // //var_dump($type); // if($sort=='orderid') $sort='reservation_id'; // if($sort=='user_id') $sort='order_rooms.member_id'; // /* //dump($order); // if($search!=null&&$search!=""){ // $condition['invalid_flag'] = 1; // $condition['u.user_id']=array('like','%'.$search.'%'); // $condition['u.user_name']=array('like','%'.$search.'%'); // $condition['_logic']='OR'; // } // if($state!=null&&$state!=""){ // $condition['state']=$state; // } // if($sdate!=null&&$sdate!=""){ // $condition['send_date']=array('like','%'.$sdate.'%'); // } // if($orderdate!=null&&$orderdate!=""){ // $condition['order_date']=array('like','%'.$orderdate.'%'); // } // if(!empty($type)){ // if($type=='payorder'){ // $condition['state']='已付款'; // }elseif($type=='onorder'){ // $condition['state']='配送中'; // } // $order = 'DESC'; // }*/ // if($search!=null&&$search!=""){ // $arr[]=" u.user_id like '%".$search."%' OR u.user_name like '%".$search."%'"; // } // if($state!=null&&$state!=""){ // $arr[]= " state = '".$state."' "; // } // if($sdate!=null&&$sdate!=""){ // $arr[]= " send_date like '%".$sdate."%'"; // } // if($orderdate!=null&&$orderdate!=""){ // $arr[]= " order_date like '%".$orderdate."%'"; // } // if(!empty($type)){ // if($type=='payorder'){ // $arr[]= " state = '已付款' AND check_flag = 1"; // }elseif($type=='onorder'){ // $arr[]= " state = '配送中' AND check_flag = 1"; // } // } // $where['_string'] = implode(' AND ', $arr); // $where['invalid_flag'] = 1; // $w['invalid_flag'] = 1; // //var_dump($where['_string']); // if(!empty($where['_string'])){ // $count = $n->relation(true)->join('df_user u ON u.user_id = df_order.user_id')->where($where)->count(); //计算总数 // $list = $n->relation(true) // ->join('df_user u ON u.user_id = df_order.user_id') // ->where($where)->page($page,$rows)->order(array($sort=>$order))->select(); // }else{ // $count = $n->relation(true)->join('df_user u ON u.user_id = df_order.user_id')->where($w)->count(); //计算总数 // $list = $n->relation(true) // ->join('df_user u ON u.user_id = df_order.user_id') // ->page($page,$rows)->order(array($sort=>$order))->where($w)->select(); // } // //echo $n->getLastSql(); // //var_dump($_GET); // $result['total'] = $count; // $result['rows'] = $list; // exit(json_encode($result)); // } // public function payorder(){ // $this->display('payorder'); // } // public function onorder(){ // $this->display('onorder'); // } public function getOrderById() { $o = D("Order_rooms"); $reservationId = $_POST['id']; $condition['order_rooms.reservation_id']=array('EQ',$_POST['id']); $list = $o->join('members m ON m.member_id = order_rooms.member_id') ->join('hotels h ON h.hotel_id = order_rooms.hotel_id') ->join('rooms r ON r.type_id = order_rooms.type_id') ->where($condition)->find(); //echo $d->getLastSql(); exit(json_encode($list)); //输出json数据 } //批量处理 public function batch(){ $n = D("order_rooms"); $m = D("Members"); $h = D("Hotel_admin"); $s = D("Score"); //$type= $_POST['type']; //$ids = $_POST['ids']; $map['reservation_id'] = $_POST['id']; $r_id = $map['reservation_id']; $data['flag'] = 1; $data['trade_status'] = 1; $paydate=date('Y-m-d H:i:s'); $data['paid_at'] = $paydate; $list = $n->where($map)->data($data)->save(); $MemberId = $n->where($map)->getField('member_id'); $HotelId = $n->where($map)->getField('hotel_id'); $username=$_SESSION["username"]; $condition['name'] = $username; //$admin_id = $_SESSION["admin_id"]; //$condition['admin_id'] = $admin_id; $admin_id = $h->where($condition)->getField('admin_id'); $h_con['admin_id'] = $admin_id; $h_credit = $h->where($h_con)->getField('credit'); $con['member_id'] = $MemberId; $VipId = $m->where($con)->getField('vip_id'); $m_score = $m->where($con)->getField('score'); $mdata['score'] = $m_score + 10; $h_con2['hotel_id'] = $VipId; $h_credit2 = $h->where($h_con2)->getField('credit'); $hdata2['credit'] = $h_credit2 + 10; //批量订单确认 // if($type=='confirm'){ // $sql = "update order_rooms set flag = 1 where reservation_id in( ".$ids." )"; // //批量订单处理 // } //echo $sql;exit; //$vo = $n->execute($sql); if ($list) { if($HotelId == $VipId){ $hdata['credit'] = $h_credit - 10; $m_result = $m->where($con)->data($mdata)->save(); $h_result = $h->where($h_con)->data($hdata)->save(); $s_con['hotelId'] = $HotelId; $s_con['contributor'] = $VipId; $s_con['score_num'] = 10; $scdate=date('Y-m-d H:i:s'); $s_con['score_date'] = $scdate; if($s->create($s_con)){ $s_reslut = $s->add(); } } else{ $hdata['credit'] = $h_credit - 30; $m_result = $m->where($con)->data($mdata)->save(); $h_result = $h->where($h_con)->data($hdata)->save(); $h_result2 = $h->where($h_con2)->data($hdata2)->save(); $s_con['hotelId'] = $HotelId; $s_con['contributor'] = $VipId; $s_con['score_num'] = 30; $scdate=date('Y-m-d H:i:s'); $s_con['score_date'] = $scdate; if($s->create($s_con)){ $s_reslut = $s->add(); } } $this->ajaxReturn($_POST,'接单成功!',1); } else { $this->ajaxReturn($_POST,'接单失败!',3); } } // 更新数据 public function edit(){ //在ThinkPHP中使用save方法更新数据库,并且也支持连贯操作的使用 $Form = D("Order_rooms"); $vo = $Form->create($_POST); if ($vo) { $list = $Form->save($vo); //var_dump($vo); $this->ajaxReturn($_POST,'更新成功!',1); } else { $this->ajaxReturn($_POST,$Form->getError(),3); } } // 删除数据 public function delete() { //在ThinkPHP中使用delete方法删除数据库中的记录。同样可以使用连贯操作进行删除操作。 if (!empty ($_POST['ids'])) { $d = M("Order_rooms"); $condition['reservation_id']=array('in',$_POST['ids']); //$condition['check_flag'] = 1; $condition2['reservation_id']=array('in',$_POST['ids']); //删除item //$im->where($condition)->delete(); $data['flag'] = 2; $result = $d->where($condition)->data($data)->save(); //删除order时,admin的count会变 /* if($result>0){ $asql = 'update df_admin set count = count -'.$result; $a->execute($asql); } */ /* delete方法可以用于删除单个或者多个数据,主要取决于删除条件,也就是where方法的参数, 也可以用order和limit方法来限制要删除的个数,例如: 删除所有状态为0的5 个用户数据 按照创建时间排序 $Form->where('status=0')->order('create_time')->limit('5')->delete(); 本列子没有where条件 传入的是主键值就行了 */ if (false !== $result) { $this->ajaxReturn($_POST,'删除订单成功!',1); } else { $this->ajaxReturn($_POST,'删除出错!',1); } } else { $this->ajaxReturn($_POST,'删除项不存在!',1); } //$this->redirect('index'); } // 导出csv public function export() { $d = D("Order"); $im = D("item"); $str = $_GET['idstr']; if(empty($str)){ $list = $d->select(); $list = $d->join("df_user u ON u.user_id = df_order.user_id")->select(); }else{ $ids = explode(',', $str); $condition['order_id']=array('in',$ids); $list = $d->join("df_user u ON u.user_id = df_order.user_id") ->where($condition)->select(); } $datastr = '订单编号,买家姓名,买家手机号,送货地址,送货时间,交易状态'; $datastr = mb_convert_encoding($datastr,'gbk','utf-8'); $datastr.="\n"; if($list){ foreach($list as $order){ $icondition['order_id']=array('EQ',$order['order_id']); $items = $im->join("df_fruit f ON f.fruit_id = df_item.fruit_id") ->where($icondition)->select(); $name = mb_convert_encoding($order['user_name'],'gbk','utf-8'); //var_dump($name); $address = $order['address1']."".$order['address2']."".$order['address3']; $address = mb_convert_encoding($address,'gbk','utf-8'); $state = mb_convert_encoding($order['state'],'gbk','utf-8'); $datastr.=$order['order_id'].",".$name.",".$order['user_id'] .",".$address.",".$order['send_date'].",".$state; $datastr.="\n"; if($items){ $datastr.=' '.','; foreach($items as $item){ $fruit_name = $item['fruit_name']; $unit = $item['unit']; $number = $item['number']; $fruit_name = mb_convert_encoding($fruit_name,'gbk','utf-8'); $unit = mb_convert_encoding($unit,'gbk','utf-8'); $datastr.=$fruit_name."".$number."".$unit."; "; } $datastr.="\n"; $tot = ' '.','.'订单总价格:'.$order['total_price']; $tot = mb_convert_encoding($tot,'gbk','utf-8'); $datastr.=$tot."\n\n\n"; } } } //exit(); ob_clean(); //$datastr = @iconv("UTF-8", "GBK//IGNORE", $datastr); //$datastr = @iconv("GBK", "UTF-8//IGNORE", $datastr); //$datastr = mb_convert_encoding($datastr,'gbk','utf-8'); //var_dump($list); $filename = date("Ymd",time()).".csv"; header("Content-Type: application/vnd.ms-excel; charset=gbk"); //header("Content-type:text/csv"); header("Content-Disposition:attachment;filename=".$filename); header('Cache-Control:must-revalidate,post-check=0,pre-check=0'); header('Expires:0'); header('Pragma:public'); echo $datastr; } } ?><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link id="easyuiTheme" rel="stylesheet" type="text/css" href="__PUBLIC__/themes/bootstrap/easyui.css" /> <link rel="stylesheet" type="text/css" href="__PUBLIC__/themes/icon.css" /> <script type="text/javascript" src="__PUBLIC__/js/jquery-1.8.0.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/jquery.easyui.min.js"></script> <script type="text/javascript" src="__PUBLIC__/layer/layer.js"></script> <script type="text/javascript" src="__PUBLIC__/js/admin.js" charset="utf-8"></script> <title>后台管理</title> </head> <style> .stage{ position:absolute; top:0; bottom:0; left:0; right:0; background:rgba(0,0,0,0.2); display:none; } .form{ position:absolute; top:50%; left:50%; transform: translate(-50%,-50%); padding:10px; background: #fff; } .stages{ position:absolute; top:0; bottom:0; left:0; right:0; background:rgba(0,0,0,0.2); display:none; } .forms{ position:absolute; top:50%; left:50%; transform: translate(-50%,-50%); padding:10px; background: #fff; } .close{ position:absolute; cursor: pointer; top:0; right:0; transform: translate(50%,-50%); width:14px; height:14px; text-align: center; line-height:14px; border-radius: 100%; background:gray; } .closes{ position:absolute; cursor: pointer; top:0; right:0; transform: translate(50%,-50%); width:14px; height:14px; text-align: center; line-height:14px; border-radius: 100%; background:gray; } </style> <body> <div > <form action="<?php echo U('Order/index');?>" method="get"> <div style="float:left"> <select name="chaxun" id=""> <option value="1">电话</option> </select> </div> <div style="float:left"> <input type="text" name="hotel" > </div> <div> <input type="submit" value="搜索"> </div> </form> </div> <table border="1" cellpadding="1" cellspacing="1" width="100%" align="center"> <thead> <tr> <th >ID</th> <th>用户</th> <th>电话</th> <th>积分</th> <th >入住时间</th> <th >离店时间</th> <th >支付状态</th> <th >支付方式</th> <th >是否入住</th> <th >详情</th> <th>操作</th> </tr> <?php if(is_array($list)): $i = 0; $__LIST__ = $list;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$vo): $mod = ($i % 2 );++$i;?><tr> <td ><?php echo ($vo["oid"]); ?></td> <td><?php echo ($vo["uname"]); ?></td> <td><?php echo ($vo["up"]); ?></td> <td><?php echo ($vo["score"]); ?></td> <td ><?php echo ($vo["ost"]); ?></td> <td ><?php echo ($vo["oed"]); ?></td> <td > <?php if($vo["ops"] == paid): ?>已支付 <?php elseif($vo["ops"] == not_paid): ?>未支付 <?php else: ?>支付失败<?php endif; ?> </td> <td > <?php if($vo["opm"] == wechat): ?>微信 <?php elseif($vo["opm"] == score): ?>金币 <?php else: ?>到店支付<?php endif; ?> </td> <td > <?php if($vo["check_in"] == 0): ?>未入住 <?php else: ?>入住<?php endif; ?> </td> <td > <button class="qita" onclick="other(<?php echo ($vo["oid"]); ?>)">详情</button> <div class="stage qita_<?php echo ($vo["oid"]); ?>" > <div class="form"> <table border="1" > <tr> <th width="80">酒店</th> <th width="80">房型</th> <th width="80">房间单价</th> <th width="80">订房数量</th> <th width="80">订单状态</th> <th width="80">最晚到店时间</th> <th width="80">微信支付的openid</th> <th width="80">特殊要求</th> <th width="80">备注</th> </tr> <tr> <td width="80"><?php echo ($vo["hn"]); ?></td> <td width="80"><?php echo ($vo["rdn"]); ?></td> <td width="80"><?php echo ($vo["rp"]); ?></td> <td width="80"><?php echo ($vo["orn"]); ?></td> <td width="80"> <?php if($vo["oos"] == wait_for_pay): ?>等待付款 <?php elseif($vo["oos"] == wait_for_confirm): ?>等待确认 <?php elseif($vo["oos"] == success): ?>成功 <?php elseif($vo["oos"] == cancle): ?>取消 <?php else: ?>完成<?php endif; ?> </td> <td width="80"><?php echo ($vo["olat"]); ?></td> <td width="80"><?php echo ($vo["ooi"]); ?></td> <td width="80"><?php echo ($vo["osr"]); ?></td> <td width="80"><?php echo ($vo["ork"]); ?></td> </tr> </table> <span class="close">&times;</span> <div> </div> </td> <td> <button class="mask" onclick="remark(<?php echo ($vo["oid"]); ?>)">备注</button> <div class="stages mask_<?php echo ($vo["oid"]); ?>"> <div class="forms"> <form action="<?php echo U('Order/mask');?>?id=<?php echo ($vo["oid"]); ?>" method="post"> <input type="text" name="mask"> <input type="submit"> </form> <span class="closes">&times;</span> </div> </div> <!-- <button class="check" bh="<?php echo ($vo["oid"]); ?>">确认入住</button> --> <button>改签</button> <button class="del" bh="<?php echo ($vo["oid"]); ?>">删除</button> <!-- <a href="<?php echo U('Order/delorder');?>?id=<?php echo ($vo["id"]); ?>" onclick="if(confirm('确定要删除吗')==false)return false">删除</a> --> </td> </tr><?php endforeach; endif; else: echo "" ;endif; ?> </thead> </table> <script> function other(id) { $('.qita_'+id).fadeIn('1000'); } function remark(id) { $('.mask_'+id).fadeIn('1000'); } $('.close').click(function(){ $('.stage').fadeOut('1000'); }) $('.closes').click(function(){ $('.stages').fadeOut('1000'); }) $('.check').click(function(){ var id = $(this).attr('bh'); $.ajax({ type:'post', url:"<?php echo U('Order/surecheck');?>", data:{'id':id}, success:function(data){ if (data > 0) { alert('已确认入住'); window.location.reload(); }else{ alert('不可重复确认'); } } }) }) $('.del').click(function(){ var id=$(this).attr('bh'); if (confirm('确定要删除吗') == true) { $.ajax({ type:'post', url:"<?php echo U('Order/delorder');?>", dataType:"json", data:{'id':id}, success:function(data){ if (data > 0) { alert('已删除'); window.location.reload(); }else{ alert('订单未完成无法删除'); } } }) } }) </script> <!-- <script language="JavaScript"> function re_fresh() { window.location.reload(); } setTimeout('re_fresh()',5000); //指定5秒刷新一次 </script> --> </body> </html><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <a href="<?php echo U('Store/index');?>" style="float:right;background:#f00">继续购物</a> <a href="<?php echo U('Store/alldel');?>" style="float:right;background:#E9C341">清空购物车</a> <a href="" style="float:right;background:#04D900">总计¥<?php echo ($count); ?> </a> <a href="<?php echo U('Store/dobuy');?>" style="float:right;background:#1596FA">立刻结算</a> <table border="1" cellpadding="1" cellspacing="1" width="100%" align="center"> <tr> <th>商品</th> <th>商品名</th> <th>商品价格</th> <th>购买数量</th> <th>小计</th> <th>操作</th> </tr> <?php if(is_array($list)): $i = 0; $__LIST__ = $list;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$vo): $mod = ($i % 2 );++$i;?><tr> <td><img src="<?php echo ($vo["iname"]); ?>" alt=""></td> <td><a href="<?php echo U('Store/gooddetail');?>?id=<?php echo ($vo["iid"]); ?>"><?php echo ($vo["gname"]); ?></a></td> <td><?php echo ($vo["price"]); ?></td> <td><?php echo ($vo["qty"]); ?></td> <td><?php echo ($vo[price] * $vo[qty]); ?></td> <td><a href="<?php echo U('Store/del');?>?id=<?php echo ($vo["id"]); ?>">删除</a></td> </tr><?php endforeach; endif; else: echo "" ;endif; ?> </table> </body> </html><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link id="easyuiTheme" rel="stylesheet" type="text/css" href="__PUBLIC__/themes/bootstrap/easyui.css" /> <link rel="stylesheet" type="text/css" href="__PUBLIC__/themes/icon.css" /> <script type="text/javascript" src="__PUBLIC__/js/jquery-1.8.0.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/jquery.easyui.min.js"></script> <script type="text/javascript" src="__PUBLIC__/layer/layer.js"></script> <script type="text/javascript" src="__PUBLIC__/js/admin.js" charset="utf-8"></script> <title>后台管理</title> </head> <body> <div > <!-- <form action="<?php echo U('Order/index');?>" method="get"> <div style="float:left"> <select name="chaxun" id=""> <option value="1">电话</option> </select> </div> <div style="float:left"> <input type="text" name="hotel" > </div> <div> <input type="submit" value="搜索"> </div> </form> --> </div> <table border="1" cellpadding="1" cellspacing="1" width="100%" align="center"> <thead> <tr> <th >用户名</th> <th>酒店号码</th> <th>酒店名称</th> <th >操作</th> </tr> <?php if(is_array($list)): $i = 0; $__LIST__ = $list;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$vo): $mod = ($i % 2 );++$i;?><tr> <td ><?php echo ($vo["han"]); ?></td> <td><?php echo ($vo["at"]); ?></td> <td><?php echo ($vo["hn"]); ?></td> <td > <a href="<?php echo U('Auser/edit');?>?id=<?php echo ($vo["aid"]); ?>">编辑</a> <a href="<?php echo U('Auser/del');?>?id=<?php echo ($vo["aid"]); ?>">删除</a> </td> </tr><?php endforeach; endif; else: echo "" ;endif; ?> </thead> </table> <script> </script> </body> </html><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html> <html> <head> <link href="__PUBLIC__/css/style.css" rel="stylesheet" type="text/css" /> <script language="JavaScript" src="__PUBLIC__/js/jquery.js"></script> <script src="__PUBLIC__/js/cloud.js" type="text/javascript"></script> <script language="javascript"> $(function () { $('.loginbox').css({ 'position': 'absolute', 'left': ($(window).width() - 692) / 2 }); $(window).resize(function () { $('.loginbox').css({ 'position': 'absolute', 'left': ($(window).width() - 692) / 2 }); }); $("#username").focus(); }); </script> </head> <body style="background-color: #1c77ac; background-image: url(../../images/light.png); background-repeat: no-repeat; background-position: center top; overflow: hidden;"> <div id="mainBody"> <div id="cloud1" class="cloud"> </div> <div id="cloud2" class="cloud"> </div> </div> <div class="logintop"> <span>欢迎登录后台管理系统</span> </div> <div class="loginbody"> <span class="systemlogo"></span> <div class="loginbox"> <form action="__APP__/Index/checklogin" method="post"> <ul> <li> <input type="text" name="username" id="username" class="loginuser" value="" placeholder="用户名" /></li> <li> <input name="password" type="<PASSWORD>" class="loginpwd" value="" placeholder="密码" /></li> <li> <input type="submit" class="loginbtn" value="登录" /></li> </ul> </form> </div> </div> <div class="loginbm"> 版权所有 2014 </div> </body> </html><file_sep><?php define('HOST','172.16.31.10'); //用户名 define('USER','zlm'); //密码 define('PWD','<PASSWORD>'); //库名 define('DB','zlm'); //字符集 define('CHAR','utf8'); $link = mysqli_connect(HOST,USER,PWD,DB) or die('数据库没有连接成功!'); mysqli_set_charset($link,CHAR); $_body = file_get_contents('php://input'); $body = json_decode($_body, true); $fname = $body['fname']; $roomId = $body['roomId']; $url = "http://img.zlmhotel.com/room/$fname"; $sql = "UPDATE display_pictures SET `url`='$url' WHERE `relate_id`='$roomId' and type='room'"; $result = mysqli_query($link,$sql); if ($result && mysqli_affected_rows($link)>0) { ECHO '{"success":true}'; }else{ ECHO '{"success":false}'; }<file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="description" content="Tsys管理系统"> <title>后台管理</title> <link id="easyuiTheme" rel="stylesheet" type="text/css" href="__PUBLIC__/themes/bootstrap/easyui.css"> <link rel="stylesheet" type="text/css" href="__PUBLIC__/themes/icon.css"> <script type="text/javascript" src="__PUBLIC__/js/jquery-1.8.0.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/jquery.easyui.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/admin.js" charset="utf-8"></script> </head> <link rel="stylesheet" type="text/css" href="__PUBLIC__/uploadify/uploadify.css" /> <script src="__PUBLIC__/uploadify/jquery.uploadify.min.js" type="text/javascript"></script> <script src="__PUBLIC__/layer/layer.js" type="text/javascript"></script> <script type="text/javascript" src="http://api.map.baidu.com/api?v=1.3"></script> <body> <div class="easyui-panel" fit="true"> <center><form action="<?php echo U('Auser/doadd');?>" id="editForm" method="post" enctype="multipart/form-data" onsubmit = "return check()"> <table width="780" border="0"> <tr style="height: 50px;"> <td width="100" align="right"> 用户名: </td> <td width="250"> <input name="name" style="width: 250px" id="name"/> <span class="uname"></span> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 酒店名称: </td> <td width="250"> <input name="hotelname" style="width: 250px" id="hotelname"/> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right" > 密码: </td> <td width="250"> <input type="password" name="pwd" style="width: 250px" id="pwd"/> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 酒店电话: </td> <td width="250"> <input name="phone" style="width: 250px" id="phone"/> </td> </tr> </table> <div style="text-align:left;padding:20px;"> <center><input type="submit" value="添加"></center> <!-- <a href="" class="easyui-linkbutton" style="width:80px" ">修改</a> --> </div> </form></center> </script> <script type="text/javascript"> function check() { if ($('#name').val() == '') { layer.msg('请输入用户名'); setTimeout(function(){ $('#name').focus(); }); return false; } if ($('.uname').text() == '×') { layer.msg('用户名有误'); setTimeout(function(){ $('#name').focus(); }); return false; } if($('#hotelname').val() == ''){ layer.msg('请输入酒店名称'); setTimeout(function(){ $('#hotelname').focus(); }); return false; } if($('#pwd').val() == ''){ layer.msg('请输入密码'); setTimeout(function() { $('#pwd').focus(); }); return false; } if($('#phone').val() == ''){ layer.msg('请输入酒店电话'); setTimeout(function(){ $('#phone').focus(); }); return false; } } $('#name').blur(function(){ var username = $(this).val(); $.ajax({ type:"post", url:"<?php echo U('Auser/username');?>", data:{'name':username}, dataType:"json", success:function(data){ if (data == 1) { layer.msg('用户名已存在'); $('.uname').attr({style:"font-size:20px;color:red"}); $('.uname').text('×'); }else{ $('.uname').text(''); } } }) }) </script> </body><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <h1>商品管理</h1> <div > <form action="<?php echo U('Adminstore/goods');?>" method="get"> <div style="float:left"> <select name="chaxun" id=""> <option value="1">商品名</option> </select> </div> <div style="float:left"> <input type="text" name="find" > </div> <div> <input type="submit" value="搜索"> </div> </form> </div> <table border="1" cellpadding="1" cellspacing="1" width="100%" align="center"> <tr> <th>id</th> <th>商品名</th> <th style="width:60px">商品信息</th> <th>所属分类</th> <th>价格</th> <th>库存</th> <th>操作</th> </tr> <?php if(is_array($list)): $i = 0; $__LIST__ = $list;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$vo): $mod = ($i % 2 );++$i;?><tr> <td><?php echo ($vo["gid"]); ?></td> <td ><img src="<?php echo ($vo["iname"]); ?>" alt="">&nbsp;&nbsp;<?php echo ($vo["gname"]); ?></td> <td style="width:60px"><?php echo ($vo["msg"]); ?></td> <td><?php echo ($vo["cname"]); ?></td> <td><?php echo ($vo["price"]); ?></td> <td><?php echo ($vo["stock"]); ?></td> <td><a href="<?php echo U('Adminstore/editgoods');?>?id=<?php echo ($vo["gid"]); ?>">商品信息编辑</a> <a href="<?php echo U('Adminstore/editimgs');?>?id=<?php echo ($vo["gid"]); ?>">图片信息编辑</a> </td> </tr><?php endforeach; endif; else: echo "" ;endif; ?> </table> </body> </html><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="description" content="Tsys管理系统"> <title>后台管理</title> <link id="easyuiTheme" rel="stylesheet" type="text/css" href="__PUBLIC__/themes/bootstrap/easyui.css"> <link rel="stylesheet" type="text/css" href="__PUBLIC__/themes/icon.css"> <script type="text/javascript" src="__PUBLIC__/js/jquery-1.8.0.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/jquery.easyui.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/admin.js" charset="utf-8"></script> </head> <link rel="stylesheet" type="text/css" href="__PUBLIC__/uploadify/uploadify.css" /> <script src="__PUBLIC__/uploadify/jquery.uploadify.min.js" type="text/javascript"></script> <script src="__PUBLIC__/layer/layer.js" type="text/javascript"></script> <script type="text/javascript" src="http://api.map.baidu.com/api?v=1.3"></script> <body> <div class="easyui-panel" fit="true"> <center><form action="<?php echo U('Adminstore/doeditgoods');?>" id="editForm" method="post" enctype="multipart/form-data" onsubmit = "return check()"> <table width="780" border="0"> <input type="hidden" name="id" value="<?php echo ($list['id']); ?>"> <tr style="height: 50px;"> <td width="100" align="right"> 商品名: </td> <td width="250"> <input name="name" style="width: 250px" id="name" value="<?php echo ($list['gname']); ?>" /> <!-- <span class="uname"></span> --> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 商品分类: </td> <td width="250"> <select name="cate_id" id=""> <?php if (!empty($cate)): ?> <?php foreach ($cate as $val): ?> <option value="<?php echo $val['id'] ?>"<?php echo $val['id'] == $list['cate_id']? 'selected':''; ?>><?php echo str_repeat('&nbsp;&nbsp;&nbsp;',substr_count($val['path'],',')).'|----'.$val['cname'] ?></option> <?php endforeach ?> <?php else: ?> <?php endif ?> <!-- <?php if(is_array($cate)): $i = 0; $__LIST__ = $cate;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$vo): $mod = ($i % 2 );++$i;?><option value="<?php echo ($vo["id"]); ?>" <?php if($list['cate_id'] == $vo['id']): ?>selected<?php endif; ?>><?php echo ($vo["cname"]); ?></option><?php endforeach; endif; else: echo "" ;endif; ?> --> </select> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 价格: </td> <td width="250"> <input name="price" style="width: 250px" value="<?php echo ($list['price']); ?>" /> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 库存: </td> <td width="250"> <input name="stock" style="width: 250px" value="<?php echo ($list['stock']); ?>" /> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 简介: </td> <td width="250"> <textarea name="msg" id="" cols="30" rows="10" style="width: 250px"><?php echo ($list["msg"]); ?></textarea> </td> </tr> </table> <div style="text-align:left;padding:20px;"> <center><input type="submit" value="修改"></center> <!-- <a href="" class="easyui-linkbutton" style="width:80px" ">修改</a> --> </div> </form></center> </script> <script type="text/javascript"> function check() { if ($('#name').val() == '') { layer.msg('请输入用户名'); setTimeout(function(){ $('#name').focus(); }); return false; } if ($('.uname').text() == '×') { layer.msg('用户名有误'); setTimeout(function(){ $('#name').focus(); }); return false; } if($('#hotelname').val() == ''){ layer.msg('请输入酒店名称'); setTimeout(function(){ $('#hotelname').focus(); }); return false; } if($('#pwd').val() == ''){ layer.msg('请输入密码'); setTimeout(function() { $('#pwd').focus(); }); return false; } if($('#phone').val() == ''){ layer.msg('请输入酒店电话'); setTimeout(function(){ $('#phone').focus(); }); return false; } } $('#name').blur(function(){ var username = $(this).val(); $.ajax({ type:"post", url:"<?php echo U('Auser/username');?>", data:{'name':username}, dataType:"json", success:function(data){ if (data == 1) { layer.msg('用户名已存在'); $('.uname').attr({style:"font-size:20px;color:red"}); $('.uname').text('×'); }else{ $('.uname').text(''); } } }) }) </script> </body><file_sep><?php if (!defined('THINK_PATH')) exit();?> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="description" content="Tsys管理系统"> <title>后台管理</title> <link id="easyuiTheme" rel="stylesheet" type="text/css" href="__PUBLIC__/themes/bootstrap/easyui.css"> <link rel="stylesheet" type="text/css" href="__PUBLIC__/themes/icon.css"> <script type="text/javascript" src="__PUBLIC__/js/jquery-1.8.0.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/jquery.easyui.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/admin.js" charset="utf-8"></script> </head> <link rel="stylesheet" type="text/css" href="__PUBLIC__/uploadify/uploadify.css" /> <script src="__PUBLIC__/uploadify/jquery.uploadify.min.js" type="text/javascript"></script> <head> <body> <style> .stage{ position:absolute; top:0; bottom:0; left:0; right:0; background:rgba(0,0,0,0.2); display:none; } .form{ position:absolute; top:50%; left:50%; transform: translate(-50%,-50%); padding:10px; background: #fff; } .close{ position:absolute; cursor: pointer; top:0; right:0; transform: translate(50%,-50%); width:14px; height:14px; text-align: center; line-height:14px; border-radius: 100%; background:gray; } </style> <table border="1" cellpadding="1" cellspacing="1" width="100%" align="center"> <thead> <tr> <th >ID</th> <th >酒店名称</th> <th >酒店星级</th> <th >酒店电话</th> <th >酒店地址</th> <th >酒店邮箱</th> <th>详情</th> <th>酒店图片</th> <th >操作</th> </tr> <tr> <th><?php echo ($list["id"]); ?></th> <th><?php echo ($list["name"]); ?></th> <th> <?php if(($list["grade"] == inn)): ?>酒馆 <?php elseif($list["grade"] == chain): ?>连锁酒店 <?php elseif($list["grade"] == theme): ?>主题酒店 <?php elseif($list["grade"] == three_star): ?>三星级 <?php elseif($list["grade"] == four_star): ?>四星级 <?php elseif($list["grade"] == five_star): ?>五星级 <?php else: ?> null<?php endif; ?> </th> <th><?php echo ($list["phone_number"]); ?></th> <th><?php echo ($list["address"]); ?></th> <th><?php echo ($list["email"]); ?></th> <th> <button class="qita" onclick="other(<?php echo ($list["id"]); ?>)">详情</button> <div class="stage qita_<?php echo ($list["id"]); ?>" > <div class="form"> <table border="1" cellpadding="1" cellspacing="1" width="100%" align="center"> <tr> <th width="80">地址经度</th> <th width="80">地址纬度</th> <th width="80">路线</th> <th >酒店介绍</th> <th width="80">改签退订规则</th> <!-- <th width="80">基础设施</th> --> </tr> <tr> <th width="80"><?php echo ($list["longitude"]); ?></th> <th width="80"><?php echo ($list["latitude"]); ?></th> <th width="80"><?php echo ($list["routes"]); ?></th> <th ><?php echo ($list["introduction"]); ?></th> <th width="80"><?php echo ($list["endorse_rules"]); ?></th> <!-- <th width="80">11</th> --> </tr> </table> <span class="close">&times;</span> <div> </div> </th> <th> <button class="btn" onclick="show(<?php echo ($list["id"]); ?>)">酒店图片</button> <div class="stage img_<?php echo ($list["id"]); ?>" > <div class="form"> <img src="/Public/image/hotel/<?php echo ($list["url"]); ?>" alt="" > <span class="close">&times;</span> <div> </div> </th> <th><a href="<?php echo U('Goods/edithotel');?>?id=<?php echo ($list["id"]); ?>" class="btn btn-danger">编辑信息</a> <a href="<?php echo U('Goods/edhotpicb');?>?id=<?php echo ($list["id"]); ?>" class="btn btn-danger">编辑图片</a> <a href="<?php echo U('Goods/infodel');?>?id=<?php echo ($list["id"]); ?>" class="btn btn-danger">删除</a> </th> </tr> </thead> </table> </div> <!-- <script type="text/javascript" src="__PUBLIC__/lhgdialog/lhgdialog.min.js"></script> --> <script type="text/javascript"> function show(id) { $('.img_'+id).fadeIn('1000'); } $('.close').click(function(){ $('.stage').fadeOut('1000'); }) function other(id) { $('.qita_'+id).fadeIn('1000'); } </script> </body> </html><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="description" content="Tsys管理系统"> <title>后台管理</title> <link id="easyuiTheme" rel="stylesheet" type="text/css" href="__PUBLIC__/themes/bootstrap/easyui.css"> <link rel="stylesheet" type="text/css" href="__PUBLIC__/themes/icon.css"> <script type="text/javascript" src="__PUBLIC__/js/jquery-1.8.0.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/jquery.easyui.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/admin.js" charset="utf-8"></script> </head> <link rel="stylesheet" type="text/css" href="__PUBLIC__/uploadify/uploadify.css" /> <script src="__PUBLIC__/uploadify/jquery.uploadify.min.js" type="text/javascript"></script> <script src="__PUBLIC__/layer/layer.js" type="text/javascript"></script> <script src="__PUBLIC__/js/ajaxfileupload.js" type="text/javascript"></script> <body> <div class="easyui-panel" fit="true"> <form action="<?php echo U('Goods/uploadify');?>" id="editForm" method="post" enctype="multipart/form-data" onsubmit="return check()"> <input name="type_id" type="hidden" value="<?php echo ($list["id"]); ?>"/> <table width="780" border="0"> <tr style="height: 50px;"> <td align="right"> 修改: </td> <td> <input id="picture" name="img" type="file"> <div id="up_image" class="image"> </div> </td> </tr> </table> <div style="text-align:left;padding:20px;"> <input type="submit" value="修改"> </div> </form> <!-- <form method="post" action="http://up.qiniu.com" enctype="multipart/form-data" class="upfile" onsubmit="return check()"> <input name="token" type="hidden" value="<?php echo ($uptoken); ?>"> <input name="file" type="file" id="picture"/> <input type="submit" name="修改"> </form> --> </div> <script type="text/javascript"> function check() { if($('#picture').val() == '') { layer.msg('请选择图片'); setTimeout(function(){ $('#picture').focus(); }); return false; }else{ return true; } } //上传图片 // $(document).on('change','#upfile',function(){ // $.ajaxFileUpload({ // url:'<?php echo U("Goods/ImgUpload");?>', // secureuri:false, // fileElementId:'upfile', // dataType: 'json', // type:'post', // data: { fileElementId: 'upfile'}, // success: function (data) { // $('#showimg').attr('src',data.upfile.url); // $('#imageurl').val(data.upfile.url); // }         // }) // }) </script> <!-- <script type="text/javascript" src="__PUBLIC__/lhgdialog/lhgdialog.min.js"></script> --> </body><file_sep><?php class CityAction extends Action { public function hot() { $area = M('areas'); $map['fullname'] =array('notlike',array('%省','%区'),'AND'); $map['level'] = array('exp','IN(1,2)'); $map['hot'] = 1; $list = $area->where($map)->select(); // var_dump($list); $this->assign('list',$list); $this->display(); } public function show() { $area = M('areas'); $map['fullname'] =array('notlike',array('%省','%区'),'AND'); $map['level'] = array('exp','IN(1,2)'); $map['fronted_show'] = 1; $list = $area->where($map)->select(); // var_dump($list); $this->assign('list',$list); $this->display(); } public function addred(){ $upid = empty($_GET['parent_code'])?"":$_GET['parent_code']; $model = M('areas'); $data = $model->where(array('parent_code'=>$upid))->select(); $this->ajaxReturn($data); } public function setup() { $sheng = $_POST['sheng']; $shi = $_POST['shi']; $qu = $_POST['qu']; if (!empty($sheng)) { $data['hot'] = 1; $edit = M('areas')->where(array("code"=>$qu))->save($data); } if (!empty($shi)) { $row['hot'] = 1; $one = M('areas')->where(array('code'=>$shi))->save($row); } if (!empty($qu)) { $result['hot'] = 1; $two = M('areas')->where(array('code'=>$sheng))->save($result); } $data['statue'] = 'fail'; $data['msg']='设置成功'; $this->ajaxReturn($data); } public function isshow() { $sheng = $_POST['sheng']; $shi = $_POST['shi']; $qu = $_POST['qu']; if (!empty($sheng)) { $data['fronted_show'] = 1; $edit = M('areas')->where(array("code"=>$qu))->save($data); } if (!empty($shi)) { $row['fronted_show'] = 1; $one = M('areas')->where(array('code'=>$shi))->save($row); } if (!empty($qu)) { $result['fronted_show'] = 1; $two = M('areas')->where(array('code'=>$sheng))->save($result); } } } ?><file_sep><?php // header('Content-Type: application/json'); // header('Cache-Control: no-store'); // require_once 'C:\xampp\htdocs\hotel\Public\path_to_sdk\autoload.php'; // use Qiniu\Auth; // use Qiniu\Storage\UploadManager; class GoodsAction extends Action { public function index() { if ($_SESSION['permission'] == 0) { $one = M('hotel_admin')->where(array('admin_id'=>$_SESSION['admin_id']))->field('hotel_id')->find(); // var_dump($one); // $what = "(rooms.hotel_id = ".$one['hotel_id']); $what = "('rooms.hotel_id'=".$one['hotel_id'].")"; if (!empty($_REQUEST['chaxun'])) { if ($_REQUEST['chaxun'] == 1) { $what .= "and (rooms.name like '%".$_REQUEST['hotel']."%')"; } if ($_REQUEST['chaxun'] == 2) { $what .= "and (rooms.display_name like '%".$_REQUEST['hotel']."%')"; } } $rooms = M('rooms'); // $list = $rooms->where($what)->select(); $list = $rooms ->join('display_pictures ON display_pictures.relate_id = rooms.id') ->where(array('hotel_id'=>$one['hotel_id'],'display_pictures.type'=>'room')) ->field('rooms.*,display_pictures.url')-> select(); // echo $rooms->getLastSql(); // var_dump($list); // var_dump($rooms->getLastSql()); $this->assign('list',$list); }else{ // var_dump($_SESSION); $what ="(display_pictures.type = 'rooms')"; if (!empty($_REQUEST['chaxun'])) { if ($_REQUEST['chaxun'] == 1) { $what .= "and (rooms.name like '%".$_REQUEST['hotel']."%')"; } if ($_REQUEST['chaxun'] == 2) { $what .= "and (rooms.display_name like '%".$_REQUEST['hotel']."%')"; } } $rooms = M('rooms'); $list = $rooms->join('display_pictures ON rooms.id=display_pictures.relate_id')->field('rooms.*,display_pictures.url')->where($what)->select(); // echo $list->getLastSql(); // var_dump($rooms->getLastSql()); $this->assign('list',$list); } $this->display('goods'); } // public function edrompic() // { // // var_dump($_GET); // $id = $_GET['id']; // $list = M('rooms')->where(array('id'=>$id))->field('id')->find(); // // var_dump($list); // $this->assign('list',$list); // $this->display(); // } // public function callback() // { // $_body = file_get_contents('php://input'); // $body = json_decode($_body, true); // $fname = $body['fname']; // $roomId = $body['roomId']; // //$hash = $body['hash']; // //$key = $body['key']; // //$resp = array('hash' => $hash,'key'=>$key); // //echo json_encode($resp); // ECHO '{"success":true}'; // } // public function edrompic() // { // $id = $_GET['id']; // $bucket = 'zlmimg'; //空间名称 这里修改,你七牛运空间名称 // $accessKey = '<KEY>'; //密钥 // $secretKey = '<KEY>';//密钥 // $auth = new Auth($accessKey, $secretKey); // $name=time().rand(); // $policy = array // ( // 'callbackUrl' => 'http://admin.zlmhotel.com/admin.php/Goods/callback', //修改数据库的页面,比如要把刚刚上传的写入你的数据库 // 'callbackBody' => '{"fname":"'.$name.'$(fname)","hotelId":"'.$id.'"}', // // 'callbackBody' => '{"fname":"'.$name.'","roomId":"'.$id.'"}', // 'callbackBodyType'=>'application/json', // //上传文件名 // 'saveKey' => "room/$name$(fname)" // ); // $token = $auth->uploadToken($bucket, null, 3600, $policy); // // $id = $_GET['id']; // // $list = M('display_pictures')->where(array('relate_id'=>$id,'type'=>'rooms'))->find(); // // var_dump($list); // // $this->assign('list',$list); // $this->assign('uptoken',$token); // $this->display(); // } public function getGoodsById() { $d = D("rooms"); $condition['hotel_id']=array('EQ',$_POST['id']); $list = $d->where($condition)->find(); exit(json_encode($list)); //输出json数据 } public function uploadify(){ $id = $_POST['type_id']; $mimo = M('display_pictures')->where(array('relate_id'=>$id))->find(); // var_dump($id); // exit; if (!empty($_FILES)) { import("ORG.Net.UploadFile"); $name=time().rand(); //设置上传图片的规则 $upload = new UploadFile();// 实例化上传类 $upload->maxSize = 3145728 ;// 设置附件上传大小 $upload->allowExts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型 $upload->savePath = './Public/image/room/';// 设置附件上传目录 // $upload->savePath ='.'.$upload_dir; $upload->saveRule = $name; //设置上传图片的规则 $upload->thumb = true; $upload->thumbMaxWidth = '300'; $upload->thumbMaxHeight = '200'; $upload->thumbRemoveOrigin = true; if(!$upload->upload()) {// 上传错误提示错误信息 //return false; echo $upload->getErrorMsg(); //echo $targetPath; }else{// 上传成功 获取上传文件信息 // $this->success('成功'); $info = $upload->getUploadFileInfo(); // echo $upload_dir.$info[0]["savename"]; $data['id'] = $mimo['id']; $data['type'] = 'rooms'; // $data['url'] = 'img.zlmhotel.com/image/hotel/'.$upload_dir.$info[0]["savename"]; $data['url'] = 'thumb_'.$upload_dir.$info[0]["savename"]; // var_dump($data); // exit; $row = M('display_pictures')->data($data)->save(); if ($row !== false) { $this->success('修改成功',U('Goods/index')); }else{ $this->error('修改失败'); exit; } } }else{ $this->redirect('Goods/edhotpica'); exit; } } // public function edhotpicb() // { // // $id = $_GET['id']; // $one = M('hotel_admin')->where(array('admin_id'=>$_SESSION['admin_id']))->field('hotel_id')->find(); // $list = M('display_pictures')->where(array('relate_id'=>$one['hotel_id']))->find(); // $this->assign('list',$list); // $this->display(); // } // public function edhotpicb() // { // // var_dump($_GET); // // exit; // $id = $_GET['id']; // $bucket = 'zlmimg'; //空间名称 这里修改,你七牛运空间名称 // $accessKey = '<KEY>'; //密钥 // $secretKey = '<KEY>';//密钥 // $auth = new Auth($accessKey, $secretKey); // $name=time().rand(); // $policy = array // ( // 'callbackUrl' => 'http://admin.zlmhotel.com/zz.php', //修改数据库的页面,比如要把刚刚上传的写入你的数据库 // 'callbackBody' => '{"fname":"'.$name.'$(fname)","hotelId":"'.$id.'"}', // // 'callbackBody' => '{"fname":"'.$name.'","roomId":"'.$id.'"}', // 'callbackBodyType'=>'application/json', // //上传文件名 // 'saveKey' => "hotel/$name$(fname)" // ); // $token = $auth->uploadToken($bucket, null, 3600, $policy); // // $id = $_GET['id']; // // $list = M('display_pictures')->where(array('relate_id'=>$id,'type'=>'rooms'))->find(); // // var_dump($list); // // $this->assign('list',$list); // $this->assign('uptoken',$token); // $this->display(); // } // public function uploadifytwob(){ // // var_dump($_POST); // // exit; // $id = $_POST['type_id']; // if (!empty($_FILES)) { // import("ORG.Net.UploadFile"); // $name=time().rand(); //设置上传图片的规则 // $upload = new UploadFile();// 实例化上传类 // $upload->maxSize = 3145728 ;// 设置附件上传大小 // $upload->allowExts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型 // $upload->savePath = './Public/image/hotel/';// 设置附件上传目录 // // $upload->savePath ='.'.$upload_dir; // $upload->saveRule = $name; //设置上传图片的规则 // $upload->thumb = true; // $upload->thumbMaxWidth = '300'; // $upload->thumbMaxHeight = '200'; // $upload->thumbRemoveOrigin = true; // // var_dump($upload); // // exit; // if(!$upload->upload()) {// 上传错误提示错误信息 // //return false; // echo $upload->getErrorMsg(); // //echo $targetPath; // }else{// 上传成功 获取上传文件信息 // // $this->success('成功'); // $info = $upload->getUploadFileInfo(); // // var_dump($info); // // exit; // // echo $upload_dir.$info[0]["savename"]; // $data['id'] = $id; // $data['type'] = 'hotels'; // // $data['url'] = 'img.zlmhotel.com/image/hotel/'.$info[0]["savename"]; // // $data['url'] =$info[0]["savename"]; // $data['url'] = 'thumb_'.$upload_dir.$info[0]["savename"]; // // var_dump($data); // // exit; // $row = M('display_pictures')->data($data)->save(); // if ($row !== false) // { // $this->success('修改成功',U('Goods/hotelinfo')); // }else{ // $this->error('修改失败'); // } // } // } // } public function uploadifytwoa(){ // var_dump($_POST); // exit; $id = $_POST['type_id']; if (!empty($_FILES)) { import("ORG.Net.UploadFile"); $name=time().rand(); //设置上传图片的规则 $upload = new UploadFile();// 实例化上传类 $upload->maxSize = 3145728 ;// 设置附件上传大小 $upload->allowExts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型 $upload->savePath = './Public/image/hotel/';// 设置附件上传目录 // $upload->savePath ='.'.$upload_dir; $upload->saveRule = $name; //设置上传图片的规则 $upload->thumb = true; $upload->thumbMaxWidth = '300'; $upload->thumbMaxHeight = '200'; $upload->thumbRemoveOrigin = true; // var_dump($upload); // exit; if(!$upload->upload()) {// 上传错误提示错误信息 //return false; echo $upload->getErrorMsg(); //echo $targetPath; }else{// 上传成功 获取上传文件信息 // $this->success('成功'); $info = $upload->getUploadFileInfo(); // var_dump($info); // exit; // echo $upload_dir.$info[0]["savename"]; $data['id'] = $id; $data['type'] = 'hotels'; // $data['url'] = 'img.zlmhotel.com/image/hotel/'.$info[0]["savename"]; $data['url'] = 'thumb_'.$upload_dir.$info[0]["savename"]; // var_dump($data); // exit; $row = M('display_pictures')->data($data)->save(); if ($row !== false) { $this->success('修改成功',U('Goods/hotelinfoa')); }else{ $this->error('修改失败'); } } } } public function uptoken() { $ak = '<KEY>'; $sk = '<KEY>'; $bucket = "zlmimg"; include '/Public/Qiniu.class.php'; $qiniu = new Qiniu($ak, $sk); $uptoken = $qiniu->QiniuRSPutPolicy($bucket); echo json_encode(array('uptoken' => $uptoken)); } public function doedit() { if (IS_POST) { foreach ($_POST as $val) { if ($val == '') { $this->error('请完善信息'); exit; } } } $data['id'] = $_POST['type_id']; $data['area'] = $_POST['room_area']; $data['display_name'] = $_POST['type_name']; $data['price'] = $_POST['room_price']; $data['count_num'] = $_POST['count_num']; $data['people_num'] = $_POST['people_num']; $data['floors'] = $_POST['floors']; $data['bed_add'] = $_POST['bed_add']; $data['bed_add_price'] = $_POST['bed_add_price']; $data['bed_area'] = $_POST['bed_area']; $data['smoke'] = $_POST['smoke']; $data['air_conditioner'] = $_POST['air_conditioner']; $data['breakfast'] = $_POST['breakfast']; $data['internet']= $_POST['internet']; $mm = M('rooms'); $aa = $mm->data($data)->save(); // var_dump($aa); // exit; // $runbo['relate_id'] = $id; // $runbo['type'] = 'rooms'; // $img['url'] = $img; // $bb = M('display_pictures')->where($runbo)->save($img); if ($aa !== false) { $this->success('修改成功',U('Goods/index')); }else { $this->error('修改失败',U('Goods/index')); } // } } public function addpd(){ $this->time = time(); $this->pid = $_REQUEST['pid']; $this->display(); } public function add() { $m = D("rooms"); $u = D("Hotel_admin"); $_POST['image_url'] = rtrim($_POST['picture'],'|'); unset($_POST['picture']); $username=$_SESSION["username"]; $con['name'] = $username; //$con['admin_id'] = $admin_id; //$_POST['HotelId'] = $HotelId; $HotelId = $u->where($con)->getField('Hotel_id'); //$admin_id = $_SESSION["admin_id"]; $image_url = substr($_POST['image_url'],37); if($image_url!=null&&$image_url!=""){ $m->image_url = "thumb_".$image_url; } $m->hotel_id = $HotelId; $m->name = $_POST['type_name'];//房型英文名 $m->display_name = $_POST['bed_type'];//大床房 $m->area = $_POST['room_area'];//房间大小面积 $m->price = $_POST['room_price'];//单间价格 $m->count_num = $_POST['room_count'];//房间数量 $m->bed_add_price = $_POST['addprice'];//加床价格 // $m->room_type = $_POST['room_type']; $m->breakfast = $_POST['breakfast'];//是否有早餐 $m->internet = $_POST['internet'];//网络情况 $m->people_num = $_POST['person'];//可住人数 $result = $m->add(); if($result) { $this->ajaxReturn($_POST,'添加房间成功!',1); }else{ $this->ajaxReturn($m->getError(),'添加房间失败!',0); } // $vo = $m->create($_POST); // if(!$vo) { // $this->ajaxReturn($_POST,$m->getError(),3); // }else{ // echo "<script>alert('success4');</script>"; // $result = $m->add(); // echo "<script>alert($result);</script>"; // if($result) { // echo "<script>alert('success');</script>"; // $this->ajaxReturn($_POST,'添加房间成功!',1); // }else{ // echo "<script>alert('fail');</script>"; // $this->ajaxReturn($m->getError(),'添加房间失败!',0); // } // } } // 更新数据 public function edit(){ //在ThinkPHP中使用save方法更新数据库,并且也支持连贯操作的使用 $Form = D("rooms"); $img_url = rtrim($_POST['picture'],'|'); $image_url = substr($img_url,37); if($image_url!=null&&$image_url!=""){ $_POST['image_url'] = "thumb_".$image_url; } unset($_POST['picture']); $vo = $Form->create($_POST); if ($vo) { $list = $Form->save($vo); $this->ajaxReturn($_POST,'更新成功!',1); } else { $this->ajaxReturn($_POST,$Form->getError(),3); } } // 删除数据 public function delete() { //在ThinkPHP中使用delete方法删除数据库中的记录。同样可以使用连贯操作进行删除操作。 if (!empty ($_POST['ids'])) { $d = M("Fruit"); $i = M("Item"); $o = M("Order"); $condition['fruit_id']=array('in',$_POST['ids']); //item删除 $data['on_flag'] = 0; $result = $d->where($condition)->data($data)->save(); /* $i->where($condition)->delete(); $result = $d->where($condition)->delete(); */ /* delete方法可以用于删除单个或者多个数据,主要取决于删除条件,也就是where方法的参数, 也可以用order和limit方法来限制要删除的个数,例如: 删除所有状态为0的5 个用户数据 按照创建时间排序 $Form->where('status=0')->order('create_time')->limit('5')->delete(); 本列子没有where条件 传入的是主键值就行了 */ if (false !== $result) { $this->ajaxReturn($_POST,'删除房间成功!',1); } else { $this->ajaxReturn($_POST,'删除出错!',1); } } else { $this->ajaxReturn($_POST,'删除项不存在!',1); } //$this->redirect('index'); } //添加修改页面 public function uppd(){ $id = $_GET['id']; $d = D("rooms"); // $con['id'] = $id; // $this->list = $d->where($con)->find(); $list = M('rooms')->where(array('id'=>$id))->find(); // var_dump($list); $this->assign('list',$list); $this->assign('time',time()); $this->display(); } public function updel() { $id = $_GET['id']; $list = M('rooms')->where(array('id'=>$id))->delete(); if ($list !==false && $list !==0) { $this->success('删除成功'); }else{ $this->error('删除失败'); } } public function getAllHotels(){ $h = D("Hotels"); $u = D("Hotel_admin"); import("ORG.Util.Page"); $page=$_POST["page"]? $_POST["page"] :1; $rows=$_POST["rows"]? $_POST["rows"] :30; $sort=$_POST["sort"]? $_POST["sort"] :'hotel_id'; $order=$_POST["order"] ? $_POST["order"] :'asc'; $search=$_POST["search"]; $username=$_SESSION["username"]; $con['name'] = $username; //$admin_id = $_SESSION["admin_id"]; //$con['admin_id'] = $admin_id; if($_SESSION["permission"] == 0){ $HotelId = $u->where($con)->getField('hotel_id'); $condition['hotel_id'] = $HotelId; } if($search!=null&&$search!=""){ $condition['hotel_name']=array('like','%'.$search.'%'); } $count = $h->where($condition)->select(); //计算总数 $list = $h->where($condition)->page($page,$rows)->order(array($sort=>$order))->select(); $result['total'] = $count; $result['rows'] = $list; exit(json_encode($result)); } public function getHotelsById() { $h = D("Hotels"); $condition['id']=array('EQ',$_POST['id']); $list = $h->where($condition)->find(); exit(json_encode($list)); //输出json数据 } public function uphotel(){ $id = $_GET['id']; $this->display(); } public function doadd() { // var_dump($_POST); // exit; if (IS_POST) { $one = M('hotel_admin')->where(array('admin_id'=>$_SESSION['admin_id']))->field('hotel_id')->find(); $data['hotel_id'] = $one['hotel_id']; $data['display_name'] = $_POST['type_name']; $data['price'] = $_POST['room_price']; $data['count_num'] = $_POST['room_count']; $data['area'] = $_POST['room_area']; $data['bed_add_price'] = $_POST['addprice']; $data['floors'] = $_POST['floors']; $data['bed_add'] = $_POST['bed_add']; $data['bed_area'] = $_POST['bed_area']; $data['addprice'] = $_POST['addprice']; $data['breakfast'] = $_POST['breakfast']; $data['smoke'] = $_POST['smoke']; $data['hot_water'] = $_POST['hot_water']; $data['air_conditioner'] = $_POST['air_conditioner']; $data['internet'] = $_POST['internet']; $data['people_num'] = $_POST['people_num']; $row = M('rooms')->add($data); if (!empty($_FILES)) { import("ORG.Net.UploadFile"); $name=time().rand(); //设置上传图片的规则 $upload = new UploadFile();// 实例化上传类 $upload->maxSize = 3145728 ;// 设置附件上传大小 $upload->allowExts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型 $upload->savePath = './Public/image/room/';// 设置附件上传目录 // $upload->savePath ='.'.$upload_dir; $upload->saveRule = $name; //设置上传图片的规则 $upload->thumb = true; $upload->thumbMaxWidth = '300'; $upload->thumbMaxHeight = '200'; $upload->thumbRemoveOrigin = true; if(!$upload->upload()) {// 上传错误提示错误信息 //return false; echo $upload->getErrorMsg(); //echo $targetPath; }else {// 上传成功 获取上传文件信息 $info = $upload->getUploadFileInfo(); // echo $upload_dir.$info[0]["savename"]; } $data['relate_id'] = $row; $data['type'] = 'rooms'; $data['url'] = 'thumb_'.$upload_dir.$info[0]["savename"]; // var_dump($data); // exit; $result = M('display_pictures')->add($data); if (!result) { $this->error('添加失败1'); exit; } } $data['relate_id'] = $row; $data['type'] = 'rooms'; $data['url'] = 'thumb_'.$upload_dir.$info[0]["savename"]; // var_dump($data); // exit; $result = M('display_pictures')->add($data); if ($row) { $this->success('添加成功',U('Goods/index')); }else{ $this->error('添加失败'); } }else{ $this->redirect(U('Goods/addpd')); } } public function edithotel() { $id = $_GET['id']; // var_dump($id); $list = M('hotels')->where(array('id'=>$id))->find(); $row = M('hotel_infrastructure')->where(array('hotel_id'=>$id))->select(); $this->assign('list',$list); $this->assign('row',$row); $this->display(); } public function edithotela() { $id = $_GET['id']; $list = M('hotels')->where(array('id'=>$id))->find(); $row = M('hotel_infrastructure')->where(array('hotel_id'=>$id))->select(); // var_dump($row); // $arr = []; // for ($i=0; $i <count($row) ; $i++) // { // $arr[]=$row[$i]['infrastructure_id']; // } // var_dump($arr); // var_dump($list); $this->assign('list',$list); $this->assign('row',$row); $this->display(); } public function hotelinfo() { if ($_SESSION['permission'] == 0) //普通用户 { $one = M('hotel_admin')->where(array('admin_id'=>$_SESSION['admin_id']))->field('hotel_id')->find(); $hotels = M('hotels'); $what = "(display_pictures.relate_id = ".$one['hotel_id'].")"; // $list = $hotels->where(array('id'=>$one['hotel_id']))->find(); $list = $hotels->join('display_pictures ON hotels.id=display_pictures.relate_id')->field('hotels.*,display_pictures.url')->where($what)->find(); // var_dump($hotels->getLastSql()); // var_dump($list); $this->assign('list',$list); } $this->display(); } public function hotelinfoa() { if($_SESSION['permission'] == 1){ $what ="(display_pictures.type = 'hotel')"; if (!empty($_REQUEST['chaxun'])) { if ($_REQUEST['chaxun'] == 1) { $what .= "and (hotels.name like '%".$_REQUEST['hotel']."%')"; } if ($_REQUEST['chaxun'] == 2) { $what .= "and (hotels.address like '%".$_REQUEST['hotel']."%')"; } } $hotels = M('hotels'); // $one = M('hotel_admin')->where(array('admin_id'=>$_SESSION['admin_id']))->field('hotel_id')->find(); $list = $hotels->join('display_pictures ON hotels.id=display_pictures.relate_id')->field('hotels.*,display_pictures.url')->where($what)->select(); // $list = $hotels->where(array("id"=>$one['hoteldisind(); // var_dump($hotels->getLastSql()); // var_dump($list); $this->assign('list',$list); } $this->display(); } // public function edhotpica() // { // $id = $_GET['id']; // $list = M('display_pictures')->where(array('relate_id'=>$id))->find(); // $this->assign('list',$list); // $this->display(); // } // public function edrompic() // { // $id = $_GET['id']; // $bucket = 'zlmimg'; //空间名称 这里修改,你七牛运空间名称 // $accessKey = '<KEY>'; //密钥 // $secretKey = '<KEY>';//密钥 // $auth = new Auth($accessKey, $secretKey); // $name=time().rand(); // $policy = array // ( // 'callbackUrl' => 'http://admin.zlmhotel.com/xx.php', //修改数据库的页面,比如要把刚刚上传的写入你的数据库 // 'callbackBody' => '{"fname":"'.$name.'$(fname)","roomId":"'.$id.'"}', // //'callbackBody' => "(fname=".$name.")", // 'callbackBodyType'=>'application/json', // //上传文件名 // 'saveKey' => "room/$name$(fname)" // ); // $token = $auth->uploadToken($bucket, null, 3600, $policy); // // $id = $_GET['id']; // // $list = M('display_pictures')->where(array('relate_id'=>$id,'type'=>'rooms'))->find(); // // var_dump($list); // // $this->assign('list',$list); // $this->assign('uptoken',$token); // $this->display(); // } public function doedithotel() { // var_dump($_POST); // exit; if (IS_POST) { foreach ($_POST as $val) { if (empty($val)) { $this->error('请完善信息'); exit; } } if (empty($_POST['address3']) && empty($_POST['address2'])) { $data['area_code'] = $_POST['address1']; }else if(empty($_POST['address3']) && !empty($_POST['address2'])){ $data['area_code'] = $_POST['address2']; }else if(!empty($_POST['address3'])){ $data['area_code'] = $_POST['address3']; } $hello = M('areas')->where(array('code'=>$data['area_code']))->field('id')->find(); $data['area_id'] = $hello['id']; $id = $_POST['hotel_id']; $data['routes'] = $_POST['routes']; $data['longitude'] = $_POST['longitude']; $data['latitude'] = $_POST['latitude']; $data['name'] = $_POST['hotel_name']; $data['grade'] = $_POST['hotel_star']; $data['phone_number'] = $_POST['hotel_telephone']; $data['address'] = $_POST['hotel_address']; $data['email'] = $_POST['hotel_email']; $data['introduction'] = $_POST['introduction']; $data['endorse_rules'] = $_POST['content']; // var_dump($data); if (!empty($_POST['checkbox'])) { $arr = []; foreach ($_POST['checkbox'] as $val) { $arr[] = $val; } } $lili['hotel_id'] = $id; $bob = M('hotel_infrastructure')->delete($lili); for ($i=0; $i <count($arr) ; $i++) { $tnt['hotel_id'] = $id; $tnt['infrastructure_id'] = $arr[$i]; $yun = M('hotel_infrastructure')->add($tnt); } $row = M('hotels')->where(array('id'=>$id))->save($data); if ($row !== false) { $this->success('修改成功',U('Goods/hotelinfo')); }else{ $this->error('修改失败'); } }else{ $this->redirect(U('Goods/edithotel')); } } public function doedithotela() { // var_dump($_POST); // exit; if (IS_POST) { foreach ($_POST as $val) { if (empty($val)) { $this->error('请完善信息'); exit; } } if (empty($_POST['address3']) && empty($_POST['address2'])) { $data['area_code'] = $_POST['address1']; }else if(empty($_POST['address3']) && !empty($_POST['address2'])){ $data['area_code'] = $_POST['address2']; }else if(!empty($_POST['address3'])){ $data['area_code'] = $_POST['address3']; } $hello = M('areas')->where(array('code'=>$data['area_code']))->field('id')->find(); $data['area_id'] = $hello['id']; $id = $_POST['hotel_id']; $data['routes'] = $_POST['routes']; $data['longitude'] = $_POST['longitude']; $data['latitude'] = $_POST['latitude']; $data['name'] = $_POST['hotel_name']; $data['grade'] = $_POST['hotel_star']; $data['phone_number'] = $_POST['hotel_telephone']; $data['address'] = $_POST['hotel_address']; $data['email'] = $_POST['hotel_email']; $data['introduction'] = $_POST['introduction']; $data['endorse_rules'] = $_POST['content']; // var_dump($data); if (!empty($_POST['checkbox'])) { $arr = []; foreach ($_POST['checkbox'] as $val) { $arr[] = $val; } } $lili['hotel_id'] = $id; $bob = M('hotel_infrastructure')->delete($lili); for ($i=0; $i <count($arr) ; $i++) { $tnt['hotel_id'] = $id; $tnt['infrastructure_id'] = $arr[$i]; $yun = M('hotel_infrastructure')->add($tnt); } $row = M('hotels')->where(array('id'=>$id))->save($data); if ($row !== false) { $this->success('修改成功',U('Goods/hotelinfoa')); }else{ $this->error('修改失败'); } }else{ $this->redirect(U('Goods/edithotel')); } } public function doup() { // var_dump($_POST); // exit; if (IS_POST) { foreach ($_POST as $val) { if (empty($val)) { $this->error('请完善信息'); exit; } } $data['routes'] = $_POST['routes']; $data['longitude'] = $_POST['longitude']; $data['latitude'] = $_POST['latitude']; $data['name'] = $_POST['hotel_name']; $data['grade'] = $_POST['hotel_star']; $data['phone_number'] = $_POST['hotel_telephone']; $data['address'] = $_POST['hotel_address']; $data['email'] = $_POST['hotel_email']; $data['introduction'] = $_POST['introduction']; $row = M('hotels')->add($data); if (!empty($_POST['checkbox'])) { $arr = []; foreach ($_POST['checkbox'] as $val) { $arr[] = $val; } } for ($i=0; $i <count($arr) ; $i++) { $tnt['hotel_id'] = $row; $tnt['infrastructure_id'] = $arr[$i]; $yun = M('hotel_infrastructure')->add($tnt); } $dui = M('hotel_infrastructure')->field('infrastructure_id')->where(array('hotel_id'=>$row))->select(); if ($dui[4]['infrastructure_id']) { $kui['type']='hotel'; $kui['relate_id'] = $row; $kui['display_name'] = $_POST['hotel_name']; $kui['created_at']=date('Y-m-d H:i:s'); $kui['updated_at'] = date('Y-m-d H:i:s'); $hui = M('tiebas')->add($kui); } if (!empty($_FILES)) { import("ORG.Net.UploadFile"); $name=time().rand(); //设置上传图片的规则 $upload = new UploadFile();// 实例化上传类 $upload->maxSize = 3145728 ;// 设置附件上传大小 $upload->allowExts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型 $upload->savePath = './Public/image/hotel/';// 设置附件上传目录 // $upload->savePath ='.'.$upload_dir; $upload->saveRule = $name; //设置上传图片的规则 // $upload->thumb = true; // $upload->thumbMaxWidth = '300'; // $upload->thumbMaxHeight = '200'; // $upload->thumbRemoveOrigin = true; if(!$upload->upload()) {// 上传错误提示错误信息 //return false; echo $upload->getErrorMsg(); //echo $targetPath; }else{// 上传成功 获取上传文件信息 // $this->success('成功'); $info = $upload->getUploadFileInfo(); // echo $upload_dir.$info[0]["savename"]; } $data['relate_id'] = $row; $data['type'] = 'hotels'; $data['url'] = 'img.zlmhotel.com/image/hotel/'.$upload_dir.$info[0]["savename"]; // var_dump($data); // exit; $result = M('display_pictures')->add($data); if (!result) { $this->error('添加失败'); exit; } } if ($row) { $this->success('添加成功',U('Goods/hotelinfo')); }else{ $this->error('添加失败'); } }else{ $this->redirect(U('Goods/uphotel')); } } public function infodel() { $id = $_GET['id']; $row = M('hotels')->where(array('id'=>$id))->delete(); $list = M('hotel_infrastructure')->where(array('hotel_id'=>$id))->delete(); if ($row !== false && $row !==0 && $list !== false && $row !== 0) { $this->success('删除成功'); }else{ $this->error('删除失败'); } } // public function ImgUpload() // { // // var_dump($_FILES); // // exit; // //$this->error("没有文件!"); // //TODO: 用户登录检测 // /* 调用文件上传组件上传文件 */ // $Picture = D('Picture'); // $pic_driver = C('PICTURE_UPLOAD_DRIVER'); // $info = $Picture->upload( // $_FILES, // C('PICTURE_UPLOAD'), // C('PICTURE_UPLOAD_DRIVER'), // C("UPLOAD_&#123;&#36;pic_driver&#125;_CONFIG") // ); //TODO:上传到远程服务器 // /* 记录图片信息 */ // if($info){ // /* 返回JSON数据 */ // echo json_encode($info); // } else { // echo json_encode($info); // } // } } ?><file_sep><?php class CountAction extends Action { public function index() { $u =D("User"); $o =D("Order"); $mcount = $u->count(); $fcount = $u->where(array('sex'=>1))->count(); $sql = 'select sum(total_price) as total from df_order'; $totalrow = $o->query($sql); $fsql = 'select sum(i.buy_price*i.number) as total from df_order o left join df_item i on i.order_id = o.order_id left join df_fruit f on f.fruit_id = i.fruit_id '; $ftotalrow = $o->query($fsql); $lr = $totalrow[0]['total']-$ftotalrow[0]['total']; $data = array('bl'=>($mcount-$fcount).':'.$fcount,'lr'=>sprintf('%.2f',$lr),'ze'=>sprintf('%.2f',$totalrow[0]['total'])); $this->assign('data',$data); $this->display(); //var_dump($ftotalrow[0]['total']); } } ?><file_sep><?php // 本类由系统自动生成,仅供测试用途 class LayoutAction extends Action { public function index() { echo THINK_VERSION; $this->display(); } } ?><file_sep><?php class UserAction extends Action { public function index() { if ($_SESSION['permission'] == 0) //普通用户 { // var_dump($_SESSION); $one = M('hotel_admin')->where(array('admin_id'=>$_SESSION['admin_id']))->field('hotel_id')->find(); $what = "(users.hotel_id = ".$one['hotel_id'].")"; if ($_GET['chaxun'] == 1) { if (!empty($_GET['hotel'])) { $what .= "and (hotels.name like '%".$_GET['hotel']."%')"; } }else if($_GET['chaxun'] == 2){ if (!empty($_GET['hotel'])) { $what .= "and (users.nickname like '%".$_GET['hotel']."%')"; } }else if($_GET['chaxun'] == 3){ if (!empty($_GET['hotel'])) { $what .= "and (users.comment like '%".$_GET['hotel']."%')"; } } $list = M('users')->join('hotels ON users.hotel_id = hotels.id')->join('user_usual_infos ON user_usual_infos.user_id = users.id')->where($what)->field('users.*,hotels.name hn,user_usual_infos.name un')->select(); // var_dump($list); $this->assign('list',$list); }else{ $what = array(); if ($_GET['chaxun'] == 1) { if (!empty($_GET['hotel'])) { $what['hotels.name'] = array('like','%'.$_GET['hotel'].'%'); } }else if($_GET['chaxun'] == 2){ if (!empty($_GET['hotel'])) { $what['users.nickname'] = array('like','%'.$_GET['hotel'].'%'); } }else if($_GET['chaxun'] == 3){ if (!empty($_GET['hotel'])) { $what['users.comment'] = array('like','%'.$_GET['hotel'].'%'); } } $list = M('users')->join('hotels ON users.hotel_id = hotels.id')->join('user_usual_infos ON user_usual_infos.user_id = users.id')->where($what)->field('users.*,hotels.name hn,user_usual_infos.name un,user_usual_infos.phone up')->select(); // var_dump($list); $this->assign('list',$list); } $this->display('user'); } public function editcom() { // var_dump($_POST); // // var_dump($_GET); // exit; if (IS_POST) { if ($_POST['comment'] == '') { $this->error('请完善信息'); exit; } $data['id'] = $_GET['id']; // $id = ('get.id'); $data['mark'] = $_POST['comment']; $row = M('users'); $list = $row->data($data)->save(); // echo $row->getLastSql(); // exit; if ($list !== false) { $this->success('修改成功'); }else{ $this->error('修改失败'); } }else{ $this->redirect(U('User/index')); } } public function getAllUser() { $n =D("Members"); $u =D("Hotel_admin"); //$n =new Model('user'); import("ORG.Util.Page"); //导入分页类 $page=$_POST["page"]? $_POST["page"] :1; $rows=$_POST["rows"]? $_POST["rows"] :10; $sort=$_POST["sort"]? $_POST["sort"] :'member_id'; $order=$_POST["order"] ? $_POST["order"] :'asc'; $search=$_POST["search"]; if($sort=='phone_number') $sort = 'member_id'; //dump($order); if($search!=null&&$search!=""){ $condition['phone_number']=array('like','%'.$search.'%'); } $count = $n->count(); //计算总数 //$p = new Page($count,$rows);order($sort+','+$order)-> $username=$_SESSION["username"]; $con['name'] = $username; //$admin_id = $_SESSION["admin_id"]; //$con['admin_id'] = $admin_id; if($_SESSION["permission"] == 0){ $HotelId = $u->where($con)->getField('hotel_id'); $condition['vip_id'] = $HotelId; $list = $n->relation(true)->join('hotels h ON h.hotel_id = members.vip_id')->where($condition)->page($page,$rows)->order(array($sort=>$order))->select(); } else{ $list = $n->relation(true)->join('hotels h ON h.hotel_id = members.vip_id')->page($page,$rows)->order(array($sort=>$order))->select(); } $result['total'] = $count; $result['rows'] = $list; exit(json_encode($result)); } public function getUserById(){ $d = D("Members"); $condition['member_id']=array('EQ',$_POST['id']); $list = $d->where($condition)->find(); exit(json_encode($list)); } // 更新数据 public function edit(){ //在ThinkPHP中使用save方法更新数据库,并且也支持连贯操作的使用 $Form = D("Members"); //$_POST['password']=md5($_POST['password']); $vo= $Form->create(); //var_dump($vo);exit; if ($vo) { $list = $Form->save($vo); $this->ajaxReturn($_POST,'更新成功!',1); } else { $this->ajaxReturn($_POST,$Form->getError(),3); } } // 导出csv public function export() { $d = D("User"); $str = $_GET['idstr']; if(empty($str)){ $list = $d->select(); }else{ $ids = explode(',', $str); $condition['user_id']=array('in',$ids); $list = $d->where($condition)->select(); } $datastr = '姓名,性别,手机,果币,点赞,注册日期,地址'; $datastr = mb_convert_encoding($datastr,'gbk','utf-8'); $datastr.="\n"; if($list){ foreach($list as $user){ $name = mb_convert_encoding($user['user_name'],'gbk','utf-8'); $sex = ($user['sex']==1)?'女':'男'; $sexn = mb_convert_encoding($sex,'gbk','utf-8'); $address = $user['address1']."".$user['address2']."".$user['address3']; $address = mb_convert_encoding($address,'gbk','utf-8'); $datastr .= $name.",".$sexn.",".$user['user_id']."," .$user['fruit_coin'].",".$user['praise_flag'].",".$user['register_time']."," .$address."\n"; } } ob_clean(); //$datastr = @iconv("UTF-8", "GBK//IGNORE", $datastr); //$datastr = @iconv("GBK", "UTF-8//IGNORE", $datastr); //$datastr = mb_convert_encoding($datastr,'gbk','utf-8'); //var_dump($list); $filename = date("Ymd",time()).".csv"; header("Content-Type: application/vnd.ms-excel; charset=gbk"); //header("Content-type:text/csv"); header("Content-Disposition:attachment;filename=".$filename); header('Cache-Control:must-revalidate,post-check=0,pre-check=0'); header('Expires:0'); header('Pragma:public'); echo $datastr; } //重置密码 public function initPwd(){ $Form = D("User"); $password=md5('<PASSWORD>'); $_POST['password'] =$password; $vo = $Form->create(); if ($vo) { $list = $Form->save($vo); } } // 更新数据 public function editPwd(){ //在ThinkPHP中使用save方法更新数据库,并且也支持连贯操作的使用 $Form = D("Hotel_admin"); $user=M('Hotel_admin'); $password=md5($_POST['password']); $newpassword=md5($_POST['newpassword']); $username=$_SESSION["username"]; $condition['name']=$username; $condition['password']=$<PASSWORD>; $query=$user->where($condition)->find(); if($query) { $user_id = $user->where($condition)->getField('user_id'); $condition2['user_id']=$user_id; $condition2['password']=$<PASSWORD>; if ($Form->create()) { $list = $Form->save($condition2); //dump($_POST); //未传入$data理由同上面的add方法 /* 为了保证数据库的安全,避免出错更新整个数据表,如果没有任何更新条件,数据对象本身也不包含主键字段的话, save方法不会更新任何数据库的记录。 因此下面的代码不会更改数据库的任何记录 */ //dump($list); if ($list !== false) { //注意save方法返回的是影响的记录数,如果save的信息和原某条记录相同的话,会返回0 //所以判断数据是否更新成功必须使用 '$list!== false'这种方式来判断 //$this->ajaxReturn($_POST,'修改密码成功!',1); unset($_SESSION["username"]); //$this->success('密码修改成功,请用新密码重新登录', '../../admin.php'); echo "<script>alert('密码修改成功,请用新密码重新登录');top.location = '../../admin.php';</script>"; } else { //$this->error('密码修改失败'); echo "<script>alert('密码修改失败');</script>"; //$this->ajaxReturn($_POST,'没有更新任何数据!',0); } } else { echo "<script>alert('密码修改失败');</script>"; //$this->ajaxReturn($_POST,$Form->getError(),3); //$this->error('密码修改失败'); } } else echo "<script>alert('原密码错误');</script>"; //$this->ajaxReturn($_POST,'原密码错误',0); //$this->error('原密码错误'); } } ?><file_sep><?php if (!defined('THINK_PATH')) exit();?><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="stylesheet" type="text/css" href="__PUBLIC__/themes/default/easyui.css" /> </head> <body> <div class="easyui-accordion" data-options="fit:false,border:false"> <div title="订单管理" icon="icon-sys" style="height:150px" > <ul class="easyui-tree"> <li ><a href="javascript:" style="color: #000" onclick="addTab('所有订单','__APP__/Order/index');"> 所有订单</a><i></i></li> <li><a href="javascript:" style="color: #000" onclick="addTab('未入住订单','__APP__/Order/onorder');"> 未入住订单</a><i></i></li> <li><a href="javascript:" style="color: #000" onclick="addTab('已入住订单','__APP__/Order/payorder');"> 已入住订单</a><i></i></li> <li><a href="javascript:" style="color: #000" onclick="addTab('退款订单','__APP__/Order/refund');"> 退款订单</a><i></i></li> </ul> </div> <?php if($_SESSION['permission']==1){?> <div title="管理员管理" icon="icon-sys" style="height:150px"> <ul class="easyui-tree"> <li><a href="javascript:" style="color: #000" onclick="addTab('管理员设置','__APP__/Auser/auser');"> 管理员设置</a><i></i></li> </ul> <ul class="easyui-tree"> <li><a href="javascript:" style="color: #000" onclick="addTab('增加管理员','__APP__/Auser/adduser');"> 增加管理员</a><i></i></li> </ul> </div> <?php }?> <?php if($_SESSION['permission']==0){?> <div title="酒店管理" icon="icon-sys" style="height:150px"> <ul class="easyui-tree"> <li><a href="javascript:" style="color: #000" onclick="addTab('酒店管理','__APP__/Goods/hotelinfo');"> 酒店管理</a><i></i></li> </ul> </div> <?php }?> <?php if($_SESSION['permission']==1){?> <div title="酒店管理" icon="icon-sys" style="height:150px"> <ul class="easyui-tree"> <li><a href="javascript:" style="color: #000" onclick="addTab('酒店管理','__APP__/Goods/hotelinfoa');"> 酒店管理</a><i></i></li> </ul> </div> <?php }?> <!-- <?php if($_SESSION['permission']==1){?> <div title="上传酒店" icon="icon-sys" style="height:150px"> <ul class="easyui-tree"> <li><a href="javascript:" style="color: #000" onclick="addTab('上传酒店','__APP__/Goods/uphotel');"> 上传酒店</a><i></i></li> </ul> </div> <?php }?> --> <?php if($_SESSION['permission']==0){?> <div title="房间管理" icon="icon-sys" style="height:150px"> <ul class="easyui-tree"> <li><a href="javascript:" style="color: #000" onclick="addTab('房间管理','__APP__/Goods/index');"> 房间管理</a><i></i></li> </ul> <ul class="easyui-tree"> <li><a href="javascript:" style="color: #000" onclick="addTab('添加房间','__APP__/Goods/addpd');"> 添加房间</a><i></i></li> </ul> </div> <?php }?> <div title="用户管理" icon="icon-sys" style="height:150px"> <ul class="easyui-tree"> <li><a href="javascript:" style="color: #000" onclick="addTab('所有用户','__APP__/User/index');"> 所有用户</a><i></i></li> </ul> </div> <?php if($_SESSION['permission']==1){?> <div title="商品管理" icon="icon-sys" style="height:150px"> <ul class="easyui-tree"> <li><a href="javascript:" style="color: #000" onclick="addTab('分类管理','__APP__/Adminstore/category');"> 分类管理</a><i></i></li> </ul> <ul class="easyui-tree"> <li><a href="javascript:" style="color: #000" onclick="addTab('分类添加','__APP__/Adminstore/addcate');"> 分类添加</a><i></i></li> </ul> <ul class="easyui-tree"> <li><a href="javascript:" style="color: #000" onclick="addTab('商品列表','__APP__/Adminstore/goods');"> 商品列表</a><i></i></li> </ul> <ul class="easyui-tree"> <li><a href="javascript:" style="color: #000" onclick="addTab('商品添加','__APP__/Adminstore/addgoods');"> 商品添加</a><i></i></li> </ul> <ul class="easyui-tree"> <li><a href="javascript:" style="color: #000" onclick="addTab('商品订单','__APP__/Adminstore/goodsorder');"> 商品订单</a><i></i></li> </ul> </div> <?php }?> <?php if($_SESSION['permission']==0){?> <div title="积分管理" icon="icon-sys" style="height:150px"> <ul class="easyui-tree"> <li><a href="javascript:" style="color: #000" onclick="addTab('积分充值','__APP__/Credit/index');"> 积分充值</a><i></i></li> <li><a href="javascript:" style="color: #000" onclick="addTab('积分记录','__APP__/Credit/query');"> 积分记录</a><i></i></li> </ul> </div> <?php }?> <?php if($_SESSION['permission']==1){?> <div title="积分管理" icon="icon-sys" style="height:150px"> <ul class="easyui-tree"> <li><a href="javascript:" style="color: #000" onclick="addTab('积分充值','__APP__/Credit/aindex');"> 积分充值</a><i></i></li> <li><a href="javascript:" style="color: #000" onclick="addTab('积分记录','__APP__/Credit/aquery');"> 积分记录</a><i></i></li> </ul> </div> <?php }?> <?php if($_SESSION['permission']==1){?> <div title="加入我们" icon="icon-sys" style="height:150px"> <ul class="easyui-tree"> <li><a href="javascript:" style="color: #000" onclick="addTab('申请记录','__APP__/Join/index');"> 申请记录</a><i></i></li> </ul> </div> <?php }?> <?php if($_SESSION['permission']==0){?> <div title="城市管理" icon="icon-sys" style="height:150px"> <ul class="easyui-tree"> <li><a href="javascript:" style="color: #000" onclick="addTab('热门城市','__APP__/City/hot');"> 热门城市</a><i></i></li> <li><a href="javascript:" style="color: #000" onclick="addTab('显示城市','__APP__/City/show');"> 显示城市</a><i></i></li> </ul> </div> <?php }?> <div title="贴吧管理" icon="icon-sys" style="height:150px"> <ul class="easyui-tree"> <li><a href="javascript:" style="color: #000" onclick="addTab('帖子管理','__APP__/Tieba/topic');"> 帖子管理</a><i></i></li> <li><a href="javascript:" style="color: #000" onclick="addTab('话题管理','__APP__/Tieba/gambit');"> 话题管理</a><i></i></li> </ul> </div> <?php if($_SESSION['permission']==0){?> <div title="在线采购" icon="icon-sys" style="height:150px"> <ul class="easyui-tree"> <li><a href="javascript:" style="color: #000" onclick="addTab('在线采购','__APP__/Store/index');"> 在线采购</a><i></i></li> <li><a href="javascript:" style="color: #000" onclick="addTab('购物车','__APP__/Store/showcart');"> 购物车</a><i></i></li> <li><a href="javascript:" style="color: #000" onclick="addTab('收货地址','__APP__/Store/address');"> 收货地址</a><i></i></li> <li><a href="javascript:" style="color: #000" onclick="addTab('我的订单','__APP__/Store/orders');"> 我的订单</a><i></i></li> </ul> </div> <?php }?> </div> </body><file_sep><?php // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: LunnLew <<EMAIL>> 20130801 // +---------------------------------------------------------------------- // | Docs:http://docs.qiniu.com/php-sdk/v6/index.html /** * 七牛API封装基类 <www.qiniu.com> */ abstract class QiniuSDK{ /** * SDK版本 */ private $SDK_Version='1.0'; private $SDK_Release='20130801'; /** * API版本 * @var string */ protected $Version = '6.1.1'; /** * 申请应用时分配的app_key * @var string */ protected $AppKey = ''; /** * 申请应用时分配的 app_secret * @var string */ protected $AppSecret = ''; /** * API根路径 * @var string */ protected $ApiBase = ''; /** * 调用接口类型 * @var string */ private $Type = ''; //请求信息 public $URL; public $rqHeader; public $rqBody; //错误信息 public $Err; // string public $Reqid; // string public $Details; // []string public $Code; // int //响应信息 public $StatusCode; public $rpHeader; public $ContentLength; public $rpBody; //上传下载域 public $downDomain; /** * 构造方法,配置应用信息 */ public function __construct(){ //设置SDK类型 $class = get_class($this); $this->Type = strtoupper(substr($class, 0, strlen($class)-3)); //获取应用配置 $config = C("THINK_SDK_QINIU"); if(empty($config['APP_KEY']) || empty($config['APP_SECRET'])){ throw new Exception('请配置您申请的APP_KEY和APP_SECRET'); } else { $this->AppKey = $config['APP_KEY']; $this->AppSecret = $config['APP_SECRET']; $this->downDomain = $config['DOWN_DOMAIN']; } } /** * 取得API实例 * @static * @return mixed 返回API */ public static function getInstance($type, $param = null) { $name = ucfirst(strtolower($type)) . 'SDK'; require_once "sdk/{$name}.class.php"; if (class_exists($name)) { return new $name($param); } else { halt(L('_CLASS_NOT_EXIST_') . ':' . $name); } } /** * URLSafeBase64Encode * @param string str 安全编码串 */ public function SafeBaseEncode($str){ $find = array('+', '/'); $replace = array('-', '_'); return str_replace($find, $replace, base64_encode($str)); } /** * 请求执行 * @param string $url 完整url * @return object 错误信息对象 */ public function callNoRet($url){ $u = array('path' => $url); self::request($u, null); self::RoundTrip(); self::setResponse(); } public function call($url){ $u = array('path' => $url); self::request($u, null); self::RoundTrip(); return self::getReponseRet(); } public function CallWithMultipartForm($url, $fields, $files){ list($contentType, $body) = self::buildMultipartForm($fields, $files); return self::CallWithForm($url, $body, $contentType); } /** * 组装请求参数 * @param array $fields 字段数组 * @param array $files 文件数组 * @return array 组装结果 */ public function buildMultipartForm($fields, $files){ $data = array(); $mimeBoundary = md5(microtime()); foreach ($fields as $name => $val) { array_push($data, '--' . $mimeBoundary); array_push($data, "Content-Disposition: form-data; name=\"$name\""); array_push($data, ''); array_push($data, $val); } foreach ($files as $file) { array_push($data, '--' . $mimeBoundary); list($name, $fileName, $fileBody) = $file; $fileName = self::escapeQuotes($fileName); array_push($data, "Content-Disposition: form-data; name=\"$name\"; filename=\"$fileName\""); array_push($data, 'Content-Type: application/octet-stream'); array_push($data, ''); array_push($data, $fileBody); } array_push($data, '--' . $mimeBoundary . '--'); array_push($data, ''); $body = implode("\r\n", $data); $contentType = 'multipart/form-data; boundary=' . $mimeBoundary; return array($contentType, $body); } /** * 数据提交过程 * @param string $url 操作路径 * @param array $params 数据参数 * @param string $contentType 文本内容 */ function CallWithForm($url, $params, $contentType = 'application/x-www-form-urlencoded'){ $u = array('path' => $url); if ($contentType === 'application/x-www-form-urlencoded') { if (is_array($params)) { $params = http_build_query($params); } } self::request($u, $params); if ($contentType !== 'multipart/form-data') { $this->rqHeader['Content-Type'] = $contentType; } self::RoundTrip(); return self::getReponseRet(); } /** * 替换处理 * @param string $str 需处理串 * @return string 处理结果 */ function escapeQuotes($str){ $find = array("\\", "\""); $replace = array("\\\\", "\\\""); return str_replace($find, $replace, $str); } /** * 设置请求参数 * @param string $url URL * @param string $body 头body内容 */ public function request($url, $body){ $this->URL = $url; $this->rqHeader = array(); $this->rqBody = $body; } /** * 执行请求 */ public function doCall(){ $ch = curl_init(); $url = $this->URL; $options = array( CURLOPT_RETURNTRANSFER => true, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => false, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_URL => $url['path'] ); $httpHeader = $this->rqHeader; if (!empty($httpHeader)) { $header = array(); foreach($httpHeader as $key => $parsedUrlValue) { $header[] = "$key: $parsedUrlValue"; } $options[CURLOPT_HTTPHEADER] = $header; } $body = $this->rqBody; if (!empty($body)) { $options[CURLOPT_POSTFIELDS] = $body; } curl_setopt_array($ch, $options); $result = curl_exec($ch); $ret = curl_errno($ch); if ($ret !== 0) { self::error(0, curl_error($ch)); curl_close($ch); } $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); $contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE); curl_close($ch); self::response($code, $result); $this->rpHeader['Content-Type'] = $contentType; } /** * 设置错误信息 * @param int $code 错误码 * @param string $err 错误信息 */ public function error($code, $err){ $this->Code = $code; $this->Err = $err; } /** * 设置响应信息 * @param int $code 响应码 * @param string $body 响应文本 */ public function response($code,$body){ $this->StatusCode = $code; $this->rpHeader = array(); $this->rpBody = $body; $this->ContentLength = strlen($body); } /** * 判断是否有body或者设置了application/x-www-form-urlencoded头 * @return bool */ public function incBody(){ $body = $this->rpBody; if (!isset($body)) { return false; } $ct = self::getHeaderType($this->rpHeader, 'Content-Type'); if ($ct === 'application/x-www-form-urlencoded') { return true; } return false; } /** * 获得头类型值 * @param array $header * @param string $key */ public function getHeaderType($header, $key){ $val = @$header[$key]; if (isset($val)) { if (is_array($val)) { return $val[0]; } return $val; } else { return ''; } } /** * 请求过程 */ public function RoundTrip(){ $incbody = self::incBody(); $token = self::SignRequest($incbody); $this->rqHeader['Authorization'] = "QBox $token"; return self::doCall(); } /** * 请求签名 * @param int $incbody */ public function SignRequest($incbody) { $url = $this->URL; $url = parse_url($url['path']); $data = ''; if (isset($url['path'])) { $data = $url['path']; } if (isset($url['query'])) { $data .= '?' . $url['query']; } $data .= "\n"; if ($incbody) { $data .= $this->Body; } return $this->Sign($data); } /** * 数据签名 * @param array $data 需签名数据 */ public function Sign($data){ $sign = hash_hmac('sha1', $data, $this->AppSecret, true); return $this->AppKey . ':' . self::SafeBaseEncode($sign); } public function SignWithData($data){ $data = self::SafeBaseEncode($data); return $this->Sign($data) . ':' . $data; } /** * 设置相应错误信息 */ public function setResponse(){ $header = $this->rpHeader; $details = self::getHeaderType($header, 'X-Log'); $reqId = self::getHeaderType($header, 'X-Reqid'); self::error($this->StatusCode, null); if ($this->Code > 299) { if ($this->ContentLength !== 0) { if (self::getHeaderType($header, 'Content-Type') === 'application/json') { $ret = json_decode($this->rpBody, true); $this->Err = $ret['error']; } } } } /** * 获得响应结果信息 * @return object */ public function getReponseErr(){ $data['Err']=$this->Err; // string $data['Reqid']=$this->Reqid; // string $data['Details']=$this->Details; // []string $data['Code']=$this->Code; // int return (object)($data); } public function getReponseRet(){ $code = $this->StatusCode; $data = null; if ($code >= 200 && $code <= 299) { if ($this->ContentLength !== 0) { $data = json_decode($this->rpBody, true); if ($data === null) { self::error(0, 'json decode null'); } } if ($code === 200) { return array($data, null); } } return array($data, self::getReponseErr()); } } ?><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html> <html> <head> <title>后台管理</title> </head> <body class="easyui-layout"> <div class="header" id="sessionInfoDiv"> <div class="topleft"> <img src="__PUBLIC__/images/logo.jpg" title="水果博士后台管理系统" style="border: none;height:70px;width:200px" /><a href="javascript:void(0);" style="display:none">水果博士后台管理系统 </a> </div> <div class="topcenter"> </div> <div class="topright"> <div class="topright_button"> <a href="javascript:void(0);" class="easyui-linkbutton" iconcls="icon-user" plain="true"> <c:if test="${sessionInfo.username != null}">欢迎管理员:[<strong><?php echo ($_SESSION['username']); ?></strong>]使用后台管理系统</c:if> </a> <a href="javascript:void(0);" class="easyui-linkbutton" iconcls="icon-kzmb" plain="true" onclick="javascript:changepsw()">修改密码</a> <a href="javascript:void(0);" class="easyui-linkbutton" iconcls="icon-zx" plain="true" onclick="$.messager.confirm('注销','您确定要退出么?',function(r){if(r)(logout(true))});">注销</a> </div> </div> </div> <!-- 初始化密码的表单 --> <div id="changepswDlg" class="easyui-dialog" style="width: 400px; height: 220px; overflow: hidden; padding: 10px 20px" scroll="no" closed="true" buttons="#changepswDlgBtn"> <form id="changepswForm" method="post"> <table width="400" border="0"> <tr> <td align="right"> 原密码: </td> <td> <input name="password" type="<PASSWORD>" class="easyui-validatebox textbox" required missingmessage="密码不能为空" /> </td> </tr> <tr> <td align="right"> 新密码: </td> <td> <input name="newpassword" id="newpassword1" type="password" class="easyui-validatebox textbox" required missingmessage="密码不能为空" /> </td> </tr> <tr> <td align="right"> 重输新密码: </td> <td> <input name="newpassword2" id="newpassword2" type="password" class="easyui-validatebox textbox" required missingmessage="密码不能为空" /> </td> </tr> </table> </form> </div> <div id="changepswDlgBtn"> <a href="#" id="addSaveBooktimecode" class="easyui-linkbutton" iconcls="icon-ok" onclick="changepsw_ok()">确认</a> <a href="#" class="easyui-linkbutton" iconcls="icon-cancel" onclick="javascript:$('#changepswDlg').dialog('close')">取消</a> </div> </body> </html><file_sep><?php if (!defined('THINK_PATH')) exit();?><script type="text/javascript" charset="utf-8"> var centerTabs; var tabsMenu; $(function() { tabsMenu = $('#tabsMenu').menu({ onClick : function(item) { var curTabTitle = $(this).data('tabTitle'); var type = $(item.target).attr('type'); if (type === 'refresh') { refreshTab(curTabTitle); return; } if (type === 'close') { var t = centerTabs.tabs('getTab', curTabTitle); if (t.panel('options').closable) { centerTabs.tabs('close', curTabTitle); } return; } var allTabs = centerTabs.tabs('tabs'); var closeTabsTitle = []; $.each(allTabs, function() { var opt = $(this).panel('options'); if (opt.closable && opt.title != curTabTitle && type === 'closeOther') { closeTabsTitle.push(opt.title); } else if (opt.closable && type === 'closeAll') { closeTabsTitle.push(opt.title); } }); for ( var i = 0; i < closeTabsTitle.length; i++) { centerTabs.tabs('close', closeTabsTitle[i]); } } }); centerTabs = $('#centerTabs').tabs({ fit : true, border : false, onContextMenu : function(e, title) { e.preventDefault(); tabsMenu.menu('show', { left : e.pageX, top : e.pageY }).data('tabTitle', title); } }); }); function addTab(cname,curl,ciconCls) { if (centerTabs.tabs('exists', cname)) { centerTabs.tabs('select', cname); } else { if (curl && curl.length > 0) { /*if (curl.indexOf('!druid.do') < 0) {/*数据源监控页面不需要开启等待提示 $.messager.progress({ text : '页面加载中....', interval : 100 }); window.setTimeout(function() { try { $.messager.progress('close'); } catch (e) { } }, 5000); }*/ centerTabs.tabs('add', { title : cname, closable : true, iconCls : ciconCls, content : '<iframe src="' + curl + '" frameborder="0" style="border:0;width:100%;height:99.4%;"></iframe>', tools : [ { iconCls : 'icon-mini-refresh', handler : function() { refreshTab(cname); } } ] }); } else { centerTabs.tabs('add', { title : cname, closable : true, iconCls : ciconCls, content : '<iframe src="error/err.jsp" frameborder="0" style="border:0;width:100%;height:99.4%;"></iframe>', tools : [ { iconCls : 'icon-mini-refresh', handler : function() { refreshTab(cname); } } ] }); } } } function refreshTab(title) { var tab = centerTabs.tabs('getTab', title); centerTabs.tabs('update', { tab : tab, options : tab.panel('options') }); } </script> <div id="centerTabs"> </div> <script> $(function(){ addTab('所有订单','__APP__/Order/index'); }) </script> <div id="tabsMenu" style="width: 120px;display:none"> <div type="refresh">刷新</div> <div class="menu-sep"></div> <div type="close">关闭</div> <div type="closeOther">关闭其他</div> <div type="closeAll">关闭所有</div> </div><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link id="easyuiTheme" rel="stylesheet" type="text/css" href="__PUBLIC__/themes/bootstrap/easyui.css" /> <link rel="stylesheet" type="text/css" href="__PUBLIC__/themes/icon.css" /> <script type="text/javascript" src="__PUBLIC__/js/jquery-1.8.0.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/jquery.easyui.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/admin.js" charset="utf-8"></script> <script type="text/javascript" charset="utf-8"> var datagrid = $('#datagrid_user'); var isClickOk = true; function edit(id) { $.ajax({ url: '__APP__/User/getUserById', data: {id: id}, dataType: 'json', success: function (rows) { $('#_username').val(rows.name); $("input[name='member_id']").val(rows.member_id); $('#_phone_number').val(rows.phone_number); $('#_identity_card').val(rows.identity_card); } }); $('#editDlg').dialog('open').dialog('setTitle', '修改用户信息'); } function initpsw(num) { $('#_user_id').val(num); $('#initpswDlg').dialog('open').dialog('setTitle', '确定要重置密码?'); } function initpsw_ok() { $('#initpswForm').form('submit', { url: "__APP__/User/initPwd", dataType: 'json', onSubmit: function () { $.messager.alert('操作提示', '重置后的密码是:<PASSWORD>', 'info'); return true; } }); $('#datagrid_user').datagrid('reload'); $('#initpswDlg').dialog('close'); } function exportData() { var rows = $('#datagrid_user').datagrid('getChecked'); var ids = []; for (var i = 0; i < rows.length; i++) { ids.push(rows[i].user_id); } var str = ids.join(','); var href = '__APP__/User/export?idstr='+str; location.href=href; } function _search() { $('#datagrid_user').datagrid('loadData', { total: 0, rows: [] }); $('#datagrid_user').datagrid('load', dj.serializeObject($('#searchForm'))); } function cleanSearch() { $('#datagrid_user').datagrid('load', {}); $('#searchForm input').val(''); } function edit_ok() { $.messager.defaults = { ok: "确定", cancel: "取消" }; $.messager.confirm('Confirm', '您确定修改?', function (r) { if (r) { $('#editForm').form('submit', { url: "__APP__/User/edit", dataType: 'json', onSubmit: function () { if ($('#editForm').form('validate')) { datagrid.datagrid('loadData', { total: 0, rows: [] }); datagrid.datagrid('load'); $.messager.alert('操作提示', '修改信息成功!', 'info'); return true; } else { $.messager.alert('操作提示', '信息填写不完整!', 'error'); return false; } } }); $('#datagrid_user').datagrid('reload'); $('#editDlg').dialog('close'); } }); } function formatOper(val,row,index){ var str= '<a href="javascript:void(0);" onclick="edit('+row.member_id+')">修改</a>'; return str; } function formatsex(val,row,index){ return (row.sex==1)?"女":"男"; } function formatphone(val,row,index){ return row.user_id; } function formataddress(val,row,index){ return row.address1+''+row.address2+''+row.address3; } </script> <title>后台管理</title> </head> <body> <div class="easyui-panel" data-options="fit:true"> <table class="easyui-datagrid" id="datagrid_user" data-options="url:'__APP__/User/getAllUser',method:'post',pagination:true,fit:true,toolbar:'#toolbar',rownumbers:true,checkOnSelect: true"> <thead> <tr> <th data-options="field:'member_id',sortable: true,checkbox: true">ID</th> <th data-options="field:'name',sortable: true" width="100">用户姓名</th> <th data-options="field:'identity_card',sortable: true" width="150">身份证号</th> <th data-options="field:'phone_number',sortable: true" width="150" >手机号</th> <th data-options="field:'score',sortable: true" width="100">积分</th> <th data-options="field:'created_at',align:'center',sortable: true" width="130">注册时间</th> <th data-options="field:'hotel_name',align:'center',sortable: true" width="200" >酒店</th> <th data-options="field:'cz',width:120,align:'center',formatter:formatOper">操作</th> </tr> </thead> </table> <div id="toolbar" style="padding:5px;"> <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-print" plain="true" onclick="">导出csv</a> <form id="searchForm" style="display:inline-block;*display:inline;zoom:1;"> <input name="search" placeholder="标题或内容" data-options="prompt:'请输入搜索内容',searcher:''" class="easyui-validatebox textbox" style="width: 180px; vertical-align: middle;" /> <input name="hiddenid" id="hiddenid" type="hidden" /> <a href="javascript:void(0);" class="easyui-linkbutton" plain="true" onclick="_search();">搜索</a> </form> </div> </div> <!-- 修改用户信息的表单 --> <div id="editDlg" class="easyui-dialog" style="width: 450px; height: 300px; padding: 10px 20px" closed="true" buttons="#editDlgBtn" data-options="modal:true" > <form id="editForm" method="post"> <input type="hidden" name="user_id" value="" /> <table width="350" border="0"> <tr> <td width="150" align="right"> 用户姓名: </td> <td width="250"> <input name="name" id="_username" class="easyui-validatebox textbox"/> </td> <input type="hidden" name="member_id" id="_memberid" /> </tr> <tr> <td align="right"> 手机号: </td> <td> <input name="phone_number" id="_phone_number" class="easyui-validatebox textbox" /> </td> </tr> <tr> <td align="right"> 身份证号: </td> <td> <input name="identity_card" id="_identity_card" class="easyui-validatebox textbox" /> </td> </tr> </table> </form> </div> <!-- 密码重置 --> <!-- 修改用户信息的表单 --> <div id="initpswDlg" class="easyui-dialog" style="width: 400px; height: 300px; padding: 10px 20px" closed="true" buttons="#initpswDlgBtn" data-options="modal:true"> <form id="initpswForm" method="post"> <input type="hidden" name="user_id" id="_user_id" value="" /> 重置密码为:<PASSWORD>. </form> </div> <!-- 修改户信息的按钮,被Jquery设置,当没被调用的时候不显示 --> <div id="initpswDlgBtn"> <a href="#" class="easyui-linkbutton" iconcls="icon-ok" onclick="initpsw_ok()">确认</a> <a href="#" class="easyui-linkbutton" iconcls="icon-cut" onclick="javascript:$('#initpswDlg').dialog('close')">取消</a> </div> <!-- 修改户信息的按钮,被Jquery设置,当没被调用的时候不显示 --> <div id="editDlgBtn"> <a href="#" id="addSaveBooktimecode" class="easyui-linkbutton" iconcls="icon-ok" onclick="edit_ok()">确认</a> <a href="#" class="easyui-linkbutton" iconcls="icon-cut" onclick="javascript:$('#editDlg').dialog('close')">取消</a> </div> </body> </html><file_sep><?php class JoinAction extends Action { public function index() { $list = M('contants')->select(); // var_dump($list); $this->assign('list',$list); $this->display(); } } ?><file_sep><?php // 本类由系统自动生成,仅供测试用途 class MembersModel extends RelationModel{ } ?><file_sep><?php if (!defined('THINK_PATH')) exit();?> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="description" content="Tsys管理系统"> <title>后台管理</title> <link id="easyuiTheme" rel="stylesheet" type="text/css" href="__PUBLIC__/themes/bootstrap/easyui.css"> <link rel="stylesheet" type="text/css" href="__PUBLIC__/themes/icon.css"> <script type="text/javascript" src="__PUBLIC__/js/jquery-1.8.0.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/jquery.easyui.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/admin.js" charset="utf-8"></script> </head> <link rel="stylesheet" type="text/css" href="__PUBLIC__/uploadify/uploadify.css" /> <script src="__PUBLIC__/uploadify/jquery.uploadify.min.js" type="text/javascript"></script> <script src="__PUBLIC__/layer/layer.js" type="text/javascript"></script> <body> <div class="easyui-panel" fit="true"> <form action="<?php echo U('Goods/doadd');?>" id="addForm" method="post" enctype="multipart/form-data" onsubmit="return check()"> <table width="780" border="0"> <tr style="height: 50px;"> <td width="100" align="right"> 房间名称: </td> <td width="250"> <input name="type_name" style="width: 250px" value="" id="name"/> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 房间价格: </td> <td width="250"> <input name="room_price" style="width: 250px" value=""/ id="price"> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 房间数量: </td> <td width="250"> <input name="room_count" style="width: 250px" value="" id="count"/> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 床位类型 : </td> <td width="250"> <input name="bed_type" style="width: 250px" value="" id="bedtype"/> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 房间大小: </td> <td width="250"> <input name="room_area" style="width: 250px" value="" id="roombs"/> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 容纳人数: </td> <td width="250"> <input name="people_num" style="width: 250px" value="" id="peoplenum"/> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 房间所在楼层: </td> <td width="250"> <input name="floors" style="width: 250px" value="" id="floor"/> </td> </tr> <!-- <tr style="height: 50px;"> <td width="100" align="right"> 房间类型: </td> <td width="250" align="left"> <select name="room_type" style="width:100px"> <option value="2">标准型</option> <option value="3">豪华型</option> <option value="4">奢靡型</option> <option value="5">总统型</option> </select> </td> </tr> --> <tr style="height: 50px;"> <td width="100" align="right"> 有无早餐: </td> <td width="250" align="left"> <select name="breakfast" style="width:100px"> <option value="0">无</option> <option value="1">有</option> </select> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 可否加床: </td> <td width="250" align="left"> <select name="bed_add" style="width:100px"> <option value="0">可以</option> <option value="1">不可以</option> </select> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 加床价格: </td> <td width="250"> <input name="addprice" style="width: 250px" value="" id="addbed"/> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 单床大小: </td> <td width="250"> <input name="bed_area" style="width: 250px" value="" id="bedarea"/> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 可否吸烟: </td> <td width="250" align="left"> <select name="smoke" style="width:100px"> <option value="0">可以</option> <option value="1">不可以</option> </select> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 是否有热水: </td> <td width="250" align="left"> <select name="hot_water" style="width:100px"> <option value="0">有</option> <option value="1">没有</option> </select> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 是否有空调: </td> <td width="250" align="left"> <select name="air_conditioner" style="width:100px"> <option value="0">有</option> <option value="1">没有</option> </select> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 无线网络: </td> <td width="250" align="left"> <select name="internet" style="width:100px"> <option value="none">无</option> <option value="wifi">wifi</option> <option value="broadband">broadband</option> </select> </td> </tr> <tr style="height: 50px;"> <td align="right"> 图片上传: </td> <td> <input id="picture" name="file_upload" type="file" multiple="false"> <div id="up_image" class="image"> </div> </td> </tr> </table> <div style="text-align:left;padding:20px;"> <input type="submit" value="添加"> </div> </form> </div> <script type="text/javascript"> function check() { if ($('#name').val() == '') { layer.msg('请输入房间名称'); setTimeout(function(){ $('#name').focus(); }); return false; }else if($('#price').val() == ''){ layer.msg('请输入房间价格'); setTimeout(function(){ $('#price').focus(); }); return false; }else if($('#count').val() == ''){ layer.msg('请输入床位数量'); setTimeout(function(){ $('#count').focus(); }); return false; }else if($('#bedtype').val() == ''){ layer.msg('请输入床位类型'); setTimeout(function(){ $('#bedtype').focus(); }); return false; }else if($('#roombs').val() == ''){ layer.msg('请输入房间大小'); setTimeout(function(){ $('#roombs').focus(); }); return false; }else if($('#peoplenum').val() == ''){ layer.msg('请输入容纳人数'); setTimeout(function(){ $('#peoplenum').focus(); }); return false; }else if($('#floor').val() == ''){ layer.msg('请输入房间所在楼层'); setTimeout(function(){ $('#floor').focus(); }); return false; }else{ return true; } } </script> </body><file_sep><?php if (!defined('THINK_PATH')) exit();?> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="description" content="Tsys管理系统"> <title>后台管理</title> <link id="easyuiTheme" rel="stylesheet" type="text/css" href="__PUBLIC__/themes/bootstrap/easyui.css"> <link rel="stylesheet" type="text/css" href="__PUBLIC__/themes/icon.css"> <script type="text/javascript" src="__PUBLIC__/js/jquery-1.8.0.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/jquery.easyui.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/admin.js" charset="utf-8"></script> </head> <link rel="stylesheet" type="text/css" href="__PUBLIC__/uploadify/uploadify.css" /> <script src="__PUBLIC__/uploadify/jquery.uploadify.min.js" type="text/javascript"></script> <script src="__PUBLIC__/js/jquery.min.js" type="text/javascript"></script> <script src="__PUBLIC__/js/bootstrap.min.js" type="text/javascript"></script> <style> .stage{ position:absolute; top:0; bottom:0; left:0; right:0; background:rgba(0,0,0,0.2); display:none; } .form{ position:absolute; top:50%; left:50%; transform: translate(-50%,-50%); padding:10px; background: #fff; } .close{ position:absolute; cursor: pointer; top:0; right:0; transform: translate(50%,-50%); width:14px; height:14px; text-align: center; line-height:14px; border-radius: 100%; background:gray; } </style> <body> <div> <form action="<?php echo U('Goods/index');?>" method="get"> <div style="float:left"> <select name="chaxun" id=""> <option value="1">房间名称</option> <option value="2">床位类型</option> </select> </div> <div style="float:left"> <input type="text" name="hotel" > </div> <div> <input type="submit" value="搜索"> </div> </form> </div> <div > <table border="1" cellpadding="1" cellspacing="1" width="100%" align="center"> <thead> <tr> <th >ID</th> <th >房间名称</th> <th >房间大小</th> <th >床位类型</th> <th >房间价格</th> <th >可住人数</th> <th width="80">房间数量</th> <th width="80">其他</th> <th width="80">房间图片</th> <th width="200">操作</th> </tr> <?php if(is_array($list)): $i = 0; $__LIST__ = $list;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$vo): $mod = ($i % 2 );++$i;?><tr height="50px"> <th><?php echo ($vo["id"]); ?></th> <th><?php echo ($vo["name"]); ?></th> <th><?php echo ($vo["area"]); ?></th> <th><?php echo ($vo["display_name"]); ?></th> <th><?php echo ($vo["price"]); ?></th> <th><?php echo ($vo["people_num"]); ?></th> <th><?php echo ($vo["count_num"]); ?></th> <!-- <th> <?php if($vo["breakfast"] == 1): ?>有 <?php else: ?>无<?php endif; ?> </th> --> <th> <button class="qita" onclick="other(<?php echo ($vo["id"]); ?>)">其他</button> <div class="stage qita_<?php echo ($vo["id"]); ?>" > <div class="form"> <table border="1"> <tr> <th width="80">早餐</th> <th width="80">加床</th> <th width="80">加床价格</th> <th width="80">单床大小</th> <th width="80">吸烟</th> <th width="80">热水</th> <th width="80">空调</th> <th width="80">网络</th> <th width="80">所在楼层</th> </tr> <tr> <td> <?php if($vo["breakfast"] == 0): ?>有 <?php else: ?>无<?php endif; ?> </td> <td> <?php if($vo["bed_add"] == 0): ?>可以 <?php else: ?>不可以<?php endif; ?> </td> <td><?php echo ($vo["bed_add_price"]); ?></td> <td><?php echo ($vo["bed_area"]); ?></td> <td> <?php if($vo["smoke"] == 0): ?>可以 <?php else: ?>不可以<?php endif; ?> </td> <td> <?php if($vo["hot_water"] == 0): ?>有 <?php else: ?>没有<?php endif; ?> </td> <td> <?php if($vo["air_conditioner"] == 0): ?>有 <?php else: ?>没有<?php endif; ?> </td> <td> <?php if($vo["internet"] == 'wifi'): ?>wifi <?php elseif($vo["internet"] == 'wired'): ?>有线 <?php else: ?>无<?php endif; ?> </td> <td><?php echo ($vo["floors"]); ?></td> </tr> </table> <span class="close">&times;</span> <div> </div> </th> <th> <button class="btn" onclick="show(<?php echo ($vo["id"]); ?>)">酒店图片</button> <div class="stage img_<?php echo ($vo["id"]); ?>" > <div class="form"> <img src="/Public/image/room/<?php echo ($vo["url"]); ?>" alt=""> <span class="close">&times;</span> <div> </div> </th> <th><a href="<?php echo U('Goods/uppd');?>?id=<?php echo ($vo["id"]); ?>" >编辑信息</a> <a href="<?php echo U('Goods/edrompic');?>?id=<?php echo ($vo["id"]); ?>">编辑图片</a> <a href="<?php echo U('Goods/updel');?>?id=<?php echo ($vo["id"]); ?>" >删除</a> </th> </tr><?php endforeach; endif; else: echo "" ;endif; ?> </thead> </table> <!-- </form> --> <!-- <div id="toolbar" style="padding:5px;"> <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-print" plain="true" onclick="exportData()">导出CSV</a> <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="addPanel()">新增</a> --> <!-- <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cut" plain="true" onclick="deleteData()">删除</a>--> <!-- <form id="searchForm" style="display:inline-block;*display:inline;zoom:1;"> <input name="search" placeholder="名称" data-options="prompt:'请输入搜索内容',searcher:''" class="easyui-validatebox textbox" style="width: 180px; vertical-align: middle;" /> <input name="hiddenid" id="hiddenid" type="hidden" /> <a href="javascript:void(0);" class="easyui-linkbutton" plain="true" onclick="s_data();">搜索</a> </form> </div> --> <!-- 添水果详情 --> <!-- <div id="viewDlg" class="easyui-dialog" style="width: 400px; height: 300px; padding: 10px 20px"> <table border="0" style="height:300px;width:400px"> <tr> <td width="100" height="30" align="right">房间名称: </td> <td width="300" height="30"><span id="_type_name"></span></td> </tr> <tr> <td width="100" height="30" align="right">描述:</td> <td width="300" height="30"><span id="_description"></span></td> </tr> <tr> <td align="right">图片:</td> <td><img name="" src="" width="300" height="230" alt="" id="_room_image"/></td> </tr> </table> </div> --> </div> <script type="text/javascript" src="__PUBLIC__/lhgdialog/lhgdialog.min.js"></script> <script type="text/javascript"> function show(id) { $('.img_'+id).fadeIn('1000'); } $('.close').click(function(){ $('.stage').fadeOut('1000'); }) function other(id) { $('.qita_'+id).fadeIn('1000'); } // function convert(rows) { // function exists(rows, parentId) { // for (var i = 0; i < rows.length; i++) { // if (rows[i].id == parentId) return true; // } // return false; // } // var nodes = []; // for (var i = 0; i < rows.length; i++) { // var row = rows[i]; // if (!exists(rows, row.parentId)) { // nodes.push({ // id: row.type_id, // text: row.name // }); // } // } // var toDo = []; // for (var i = 0; i < nodes.length; i++) { // toDo.push(nodes[i]); // } // while (toDo.length) { // var node = toDo.shift(); // the parent node // // get the children nodes // for (var i = 0; i < rows.length; i++) { // var row = rows[i]; // if (row.parentId == node.id) { // var child = { id: row.type_id, text: row.name }; // if (node.children) { // node.children.push(child); // } else { // node.children = [child]; // } // toDo.push(child); // } // } // } // return nodes; // } // //添加产品 // function addData(){ // var node = $('#menu-tree').tree("getSelected"); // //if(node === null){ // if(node == null){ // $.dialog({lock:true,time: 3,icon:'error.gif',title:'错误提示',content: '请选择要添加的菜单!'}); // return false; // }else{ // var pid = node.id; // $.post("<?php echo U('Goods/addpd');?>",{pid:pid},function(data){ // $('#audata').html(data); // }); // } // } // //删除选中项 // function deleteData() { // var datagrid = $("#tab_data"); // var rows = datagrid.datagrid('getChecked'); // var ids = []; // if (rows.length > 0) { // parent.dj.messagerConfirm('请确认', '您要删除当前所选项目?', function(r) { // if (r) { // for ( var i = 0; i < rows.length; i++) { // ids.push(rows[i].fruit_id); // } // $.ajax({ // url : '__APP__/Goods/delete', // data : { // ids : ids.join(',') // }, // dataType : 'json', // success : function(d) { // datagrid.datagrid('load'); // datagrid.datagrid('unselectAll'); // parent.dj.messagerShow({ // title : '提示', // msg : d.info // }); // } // }); // } // }); // } else { // parent.dj.messagerAlert('提示', '请勾选要删除的记录!', 'error'); // } // } // function formatType(val,row,index){ // var type = row.type; // var typename = ''; // switch(type){ // case "tehuishuiguo": // typename = '特惠水果'; // break; // case "jinkoushuiguo": // typename = '进口水果'; // break; // case "shiyanshitaocan": // typename = '实验室套餐'; // break; // case "gerentaocan": // typename = '个人套餐'; // break; // case "zhengxiangpifa": // typename = '整箱批发'; // break; // case "yinliaoguozhi": // typename = '饮料果汁'; // break; // case "lingshi": // typename = '零食'; // break; // case "qita": // typename = '其他'; // break; // } // return typename; // } // function formatOper(val,row,index){ // var optr = '<a href="javascript:void(0);" onclick="edit('+row.type_id+')">修改</a>'; // optr +=' &nbsp;&nbsp;<a href="javascript:void(0);" onclick="view('+row.type_id+')">详情</a>'; // return optr; // } // function view(id){ // $.ajax({ // url: '__APP__/Goods/getGoodsById', // data: {id: id}, // dataType: 'json', // async:false, // success: function (rows) { // $('#_type_name').html(rows.type_name); // $('#_room_image').attr('src',rows.image_url); // $('#_description').html(rows.description); // } // }); // var html = $('#viewDlg').clone(); // $.dialog({ // id:'test123', // lock: true, // content: html, // width: 400, // height: 250, // title:'查看房间详情', // cancel: true // }); // } // function addPanel(){ // $.dialog({ // id:'testadd', // lock: true, // //content: 'url:/admin.php/Goods/addpd', // url: '__APP__/Goods/addpd', // content: 'url:__APP__/Goods/addpd', // width: 800, // height: 500, // title:"房间添加", // cancel:function(){ // window.location.reload(); // } // }); // } // function edit(id){ // $.dialog({ // id:'testedit', // lock: true, // //content: 'url:/admin.php/Goods/uppd/id/'+id, // //url: '__APP__/Goods/uppd?id='+id, // content: 'url: __APP__/Goods/uppd?id='+id, // width: 800, // height: 350, // title:"房间编辑", // cancel:function(){ // window.location.reload(); // } // }); // } // function exportData() { // } // //搜索名称 // function s_data() { // $('#tab_data').datagrid('loadData', { total: 0, rows: [] }); // $('#tab_data').datagrid('load', dj.serializeObject($('#searchForm'))); // } </script> </body> </html><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html> <html lang="en"> <head> <script type="text/javascript" src="__PUBLIC__/js/jquery-1.8.0.min.js"></script> <script type="text/javascript" src="__PUBLIC__/layer/layer.js"></script> <meta charset="UTF-8"> <title>Document</title> </head> <body> <h1>添加子类</h1> <table style="margin-top:50px"> <form action="<?php echo U('Adminstore/addchild');?>" method="post" onsubmit="return check()"> <tr> <th> <input type="hidden" name="pid" value="<?php echo ($pid); ?>" readonly="readonly"> <input type="hidden" name="path" value="<?php echo ($path); ?>" readonly="readonly"> 名称: <input type="text" name="cname" class="cname"> </th> <th> <input type="submit"> </th> </tr> </table> </form> <script> function check() { if ($('.cname').val() == '') { layer.msg('请输入分类名'); setTimeout(function(){ $('.cname').focus(); }); return false; } } </script> </body> </html><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="description" content="Tsys管理系统"> <title>后台管理</title> <link id="easyuiTheme" rel="stylesheet" type="text/css" href="__PUBLIC__/themes/bootstrap/easyui.css"> <link rel="stylesheet" type="text/css" href="__PUBLIC__/themes/icon.css"> <script type="text/javascript" src="__PUBLIC__/js/jquery-1.8.0.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/jquery.easyui.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/admin.js" charset="utf-8"></script> </head> <link rel="stylesheet" type="text/css" href="__PUBLIC__/uploadify/uploadify.css" /> <script src="__PUBLIC__/uploadify/jquery.uploadify.min.js" type="text/javascript"></script> <script src="__PUBLIC__/layer/layer.js" type="text/javascript"></script> <script src="__PUBLIC__/ueditor/ueditor.config.js" type="text/javascript"></script> <script src="__PUBLIC__/ueditor/ueditor.all.js" type="text/javascript"></script> <script type="text/javascript" src="http://api.map.baidu.com/api?v=1.3"></script> <body> <div class="easyui-panel" fit="true"> <form action="<?php echo U('Goods/doedithotel');?>" id="editForm" method="post" enctype="multipart/form-data" onsubmit = "return check()"> <input name="hotel_id" type="hidden" value="<?php echo ($list["id"]); ?>"/> <table width="780" border="0"> <tr style="height: 50px;"> <td width="100" align="right"> 酒店名称: </td> <td width="250"> <input name="hotel_name" style="width: 250px" value="<?php echo ($list["name"]); ?>" id="name"/> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 酒店星级: </td> <td width="250"> <select name="hotel_star"> <option value="inn" <?php if($list["grade"] == 'inn'): ?>selected<?php endif; ?>>客栈公寓</option> <option value="chain" <?php if($list["grade"] == 'chain'): ?>selected<?php endif; ?>>经济连锁</option> <option value="theme" <?php if($list["grade"] == 'theme'): ?>selected<?php endif; ?>>主题酒店</option> <option value="three_star" <?php if($list["grade"] == 'three_star'): ?>selected<?php endif; ?>>三星舒适</option> <option value="four_star" <?php if($list["grade"] == 'four_star'): ?>selected<?php endif; ?>>四星高档</option> <option value="five_star" <?php if($list["grade"] == 'five_star'): ?>selected<?php endif; ?>>五星豪华</option> </select> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 酒店电话: </td> <td width="250"> <input name="hotel_telephone" style="width: 250px" value="<?php echo ($list["phone_number"]); ?>" id="phone"/> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 酒店地址: </td> <td width="250"> <select name="address1" id="address1" > </select> <select name="address2" id="address2"> </select> <select name="address3" id="address3"> </select> <input name="hotel_address" style="width: 200px" value="<?php echo ($list["address"]); ?>" id="address"/> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 地址经度: </td> <td width="250"> <input name="longitude" placeholder="请在底部的地图上查询经度" style="width: 250px" value="<?php echo ($list["longitude"]); ?>" id="longitude"/> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 地址纬度: </td> <td width="250"> <input name="latitude" placeholder="请在底部的地图上查询纬度" style="width: 250px" value="<?php echo ($list["latitude"]); ?>" id="latitude"/> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 酒店邮箱: </td> <td width="250"> <input name="hotel_email" style="width: 250px" value="<?php echo ($list["email"]); ?>" id="email"/> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 基础设施: </td> <td width="250"> <label><input type="checkbox" name="checkbox[]" value="1" <?php if($row[0][infrastructure_id] == 1): ?>checked<?php endif; ?> >停车场</label> <label><input type="checkbox" name="checkbox[]" value="2" <?php if($row[1][infrastructure_id] == 2): ?>checked<?php endif; ?> >游泳池</label> <label><input type="checkbox" name="checkbox[]" value="3" <?php if($row[2][infrastructure_id] == 3): ?>checked<?php endif; ?> >接送服务</label> <label><input type="checkbox" name="checkbox[]" value="4" <?php if($row[3][infrastructure_id] == 4): ?>checked<?php endif; ?>>健身房</label> <label><input type="checkbox" name="checkbox[]" value="5" <?php if($row[4][infrastructure_id] == 5): ?>checked<?php endif; ?> >社交圈</label> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 路线: </td> <td width="250"> <textarea style="width: 600px;height: 100px;" name="routes" id="route"><?php echo ($list["routes"]); ?></textarea> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 退订和改签规则: </td> <td width="250"> <textarea style="width: 600px;height: 100px;" name="content" id="contents"><?php echo ($list['endorse_rules']); ?></textarea> </td> </tr> <tr style="height: 220px;"> <td align="right"> 酒店简介: </td> <td> <textarea style="width: 600px;height: 200px;" name="introduction" id="intro"><?php echo ($list["introduction"]); ?></textarea> </td> </tr> </table> <div style="text-align:left;padding:20px;"> <input type="submit" value="修改"> <!-- <a href="" class="easyui-linkbutton" style="width:80px" ">修改</a> --> </div> </form> <div style="width:730px;margin:auto;"> 要查询的地址:<input id="text_" type="text" value="徐州古彭广场" style="margin-right:100px;"/> 查询结果(经纬度):<input id="result_" type="text" /> <input type="button" value="查询" onclick="searchByStationName();"/> <div id="container" style=" margin-top:30px; width: 730px; height: 590px; top: 50; border: 1px solid gray; overflow:hidden;"> </div> </div> </div> <!-- <script type="text/javascript" src="__PUBLIC__/lhgdialog/lhgdialog.min.js"></script> --> <script type="text/javascript"> var map = new BMap.Map("container"); map.centerAndZoom("徐州", 12); map.enableScrollWheelZoom(); //启用滚轮放大缩小,默认禁用 map.enableContinuousZoom(); //启用地图惯性拖拽,默认禁用 map.addControl(new BMap.NavigationControl()); //添加默认缩放平移控件 map.addControl(new BMap.OverviewMapControl()); //添加默认缩略地图控件 map.addControl(new BMap.OverviewMapControl({ isOpen: true, anchor: BMAP_ANCHOR_BOTTOM_RIGHT })); //右下角,打开 var localSearch = new BMap.LocalSearch(map); localSearch.enableAutoViewport(); //允许自动调节窗体大小 function searchByStationName() { map.clearOverlays();//清空原来的标注 var keyword = document.getElementById("text_").value; localSearch.setSearchCompleteCallback(function (searchResult) { var poi = searchResult.getPoi(0); document.getElementById("result_").value = poi.point.lng + "," + poi.point.lat; map.centerAndZoom(poi.point, 13); var marker = new BMap.Marker(new BMap.Point(poi.point.lng, poi.point.lat)); // 创建标注,为要查询的地方对应的经纬度 map.addOverlay(marker); var content = document.getElementById("text_").value + "<br/><br/>经度:" + poi.point.lng + "<br/>纬度:" + poi.point.lat; var infoWindow = new BMap.InfoWindow("<p style='font-size:14px;'>" + content + "</p>"); marker.addEventListener("click", function () { this.openInfoWindow(infoWindow); }); // marker.setAnimation(BMAP_ANIMATION_BOUNCE); //跳动的动画 var jing = poi.point.lng; var wei = poi.point.lat; console.log(jing) console.log(wei) }); localSearch.search(keyword); } </script> <script type="text/javascript"> //三级联动地址 //获取省份的数据 $.ajax({ type:'get', url:"<?php echo U('City/addred');?>", async:false, success:function(data){ //console.log(data); //将省份信息 追加到 下拉框中 //先清空原先的数据 $('#address1').empty(); //遍历省份数据 for (var i = 0; i < data.length; i++) { $('<option value="'+data[i].code+'">'+data[i].fullname+'</option>').appendTo('#address1'); }; }, dataType:'json', }) //绑定事件 $('#address1,#address2,#address3').change(function(){ var upid = $(this).val(); console.log(upid); //清空之前的所有数据 $(this).nextAll('select').empty(); //保留 $(this) 的值 var _this = $(this); //请求下一级的数据 $.ajax({ type:'get', url:"<?php echo U('City/addred');?>", data:"parent_code="+upid, success:function(data){ // console.log(data); //如果下一级没有数据,就隐藏后面的下拉框 if (!data) { _this.nextAll('select').hide(); return; } // console.log(data.length); // 填充下一级的数据 for (var i = 0; i < data.length; i++) { // console.log(_this.next('select')); $('<option value="'+data[i].code+'">'+data[i].fullname+'</option>').appendTo(_this.next('select')); } //自动触发 后面的select 的change事件 _this.next('select').trigger('change'); _this.nextAll('select').show(); }, dataType:'json', }) }) //自动触发 #address1 的change $('#address1').trigger('change'); // $('#shezhi').click(function() // { // var sheng = $('#address1').val(); // var shi = $('#address2').val(); // var qu = $('#address3').val(); // }) //上传图片 $(document).on('change','#picture',function(){ $.ajaxFileUpload({ url:'<?php echo U("Company/ImgUpload");?>', secureuri:false, fileElementId:'picture', dataType: 'json', type:'post', data: { fileElementId: 'picture'}, // success: function (data) { // $('#showimg').attr('src',data.upfile.url); // $('#imageurl').val(data.upfile.url); // }         }) }) function check() { if($('#phone').val() == ''){ layer.msg('请输入酒店电话'); setTimeout(function(){ $('#phone').focus(); }); return false; }else if($('#address').val() == ''){ layer.msg('请输入酒店地址'); setTimeout(function(){ $('#address').focus(); }); return false; }else if($('#longitude').val() == ''){ layer.msg('请输入经度'); setTimeout(function(){ $('#longitude').focus(); }); return false; }else if($('#latitude').val() == ''){ layer.msg('请输入纬度'); setTimeout(function(){ $('#latitude').focus(); }); return false; }else if($('#email').val() == ''){ layer.msg('请输入酒店邮箱'); setTimeout(function(){ $('#email').focus(); }); return false; }else if($('#route').val() == ''){ layer.msg('请输入路线'); setTimeout(function(){ $('#route').focus(); }); return false; }else if($('#contents').val() == ''){ layer.msg('请输入退订改签规则'); setTimeout(function(){ $('#contents').focus(); }); return false; }else if($('#intro').val() == ''){ layer.msg('请输入酒店简介'); setTimeout(function(){ $('#intro').focus(); }); return false; }else{ return true; } } </script> </body><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link id="easyuiTheme" rel="stylesheet" type="text/css" href="__PUBLIC__/themes/bootstrap/easyui.css" /> <link rel="stylesheet" type="text/css" href="__PUBLIC__/themes/icon.css" /> <script type="text/javascript" src="__PUBLIC__/js/jquery-1.8.0.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/jquery.easyui.min.js"></script> <script type="text/javascript" src="__PUBLIC__/layer/layer.js"></script> <script type="text/javascript" src="__PUBLIC__/js/admin.js" charset="utf-8"></script> <title>后台管理</title> </head> <style> .stage{ position:absolute; top:0; bottom:0; left:0; right:0; background:rgba(0,0,0,0.2); display:none; } .form{ position:absolute; top:50%; left:50%; transform: translate(-50%,-50%); padding:10px; background: #fff; } .close{ position:absolute; cursor: pointer; top:0; right:0; transform: translate(50%,-50%); width:14px; height:14px; text-align: center; line-height:14px; border-radius: 100%; background:gray; } </style> <body> <div > <form action="<?php echo U('Order/refund');?>" method="get"> <div style="float:left"> <select name="chaxun" id=""> <option value="1">手机号</option> </select> </div> <div style="float:left"> <input type="text" name="hotel" > </div> <div> <input type="submit" value="搜索"> </div> </form> <table border="1" cellpadding="1" cellspacing="1" width="100%" align="center"> <thead> <tr> <th >ID</th> <th >对应订单</th> <th>用户</th> <th>手机号</th> <th>退款金额</th> <th >退款方式</th> <th>到账时间</th> <th >退款状态</th> <th>操作</th> <th >备注</th> </tr> <?php if(is_array($list)): $i = 0; $__LIST__ = $list;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$vo): $mod = ($i % 2 );++$i;?><tr> <td ><?php echo ($vo["id"]); ?></td> <td ><?php echo ($vo["order_id"]); ?></td> <td><?php echo ($vo["nickname"]); ?></td> <td><?php echo ($vo["phone_number"]); ?></td> <td><?php echo ($vo["money"]); ?></td> <td> <?php if($vo["method"] == wechat): ?>微信钱包 <?php elseif($vo["method"] == store): ?>店面退款 <?php else: ?>积分<?php endif; ?> </td> <td><?php echo ($vo["refund_time"]); ?></td> <td > <?php if($vo["status"] == apply): ?>用户请求退款 <?php elseif($vo["status"] == agree): ?>酒店同意退款 <?php elseif($vo["status"] == reject): ?>酒店拒绝退款 <?php else: ?>退款到账<?php endif; ?> </td> <td style="width:300px"> <button class="agree" bh="<?php echo ($vo["id"]); ?>">同意退款</button> <button class="refuse" bh="<?php echo ($vo["id"]); ?>">拒绝退款</button> <button class="tui" bh="<?php echo ($vo["id"]); ?>">退款完成</button> <button class="mask" onclick="other(<?php echo ($vo["id"]); ?>)">修改备注</button> <div class="stage mask_<?php echo ($vo["id"]); ?>"> <div class="form"> <form action="<?php echo U('Order/editcom');?>?id=<?php echo ($vo["id"]); ?>" method="post"> <input type="text" name="mask"> <input type="submit"> </form> <span class="close">&times;</span> </div> </div> </td> <td ><?php echo ($vo["remark"]); ?></td> </tr><?php endforeach; endif; else: echo "" ;endif; ?> </thead> </table> <!-- <div id="toolbar" style="padding:5px;"> <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-print" plain="true" onclick="">导出csv</a> <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-reload" plain="true" onclick="">批量接单</a> <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-ok" plain="true" onclick="">批量处理订单</a> <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cut" plain="true" onclick="deleteData()">删除</a> <form id="searchForm" style="display:inline-block;*display:inline;zoom:1;"> <input name="search" placeholder="手机号" data-options="prompt:'请输入搜索内容',searcher:''" class="easyui-validatebox textbox" style="width: 180px; vertical-align: middle;" /> 选择分类: <select name="flag"> <option value="">全部</option> <option value="0">未入住</option> <option value="1">已入住</option> </select> 入住时间:<input name="start_time" class="easyui-datebox" data-options="formatter:myformatter,parser:myparser" /> 离开时间: <input name="end_time" class="easyui-datebox" data-options="formatter:myformatter,parser:myparser" /> <input name="hiddenid" id="hiddenid" type="hidden" /> <a href="javascript:void(0);" class="easyui-linkbutton" plain="true" onclick="_search();">搜索</a> </form> </div> </div> --> <!-- 修改订单信息的表单 --> <!-- <div id="editDlg" class="easyui-dialog" style="width: 400px; height: 300px; padding: 10px 20px" closed="true" buttons="#editDlgBtn" data-options="modal:true"> <form id="editForm" method="post"> <table width="350" border="0"> <tr> <td width="150" align="right"> 订单状态: </td> <td width="250"> <input type="radio" name="flag" value="0" />未入住 <input type="radio" name="flag" value="1" />已入住 </td> <input type="hidden" name="reservation_id" id="_orderid" /> </tr> </table> </form> </div> --> <!-- 密码重置 --> <!-- 修改订单信息的表单 --> <!-- <div id="viewDlg" class="easyui-dialog" style="width: 1200px; height: 300px; padding: 10px 20px" closed="true" buttons="#viewDlgBtn" data-options="modal:true"> <style> .itemtable th,td{ border:solid 1px #ccc; } </style> <table style="border:solid 1px #ccc;width:100%;table-layout:fixed; empty-cells:show; border-collapse: collapse; margin:0 auto; " class="itemtable"> <tr> <th>酒店名</th> <th>房间名</th> <th>客户名字</th> <th>客户手机号</th> <th>客户身份证</th> <th>入住时间</th> <th>离开时间</th> <th>订单总价格</th> <th>客户留言</th> </tr> <tbody class="itbody"></tbody> </table> </div> 修改户信息的按钮,被Jquery设置,当没被调用的时候不显示 --> <!-- <div id="viewDlgBtn"> <a href="#" class="easyui-linkbutton" iconcls="icon-cut" onclick="javascript:$('#viewDlg').dialog('close')">取消</a> </div> --> <!-- 修改户信息的按钮,被Jquery设置,当没被调用的时候不显示 --> <!-- <div id="editDlgBtn"> <a href="#" id="addSaveBooktimecode" class="easyui-linkbutton" iconcls="icon-ok" onclick="edit_ok()">确认</a> <a href="#" class="easyui-linkbutton" iconcls="icon-cut" onclick="javascript:$('#editDlg').dialog('close')">取消</a> </div> --> <script> function other(id) { $('.mask_'+id).fadeIn('1000'); } $('.close').click(function(){ $('.stage').fadeOut('1000'); }) $('.tui').click(function(){ var id = $(this).attr('bh'); $.ajax({ type:'post', url:"<?php echo U('Order/tuikuan');?>", data:{'id':id}, datatype:'json', success:function(data){ if (data >0) { alert('退款完成'); window.location.reload(); }else{ alert('无法修改状态'); } } }) }) $('.agree').click(function(){ var id = $(this).attr('bh'); $.ajax({ type:'post', url:"<?php echo U('Order/agree');?>", data:{'id':id}, datatype:'json', success:function(data){ if (data > 0) { alert('已同意'); window.location.reload(); }else{ alert('订单未完成或非请求退款状态'); } } }) }) $('.refuse').click(function(){ var id = $(this).attr('bh'); $.ajax({ type:'post', url:"<?php echo U('Order/refuse');?>", data:{'id':id}, datatype:'json', success:function(data){ if (data > 0) { alert('已拒绝'); window.location.reload(); }else{ alert('拒绝失败'); } } }) }) </script> </body> </html><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html> <html lang="en"> <head> <script type="text/javascript" src="__PUBLIC__/js/jquery-1.8.0.min.js"></script> <script type="text/javascript" src="__PUBLIC__/layer/layer.js"></script> <meta charset="UTF-8"> <link href="__PUBLIC__/css/store.css" rel="stylesheet" type="text/css" /> <title>Document</title> </head> <style> #stage{ display:none; position:fixed; top:0; bottom:0; left:0; right:0; background:rgba(0,0,0,0.5); } #forms{ position:absolute; top:50%; left:50%; transform: translate(-50%,-50%); padding:10px; background: #fff; } #close{ position:absolute; cursor: pointer; top:0; right:0; transform: translate(50%,-50%); width:14px; height:14px; text-align: center; line-height:14px; border-radius: 100%; background:rgba(0,250,250,0.7) } </style> <body> <span>收货信息:</span> <div> <table border="1" cellpadding="1" cellspacing="1" width="100%" align="center"> <tr> <th>收货人</th> <th>电话</th> <th>地址</th> <th>备注</th> <th>修改</th> </tr> <tr> <th><?php echo ($list["linkman"]); ?></th> <th><?php echo ($list["phone"]); ?></th> <th><?php echo ($list["address"]); ?></th> <th><?php echo ($list["remark"]); ?></th> <th><button id="btn">修改</button></th> <div id="stage"> <div id="forms"> <form action="<?php echo U('Store/edaddress');?>" method="post" onsubmit="return check()"> <input type="hidden" name="id" value="<?php echo ($list["id"]); ?>"> <div>姓名:<input type="text" value="<?php echo ($list["linkman"]); ?>" name="linkman" class="name"></div> <div style="margin-top:10px">电话:<input type="text" value="<?php echo ($list["phone"]); ?>" name="phone" class="phone"></div> <div style="margin-top:10px">地址:<input type="text" value="<?php echo ($list["address"]); ?>" name="address" class="address"></div> <div style="marg in-top:10px">备注:<input type="text" value="<?php echo ($list["remark"]); ?>" name="remark" class="remark"></div> <center><input type="submit" value="修改"></center> </form> <span id="close">&times;</span> </div> </div> <div> <!-- <button id="btn">添加地址</button> --> </div> </div> </tr> </table> </div> <div style="margin-top:50px"> <table border="1" cellpadding="1" cellspacing="1" width="100%" align="center"> <tr> <th>商品</th> <th>商品名</th> <th>商品价格</th> <th>购买数量</th> <!-- <th>总价</th> --> <!-- <th>操作</th> --> </tr> <?php if(is_array($row)): $i = 0; $__LIST__ = $row;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$vo): $mod = ($i % 2 );++$i;?><tr> <td><img src="<?php echo ($vo["iname"]); ?>" alt=""></td> <td><a href="<?php echo U('Store/gooddetail');?>?id=<?php echo ($vo["iid"]); ?>"><?php echo ($vo["gname"]); ?></a></td> <td><?php echo ($vo["price"]); ?></td> <td><?php echo ($vo["qty"]); ?></td> <!-- <td><?php echo ($vo[price] * $vo[qty]); ?></td> --> <!-- <td rowspan="2"><button class="jiesuan" bh=<?php echo ($vo["id"]); ?>>结算</button></td> --> </tr><?php endforeach; endif; else: echo "" ;endif; ?> </table> </div> <div style="margin-top:20px"> <table border="1" cellpadding="1" cellspacing="1" width="50%" align="center"> <form action="<?php echo U('Store/sureorder');?>" method="post" onsubmit="return allprices()"> <tr> <th>确认订单</th> </tr> <tr> <td> 总计: <input type="text" value="<?php echo ($sum); ?>" readonly="readonly" name="allprice" class="allprice"> </td> </tr> <tr> <td> <input type="submit" value="提交订单"> </td> </tr> </table> </form> </div> <script> $('#btn').click(function(){ $('#stage').css('display','block') }) $('#close').click(function(){ $('#stage').css('display','none') }) function allprices() { if ($('.allprice').val() == '' || $('.allprice').val() == 0) { layer.msg('亲,没有购买任何商品哦',{icon:5}); setTimeout(function(){ $('.allprice').focus(); }); return false; } } function check() { if ($('.name').val() == '') { layer.msg('请输入姓名'); setTimeout(function(){ $('.name').focus(); }); return false; }else if($('.phone').val()==''){ layer.msg('请输入电话'); setTimeout(function(){ $('.phone').focus(); }); return false; }else if($('.address').val() == ''){ layer.msg('请输入地址'); setTimeout(function(){ $('.address').focus(); }); return false; } } $('.deny').click(function(){ if ($(this).text() == '设为默认地址') { $(this).text('默认地址'); window.location.reload(); }else{ $(this).text('设为默认地址'); window.location.reload(); } var id = $(this).attr('bh'); $.ajax({ type:'get', url:"<?php echo U('Store/mo');?>"+'?id='+id, }) }); </script> </body> </html><file_sep> var varPostage = 0 ; //邮费 var g_maxNumber = 99 ; //最大购买数量 //得到对象 function getObj(id) { return $("#" + id); } var total = 1; //总数 function chkAddAmount(id, type) { //得到数量文本框 var varObj = getObj(createCountId(id)); var varObjValue = varObj.val(); if(type==0){ //为空,用于计算用户输入数量,不改变文本框值,重新计算商品总金额 }else if (type == 1) { varObjValue++; } else { varObjValue--; } //判断数量是否大于最大购买数量 if (varObjValue > g_maxNumber) { alert('一次性购买不能超过'+g_maxNumber+'个'); varObj.val(g_maxNumber); changeSumPrice(); changeSubtotal(id,g_maxNumber); return; } //判断数量是否小于1 if (varObjValue <= 1) { //当前文本框数量为1 varObj.val(1); //设置当前文本框的 getObj(createSubtotalId(id)).text(getObj(createFirstId(id)).text()); //改变余额 changeSumPrice(); return; } varObj.val(varObjValue); changeSubtotal(id, varObjValue); } //改变小计 function changeSubtotal(id, amount) { //得到单价 var varFirstPrice = getObj(createFirstId(id)).text(); //单价乘以数量 var varSubtotal = floatCounstrue(varFirstPrice * amount); //赋值 getObj(createSubtotalId(id)).text(varSubtotal); //余额赋值 changeSumPrice(); } //改变余额 function changeSumPrice() { var index = 1; var varSumPrice = 0; for (index; index <= total; index++) { varSumPrice += parseFloat(getObj(createSubtotalId(index)).text()); //alert(parseFloat(getObj(createSubtotalId(index)).text())); } varSumPrice = floatCounstrue(varSumPrice); getObj("span_sumPirce").text(varSumPrice); getObj("b_sumPirce").text(varSumPrice); } //浮点型分析 function floatCounstrue(val) { val = val.toString(); var index = val.indexOf("."); if (index > 0) { return val.substring(0, index + 3); } else { return val + ".00"; } } //创建单价Id function createFirstId(id) { return "span_first_price_" + id; } //创建数量 I function createCountId(id) { return "input_count_" + id; } //创建小计Id function createSubtotalId(id) { return "span_subtotal_price_" + id; } function fnChangePictrue(number,flag){ switch(number){ case 1: break; case 2: var varImagePath1 = baseLocation+"web/images/message_btn.png"; var varImagePath2 = baseLocation+"web/images/message_btn1.png"; if(flag){ alert(varImagePath1); getObj("next2 > img").attr("src",varImagePath2); }else{ alert(varImagePath2); getObj("next2 > img").attr("src",varImagePath1); } break; } } <file_sep><?php if (!defined('THINK_PATH')) exit();?> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="description" content="Tsys管理系统"> <title>后台管理</title> <link id="easyuiTheme" rel="stylesheet" type="text/css" href="__PUBLIC__/themes/bootstrap/easyui.css"> <link rel="stylesheet" type="text/css" href="__PUBLIC__/themes/icon.css"> <script type="text/javascript" src="__PUBLIC__/js/jquery-1.8.0.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/jquery.easyui.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/admin.js" charset="utf-8"></script> </head> <link rel="stylesheet" type="text/css" href="__PUBLIC__/uploadify/uploadify.css" /> <script src="__PUBLIC__/uploadify/jquery.uploadify.min.js" type="text/javascript"></script> <body> <div class="easyui-panel" fit="true"> <form id="addForm" method="post" enctype="multipart/form-data"> <table width="780" border="0"> <tr style="height: 50px;"> <td width="100" align="right"> 房间名称: </td> <td width="250"> <input name="type_name" class="easyui-validatebox textbox" required missingmessage="房间名称不能为空" style="width: 250px" value=""/> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 房间价格: </td> <td width="250"> <input name="room_price" class="easyui-validatebox textbox" required missingmessage="房间价格不能为空" style="width: 250px" value=""/> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 房间数量: </td> <td width="250"> <input name="room_count" class="easyui-validatebox textbox" required missingmessage="房间数量不能为空" style="width: 250px" value=""/> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 床位类型 : </td> <td width="250"> <input name="bed_type" class="easyui-validatebox textbox" required missingmessage="床位类型不能为空" style="width: 250px" value=""/> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 房间大小: </td> <td width="250"> <input name="room_area" class="easyui-validatebox textbox" required missingmessage="房间大小不能为空" style="width: 250px" value=""/> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 加床价格: </td> <td width="250"> <input name="addprice" class="easyui-validatebox textbox" required missingmessage="加床价格不能为空" style="width: 250px" value=""/> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 房间类型: </td> <td width="250" align="left"> <select name="room_type" style="width:100px"> <option value="2">标准型</option> <option value="3">豪华型</option> <option value="4">奢靡型</option> <option value="5">总统型</option> </select> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 有无早餐: </td> <td width="250" align="left"> <select name="breakfast" style="width:100px"> <option value="0">无</option> <option value="1">有</option> </select> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 无线网络: </td> <td width="250" align="left"> <select name="internet" style="width:100px"> <option value="none">无</option> <option value="wifi">wifi</option> <option value="broadband">broadband</option> </select> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 容纳人数: </td> <td width="250" align="left" > <select name="person" style="width:100px"> <option value="1">1</option> <option value="2">2</option> </select> </td> </tr> <tr style="height: 50px;"> <td align="right"> 图片上传: </td> <td> <input id="up_file_upload" name="file_upload" type="file" multiple="false"> <div id="up_image" class="image"> </div> <input type="hidden" id="url" value="__URL__"> <input type="hidden" id="root" value="__ROOT__"> <input type="hidden" id="public" value="__PUBLIC__"> <input id="hiddenimgpath" name="picture" type="hidden" /> </td> </tr> </table> <div style="text-align:left;padding:20px;"> <a href="javascript:void(0);" class="easyui-linkbutton" style="width:80px" onclick="submitForm()">添加</a> </div> </form> </div> <script type="text/javascript"> function submitForm(){ var isClickOk = true; $.messager.defaults={ok:"确定",cancel:"取消"}; $.messager.confirm('Confirm', '您确定增加?', function(r){ if (r){ $('#addForm').form('submit',{ url:"__APP__/Goods/add", onSubmit: function(){ if(isClickOk==false){ $.messager.alert('操作提示', '主键不能重复!','error'); return false; }else if ($('#addForm').form('validate')) { //datagrid.datagrid('loadData', { total: 0, rows: [] }); //datagrid.datagrid('reload'); $.messager.alert('操作提示', '添加房间成功!','info'); return true; }else{ $.messager.alert('操作提示', '信息填写不完整!','error'); return false; } }, success: function(){ //removePanel(); } }); //$('#datagrid_menu').datagrid('reload'); } }); } </script> <script type="text/javascript"> function aDel(id) { //点击删除链接,ajax var rem_id = $("#adel_"+id); $.messager.defaults = { ok: "确定", cancel: "取消" }; $.messager.confirm('提示', '您确定要删除吗?', function (r) { if(r){ rem_id.hide(500).remove(); } }); } $(function () { var img_path = ""; $('#up_file_upload').uploadify({ 'formData': { 'timestamp': '<?php echo ($time); ?>', //时间 'token': '<?php echo (md5($time )); ?>', //加密字段 'url': $('#url').val() + '/upload/', //url 'imageUrl': $('#root').val() //root }, 'fileTypeDesc': 'Image Files', //类型描述 //'removeCompleted' : false, //是否自动消失 'fileTypeExts': '*.gif; *.jpg; *.png', //允许类型 'fileSizeLimit': '3MB', //允许上传最大值 'swf': $('#public').val() + '/uploadify/uploadify.swf', //加载swf 'uploader': $('#url').val() + '/uploadify', //上传路径 'buttonText': '文件上传', //按钮的文字 'onUploadSuccess': function (file, data, response) { //成功上传返回 var n = parseInt(Math.random() * 100); //100以内的随机数 img_path += data + "|"; $('#hiddenimgpath').val(img_path); //插入到image标签内,显示图片的缩略图 $('#up_image').append('<div id="adel_' + n + '" class="photo"><a href="' + data + '" target="_blank"><img src="' + data + '" height=80 width=80 /></a><div class="del"><a href="javascript:vo(0)" onclick=aDel("' + n +'");>删除</a></div></div>'); } }); }); </script> <script type="text/javascript" src="__PUBLIC__/lhgdialog/lhgdialog.min.js"></script> </body><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link id="easyuiTheme" rel="stylesheet" type="text/css" href="__PUBLIC__/themes/bootstrap/easyui.css" /> <link rel="stylesheet" type="text/css" href="__PUBLIC__/themes/icon.css" /> <script type="text/javascript" src="__PUBLIC__/js/jquery-1.8.0.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/jquery.easyui.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/admin.js" charset="utf-8"></script> <!-- <script type="text/javascript" charset="utf-8"> var datagrid = $('#datagrid_Order'); var isClickOk = true; function edit(id) { $.ajax({ url: '__APP__/Order/getOrderById', data: {id: id}, dataType: 'json', success: function (rows) { rows = rows[0]; $('#_orderid').val(rows.order_id); $("input[name='state'][value="+rows.state+"]").attr("checked",true); } }); $('#editDlg').dialog('open').dialog('setTitle', '修改订单信息'); } function view(id) { $.ajax({ url: '__APP__/Order/getOrderById', data: {id: id}, dataType: 'json', async: false, success: function (rows) { var table = ''; table+= '<tr>'; table+='<td>'+rows.hotel_name+'</td>'; table+='<td>'+rows.type_name+'</td>'; table+='<td>'+rows.name+'</td>'; table+='<td>'+rows.phone_number+'</td>'; table+='<td>'+rows.identity_card+'</td>'; table+='<td>'+rows.start_time+'</td>'; table+='<td>'+rows.end_time+'</td>'; table+='<td>'+rows.total_price+'</td>'; table+='<td>'+rows.special_requirement+'</td>'; table+="</tr>"; //alert(table); $('.itbody').empty(); $('.itbody').append(table); } }); $('#viewDlg').dialog('open').dialog('setTitle', '订单信息'); } function batch(t){ var datagrid = $("#datagrid_Order"); var rows = datagrid.datagrid('getChecked'); var ids = []; var tn = (t=='confirm')?"接单":"修改订单状态为已支付"; if (rows.length > 0) { parent.dj.messagerConfirm('请确认', '您要批量'+tn+'吗?', function(r) { if (r) { for ( var i = 0; i < rows.length; i++) { ids.push(rows[i].order_id); } $.ajax({ url : '__APP__/Order/batch', data : { type:t, ids : ids.join(',') }, dataType : 'json', success : function(d) { datagrid.datagrid('load'); datagrid.datagrid('unselectAll'); parent.dj.messagerShow({ title : '提示', msg : d.info }); } }); } }); } else { parent.dj.messagerAlert('提示', '请勾选要处理的订单!', 'error'); } } //接单 function accept(id){ parent.dj.messagerConfirm('请确认', '入住确认吗?', function(r) { if (r) { $.ajax({ url : '__APP__/Order/batch', data : {id:id}, dataType : 'json', success : function(d) { datagrid.datagrid('load'); datagrid.datagrid('unselectAll'); parent.dj.messagerShow({ title : '提示', msg : '入住确认成功' }); window.location.reload(); } }); } }); } function bgcolor(index,row){ if (row.flag==0){ return 'background-color:red;'; } } function exportData() { var rows = $('#datagrid_Order').datagrid('getChecked'); var ids = []; for (var i = 0; i < rows.length; i++) { ids.push(rows[i].order_id); } var str = ids.join(','); var href = '__APP__/Order/export?idstr='+str; location.href=href; } function _search() { $('#datagrid_Order').datagrid('loadData', { total: 0, rows: [] }); $('#datagrid_Order').datagrid('load', dj.serializeObject($('#searchForm'))); } function cleanSearch() { $('#datagrid_Order').datagrid('load', {}); $('#searchForm input').val(''); } //删除选中项 function deleteData() { var datagrid = $("#datagrid_Order"); var rows = datagrid.datagrid('getChecked'); var ids = []; if (rows.length > 0) { parent.dj.messagerConfirm('请确认', '您要删除当前所选项目?', function(r) { if (r) { for ( var i = 0; i < rows.length; i++) { ids.push(rows[i].order_id); } $.ajax({ url : '__APP__/Order/delete', data : { ids : ids.join(',') }, dataType : 'json', success : function(d) { datagrid.datagrid('load'); datagrid.datagrid('unselectAll'); parent.dj.messagerShow({ title : '提示', msg : d.info }); } }); } }); } else { parent.dj.messagerAlert('提示', '请勾选要删除的记录!', 'error'); } } function edit_ok() { $.messager.defaults = { ok: "确定", cancel: "取消" }; $.messager.confirm('Confirm', '您确定修改?', function (r) { if (r) { $('#editForm').form('submit', { url: "__APP__/Order/edit", dataType: 'json', onSubmit: function () { if ($('#editForm').form('validate')) { datagrid.datagrid('loadData', { total: 0, rows: [] }); datagrid.datagrid('load'); $.messager.alert('操作提示', '修改信息成功!', 'info'); return true; } else { $.messager.alert('操作提示', '信息填写不完整!', 'error'); return false; } } }); $('#datagrid_Order').datagrid('reload'); $('#editDlg').dialog('close'); } }); } function formatOper(val,row,index){ var str= '<a href="javascript:void(0);" onclick="accept('+row.reservation_id+')">入住确认</a>'; str+=' &nbsp;&nbsp;<a href="javascript:void(0);" onclick="view('+row.reservation_id+')">订单详情</a>'; return str; } function formatsex(val,row,index){ return (row.sex==1)?"女":"男"; } function formatphone(val,row,index){ return row.order_id; } function formataddress(val,row,index){ return row.address1+''+row.address2+''+row.address3; } function myformatter(date){ var y = date.getFullYear(); var m = date.getMonth()+1; var d = date.getDate(); return y+'-'+(m<10?('0'+m):m)+'-'+(d<10?('0'+d):d); } function myparser(s){ if (!s) return new Date(); var ss = (s.split('-')); var y = parseInt(ss[0],10); var m = parseInt(ss[1],10); var d = parseInt(ss[2],10); if (!isNaN(y) && !isNaN(m) && !isNaN(d)){ return new Date(y,m-1,d); } else { return new Date(); } } </script> --> <title>后台管理</title> </head> <style> .stage{ position:absolute; top:0; bottom:0; left:0; right:0; background:rgba(0,0,0,0.2); display:none; } .form{ position:absolute; top:50%; left:50%; transform: translate(-50%,-50%); padding:10px; background: #fff; } .close{ position:absolute; cursor: pointer; top:0; right:0; transform: translate(50%,-50%); width:14px; height:14px; text-align: center; line-height:14px; border-radius: 100%; background:gray; } </style> <body> <div> <form action="<?php echo U('Order/onorder');?>" method="post"> <div style="float:left"> <select name="chaxun" id=""> <option value="1">电话</option> </select> </div> <div style="float:left"> <input type="text" name="hotel" > </div> <div> <input type="submit" value="搜索"> </div> </form> </div> <div class="easyui-panel" data-options="fit:true"> <table border="1" cellpadding="1" cellspacing="1" width="100%" align="center"> <thead> <tr> <th >ID</th> <th>用户</th> <th >手机号</th> <th >入住酒店</th> <th>房型</th> <th>单价</th> <th >入住时间</th> <th >支付状态</th> <th >支付方式</th> <th >其他</th> <th>操作</th> </tr> <?php if(is_array($list)): $i = 0; $__LIST__ = $list;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$vo): $mod = ($i % 2 );++$i;?><tr> <td ><?php echo ($vo["id"]); ?></td> <td><?php echo ($vo["nickname"]); ?></td> <td ><?php echo ($vo["phone_number"]); ?></td> <td ><?php echo ($vo["name"]); ?></td> <td><?php echo ($vo["display_name"]); ?></td> <td><?php echo ($vo["price"]); ?></td> <td ><?php echo ($vo["start_time"]); ?></td> <td > <?php if($vo["payment_status"] == paid): ?>已支付 <?php elseif($vo["payment_status"] == not_paid): ?>未支付 <?php else: ?>支付失败<?php endif; ?> </td> <td > <?php if($vo["payment_method"] == wechat): ?>微信 <?php elseif($vo["payment_method"] == score): ?>金币 <?php else: ?>到店支付<?php endif; ?> </td> <td > <button class="qita" onclick="other(<?php echo ($vo["id"]); ?>)">其他</button> <div class="stage qita_<?php echo ($vo["id"]); ?>" > <div class="form"> <table border="1" > <tr> <th width="80">订单状态</th> <th width="80">最晚到店时间</th> <th width="80">微信支付的openid</th> <th width="80">特殊要求</th> <th width="80">备注</th> </tr> <tr> <td width="80"> <?php if($vo["order_status"] == tbc): ?>待确认 <?php elseif($vo["order_status"] == success): ?>成功 <?php elseif($vo["order_status"] == cancle): ?>取消 <?php elseif($vo["order_status"] == refunding): ?>退款中 <?php else: ?>关闭<?php endif; ?> </td> <td width="80"><?php echo ($vo["latest_arrive_time"]); ?></td> <td width="80"><?php echo ($vo["open_id"]); ?></td> <td width="80"><?php echo ($vo["special_requirement"]); ?></td> <td width="80"><?php echo ($vo["remark"]); ?></td> </tr> </table> <span class="close">&times;</span> <div> </div> </td> <td><button class="check" bh="<?php echo ($vo["id"]); ?>">确认入住</button></td> </tr><?php endforeach; endif; else: echo "" ;endif; ?> </thead> </table> <!-- <div id="toolbar" style="padding:5px;"> <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-print" plain="true" onclick="exportData()">导出csv</a> <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-reload" plain="true" onclick="">批量接单</a> <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-ok" plain="true" onclick="">批量处理订单</a> <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cut" plain="true" onclick="deleteData()">删除</a> <form id="searchForm" style="display:inline-block;*display:inline;zoom:1;"> <input name="search" placeholder="手机号" data-options="prompt:'请输入搜索内容',searcher:''" class="easyui-validatebox textbox" style="width: 180px; vertical-align: middle;" /> </select> 入住时间:<input name="start_time" class="easyui-datebox" data-options="formatter:myformatter,parser:myparser" /> 离开时间: <input name="end_time" class="easyui-datebox" data-options="formatter:myformatter,parser:myparser" /> <input name="hiddenid" id="hiddenid" type="hidden" /> <a href="javascript:void(0);" class="easyui-linkbutton" plain="true" onclick="_search();">搜索</a> </form> </div> --> <!-- </div> --> <!-- 修改订单信息的表单 --> <!-- <div id="editDlg" class="easyui-dialog" style="width: 400px; height: 300px; padding: 10px 20px" closed="true" buttons="#editDlgBtn" data-options="modal:true"> <form id="editForm" method="post"> <table width="350" border="0"> <tr> <td width="150" align="right"> 订单状态: </td> <td width="250"> <input type="radio" name="state" value="未入住" />未入住 <input type="radio" name="state" value="已入住" />已入住 </td> <input type="hidden" name="reservation_id" id="_orderid" /> </tr> </table> </form> </div> --> <!-- 密码重置 --> <!-- 修改订单信息的表单 --> <!-- <div id="viewDlg" class="easyui-dialog" style="width: 1200px; height: 300px; padding: 10px 20px" closed="true" buttons="#viewDlgBtn" data-options="modal:true"> <style> .itemtable th,td{ border:solid 1px #ccc; } </style> --> <!-- <table style="border:solid 1px #ccc;width:100%;table-layout:fixed; empty-cells:show; border-collapse: collapse; margin:0 auto; " class="itemtable"> <tr> <th>酒店名</th> <th>房间名</th> <th>客户名字</th> <th>客户手机号</th> <th>客户身份证</th> <th>入住时间</th> <th>离开时间</th> <th>订单总价格</th> <th>客户留言</th> </tr> <tbody class="itbody"></tbody> </table> </div> --> <!-- 修改户信息的按钮,被Jquery设置,当没被调用的时候不显示 --> <!-- <div id="viewDlgBtn"> <a href="#" class="easyui-linkbutton" iconcls="icon-cut" onclick="javascript:$('#viewDlg').dialog('close')">取消</a> </div> --> <!-- 修改户信息的按钮,被Jquery设置,当没被调用的时候不显示 --> <!-- <div id="editDlgBtn"> <a href="#" id="addSaveBooktimecode" class="easyui-linkbutton" iconcls="icon-ok" onclick="edit_ok()">确认</a> <a href="#" class="easyui-linkbutton" iconcls="icon-cut" onclick="javascript:$('#editDlg').dialog('close')">取消</a> </div> --> <script> function other(id) { $('.qita_'+id).fadeIn('1000'); } $('.close').click(function(){ $('.stage').fadeOut('1000'); }) $('.check').click(function(){ var id = $(this).attr('bh'); $.ajax({ type:'post', url:"<?php echo U('Order/surecheck');?>", data:{'id':id}, success:function(data){ if (data > 0) { alert('已确认入住'); window.location.reload(); } } }) }) </script> </body> </html><file_sep><?php if (!defined('THINK_PATH')) exit();?><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="stylesheet" type="text/css" href="__PUBLIC__/themes/default/easyui.css" /> </head> <body> <div class="easyui-accordion" data-options="fit:false,border:false"> <div title="订单管理" icon="icon-sys" style="height:150px" > <ul class="easyui-tree"> <li ><a href="javascript:" style="color: #000" onclick="addTab('所有订单','__APP__/Order/index');"> 所有订单</a><i></i></li> <li><a href="javascript:" style="color: #000" onclick="addTab('未入住订单','__APP__/Order/onorder');"> 未入住订单</a><i></i></li> <li><a href="javascript:" style="color: #000" onclick="addTab('已入住订单','__APP__/Order/payorder');"> 已入住订单</a><i></i></li> <li><a href="javascript:" style="color: #000" onclick="addTab('退款订单','__APP__/Order/refund');"> 退款订单</a><i></i></li> </ul> </div> <?php if($_SESSION['permission']==1){?> <div title="管理员管理" icon="icon-sys" style="height:150px"> <ul class="easyui-tree"> <li><a href="javascript:" style="color: #000" onclick="addTab('管理员设置','__APP__/Auser/index');"> 管理员设置</a><i></i></li> </ul> </div> <?php }?> <div title="酒店管理" icon="icon-sys" style="height:150px"> <ul class="easyui-tree"> <li><a href="javascript:" style="color: #000" onclick="addTab('酒店管理','__APP__/Goods/hotelinfo');"> 酒店管理</a><i></i></li> </ul> <ul class="easyui-tree"> <li><a href="javascript:" style="color: #000" onclick="addTab('上传酒店','__APP__/Goods/uphotel');"> 上传酒店</a><i></i></li> </ul> </div> <?php if($_SESSION['permission']==0){?> <div title="房间管理" icon="icon-sys" style="height:150px"> <ul class="easyui-tree"> <li><a href="javascript:" style="color: #000" onclick="addTab('房间管理','__APP__/Goods/index');"> 房间管理</a><i></i></li> </ul> <ul class="easyui-tree"> <li><a href="javascript:" style="color: #000" onclick="addTab('添加房间','__APP__/Goods/addpd');"> 添加房间</a><i></i></li> </ul> </div> <?php }?> <div title="用户管理" icon="icon-sys" style="height:150px"> <ul class="easyui-tree"> <li><a href="javascript:" style="color: #000" onclick="addTab('所有用户','__APP__/User/index');"> 所有用户</a><i></i></li> </ul> </div> <?php if($_SESSION['permission']==0){?> <div title="积分管理" icon="icon-sys" style="height:150px"> <ul class="easyui-tree"> <li><a href="javascript:" style="color: #000" onclick="addTab('积分充值','__APP__/Credit/index');"> 积分充值</a><i></i></li> <li><a href="javascript:" style="color: #000" onclick="addTab('积分记录','__APP__/Credit/query');"> 积分记录</a><i></i></li> </ul> </div> <?php }?> <?php if($_SESSION['permission']==0){?> <div title="城市管理" icon="icon-sys" style="height:150px"> <ul class="easyui-tree"> <li><a href="javascript:" style="color: #000" onclick="addTab('热门城市','__APP__/City/hot');"> 热门城市</a><i></i></li> <li><a href="javascript:" style="color: #000" onclick="addTab('显示城市','__APP__/City/show');"> 显示城市</a><i></i></li> </ul> </div> <?php }?> <?php if($_SESSION['permission']==0){?> <div title="贴吧管理" icon="icon-sys" style="height:150px"> <ul class="easyui-tree"> <li><a href="javascript:" style="color: #000" onclick="addTab('帖子管理','__APP__/Tieba/topic');"> 帖子管理</a><i></i></li> <li><a href="javascript:" style="color: #000" onclick="addTab('话题管理','__APP__/Tieba/gambit');"> 话题管理</a><i></i></li> </ul> </div> <?php }?> </div> </body><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="stylesheet" type="text/css" href="__PUBLIC__/themes/icon.css" /> <script type="text/javascript" src="__PUBLIC__/js/jquery-1.8.0.min.js"></script> <script type="text/javascript" src="__PUBLIC__/layer/layer.js"></script> </head> <body> <div> <table border="1" cellpadding="1" cellspacing="1" width="100%" align="center"> <tr> <th><button onclick="fun()">批量删除</button></th> <th>帖子名</th> <th>所属贴吧</th> <th>所属分类</th> <th>发帖人</th> <th width="200px">帖子内容</th> <th>浏览量</th> <th>评论数</th> <th>关注数</th> <th>分享数</th> <th>操作</th> </tr> <?php if(is_array($list)): $i = 0; $__LIST__ = $list;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$vo): $mod = ($i % 2 );++$i;?><tr> <td><input type="checkbox" value="<?php echo ($vo["id"]); ?>" name="test"></td> <td><?php echo ($vo["title"]); ?></td> <td><?php echo ($vo["tdn"]); ?></td> <td><?php echo ($vo["tcdn"]); ?></td> <td><?php echo ($vo["nickname"]); ?></td> <td><?php echo ($vo["content"]); ?></td> <td><?php echo ($vo["view_num"]); ?></td> <td><?php echo ($vo["comment_num"]); ?></td> <td><?php echo ($vo["heart_num"]); ?></td> <td><?php echo ($vo["share_num"]); ?></td> <td><button class="del" bh="<?php echo ($vo["id"]); ?>">删除</button></td> </tr><?php endforeach; endif; else: echo "" ;endif; ?> </table> </div> <script> $('.del').click(function(){ var id = $(this).attr('bh'); if (confirm('确认删除吗?') == true) { $.ajax({ type:'post', url:"<?php echo U('Tieba/opcdel');?>", dataType:"json", data:{'id':id}, success:function(data){ if (data > 0) { alert('已删除'); window.location.reload(); }else{ alert('删除失败'); } } }) } }) function fun(){ obj = document.getElementsByName("test"); check_val = []; for(k in obj){ if(obj[k].checked) check_val.push(obj[k].value); } var arr = check_val; $.ajax({ type:'post', url:"<?php echo U('Tieba/alldel');?>", dataType:"json", data:{'id':arr}, success:function(data){ if (data == '1') { alert('已删除'); // window.location.reload(); }else{ alert('删除失败'); } } }) } </script> </body> </html><file_sep><?php if (!defined('THINK_PATH')) exit();?><html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>积分充值</title> </head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link id="easyuiTheme" rel="stylesheet" type="text/css" href="__PUBLIC__/themes/bootstrap/easyui.css" /> <link rel="stylesheet" type="text/css" href="__PUBLIC__/themes/icon.css" /> <script type="text/javascript" src="__PUBLIC__/js/jquery-1.8.0.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/jquery.easyui.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/admin.js" charset="utf-8"></script> <script type="text/javascript" src="http://api.map.baidu.com/api?v=1.3"></script> <body> <body style="background:#CBE1FF"> <div style="width:730px;margin:auto;"> 要查询的地址:<input id="text_" type="text" value="徐州古彭广场" style="margin-right:100px;"/> 查询结果(经纬度):<input id="result_" type="text" /> <input type="button" value="查询" onclick="searchByStationName();"/> <div id="container" style="position: absolute; margin-top:30px; width: 730px; height: 590px; top: 50; border: 1px solid gray; overflow:hidden;"> </div> </div> </body> <script type="text/javascript"> var map = new BMap.Map("container"); map.centerAndZoom("徐州", 12); map.enableScrollWheelZoom(); //启用滚轮放大缩小,默认禁用 map.enableContinuousZoom(); //启用地图惯性拖拽,默认禁用 map.addControl(new BMap.NavigationControl()); //添加默认缩放平移控件 map.addControl(new BMap.OverviewMapControl()); //添加默认缩略地图控件 map.addControl(new BMap.OverviewMapControl({ isOpen: true, anchor: BMAP_ANCHOR_BOTTOM_RIGHT })); //右下角,打开 var localSearch = new BMap.LocalSearch(map); localSearch.enableAutoViewport(); //允许自动调节窗体大小 function searchByStationName() { map.clearOverlays();//清空原来的标注 var keyword = document.getElementById("text_").value; localSearch.setSearchCompleteCallback(function (searchResult) { var poi = searchResult.getPoi(0); document.getElementById("result_").value = poi.point.lng + "," + poi.point.lat; map.centerAndZoom(poi.point, 13); var marker = new BMap.Marker(new BMap.Point(poi.point.lng, poi.point.lat)); // 创建标注,为要查询的地方对应的经纬度 map.addOverlay(marker); var content = document.getElementById("text_").value + "<br/><br/>经度:" + poi.point.lng + "<br/>纬度:" + poi.point.lat; var infoWindow = new BMap.InfoWindow("<p style='font-size:14px;'>" + content + "</p>"); marker.addEventListener("click", function () { this.openInfoWindow(infoWindow); }); // marker.setAnimation(BMAP_ANIMATION_BOUNCE); //跳动的动画 }); localSearch.search(keyword); } </script> </html><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link id="easyuiTheme" rel="stylesheet" type="text/css" href="__PUBLIC__/themes/bootstrap/easyui.css" /> <link rel="stylesheet" type="text/css" href="__PUBLIC__/themes/icon.css" /> <script type="text/javascript" src="__PUBLIC__/js/jquery-1.8.0.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/jquery-1.7.2.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/jquery.easyui.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/admin.js" charset="utf-8"></script> <script type="text/javascript" src="__PUBLIC__/js/vue.js" charset="utf-8"></script> <title>后台管理</title> </head> <body id="shuaxin"> <div id="my-vue" class="container"> <header>显示城市</header> <table> <tr> <td> <select name="address1" id="address1"> </select> <select name="address2" id="address2"> </select> <select name="address3" id="address3"> </select> <input type="submit" value="设置" id="shezhi"> </td> </tr> </table> </div> <ul> <?php if(is_array($list)): $i = 0; $__LIST__ = $list;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$vo): $mod = ($i % 2 );++$i;?><li><?php echo ($vo["fullname"]); ?></li><?php endforeach; endif; else: echo "" ;endif; ?> </ul> <!-- js --> <script> //三级联动地址 //获取省份的数据 $.ajax({ type:'get', url:"<?php echo U('City/addred');?>", async:false, success:function(data){ // console.log(data); //将省份信息 追加到 下拉框中 //先清空原先的数据 $('#address1').empty(); //遍历省份数据 for (var i = 0; i < data.length; i++) { $('<option value="'+data[i].code+'">'+data[i].fullname+'</option>').appendTo('#address1'); }; }, dataType:'json', }) //绑定事件 $('#address1,#address2,#address3').change(function(){ var upid = $(this).val(); // console.log(upid); //清空之前的所有数据 $(this).nextAll('select').empty(); //保留 $(this) 的值 var _this = $(this); //请求下一级的数据 $.ajax({ type:'get', url:"<?php echo U('City/addred');?>", data:"parent_code="+upid, success:function(data){ // console.log(data); //如果下一级没有数据,就隐藏后面的下拉框 if (!data) { _this.nextAll('select').hide(); return; } // console.log(data.length); // 填充下一级的数据 for (var i = 0; i < data.length; i++) { // console.log(_this.next('select')); $('<option value="'+data[i].code+'">'+data[i].fullname+'</option>').appendTo(_this.next('select')); } //自动触发 后面的select 的change事件 _this.next('select').trigger('change'); _this.nextAll('select').show(); }, dataType:'json', }) }) //自动触发 #address1 的change $('#address1').trigger('change'); $('#shezhi').click(function() { var sheng = $('#address1').val(); var shi = $('#address2').val(); var qu = $('#address3').val(); $.ajax({ type:"post", url:"<?php echo U('City/isshow');?>", data:{'sheng':sheng,'shi':shi,'qu':qu}, success:function(data){ window.location.reload(); // } }) }) </script> </body> </html><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <h1>分类管理</h1> <table border="1" cellpadding="1" cellspacing="1" width="100%" align="center"> <tr> <th>id</th> <th>分类名</th> <th>PID</th> <th>PATH</th> <th>相关操作&nbsp;<a href="<?php echo U('Adminstore/category');?>?pid=<?php echo ($row['pid']); ?>">返回</a></th> </tr> <?php if(is_array($list)): $i = 0; $__LIST__ = $list;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$vo): $mod = ($i % 2 );++$i;?><tr> <td><?php echo ($vo["id"]); ?></td> <td><?php echo ($vo["cname"]); ?></td> <td><?php echo ($vo["pid"]); ?></td> <td><?php echo ($vo["path"]); ?></td> <td> <a href="<?php echo U('Adminstore/category');?>?pid=<?php echo ($vo["id"]); ?>">查看子类</a>&nbsp; <a href="<?php echo U('Adminstore/addcatechrild');?>?pid=<?php echo ($vo["id"]); ?>&path=<?php echo ($vo["path"]); ?>">添加子类</a>&nbsp; <a href="<?php echo U('Adminstore/editcate');?>?id=<?php echo ($vo["id"]); ?>">编辑</a>&nbsp; <a href="<?php echo U('Adminstore/delcate');?>?id=<?php echo ($vo["id"]); ?>&pid=<?php echo ($vo["pid"]); ?>&path=<?php echo ($vo["path"]); ?>">删除</a>&nbsp; </td> </tr><?php endforeach; endif; else: echo "" ;endif; ?> </table> </body> </html><file_sep><?php class StoreAction extends Action { public function index() { $list = M('goods')->table('goods g,image i')->where('i.goods_id = g.id')->select(); // var_dump($list); $this->assign('list',$list); $this->display(); } public function gooddetail() { $id = $_GET['id']; $what = "(g.id = i.goods_id and i.id = $id)"; $list = M('image')->table('goods g,image i')->where($what)->find(); // var_dump($list); $this->assign('list',$list); $this->display(); } //购物车展示页 public function showcart() { // var_dump($_SESSION); // $abc = $_SESSION['cart']['price'] $aaa = $_SESSION['cart']; foreach ($aaa as $k => $v) { $aaa[$k]['chengji'] = $v['qty'] * $v['price']; } // var_dump($aaa); $sum = 0; foreach ($aaa as $val) { $sum += $val['chengji']; } // var_dump($sum); // var_dump($_SESSION); $this->assign('count',$sum); $this->assign('list',$_SESSION['cart']); $this->display(); } public function alldel() { unset($_SESSION['cart']); $this->success('已清空'); } public function cartdo() { // unset($_SESSION); // exit; // var_dump($_GET); // exit; $goods_id = $_GET['goods_id']; $qty = $_GET['qty']; $sql = M('goods')->field('stock')->where(array('id'=>$goods_id))->find(); $stock = $sql['stock']; // var_dump($stock); // var_dump($_SESSION['cart']); // exit; if ($_GET['b'] == 'buy') { if (!empty($_SESSION['cart'][$goods_id])) { //之前的数量加上新传过来的数量 $c = $_SESSION['cart'][$goods_id]['qty'] += $qty; //跳转购物车展示页 if ($c > $stock) { $c = $_SESSION['cart'][$goods_id]['qty'] -= $qty; $this->error('商品库存不足'); exit; } $this->success('去往交钱的路上',U('Store/showcart')); exit; } //查询商品信息 $what = "(g.id=i.goods_id and g.id =$goods_id)"; $lili = M('goods')->table('goods g,image i')->field('g.gname,i.iname,g.price,g.id,i.id iid')->where($what)->find(); //将购买数量放入$row数组中 $row['qty'] = $qty; $row['gname'] = $lili['gname']; $row['iname'] = $lili['iname']; $row['id'] = $lili['id']; $row['price'] = $lili['price']; $row['iid'] = $lili['iid']; //将信息存入session中 $_SESSION['cart'][$goods_id] = $row; // var_dump($_SESSION); // exit; $this->success('正在加载中',U('Store/showcart')); exit; }else if($_GET['b'] == 'add') { if (!empty($_SESSION['cart'][$goods_id])) { //之前的数量加上,新传过来的数量 $d = $_SESSION['cart'][$goods_id]['qty'] += $qty; //跳转购物车展示页 if ($d > $stock) { $d = $_SESSION['cart'][$goods_id]['qty'] -=$qty; $this->error('商品库存不足'); exit; }else{ $cool['stock'] = $stock -$qty; $list = M('goods')->where(array('id'=>$goods_id))->save($cool); if ($list !== false) { $this->success('已加入购物车'); exit; }else{ $this->error('无法加入购物车'); exit; } } } } //查询商品的信息 $what = "(g.id=i.goods_id and g.id =$goods_id)"; $lili = M('goods')->table('goods g,image i')->field('g.gname,i.iname,g.price,g.id,i.id iid,g.stock')->where($what)->find(); if ($lili['stock'] >= $qty) { $row['qty'] = $qty; }else{ $this->error('库存不足'); exit; } $row['gname'] = $lili['gname']; $row['iname'] = $lili['iname']; $row['id'] = $lili['id']; $row['price'] = $lili['price']; $row['iid'] = $lili['iid']; //将信息存入session中 $_SESSION['cart'][$goods_id] = $row; // $jack = M $rose['stock'] = $lili['stock'] -$qty; $list = M('goods')->where(array('id'=>$goods_id))->save($rose); // var_dump($_SESSION); // exit; $this->success('已加入购物车'); exit; } //删除购物车单条记录 public function del() { $goods_id = $_GET['id']; unset($_SESSION['cart'][$goods_id]); $this->success('已删除'); } public function dobuy() { // unset($_SESSION['cart']); // var_dump($_SESSION['cart']); $list = M('address')->where(array('operate'=>'2'))->find(); $aaa = $_SESSION['cart']; foreach ($aaa as $k => $v) { $aaa[$k]['chengji'] = $v['qty'] * $v['price']; } // var_dump($aaa); $sum = 0; foreach ($aaa as $val) { $sum += $val['chengji']; } $_SESSION['cart'] = $aaa; // var_dump($sum); // var_dump($_SESSION); $this->assign('sum',$sum); $this->assign('row',$_SESSION['cart']); $this->assign('list',$list); $this->display(); } public function addaddress() { // var_dump($_POST); // exit; if (IS_POST) { $name = $_POST['name']; $phone = $_POST['phone']; $address = $_POST['address']; $remark = $_POST['mark']; if (empty($name) && empty($phone) && empty($address)) { $this->error('请完善信息'); exit; } $data['linkman'] = $name; $data['phone'] = $phone; $data['address'] = $address; $data['remark'] = $remark; $list = M('address')->add($data); if ($list) { $this->success('添加成功'); }else{ $this->error('添加失败'); } }else{ $this->redirect('Store/dobuy'); exit; } } //默认地址 public function mo() { $id = $_GET['id']; $data['operate'] = '1'; $row['operate'] = '2'; $list = M('address')->where(array('id'=>$id))->save($row); $row = M('address')->where(array('id'=>array('neq',$id)))->save($data); } public function address() { $list = M('address')->order('id desc')->select(); $this->assign('list',$list); $this->display(); } public function edaddress() { // var_dump($_POST); if (IS_POST) { $id = $_POST['id']; $name = $_POST['linkman']; $phone = $_POST['phone']; $address = $_POST['address']; $remark = $_POST['remark']; if (empty($id) && empty($name) && empty($phone) && empty($address)) { $this->error('请完善信息'); exit; } $data['linkman'] = $name; $data['phone'] = $phone; $data['address'] = $address; $data['remark'] = $remark; $list = M('address')->where(array('id'=>$id))->save($data); if ($list !== false) { $this->success('修改成功'); }else{ $this->error('修改失败'); } }else{ $this->redirect('Store/dobuy'); } } public function sureorder() { if (IS_POST) { if (empty($_POST['allprice'])) { $this->error('请购买商品再提交'); } $allprice = $_POST['allprice']; $list = M('address')->where(array('operate'=>2))->find(); // var_dump($list); $data['ordernum'] = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8); $data['lname'] = $list['linkman']; $data['phone'] = $list['phone']; $data['address'] = $list['address']; $data['allprice'] = $allprice; $result = M('goodsorder')->add($data); if ($result) { foreach ($_SESSION['cart'] as $key => $val) { $jack['goods_id'] = $val['id']; $jack['price'] = $val['price']; $jack['qty'] = $val['qty']; $jack['order_id'] = $result; $rose = M('order_goods')->add($jack); } unset($_SESSION['cart']); $this->success('订单已生成',U('Store/orders')); }else{ $this->error('提交失败'); } } } public function orders() { $what = "(og.order_id = go.id and og.goods_id = g.id and i.goods_id = g.id)"; if (!empty($_REQUEST['chaxun'])) { if ($_REQUEST['chaxun'] == 1) { $what .= "and (go.ordernum like '%".$_REQUEST['find']."%')"; } if ($_REQUEST['chaxun'] == 2) { $what .= "and (go.phone like '%".$_REQUEST['find']."%')"; } } $list = M('goodsorder')->field('i.iname,g.gname,go.lname,go.address,go.phone,go.allprice,og.price,og.qty,go.ordernum')->table('goodsorder go,image i,order_goods og,goods g')->where($what)->select(); // $list = M('goodsorder')->order('id desc')->select(); // var_dump($list); $this->assign('list',$list); $this->display(); } } ?><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="description" content="Tsys管理系统"> <title>后台管理</title> <link id="easyuiTheme" rel="stylesheet" type="text/css" href="__PUBLIC__/themes/bootstrap/easyui.css"> <link rel="stylesheet" type="text/css" href="__PUBLIC__/themes/icon.css"> <script type="text/javascript" src="__PUBLIC__/js/jquery-1.8.0.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/jquery.easyui.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/admin.js" charset="utf-8"></script> </head> <link rel="stylesheet" type="text/css" href="__PUBLIC__/uploadify/uploadify.css" /> <script src="__PUBLIC__/uploadify/jquery.uploadify.min.js" type="text/javascript"></script> <script src="__PUBLIC__/layer/layer.js" type="text/javascript"></script> <script type="text/javascript" src="http://api.map.baidu.com/api?v=1.3"></script> <body> <div class="easyui-panel" fit="true"> <center> <h1>添加商品</h1> <form action="<?php echo U('Adminstore/doaddgoods');?>" id="editForm" method="post" enctype="multipart/form-data" onsubmit = "return check()"> <table width="780" border="0"> <tr style="height: 50px;"> <td width="100" align="right"> 商品名: </td> <td width="250"> <input name="name" style="width: 250px" id="name" /> <!-- <span class="uname"></span> --> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 商品分类: </td> <td width="250"> <select name="cate_id" id=""> <?php if (!empty($cate)): ?> <?php foreach ($cate as $val): ?> <option value="<?php echo $val['id'] ?>"><?php echo str_repeat('&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',substr_count($val['path'],',')).'|----'.$val['cname'] ?></option> <?php endforeach ?> <?php else: ?> <?php endif ?> </select> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 价格: </td> <td width="250"> <input name="price" style="width: 250px" value="" id="price" /> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 库存: </td> <td width="250"> <input name="stock" style="width: 250px" value="" id="stock" /> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 简介: </td> <td width="250"> <textarea name="msg" id="msg" cols="30" rows="10" style="width: 250px"></textarea> </td> </tr> </table> <div style="text-align:left;padding:20px;"> <center><input type="submit" value="添加"></center> <!-- <a href="" class="easyui-linkbutton" style="width:80px" ">修改</a> --> </div> </form></center> </script> <script type="text/javascript"> function check() { if ($('#name').val() == '') { layer.msg('请输入商品名'); setTimeout(function(){ $('#name').focus(); }); return false; } if($('#price').val() == ''){ layer.msg('请输入价格'); setTimeout(function(){ $('#price').focus(); }); return false; } if($('#stock').val() == ''){ layer.msg('请输入库存'); setTimeout(function() { $('#stock').focus(); }); return false; } if($('#msg').val() == ''){ layer.msg('请输入简介'); setTimeout(function(){ $('#msg').focus(); }); return false; } } </script> </body><file_sep><?php if (!defined('THINK_PATH')) exit();?> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="description" content="Tsys管理系统"> <title>后台管理</title> <link id="easyuiTheme" rel="stylesheet" type="text/css" href="__PUBLIC__/themes/bootstrap/easyui.css"> <link rel="stylesheet" type="text/css" href="__PUBLIC__/themes/icon.css"> <script type="text/javascript" src="__PUBLIC__/js/jquery-1.8.0.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/jquery.easyui.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/admin.js" charset="utf-8"></script> </head> <link rel="stylesheet" type="text/css" href="__PUBLIC__/uploadify/uploadify.css" /> <script src="__PUBLIC__/uploadify/jquery.uploadify.min.js" type="text/javascript"></script> <!-- <script type="text/javascript"> function convert(rows) { function exists(rows, parentId) { for (var i = 0; i < rows.length; i++) { if (rows[i].id == parentId) return true; } return false; } var nodes = []; for (var i = 0; i < rows.length; i++) { var row = rows[i]; if (!exists(rows, row.parentId)) { nodes.push({ id: row.type_id, text: row.name }); } } var toDo = []; for (var i = 0; i < nodes.length; i++) { toDo.push(nodes[i]); } while (toDo.length) { var node = toDo.shift(); // the parent node // get the children nodes for (var i = 0; i < rows.length; i++) { var row = rows[i]; if (row.parentId == node.id) { var child = { id: row.type_id, text: row.name }; if (node.children) { node.children.push(child); } else { node.children = [child]; } toDo.push(child); } } } return nodes; } //添加产品 function addData(){ var node = $('#menu-tree').tree("getSelected"); //if(node === null){ if(node == null){ $.dialog({lock:true,time: 3,icon:'error.gif',title:'错误提示',content: '请选择要添加的菜单!'}); return false; }else{ var pid = node.id; $.post("<?php echo U('Goods/addpd');?>",{pid:pid},function(data){ $('#audata').html(data); }); } } //删除选中项 function deleteData() { var datagrid = $("#tab_data"); var rows = datagrid.datagrid('getChecked'); var ids = []; if (rows.length > 0) { parent.dj.messagerConfirm('请确认', '您要删除当前所选项目?', function(r) { if (r) { for ( var i = 0; i < rows.length; i++) { ids.push(rows[i].fruit_id); } $.ajax({ url : '__APP__/Goods/delete', data : { ids : ids.join(',') }, dataType : 'json', success : function(d) { datagrid.datagrid('load'); datagrid.datagrid('unselectAll'); parent.dj.messagerShow({ title : '提示', msg : d.info }); } }); } }); } else { parent.dj.messagerAlert('提示', '请勾选要删除的记录!', 'error'); } } function formatType(val,row,index){ var type = row.hotel_star; var typename = ''; switch(type){ case "kezhan": typename = '客栈公寓'; break; case "liansuo": typename = '经济连锁'; break; case "two": typename = '二星民宿'; break; case "three": typename = '三星舒适'; break; case "four": typename = '四星高档'; break; case "five": typename = '五星豪华'; break; } return typename; } function formatOper(val,row,index){ var optr = '<a href="javascript:void(0);" onclick="edit('+row.hotel_id+')">修改</a>'; optr +=' &nbsp;&nbsp;<a href="javascript:void(0);" onclick="view('+row.hotel_id+')">详情</a>'; return optr; } function view(id){ $.ajax({ url: '__APP__/Goods/getHotelsById', data: {id: id}, dataType: 'json', async:false, success: function (rows) { $('#_hotel_name').html(rows.hotel_name); $('#_hotel_star').html(rows.hotel_star); $('#_hotel_title').html(rows.hotel_title); $('#_hotel_email').html(rows.hotel_email); $('#_total_rooms').html(rows.total_rooms); $('#_hotel_telephone').html(rows.hotel_telephone); $('#_hotel_address').html(rows.hotel_address); $('#_introduction').html(rows.introduction); $('#_hotel_image').attr('src',rows.image_url); } }); var html = $('#viewDlg').clone(); $.dialog({ id:'test123', lock: true, content: html, width: 400, height: 250, title:'查看酒店详情', cancel: true }); } function addPanel(){ $.dialog({ id:'testadd', lock: true, //content: 'url:/admin.php/Goods/addpd', url: '__APP__/Goods/addpd', content: 'url:__APP__/Goods/addpd', width: 800, height: 350, title:"房间添加", cancel:function(){ window.location.reload(); } }); } function edit(id){ $.dialog({ id:'testedit', lock: true, //content: 'url:/admin.php/Goods/uppd/id/'+id, //url: '__APP__/Goods/uppd?id='+id, content: 'url: __APP__/Goods/uphotel?id='+id, width: 800, height: 350, title:"酒店编辑", cancel:function(){ window.location.reload(); } }); } function exportData() { } //搜索名称 function s_data() { $('#tab_data').datagrid('loadData', { total: 0, rows: [] }); $('#tab_data').datagrid('load', dj.serializeObject($('#searchForm'))); } </script> --> <head> <body> <style> .stage{ position:absolute; top:0; bottom:0; left:0; right:0; background:rgba(0,0,0,0.2); display:none; } .form{ position:absolute; top:50%; left:50%; transform: translate(-50%,-50%); padding:10px; background: #fff; } .close{ position:absolute; cursor: pointer; top:0; right:0; transform: translate(50%,-50%); width:14px; height:14px; text-align: center; line-height:14px; border-radius: 100%; background:gray; } </style> <div> <form action="<?php echo U('Goods/hotelinfo');?>" method="post"> <div style="float:left"> <select name="chaxun" id="cha"> <option value="1">酒店名称</option> <option value="2">酒店地址</option> </select> </div> <div style="float:left"> <input type="text" name="hotel"> </div> <div> <input type="submit" value="搜索"> </div> </form> </div> <table border="1" cellpadding="1" cellspacing="1" width="100%" align="center"> <thead> <tr> <th >ID</th> <th >酒店名称</th> <th >酒店星级</th> <th >酒店电话</th> <th >酒店地址</th> <th >酒店邮箱</th> <th>其他</th> <th>酒店图片</th> <th >操作</th> </tr> <?php if(is_array($list)): $i = 0; $__LIST__ = $list;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$vo): $mod = ($i % 2 );++$i;?><tr> <th><?php echo ($vo["id"]); ?></th> <th><?php echo ($vo["name"]); ?></th> <th> <?php if(($vo["grade"] == inn)): ?>酒馆 <?php elseif($vo["grade"] == chain): ?>连锁酒店 <?php elseif($vo["grade"] == theme): ?>主题酒店 <?php elseif($vo["grade"] == three_star): ?>三星级 <?php elseif($vo["grade"] == four_star): ?>四星级 <?php elseif($vo["grade"] == five_star): ?>五星级 <?php else: ?> null<?php endif; ?> </th> <th><?php echo ($vo["phone_number"]); ?></th> <th><?php echo ($vo["address"]); ?></th> <th><?php echo ($vo["email"]); ?></th> <th> <button class="qita" onclick="other(<?php echo ($vo["id"]); ?>)">其他</button> <div class="stage qita_<?php echo ($vo["id"]); ?>" > <div class="form"> <table border="1"> <tr> <th width="80">地址经度</th> <th width="80">地址纬度</th> <th width="80">路线</th> <th width="80">酒店介绍</th> <th width="80">基础设施</th> </tr> <tr> <th width="80"><?php echo ($vo["longitude"]); ?></th> <th width="80"><?php echo ($vo["latitude"]); ?></th> <th width="80"><?php echo ($vo["routes"]); ?></th> <th width="80"><?php echo ($vo["introduction"]); ?></th> <th width="80">11</th> </tr> </table> <span class="close">&times;</span> <div> </div> </th> <th> <button class="btn" onclick="show(<?php echo ($vo["id"]); ?>)">酒店图片</button> <div class="stage img_<?php echo ($vo["id"]); ?>" > <div class="form"> <img src="/Public/image/hotel/<?php echo ($vo["url"]); ?>" alt=""> <span class="close">&times;</span> <div> </div> </th> <th><a href="<?php echo U('Goods/edithotel');?>?id=<?php echo ($vo["id"]); ?>" class="btn btn-danger">编辑信息</a> <a href="<?php echo U('Goods/edhotpic');?>?id=<?php echo ($vo["id"]); ?>" class="btn btn-danger">编辑图片</a> <a href="<?php echo U('Goods/infodel');?>?id=<?php echo ($vo["id"]); ?>" class="btn btn-danger">删除</a> </th> </tr><?php endforeach; endif; else: echo "" ;endif; ?> </thead> </table> <!-- <div id="toolbar" style="padding:5px;"> <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-print" plain="true" onclick="exportData()">导出CSV</a> --> <!-- <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cut" plain="true" onclick="deleteData()">删除</a>--> <!-- <form id="searchForm" style="display:inline-block;*display:inline;zoom:1;"> <input name="search" placeholder="名称" data-options="prompt:'请输入搜索内容',searcher:''" class="easyui-validatebox textbox" style="width: 180px; vertical-align: middle;" /> <input name="hiddenid" id="hiddenid" type="hidden" /> <a href="javascript:void(0);" class="easyui-linkbutton" plain="true" onclick="s_data();">搜索</a> </form> </div> --> <!-- 添水果详情 --> <!-- <div id="viewDlg" class="easyui-dialog" style="width: 600px; height: 500px; padding: 10px 20px"> <table border="0" style="height:500px;width:400px" align="center"> <tr> <td width="100" height="30" align="right">酒店名称: </td> <td width="300" height="30"><span id="_hotel_name"></span></td> </tr> <tr> <td width="100" height="30" align="right">酒店星级: </td> <td width="300" height="30"><span id="_hotel_star"></span></td> </tr> <tr> <td width="100" height="30" align="right">酒店主题: </td> <td width="300" height="30"><span id="_hotel_title"></span></td> </tr> <tr> <td width="100" height="30" align="right">房间数量: </td> <td width="300" height="30"><span id="_total_rooms"></span></td> </tr> <tr> <td width="100" height="30" align="right">酒店电话: </td> <td width="300" height="30"><span id="_hotel_telephone"></span></td> </tr> <tr> <td width="100" height="30" align="right">酒店地址: </td> <td width="300" height="30"><span id="_hotel_address"></span></td> </tr> <tr> <td width="100" height="30" align="right">酒店邮箱: </td> <td width="300" height="30"><span id="_hotel_email"></span></td> </tr> <tr> <td width="100" height="30" align="right">酒店简介:</td> <td width="300" height="30"><span id="_introduction"></span></td> </tr> <tr> <td align="right">图片:</td> <td><img name="" src="" width="300" height="230" alt="" id="_hotel_image"/></td> </tr> </table> </div> --> </div> <!-- <script type="text/javascript" src="__PUBLIC__/lhgdialog/lhgdialog.min.js"></script> --> <script type="text/javascript"> function show(id) { $('.img_'+id).fadeIn('1000'); } $('.close').click(function(){ $('.stage').fadeOut('1000'); }) function other(id) { $('.qita_'+id).fadeIn('1000'); } </script> </body> </html><file_sep><?php if (!defined('THINK_PATH')) exit();?><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="stylesheet" type="text/css" href="__PUBLIC__/themes/default/easyui.css" /> </head> <body> <div class="easyui-accordion" data-options="fit:false,border:false"> <div title="订单管理" icon="icon-sys" style="height:150px" > <ul class="easyui-tree"> <li ><a href="javascript:" style="color: #000" onclick="addTab('所有订单','__APP__/Order/index');"> 所有订单</a><i></i></li> <li><a href="javascript:" style="color: #000" onclick="addTab('未入住订单','__APP__/Order/onorder');"> 未入住订单</a><i></i></li> <li><a href="javascript:" style="color: #000" onclick="addTab('已入住订单','__APP__/Order/payorder');"> 已入住订单</a><i></i></li> </ul> </div> <?php if($_SESSION['permission']==1){?> <div title="管理员管理" icon="icon-sys" style="height:150px"> <ul class="easyui-tree"> <li><a href="javascript:" style="color: #000" onclick="addTab('管理员设置','__APP__/Auser/index');"> 管理员设置</a><i></i></li> </ul> </div> <?php }?> <div title="酒店管理" icon="icon-sys" style="height:150px"> <ul class="easyui-tree"> <li><a href="javascript:" style="color: #000" onclick="addTab('酒店管理','__APP__/Goods/hotelinfo');"> 酒店管理</a><i></i></li> </ul> <ul class="easyui-tree"> <li><a href="javascript:" style="color: #000" onclick="addTab('上传酒店','__APP__/Goods/uphotel');"> 上传酒店</a><i></i></li> </ul> </div> <?php if($_SESSION['permission']==0){?> <div title="房间管理" icon="icon-sys" style="height:150px"> <ul class="easyui-tree"> <li><a href="javascript:" style="color: #000" onclick="addTab('房间管理','__APP__/Goods/index');"> 房间管理</a><i></i></li> </ul> <ul class="easyui-tree"> <li><a href="javascript:" style="color: #000" onclick="addTab('修改房间','__APP__/Goods/uppd');"> 修改房间</a><i></i></li> </ul> </div> <?php }?> <div title="用户管理" icon="icon-sys" style="height:150px"> <ul class="easyui-tree"> <li><a href="javascript:" style="color: #000" onclick="addTab('所有用户','__APP__/User/index');"> 所有用户</a><i></i></li> </ul> </div> <?php if($_SESSION['permission']==0){?> <div title="积分管理" icon="icon-sys" style="height:150px"> <ul class="easyui-tree"> <li><a href="javascript:" style="color: #000" onclick="addTab('积分充值','__APP__/Credit/index');"> 积分充值</a><i></i></li> <li><a href="javascript:" style="color: #000" onclick="addTab('积分记录','__APP__/Credit/query');"> 积分记录</a><i></i></li> </ul> </div> <?php }?> <?php if($_SESSION['permission']==0){?> <div title="城市管理" icon="icon-sys" style="height:150px"> <ul class="easyui-tree"> <li><a href="javascript:" style="color: #000" onclick="addTab('热门城市','__APP__/City/hot');"> 热门城市</a><i></i></li> <li><a href="javascript:" style="color: #000" onclick="addTab('显示城市','__APP__/City/show');"> 显示城市</a><i></i></li> </ul> </div> <?php }?> <?php if($_SESSION['permission']==0){?> <div title="坐标管理" icon="icon-sys" style="height:150px"> <ul class="easyui-tree"> <li><a href="javascript:" style="color: #000" onclick="addTab('酒店地址','__APP__/Address/index');"> 酒店地址</a><i></i></li> </ul> </div> <?php }?> </div> </body><file_sep><?php // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: LunnLew <<EMAIL>> 20130801 // +---------------------------------------------------------------------- // | Docs:http://docs.qiniu.com/php-sdk/v6/index.html#rs-api /** * 资源管理类 */ abstract class QiniuRSSDK extends QiniuSDK{ /** * 申请应用时分配的app_key * @var string */ protected $AppKey = ''; /** * 申请应用时分配的 app_secret * @var string */ protected $AppSecret = ''; /** * API根路径 * @var string */ protected $ApiBase = 'http://rs.qbox.me'; public function __construct($param){ parent::__construct(); } /** * 取得API实例 * @static * @return mixed 返回API */ public static function getInstance($type, $param = null) { $name = ucfirst(strtolower($type)) . 'SDK'; require_once "sdk/{$name}.class.php"; if (class_exists($name)) { return new $name($param); } else { halt(L('_CLASS_NOT_EXIST_') . ':' . $name); } } /** * 资源状态 * @param string $bucket 空间名 * @param string $key 文件名 */ public function Stat($bucket, $key){ $uri = self::get_RS_URIStat($bucket, $key); return parent::call($this->ApiBase . $uri); } /** * 资源移动 * @param string $bucket 空间桶名 * @param string $key 文件名 * @param string $bucket1 空间桶名 * @param string $key1 文件名 */ public function Move($bucket, $key, $bucket1, $key1){ $uri = self::get_RS_URIMove($bucket, $key, $bucket1, $key1); parent::callNoRet($this->ApiBase . $uri); } /** * 资源复制 * @param string $bucket 空间桶名 * @param string $key 文件名 * @param string $bucket1 空间桶名 * @param string $key1 文件名 */ public function Copy($bucket, $key, $bucket1, $key1){ $uri = self::get_RS_URICopy($bucket, $key, $bucket1, $key1); parent::callNoRet($this->ApiBase . $uri); } /** * 资源删除 * @param string $bucket 空间名 * @param string $key 文件名 */ public function Delete($bucket, $key){ $uri = self::get_RS_URIDelete($bucket, $key); parent::callNoRet($this->ApiBase . $uri); } /** * 组合操作地址 * @param string $bucket 空间桶名 * @param string $key 文件名 * @param string $bucket1 空间桶名 * @param string $key1 文件名 * @return string uri */ public function get_RS_URIMove($bucket, $key, $bucket1, $key1){ return '/move/' . parent::SafeBaseEncode("$bucket:$key") . '/' . parent::SafeBaseEncode("$bucket1:$key1"); } public function get_RS_URIStat($bucket, $key){ return '/stat/' . parent::SafeBaseEncode("$bucket:$key"); } public function get_RS_URIDelete($bucket, $key){ return '/delete/' . parent::SafeBaseEncode("$bucket:$key"); } public function get_RS_URICopy($bucketSrc, $keySrc, $bucketDest, $keyDest){ return '/copy/' . parent::SafeBaseEncode("$bucketSrc:$keySrc") . '/' . parent::SafeBaseEncode("$bucketDest:$keyDest"); } } ?><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link id="easyuiTheme" rel="stylesheet" type="text/css" href="__PUBLIC__/themes/bootstrap/easyui.css" /> <link rel="stylesheet" type="text/css" href="__PUBLIC__/themes/icon.css" /> <script type="text/javascript" src="__PUBLIC__/js/jquery-1.8.0.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/jquery.easyui.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/admin.js" charset="utf-8"></script> <title>后台管理</title> </head> <body> <div class="easyui-panel" data-options="fit:true"> <table class="easyui-datagrid" id="datagrid_Order" data-options="url:'__APP__/Credit/getScore',method:'post',pagination:true,fit:true,toolbar:'#toolbar',rownumbers:true,checkOnSelect: true"> <thead> <tr> <th data-options="field:'hotel_name',sortable: true" width="250" align="center">贡献酒店名</th> <th data-options="field:'order_number',sortable: true" width="200" align="center">贡献订单数</th> <th data-options="field:'total_score',sortable: true" width="200" align="center">贡献金币数</th> </tr> </thead> </table> </div> </body> </html><file_sep><?php // 本类由系统自动生成,仅供测试用途 class CreditAction extends Action { public function index() { // var_dump($_SESSION); $this->display(); } public function getScore(){ $s = D("Score"); import("ORG.Util.Page"); //导入分页类 $page=$_POST["page"]? $_POST["page"] :1; $rows=$_POST["rows"]? $_POST["rows"] :10; $admin_id = $_SESSION["admin_id"]; $con['admin_id'] = $admin_id; $count = $s->count(); $list = $s->field('hotel_name,count(*) as order_number,sum(score_num) as total_score')->join('hotels ON score.contributor = hotels.hotel_id')->where($con)->group('contributor')->select(); $result['total'] = $count; $result['rows'] = $list; exit(json_encode($result)); } } ?><file_sep><?php if (!defined('THINK_PATH')) exit();?> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="description" content="Tsys管理系统"> <title>后台管理</title> <link id="easyuiTheme" rel="stylesheet" type="text/css" href="__PUBLIC__/themes/bootstrap/easyui.css"> <link rel="stylesheet" type="text/css" href="__PUBLIC__/themes/icon.css"> <script type="text/javascript" src="__PUBLIC__/js/jquery-1.8.0.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/jquery.easyui.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/admin.js" charset="utf-8"></script> </head> <link rel="stylesheet" type="text/css" href="__PUBLIC__/uploadify/uploadify.css" /> <script src="__PUBLIC__/uploadify/jquery.uploadify.min.js" type="text/javascript"></script> <body> <!-- <form action="<?php echo U('Goods/uppd');?>?id" method="post"> --> <div class="easyui-layout" data-options="fit:true"> <table class="easyui-datagrid" id="tab_data" data-options="url:'__APP__/Goods/getAllGoods',method:'post',pagination:true,fit:true,toolbar:'#toolbar',rownumbers:true,checkOnSelect: true"> <thead> <tr> <th data-options="field:'id',checkbox: true">ID</th> <th data-options="field:'name',sortable: true" width="100">房间名称</th> <th data-options="field:'area',align:'center',sortable: true" width="100">房间大小</th> <th data-options="field:'display_name',align:'center',sortable: true" width="100">床位类型</th> <th data-options="field:'price',align:'center',sortable: true" width="80">房间价格</th> <th data-options="field:'room_count',align:'center',sortable: true" width="80">房间数量</th> <th data-options="field:'cz',width:80,align:'center',formatter:formatOper" width="100">操作</th> </tr> <?php if(is_array($list)): $i = 0; $__LIST__ = $list;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$vo): $mod = ($i % 2 );++$i;?><tr> <th><?php echo ($vo["id"]); ?></th> <th><?php echo ($vo["name"]); ?></th> <th><?php echo ($vo["area"]); ?></th> <th><?php echo ($vo["display_name"]); ?></th> <th><?php echo ($vo["price"]); ?></th> <th><?php echo ($vo["count_num"]); ?></th> <th><a href="<?php echo U('Goods/uppd');?>?id=<?php echo ($vo["id"]); ?>" class="btn btn-danger">编辑</a></th> </tr><?php endforeach; endif; else: echo "" ;endif; ?> </thead> </table> <!-- </form> --> <!-- <div id="toolbar" style="padding:5px;"> <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-print" plain="true" onclick="exportData()">导出CSV</a> <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="addPanel()">新增</a> --> <!-- <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cut" plain="true" onclick="deleteData()">删除</a>--> <!-- <form id="searchForm" style="display:inline-block;*display:inline;zoom:1;"> <input name="search" placeholder="名称" data-options="prompt:'请输入搜索内容',searcher:''" class="easyui-validatebox textbox" style="width: 180px; vertical-align: middle;" /> <input name="hiddenid" id="hiddenid" type="hidden" /> <a href="javascript:void(0);" class="easyui-linkbutton" plain="true" onclick="s_data();">搜索</a> </form> </div> --> <!-- 添水果详情 --> <div id="viewDlg" class="easyui-dialog" style="width: 400px; height: 300px; padding: 10px 20px"> <table border="0" style="height:300px;width:400px"> <tr> <td width="100" height="30" align="right">房间名称: </td> <td width="300" height="30"><span id="_type_name"></span></td> </tr> <tr> <td width="100" height="30" align="right">描述:</td> <td width="300" height="30"><span id="_description"></span></td> </tr> <tr> <td align="right">图片:</td> <td><img name="" src="" width="300" height="230" alt="" id="_room_image"/></td> </tr> </table> </div> </div> <script type="text/javascript" src="__PUBLIC__/lhgdialog/lhgdialog.min.js"></script> <script type="text/javascript"> function convert(rows) { function exists(rows, parentId) { for (var i = 0; i < rows.length; i++) { if (rows[i].id == parentId) return true; } return false; } var nodes = []; for (var i = 0; i < rows.length; i++) { var row = rows[i]; if (!exists(rows, row.parentId)) { nodes.push({ id: row.type_id, text: row.name }); } } var toDo = []; for (var i = 0; i < nodes.length; i++) { toDo.push(nodes[i]); } while (toDo.length) { var node = toDo.shift(); // the parent node // get the children nodes for (var i = 0; i < rows.length; i++) { var row = rows[i]; if (row.parentId == node.id) { var child = { id: row.type_id, text: row.name }; if (node.children) { node.children.push(child); } else { node.children = [child]; } toDo.push(child); } } } return nodes; } //添加产品 function addData(){ var node = $('#menu-tree').tree("getSelected"); //if(node === null){ if(node == null){ $.dialog({lock:true,time: 3,icon:'error.gif',title:'错误提示',content: '请选择要添加的菜单!'}); return false; }else{ var pid = node.id; $.post("<?php echo U('Goods/addpd');?>",{pid:pid},function(data){ $('#audata').html(data); }); } } //删除选中项 function deleteData() { var datagrid = $("#tab_data"); var rows = datagrid.datagrid('getChecked'); var ids = []; if (rows.length > 0) { parent.dj.messagerConfirm('请确认', '您要删除当前所选项目?', function(r) { if (r) { for ( var i = 0; i < rows.length; i++) { ids.push(rows[i].fruit_id); } $.ajax({ url : '__APP__/Goods/delete', data : { ids : ids.join(',') }, dataType : 'json', success : function(d) { datagrid.datagrid('load'); datagrid.datagrid('unselectAll'); parent.dj.messagerShow({ title : '提示', msg : d.info }); } }); } }); } else { parent.dj.messagerAlert('提示', '请勾选要删除的记录!', 'error'); } } function formatType(val,row,index){ var type = row.type; var typename = ''; switch(type){ case "tehuishuiguo": typename = '特惠水果'; break; case "jinkoushuiguo": typename = '进口水果'; break; case "shiyanshitaocan": typename = '实验室套餐'; break; case "gerentaocan": typename = '个人套餐'; break; case "zhengxiangpifa": typename = '整箱批发'; break; case "yinliaoguozhi": typename = '饮料果汁'; break; case "lingshi": typename = '零食'; break; case "qita": typename = '其他'; break; } return typename; } function formatOper(val,row,index){ var optr = '<a href="javascript:void(0);" onclick="edit('+row.type_id+')">修改</a>'; optr +=' &nbsp;&nbsp;<a href="javascript:void(0);" onclick="view('+row.type_id+')">详情</a>'; return optr; } function view(id){ $.ajax({ url: '__APP__/Goods/getGoodsById', data: {id: id}, dataType: 'json', async:false, success: function (rows) { $('#_type_name').html(rows.type_name); $('#_room_image').attr('src',rows.image_url); $('#_description').html(rows.description); } }); var html = $('#viewDlg').clone(); $.dialog({ id:'test123', lock: true, content: html, width: 400, height: 250, title:'查看房间详情', cancel: true }); } function addPanel(){ $.dialog({ id:'testadd', lock: true, //content: 'url:/admin.php/Goods/addpd', url: '__APP__/Goods/addpd', content: 'url:__APP__/Goods/addpd', width: 800, height: 500, title:"房间添加", cancel:function(){ window.location.reload(); } }); } function edit(id){ $.dialog({ id:'testedit', lock: true, //content: 'url:/admin.php/Goods/uppd/id/'+id, //url: '__APP__/Goods/uppd?id='+id, content: 'url: __APP__/Goods/uppd?id='+id, width: 800, height: 350, title:"房间编辑", cancel:function(){ window.location.reload(); } }); } function exportData() { } //搜索名称 function s_data() { $('#tab_data').datagrid('loadData', { total: 0, rows: [] }); $('#tab_data').datagrid('load', dj.serializeObject($('#searchForm'))); } </script> </body> </html><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html> <html lang="en"> <head> <script src="__PUBLIC__/js/jquery-1.8.0.min.js" type="text/javascript"></script> <script src="__PUBLIC__/layer/layer.js" type="text/javascript"></script> <meta charset="UTF-8"> <title>Document</title> </head> <body> <h1>更换图片</h1> <form method="post" action="" enctype="multipart/form-data" class="upfile" onsubmit="return check()"> <input name="token" type="hidden" value="<?php echo ($uptoken); ?>"> <input name="file" type="file" id="picture"/> <input type="submit" value="修改"> </form> <script> function check() { if($('#picture').val() == '') { layer.msg('请选择图片'); setTimeout(function(){ $('#picture').focus(); }); return false; }else{ return true; } } </script> </body> </html><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link id="easyuiTheme" rel="stylesheet" type="text/css" href="__PUBLIC__/themes/bootstrap/easyui.css" /> <link rel="stylesheet" type="text/css" href="__PUBLIC__/themes/icon.css" /> <script type="text/javascript" src="__PUBLIC__/js/jquery-1.8.0.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/jquery-1.7.2.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/jquery.easyui.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/admin.js" charset="utf-8"></script> <script type="text/javascript" src="__PUBLIC__/js/vue.js" charset="utf-8"></script> <script type="text/javascript" src="__PUBLIC__/js/bootstrap.min.js" charset="utf-8"></script> <title>后台管理</title> </head> <body> </body> </html><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="stylesheet" type="text/css" href="__PUBLIC__/themes/icon.css" /> <link href="__PUBLIC__/css/store.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="__PUBLIC__/js/jquery-1.8.0.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/bootstrap.min.js"></script> <script type="text/javascript" src="__PUBLIC__/layer/layer.js"></script> <title>Document</title> </head> <body> <?php if(is_array($list)): $i = 0; $__LIST__ = $list;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$vo): $mod = ($i % 2 );++$i;?><div class="goods"> <a href="<?php echo U('Store/gooddetail');?>?id=<?php echo ($vo["id"]); ?>"><img src="<?php echo ($vo["iname"]); ?>" alt=""></a> <p style="text-align:center"><?php echo ($vo["gname"]); ?></p> </div><?php endforeach; endif; else: echo "" ;endif; ?> </body> </html><file_sep><?php class TiebaAction extends Action { public function topic() { $list = M('tieba_topics')->join('tiebas ON tieba_topics.tieba_id = tiebas.id')->join('tieba_classifies ON tieba_topics.classify_id = tieba_classifies.id')->join('users ON tieba_topics.user_id = users.id')-> field('tieba_topics.*,tiebas.display_name tdn,tieba_classifies.display_name tcdn,users.nickname')->select(); $this->assign('list',$list); $this->display(); } public function opcdel() { $id = $_POST['id']; $list = M('tieba_topics')->delete($id); if ($list !== false && $list !== 0) { $this->ajaxReturn($list); }else{ $this->ajaxReturn('false'); } } public function gambit() { $this->display(); } } ?><file_sep><?php class TiebaAction extends Action { public function topic() { if ($_SESSION['permission'] == 0) { // var_dump($_SESSION); // exit; $id = M('hotel_admin')->where(array('admin_id'=>$_SESSION['admin_id']))->field('hotel_id')->find(); $hotelid = $id['hotel_id']; $map = "('tiebas.type = hotel') and (relate_id=".$hotelid.")"; $list = M('tieba_topics') ->join('tiebas ON tieba_topics.tieba_id = tiebas.id') ->join('tieba_classifies ON tieba_topics.classify_id = tieba_classifies.id') ->join('users ON tieba_topics.user_id = users.id') ->where($map) -> field('tieba_topics.*,tiebas.display_name tdn,tieba_classifies.display_name tcdn,users.nickname') ->select(); }else{ $list = M('tieba_topics') ->join('tiebas ON tieba_topics.tieba_id = tiebas.id') ->join('tieba_classifies ON tieba_topics.classify_id = tieba_classifies.id') ->join('users ON tieba_topics.user_id = users.id') -> field('tieba_topics.*,tiebas.display_name tdn,tieba_classifies.display_name tcdn,users.nickname') ->select(); } $this->assign('list',$list); $this->display(); } public function opcdel() { $id = $_POST['id']; $list = M('tieba_topics')->delete($id); if ($list !== false && $list !== 0) { $this->ajaxReturn($list); }else{ $this->ajaxReturn('false'); } } public function alldel() { // var_dump($_POST); // exit; // $arr = []; foreach ($_POST as $key => $val) { foreach ($val as $v) { $list = M('tieba_topics')->delete($v); } } if ($list !== false && $list !== 0) { $this->ajaxReturn('1'); }else{ $this->ajaxReturn('2'); } } public function gambit() { $this->display(); } } ?><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="description" content="Tsys管理系统"> <title>后台管理</title> <link id="easyuiTheme" rel="stylesheet" type="text/css" href="__PUBLIC__/themes/bootstrap/easyui.css"> <link rel="stylesheet" type="text/css" href="__PUBLIC__/themes/icon.css"> <script type="text/javascript" src="__PUBLIC__/js/jquery-1.8.0.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/jquery.easyui.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/admin.js" charset="utf-8"></script> </head> <link rel="stylesheet" type="text/css" href="__PUBLIC__/uploadify/uploadify.css" /> <script src="__PUBLIC__/uploadify/jquery.uploadify.min.js" type="text/javascript"></script> <script src="__PUBLIC__/layer/layer.js" type="text/javascript"></script> <body> <div class="easyui-panel" fit="true"> <form action="<?php echo U('Goods/doedit');?>" id="editForm" method="post" enctype="multipart/form-data" onsubmit="return check()"> <input name="type_id" type="hidden" value="<?php echo ($list["id"]); ?>"/> <table width="780" border="0"> <tr style="height: 50px;"> <td width="100" align="right"> 房间名称: </td> <td width="250"> <input name="type_name" style="width: 250px" value="<?php echo ($list["display_name"]); ?>" id="name"/> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 房间大小: </td> <td width="250"> <input name="room_area" style="width: 250px" value="<?php echo ($list["area"]); ?>" id="area"/> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 房间价格 : </td> <td width="250"> <input name="room_price" style="width: 250px" value="<?php echo ($list["price"]); ?>" id="price"/> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 房间数量: </td> <td width="250"> <input name="count_num" style="width: 250px" value="<?php echo ($list["count_num"]); ?>" id="count"/> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 可住人数: </td> <td width="250"> <input name="people_num" style="width: 250px" value="<?php echo ($list["people_num"]); ?>" id="peobun"/> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 房间所在楼层: </td> <td width="250"> <input name="floors" style="width: 250px" value="<?php echo ($list["floors"]); ?>" id="floor"/> </td> </tr> <!-- <tr style="height: 50px;"> <td width="100" align="right"> 房间类型: </td> <td width="250" align="left"> <select name="room_type" style="width:100px"> <option value="2" <?php if($list["room_type"] == '2'): ?>selected<?php endif; ?>>标准型</option> <option value="3" <?php if($list["room_type"] == '3'): ?>selected<?php endif; ?>>豪华型</option> <option value="4" <?php if($list["room_type"] == '4'): ?>selected<?php endif; ?>>奢靡型</option> <option value="5" <?php if($list["room_type"] == '5'): ?>selected<?php endif; ?>>总统型</option> </select> </td> </tr> --> <tr style="height: 50px;"> <td width="100" align="right"> 有无早餐: </td> <td width="250" align="left"> <select name="breakfast" style="width:100px"> <option value="0" <?php if($list["breakfast"] == '0'): ?>selected<?php endif; ?>>无</option> <option value="1" <?php if($list["breakfast"] == '1'): ?>selected<?php endif; ?>>有</option> </select> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 可否加床: </td> <td width="250" align="left"> <select name="bed_add" style="width:100px"> <option value="0" <?php if($list["bed_add"] == '0'): ?>selected<?php endif; ?>>可以</option> <option value="1" <?php if($list["bed_add"] == '1'): ?>selected<?php endif; ?>>不可以</option> </select> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 加床价格: </td> <td width="250"> <input name="bed_add_price" style="width: 250px" value="<?php echo ($list["bed_add_price"]); ?>" id="bedadd"/> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 单床大小: </td> <td width="250"> <input name="bed_area" style="width: 250px" value="<?php echo ($list["bed_area"]); ?>" id="bedarea"/> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 可否吸烟: </td> <td width="250" align="left"> <select name="smoke" style="width:100px"> <option value="0" <?php if($list["smoke"] == '0'): ?>selected<?php endif; ?>>可以</option> <option value="1" <?php if($list["smoke"] == '1'): ?>selected<?php endif; ?>>不可以</option> </select> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 是否有热水: </td> <td width="250" align="left"> <select name="hot_water" style="width:100px"> <option value="0" <?php if($list["hot_water"] == '0'): ?>selected<?php endif; ?>>有</option> <option value="1" <?php if($list["hot_water"] == '1'): ?>selected<?php endif; ?>>没有</option> </select> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 是否有空调: </td> <td width="250" align="left"> <select name="air_conditioner" style="width:100px"> <option value="0" <?php if($list["air_conditioner"] == '0'): ?>selected<?php endif; ?>>有</option> <option value="1" <?php if($list["air_conditioner"] == '1'): ?>selected<?php endif; ?>>没有</option> </select> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 无线网络: </td> <td width="250" align="left"> <select name="internet" style="width:100px"> <option value="none" <?php if($list["internet"] == 'none'): ?>selected<?php endif; ?>>无</option> <option value="wifi" <?php if($list["internet"] == 'wifi'): ?>selected<?php endif; ?>>wifi</option> <option value="broadband" <?php if($list["internet"] == 'broadband'): ?>selected<?php endif; ?>>broadband</option> </select> </td> </tr> <!-- <tr style="height: 50px;"> <td width="100" align="right"> 容纳人数: </td> <td width="250" align="left" > <select name="people_num" style="width:100px"> <option value="1" <?php if($list["person"] == '1'): ?>selected<?php endif; ?>>1</option> <option value="2" <?php if($list["person"] == '2'): ?>selected<?php endif; ?>>2</option> </select> </td> </tr> --> </table> <div style="text-align:left;padding:20px;"> <input type="submit" value="修改"> </div> </form> </div> <script type="text/javascript"> function check() { if ($('#name').val() == '') { layer.msg('请输入房间名称'); setTimeout(function(){ $('#name').focus(); }); return false; }else if($('#area').val() == ''){ layer.msg('请输入房间大小'); setTimeout(function(){ $('#area').focus(); }); return false; }else if($('#price').val() == ''){ layer.msg('请输入房间价格'); setTimeout(function(){ $('#price').focus(); }); return false; }else if($('#count').val() == ''){ layer.msg('请输入房间数量'); setTimeout(function(){ $('#count').focus(); }); return false; }else if($('#peobun').val() == ''){ layer.msg('请输入可住人数'); setTimeout(function(){ $('#peobun').focus(); }); return false; }else if($('#floor').val() == ''){ layer.msg('请输入所在楼层'); setTimeout(function(){ $('#floor').focus(); }); return false; }else{ return true; } } </script> <!-- <script type="text/javascript" src="__PUBLIC__/lhgdialog/lhgdialog.min.js"></script> --> </body><file_sep><?php // 本类由系统自动生成,仅供测试用途 class IndexAction extends Action { public function index() { if (!isset($_SESSION["username"])) { $this->redirect('Index/login') ; } $dtcount = C('DT_TIME_COUNT'); $rfcount = C('DT_REFRESH_COUNT'); $this->assign('dtcount',$dtcount); $this->assign('rfcount',$rfcount); $this->display(); } public function checklogin() { $admin=M('admin'); $user=M('Hotel_admin'); $username=trim($_POST['username']); $password=trim($_POST['password']); //$password2=md5($password); $condition['name']=$username; $condition['password']=$<PASSWORD>; $con['Name'] = $username; $con['Password'] = $<PASSWORD>; $query=$user->where($condition)->find(); $query_admin=$admin->where($con)->find(); $admin_id = $user->where($con)->getField('admin_id'); $credit = $user->where($con)->getField('credit'); //var_dump($user->getLastSql());exit; if($query_admin){ $_SESSION["username"] = $username; $_SESSION['permission'] = 1; $this->redirect('../../admin.php') ; //$this->success('登录成功', '../../admin.php'); } else{ if($query){ $_SESSION["username"] = $username; $_SESSION['permission'] = 0; $_SESSION["admin_id"] = $admin_id; $_SESSION["credit"] = $credit; $this->redirect('../../admin.php') ; //$this->success('登录成功', '../../admin.php'); }else{ $this->error('登录失败,请重新登录'); } } } public function loginout() { if (isset($_SESSION["username"])){ unset($_SESSION["username"]); //unset($_SESSION["admin_id"]); unset($_SESSION["credit"]); session('[destroy]'); exit(); }else { session('[destroy]'); exit(); //$this->error("已经注销登录!"); } } public function editPwd(){ //在ThinkPHP中使用save方法更新数据库,并且也支持连贯操作的使用 $Form = D("Hotel_admin"); $user=M('Hotel_admin'); //$password=md5($_POST['password']); //$newpassword=md5($_POST['newpassword']); $password=$_POST['password']; $newpassword=$_POST['newpassword']; $username=$_SESSION["username"]; $condition['name']=$username; $condition['password']=$<PASSWORD>; $query=$user->where($condition)->find(); header("Content-type:text/html;charset=utf-8"); if($query) { $AdminId = $user->where($condition)->getField('admin_id'); $con1['admin_id'] = $AdminId; $con['name'] = $username; $con['password'] = <PASSWORD>; $result = $user->where($con1)->save($con); unset($_SESSION["username"]); //$this->success('密码修改成功,请用新密码重新登录', '../../admin.php'); echo "<script>alert('密码修改成功,请用新密码重新登录');top.location = '../../admin.php';</script>"; } else echo "<script>alert('原密码错误');</script>"; //$this->ajaxReturn($_POST,'原密码错误',0); //$this->error('原密码错误'); } // public function editPwd(){ // //在ThinkPHP中使用save方法更新数据库,并且也支持连贯操作的使用 // $Form = D("admin"); // $user=M('admin'); // //$password=md5($_POST['password']); // //$newpassword=md5($_POST['newpassword']); // $password=$_POST['password']; // $newpassword=$_POST['newpassword']; // $username=$_SESSION["username"]; // $condition['Name']=$username; // $condition['Password']=$<PASSWORD>; // $query=$user->where($condition)->find(); // header("Content-type:text/html;charset=utf-8"); // if($query) // { // $user_id = $user->where($condition)->getField('admin_id'); // $condition2['admin_id']=$user_id; // $condition2['admin_password']=$<PASSWORD>; // if ($Form->create($condition2)) { // $list = $Form->save($condition2); // //dump($_POST); // //未传入$data理由同上面的add方法 // /* 为了保证数据库的安全,避免出错更新整个数据表,如果没有任何更新条件,数据对象本身也不包含主键字段的话, // save方法不会更新任何数据库的记录。 // 因此下面的代码不会更改数据库的任何记录 // */ // //dump($list); // if ($list !== false) { // //注意save方法返回的是影响的记录数,如果save的信息和原某条记录相同的话,会返回0 // //所以判断数据是否更新成功必须使用 '$list!== false'这种方式来判断 // //$this->ajaxReturn($_POST,'修改密码成功!',1); // unset($_SESSION["username"]); // //$this->success('密码修改成功,请用新密码重新登录', '../../admin.php'); // echo "<script>alert('密码修改成功,请用新密码重新登录');top.location = '../../admin.php';</script>"; // } else { // //$this->error('密码修改失败'); // echo "<script>alert('密码修改失败');</script>"; // //$this->ajaxReturn($_POST,'没有更新任何数据!',0); // } // } else { // echo "<script>alert('密码修改失败');</script>"; // //$this->ajaxReturn($_POST,$Form->getError(),3); // //$this->error('密码修改失败'); // } // } // else // echo "<script>alert('原密码错误');</script>"; // //$this->ajaxReturn($_POST,'原密码错误',0); // //$this->error('原密码错误'); // } public function check(){ $o = D('Order_rooms'); $sql = 'select count(*) count from Order_rooms where flag = 0'; $count = $o->query($sql); if($count[0]['count'] > 0){ $code = true; $num = $count[0]['count']; }else{ $code = false; $num = 0; } echo json_encode(array('code'=>$code,'num'=>$num)); } //订单监听 // public function check(){ // $o = D('Order_rooms'); // $a = D('Admin'); // $sql = 'select count(*) count from Order_rooms'; // $asql = 'select count from Admin where admin_id = 1'; // $count1 = $o->query($sql); // $count2 = $a->query($asql); // if($count2[0]['count']<$count1[0]['count']){ // //有订单没处理 // $code = true; // $num = $count1[0]['count'] - $count2[0]['count']; // }else{ // $code = false; // $num = 0; // } // echo json_encode(array('code'=>$code,'num'=>$num)); // } }<file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html> <html lang="en"> <head> <script type="text/javascript" src="__PUBLIC__/js/jquery-1.8.0.min.js"></script> <script src="__PUBLIC__/layer/layer.js" type="text/javascript"></script> <meta charset="UTF-8"> <title>Document</title> </head> <body> <h1>添加顶级分类</h1> <form action="<?php echo U('Adminstore/doaddcate');?>" method="post" onsubmit="return check()"> <table> <input type="hidden" name="pid" value="<?php echo ($pid); ?>" readonly="readonly"> <input type="hidden" name="path" value="<?php echo ($path); ?>" readonly="readonly"> <tr> <th>名称<input type="text" name="cname" id="name"></th> </tr> <tr> <th><input type="submit"> </th> </tr> </table> </form> <script> function check() { if ($('#name').val() == '') { layer.msg('请输入分类名'); setTimeout(function(){ $('#name').focus(); }); return false; } } </script> </body> </html><file_sep><?php // 本类由系统自动生成,仅供测试用途 class IndexAction extends Action { public function index(){ //$this->show('欢迎来到春堤网站管理系统'); header("location:/admin.php"); } } <file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link id="easyuiTheme" rel="stylesheet" type="text/css" href="__PUBLIC__/themes/bootstrap/easyui.css" /> <link rel="stylesheet" type="text/css" href="__PUBLIC__/themes/icon.css" /> <script type="text/javascript" src="__PUBLIC__/js/jquery-1.8.0.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/jquery.easyui.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/admin.js" charset="utf-8"></script> <title>后台管理</title> </head> <body> <div class="easyui-panel" data-options="fit:true"> <table border="1" cellpadding="1" cellspacing="1" width="100%" align="center"> <thead> <tr> <th width="250" align="center">姓名</th> <th width="200" align="center">联系方式</th> <th width="200" align="center">酒店名称</th> <th width="200" align="center">酒店地址</th> <th width="200" align="center">电子邮箱</th> <th width="200" align="center">酒店管理系统使用情况</th> </tr> <?php if(is_array($list)): $i = 0; $__LIST__ = $list;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$vo): $mod = ($i % 2 );++$i;?><tr> <td width="250" align="center"><?php echo ($vo["name"]); ?></th> <td width="250" align="center"><?php echo ($vo["phone"]); ?></th> <td width="250" align="center"><?php echo ($vo["hotel_name"]); ?></th> <td width="250" align="center"><?php echo ($vo["hotel_address"]); ?></th> <td width="250" align="center"><?php echo ($vo["email"]); ?></th> <td width="250" align="center"> <?php if(($vo["platform"] == zlm)): ?>住了吗酒店管理系统 <?php elseif($vo["platform"] == others): ?>其他酒店管理系统 <?php else: ?> 没有使用酒店管理系统<?php endif; ?> </td> </tr><?php endforeach; endif; else: echo "" ;endif; ?> </thead> </table> </div> </body> <script> </script> </html><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link id="easyuiTheme" rel="stylesheet" type="text/css" href="__PUBLIC__/themes/bootstrap/easyui.css" /> <link rel="stylesheet" type="text/css" href="__PUBLIC__/themes/icon.css" /> <script type="text/javascript" src="__PUBLIC__/js/jquery-1.8.0.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/jquery.easyui.min.js"></script> <script type="text/javascript" src="__PUBLIC__/layer/layer.js"></script> <script type="text/javascript" src="__PUBLIC__/js/admin.js" charset="utf-8"></script> <title>后台管理</title> </head> <style> .stage{ position:absolute; top:0; bottom:0; left:0; right:0; background:rgba(0,0,0,0.2); display:none; } .form{ position:absolute; top:50%; left:50%; transform: translate(-50%,-50%); padding:10px; background: #fff; } .close{ position:absolute; cursor: pointer; top:0; right:0; transform: translate(50%,-50%); width:14px; height:14px; text-align: center; line-height:14px; border-radius: 100%; background:gray; } </style> <body> <div > <form action="<?php echo U('Order/refund');?>" method="get"> <div style="float:left"> <select name="chaxun" id=""> <option value="1">手机号</option> </select> </div> <div style="float:left"> <input type="text" name="hotel" > </div> <div> <input type="submit" value="搜索"> </div> </form> <table border="1" cellpadding="1" cellspacing="1" width="100%" align="center"> <thead> <tr> <th >ID</th> <th >对应订单</th> <th>用户</th> <th>手机号</th> <th>退款金额</th> <th >退款方式</th> <th>到账时间</th> <th >退款状态</th> <th>操作</th> <th >备注</th> </tr> <?php if(is_array($list)): $i = 0; $__LIST__ = $list;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$vo): $mod = ($i % 2 );++$i;?><tr> <td ><?php echo ($vo["id"]); ?></td> <td ><?php echo ($vo["order_id"]); ?></td> <td><?php echo ($vo["uname"]); ?></td> <td><?php echo ($vo["up"]); ?></td> <td><?php echo ($vo["money"]); ?></td> <td> <?php if($vo["method"] == wechat): ?>微信钱包 <?php elseif($vo["method"] == store): ?>店面退款 <?php else: ?>积分<?php endif; ?> </td> <td><?php echo ($vo["refund_time"]); ?></td> <td > <?php if($vo["status"] == apply): ?>用户请求退款 <?php elseif($vo["status"] == agree): ?>酒店同意退款 <?php elseif($vo["status"] == reject): ?>酒店拒绝退款 <?php else: ?>退款到账<?php endif; ?> </td> <td style="width:300px"> <button class="agree" bh="<?php echo ($vo["id"]); ?>">同意退款</button> <button class="refuse" bh="<?php echo ($vo["id"]); ?>">拒绝退款</button> <button class="tui" bh="<?php echo ($vo["id"]); ?>">退款完成</button> <button class="mask" onclick="other(<?php echo ($vo["id"]); ?>)">修改备注</button> <div class="stage mask_<?php echo ($vo["id"]); ?>"> <div class="form"> <form action="<?php echo U('Order/editcom');?>?id=<?php echo ($vo["id"]); ?>" method="post"> <input type="text" name="mask"> <input type="submit"> </form> <span class="close">&times;</span> </div> </div> </td> <td ><?php echo ($vo["remark"]); ?></td> </tr><?php endforeach; endif; else: echo "" ;endif; ?> </thead> </table> <script> function other(id) { $('.mask_'+id).fadeIn('1000'); } $('.close').click(function(){ $('.stage').fadeOut('1000'); }) $('.tui').click(function(){ var id = $(this).attr('bh'); $.ajax({ type:'post', url:"<?php echo U('Order/tuikuan');?>", data:{'id':id}, datatype:'json', success:function(data){ if (data >0) { alert('退款完成'); window.location.reload(); }else{ alert('无法修改状态'); } } }) }) $('.agree').click(function(){ var id = $(this).attr('bh'); $.ajax({ type:'post', url:"<?php echo U('Order/agree');?>", data:{'id':id}, datatype:'json', success:function(data){ if (data > 0) { alert('已同意'); window.location.reload(); }else{ alert('订单未完成或非请求退款状态'); } } }) }) $('.refuse').click(function(){ var id = $(this).attr('bh'); $.ajax({ type:'post', url:"<?php echo U('Order/refuse');?>", data:{'id':id}, datatype:'json', success:function(data){ if (data > 0) { alert('已拒绝'); window.location.reload(); }else{ alert('拒绝失败'); } } }) }) </script> </body> </html><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="description" content="Tsys管理系统"> <title>后台管理</title> <link id="easyuiTheme" rel="stylesheet" type="text/css" href="__PUBLIC__/themes/bootstrap/easyui.css"> <link rel="stylesheet" type="text/css" href="__PUBLIC__/themes/icon.css"> <script type="text/javascript" src="__PUBLIC__/js/jquery-1.8.0.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/jquery.easyui.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/admin.js" charset="utf-8"></script> </head> <link rel="stylesheet" type="text/css" href="__PUBLIC__/uploadify/uploadify.css" /> <script src="__PUBLIC__/uploadify/jquery.uploadify.min.js" type="text/javascript"></script> <script src="__PUBLIC__/layer/layer.js" type="text/javascript"></script> <script type="text/javascript" src="http://api.map.baidu.com/api?v=1.3"></script> <body> <div class="easyui-panel" fit="true"> <center><form action="<?php echo U('Auser/doedit');?>" id="editForm" method="post" enctype="multipart/form-data" onsubmit = "return check()"> <input name="id" type="hidden" value="<?php echo ($list["aid"]); ?>"/> <table width="780" border="0"> <tr style="height: 50px;"> <td width="100" align="right"> 用户名: </td> <td width="250"> <input name="name" style="width: 250px" value="<?php echo ($list["han"]); ?>" id="name"/> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 酒店名称: </td> <td width="250"> <input name="hotelname" style="width: 250px" value="<?php echo ($list["hn"]); ?>" id="hotelname"/> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right" > 密码: </td> <td width="250"> <input type="password" name="pwd" placeholder="如不修改请勿输入" style="width: 250px" id="pwd"/> </td> </tr> <tr style="height: 50px;"> <td width="100" align="right"> 酒店电话: </td> <td width="250"> <input name="phone" style="width: 250px" value="<?php echo ($list["at"]); ?>" id="phone"/> </td> </tr> </table> <div style="text-align:left;padding:20px;"> <center><input type="submit" value="修改"></center> <!-- <a href="" class="easyui-linkbutton" style="width:80px" ">修改</a> --> </div> </form></center> </script> <script type="text/javascript"> function check() { if ($('#name').val() == '') { layer.msg('请输入用户名'); setTimeout(function(){ $('#name').focus(); }); return false; }else if($('#hotelname').val() == ''){ layer.msg('请输入酒店名称'); setTimeout(function(){ $('#hotelname').focus(); }); return false; }else if($('#phone').val() == ''){ layer.msg('请输入酒店电话'); setTimeout(function(){ $('#phone').focus(); }); return false; }else{ return true; } } </script> </body><file_sep><?php return array( //'配置项'=>'配置值' 'OUTPUT_ENCODE' => false, 'APP_DEBUG' => false, // 开启调试模式 'DB_TYPE'=> 'mysql', // 数据库类型 'DB_HOST'=> 'localhost', // 数据库服务器地址 'DB_NAME'=>'hotel', // 数据库名称 'DB_USER'=>'root', // 数据库用户名 'DB_PWD'=>'', // 数据库密码 'DB_PORT'=>'3306', // 数据库端口 'DB_PREFIX'=>'', // 数据表前缀 //酒店 // 'DB_TYPE'=>'mysql', // 数据库类型 // 'DB_HOST'=>'172.16.17.32', // 数据库服务器地址 // 'DB_NAME'=>'zjuhotel', // 数据库名称 // 'DB_USER'=>'zjuhotel', // 数据库用户名 // 'DB_PWD'=>'<PASSWORD>', // 数据库密码 // 'DB_PORT'=>'3306', // 数据库端口 // 'DB_PREFIX'=>'', // 数据表前缀 // 'DB_CHARSET'=>'utf8', 'DB_CHARSET'=>'utf8', 'SESSION_AUTO_START' =>true, // //图片上传路径 // 'UPLOAD_DIR'=>'/Public/upload/', 'ROOM_UPLOAD_DIR'=>'./laravel/public/uploads/image/', //监听时间间隔10s 'DT_TIME_COUNT'=>'10000',//默认10s 这个单位是ms //监听消息提示n次后刷新订单页面 'DT_REFRESH_COUNT'=>'5',//默认是5次 // 'THINK_SDK_QINIU'=>array( // 'APP_KEY'=>'<<KEY>>', // 'APP_SECRET'=>'<<KEY>>', // 'DOWN_DOMAIN'=>'<zlmimg.qiniudn.com>' // ), //七牛上传文件设置 // 'PICTURE_UPLOAD_DRIVER'=>'Qiniu', // //本地上传文件驱动配置 // 'UPLOAD_LOCAL_CONFIG'=>array(), // 'UPLOAD_QINIU_CONFIG'=>array( // 'accessKey'=>'<KEY>', // 'secrectKey'=>'<KEY>', // 'bucket'=>'zlmimg', // 'domain'=>'zlmimg.qiniudn.com', // 'timeout'=>3600, // ), // 'UPLOAD_SITEIMG_QINIU'=>array( // 'maxSize'=>5*1024*1024,//文件大小 // 'rootPath'=>'./', // 'saveName'=>array('uniqid',''), // 'driver'=>'Qiniu', // 'driverConfig'=>array( // 'secrectKey'=>'<KEY>', // 'accessKey'=>'<KEY>', // 'domain'=>'zlmimg.qiniudn.com', // 'bucket'=>'zlmimg', // 'default' => 'ofnl1imqj.bkt.clouddn.com', // ), // ) // 'qiniu' => [ // 'driver' => 'qiniu', // 'domains' => [ // 'default' => 'ofnl1imqj.bkt.clouddn.com', //你的七牛域名 // 'https' => '', //你的HTTPS域名 // 'custom' => 'img.zlmhotel.com', //你的自定义域名 // ], // 'access_key'=> env('QINIU_AK','<KEY>'), //AccessKey // 'secret_key'=> env('QINIU_SK','<KEY>'), //SecretKey // 'bucket' => env('QINIU_BUCKET','zlmimg'), //Bucket名字 // 'notify_url'=> '', //持久化处理回调地址 // ], ) ?> <file_sep><?php if (!defined('THINK_PATH')) exit();?> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="description" content="Tsys管理系统"> <title>后台管理</title> <link id="easyuiTheme" rel="stylesheet" type="text/css" href="__PUBLIC__/themes/bootstrap/easyui.css"> <link rel="stylesheet" type="text/css" href="__PUBLIC__/themes/icon.css"> <script type="text/javascript" src="__PUBLIC__/js/jquery-1.8.0.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/jquery.easyui.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/admin.js" charset="utf-8"></script> </head> <link rel="stylesheet" type="text/css" href="__PUBLIC__/uploadify/uploadify.css" /> <script src="__PUBLIC__/uploadify/jquery.uploadify.min.js" type="text/javascript"></script> <script type="text/javascript"> function convert(rows) { function exists(rows, parentId) { for (var i = 0; i < rows.length; i++) { if (rows[i].id == parentId) return true; } return false; } var nodes = []; for (var i = 0; i < rows.length; i++) { var row = rows[i]; if (!exists(rows, row.parentId)) { nodes.push({ id: row.type_id, text: row.name }); } } var toDo = []; for (var i = 0; i < nodes.length; i++) { toDo.push(nodes[i]); } while (toDo.length) { var node = toDo.shift(); // the parent node // get the children nodes for (var i = 0; i < rows.length; i++) { var row = rows[i]; if (row.parentId == node.id) { var child = { id: row.type_id, text: row.name }; if (node.children) { node.children.push(child); } else { node.children = [child]; } toDo.push(child); } } } return nodes; } //添加产品 function addData(){ var node = $('#menu-tree').tree("getSelected"); //if(node === null){ if(node == null){ $.dialog({lock:true,time: 3,icon:'error.gif',title:'错误提示',content: '请选择要添加的菜单!'}); return false; }else{ var pid = node.id; $.post("<?php echo U('Goods/addpd');?>",{pid:pid},function(data){ $('#audata').html(data); }); } } //删除选中项 function deleteData() { var datagrid = $("#tab_data"); var rows = datagrid.datagrid('getChecked'); var ids = []; if (rows.length > 0) { parent.dj.messagerConfirm('请确认', '您要删除当前所选项目?', function(r) { if (r) { for ( var i = 0; i < rows.length; i++) { ids.push(rows[i].fruit_id); } $.ajax({ url : '__APP__/Goods/delete', data : { ids : ids.join(',') }, dataType : 'json', success : function(d) { datagrid.datagrid('load'); datagrid.datagrid('unselectAll'); parent.dj.messagerShow({ title : '提示', msg : d.info }); } }); } }); } else { parent.dj.messagerAlert('提示', '请勾选要删除的记录!', 'error'); } } function formatType(val,row,index){ var type = row.hotel_star; var typename = ''; switch(type){ case "kezhan": typename = '客栈公寓'; break; case "liansuo": typename = '经济连锁'; break; case "two": typename = '二星民宿'; break; case "three": typename = '三星舒适'; break; case "four": typename = '四星高档'; break; case "five": typename = '五星豪华'; break; } return typename; } function formatOper(val,row,index){ var optr = '<a href="javascript:void(0);" onclick="edit('+row.hotel_id+')">修改</a>'; optr +=' &nbsp;&nbsp;<a href="javascript:void(0);" onclick="view('+row.hotel_id+')">详情</a>'; return optr; } function view(id){ $.ajax({ url: '__APP__/Goods/getHotelsById', data: {id: id}, dataType: 'json', async:false, success: function (rows) { $('#_hotel_name').html(rows.hotel_name); $('#_hotel_star').html(rows.hotel_star); $('#_hotel_title').html(rows.hotel_title); $('#_hotel_email').html(rows.hotel_email); $('#_total_rooms').html(rows.total_rooms); $('#_hotel_telephone').html(rows.hotel_telephone); $('#_hotel_address').html(rows.hotel_address); $('#_introduction').html(rows.introduction); $('#_hotel_image').attr('src',rows.image_url); } }); var html = $('#viewDlg').clone(); $.dialog({ id:'test123', lock: true, content: html, width: 400, height: 250, title:'查看酒店详情', cancel: true }); } function addPanel(){ $.dialog({ id:'testadd', lock: true, //content: 'url:/admin.php/Goods/addpd', url: '__APP__/Goods/addpd', content: 'url:__APP__/Goods/addpd', width: 800, height: 350, title:"房间添加", cancel:function(){ window.location.reload(); } }); } function edit(id){ $.dialog({ id:'testedit', lock: true, //content: 'url:/admin.php/Goods/uppd/id/'+id, //url: '__APP__/Goods/uppd?id='+id, content: 'url: __APP__/Goods/uphotel?id='+id, width: 800, height: 350, title:"酒店编辑", cancel:function(){ window.location.reload(); } }); } function exportData() { } //搜索名称 function s_data() { $('#tab_data').datagrid('loadData', { total: 0, rows: [] }); $('#tab_data').datagrid('load', dj.serializeObject($('#searchForm'))); } </script> <body> <div class="easyui-layout" data-options="fit:true"> <table class="easyui-datagrid" id="tab_data" data-options="url:'__APP__/Goods/getAllHotels',method:'post',pagination:true,fit:true,toolbar:'#toolbar',rownumbers:true,checkOnSelect: true"> <thead> <tr> <th data-options="field:'hotel_id',checkbox: true">ID</th> <th data-options="field:'hotel_name',sortable: true" width="150">酒店名称</th> <th data-options="field:'hotel_star',align:'center',sortable: true,formatter:formatType" width="100">酒店星级</th> <th data-options="field:'hotel_title',align:'center',sortable: true" width="120">酒店主题</th> <th data-options="field:'total_rooms',align:'center',sortable: true" width="100">房间数量</th> <th data-options="field:'hotel_telephone',align:'center',sortable: true" width="150">酒店电话</th> <th data-options="field:'hotel_address',align:'center',sortable: true" width="150">酒店地址</th> <th data-options="field:'hotel_email',align:'center',sortable: true" width="130">酒店邮箱</th> <th data-options="field:'introduction',align:'center',sortable: true" width="150">酒店简介</th> <th data-options="field:'cz',width:80,align:'center',formatter:formatOper" width="100">操作</th> </tr> </thead> </table> <div id="toolbar" style="padding:5px;"> <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-print" plain="true" onclick="exportData()">导出CSV</a> <!-- <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cut" plain="true" onclick="deleteData()">删除</a>--> <form id="searchForm" style="display:inline-block;*display:inline;zoom:1;"> <input name="search" placeholder="名称" data-options="prompt:'请输入搜索内容',searcher:''" class="easyui-validatebox textbox" style="width: 180px; vertical-align: middle;" /> <input name="hiddenid" id="hiddenid" type="hidden" /> <a href="javascript:void(0);" class="easyui-linkbutton" plain="true" onclick="s_data();">搜索</a> </form> </div> <!-- 添水果详情 --> <div id="viewDlg" class="easyui-dialog" style="width: 600px; height: 500px; padding: 10px 20px"> <table border="0" style="height:500px;width:400px" align="center"> <tr> <td width="100" height="30" align="right">酒店名称: </td> <td width="300" height="30"><span id="_hotel_name"></span></td> </tr> <tr> <td width="100" height="30" align="right">酒店星级: </td> <td width="300" height="30"><span id="_hotel_star"></span></td> </tr> <tr> <td width="100" height="30" align="right">酒店主题: </td> <td width="300" height="30"><span id="_hotel_title"></span></td> </tr> <tr> <td width="100" height="30" align="right">房间数量: </td> <td width="300" height="30"><span id="_total_rooms"></span></td> </tr> <tr> <td width="100" height="30" align="right">酒店电话: </td> <td width="300" height="30"><span id="_hotel_telephone"></span></td> </tr> <tr> <td width="100" height="30" align="right">酒店地址: </td> <td width="300" height="30"><span id="_hotel_address"></span></td> </tr> <tr> <td width="100" height="30" align="right">酒店邮箱: </td> <td width="300" height="30"><span id="_hotel_email"></span></td> </tr> <tr> <td width="100" height="30" align="right">酒店简介:</td> <td width="300" height="30"><span id="_introduction"></span></td> </tr> <tr> <td align="right">图片:</td> <td><img name="" src="" width="300" height="230" alt="" id="_hotel_image"/></td> </tr> </table> </div> </div> <script type="text/javascript" src="__PUBLIC__/lhgdialog/lhgdialog.min.js"></script> </body> </html><file_sep><?php class AuserAction extends Action { public function auser() { $row = M('hotel_admin'); // $list = M('hotel_admin')->table('hotel_admin ha,hotels h')->field('ha.name han,ha.admin_telephone at,h.name hn')->select(); $list = $row->join('hotels ON hotels.id=hotel_admin.hotel_id')->field('hotel_admin.name han,hotel_admin.admin_telephone at,hotels.name hn,hotel_admin.admin_id aid')->select(); // var_dump($list); $this->assign('list',$list); $this->display(); } public function edit() { $id = $_GET['id']; // var_dump($id); // exit; $row = M('hotel_admin'); $what = "(hotel_admin.admin_id = ".$id.")"; $list = $row->join('hotels ON hotels.id=hotel_admin.hotel_id')->field('hotel_admin.name han,hotel_admin.admin_telephone at,hotels.name hn,hotel_admin.admin_id aid')->where($what)->find(); // var_dump($list); $this->assign('list',$list); $this->display(); } public function doedit() { // var_dump($_POST); // exit; if (IS_POST) { // var_dump($_SESSION); // exit; $bun['name'] = $_POST['hotelname']; if (!empty($_POST['pwd'])) { $id = $_POST['id']; $data['name'] = $_POST['name']; $data['password'] = md5($_POST['pwd']); $data['admin_telephone'] = $_POST['phone']; $row = M('hotel_admin')->where(array('admin_id'=>$id))->save($data); $one = M('hotel_admin')->where(array('admin_id'=>$id))->field('hotel_id')->find(); $result = M('hotels')->where(array('id'=>$one['hotel_id']))->save($bun); if ($row !== false && $result !== false) { $this->success('修改成功',U('Auser/auser')); }else{ $this->error('修改失败'); } }else{ $id = $_POST['id']; $data['name'] = $_POST['name']; $data['admin_telephone'] = $_POST['phone']; $row = M('hotel_admin')->where(array('admin_id'=>$id))->save($data); $one = M('hotel_admin')->where(array('admin_id'=>$id))->field('hotel_id')->find(); $result = M('hotels')->where(array('id'=>$one['hotel_id']))->save($bun); if ($row !== false && $result !== false) { $this->success('修改成功',U('Auser/auser')); }else{ $this->error('修改失败'); } } }else{ $this->redirect(U('Auser/auser')); } } public function del() { $id = $_GET['id']; $one = M('hotel_admin')->where(array('admin_id'=>$_SESSION['admin_id']))->field('hotel_id')->find(); $row = M('hotel_admin')->where(array('admin_id'=>$id))->delete(); $result = M('hotels')->where(array('id'=>$one['hotel_id']))->delete(); if ($row !== false && $row !== 0 && $result !== false && $row !==0) { $this->success('删除成功'); }else{ $this->error('删除失败'); } } public function doadd() { // var_dump($_POST); // exit; if (IS_POST) { foreach ($_POST as $val) { if (empty($val)) { $this->error('请完善信息'); exit; } } $one = M('hotel_admin')->where(array('name'=>$_POST['name']))->find(); if ($one) { $this->error('用户名已存在,请重新输入'); exit; } $data['name'] = $_POST['hotelname']; $list = M('hotels')->add($data);//把酒店名字上传,获得酒店id $bun['relate_id'] = $list; $bun['type'] = 'hotels'; $pun = M('display_pictures')->add($bun); $run['admin_telephone'] = $_POST['phone']; $run['password'] = md5($_POST['pwd']); $run['name'] = $_POST['name']; $run['hotel_id'] = $list; $run['credit'] = 0; $result = M('hotel_admin')->add($run); $bob['relate_id'] = $list; $bob['type'] = 'hotel'; $res = M('display_pictures')->add($bob); if ($result && $res) { $this->success('增加成功',U('Auser/auser')); }else{ $this->error('增加失败'); } }else{ $this->redirect(U('Auser/adduser')); } } public function username() { if (IS_AJAX) { $name = $_POST['name']; $list = M('hotel_admin')->where(array('name'=>$name))->find(); if ($list) { $this->ajaxReturn('1'); }else{ $this->ajaxReturn('0'); } }else{ $this->redirect('Auser/adduser'); } } // public function getAllUser() { // $n =D("Hotel_admin"); // //$n =new Model("Admin"); // import("ORG.Util.Page"); //导入分页类 // $page=$_POST["page"]? $_POST["page"] :1; // $rows=$_POST["rows"]? $_POST["rows"] :10; // $sort=$_POST["sort"]? $_POST["sort"] :'admin_id'; // $order=$_POST["order"] ? $_POST["order"] :'asc'; // $search=$_POST["search"]; // //dump($order); // if($search!=null&&$search!=""){ // $condition['hotel_admin.name']=array('like','%'.$search.'%'); // } // $count = $n->count(); //计算总数 // //$p = new Page($count,$rows);order($sort+','+$order)-> // $list = $n->join('Hotels h ON h.hotel_id = Hotel_admin.hotel_id')->where($condition)->page($page,$rows)->order(array($sort=>$order))->select(); // $result['total'] = $count; // $result['rows'] = $list; // exit(json_encode($result)); // } // public function getUserById(){ // $d = d("Hotel_admin"); // $condition['admin_id']=array('EQ',$_POST['id']); // $list = $d->where($condition)->find(); // exit(json_encode($list)); // } // //添加用户提交处理 // public function add() { // $m = D("Hotel_admin"); // $h = D("Hotels"); // //$_POST['image_url'] = rtrim($_POST['picture'],'|'); // //unset($_POST['picture']); // $cond['hotel_name'] = $_POST['hotel_name']; // //$cond['hotel_title'] = $_POST['hotel_title']; // $cond['tieba'] = $_POST['tieba']; // $cond['hotel_star'] = $_POST['hotel_star']; // //$cond['hotel_address'] = $_POST['hotel_address']; // //$cond['hotel_telephone'] = $_POST['admin_telephone']; // //$cond['introduction'] = $_POST['introduction']; // //$cond['total_rooms'] = $_POST['total_rooms']; // //$cond['hotel_email'] = $_POST['hotel_email']; // $cond['invalid'] = 1; // //$cond['image_url'] = $_POST['image_url']; // if(!$h->create($cond)) { // $this->ajaxReturn($_POST,$m->getError(),3); // }else{ // if($h->add()) { // $hotelId = $h->where($cond)->getField('hotel_id'); // $condition['hotel_id'] = $hotelId; // $condition['name'] = $_POST['name']; // $condition['password'] = $_POST['<PASSWORD>']; // $condition['admin_telephone'] = $_POST['admin_telephone']; // $condition['credit'] = 0; // if(!$m->create($condition)) { // $this->ajaxReturn($_POST,$m->getError(),3); // }else{ // if($m->add()) { // $this->ajaxReturn($_POST,'添加用户成功!',1); // }else{ // $this->ajaxReturn($m->getError(),'添加用户失败!',0); // } // } // }else{ // $this->ajaxReturn($m->getError(),'添加失败!',0); // } // } // } // // 更新数据 // public function edit(){ // //在ThinkPHP中使用save方法更新数据库,并且也支持连贯操作的使用 // $Form = D("Hotel_admin"); // if ($Form->create($_POST)) { // $list = $Form->save($_POST); // $this->ajaxReturn($_POST,'更新成功!',1); // } else { // $this->ajaxReturn($_POST,$Form->getError(),3); // } // } // // 删除数据 // public function delete() { // //在ThinkPHP中使用delete方法删除数据库中的记录。同样可以使用连贯操作进行删除操作。 // if (!empty ($_POST['ids'])) { // $d = M("Hotel_admin"); // $h = M("Hotels"); // $condition['admin_id']=array('in',$_POST['ids']); // //超级管理员禁止删除 // $result = $d->where($condition)->select(); // $HotelId = $d->where($condition)->getField('hotel_id'); // $data['invalid'] = 0; // $con['hotel_id'] = $HotelId; // $result = $d->where($condition)->delete(); // $res = $h->where($con)->data($data)->save(); // /* // delete方法可以用于删除单个或者多个数据,主要取决于删除条件,也就是where方法的参数, // 也可以用order和limit方法来限制要删除的个数,例如: // 删除所有状态为0的5 个用户数据 按照创建时间排序 // $Form->where('status=0')->order('create_time')->limit('5')->delete(); // 本列子没有where条件 传入的是主键值就行了 // */ // if (false !== $result && false !== $res) { // $this->ajaxReturn($_POST,'删除用户成功!',1); // } else { // $this->ajaxReturn($_POST,'删除出错!',1); // } // } else { // $this->ajaxReturn($_POST,'删除项不存在!',1); // } // //$this->redirect('index'); // } // public function uploadify(){ // //$targetPath = "/Public/upload/"; // $upload_dir= C('UPLOAD_DIR'); // //echo $_POST['token']; // $verifyToken = md5($_POST['timestamp']); // if (!empty($_FILES) && $_POST['token'] == $verifyToken) { // import("ORG.Net.UploadFile"); // $name=time().rand(); //设置上传图片的规则 // $upload = new UploadFile();// 实例化上传类 // $upload->maxSize = 3145728 ;// 设置附件上传大小 // $upload->allowExts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型 // //$upload->savePath = './Public/upload/';// 设置附件上传目录 // $upload->savePath ='.'.$upload_dir; // $upload->saveRule = $name; //设置上传图片的规则 // if(!$upload->upload()) {// 上传错误提示错误信息 // //return false; // echo $upload->getErrorMsg(); // //echo $targetPath; // }else{// 上传成功 获取上传文件信息 // $info = $upload->getUploadFileInfo(); // echo $upload_dir.$info[0]["savename"]; // } // } // } // // 更新数据 // public function editPwd(){ // echo "<script>alert('test');</script>"; // //在ThinkPHP中使用save方法更新数据库,并且也支持连贯操作的使用 // $Form = D("Hotel_admin"); // $user=M("Hotel_admin"); // $password=md5($_POST['password']); // $newpassword=md5($_POST['newpassword']); // $username=$_SESSION["username"]; // $condition['name']=$username; // $condition['password']=$<PASSWORD>; // $query=$user->where($condition)->find(); // //header("Content-type:text/html;charset=utf-8"); // if($query) // { // $admin_id = $user->where($condition)->getField('admin_id'); // $condition2['admin_id']=$admin_id; // $condition2['password']=$<PASSWORD>; // if ($vo = $Form->create()) { // $list = $Form->save($condition2); // //dump($_POST); // //未传入$data理由同上面的add方法 // /* 为了保证数据库的安全,避免出错更新整个数据表,如果没有任何更新条件,数据对象本身也不包含主键字段的话, // save方法不会更新任何数据库的记录。 // 因此下面的代码不会更改数据库的任何记录 // */ // //dump($list); // if ($list !== false) { // //注意save方法返回的是影响的记录数,如果save的信息和原某条记录相同的话,会返回0 // //所以判断数据是否更新成功必须使用 '$list!== false'这种方式来判断 // //$this->ajaxReturn($_POST,'修改密码成功!',1); // unset($_SESSION["username"]); // //$this->success('密码修改成功,请用新密码重新登录', '../../admin.php'); // echo "<script>alert('密码修改成功,请用新密码重新登录');top.location = '../../admin.php';</script>"; // } else { // //$this->error('密码修改失败'); // echo "<script>alert('密码修改失败');</script>"; // //$this->ajaxReturn($_POST,'没有更新任何数据!',0); // } // } else { // echo "<script>alert('密码修改失败');</script>"; // //$this->ajaxReturn($_POST,$Form->getError(),3); // //$this->error('密码修改失败'); // } // } // else // echo "<script>alert('原密码错误');</script>"; // //$this->ajaxReturn($_POST,'原密码错误',0); // //$this->error('原密码错误'); // } // public function queryCredit(){ // } } ?><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <script type="text/javascript" src="__PUBLIC__/js/bootstrap.js"></script> <script type="text/javascript" src="__PUBLIC__/js/jquery.js"></script> <script type="text/javascript" src="__PUBLIC__/js/jquery.min.js"></script> <link href="__PUBLIC__/css/store.css" rel="stylesheet" type="text/css" /> <title>Document</title> </head> <body> <div class="aaa"> <div class="fl"> <img src="<?php echo ($list["iname"]); ?>" alt=""> </div> <div class='ccc fr'> <ul style="list-style:none"> <h1><li><?php echo ($list["gname"]); ?></li></h1> <h3><li><?php echo ($list["msg"]); ?></li></h3> <h2><li style="color:#FF851B">抢购价:<?php echo ($list["price"]); ?></li></h2> </ul> <form action="<?php echo U('Store/cartdo');?>" method="get"> <input type="hidden" name="goods_id" value="<?php echo ($list["goods_id"]); ?>"> 数量: <button type="button" onclick="show()">-</button> <input type="text" id="count" value="1" name="qty" maxlength="3"> <button type="button" onclick="document.getElementById('count').value++">+</button> 库存:<?php echo ($list["stock"]); ?> <button type="submit" name="b" value="add">加入购物车</button> <button type="submit" name="b" value="buy">立即购买</button> </form> </div> </div> <script> function show(){ var getNum = parseInt(document.getElementById("count").value); if(getNum >1){ document.getElementById("count").value = getNum - 1; }else{ alert("至少一件哦"); } } </script> </body> </html><file_sep><?php // header('Content-Type: application/json'); // //header('Cache-Control: no-store'); // header('Access-Control-Allow-Origin:*'); // require_once 'C:\xampp\htdocs\hotel\Public\path_to_sdk\autoload.php'; // use Qiniu\Auth; // use Qiniu\Storage\UploadManager; class AdminstoreAction extends Action { public function category() { $pid = empty($_GET['pid'])?0:$_GET['pid']; $list = M('categroy')->where(array('pid'=>$pid))->select(); $row = M('categroy')->where(array('id'=>$pid))->find(); // var_dump($row); // var_dump($list); $this->assign('row',$row); $this->assign('list',$list); $this->display(); } public function addcatechrild() { // var_dump($_GET); $pid = $_GET['pid']; $path = $_GET['path'].$pid.','; $this->assign('pid',$pid); $this->assign('path',$path); $this->display(); } public function addchild() { if (IS_POST) { foreach ($_POST as $key => $val) { if (empty($val)) { $this->error('请完善信息'); exit; } } $data['cname'] = $_POST['cname']; $data['pid'] = $_POST['pid']; $data['path'] = $_POST['path']; $row = M('categroy')->add($data); if ($row) { $this->success('添加成功',U('Adminstore/category')); }else{ $this->error('添加失败'); } }else{ $this->redirect('Adminstore/addcatechrild'); } } public function editcate() { // var_dump($_GET); $id = $_GET['id']; $list = M('categroy')->where(array('id'=>$id))->find(); // var_dump($list); $this->assign('list',$list); $this->display(); } public function doeditcate() { // var_dump($_POST); if (IS_POST) { foreach ($_POST as $val) { if (empty($val)) { $this->error('请完善信息'); } } $id = $_POST['id']; $data['cname'] = $_POST['cname']; $row = M('categroy')->where(array('id'=>$id))->save($data); if ($row !== false) { $this->success('修改成功',U('Adminstore/category')); }else{ $this->error('修改失败'); } }else{ $this->redirect('Adminstore/editcate'); } } public function delcate() { // var_dump($_GET); $id = $_GET['id']; $pid = $_GET['pid']; $path = $_GET['path']; if ($pid !=0 && $path != '0,') { //子类的规律:自己的path拼接自己的id再加逗号 $cons = $path.$id.','; // $what['path'] = "(path like".$cons."%)"; $what['path'] = array('like',''.$cons.'%'); $row = M('categroy')->where($what)->select(); // var_dump($row); // echo M('categroy')->getLastSql(); if ($row) { $this->error('不能删除,该类下还有商品'); exit; } $result = M('categroy')->where(array('id'=>$id))->delete(); if ($result !== 0 && $result !== false) { $this->success('删除成功'); }else{ $this->error('删除失败'); } }else{ $this->error('顶级分类不可删除'); } } public function addcate() {//直接产生pid $pid = empty($_GET['pid'])?0:$_GET['pid']; //直接产生path //为空默认0,不为空就是传值,拼接pid和一个逗号 $path = empty($_GET['path'])?'0,':$_GET['path'].$pid.','; // var_dump($pid); // var_dump($path); $this->assign('pid',$pid); $this->assign('path',$path); $this->display(); } public function doaddcate() { // var_dump($_POST); // exit; if (IS_POST) { if (empty($_POST['cname'])) { $this->error('请输入分类名'); exit; } $data['pid'] = $_POST['pid']; $data['path'] = $_POST['path']; $data['cname'] = $_POST['cname']; $row = M('categroy')->add($data); if ($row) { $this->success('添加成功',U('Adminstore/category')); }else{ $this->error('添加失败'); } }else{ $this->redirect(U('Adminstore/addcate')); exit; } } public function goods() { $what = "(g.cate_id = c.id and g.id = i.goods_id)"; if (!empty($_REQUEST['chaxun'])) { if ($_REQUEST['chaxun'] == 1) { $what .= "and (g.gname like '%".$_REQUEST['find']."%')"; } } $list = M('goods')->field('g.id gid,g.gname,c.cname,g.price,g.stock,i.iname,g.msg')->table('categroy c,image i,goods g')->where($what)->select(); // var_dump($list); $this->assign('list',$list); $this->display(); } public function editgoods() { $id = $_GET['id']; $cate = M('categroy')->field('cname,id,path')->select(); $list = M('goods')->field('id,gname,cate_id,price,stock,msg')->where(array('id'=>$id))->find(); // var_dump($list); $this->assign('list',$list); $this->assign('cate',$cate); // var_dump($_GET); // $list = M('') $this->display(); } public function doeditgoods() { // var_dump($_POST); if (IS_POST) { foreach ($_POST as $val) { if (empty($val)) { $this->error('请完善信息'); exit; } } $data['id'] = $_POST['id']; $data['gname'] = $_POST['name']; $data['cate_id'] = $_POST['cate_id']; $data['price'] = $_POST['price']; $data['stock'] = $_POST['stock']; $data['msg'] = $_POST['msg']; $row = M('goods')->data($data)->save(); if ($row !== false) { $this->success('修改成功',U('Adminstore/goods')); }else{ $this->error('修改失败'); } }else{ $this->redirect('Adminstore/editgoods'); } } public function editimgs() { // var_dump($_GET); // exit; $id = $_GET['id']; $bucket = 'zlmimg'; //空间名称 这里修改,你七牛运空间名称 $accessKey = '<KEY>'; //密钥 $secretKey = '<KEY>';//密钥 $auth = new Auth($accessKey, $secretKey); $name=time().rand(); $policy = array ( 'callbackUrl' => 'http://admin.zlmhotel.com/goods.php', //修改数据库的页面,比如要把刚刚上传的写入你的数据库 'callbackBody' => '{"fname":"'.$name.'$(fname)","imgId":"'.$id.'"}', // 'callbackBody' => '{"fname":"'.$name.'","roomId":"'.$id.'"}', 'callbackBodyType'=>'application/json', //上传文件名 'saveKey' => "goodsimg/$name$(fname)" ); $token = $auth->uploadToken($bucket, null, 3600, $policy); $this->assign('uptoken',$token); $this->display(); } public function addgoods() { $list = M('categroy')->field('id,cname,path')->select(); // var_dump($list); $this->assign('cate',$list); $this->display(); } public function doaddgoods() { // var_dump($_POST); // exit; if (IS_POST) { foreach ($_POST as $val) { if (empty($val)) { $this->error('请完善信息'); exit; } } $data['gname'] = $_POST['name']; $data['cate_id'] = $_POST['cate_id']; $data['price'] = $_POST['price']; $data['stock'] = $_POST['stock']; $data['msg'] = $_POST['msg']; $row = M('goods')->add($data); if ($row) { $jack['iname']= '1'; $jack['goods_id'] = $row; $result = M('image')->add($jack); $this->success('添加成功',U('Adminstore/goods')); }else{ $this->error('添加失败'); } }else{ $this->redirect(U('Adminstore/addgoods')); } } public function goodsorder() { $what = "(og.order_id = go.id and og.goods_id = g.id and i.goods_id = g.id)"; if (!empty($_REQUEST['chaxun'])) { if ($_REQUEST['chaxun'] == 1) { $what .= "and (go.ordernum like '%".$_REQUEST['find']."%')"; } if ($_REQUEST['chaxun'] == 2) { $what .= "and (go.phone like '%".$_REQUEST['find']."%')"; } } $list = M('goodsorder')->field('i.iname,g.gname,go.lname,go.address,go.phone,go.allprice,og.price,og.qty,go.ordernum')->table('goodsorder go,image i,order_goods og,goods g')->where($what)->select(); // echo M('goodsorder')->getLastSql(); // var_dump($list); $this->assign('list',$list); $this->display(); } } ?><file_sep> //关闭 & 取消按钮 $('.closeButton').click(function(){ $('.pop').hide(); }); $('.cancel').click(function(){ $('.pop').hide(); }); //确认按钮 //$('.checkInSuccess').click(function(){ // alert('操作成功!'); // }); // ************ 交易所 *************** //确认购买弹窗 //$('.deal .buy').click(function(){ // $('.confirmBuy').show(); // }); //确认求购交易 $('.deal .tradeOperate').click(function(){ $('.confirmTrade').show(); }); //添加出售登记 $('.checkIn .addSale').click(function(){ $('.checkSalePop').show(); }); //添加求购登记 $('.checkIn .addAskBuy').click(function(){ $('.checkBuyPop').show(); }); //确认回收登记弹窗 $('.recycle').click(function(){ $('.confirmRecycle').show(); }); //确认删除求购信息弹窗 $('.delete').click(function(){ $('.confirmDelete').show(); }); //登记弹窗中的米币分类选中效果 $('.classify li').click(function(){ $(this).siblings().each(function(index,element){ $(this).removeClass('on'); }); $(this).addClass('on'); }); //左侧导航(出售&求购) //$('.deal .leftNav li').click(function(){ // $(this).siblings().each(function(index,element){ // $(this).removeClass('on'); // }); // $(this).addClass('on'); // }); // ************我的账户*************** //拆分确认窗口 $('.addSplit').click(function(){ $('.addSplitPop').show(); }); $('.rechargeWay ul li').click(function(){ $(this).siblings().each(function(index,element){ $(this).removeClass('on'); }); $(this).addClass('on'); }); // *************** 安全中心 *************** //安全指数颜色条 $(function(){ var num=$('.safetyIndex .on').length; if(num==2){ $('.safetyIndex li').eq(0).css('background-color','#fec346'); $('.safetyIndex li').eq(1).css('background-color','#fec346'); $('#safetyText').text('中'); }else if(num==3){ $('.safetyIndex li').css('background-color','#77b527'); $('#safetyText').text('高'); }else{ $('.safetyIndex li').eq(0).css('background-color','#e00101'); $('#safetyText').text('低'); } }); //默认地址 $('.defaultAddress').click(function(){ $('.defaultAddress').each(function(index,element){ $(this).removeClass('active'); $(this).html('设为默认地址'); }); $(this).addClass('active'); $(this).html('默认地址'); }); //添加银行卡窗口 $('.addBankCard').click(function(){ $('.addBankCardPop').show(); }); //添加地址窗口 $('.addNewAddress').click(function(){ $('.addAddressPop').show(); }); <file_sep><?php return array( //'配置项'=>'配置值' 'OUTPUT_ENCODE' => false, 'APP_DEBUG' => false, // 开启调试模式 'DB_TYPE'=> 'mysql', // 数据库类型 'DB_HOST'=> 'localhost', // 数据库服务器地址 'DB_NAME'=>'hotel', // 数据库名称 'DB_USER'=>'root', // 数据库用户名 'DB_PWD'=>'', // 数据库密码 'DB_PORT'=>'3306', // 数据库端口 'DB_PREFIX'=>'', // 数据表前缀 //酒店 // 'DB_TYPE'=>'mysql', // 数据库类型 // 'DB_HOST'=>'192.168.127.12', // 数据库服务器地址 // 'DB_NAME'=>'zjuhotel', // 数据库名称 // 'DB_USER'=>'zjuhotel', // 数据库用户名 // 'DB_PWD'=>'<PASSWORD>', // 数据库密码 // 'DB_PORT'=>'3306', // 数据库端口 // 'DB_PREFIX'=>'', // 数据表前缀 // 'DB_CHARSET'=>'utf8', 'DB_CHARSET'=>'utf8', 'SESSION_AUTO_START' =>true, //图片上传路径 'UPLOAD_DIR'=>'/Public/upload/', 'ROOM_UPLOAD_DIR'=>'./laravel/public/uploads/image/', //监听时间间隔10s 'DT_TIME_COUNT'=>'10000',//默认10s 这个单位是ms //监听消息提示n次后刷新订单页面 'DT_REFRESH_COUNT'=>'5',//默认是5次 ) ?> <file_sep><?php if (!defined('THINK_PATH')) exit();?><html> <head> <title>积分充值</title> </head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link id="easyuiTheme" rel="stylesheet" type="text/css" href="__PUBLIC__/themes/bootstrap/easyui.css" /> <link rel="stylesheet" type="text/css" href="__PUBLIC__/themes/icon.css" /> <script type="text/javascript" src="__PUBLIC__/js/jquery-1.8.0.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/jquery.easyui.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/admin.js" charset="utf-8"></script> <body> <table width="400" height="20" align="center"> <tr align="center" valign="middle"> <c:if test="${sessionInfo.credit != null}">金币余额:<strong><?php echo ($_SESSION['credit']); ?></strong>个</c:if> </tr> </table> <form action="/pay/example/native.php" method="post" onsubmit="check()"> <input name="score" id="score" placeholder="充值金额" data-options="prompt:'请输入充值金额'" class="easyui-validatebox textbox" style="width: 180px; vertical-align: middle;" type="number" min ="0" required missingmessage="金额不能为空"/>元(1元=2金币,充值1000元起) <input type="submit" class="loginbtn" value="充值" /> </form> <form action="" method="post"> <input name="dscore" id="score" placeholder="提现金额" data-options="prompt:'请输入提现金额'" class="easyui-validatebox textbox" style="width: 180px; vertical-align: middle;" type="number" min ="0" required missingmessage="金额不能为空"/>元(1元=2金币,提现1000元起) <input type="submit" class="loginbtn" value="提现" /> </form> <script type="text/javascript"> function check(){ // var num = document.getElementById("score").value; var num = $('#score').val(); if(num <1000){ alert("充值至少1000元起!"); return false; }else{ return true; } } </script> </body> </html><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <h1>订单</h1> <div > <form action="<?php echo U('Adminstore/goodsorder');?>" method="get"> <div style="float:left"> <select name="chaxun" id=""> <option value="1">订单号</option> <option value="2">电话</option> </select> </div> <div style="float:left"> <input type="text" name="find" > </div> <div> <input type="submit" value="搜索"> </div> </form> </div> <!-- <h1>订单</h1> --> <?php if(is_array($list)): $i = 0; $__LIST__ = $list;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$vo): $mod = ($i % 2 );++$i;?><br><br> <table border="1" cellpadding="1" cellspacing="1" width="100%" align="center"> <span>订单号: <?php echo ($vo["ordernum"]); ?>&nbsp;总价:<?php echo ($vo["allprice"]); ?>&nbsp;订单状态:</span> <tr> <th>商品图片</th> <th>商品名</th> <th>收货人</th> <th>收货地址</th> <th>电话</th> <th>数量</th> <th>价格</th> <th>合计</th> <th>修改订单状态</th> </tr> <tr> <td><?php echo ($vo["iname"]); ?></td> <td><?php echo ($vo["gname"]); ?></td> <td><?php echo ($vo["lname"]); ?></td> <td><?php echo ($vo["address"]); ?></td> <td><?php echo ($vo["phone"]); ?></td> <td><?php echo ($vo["qty"]); ?></td> <td><?php echo ($vo["price"]); ?></td> <td><?php echo ($vo["allprice"]); ?></td> <td><button>发货</button> <button>强制收货</button> <button>撤销订单</button> </td> </tr> </table><?php endforeach; endif; else: echo "" ;endif; ?> </body> </html><file_sep><?php // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: LunnLew <<EMAIL>> 20130802 // +---------------------------------------------------------------------- // | Docs:http://docs.qiniu.com/api/v6/audio-video-hls-process.html /** * 媒体资源类 */ class QiniuAudioVisualSDK extends QiniuSDK{ /** * 申请应用时分配的app_key * @param string */ protected $AppKey = ''; /** * 申请应用时分配的 app_secret * @param string */ protected $AppSecret = ''; /** * API根路径 * @param string */ protected $ApiBase = ''; //上传下载域 public $DownDomain; public $Map; //应用参数 public $HLS; //媒体格式 public $Format; //静态码率 public $BitRate; //动态码率 public $AudioQuality; //音频采样频率 public $SamplingRate; //视频帧率 public $FrameRate; //视频比特率 public $VideoBitRate; //视频编码方案 public $Vcodec; //音频编码方案 public $Acodec; //取视频的第几秒 public $Offset; //缩略图宽度 public $Width; //缩略图高度 public $Height; //预设集 public $Preset; public function __construct($params=''){ parent::__construct(); } /** * 设置请求参数 * @param array $params 请求参数数组 */ public function setRequestParams($params){ foreach ($params as $key => $value) { if(array_key_exists($key, $this->Map)){ $this->Map[$key] = $value; }else{ $this->$key = $value; } } } /** * 生成请求 * @param string $url 请求地址 * @param strng $type 请求类型 */ public function MakeRequest($url,$type='avthumb',$params=''){ if($params!=''){ self::setRequestParams($params); } $func = '_make_'.$type.'_Request'; return self::$func($url); } protected function _make_avthumb_Request($url){ if (!empty($this->Format)) { $ops[] = $this->Format; } //HLS自定义 if (!empty($this->HLS)) { $ops[] = 'm3u8/segtime'; //HLS自定义必须 if (!empty($this->SegSeconds)) { $ops[] = $this->SegSeconds; } //HLS预设必须 if (!empty($this->Preset)) { $ops[] = 'preset/'.$this->Preset; } } //视频 if (!empty($this->FrameRate)) { $ops[] = 'r/' . $this->FrameRate; } if (!empty($this->VideoBitRate)) { $ops[] = 'vb/' . $this->VideoBitRate; } if (!empty($this->Vcodec)) { $ops[] = 'vcodec/' . $this->Vcodec; } if (!empty($this->Acodec)) { $ops[] = 'acodec/' . $this->Acodec; } /// if (!empty($this->BitRate)) { $ops[] = 'ab/' . $this->BitRate; } if (!empty($this->AudioQuality)) { $ops[] = 'aq/' . $this->AudioQuality; } if (!empty($this->AudioQuality)) { $ops[] = 'ar/' . $this->SamplingRate; } return $url . "?avthumb/". implode('/', $ops); } protected function _make_vframe_Request($url){ if (!empty($this->Format)) { $ops[] = $this->Format; } if (!empty($this->Offset)) { $ops[] = 'offset/' . $this->Offset; } if (!empty($this->Width)) { $ops[] = 'w/' . $this->Width; } if (!empty($this->Height)) { $ops[] = 'h/' . $this->Height; } return $url . "?vframe/". implode('/', $ops); } } ?><file_sep><?php // ±¾ÀàÓÉϵͳ×Ô¶¯Éú³É£¬½ö¹©²âÊÔÓÃ; class CreditAction extends Action { public function index() { // var_dump($_SESSION); $this->display(); } public function query() { // var_dump($_SESSION); // $list =M('hotel_admin') // ->join('hotels ON hotel_admin.hotel_id = hotels.id') // ->where(array('admin_id'=>$_SESSION['admin_id'])) // ->field('hotels.name')->select(); // var_dump($list); // $row =M('hotel_admin') // ->join('orders ON orders.hotel_id = hotel_admin.hotel_id') // ->where(array('admin_id'=>$_SESSION['admin_id'])) // ->field('count(*) as total')->group("orders.hotel_id")->select(); // var_dump($row); // $result = M('hotel_admin') // ->join('score ON score.hotelId = hotel_admin.hotel_id') // ->where(array('admin_id'=>$_SESSION['admin_id'])) // ->field('sum(score_num)')->select(); // var_dump($result); $one = M('hotel_admin')->field('hotel_id')->where(array('admin_id'=>$_SESSION['admin_id']))->select(); // var_dump($one); $two=[]; foreach ($one as $key => $value) { $two[] = $value['hotel_id']; } $a = []; foreach ($two as $val) { $b = []; $list =M('hotels') ->where(array('id'=>$val)) ->field('hotels.name')->select(); $row = M('orders')->field('count(*) as total')->where(array('hotel_id'=>$val))->select(); $result = M('score')->field('sum(score_num) as allscore')->where(array('hotelId'=>$val))->select(); $b['name'] = $list[0]['name']; $b['total'] = $row[0]['total']; $b['allscore'] =$result[0]['allscore']; $a[] = $b; } $this->assign('list',$a); $this->display(); } public function aindex() { $this->display(); } public function aquery() { // var_dump($_SESSION); $one = M('hotel_admin')->field('hotel_id')->select(); // var_dump($one); $two=[]; foreach ($one as $key => $value) { $two[] = $value['hotel_id']; } $a = []; foreach ($two as $val) { $b = []; $list =M('hotels') ->where(array('id'=>$val)) ->field('hotels.name')->select(); $row = M('orders')->field('count(*) as total')->where(array('hotel_id'=>$val))->select(); $result = M('score')->field('sum(score_num) as allscore')->where(array('hotelId'=>$val))->select(); $b['name'] = $list[0]['name']; $b['total'] = $row[0]['total']; $b['allscore'] =$result[0]['allscore']; $a[] = $b; } $this->assign('list',$a); $this->display(); } // $model->field('count(*) as total,hotel_id')->where()->group('hotel_id')->select(); // public function getScore(){ // var_dump($_SESSION); // $s = D("Score"); // import("ORG.Util.Page"); //µ¼Èë·ÖÒ³Àà // $page=$_POST["page"]? $_POST["page"] :1; // $rows=$_POST["rows"]? $_POST["rows"] :10; // $admin_id = $_SESSION["admin_id"]; // $con['admin_id'] = $admin_id; // $count = $s->count(); // $list = $s->field('hotel_name,count(*) as order_number,sum(score_num) as total_score')->join('hotels ON score.contributor = hotels.hotel_id')->where($con)->group('contributor')->select(); // $result['total'] = $count; // $result['rows'] = $list; // exit(json_encode($result)); // } } ?><file_sep><?php class GoodsAction extends Action { public function index() { // var_dump($_SESSION); $list = M('rooms')->select(); // var_dump($list); $this->assign('list',$list); $this->display('goods'); } /*public function getAllGoods() { $n =D("rooms"); $u = D("Hotel_admin"); import("ORG.Util.Page"); //导入分页类 $page=$_POST["page"]? $_POST["page"] :1; $rows=$_POST["rows"]? $_POST["rows"] :30; $sort=$_POST["sort"]? $_POST["sort"] :'type_id'; $order=$_POST["order"] ? $_POST["order"] :'asc'; $search=$_POST["search"]; $username=$_SESSION["username"]; $con['name'] = $username; //$admin_id = $_SESSION["admin_id"]; //$con['admin_id'] = $admin_id; if($_SESSION["permission"] == 0){ $HotelId = $u->where($con)->getField('Hotel_id'); // var_dump($HotelId); $condition['hotel_id'] = $HotelId; } //dump($order); if($search!=null&&$search!=""){ $condition['type_name']=array('like','%'.$search.'%'); //$condition['description']=array('like','%'.$search.'%'); //$condition['type']=array('like','%'.$this->getType($search).'%'); //$condition['_logic']='OR'; } $count = $n->where($condition)->select(); //计算总数 $list = $n->where($condition)->page($page,$rows)->order(array($sort=>$order))->select(); //$list = $n->relation(true)->where($condition)->page($page,$rows)->order(array($sort=>$order))->select(); //$list = $n->where($condition)->page(1,30)->order(array('type_id'=>'asc'))->select(); //$list = $n->where($condition)->page(1,30)->order(array('type_id'=>'asc'))->select(); $result['total'] = $count; $result['rows'] = $list; exit(json_encode($result)); }*/ public function getGoodsById() { $d = D("rooms"); $condition['hotel_id']=array('EQ',$_POST['id']); $list = $d->where($condition)->find(); exit(json_encode($list)); //输出json数据 } public function uploadify(){ //$targetPath = "/Public/upload/"; $upload_dir= C('ROOM_UPLOAD_DIR'); //echo $_POST['token']; $verifyToken = md5($_POST['timestamp']); if (!empty($_FILES) && $_POST['token'] == $verifyToken) { import("ORG.Net.UploadFile"); $name=time().rand(); //设置上传图片的规则 $upload = new UploadFile();// 实例化上传类 $upload->maxSize = 3145728 ;// 设置附件上传大小 $upload->allowExts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型 //$upload->savePath = './Public/upload/';// 设置附件上传目录 $upload->savePath ='.'.$upload_dir; $upload->saveRule = $name; //设置上传图片的规则 $upload->thumb = true; $upload->thumbMaxWidth = '300'; $upload->thumbMaxHeight = '200'; $upload->thumbRemoveOrigin = true; if(!$upload->upload()) {// 上传错误提示错误信息 //return false; echo $upload->getErrorMsg(); //echo $targetPath; }else{// 上传成功 获取上传文件信息 $info = $upload->getUploadFileInfo(); echo $upload_dir.$info[0]["savename"]; } } } public function addpd(){ $this->time = time(); $this->pid = $_REQUEST['pid']; $this->display(); } public function add() { $m = D("rooms"); $u = D("Hotel_admin"); $_POST['image_url'] = rtrim($_POST['picture'],'|'); unset($_POST['picture']); $username=$_SESSION["username"]; $con['name'] = $username; //$con['admin_id'] = $admin_id; //$_POST['HotelId'] = $HotelId; $HotelId = $u->where($con)->getField('Hotel_id'); //$admin_id = $_SESSION["admin_id"]; $image_url = substr($_POST['image_url'],37); if($image_url!=null&&$image_url!=""){ $m->image_url = "thumb_".$image_url; } $m->hotel_id = $HotelId; $m->name = $_POST['type_name'];//房型英文名 $m->display_name = $_POST['bed_type'];//大床房 $m->area = $_POST['room_area'];//房间大小面积 $m->price = $_POST['room_price'];//单间价格 $m->count_num = $_POST['room_count'];//房间数量 $m->bed_add_price = $_POST['addprice'];//加床价格 // $m->room_type = $_POST['room_type']; $m->breakfast = $_POST['breakfast'];//是否有早餐 $m->internet = $_POST['internet'];//网络情况 $m->people_num = $_POST['person'];//可住人数 $result = $m->add(); if($result) { $this->ajaxReturn($_POST,'添加房间成功!',1); }else{ $this->ajaxReturn($m->getError(),'添加房间失败!',0); } // $vo = $m->create($_POST); // if(!$vo) { // $this->ajaxReturn($_POST,$m->getError(),3); // }else{ // echo "<script>alert('success4');</script>"; // $result = $m->add(); // echo "<script>alert($result);</script>"; // if($result) { // echo "<script>alert('success');</script>"; // $this->ajaxReturn($_POST,'添加房间成功!',1); // }else{ // echo "<script>alert('fail');</script>"; // $this->ajaxReturn($m->getError(),'添加房间失败!',0); // } // } } // 更新数据 public function edit(){ //在ThinkPHP中使用save方法更新数据库,并且也支持连贯操作的使用 $Form = D("rooms"); $img_url = rtrim($_POST['picture'],'|'); $image_url = substr($img_url,37); if($image_url!=null&&$image_url!=""){ $_POST['image_url'] = "thumb_".$image_url; } unset($_POST['picture']); $vo = $Form->create($_POST); if ($vo) { $list = $Form->save($vo); $this->ajaxReturn($_POST,'更新成功!',1); } else { $this->ajaxReturn($_POST,$Form->getError(),3); } } // 删除数据 public function delete() { //在ThinkPHP中使用delete方法删除数据库中的记录。同样可以使用连贯操作进行删除操作。 if (!empty ($_POST['ids'])) { $d = M("Fruit"); $i = M("Item"); $o = M("Order"); $condition['fruit_id']=array('in',$_POST['ids']); //item删除 $data['on_flag'] = 0; $result = $d->where($condition)->data($data)->save(); /* $i->where($condition)->delete(); $result = $d->where($condition)->delete(); */ /* delete方法可以用于删除单个或者多个数据,主要取决于删除条件,也就是where方法的参数, 也可以用order和limit方法来限制要删除的个数,例如: 删除所有状态为0的5 个用户数据 按照创建时间排序 $Form->where('status=0')->order('create_time')->limit('5')->delete(); 本列子没有where条件 传入的是主键值就行了 */ if (false !== $result) { $this->ajaxReturn($_POST,'删除房间成功!',1); } else { $this->ajaxReturn($_POST,'删除出错!',1); } } else { $this->ajaxReturn($_POST,'删除项不存在!',1); } //$this->redirect('index'); } //添加修改页面 public function uppd(){ $id = $_GET['id']; $d = D("rooms"); // $con['id'] = $id; // $this->list = $d->where($con)->find(); $list = M('rooms')->where(array('id'=>$id))->find(); // var_dump($list); $this->assign('list',$list); $this->assign('time',time()); $this->display(); } // 导出csv public function getAllHotels(){ $h = D("Hotels"); $u = D("Hotel_admin"); import("ORG.Util.Page"); $page=$_POST["page"]? $_POST["page"] :1; $rows=$_POST["rows"]? $_POST["rows"] :30; $sort=$_POST["sort"]? $_POST["sort"] :'hotel_id'; $order=$_POST["order"] ? $_POST["order"] :'asc'; $search=$_POST["search"]; $username=$_SESSION["username"]; $con['name'] = $username; //$admin_id = $_SESSION["admin_id"]; //$con['admin_id'] = $admin_id; if($_SESSION["permission"] == 0){ $HotelId = $u->where($con)->getField('hotel_id'); $condition['hotel_id'] = $HotelId; } if($search!=null&&$search!=""){ $condition['hotel_name']=array('like','%'.$search.'%'); } $count = $h->where($condition)->select(); //计算总数 $list = $h->where($condition)->page($page,$rows)->order(array($sort=>$order))->select(); $result['total'] = $count; $result['rows'] = $list; exit(json_encode($result)); } public function getHotelsById() { $h = D("Hotels"); $condition['id']=array('EQ',$_POST['id']); $list = $h->where($condition)->find(); exit(json_encode($list)); //输出json数据 } public function uphotel(){ $id = $_GET['id']; $h = D("Hotels"); $con['id'] = $id; $this->list = $h->where($con)->find(); // $row = M('hotels')->where(array('id'=>1))->find(); // var_dump($row); $this->assign('time',time()); $this->display(); } public function doadd() { // var_dump($_POST); $id = $_POST['hotel_id']; $data['name'] = $_POST['hotel_name']; $data['grade'] = $_POST['hotel_star']; // $hotel_title = $_POST['hotel_title']; // $total_rooms = $_POST['total_rooms']; $data['telephone'] = $_POST['hotel_telephone']; $data['address'] = $_POST['hotel_address']; $data['email'] = $_POST['hotel_email']; $data['introduction'] = $_POST['introduction']; $row = M('hotels')->where(array('id'=>$id))->save(); } public function edithotel(){ //在ThinkPHP中使用save方法更新数据库,并且也支持连贯操作的使用 $Form = D("Hotels"); $img_url = rtrim($_POST['picture'],'|'); $image_url = substr($img_url,37); if($image_url!=null&&$image_url!=""){ $_POST['image_url'] = "thumb_".$image_url; } unset($_POST['picture']); $vo = $Form->create($_POST); if ($vo) { $list = $Form->save($vo); $this->ajaxReturn($_POST,'更新成功!',1); } else { $this->ajaxReturn($_POST,$Form->getError(),3); } } public function export() { // $d = D("Fruit"); // $str = $_GET['idstr']; // if(empty($str)){ // $list = $d->select(); // }else{ // $ids = explode(',', $str); // $condition['fruit_id']=array('in',$ids); // $list = $d->where($condition)->select(); // } // $datastr = '水果名称,类目,售价,市场价,进货价,单位,库存,卖出数量,点赞数,推荐数,描述'; // $datastr = mb_convert_encoding($datastr,'gbk','utf-8'); // $datastr.="\n"; // if($list){ // foreach($list as $fruit){ // $name = mb_convert_encoding($fruit['fruit_name'],'gbk','utf-8'); // $typename = $this->getTypename($fruit['type']); // $typename = mb_convert_encoding($typename,'gbk','utf-8'); // $unit = $fruit['unit']; // $unit = mb_convert_encoding($unit,'gbk','utf-8'); // $desc = mb_convert_encoding($fruit['description'],'gbk','utf-8'); // $datastr .= $name.",".$typename.",".$fruit['price']."," // .$fruit['market_price'].",".$fruit['purchase_price'].",".$unit.','.$fruit['stock']."," // .$fruit['sold_num'].','.$fruit['praise'].','.$fruit['recommend'] // .','.$desc."\n"; // } // } // ob_clean(); // //$datastr = @iconv("UTF-8", "GBK//IGNORE", $datastr); // //$datastr = @iconv("GBK", "UTF-8//IGNORE", $datastr); // //$datastr = mb_convert_encoding($datastr,'gbk','utf-8'); // //var_dump($list); // $filename = date("Ymd",time()).".csv"; // header("Content-Type: application/vnd.ms-excel; charset=gbk"); // //header("Content-type:text/csv"); // header("Content-Disposition:attachment;filename=".$filename); // header('Cache-Control:must-revalidate,post-check=0,pre-check=0'); // header('Expires:0'); // header('Pragma:public'); // echo $datastr; } public function getTypename($type){ $typename = ''; switch($type){ case "jinritehui": $typename = '特惠水果'; break; case "jinkoushuiguo": $typename = '进口水果'; break; case "shiyanshitaocan": $typename = '实验室套餐'; break; case "gerentaocan": $typename = '个人套餐'; break; case "zhengxiangpifa": $typename = '整箱批发'; break; case "yinliaoguozhi": $typename = '饮料果汁'; break; case "lingshi": $typename = '零食'; break; case "qita": $typename = '其他'; break; } return $typename; } public function getType($typename){ $type = ''; switch($typename){ case "特惠水果": $type = 'jinritehui'; break; case "进口水果": $type = 'jinkoushuiguo'; break; case "实验室套餐": $type = 'shiyanshitaocan'; break; case "个人套餐": $type = 'gerentaocan'; break; case "整箱批发": $type = 'zhengxiangpifa'; break; case "饮料果汁": $type = 'yinliaoguozhi'; break; case "零食": $type = 'lingshi'; break; case "其他": $type = 'qita'; break; } return $type; } public function hotelinfo() { $this->display(); } } ?><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="description" content="Tsys管理系统"> <title>后台管理</title> <link id="easyuiTheme" rel="stylesheet" type="text/css" href="__PUBLIC__/themes/bootstrap/easyui.css"> <link rel="stylesheet" type="text/css" href="__PUBLIC__/themes/icon.css"> <script type="text/javascript" src="__PUBLIC__/js/jquery-1.8.0.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/jquery.easyui.min.js"></script> <script type="text/javascript" src="__PUBLIC__/js/admin.js" charset="utf-8"></script> </head> <!-- <link rel="stylesheet" type="text/css" href="__PUBLIC__/uploadify/uploadify.css" /> --> <!-- <link rel="stylesheet" type="text/css" href="__PUBLIC__/css/iframe.css" /> --> <!-- <link rel="stylesheet" type="text/css" href="__PUBLIC__/css/reset.css" /> --> <script src="__PUBLIC__/uploadify/jquery.uploadify.min.js" type="text/javascript"></script> <!-- <script src="//hm.baidu.com/hm.js?4b889ea3d1a9c076184ed8da84e5d719" ></script> --> <script src="__PUBLIC__/layer/layer.js" type="text/javascript"></script> <!-- <script src="__PUBLIC__/js/ajaxfileupload.js" type="text/javascript"></script> --> <!-- <script> var _hmt = _hmt || []; (function() { var hm = document.createElement("script"); hm.src = "//hm.baidu.com/hm.js?4b889ea3d1a9c076184ed8da84e5d719"; var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(hm, s); })(); </script> --> <body> <!-- <div class="easyui-panel" fit="true"> --> <!-- <form action="<?php echo U('Goods/uploadify');?>" id="editForm" method="post" enctype="multipart/form-data" onsubmit="return check()"> <input name="type_id" type="hidden" value="<?php echo ($list["id"]); ?>"/> <table width="780" border="0"> <tr style="height: 50px;"> <td align="right"> 修改: </td> <td> <input id="picture" name="img" type="file"> <div id="up_image" class="image"> </div> </td> </tr> </table> <div style="text-align:left;padding:20px;"> <input type="submit" value="修改"> </div> </form> --> <form method="post" action="http://up.qiniu.com" enctype="multipart/form-data" class="upfile" onsubmit="return check()"> <input name="token" type="hidden" value="<?php echo ($uptoken); ?>"> <input name="file" type="file" id="uploadPic"/> <input type="submit" name="修改" id="btn"> </form> <!-- <form class="fileForm picUpload" method="post" action="http://up.qiniu.com" enctype="multipart/form-data" class="upfile" onsubmit="return check()"> <input name="token" type="hidden" value="<?php echo ($uptoken); ?>"> <input name="file" type="file" id="uploadPic"/> <label id="fileBtn" for="uploadPic"> + <img class="showPic" src="" /> </label> <span class="tip"> 请上传图片,大小在2M以内<br/> (图片类型可为jpg,jepg,png,gif,bmp)<br/> 推荐图片比例为640*400 </span> <input type="submit" name="修改"> </form> --> <!-- <form class="fileForm picUpload" action="http://up.qiniu.com" enctype="multipart/form-data" method="post"> <input name="token" type="hidden" value="<?php echo ($uptoken); ?>"> <input id="uploadPic" name="file" type="file"> <label id="fileBtn" for="uploadPic"> + <img class="showPic" src="" /> </label> <span class="tip"> 请上传图片,大小在2M以内<br/> (图片类型可为jpg,jepg,png,gif,bmp)<br/> 推荐图片比例为640*400 </span> --> <!-- <input class="turnUrl" name="turnUrl" style="display:none" type="text"> --> <!-- <input value="submit" style="display:none" type="submit"> --> <!-- </form> --> <!-- <canvas id="uploadImg" style="display:none"></canvas> --> <!-- </div> --> <script type="text/javascript"> function check() { if ($('#uploadPic').val() == '') { layer.msg('请上传图片'); setTimeout(function(){ $('#uploadPic').focus(); }); return false; } var file = $("#uploadPic")[0].files[0]; if(file.size>4194304){ alert("上传图片请小于4M"); return false; }else if (!/image\/\w+/.test(file.type)) { alert("文件必须为图片!"); return false; } } // $("#uploadPic").on('change', function(event) { // var file = $(this)[0].files[0]; // if(file.size>4194304){ // alert("上传图片请小于4M"); // history.back(-1) // return false; // }else if (!/image\/\w+/.test(file.type)) { // alert("文件必须为图片!"); // window.location.reload(); // return false; // } // }); // function createCanvas(src) { // var canvas = document.getElementById("uploadImg"); // var cxt = canvas.getContext('2d'); // canvas.width = 640; // canvas.height = 400; // var img = new Image(); // img.src = src; // img.onload = function() { // // var w=img.width; // // var h=img.height; // // canvas.width= w; // // canvas.height=h; // cxt.drawImage(img, 0, 0,640,400); // //cxt.drawImage(img, 0, 0); // $(".showPic").show().attr('src', canvas.toDataURL("image/jpeg", 0.9)); // $.ajax({ // url: "/front/uploadByBase64.do", // type: "POST", // data: { // "imgStr": canvas.toDataURL("image/jpeg", 0.9).split(',')[1] // }, // success: function(data) { // console.log(data); // $(".showPic").show().attr('data-url',"/"+ data.url); // } // }); // } // } //上传图片 // $(document).on('change','#upfile',function(){ // $.ajaxFileUpload({ // url:'<?php echo U("Goods/ImgUpload");?>', // secureuri:false, // fileElementId:'upfile', // dataType: 'json', // type:'post', // data: { fileElementId: 'upfile'}, // success: function (data) { // $('#showimg').attr('src',data.upfile.url); // $('#imageurl').val(data.upfile.url); // }         // }) // }) </script> <!-- <script type="text/javascript" src="__PUBLIC__/lhgdialog/lhgdialog.min.js"></script> --> </body><file_sep>jQuery(function () { /** * 文件上传jQuery插件 * @returns {undefined} * @author zoujingli <<EMAIL>> */ jQuery.fn.upload = function (option) { /* 变量初始化 */ option = option || {}; var $self = jQuery(this); /* 事件触发按钮ID */ option.id = option.id || $self.attr('id') || '_' + parseInt(Math.random() * 10000); $self.attr('id', option.id); /* 返回值接收ID */ option.name = option.name || $self.data('name') || 'upload'; $self.data('name', option.name); /** * 初始化参数 * @type type */ var _default = { multi_selection: true, //是否启用多文件上传 runtimes: 'html5,flash,html4', //上传模式,依次退化 browse_button: option.id, //上传选择的点选按钮,**必需** uptoken_url: '{:U("Goods/uptoken")}', //Ajax请求upToken的Url,**强烈建议设置**(服务端提供) // downtoken_url: '/downtoken', // Ajax请求downToken的Url,私有空间时使用,JS-SDK将向该地址POST文件的key和domain,服务端返回的JSON必须包含`url`字段,`url`值为该文件的下载地址 unique_names: false, // 默认 false,key为文件名。若开启该选项,SDK会为每个文件自动生成key(文件名) save_key: false, // 默认 false。若在服务端生成uptoken的上传策略中指定了 `sava_key`,则开启,SDK在前端将不对key进行任何处理 domain: 'http://zlmimg.qiniudn.com/', //bucket 域名,下载资源时用到,**必需** container: 'container', //上传区域DOM ID,默认是browser_button的父元素, max_file_size: '500mb', //最大文件体积限制 flash_swf_url: 'Moxie.swf', //引入flash,相对路径 max_retries: 3, //上传失败最大重试次数 dragdrop: true, //开启可拖曳上传 drop_element: 'container', //拖曳上传区域元素的ID,拖曳文件或文件夹后可触发上传 chunk_size: '4mb', //分块上传时,每片的体积 auto_start: true //选择文件后自动上传,若关闭需要自己绑定事件触发上传, // filters: { // mime_types : [ //只允许上传图片 // { title : "Image files", extensions : "jpg,jpeg,gif,png" }, // ], // prevent_duplicates : false //不允许选取重复文件 // }, }; /** * 初始化处理函数 * @type type */ var _init = { FilesAdded: function (up, files) { plupload.each(files, function (file) { /* 文件添加进队列后,处理相关的事情 */ }); }, BeforeUpload: function (up, file) { /* 每个文件上传前,处理相关的事情 */ }, UploadProgress: function (up, file) { var msg = file.percent + '%'; jQuery('[name="' + option.name + '"]').val(msg); /* 每个文件上传时,处理相关的事情 */ }, FileUploaded: function (up, file, info) { /* 每个文件上传成功后,处理相关的事情 * 其中 info 是文件上传成功后,服务端返回的json,形式如 * { * "hash": "Fh8xVqod2MQ1mocfI4S4KpRL6D98", * "key": "<KEY>" * } */ var domain = up.getOption('domain'); var res = jQuery.parseJSON(info); var sourceLink = domain + res.key; //获取上传成功后的文件的Url jQuery('[name="' + option.name + '"]').val(sourceLink); }, Error: function (up, err, errTip) { console.dir(arguments); /* 上传出错时,处理相关的事情 */ }, UploadComplete: function () { console.dir(arguments); /* 队列文件处理完毕后,处理相关的事情 */ }, Key: function (up, file) { /* 若想在前端对每个文件的key进行个性化处理,可以配置该函数 * 该配置必须要在 unique_names: false , save_key: false 时才生效 */ var d = new Date(); var key = d.getFullYear() + ''; key += (d.getMonth() + 1); key += d.getDay(); key += d.getHours(); key += d.getMinutes(); key += d.getSeconds(); key += '/'; key += file.name; return key; } }; option = jQuery.extend(_default, option || {}); option.init = jQuery.extend(_init, option.init || {}); return Qiniu.uploader(option); }; });<file_sep><?php // 本类由系统自动生成,仅供测试用途 class adminModel extends RelationModel{ protected function pwdHash() { if(isset($_POST['password'])) { return md5($_POST['password']); }else{ return 123456; } } } ?>
c3822bc8e5888ce113d817ea533eb70e76f813e2
[ "JavaScript", "PHP" ]
76
PHP
zxy123123/hotel
2e9b97893e67fc7162619826718ef01abd652961
94d289f493d672b3c757daa80c76fd7c2f6ed706
refs/heads/master
<repo_name>ayman-93/js-functions-challenge<file_sep>/challenge.js //1. Write a function that will get the sum of the numbers between 1 and n and return the answer function summation(num) { var sum = 0; for (var i = 1; i <= num; i++) { sum += i; } return sum; } //2. Write a function to get the average of a group of numbers function avg(arr) { var sum = 0; for (var i = 0; i < arr.length; i++) { sum += arr[i]; } return sum / arr.length; } //3. Write a function to get the sum of all the even numbers in a group function summationEven(num) { var sum = 0; for (var i = 0; i <= num; i++) { if (i % 2 === 0) sum += i; } return sum; } //4. Write a function to reverse the letters in a word function reverse(str) { var newStr = ""; for (i = str.length - 1; i >= 0; i--) { newStr += str.charAt(i); } return newStr; } //5. Write a function that takes an array of words and combines them with a dash function addDashes(wordsArray) { var dashWords = ""; for (var i = 0; i < wordsArray.length; i++) { dashWords += wordsArray[i]; //i use 'if' instade of 'wordsArray[i]+"-"' to remove the last dash. if (i < wordsArray.length - 1) dashWords += "-"; } return dashWords; } //6. Function that will count up to a number and back down and return a string of the climb function countUpAndDown(num) { var climb = ""; for (var i = 1; i < num; i++) { climb += i + " "; } for (var i = num; i > 0; i--) { climb += i + " "; } return climb.slice(0, -1); // slice to remove the space at the end. } //7. Write a function that will tell you all of the words in an array that contain the letter a function wordsWithA(words) { var wordsWA = []; for (var i = 0; i < words.length; i++) { if (words[i].includes("a")) wordsWA.push(words[i]); } return wordsWA; } //search with more than one letter ;) function searchWords(words, liter) { var searchResult = []; for (var i = 0; i < words.length; i++) { if (words[i].includes(liter)) searchResult.push(words[i]); } return searchResult; } //8- Write a function that returns the longest word in sentence function longestWord(str) { var words = str.split(" "); var longest = ""; for (var i = 0; i <= words.length - 1; i++) { if (words[i].length > longest.length) longest = words[i]; } return longest; }
e0ef43d70e2c0c7c835b3832152ffd0b4ff695d9
[ "JavaScript" ]
1
JavaScript
ayman-93/js-functions-challenge
d23e96da7ad75f70d995df231be426af57d42ae8
1c0c4447dece500e5a227079f0fc9df3d0998cf3
refs/heads/master
<repo_name>ashleighchubbalubba/LoadBalancing<file_sep>/client.py import time import random import socket def client(lsHostname, lsListenPort): # list that contains all queried hostnames hostnameList = [] # populate hostNameList with hostnames from 'PROJ2-HNS.txt'(one line of the file = one element of hostnameList) file = open('PROJ2-HNS.txt', 'r') linesList = file.readlines() for line in linesList: hostnameList.append(line.lower()) # create LS socket try: csLS = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error as err: exit() # connect to LS server lsAddr = socket.gethostbyname(lsHostname) server_binding = (lsAddr, lsListenPort) csLS.connect(server_binding) # iterate through each hostName to talk to servers for hostname in hostnameList: csLS.send(hostname.encode('utf-8')) # send queried hostname to LS receivedString = csLS.recv(300) # receive LS's answer receivedString = receivedString.decode('utf-8').rstrip() # write to RESOLVED.txt file with open('RESOLVED.txt', 'a') as the_file: the_file.write(receivedString) the_file.write("\n") # if done going going through hostnames, tell LS to close connection csLS.send("closeConnection".encode('utf-8')) # close both sockets csLS.close() exit() if __name__ == "__main__": lsHostname = "" # type in hostname of machine that LS runs on lsListenPort = 50007 client(lsHostname, lsListenPort)<file_sep>/ts1.py import time import random import socket def ts1(ts1ListenPort): dnsTable = [] # list of arrays [ [hostname1, ip1, flag1], [hostname2, ip2, flag2],...] currInfo = [] # current line's info [hostname1,ip1,flag1] # populate the table while reading the file file = open('PROJ2-DNSTS1.txt', 'r') linesList = file.readlines() for line in linesList: for word in line.split(): currInfo.append(word) dnsTable.append(currInfo) currInfo = [] # socket to connect to LS try: ts1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error as err: exit() # connect to LS server server_binding = ('', ts1ListenPort) ts1.bind(server_binding) ts1.listen(1) LSsockid, addr = ts1.accept() while True: # receive queried hostname from LS queriedHostname = LSsockid.recv(300).decode('utf-8').rstrip() # if LS finished sending all hostnames, close socket if queriedHostname == "closeConnection": break string = "" # search dnsTable for queried hostname for info in dnsTable: replacement = info[0].lower() # check hostname of each list stored in DNSTable if(replacement == queriedHostname): # there's a match! send "Hostname IPaddress A" to LS string = "" + info[0] + " " + info[1] + " " + info[2] LSsockid.send(string.encode('utf-8')) break # Close the server socket ts1.close() exit() if __name__ == "__main__": ts1ListenPort = 50008 ts1(ts1ListenPort)<file_sep>/ls.py import time import random import socket def ls(lsListenPort, ts1Hostname, ts1ListenPort, ts2Hostname, ts2ListenPort): # create socket to connect to client try: ls = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error as err: exit() # connect to client server_binding = ('', lsListenPort) ls.bind(server_binding) ls.listen(1) csockid, addr = ls.accept() # create TS1 socket try: ts1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error as err: exit() # connect to TS1 server ts1Addr = socket.gethostbyname(ts1Hostname) server_binding = (ts1Addr, ts1ListenPort) ts1.connect(server_binding) ts1.settimeout(5) # create TS2 socket try: ts2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error as err: exit() # connect to TS2 server ts2Addr = socket.gethostbyname(ts2Hostname) server_binding = (ts2Addr, ts2ListenPort) ts2.connect(server_binding) ts2.settimeout(5) while(True): # Receive queried hostname from the client queriedHostname = csockid.recv(300).decode('utf-8').rstrip() # if client finished sending all hostnames, close socket if queriedHostname == "closeConnection": # send closing message to TS1 and TS2 ts1.send("closeConnection".encode('utf-8')) ts2.send("closeConnection".encode('utf-8')) break # send queriedHostname to TS1 ts1.send(queriedHostname.encode('utf-8')) ts2.send(queriedHostname.encode('utf-8')) # if we got a response from TS1, send response to client try: receivedString = ts1.recv(300).decode('utf-8').rstrip() # receive TS1's answer csockid.send(receivedString.encode('utf-8')) # send string to the client # if we didn't get a response from TS1, send error to client except socket.timeout: try: receivedString = ts2.recv(300).decode("utf-8").rstrip() csockid.send(receivedString.encode("utf-8")) except socket.timeout: errorMessage = "" + queriedHostname + " - Error:HOST NOT FOUND" csockid.send(errorMessage.encode('utf-8')) # send string to the client # close socket ls.close() ts1.close() ts2.close() exit() if __name__ == "__main__": lsListenPort = 50007 ts1Hostname = "" # type in hostname of machine that TS1 runs on ts1ListenPort = 50008 ts2Hostname = "" # type in hostname of machine that TS2 runs on ts2ListenPort = 50009 ls(lsListenPort, ts1Hostname, ts1ListenPort, ts2Hostname, ts2ListenPort) <file_sep>/README.txt README file ----------- 0. Please write down the full names and netids of all your team members. <NAME> (atc101) <NAME> (vm479) 1. Briefly discuss how you implemented the LS functionality of tracking which TS responded to the query and timing out if neither TS responded. 1) We sent the query to TS1 and then to TS2 immediately right after. 2) LS waits for 5 seconds using .settimeout(5) on the socket that connects LS to TS1 and the socket that connects LS to TS2 3) We used nested try/except blocks (TS1's response for the outer, TS2's response for the inner) to handle whether LS receives a response from the two severs. If TS1 responds (enters outer try block), then LS sends its response to client. If TS1 doesn't respond (enters outer except block), then LS checks if TS2 has responded. 4) If TS2 has responded (enters inner try block), then LS sends its response to client. If TS2 has not responded (enters inner except block), then LS sends an error message to client, meaning that neither TS1 or TS2 have reponded. We sent queries to both TS1 and TS2 at the same time, however with the nested try/except blocks, our program is structured so that it checks for TS1's response first and then TS2's response if there is no TS1 response. This does not act as a problem since at most one of the TS servers will have the hostname in their DNS table. 2. Are there known issues or functions that aren't working currently in your attached code? If so, explain. - None that we know so far - Before running the program, manually type in LS's hostname in line 46 of client.py TS1's hostname in line 80 of ls.py TS2's hostname in line 82 of ls.py 3. What problems did you face developing code for this project? The main problem we faced was determining how to make LS wait 5 seconds for a response. We were also unsure about how to first check if TS1 responded and only then check if TS2 responded. But once we realized we can use two try/except blocks to make this work, we were able to correctly check for TS1 and TS2 responses. 4. What did you learn by working on this project? Since this project was similar to Project 1 in terms of creating sockets, sending hostnames, etc., working on Project 2 only reinforced those skills for us. But what made Project 2 a step above Project 1 was its different structure along with the timing mechanism. We were able to learn how to structure the program differently (dividing Project 1's client.py into Project 2's client.py and ls.py, creating ts2.py, etc.). More notably, we learned how to handle a situation when the server does not send any response back at all and we had to rely on setting a timer to figure out its answer.
d0a300db0acd76560fb30bdbe961d3f41b70f3fd
[ "Python", "Text" ]
4
Python
ashleighchubbalubba/LoadBalancing
b9be327b23960421518acbb1f90e67d63005f0e1
0ed258db909e694f4a73fdb4463cb744e6b7223f
refs/heads/main
<file_sep># Hydra_Display_RPi This is the active repository for downloading the display and logger components of the truck's display Raspberry Pi <file_sep>""" AUTHOR: <NAME> Portions that deal with receiving CAN messages have been adapted from Calvin Lefebvre's code PURPOSE: This is an app to be used on small 5" touch screen displays inside Hydra's trucks. It is used to display information gathered from the truck monitoring scripts in an easy to read touch screen GUI. It (currently) consists of 7 pages: Main Menu, H2 Fuel Gauge, H2 Injection Rate, Tank Pressure and Temperature, Fault Information, Leakage Information, and the Screen Saver. The pages' functions/purposes are described below. The app automatically runs on the boot up of the Raspberry Pi computer it is loaded on as long as the appropriate scripts/files are added as described in the README. The app requires a few files to run properly, these include the 2 image files "cadran.png" which is the gauge and "needle.png" which is the needle on the gauge. The entire app is built with Kivy via Python 3.7 and requires an up to date Python 3.7 as well as Kivy install to work. The file paths are currently set up for the Raspberry Pi computer that the app was built for but can be easily changed to fit any computer OS or file path. Page Descriptions: Main Menu: This page is where the app initially loads to and consists of 5 buttons that each take you to the individual information pages. In the top left of the page is an area where in the case of a system fault a red message saying "FAULT" as well as the fault number code will be displayed. In the top right of the page is an area where the current mode of the truck (Hydrogen or Diesel) is displayed. H2 Fuel Gauge: This is the page that shows the current Hydrogen fuel level in the truck. It displays the percentage as a number in the bottom of the page as well as graphically in the form of the fuel gauge itself. In the bottom left of the page is a button that says "BACK" which when pressed takes the user back to the Main Menu page. As with all of the screens/pages the top left displays any faults and the top right displays the current engine mode of the truck H2 Injection Rate: Very similar in appearance to the H2 Fuel Gauge screen, this page shows the current instantaneous Hydrogen injection rate into the engine. It is displayed graphically as a percentage of the maximum injection rate on the gauge as well as the specific value in kg/h in the bottom of the page. This screen includes the same "BACK" button, Fault, and engine mode displays as all the other pages. Tank Pressure and Temperature: This page shows the current temperatures of all of the Hydrogen tanks in addition to the readings from the 2 in-line pressure sensors. Includes the same buttons and corner displays as the other screens Fault Information: This page provides more in depth information about the fault (if any) occurring within the truck. On the left it shows the fault code and on the right has the brief description of what the fault is. This is mainly for the driver to be able to inform the technician(s) and thus the fault description is brief and requires knowledge of the fault codes/messages to understand. Has the same "BACK" button and engine mode display however does not include a Fault display in the top left as that would be redundant since the page already displays that information Leakage Information: This page provides information on the status/severity of any Hydrogen leaks occurring in the truck. Includes the same corner buttons and displays as the other screens. Screen Saver: There is no direct button to access this screen. If there is no user interaction on any of the pages for a designated amount of time (controlled by the variable 'delay') then the app will automatically change to this page. To avoid burn in the Hydra logo is animated to slowly bounce around Any reference to the Kivy back end or the Kivy code relates to the code held within the "fuelgauge.kv" file -- it will/needs to be in the same folder as this code for the app to work """ """ Outside References: - For the dusk screen dimming system the https://sunrise-sunset.org/api was used, this provided a very useful list of sunset times """ import time import can import os from threading import Thread from kivy.app import App from kivy.clock import Clock from kivy.config import Config from kivy.core.window import Window from kivy.properties import NumericProperty, ListProperty, StringProperty from kivy.uix.screenmanager import ScreenManager, Screen from kivy.uix.dropdown import DropDown # The conversion factor is used to convert the raw numerical data into degrees to move the needle # default is 1.8 which works for a 0-100 slider, this is because when the needle is pointing straight up (at the 50) it is at 0˚ and since # the maximum angles for the needle will be 50 points on the dial either way to get this as +/- 90˚ you multiply the value by 1.8. # To put it more simply 50 * 1.8 = 90, the needle has to be able to rotate 180˚ total and the gauge is from 0-100, 100 * 1.8 = 180 # cf = conversion_factor cf = 1.8 # The delay is how long the app goes without user input before it changes to the screen saver delay = 2000 # This is the main directory where everything for this is stored (including this file) display_code_dir = '/Users/<NAME>/PycharmProjects/Hydra_Display_RPi/' _canIdTank123 = "cff3d17" _canIdTank456 = "cff4017" _canIdNira3 = "cff3e17" _canIdWheelSpeed = "18fef100" # This next block of functions are all derived from Calvin's PI data logging code, the main differences between them in this code and his are where the variables send their contents ################################################################################################################# def msg_receiving(): '''outDir = sys.argv[1] # "/home/pi/rough/logger-rbp-python-out/lomack150_" numCAN = int(sys.argv[2]) # 2 bRate = int(sys.argv[3]) # 250000 or 500000 CANtype = sys.argv[4] # OCAN or ACAN numTank = int(sys.argv[5]) volumeStr = sys.argv[6]''' outDir = "/Users/<NAME>/PycharmProjects/Display_rep/" # Display_rep/out/hydraFL # "/home/pi/rough/logger-rbp-python-out/lomack150_" numCAN = 1 # 2 bRate = 250000 # 250000 or 500000 CANtype = "RBP15" # OCAN or ACAN numTank = 5 volumeStr = "202,202,202,202,148" volumeL = [float(x) for x in volumeStr.split(",")] os.system("sudo /sbin/ip link set can0 down") if numCAN == 2: os.system("sudo /sbin/ip link set can1 down") # Make CAN interface to 250 or 500kbps setCANbaudRate(numCAN, bRate) # Connect to Bus bus0 = connectToLogger('can0') if numCAN == 2: bus1 = connectToLogger('can1') # Continually recieved messages readwriteMessageThread(bus0, outDir, numCAN, bRate, CANtype, numTank, volumeL) # if numCAN == 2: # readwriteMessageThread(bus1, outDir, numCAN, bRate, CANtype + "1", numTank, volumeL) # Continually write readMessages try: while True: pass except KeyboardInterrupt: # Catch keyboard interrupt os.system("sudo /sbin/ip link set can0 down") if numCAN == 2: os.system("sudo /sbin/ip link set can1 down") print('\n\rKeyboard interrtupt') def readwriteMessageThread(bus, outDir, numCAN, bRate, CANv, numTank, volumeL): """ In seperate thread continually recieve messages from CAN logger """ # Start receive thread t = Thread(target=can_rx_task, args=(bus, outDir, numCAN, bRate, CANv, numTank, volumeL)) t.start() def can_rx_task(bus, outDir, numCAN, bRate, CANv, numTank, volumeL): """ CAN receive thread """ curFname = None outF = None prevTime = ("-1", "-1", "-1") livefeedNiraErrorFname = "_".join([outDir, CANv, "liveUpdate-NiraError.txt"]) livefeedHmassFname = "_".join([outDir, CANv, "liveUpdate-Hmass.txt"]) prevNiraError = None tempL = [] maxNumTanks = 6 for i in range(maxNumTanks): tempL.append(None) presT1 = None wheelSpeed = None railPressure = None prevSec = None curVarL = [railPressure, presT1, wheelSpeed] while True: # recieve message and extract info (outstr, timeDateV) = createLogLine(bus.recv()) (ymdFV, hourV, ymdBV, hmsfV) = timeDateV prevYmdBV = ymdBV prevHmsfV = hmsfV prevHour = hourV prevTime = (prevYmdBV, prevHmsfV, prevHour) (prevNiraError, tempL, curVarL, prevSec) = liveUpdateTruck(outstr, livefeedNiraErrorFname, livefeedHmassFname, prevNiraError, prevTime, tempL, curVarL, volumeL, numTank, maxNumTanks, prevSec) # if not(HtotalMass == None): # WRITE CODE HERE ... use HtotalMass def createLogLine(message): """ Format the CAN message """ # Time Stamp (ymdFV, hmsfV, hourV, ymdBV) = extractTimeFromEpoch(message.timestamp) # PGN pgnV = '0x{:02x}'.format(message.arbitration_id) # Hex hexV = '' for i in range(message.dlc): hexV += '{0:x} '.format(message.data[i]) outstr = " ".join([hmsfV, "Rx", "1", pgnV, "x", str(message.dlc), hexV]) + " " timeDateV = (ymdFV, hourV, ymdBV, hmsfV) return (outstr, timeDateV) def extractTimeFromEpoch(timeStamp): """ Extract all the relative time and date info from CAN timestamp """ ymdFV = time.strftime('%Y%m%d', time.localtime(timeStamp)) ymdBV = time.strftime('%d:%m:%Y', time.localtime(timeStamp)) hmsV = time.strftime('%H:%M:%S', time.localtime(timeStamp)) hourV = time.strftime('%H', time.localtime(timeStamp)) millsecondV = str(timeStamp).split(".")[1][:3] return (ymdFV, hmsV + ":" + millsecondV, hourV, ymdBV) def liveUpdateTruck(outstr, livefeedNiraErrorFname, livefeedHmassFname, prevNiraError, YDM, tempL, curVarL, volumeL, numTank, maxNumTanks, prevSec): """ ... """ app = App.get_running_app() splt = outstr.strip().split(" ") # Timestamp with date monthNumToChar = {1: "Jan", 2: "Feb", 3: "Mar", 4: "Apr", 5: "May", 6: "Jun", 7: "Jul", 8: "Aug", 9: "Sep", 10: "Oct", 11: "Nov", 12: "Dec"} [dayV, monthV, yearV] = YDM[0].split(":") hmsStr = ":".join(YDM[1].split(":")[:3]) outDate = " ".join([dayV, monthNumToChar[int(monthV)], yearV, hmsStr]) [railPressure, presT1, wheelSpeed] = curVarL # date, can ID, hex value if (outstr[0] != "*"): try: dateV = splt[0] idV = splt[3].lower()[2:] hexVsplt = splt[6:] hexV = "" for h in hexVsplt: if len(h) == 1: hexV += "0" + h elif len(h) == 2: hexV += h except IndexError: hexV = "" idV = "" if len(hexV) == 16: ####################################################################################### # Nirai7LastFaultNumber_spnPropB_3E if (idV == _canIdNira3): dateCond0 = (len(splt[0]) != 12) dateCond1 = ((len(splt[0]) == 13) and (len(splt[0].split(":")[-1]) == 4)) piCcond = ((len(hexV) != 16) or (dateCond0 and not (dateCond1))) if piCcond: pass else: nirai7LastFaultNumber = (enforceMaxV(((int(hexV[6:8], 16))), 255) * 1.0) app.error_code = str(int(nirai7LastFaultNumber)) if prevNiraError == None: prevNiraError = nirai7LastFaultNumber elif nirai7LastFaultNumber != prevNiraError: 'INSERT CODE HERE' ####################################################################################### # Temperature and Pressure T1-T3 if (idV == _canIdTank123): presT1 = (enforceMaxV(((int(hexV[0:2], 16)) + ((int(hexV[2:4], 16) & 0b00001111) << 8)), 4015) * 0.1) presT2 = (enforceMaxV((((int(hexV[2:4], 16) & 0b11110000) >> 4) + ((int(hexV[4:6], 16)) << 4)), 4015) * 0.1) tempL[0] = (enforceMaxV(((int(hexV[10:12], 16))), 250) * 1.0) - 40.0 tempL[1] = (enforceMaxV(((int(hexV[12:14], 16))), 250) * 1.0) - 40.0 tempL[2] = (enforceMaxV(((int(hexV[14:16], 16))), 250) * 1.0) - 40.0 app.pressures[0] = str("%.2f" % presT1) + ' bar' app.temps[0] = str("%.2f" % tempL[0]) + '˚C' app.temps[1] = str("%.2f" % tempL[1]) + '˚C' app.temps[2] = str("%.2f" % tempL[2]) + '˚C' ####################################################################################### # Temperature and Pressure T4-T6 elif (idV == _canIdTank456): tempL[3] = (enforceMaxV(((int(hexV[10:12], 16))), 250) * 1.0) - 40.0 tempL[4] = (enforceMaxV(((int(hexV[12:14], 16))), 250) * 1.0) - 40.0 tempL[5] = (enforceMaxV(((int(hexV[14:16], 16))), 250) * 1.0) - 40.0 app.temps[3] = str("%.2f" % tempL[3]) + '˚C' app.temps[4] = str("%.2f" % tempL[4]) + '˚C' app.temps[5] = str("%.2f" % tempL[5]) + '˚C' ####################################################################################### # Rail pressure elif (idV == _canIdNira3): railPressure = (enforceMaxV(((int(hexV[12:14], 16))), 4015) * 0.1) app.pressures[1] = str('%.2f' % railPressure) + ' bar' ####################################################################################### # Wheel-Based Vehicle Speed elif (idV == _canIdWheelSpeed): wheelSpeed = (enforceMaxV(((int(hexV[2:4], 16)) + ((int(hexV[4:6], 16)) << 8)), 64259) * 0.003906) ####################################################################################### # Hydrogen injection rate elif ((idV == "cff3f28") or (idV == "cff3ffa")): app.HinjectionV = (enforceMaxV(((int(hexV[12:14], 16)) + ((int(hexV[14:16], 16)) << 8)), 64255) * 0.02) ####################################################################################### # Hydrogen leakage elif ((idV == "cff3e28") or (idV == "cff3efa")): app.Hleakage = (enforceMaxV(((int(hexV[2:4], 16))), 250) * 0.4) # Coolant temperature elif (idV == "18feee00"): coolant_temp = str((enforceMaxV(((int(hexV[0:2], 16))), 250) * 1.0) - 40.0) # Unit = °C if coolant_temp is not '': app.coolant_temp = coolant_temp + u' \u00BAC' # Diagnostic Message 1 -- Active DTCs elif (idV == "18feca00"): DM1 = (enforceMaxV((((int(hexV[0:2], 16) & 0b11000000) >> 6)), 3) * 1.0) # Unit = bit if DM1 == 0: app.mil_light = 'Lamp Off' else: app.mil_light = 'Lamp On' # Diesel particulate filter elif (idV == "18fd7c00"): dpf = (enforceMaxV((((int(hexV[2:4], 16) & 0b00001100) >> 2)), 3) * 1.0) # Unit = bit if dpf == 0: app.dpf_status = 'Not Active' elif dpf == 1: app.dpf_status = 'Active' elif dpf == 2: app.dpf_status = 'Regen Needed' else: app.dpf_status = 'Not Available' # Mode requests elif idV == 'cff3c17': mode_being_requested = (enforceMaxV(((int(hexV[0:2], 16) & 0b00000011)), 3) * 1.0) # Unit = bit mode_num = (enforceMaxV((((int(hexV[0:2], 16) & 0b00001100) >> 2)), 3) * 1.0) # Unit = bit if (mode_num == 0) or (mode_num == 1): app.current_mode = 'Hydrogen' # app.mode_num = str(mode_num) elif mode_num == 2: app.current_mode = 'Diesel' # app.mode_num = str(mode_num) # print(app.mode_being_requested) if (mode_being_requested) == 0 or (mode_being_requested == 1): app.truck_reqd = u'H\u2082 Mode ' # app.mode_color = [235 / 255, 150 / 255, 72 / 255, 1] elif mode_being_requested == 2: app.truck_reqd = 'Diesel Mode' # app.mode_color = [0.431, 0.431, 0.431, 1] else: app.truck_reqd = 'Missing' app.mode_color = [1, 0, 0, 1] # if (app.mode_num == '0') or (app.mode_num == '1'): # app.engine_mode = u'H\u2082 Mode ' # app.mode_color = [235 / 255, 150 / 255, 72 / 255, 1] # elif app.mode_num == '2': # app.engine_mode = 'Diesel Mode' # app.mode_color = [0.431, 0.431, 0.431, 1] ####################################################################################### # curHr = int(dateV.split(":")[1]) # if ((curHr in [0, 15, 30, 45]) and (curHr != lastQuarterHour)): curSec = int(dateV.split(":")[2]) if curSec != prevSec: ################################################################################### # H mass calculation HtotalMass = None if (not (None in tempL) and (presT1 != None)): HtotalMassL = [] for t in range(numTank): # Only consider tank 1 hydrogen pressure currHtotalMassT = hydrogenMassEq2(presT1, tempL[t], volumeL[t]) HtotalMassL.append(currHtotalMassT) HtotalMass = round(sum(HtotalMassL), 1) app.hMass = HtotalMass tempL = [] for i in range(maxNumTanks): tempL.append(None) presT1 = None railPressure = None wheelSpeed = None prevSec = curSec # lastQuarterHour = curHr curVarL = [railPressure, presT1, wheelSpeed] return (prevNiraError, tempL, curVarL, prevSec) def connectToLogger(canV): """ Connect to Bus """ app = App.get_running_app() try: app.bus = can.interface.Bus(channel=canV, bustype='socketcan_native') except OSError: print('Cannot find PiCAN board.') exit() return app.bus def setCANbaudRate(numCAN, bRate): """ Make CAN interface to 250 or 500 kbps """ os.system("sudo /sbin/ip link set can0 up type can bitrate " + str(bRate)) if numCAN == 2: os.system("sudo /sbin/ip link set can1 up type can bitrate " + str(bRate)) time.sleep(0.1) def hydrogenMassEq2(pressureV, tempV, volumeV): """ Calculate the hydrogen mass using more complex equation Value returns in unit kilo grams """ var1 = 0.000000001348034 var2 = 0.000000267013 var3 = 0.00004247859 var4 = 0.000001195678 var5 = 0.0003204561 var6 = 0.0867471 component1 = (((-var1 * (tempV ** 2)) + (var2 * tempV) - var3) * (pressureV ** 2)) component2 = ((var4 * (tempV ** 2)) - (var5 * tempV) + var6) * pressureV HmassTotal = (component1 + component2) * volumeV HmassTotalKg = HmassTotal / 1000.0 return HmassTotalKg def enforceMaxV(origV, maxV): """ ... """ if origV < maxV: return origV else: return maxV ################################################################################################################# # The following functions are all used for the displays operation ################################################################################################################# # This function checks the value read by modeReader and checks what it is -- if it is 0 or 1 it sets the engine_mode string variable to 'H2\nMODE' which is just H2 MODE on separate lines, otherwise it sets the variable # to 'DIESEL\nMODE'. It also then changes the color of the text to either green or grey def truckEngineMode(dt): app = App.get_running_app() if (app.mode_num == '0') or (app.mode_num == '1'): app.engine_mode = u'H\u2082 Mode ' app.mode_color = [235 / 255, 150 / 255, 72 / 255, 1] app.alignment = 'right' elif app.mode_num == '2': app.engine_mode = 'Diesel Mode' app.alignment = 'center' app.mode_color = [0.431, 0.431, 0.431, 1] def stateUpdate(dt): app = App.get_running_app() # This checks what value the error_code variable has and if it has no value or is 255 then since there is no fault the function sets the error_base string variable to ' ' which is just blank # If error_code is any other number it then changes the error_base variable to a couple different things. This function is called repeatedly every 2s so it checks to see what error_base is currently # if it is blank it changes it to 'FAULT' if it says 'FAULT' it changes it to the error code, and if it is the error code it changes it to 'FAULT' essentially flipping between displaying 'FAULT' and # the error code every 2s def errorMsg(dt): app = App.get_running_app() if (app.error_code == '255') or (app.error_code == ''): app.error_base = '' else: if app.error_base == '': app.error_base = 'FAULT' elif app.error_base == 'FAULT': app.error_base = '#' + app.error_code elif app.error_base == '#' + app.error_code: app.error_base = 'FAULT' # This function just changes the current page to the 'third' which is what the screen saver page is defined as in the Kivy back end def callback(dt): app = App.get_running_app() # app.root.current just calls the the Kivy ScreenManger class that handles all of the screens and changes it to the screen defined as 'third' app.root.current = 'third' # Is called every 10s and checks to see if the current time is equal to the stored dusk time -- If it is, and if the screen is not currently dimmed this will # proceed to set pin 18 to PWM and reduce it to 512 out of 1024 def isDusk(dt): app = App.get_running_app() dusk_today = app.dusk_time now = time.strftime('%I:%m') dimmed = app.screen_dim print(now) if (not dimmed) and (now == dusk_today): try: os.system('gpio -g pwm 18 75') except OSError: exit() app.screen_dim = True # This function is called when the display first starts up -- it reads the stored sunset/dusk data file then extracts and stores the sunset time for the current day def getDuskTime(): dusk_file = open(display_code_dir + '2021PrinceGeorgeSunsets.txt', 'r') dusk_list = dusk_file.readlines() this_month = time.strftime('%m') real_today = time.strftime('%d') # Storing the sunset time for every day of the year would be a lot to sort through -- to speed things up only 5 days a month are used and the display assigns a # 'sudo today' which is the closest stored date to the current day if int(real_today) <= 3: sudo_today = '1' elif int(real_today) <= 10: sudo_today = '7' elif int(real_today) <= 17: sudo_today = '14' elif int(real_today) <= 23: sudo_today = '20' else: sudo_today = '26' for line in dusk_list: dusk_month = line.split('>')[0].split('-')[1] dusk_day = line.split('>')[0].split('-')[2] if dusk_month == this_month: dusk_time = line.split('>')[1].strip('\n') if dusk_day == sudo_today: if (int(this_month) > 3) or (int(this_month) < 11): DST = True elif (int(this_month == 3)) and (int(real_today) >= 14): DST = True elif (int(this_month == 11)) and (int(real_today) < 7): DST = True else: DST = False if DST == True: dhour = int(dusk_time.split(':')[0]) + 1 dmin = int(dusk_time.split(':')[1]) if dhour < 10: dusk_time = '0' + str(dhour) + ':' + str(dmin) else: dusk_time = str(dhour) + ':' + str(dmin) print(dusk_time) dusk_file.close() return dusk_time def bus_activator(dt): app = App.get_running_app() try: app.bus = can.interface.Bus(channel='can0', bustype='socketcan_native') print('Found PiCAN board!') except OSError: print('Cannot find PiCAN board') Clock.schedule_once(bus_activator, 2) return try: print('made it past setting up bus now trying to send the toggle msg') app.task = app.bus.send_periodic(app.toggle_msg, 0.2) print('Toggle Message Successfully Sending') except NameError: Clock.schedule_once(bus_activator, 2) return ################################################################################################################# # The following code are all of the classes that make up the main body and backend of the display app ################################################################################################################# # This is the screen saver page -- for its design/visual setup look in the Kivy back end code (in the 'root_widget') class ScreenSaver(Screen): # Sets the speed that the logo will travel at based on the size of the screen velocity = ListProperty([Window.width / 200, Window.height / 200]) screen_pos = ListProperty([0, 0]) # Updates the position of the Hydra logo (animates it) def update(self, dt): self.screen_pos[0] += self.velocity[0] self.screen_pos[1] += self.velocity[1] if self.screen_pos[0] < 0 or self.screen_pos[0] > ((Window.width * 2 / 3)): self.velocity[0] *= -1 # or (self.screen_pos[1] + self.height) > Window.height if self.screen_pos[1] < 0 or self.screen_pos[1] > (Window.height * (1 - (1.8 * (2.5 / 12)))): self.velocity[1] *= -1 app = App.get_running_app() def on_enter(self): Clock.unschedule(callback) Clock.schedule_interval(self.update, 1 / 120) # Special Kivy function that runs its code when the user touches the screen and releases def on_touch_up(self, touch): if self.collide_point(*touch.pos): # Since this page is the screen saver there is no timer/delay to reset, however when the user touches the screen saver and 'wakes' the device the app will return to the main menu self.manager.current = 'menu' def on_leave(self): Clock.unschedule(self.update) # This is the fuel gauge screen that displays the current Hydrogen fuel level class FuelGaugeLayout(Screen): # This (dash_val) value is the value that the dashboard/fuel gauge uses and starts at dash_val = NumericProperty(0.00) dash_label = StringProperty() percent_label = StringProperty() def mass_reader(self, dt): app = App.get_running_app() # Divides the current hydrogen mass by the maximum possible then multiplies by 100 to get a percentage # then assigns this value to the 'dash_val' variable self.dash_val = ((app.hMass / 20.7) * 100) self.percent_label = '%.2f' % self.dash_val self.dash_label = '%.2f' % app.hMass # Kivy function runs code on entering the page def on_enter(self): Clock.schedule_once(self.mass_reader) Clock.schedule_once(callback, delay) Clock.schedule_interval(self.mass_reader, 0.2) # Kivy function runs code when the user touches and releases on the screen. This is the delay reset for the screen saver def on_touch_up(self, touch): Clock.unschedule(callback) Clock.schedule_once(callback, delay) # Same as in the other classes def on_leave(self): Clock.unschedule(callback) # FuelInjectionLayout is the second screen and does what it says on the tin -- it displays the current H2 injection rate class FuelInjectionLayout(Screen): # This variable is what is used to display injection reading at the bottom of the page, is a string property to allow the Kivy back end to read it even when it changes hInjection = StringProperty() leak_display = StringProperty() # Same as in the other classes, calls functions as the user enters the page. Upon_entering has the same function as upon_entering_mass and just calls the functions after a 0.5s # delay to avoid any issues def on_enter(self): Clock.schedule_once(self.injection_reader) Clock.schedule_interval(self.injection_reader, 0.2) # Same as in fuel gauge screen Clock.schedule_once(callback, delay) # Ticker is what checks to see if the time is at a 15min +1 time interval # Kivy function that runs code after the user touches the screen def on_touch_up(self, touch): Clock.unschedule(callback) Clock.schedule_once(callback, delay) # This function opens the file that contains the data about the injection rate, reads it and sets it to some variables def injection_reader(self, dt): app = App.get_running_app() # hInj -- This is the variable that contains the injection rate value self.hInjection = '%.2f' % app.HinjectionV leakAmt = app.Hleakage self.leak_display = '%.2f' % app.Hleakage # Same as in the other classes def on_leave(self): Clock.unschedule(callback) Clock.unschedule(self.injection_reader) # This is the page that displays the Fault code and its corresponding message class ErrorPage(Screen): error_expl = StringProperty('Missing') # Same as in the other classes def on_touch_up(self, touch): Clock.unschedule(callback) Clock.schedule_once(callback, delay) # Same as in the other classes, apart from the bottom bit def code_checker(self, dt): app = App.get_running_app() # This part checks to see if the error code is 255 as this means that there is no fault or if the code is greater than 233 as this is out of the possible range of # fault codes, if it is 255 it sets the message to 'Everything is running as expected' and if the code is greater than 233 it sets it as 'ERROR: Code outside of range' try: e_c = int(app.error_code) except ValueError: return () if e_c == 255: self.error_expl = 'Running as expected' elif int(app.error_code) >= 233: self.error_expl = 'Invalid Code' else: self.error_expl = app.error_list[e_c] # Same as in the other class def on_enter(self): Clock.schedule_once(self.code_checker) Clock.schedule_interval(self.code_checker, 0.2) Clock.schedule_once(callback, delay) def on_leave(self): Clock.unschedule(self.code_checker) Clock.unschedule(callback) # This is the screen that displays the temperatures and pressures of the tanks and lines from the tanks class TankTempPress(Screen): # Nothing fancy happens on this page, all of the data collection/displaying is handled by the main app class in addition to the kivy code file (fuelgauge.kv) def on_enter(self): Clock.schedule_once(callback, delay) def on_touch_up(self, touch): Clock.unschedule(callback) Clock.schedule_once(callback, delay) def on_leave(self): Clock.unschedule(callback) # This is the screen manager that holds all of the other pages together class MyScreenManager(ScreenManager): pass # Screen that shows the leakage rate class Mode(Screen): def on_enter(self): app = App.get_running_app() # app.title_changer('Engine Mode') Clock.schedule_once(callback, delay) # Kivy function runs code when the user touches and releases on the screen. This is the delay reset for the screen saver def on_touch_up(self, touch): Clock.unschedule(callback) Clock.schedule_once(callback, delay) # Same as in the other classes def on_leave(self): Clock.unschedule(callback) # This is the lock screen where technicians can lock or unlock the engine mode toggle button -- accessed by hitting the engine mode descriptor class ModeLocking(Screen): # This is the correct password/pin password = '<PASSWORD>' # This is the descriptor text that says either 'Locked' or 'Unlocked' status = StringProperty() def on_enter(self): # When the user enters the screen checks the current lock status Clock.schedule_once(self.launch_status) Clock.schedule_once(callback, delay) def on_touch_up(self, touch): Clock.unschedule(callback) Clock.schedule_once(callback, delay) def on_leave(self): Clock.unschedule(callback) # Checks the current lock status and sets the descriptor text accordingly def launch_status(self, dt): app = App.get_running_app() if app.lock_status == '0': self.status = 'Unlocked' else: self.status = 'Locked' # Sets the default color of the submit button wrong_password_ind = ListProperty([44 / 255, 49 / 255, 107 / 255, 1]) # Called when the user submits their password def code_tester(self, text): # Allows this function to reference variables/functions from the main app class app = App.get_running_app() # Checks if the entered password matches the correct one if text == self.password: # Changes the color of the submit button to Green in order to show the correct password was entered self.wrong_password_ind = [0, 1, 0, 1] # Checks the current lock status if app.lock_status == '1': # Toggles the lock status to unlocked app.lock_status = '0' self.status = 'Unlocked' else: # Toggles the lock status to locked app.lock_status = '1' self.status = 'Locked' # Writes the current lock status to lock_file.txt to save it across sessions fin = open(display_code_dir + "lock_file.txt", "wt") fin.write(app.lock_status) fin.close() else: # Changes the color of the submit button to Red in order to show an incorrect password was entered self.wrong_password_ind = [1, 0, 0, 1] class Message_settings(Screen): def on_enter(self): Clock.schedule_once(callback, delay) # Kivy function runs code when the user touches and releases on the screen. This is the delay reset for the screen saver def on_touch_up(self, touch): Clock.unschedule(callback) Clock.schedule_once(callback, delay) # Same as in the other classes def on_leave(self): Clock.unschedule(callback) # The main app class that everything runs off of class FuelGaugeApp(App): os.system('gpio -g mode 18 pwm') os.system('gpio -g pwm 18 1024') #################################################################################################### # Variable declarations #################################################################################################### temps = ListProperty(['NA', 'NA', 'NA', 'NA', 'NA', 'NA']) pressures = ListProperty(['NA', 'NA']) font_file = StringProperty(display_code_dir + 'Montserrat-Regular.ttf') bold_font_file = StringProperty(display_code_dir + 'Montserrat-Bold.ttf') current_page = StringProperty('Fuel Gauge') dropdown_list = ListProperty( ['Fuel Gauge', 'Injection Rate', 'Engine Mode', 'Temp & Press', 'Fault Info', 'CAN Settings']) mode_being_requested = int error_list = [] mode_num = str error_code_list = [] screen_dim = False Hleakage = NumericProperty() HinjectionV = NumericProperty() mil_light = StringProperty('Missing') coolant_temp = StringProperty('Missing') dpf_status = StringProperty('Missing') current_mode = StringProperty('Missing') truck_reqd = StringProperty() # The 0 inside the brackets is providing an initial value for hMass -- required or else something breaks hMass = NumericProperty(0) # error_code is a string variable that is used to temporarily store the current error code taken from the text document it is stored in. It is a string because after coming from the .txt the data is a string and # must be converted into a float or int to be used as a number error_code = StringProperty('Missing') # error_base is the text that is displayed in the top left hand of most screens -- if there is a fault this variable becomes "FAULT" and then the error code and flips between them # It is a StringProperty() which is a Kivy variable type the essentially tells the Kivy back end code to keep checking what its value is/if it changes error_base = StringProperty() # The conversion factor is for changing the discrete data values into a specific angle of rotation for the gauges conversion_factor = cf dusk_time = getDuskTime() #################################################################################################### # Extracting data from the stored text files #################################################################################################### # Opens the NIRA error code file and saves th error codes to error_code_list with open(display_code_dir + 'faultmessages.txt', 'r') as f: lines = f.readlines() # Goes line by line and adds the error codes to the 'error_code_list' list for l in lines: error_code_list.append(l.split(',')[0]) f.close() # Opens the NIRA error code file and saves the fault code descriptions to error_list with open(display_code_dir + 'faultmessages.txt', 'r') as f: lines = f.readlines() # Goes line by line and adds the error messages to the 'error_list' list for l in lines: error_list.append(l.split(',')[2]) f.close() # lock_file.txt and fuel_file.txt contains and holds the lock and engine mode statuses so they are saved after the screen is turned off # Tries to open the file -- if it isn't there it creates it with a default value if os.path.isfile(display_code_dir + "lock_file.txt"): fin = open(display_code_dir + "lock_file.txt", "rt") lock_status = fin.read() fin.close() else: fin = open(display_code_dir + "lock_file.txt", "w") fin.write('0') lock_status = '0' fin.close() if os.path.isfile(display_code_dir + "fuel_file.txt"): fin = open(display_code_dir + "fuel_file.txt", "rt") mode_num = fin.read().strip('\n') fin.close() else: fin = open(display_code_dir + "fuel_file.txt", "w") fin.write('2') mode_num = '2' fin.close() if os.path.isfile(display_code_dir + "arbitration_file.txt"): fin = open(display_code_dir + "arbitration_file.txt", "r+") stored_id = fin.read() print(stored_id) if stored_id == '': arb_id = '0xCFF41F2' arb_address = StringProperty(arb_id) fin.write(arb_id) fin.close() else: arb_id = stored_id arb_address = StringProperty(arb_id) fin.close() else: fin = open(display_code_dir + "arbitration_file.txt", "w") arb_id = '0xCFF41F2' fin.write(arb_id) arb_address = StringProperty(arb_id) fin.close() # Declaring variables and giving them data from the stored/extracted text files source_id = StringProperty(arb_id[7:9]) dest_id = StringProperty(arb_id[5:7]) #################################################################################################### # Determines what the current engine mode is (H2 or Diesel) and sets the initial value for the top right corner display zone #################################################################################################### if (mode_num == '0') or (mode_num == '1'): engine_mode = StringProperty(u'H\u2082 Mode ') alignment = StringProperty('right') mode_color = ListProperty([235 / 255, 150 / 255, 72 / 255, 1]) msg_data = [1, 0, 0, 0, 0, 0, 0, 0] elif mode_num == '2': engine_mode = StringProperty('Diesel Mode') alignment = StringProperty('center') mode_color = ListProperty([0.431, 0.431, 0.431, 1]) msg_data = [0, 0, 0, 0, 0, 0, 0, 0] #################################################################################################### # These are the scheduled functions -- functions that are called every delay (###, delay) seconds #################################################################################################### # This calls errorMsg every 2 seconds to constantly change the error notification text from "FAULT" to the error code, or if there is no error it sets the text to blank Clock.schedule_interval(errorMsg, 2) Clock.schedule_interval(isDusk, 5) # This checks the value of the engine mode number every 2 seconds and changes the notification text if needed Clock.schedule_interval(truckEngineMode, 2) # Starts Calvin's CAN message reading code in another thread so that it is constantly reading while the display is active a = Thread(target=msg_receiving) a.start() try: bus = can.interface.Bus(channel='can0', bustype='socketcan_native') except OSError: print('Cannot find PiCAN board.') Clock.schedule_once(bus_activator) pass toggle_msg = can.Message(arbitration_id=0xCFF41F2, data=msg_data, is_extended_id=True) try: task = bus.send_periodic(toggle_msg, 0.2) except NameError: Clock.schedule_once(bus_activator) pass #################################################################################################### # These are the functions that are used by the kivy side of the app -- they are defined here so that they can be accessed by the # .kv file #################################################################################################### # Runs the screen manager that sets everything in motion def build(self): # Clock.schedule_once(self.bus_activator) return MyScreenManager() # Called when the user hits the 'Truck Engine Mode' button def ModeSender(self): print(self.lock_status) print(self.mode_num) prev_mode = self.mode_num prev_data = self.msg_data # Clock.unschedule(self.toggle_try) # If the display is unlocked (lock_status == '0') it checks to see what the current engine mode is if self.lock_status == '0': # Depending on the current mode the CAN msg data is set to either 1 or 0 (for H2 mode and Diesel mode respectively) if self.mode_num == '2': self.msg_data = [1, 0, 0, 0, 0, 0, 0, 0] # Then it changes what the current mode number is (ie. it toggles the engine mode for the next time the button is pressed) self.mode_num = '0' else: self.msg_data = [0, 0, 0, 0, 0, 0, 0, 0] self.mode_num = '2' self.toggle_msg.data = self.msg_data self.toggle_msg.dlc = 8 try: self.task.modify_data(self.toggle_msg) except AttributeError: print('Unable to Change Message, Please Try Again') self.mode_num = prev_mode self.msg_data = prev_data return # Writing the current engine mode to a text file so that it is saved when the display is shut off fin = open(display_code_dir + "fuel_file.txt", "wt") fin.write(self.mode_num) fin.close() # Clock.schedule_once(truckEngineMode) def source_changer(self, new_id): if new_id == '': return try: int(new_id) except ValueError: print('This is not an integer value') else: no_caps = str(self.arb_id)[0:2] wo_source = str(self.arb_id)[2:7] if int(new_id) > 255: print('Inputted value is too high, 255 is the max input') return else: new_id = str(hex(int(new_id)))[2:] self.arb_id = (no_caps + wo_source.upper() + new_id.upper()) self.source_id = new_id fin = open(display_code_dir + "arbitration_file.txt", "wt") fin.write(self.arb_id) fin.close() self.arb_address = self.arb_id self.task.stop() self.toggle_msg = can.Message(arbitration_id=int(self.arb_id, 16), data=self.msg_data) self.task = self.bus.send_periodic(self.toggle_msg, 0.2) def destination_changer(self, new_id): cap = 2 ** 29 try: int(new_id) except ValueError: print('This is not an integer value') else: print('Input accepted') check = int(new_id) if check > (cap - 255): print('That was too large a number. The max input is: ' + str(cap - 255)) return else: self.dest_id = str(hex(int(new_id)))[2:] front_mid = self.arb_id[2:5] rear = self.arb_id[7:9] no_caps = self.arb_id[0:2] new_id = (str(hex(check)))[2:] self.arb_id = (no_caps + front_mid.upper() + new_id.upper() + rear.upper()) self.arb_address = self.arb_id fin = open(display_code_dir + "arbitration_file.txt", "wt") fin.write(self.arb_id) fin.close() self.task.stop() self.toggle_msg = can.Message(arbitration_id=int(self.arb_id, 16), data=self.msg_data) self.task = self.bus.send_periodic(self.toggle_msg, 0.2) def title_changer(self, cur_page): self.current_page = cur_page # Makes everything start if __name__ == '__main__': # Tells KIVY to open in fullscreen mode Config.set('graphics', 'fullscreen', '0') # Tells KIVY what keyboard to use (systemanddock is both physical and onscreen keyboards) Config.set('kivy', 'keyboard_mode', 'systemanddock') # Tells KIVY to use the custom keyboard layout named pinpad.json and located in the kivy data files Config.set('kivy', 'keyboard_layout', 'pinpad') # Actually sends all of the previously set config options to the KIVY config controller Config.write() # Runs the app class that controls the screen FuelGaugeApp().run()
1ffd0894295b38b7e81abf6941b285fe3b4f0e38
[ "Markdown", "Python" ]
2
Markdown
zahoov/Hydra_Display_RPi
335ae038e1d8b936a2acc6949769b847507aa9ec
b6b7ba58ef4421b809468e5adfd5c095cc3f15b7
refs/heads/master
<repo_name>breakmo/AutoZoning<file_sep>/extract_zones.py """ Scientific articles come in the form of sections or zones. The code below tries to segment/decompose the text into zones. Some portions of the code are taken refers sentence classification by '<NAME>ic' and '<NAME>' [https://github.com/vdragan1993/sentence-classification] Author: <NAME> Github: https://github.com/yogeshhk """ import os import os.path import re from nltk import word_tokenize from nltk.corpus import stopwords import gensim import pandas as pd import numpy as np from sklearn.linear_model import LogisticRegressionCV, SGDClassifier from sklearn.naive_bayes import GaussianNB from sklearn import svm from sklearn.metrics import confusion_matrix, accuracy_score stopwords = set(stopwords.words('english')) def read_directory(directory): """ Lists all file paths from given directory """ ret_val = [] for file in os.listdir(directory): if file.endswith(".txt"): ret_val.append(str(directory) + "/" + str(file)) return ret_val def read_file(path): """ Reads all lines from file on given path """ f = open(path, "r") read = f.readlines() ret_val = [] for line in read: if line.startswith("#"): pass else: ret_val.append(line) return ret_val def read_line(line): """ Returns sentence category and sentence in given line """ splits = [] s_category = "" sentence = "" if "\t" in line: splits = line.split("\t") s_category = splits[0] sentence = splits[1].lower() else: splits = line.split(" ") s_category = splits[0] sentence = line[len(s_category)+1:].lower() sentence = " ".join([word for word in word_tokenize(sentence) if word not in stopwords]) # for sw in stopwords: # sentence = sentence.replace(sw, "") pattern = re.compile("[^\w']") sentence = pattern.sub(' ', sentence) # Any non-characters (here ^ is for negation and not for the start) replace with white space sentence = re.sub(' +', ' ', sentence) # If more than one spaces, make them just one space return s_category, sentence def read_testdata(input_folder): """ Maps each sentence to it's category """ test_folder = read_directory(input_folder) t_sentences = [] t_categories = [] for file in test_folder: lines = read_file(file) for line in lines: c, s = read_line(line) if s.endswith('\n'): s = s[:-1] t_sentences.append(s) t_categories.append(c) return t_categories, t_sentences def comput_sentence2vec(model,sentence): return np.array([np.mean([model[w] for w in sentence.split() if w in model], axis=0)]) def fill_dataframe(sentences_vecs, categories_training): vec_len = len(sentences_vecs[0][0]) col_names = [ "Feature_" + str(i) for i in range(1, vec_len+1)] + ["Target"] df = pd.DataFrame(columns=col_names) for i in range(len(sentences_vecs)): vec = sentences_vecs[i] # if i > 500: # break try: ndarray = vec[0] len_array = len(ndarray) print(".{}.".format(i)) df.loc[i,"Target"] = categories_training[i]#).replace(map_to_int) for j in range(len_array): df.loc[i,col_names[j]] = ndarray[j] except: print("Error at {} sentence...".format(ndarray)) continue # Target label encoding targets = df["Target"].unique() map_to_int = {name: n for n, name in enumerate(targets)} df["Target"] = df["Target"].replace(map_to_int) return df def extract_zones_deep_learning(): """ Gensim method using Word2Vec """ # prepare training and test data categories_training, sentences_training = read_testdata("training_set") categories_testing, sentences_test = read_testdata("test_set") all_sentences_list = [word_tokenize(sentence) for sentence in sentences_training] # trains here itself. if you get more sentences, use "train" method modelword = gensim.models.Word2Vec(all_sentences_list,sg=1) modelword.init_sims() sentences_training_vecs = [comput_sentence2vec(modelword,sentence) for sentence in sentences_training] sentences_testing_vecs = [comput_sentence2vec(modelword,sentence) for sentence in sentences_test] save_training_df_file = "training_word2vec.csv" if os.path.exists(save_training_df_file): df_training = pd.read_pickle(save_training_df_file) else: df_training = fill_dataframe(sentences_training_vecs, categories_training) df_training.to_pickle(save_training_df_file) save_testing_df_file = "testing_word2vec.csv" if os.path.exists(save_testing_df_file): df_testing = pd.read_pickle(save_testing_df_file) else: df_testing = fill_dataframe(sentences_testing_vecs, categories_testing) df_testing.to_pickle(save_testing_df_file) features = ["Feature_" + str(i) for i in range(1, 100 + 1)] # Default word2vec size is 100 train_Y = df_training["Target"] train_X = df_training[features] test_X = df_testing[features] test_Y = df_testing["Target"] classifiers = [] classifiers.append(("LogisticRegressionCV", LogisticRegressionCV())) classifiers.append(("NaiveBayesClassifier", GaussianNB())) # THIS DOES WORSE as it does not like -ve values in word2vec classifiers.append(("SVM", svm.SVC())) classifiers.append(("SGDClassifier", SGDClassifier(loss='log', penalty='l1'))) for name, clf in classifiers: print("----------------------------------------") print("Testing with " + name) clf.fit(train_X, train_Y) ypred_train = clf.predict(train_X) ypred_test = clf.predict(test_X) train_acc = accuracy_score(train_Y, ypred_train) print('Training Accuracy score: {}'.format(train_acc)) test_acc = accuracy_score(test_Y, ypred_test) print('Testing Accuracy score: {}'.format(test_acc)) diff = ypred_test - test_Y rsqr = np.mean(diff * diff) print("Mean squared error: {}".format(rsqr)) if __name__ == "__main__": # extract_zones_without_features() extract_zones_deep_learning()
fcc3fb68c0fe751f8bb66bbe5c72740913c55e9d
[ "Python" ]
1
Python
breakmo/AutoZoning
70944271863ca873a081b68516c1e89059a185f6
33cbedc1e12b69c338bd701c96818a3948a20f98
refs/heads/master
<repo_name>anycollect/anycollect<file_sep>/anycollect-core/src/main/java/io/github/anycollect/core/impl/matcher/RuleListQueryMatcher.java package io.github.anycollect.core.impl.matcher; import io.github.anycollect.core.api.internal.QueryMatcher; import io.github.anycollect.core.api.query.Query; import io.github.anycollect.core.api.target.Target; import javax.annotation.Nonnull; import javax.annotation.concurrent.Immutable; import java.util.ArrayList; import java.util.List; @Immutable public class RuleListQueryMatcher implements QueryMatcher { private final List<MatchRule> rules; public RuleListQueryMatcher(@Nonnull final List<MatchRule> rules) { this.rules = new ArrayList<>(rules); } @Override public int getPeriodInSeconds(@Nonnull final Target target, @Nonnull final Query query, final int defaultPeriod) { int minPeriod = -1; for (MatchRule rule : rules) { if (rule.match(target, query)) { if (minPeriod == -1) { minPeriod = rule.getPeriod(); } else if (rule.getPeriod() != -1) { minPeriod = Math.min(minPeriod, rule.getPeriod()); } } } return minPeriod; } } <file_sep>/anycollect-test-utils/anycollect-extension-test/src/main/java/io/github/anycollect/test/TestContext.java package io.github.anycollect.test; import io.github.anycollect.assertj.SampleAssert; import io.github.anycollect.core.api.Reader; import io.github.anycollect.core.api.Router; import io.github.anycollect.extensions.Instance; import io.github.anycollect.extensions.annotations.InjectMode; import io.github.anycollect.extensions.context.ContextImpl; import io.github.anycollect.extensions.context.DelegatingContext; import io.github.anycollect.extensions.context.ExtendableContext; import io.github.anycollect.extensions.loaders.ClassPathManifestScanDefinitionLoader; import io.github.anycollect.extensions.loaders.InstanceLoader; import io.github.anycollect.extensions.loaders.snakeyaml.YamlInstanceLoader; import io.github.anycollect.extensions.scope.Scope; import io.github.anycollect.extensions.scope.SimpleScope; import io.github.anycollect.extensions.substitution.VarSubstitutor; import io.github.anycollect.metric.Sample; import io.github.anycollect.metric.Tags; import org.apache.commons.io.FileUtils; import javax.annotation.Nonnull; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.List; import java.util.stream.Collectors; public final class TestContext extends DelegatingContext { private final Scope rootScope = new SimpleScope(null, "root"); private final ContextImpl context = new ContextImpl(); public TestContext(final String manifest) throws FileNotFoundException { ClassPathManifestScanDefinitionLoader loader = new ClassPathManifestScanDefinitionLoader(); loader.load(context); File config = FileUtils.getFile("src", "test", "resources", manifest); InstanceLoader instanceLoader = new YamlInstanceLoader(rootScope, new FileReader(config), VarSubstitutor.EMPTY); instanceLoader.load(context); } public Instance getInstance(final String name) { return getInstances().stream() .filter(instance -> instance.getInstanceName().equals(name)) .findFirst().get(); } public Instance getInstance(final Class<?> type) { List<Instance> instances = getInstances(type); if (instances.size() != 1) { throw new IllegalArgumentException("there are " + instances.size() + " instances for " + type); } return instances.get(0); } public List<Instance> getInstances(final Class<?> type) { return getInstances().stream() .filter(instance -> instance.getDefinition().getContracts().stream().anyMatch(contract -> contract.isAssignableFrom(type))) .collect(Collectors.toList()); } @Override protected ExtendableContext getContext() { return context; } public Interceptor intercept(@Nonnull final String readerId) { Reader reader = (Reader) getInstance(readerId).resolve(); String interceptorId = "interceptor"; Interceptor interceptor = new InterceptorImpl(interceptorId); addInstance(new Instance(getDefinition(InterceptorImpl.NAME), interceptorId, interceptor, InjectMode.MANUAL, rootScope, false )); String routerId = "router"; Router router = new TestRouter(reader, interceptor); addInstance(new Instance(getDefinition(TestRouter.NAME), routerId, router, InjectMode.MANUAL, rootScope, false )); return new InterceptorWrapper(interceptor, router); } private static class InterceptorWrapper implements Interceptor { private final Interceptor interceptor; private final Router router; InterceptorWrapper(final Interceptor interceptor, final Router router) { this.interceptor = interceptor; this.router = router; } @Override public void start() { router.start(); } @Override public void stop() { router.stop(); } @Override public SampleAssert intercepted(final String key) { return interceptor.intercepted(key); } @Override public SampleAssert intercepted(final String key, final Tags tags) { return interceptor.intercepted(key, tags); } @Override public SampleAssert intercepted(final String key, final Tags tags, final Tags meta) { return interceptor.intercepted(key, tags, meta); } @Override public void write(@Nonnull final List<? extends Sample> metrics) { interceptor.write(metrics); } @Override public String getId() { return interceptor.getId(); } } } <file_sep>/extensions/readers/anycollect-jmx-reader/src/main/java/io/github/anycollect/readers/jmx/server/JmxConnection.java package io.github.anycollect.readers.jmx.server; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.management.MBeanServerConnection; import javax.management.Notification; import javax.management.NotificationListener; import javax.management.remote.JMXConnectionNotification; import javax.management.remote.JMXConnector; import java.io.Closeable; import java.io.IOException; import java.lang.management.ManagementFactory; import java.util.Objects; import java.util.concurrent.CopyOnWriteArrayList; public final class JmxConnection implements Closeable { @Nullable private final JMXConnector connector; @Nonnull private final MBeanServerConnection connection; @SuppressWarnings("FieldCanBeLocal") private final ConnectionListener connectionListener = new ConnectionListener(); private final CopyOnWriteArrayList<JmxConnectionDropListener> listeners = new CopyOnWriteArrayList<>(); private volatile boolean destroyed = false; private volatile boolean closed = false; public JmxConnection(@Nullable final JMXConnector connector, @Nonnull final MBeanServerConnection connection) { Objects.requireNonNull(connection, "connection must not be null"); this.connector = connector; this.connection = connection; if (connector != null) { this.connector.addConnectionNotificationListener(connectionListener, null, null); } } public static JmxConnection local() { return new JmxConnection(null, ManagementFactory.getPlatformMBeanServer()); } @Nonnull public MBeanServerConnection getConnection() { return connection; } public void markAsDestroyed() { this.destroyed = true; } public boolean isAlive() { return !destroyed; } public boolean isClosed() { return closed; } public void onConnectionDrop(@Nonnull final JmxConnectionDropListener listener) { this.listeners.add(listener); } @Override public void close() throws IOException { if (closed) { return; } if (connector != null) { connector.close(); } closed = true; } private class ConnectionListener implements NotificationListener { @Override public void handleNotification(final Notification notification, final Object handback) { if (notification instanceof JMXConnectionNotification) { JMXConnectionNotification connectionNotification = (JMXConnectionNotification) notification; if (JMXConnectionNotification.CLOSED.equals(connectionNotification.getType()) || JMXConnectionNotification.FAILED.equals(connectionNotification.getType())) { for (JmxConnectionDropListener listener : listeners) { listener.onDrop(); } } } } } } <file_sep>/extensions/common/anycollect-common-expression/src/main/java/io/github/anycollect/extensions/common/expression/ast/visitor/ExpressionNodeVisitor.java package io.github.anycollect.extensions.common.expression.ast.visitor; import io.github.anycollect.extensions.common.expression.ast.*; public interface ExpressionNodeVisitor { static ExpressionNodeVisitor reset() { return ResetVariables.INSTANCE; } default void visit(ConstantExpressionNode constant) { } default void visit(VariableExpressionNode variable) { } default void visit(ComplexStringExpressionNode complex) { } default void visit(ArgumentExpressionNode argument) { } default void visit(ArgumentsExpressionNode arguments) { } default void visit(FilterExpressionNode filter) { } default void visit(PipeExpressionNode pipe) { } } <file_sep>/anycollect-extension-system/src/main/java/io/github/anycollect/extensions/dependencies/ConfigDependency.java package io.github.anycollect.extensions.dependencies; import io.github.anycollect.extensions.di.InjectionPoint; import lombok.EqualsAndHashCode; import java.util.Objects; @EqualsAndHashCode public final class ConfigDependency implements Dependency { private final ConfigDefinition definition; private final Object object; public ConfigDependency(final ConfigDefinition definition, final Object object) { Objects.requireNonNull(definition, "definition must not be null"); if (object == null) { if (!definition.isOptional()) { throw new IllegalArgumentException("config must be passed"); } } else { if (!definition.getParameterType().isAssignableFrom(object.getClass())) { throw new IllegalArgumentException("config must be assignable from " + definition.getParameterType() + ", given: " + object.getClass()); } } this.definition = definition; this.object = object; } @Override public InjectionPoint inject() { return new InjectionPoint(object, definition.getPosition()); } } <file_sep>/anycollect-extension-system/src/main/java/io/github/anycollect/extensions/context/ContextImpl.java package io.github.anycollect.extensions.context; import io.github.anycollect.extensions.Definition; import io.github.anycollect.extensions.Instance; import io.github.anycollect.extensions.annotations.InjectMode; import io.github.anycollect.extensions.scope.Scope; import io.github.anycollect.extensions.scope.SimpleScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.*; import java.util.function.Predicate; public final class ContextImpl implements ExtendableContext { private static final Logger LOG = LoggerFactory.getLogger(ContextImpl.class); private final Map<String, Definition> definitions; private final List<Instance> instances; private final Scope auto = new SimpleScope(null, "auto"); public ContextImpl() { this(Collections.emptyList()); } public ContextImpl(@Nonnull final Collection<Definition> definitions) { this.instances = new ArrayList<>(); this.definitions = new HashMap<>(); for (Definition definition : definitions) { addDefinition(definition); } } @Override public boolean hasInstance(@Nonnull final String name, @Nonnull final Scope scope) { return getInstance(name, scope) != null; } @Nullable @Override public Instance getInstance(@Nonnull final Class<?> type, @Nonnull final Scope scope) { return getInstance(instance -> instance.getDefinition().getContracts().contains(type) && instance.getInjectMode() == InjectMode.AUTO, scope); } @Nullable @Override public Instance getInstance(@Nonnull final String name, @Nonnull final Scope scope) { return getInstance(instance -> instance.getInstanceName().equals(name), scope); } @Override public boolean hasDefinition(@Nonnull final String name) { return definitions.containsKey(name); } @Nullable @Override public Definition getDefinition(@Nonnull final String name) { return definitions.get(name); } @Override public List<Instance> getInstances() { return instances; } @Override public Collection<Definition> getDefinitions() { return definitions.values(); } private Instance getInstance(@Nonnull final Predicate<Instance> filter, @Nonnull final Scope scope) { Instance candidate = null; for (Instance instance : instances) { if (filter.test(instance)) { if (instance.getScope().isParent(scope)) { if (candidate == null) { candidate = instance; continue; } if (instance.getScope().distance(scope) < candidate.getScope().distance(scope)) { candidate = instance; } } else if (instance.getScope().equals(auto)) { if (candidate == null) { candidate = instance; } } } } return candidate; } @Override public void addInstance(@Nonnull final Instance instance) { // TODO check if name is unique in the scope this.instances.add(instance); } @Override public void addDefinition(@Nonnull final Definition definition) { definitions.put(definition.getName(), definition); if (definition.isAutoLoad()) { LOG.debug("auto load instance of {}", definition.getName()); addInstance(definition.createAutoInstance(auto)); } } } <file_sep>/anycollect-extension-system/src/test/java/io/github/anycollect/extensions/samples/ExtensionPointWithId.java package io.github.anycollect.extensions.samples; import io.github.anycollect.extensions.annotations.ExtCreator; import io.github.anycollect.extensions.annotations.Extension; import io.github.anycollect.extensions.annotations.InstanceId; @Extension(name = "WithId", contracts = SampleExtensionPoint.class) public class ExtensionPointWithId implements SampleExtensionPoint { private final String id; @ExtCreator public ExtensionPointWithId(@InstanceId final String id) { this.id = id; } public String getId() { return id; } } <file_sep>/anycollect-core/src/main/java/io/github/anycollect/core/impl/router/adapters/WriterAdapter.java package io.github.anycollect.core.impl.router.adapters; import io.github.anycollect.core.api.Writer; import io.github.anycollect.core.impl.router.AbstractRouterNode; import io.github.anycollect.core.impl.router.MetricConsumer; import io.github.anycollect.metric.Sample; import javax.annotation.Nonnull; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; public final class WriterAdapter extends AbstractRouterNode implements MetricConsumer { private final Writer writer; private final AtomicBoolean stopped = new AtomicBoolean(false); public WriterAdapter(@Nonnull final Writer writer) { super(writer.getId()); this.writer = writer; } @Override public void consume(@Nonnull final List<? extends Sample> samples) { if (!stopped.get()) { this.writer.write(samples); } } @Override public void stop() { stopped.set(true); } } <file_sep>/extensions/readers/anycollect-jmx-reader/src/test/java/io/github/anycollect/readers/jmx/utils/HistogramTestMBean.java package io.github.anycollect.readers.jmx.utils; public interface HistogramTestMBean { double getMin(); double getMax(); double getMean(); double getStdDev(); double get50thPercentile(); double get75thPercentile(); double get90thPercentile(); double get95thPercentile(); double get99thPercentile(); } <file_sep>/anycollect-meter-api/src/main/java/io/github/anycollect/meter/api/BaseMeterBuilder.java package io.github.anycollect.meter.api; import io.github.anycollect.metric.Key; import javax.annotation.Nonnull; abstract class BaseMeterBuilder<T extends BaseMeterBuilder<T>> extends BaseBuilder<T> { BaseMeterBuilder(@Nonnull final Key key) { key(key); } /** * Adds source class meta tag * * @param source - class that creates and uses meter * @return current builder */ public T meta(@Nonnull final Class<?> source) { return super.meta("class", source.getName()); } } <file_sep>/extensions/readers/anycollect-jmx-reader/src/main/java/io/github/anycollect/readers/jmx/server/JavaApp.java package io.github.anycollect.readers.jmx.server; import io.github.anycollect.core.api.job.Job; import io.github.anycollect.core.api.target.Target; import io.github.anycollect.core.exceptions.ConnectionException; import io.github.anycollect.core.exceptions.QueryException; import io.github.anycollect.meter.api.MeterRegistry; import io.github.anycollect.metric.Tags; import io.github.anycollect.readers.jmx.query.JmxQuery; import io.github.anycollect.readers.jmx.query.operations.QueryOperation; import io.github.anycollect.readers.jmx.server.pool.JmxConnectionPool; import javax.annotation.Nonnull; public interface JavaApp extends Target { static JavaApp create(@Nonnull String id, @Nonnull Tags tags, @Nonnull Tags meta, @Nonnull JmxConnectionPool pool, @Nonnull MeterRegistry registry) { return new PooledJavaApp(id, tags, meta, pool, registry); } @Nonnull default Job bind(@Nonnull JmxQuery query) { return query.bind(this); } <T> T operate(@Nonnull QueryOperation<T> operation) throws QueryException, ConnectionException; } <file_sep>/anycollect-core/src/test/java/io/github/anycollect/core/impl/pull/DesiredStateUpdateJobTest.java package io.github.anycollect.core.impl.pull; import io.github.anycollect.core.api.internal.DesiredStateProvider; import io.github.anycollect.core.api.internal.State; import io.github.anycollect.core.impl.TestQuery; import io.github.anycollect.core.impl.TestTarget; import org.junit.jupiter.api.Test; import static org.mockito.Mockito.*; class DesiredStateUpdateJobTest { @Test @SuppressWarnings("unchecked") void mustUpdateManagerStateFromProvider() { DesiredStateProvider<TestTarget, TestQuery> provider = mock(DesiredStateProvider.class); DesiredStateManager<TestTarget, TestQuery> manager = mock(DesiredStateManager.class); DesiredStateUpdateJob<TestTarget, TestQuery> job = new DesiredStateUpdateJob<>(provider, manager); State<TestTarget, TestQuery> state = mock(State.class); when(provider.current()).thenReturn(state); job.run(); verify(manager, times(1)).update(state); } }<file_sep>/extensions/common/anycollect-common-expression/src/main/java/io/github/anycollect/extensions/common/expression/ast/ComplexStringExpressionNode.java package io.github.anycollect.extensions.common.expression.ast; import io.github.anycollect.extensions.common.expression.EvaluationException; import io.github.anycollect.extensions.common.expression.ast.visitor.ExpressionNodeVisitor; import lombok.ToString; import java.util.ArrayList; import java.util.List; @ToString(doNotUseGetters = true) public final class ComplexStringExpressionNode implements ValueExpressionNode { private final List<ValueExpressionNode> parts; public ComplexStringExpressionNode() { this.parts = new ArrayList<>(); } public void add(final ValueExpressionNode part) { this.parts.add(part); } @Override public String getValue() throws EvaluationException { StringBuilder accumulator = new StringBuilder(); for (ValueExpressionNode part : parts) { accumulator.append(part.getValue()); } return accumulator.toString(); } @Override public boolean isResolved() { return parts.stream().allMatch(ValueExpressionNode::isResolved); } @Override public void accept(final ExpressionNodeVisitor visitor) { visitor.visit(this); for (ValueExpressionNode part : parts) { part.accept(visitor); } } } <file_sep>/anycollect-core-api/src/main/java/io/github/anycollect/core/manifest/ExtensionManifest.java package io.github.anycollect.core.manifest; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import javax.annotation.Nonnull; public final class ExtensionManifest { private final String className; @JsonCreator public ExtensionManifest(@JsonProperty("class") @Nonnull final String className) { this.className = className; } public String getClassName() { return className; } } <file_sep>/extensions/common/anycollect-common-expression/src/main/java/io/github/anycollect/extensions/common/expression/ast/ValueExpressionNode.java package io.github.anycollect.extensions.common.expression.ast; import io.github.anycollect.extensions.common.expression.EvaluationException; public interface ValueExpressionNode extends ExpressionNode { String getValue() throws EvaluationException; boolean isResolved(); } <file_sep>/extensions/readers/anycollect-jmx-reader/src/test/java/io/github/anycollect/readers/jmx/config/CredentialsTest.java package io.github.anycollect.readers.jmx.config; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; class CredentialsTest { @Test void propertiesTest() { Credentials credentials = new Credentials("user", "pass"); assertThat(credentials.getUsername()).isEqualTo("user"); assertThat(credentials.getPassword()).isEqualTo("<PASSWORD>"); } }<file_sep>/anycollect-assembly/bin/anycollect.sh #!/bin/bash ACTION=status ENABLE_JFR=false ENABLE_DEBUG=false DEBUG_PORT=5005 while (( "$#" )); do case "$1" in -a|--additional-anycollect-args) ADDITIONAL_ANYCOLLECT_ARGS=$2 shift 2 ;; --enable-jfr) ENABLE_JFR=$2 shift 2 ;; --debug) ENABLE_DEBUG=true DEBUG_PORT=$2 shift 2 ;; --log-level) LOG_LEVEL=$2 shift 2 ;; --start) ACTION=start shift ;; --status) ACTION=status shift ;; --stop) ACTION=stop shift ;; --restart) ACTION=restart shift ;; --run) ACTION=run shift ;; --print-exec-line) ACTION=printExecLine shift ;; --) # end argument parsing shift break ;; -*|--*=) # unsupported flags echo "Error: Unsupported flag $1" >&2 exit 1 ;; esac done SCRIPT_FILE=$(realpath $0) ANYCOLLECT_HOME=${SCRIPT_FILE%/bin/*} # Java JAVA_HOME=${JAVA_HOME:-"/usr"} ANYCOLLECT_JAR=${ANYCOLLECT_JAR:-"${ANYCOLLECT_HOME}/lib/anycollect.jar"} JAVA_OPTS=${JAVA_OPTS:-""} JAVA=${JAVA:-"${JAVA_HOME}/bin/java"} # Java Flight Recorder if [[ ${ENABLE_JFR} = true ]]; then JFR_OPTS="-XX:+UnlockCommercialFeatures -XX:+FlightRecorder" JAVA_OPTS="${JAVA_OPTS} ${JFR_OPTS}" fi # Debug if [[ ${ENABLE_DEBUG} = true ]]; then DEBUG_OPTS="-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=${DEBUG_PORT}" JAVA_OPTS="${JAVA_OPTS} ${DEBUG_OPTS}" fi # Class-Path ANYCOLLECT_EXT=${ANYCOLLECT_EXT:-"${ANYCOLLECT_HOME}/extensions/*"} TOOLS_JAR="${JAVA_HOME}/lib/tools.jar" CLASSPATH=${CLASSPATH:-"${TOOLS_JAR}:${ANYCOLLECT_EXT}:${ANYCOLLECT_JAR}"} # pid PID_FILE=${PID_FILE:-"${ANYCOLLECT_HOME}/var/run/anycollect.pid"} PID_FILE_DIR=${PID_FILE%/*} mkdir -p PID_FILE_DIR # AnyCollect LOG_DIR=${LOG_DIR:-"${ANYCOLLECT_HOME}/logs"} LOG_LEVEL=${LOG_LEVEL:-"debug"} ANYCOLLECT_OPTS=${ANYCOLLECT_OPTS:-"-Danycollect.log.dir=${LOG_DIR} -Danycollect.log.level=${LOG_LEVEL}"} ANYCOLLECT_CONF_FILE=${ANYCOLLECT_CONF_FILE:-"${ANYCOLLECT_HOME}/etc/anycollect.yaml"} LOGBACK_CONF_FILE=${LOGBACK_CONF_FILE:-"${ANYCOLLECT_HOME}/etc/logback.xml"} ADDITIONAL_ANYCOLLECT_ARGS=${ADDITIONAL_ANYCOLLECT_ARGS:-""} ANYCOLLECT_ARGS=${ANYCOLLECT_ARGS:-"--logback-conf=${LOGBACK_CONF_FILE} --pid-file=${PID_FILE} ${ADDITIONAL_ANYCOLLECT_ARGS}"} MAIN_CLASS="io.github.anycollect.Init" getAnyCollectPid() { if [[ -f ${PID_FILE} ]]; then echo $(cat ${PID_FILE}) fi } # JMX JMX_PORT=${JMX_PORT:-"9797"} MONITOR_OPTS=${MONITOR_OPTS:-"-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.local.only=true -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.port=${JMX_PORT}"} # GC HEAP_INIT=${HEAP_INIT:-"256m"} HEAP_MAX=${HEAP_MAX:-"512m"} GC_OPTS=${GC_OPTS:-"-Xms${HEAP_INIT} -Xmx${HEAP_MAX}"} createExecLine() { echo "${JAVA} -server ${JAVA_OPTS} ${GC_OPTS} ${MONITOR_OPTS} ${ANYCOLLECT_OPTS} -cp ${CLASSPATH} ${MAIN_CLASS} ${ANYCOLLECT_ARGS}" } assertAnyCollectIsNotRunning() { pid=$(getAnyCollectPid) if [[ ! -z ${pid} ]]; then echo "AnyCollect is running, pid ${pid}" exit 1 fi } start() { assertAnyCollectIsNotRunning nohup sh -c "$(createExecLine) &" } run() { assertAnyCollectIsNotRunning sh -c "$(createExecLine)" } printExecLine() { echo $(createExecLine) } status() { pid=$(getAnyCollectPid) if [[ ! -z ${pid} ]]; then echo "UP $pid" else echo "DOWN" fi } stop() { pid=$(getAnyCollectPid) if [[ ! -z ${pid} ]]; then kill -15 ${pid} while (true); do ps -p ${pid} >/dev/null if [[ $? -eq 0 ]]; then echo "Waiting for graceful shutdown, pid=${pid}" else echo "AnyCollect has been stopped gracefully" break fi sleep 1 done else echo "AnyCollect was not running" fi } restart() { stop start } case ${ACTION} in start) start ;; stop) stop ;; restart) restart ;; run) run ;; status) status ;; printExecLine) printExecLine ;; *) echo $"Usage: $0 {start|stop|restart|run|status}" ;; esac exit 0<file_sep>/anycollect-core/src/main/java/io/github/anycollect/core/impl/pull/separate/ConcurrencyRules.java package io.github.anycollect.core.impl.pull.separate; import io.github.anycollect.core.api.target.Target; import lombok.ToString; import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.List; @ToString public final class ConcurrencyRules implements ConcurrencyRule { private final List<ConcurrencyRule> rules; public static Builder builder() { return new Builder(); } private ConcurrencyRules(final Builder builder) { this.rules = new ArrayList<>(builder.rules); } @Override public int getPoolSize(@Nonnull final Target target, final int fallback) { for (ConcurrencyRule rule : rules) { int poolSize = rule.getPoolSize(target, -1); if (poolSize != -1) { return poolSize; } } return fallback; } public static final class Builder { private final List<ConcurrencyRule> rules = new ArrayList<>(); public Builder withRule(@Nonnull final ConcurrencyRule rule) { this.rules.add(rule); return this; } public Builder withRules(@Nonnull final List<ConcurrencyRule> list) { this.rules.addAll(list); return this; } public ConcurrencyRules build() { return new ConcurrencyRules(this); } } } <file_sep>/anycollect-meter-api/src/main/java/io/github/anycollect/meter/api/MeterId.java package io.github.anycollect.meter.api; import io.github.anycollect.metric.Key; import io.github.anycollect.metric.Tags; import org.apiguardian.api.API; import javax.annotation.Nonnull; @API(since = "0.1.0", status = API.Status.EXPERIMENTAL) public interface MeterId { @Nonnull Key getKey(); @Nonnull Tags getTags(); @Nonnull Tags getMeta(); @Nonnull String getUnit(); } <file_sep>/extensions/readers/anycollect-jmx-reader/src/main/java/io/github/anycollect/readers/jmx/discovery/CurrentApp.java package io.github.anycollect.readers.jmx.discovery; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import io.github.anycollect.core.api.target.ServiceDiscovery; import io.github.anycollect.extensions.annotations.ExtConfig; import io.github.anycollect.extensions.annotations.ExtCreator; import io.github.anycollect.extensions.annotations.ExtDependency; import io.github.anycollect.extensions.annotations.Extension; import io.github.anycollect.meter.api.MeterRegistry; import io.github.anycollect.metric.Tags; import io.github.anycollect.readers.jmx.server.JavaApp; import io.github.anycollect.readers.jmx.server.JmxConnection; import io.github.anycollect.readers.jmx.server.JmxConnectionFactory; import io.github.anycollect.readers.jmx.server.pool.JmxConnectionPool; import io.github.anycollect.readers.jmx.server.pool.JmxConnectionPoolFactory; import io.github.anycollect.readers.jmx.server.pool.impl.CommonsJmxConnectionPoolFactory; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.lang.management.ManagementFactory; import java.util.Collections; import java.util.Set; @Extension(name = "CurrentApp", contracts = ServiceDiscovery.class) public final class CurrentApp implements ServiceDiscovery<JavaApp> { private static final JmxConnectionFactory JMX_CONNECTION_FACTORY = new JmxConnectionFactory() { @Nonnull @Override public JmxConnection createJmxConnection() { return new JmxConnection(null, ManagementFactory.getPlatformMBeanServer()); } }; private final Set<JavaApp> app; @ExtCreator public CurrentApp(@ExtDependency(qualifier = "registry") @Nonnull final MeterRegistry registry, @ExtConfig @Nonnull final Config config) { JmxConnectionPoolFactory poolFactory = new CommonsJmxConnectionPoolFactory(); JmxConnectionPool pool = poolFactory.create(JMX_CONNECTION_FACTORY); app = Collections.singleton(JavaApp.create(config.targetId, config.tags, config.meta, pool, registry)); } @Override public Set<JavaApp> discover() { return app; } public static class Config { private final String targetId; private final Tags tags; private final Tags meta; @JsonCreator public Config(@JsonProperty(value = "targetId", required = true) @Nonnull final String targetId, @JsonProperty("tags") @Nullable final Tags tags, @JsonProperty("meta") @Nullable final Tags meta) { this.targetId = targetId; this.tags = tags != null ? tags : Tags.empty(); this.meta = meta != null ? meta : Tags.empty(); } } } <file_sep>/anycollect-extension-system/src/test/java/io/github/anycollect/extensions/loaders/snakeyaml/YamlInstanceLoaderTest.java package io.github.anycollect.extensions.loaders.snakeyaml; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException; import io.github.anycollect.core.exceptions.ConfigurationException; import io.github.anycollect.extensions.Definition; import io.github.anycollect.extensions.Instance; import io.github.anycollect.extensions.context.ContextImpl; import io.github.anycollect.extensions.dependencies.ConfigDefinition; import io.github.anycollect.extensions.dependencies.MultiDependencyDefinition; import io.github.anycollect.extensions.dependencies.SingleDependencyDefinition; import io.github.anycollect.extensions.exceptions.MissingRequiredPropertyException; import io.github.anycollect.extensions.scope.SimpleScope; import io.github.anycollect.extensions.substitution.VarSubstitutor; import io.github.anycollect.extensions.utils.ConstrictorUtils; import io.github.anycollect.extensions.utils.TestConfigUtils; import lombok.EqualsAndHashCode; import org.junit.jupiter.api.*; import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; class YamlInstanceLoaderTest { private static String selfRefYaml; private static String selfRefsYaml; private static String refToUnknownDependencyYaml; private static String refsToUnknownDependencyYaml; private static String loadScalarYaml; private static String loadSequenceYaml; private static String unsupportedConfigYaml; private static String wrongConfigYaml; @BeforeAll static void setUpFiles() throws IOException { List<String> wrongRefConfigs = TestConfigUtils.splitFileBySeparator( "/config/anycollect-wrong-ref.yaml", "###"); selfRefYaml = wrongRefConfigs.get(0); selfRefsYaml = wrongRefConfigs.get(1); refToUnknownDependencyYaml = wrongRefConfigs.get(2); refsToUnknownDependencyYaml = wrongRefConfigs.get(3); List<String> wrongLoadConfigs = TestConfigUtils.splitFileBySeparator( "/config/anycollect-wrong-load.yaml", "###"); loadScalarYaml = wrongLoadConfigs.get(0); loadSequenceYaml = wrongLoadConfigs.get(1); List<String> illegalConfigs = TestConfigUtils.splitFileBySeparator( "/config/anycollect-illegal-configure.yaml", "###"); unsupportedConfigYaml = illegalConfigs.get(0); wrongConfigYaml = illegalConfigs.get(1); } private List<Definition> definitions; @BeforeEach void setUp() { definitions = new ArrayList<>(); Definition ext1 = Definition.builder() .withName("Ext1") .withExtension(ExtPoint1.class, ConstrictorUtils.createFor(Ext1.class)) .build(); Definition ext2 = Definition.builder() .withName("Ext2") .withExtension(ExtPoint2.class, ConstrictorUtils.createFor(Ext2.class)) .build(); Definition ext3 = Definition.builder() .withName("Ext3") .withExtension(ExtPoint3.class, ConstrictorUtils.createFor(Ext3.class, ExtPoint1.class, List.class, Ext3Config.class)) .withSingleDependency(new SingleDependencyDefinition("ext1", ExtPoint1.class, false, 0)) .withMultiDependency(new MultiDependencyDefinition("ext2", ExtPoint2.class, false, 1)) .withConfig(new ConfigDefinition(Ext3Config.class, true, 2)) .build(); definitions.add(ext1); definitions.add(ext2); definitions.add(ext3); } @Test @DisplayName("complex configuration test") void complexTest() throws IOException { List<Instance> instances = loadFile("anycollect.yaml"); Definition ext1def = definitions.get(0); Instance ext1 = instances.get(0); assertThat(ext1.getInstanceName()).isEqualTo("ext1"); assertThat(ext1.getDefinition()).isSameAs(ext1def); Definition ext2def = definitions.get(1); Instance ext2_1 = instances.get(1); assertThat(ext2_1.getInstanceName()).isEqualTo("ext2_1"); assertThat(ext2_1.getDefinition()).isSameAs(ext2def); Instance ext2_2 = instances.get(2); assertThat(ext2_2.getInstanceName()).isEqualTo("ext2_2"); assertThat(ext2_2.getDefinition()).isSameAs(ext2def); Definition ext3def = definitions.get(2); Instance ext3 = instances.get(3); assertThat(ext3.getInstanceName()).isEqualTo("Ext3"); Ext3 ext3Resolved = (Ext3) ext3.resolve(); assertThat(ext3Resolved.getExt1()).isSameAs(ext1.resolve()); assertThat(ext3Resolved.getExt2s()).hasSameElementsAs(Arrays.asList((Ext2) ext2_1.resolve(), (Ext2) ext2_2.resolve())); assertThat(ext3.getDefinition()).isSameAs(ext3def); } @Test @DisplayName("must fail if no extension definition not found") void mustFailIfDefinitionNotFound() { definitions.remove(0); Assertions.assertThrows(ConfigurationException.class, () -> loadFile("anycollect.yaml")); } @Test @DisplayName("!ref tag is designed for single dependency") void refTagIsDesignedForSingleDependency() { Assertions.assertThrows(ConfigurationException.class, () -> loadFile("anycollect-illegal-ref-tag.yaml")); } @Test @DisplayName("!refs tag is designed for multi dependencies") void refsTagIsDesignedForMultiDependencies() { Assertions.assertThrows(ConfigurationException.class, () -> loadFile("anycollect-illegal-refs-tag.yaml")); } @Test @DisplayName("self reference in !ref or !refs is forbidden") void selfReferenceIsForbidden() { ConfigurationException exRef = Assertions.assertThrows(ConfigurationException.class, () -> loadString(selfRefYaml)); assertThat(exRef).hasMessageContaining("could not find definition for ext1"); ConfigurationException exRefs = Assertions.assertThrows(ConfigurationException.class, () -> loadString(selfRefsYaml)); assertThat(exRefs).hasMessageContaining("could not find definition for ext1"); } @Test @DisplayName("Reference in !ref or !refs to unknown instance is forbidden") void unknownReferenceIsForbidden() { ConfigurationException exRef = Assertions.assertThrows(ConfigurationException.class, () -> loadString(refToUnknownDependencyYaml)); assertThat(exRef).hasMessageContaining("could not find definition for ext1"); ConfigurationException exRefs = Assertions.assertThrows(ConfigurationException.class, () -> loadString(refsToUnknownDependencyYaml)); assertThat(exRefs).hasMessageContaining("could not find definition for ext2"); } @Test @DisplayName("!load tag must be used only for mapping") void loadTagMustBeUsedOnlyForMapping() { ConfigurationException exScalar = Assertions.assertThrows(ConfigurationException.class, () -> loadString(loadScalarYaml)); assertThat(exScalar).hasMessageContaining("!load").hasMessageContaining("illegal"); ConfigurationException exSequence = Assertions.assertThrows(ConfigurationException.class, () -> loadString(loadSequenceYaml)); assertThat(exSequence).hasMessageContaining("!load").hasMessageContaining("illegal"); } @Test @DisplayName("try to configure not configurable extension must fail") void tryToConfigureNotConfigurableExtensionMustFail() { ConfigurationException ex = Assertions.assertThrows(ConfigurationException.class, () -> loadString(unsupportedConfigYaml)); assertThat(ex).hasStackTraceContaining("is not supported").hasStackTraceContaining("Ext1"); } @Test @DisplayName("must throw high level exception if jackson fail to parse config") void mustThrowHighLevelExceptionIfExtensionConfigIsNotValid() { ConfigurationException ex = Assertions.assertThrows(ConfigurationException.class, () -> loadString(wrongConfigYaml)); assertThat(ex).hasCauseInstanceOf(UnrecognizedPropertyException.class); } @Test @DisplayName("extension is required property") void extensionIsRequiredProperty() { MissingRequiredPropertyException ex = Assertions.assertThrows(MissingRequiredPropertyException.class, () -> loadFile("anycollect-extension-required.yaml")); assertThat(ex.getProperty()).isEqualTo("extension"); } @Test @DisplayName("activation test") void activationTest() throws IOException { List<Instance> instances = loadFile("activation.yaml", VarSubstitutor.of("ext3.number", "1")); assertThat(instances).size().isEqualTo(2); Ext3 ext3 = (Ext3) instances.get(1).resolve(); assertThat(ext3.config.key).isEqualTo("1"); } private List<Instance> loadString(String content) { return loadString(content, VarSubstitutor.EMPTY); } private List<Instance> loadString(String content, VarSubstitutor environment) { return loadReader(new StringReader(content), environment); } private List<Instance> loadFile(String name) throws IOException { return loadFile(name, VarSubstitutor.EMPTY); } private List<Instance> loadFile(String name, VarSubstitutor environment) throws IOException { try (FileReader reader = new FileReader(new File("src/test/resources/config/" + name))) { return loadReader(reader, environment); } } private List<Instance> loadReader(Reader reader) { return loadReader(reader, VarSubstitutor.EMPTY); } private List<Instance> loadReader(Reader reader, VarSubstitutor environment) { ContextImpl context = new ContextImpl(this.definitions); new YamlInstanceLoader(new SimpleScope(null, "default"), reader, environment).load(context); Collection<Instance> instances = context.getInstances(); return new ArrayList<>(instances); } interface ExtPoint1 { } interface ExtPoint2 { } interface ExtPoint3 { } static public class Ext1 implements ExtPoint1 { } static public class Ext2 implements ExtPoint2 { } static public class Ext3 implements ExtPoint3 { private final ExtPoint1 ext1; private final List<ExtPoint2> ext2s; private final Ext3Config config; public Ext3(ExtPoint1 ext1, List<ExtPoint2> ext2s, Ext3Config config) { this.ext1 = ext1; this.ext2s = ext2s; this.config = config; } public ExtPoint1 getExt1() { return ext1; } public List<ExtPoint2> getExt2s() { return ext2s; } } @EqualsAndHashCode static class Ext3Config { private final String key; @JsonCreator Ext3Config(@JsonProperty("key") String key) { this.key = key; } } }<file_sep>/anycollect-core/src/test/java/io/github/anycollect/core/impl/matcher/RuleListQueryMatcherTest.java package io.github.anycollect.core.impl.matcher; import io.github.anycollect.core.api.query.Query; import io.github.anycollect.core.api.target.Target; import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.Collections; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; class RuleListQueryMatcherTest { private Target target = mock(Target.class); private Query query = mock(Query.class); @Test void smallestPeriodMustBeChosen() { MatchRule rule1 = mock(MatchRule.class); when(rule1.match(target, query)).thenReturn(true); when(rule1.getPeriod()).thenReturn(40); MatchRule rule2 = mock(MatchRule.class); when(rule2.match(target, query)).thenReturn(true); when(rule2.getPeriod()).thenReturn(30); assertThat(new RuleListQueryMatcher(Arrays.asList(rule1, rule2)) .getPeriodInSeconds(target, query, -1)).isEqualTo(30); assertThat(new RuleListQueryMatcher(Arrays.asList(rule2, rule1)) .getPeriodInSeconds(target, query, -1)).isEqualTo(30); } @Test void periodMustNotBeOverwrittenIfNewRuleDoesNotProvidePositivePeriod() { MatchRule rule1 = mock(MatchRule.class); when(rule1.match(target, query)).thenReturn(true); when(rule1.getPeriod()).thenReturn(40); MatchRule rule2 = mock(MatchRule.class); when(rule2.match(target, query)).thenReturn(true); when(rule2.getPeriod()).thenReturn(-1); assertThat(new RuleListQueryMatcher(Arrays.asList(rule1, rule2)) .getPeriodInSeconds(target, query, -1)).isEqualTo(40); assertThat(new RuleListQueryMatcher(Arrays.asList(rule2, rule1)) .getPeriodInSeconds(target, query, -1)).isEqualTo(40); } @Test void mustReturnMinusOneIfNoRuleFound() { MatchRule rule1 = mock(MatchRule.class); when(rule1.match(target, query)).thenReturn(false); assertThat(new RuleListQueryMatcher(Collections.singletonList(rule1)) .getPeriodInSeconds(target, query, 30)).isEqualTo(-1); } }<file_sep>/anycollect-core/src/main/java/io/github/anycollect/core/impl/router/MonitoredMetricConsumer.java package io.github.anycollect.core.impl.router; import io.github.anycollect.meter.api.Counter; import io.github.anycollect.meter.api.MeterRegistry; import io.github.anycollect.metric.Sample; import io.github.anycollect.meter.api.Timer; import javax.annotation.Nonnull; import java.util.List; import java.util.concurrent.TimeUnit; public final class MonitoredMetricConsumer implements MetricConsumer { private final MetricConsumer delegate; private final Counter consumedMetrics; private final Timer processingTime; public MonitoredMetricConsumer(@Nonnull final MetricConsumer delegate, @Nonnull final MeterRegistry registry) { this.delegate = delegate; this.consumedMetrics = Counter.key("router/route/delivered.metrics") .tag("route", getAddress()) .meta(this.getClass()) .register(registry); this.processingTime = Timer.key("router/route/processing.time") .unit(TimeUnit.MILLISECONDS) .tag("route", getAddress()) .meta(this.getClass()) .register(registry); } @Override public void consume(@Nonnull final List<? extends Sample> samples) { consumedMetrics.increment(samples.size()); processingTime.record(() -> delegate.consume(samples)); } @Override public void stop() { delegate.stop(); } @Nonnull @Override public String getAddress() { return delegate.getAddress(); } } <file_sep>/extensions/readers/anycollect-jmx-reader/src/main/java/io/github/anycollect/readers/jmx/query/JvmRuntime.java package io.github.anycollect.readers.jmx.query; import io.github.anycollect.core.api.job.Job; import io.github.anycollect.metric.Key; import io.github.anycollect.metric.Stat; import io.github.anycollect.metric.Tags; import io.github.anycollect.readers.jmx.server.JavaApp; import javax.annotation.Nonnull; import java.util.Collections; public final class JvmRuntime extends JmxQuery { private final StdJmxQuery uptime; public JvmRuntime(@Nonnull final String prefix, @Nonnull final Tags tags, @Nonnull final Tags meta) { super("jvm.runtime", tags, meta); this.uptime = new StdJmxQuery( Key.of("jvm/runtime/uptime").withPrefix(prefix), tags, meta, Collections.emptyList(), "java.lang:type=Runtime", null, Collections.singletonList(new MeasurementPath("Uptime", Stat.time(), "ms"))); } @Nonnull @Override public Job bind(@Nonnull final JavaApp app) { return uptime.bind(app); } } <file_sep>/anycollect-core/src/test/java/io/github/anycollect/core/impl/pull/separate/ConcurrencyRulesTest.java package io.github.anycollect.core.impl.pull.separate; import io.github.anycollect.core.api.target.Target; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.mockito.stubbing.Answer; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; class ConcurrencyRulesTest { @Nested @DisplayName("when several rules is accepted") class WhenSeveralRulesIsAccepted { private ConcurrencyRules rules; private Target target; @BeforeEach void setUp() { target = mock(Target.class); ConcurrencyRule rule1 = mock(ConcurrencyRule.class); ConcurrencyRule rule2 = mock(ConcurrencyRule.class); when(rule1.getPoolSize(eq(target), anyInt())).thenReturn(3); when(rule2.getPoolSize(eq(target), anyInt())).thenReturn(5); rules = ConcurrencyRules.builder() .withRule(rule1) .withRule(rule2) .build(); } @Test @DisplayName("the first one must be used") void theFirstOneMustBeUsed() { assertThat(rules.getPoolSize(target, -1)).isEqualTo(3); } } @Nested @DisplayName("when no appropriate rules found") class WhenNoAppropriateRulesFound { private ConcurrencyRules rules; @BeforeEach void setUp() { ConcurrencyRule rule = mock(ConcurrencyRule.class); when(rule.getPoolSize(any(), anyInt())).thenAnswer((Answer<Integer>) invocation -> (int) invocation.getArgument(1)); rules = ConcurrencyRules.builder() .withRule(rule) .build(); } @Test @DisplayName("must return fallback") void mustReturnFallback() { Target target = mock(Target.class); assertThat(rules.getPoolSize(target, -1)).isEqualTo(-1); assertThat(rules.getPoolSize(target, 10)).isEqualTo(10); } } }<file_sep>/extensions/readers/anycollect-jmx-reader/src/main/java/io/github/anycollect/readers/jmx/discovery/StaticJavaAppDiscovery.java package io.github.anycollect.readers.jmx.discovery; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import io.github.anycollect.core.api.target.ServiceDiscovery; import io.github.anycollect.core.api.target.TargetCreationException; import io.github.anycollect.extensions.annotations.ExtConfig; import io.github.anycollect.extensions.annotations.ExtCreator; import io.github.anycollect.extensions.annotations.ExtDependency; import io.github.anycollect.extensions.annotations.Extension; import io.github.anycollect.meter.api.MeterRegistry; import io.github.anycollect.readers.jmx.config.JavaAppConfig; import io.github.anycollect.readers.jmx.server.JavaApp; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nonnull; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Static Java App discovery */ @Extension(name = StaticJavaAppDiscovery.NAME, contracts = ServiceDiscovery.class) public final class StaticJavaAppDiscovery implements ServiceDiscovery<JavaApp> { public static final String NAME = "StaticJavaAppDiscovery"; private static final Logger LOG = LoggerFactory.getLogger(StaticJavaAppDiscovery.class); private final Set<JavaApp> apps; @ExtCreator public StaticJavaAppDiscovery(@ExtDependency(qualifier = "registry") @Nonnull final MeterRegistry registry, @ExtConfig @Nonnull final Config config) { // TODO inject JavaAppFactory factory = new DefaultJavaAppFactory(registry); apps = new HashSet<>(); for (JavaAppConfig appConfig : config.appConfigs) { try { apps.add(factory.create(appConfig)); } catch (TargetCreationException e) { LOG.warn("could not create java target from definition: {}", appConfig, e); } } } @Override public Set<JavaApp> discover() { return Collections.unmodifiableSet(apps); } public static class Config { private final List<JavaAppConfig> appConfigs; @JsonCreator public Config(@JsonProperty("instances") @Nonnull final List<JavaAppConfig> appConfigs) { this.appConfigs = appConfigs; } } } <file_sep>/anycollect-core-api/src/main/java/io/github/anycollect/core/api/Reader.java package io.github.anycollect.core.api; import io.github.anycollect.core.api.dispatcher.Dispatcher; import javax.annotation.Nonnull; public interface Reader extends Route { void start(@Nonnull Dispatcher dispatcher); void stop(); } <file_sep>/anycollect-core/src/test/java/io/github/anycollect/core/impl/scheduler/CustomFutureTest.java package io.github.anycollect.core.impl.scheduler; import org.junit.jupiter.api.Test; import java.util.concurrent.Delayed; import java.util.concurrent.RunnableScheduledFuture; import java.util.concurrent.TimeUnit; import static org.mockito.Mockito.*; class CustomFutureTest { @Test void delegationTest() throws Exception { RunnableScheduledFuture<?> delegate = mock(RunnableScheduledFuture.class); CustomFuture<?> future = new CustomFuture<>(delegate); future.cancel(false); future.get(); future.get(10, TimeUnit.MILLISECONDS); Delayed delayed = mock(Delayed.class); future.compareTo(delayed); future.isPeriodic(); future.isCancelled(); future.isDone(); verify(delegate, times(1)).cancel(false); verify(delegate, times(1)).get(); verify(delegate, times(1)).get(10, TimeUnit.MILLISECONDS); verify(delegate, times(1)).compareTo(delayed); verify(delegate, times(1)).isPeriodic(); verify(delegate, times(1)).isCancelled(); verify(delegate, times(1)).isDone(); } }<file_sep>/extensions/common/anycollect-common-expression/src/main/java/io/github/anycollect/extensions/common/expression/ParseException.java package io.github.anycollect.extensions.common.expression; public class ParseException extends Exception { public ParseException(final String message) { super(message); } } <file_sep>/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>io.github.anycollect</groupId> <artifactId>anycollect</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>pom</packaging> <properties> <encoding>UTF-8</encoding> <project.build.sourceEncoding>${encoding}</project.build.sourceEncoding> <jacoco.plugin.version>0.8.2</jacoco.plugin.version> </properties> <modules> <module>anycollect-parent</module> <module>anycollect-build-tools</module> <module>anycollect-metric</module> <module>anycollect-tests</module> <module>anycollect-extension-system</module> <module>anycollect-extension-annotations</module> <module>extensions/common/anycollect-common-expression</module> <module>extensions/readers/anycollect-jmx-reader</module> <module>anycollect-core-api</module> <module>anycollect-core</module> <module>anycollect-jackson</module> <module>anycollect-test-utils</module> <module>anycollect-meter</module> <module>extensions/kv/anycollect-consul-kv</module> <module>extensions/readers/anycollect-async-socket-reader</module> <module>extensions/readers/anycollect-system-reader</module> <module>anycollect-benchmarks</module> <module>anycollect-extension-system-api</module> <module>extensions/jackson/anycollect-jackson-guava</module> <module>anycollect-agent</module> <module>anycollect-assembly</module> <module>extensions/anycollect-collectd</module> <module>anycollect-meter-api</module> </modules> <build> <plugins> <plugin> <groupId>org.jacoco</groupId> <artifactId>jacoco-maven-plugin</artifactId> <version>${jacoco.plugin.version}</version> <executions> <execution> <goals> <goal>prepare-agent</goal> </goals> </execution> <execution> <id>report</id> <phase>test</phase> <goals> <goal>report</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project><file_sep>/anycollect-core/src/main/java/io/github/anycollect/core/impl/router/Channel.java package io.github.anycollect.core.impl.router; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nonnull; import javax.annotation.concurrent.ThreadSafe; @ThreadSafe public final class Channel { private static final Logger LOG = LoggerFactory.getLogger(Channel.class); private final MetricProducer producer; private final RouteDispatcher consumer; public Channel(@Nonnull final MetricProducer producer, @Nonnull final RouteDispatcher consumer) { this.producer = producer; this.consumer = consumer; } public void connect() { LOG.info("Connecting channel: {}->{}", producer.getAddress(), consumer); producer.start(consumer); } public void disconnect() { LOG.info("Disconnecting channel: {}->{}", producer.getAddress(), consumer); consumer.stop(); } @Override public String toString() { return producer + "->" + consumer.toString(); } } <file_sep>/extensions/readers/anycollect-jmx-reader/src/main/java/io/github/anycollect/readers/jmx/query/operations/QueryAttributes.java package io.github.anycollect.readers.jmx.query.operations; import io.github.anycollect.core.exceptions.ConnectionException; import io.github.anycollect.core.exceptions.QueryException; import javax.annotation.Nonnull; import javax.management.*; import java.io.IOException; import java.util.List; public final class QueryAttributes implements QueryOperation<List<Attribute>> { private final ObjectName objectName; private final String[] attributeNames; public QueryAttributes(@Nonnull final ObjectName objectName, @Nonnull final String[] attributeNames) { this.objectName = objectName; this.attributeNames = attributeNames; } @Override public List<Attribute> operate(@Nonnull final MBeanServerConnection connection) throws QueryException, ConnectionException { try { return connection.getAttributes(objectName, attributeNames).asList(); } catch (IOException e) { throw new ConnectionException("could not get attributes", e); } catch (InstanceNotFoundException | ReflectionException e) { throw new QueryException("could not get attributes", e); } } } <file_sep>/anycollect-extension-system/src/test/java/io/github/anycollect/extensions/samples/ExtensionPointWithTwoConstructors.java package io.github.anycollect.extensions.samples; import io.github.anycollect.extensions.annotations.ExtConfig; import io.github.anycollect.extensions.annotations.ExtCreator; import io.github.anycollect.extensions.annotations.Extension; @Extension(contracts = SampleExtensionPoint.class, name = "TwoConstructors") public class ExtensionPointWithTwoConstructors implements SampleExtensionPoint { @ExtCreator public ExtensionPointWithTwoConstructors() { } @ExtCreator public ExtensionPointWithTwoConstructors(@ExtConfig SampleExtensionConfig config) { } } <file_sep>/anycollect-core/src/main/java/io/github/anycollect/core/impl/writers/socket/Sender.java package io.github.anycollect.core.impl.writers.socket; import io.github.anycollect.core.exceptions.SerialisationException; import io.github.anycollect.metric.Sample; import javax.annotation.Nonnull; import java.io.IOException; public interface Sender { void connected() throws IOException; boolean isConnected(); void send(@Nonnull Sample sample) throws SerialisationException, IOException; void flush() throws IOException; void closed(); } <file_sep>/extensions/readers/anycollect-jmx-reader/src/test/java/io/github/anycollect/readers/jmx/JmxReaderTest.java package io.github.anycollect.readers.jmx; import io.github.anycollect.core.api.dispatcher.Dispatcher; import io.github.anycollect.metric.*; import io.github.anycollect.readers.jmx.utils.HistogramTest; import io.github.anycollect.test.TestContext; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import javax.annotation.Nonnull; import javax.management.MBeanServer; import javax.management.ObjectName; import java.lang.management.ManagementFactory; import java.util.List; import java.util.stream.Collectors; import static io.github.anycollect.assertj.AnyCollectAssertions.assertThat; import static org.awaitility.Awaitility.await; class JmxReaderTest { private JmxReader jmx; @BeforeEach void createJmxReader() throws Exception { TestContext context = new TestContext("jmx-reader.yaml"); jmx = (JmxReader) context.getInstance("jmx").resolve(); } @Test @DisplayName("is successfully instantiated by extension system") void isInstantiatedBySystem() { assertThat(jmx).isNotNull(); } @Nested class QueryTest { private CumulativeDispatcher dispatcher = new CumulativeDispatcher(); @BeforeEach void setUp() throws Exception { MBeanServer server = ManagementFactory.getPlatformMBeanServer(); server.registerMBean(new HistogramTest(), new ObjectName("test:name=Test,k1=k1val1,k2=k2val1")); server.registerMBean(new HistogramTest(), new ObjectName("test:name=Test,k1=k1val1,k2=k2val2")); server.registerMBean(new HistogramTest(), new ObjectName("test:name=Test,k1=k1val2,k2=k2val1")); server.registerMBean(new HistogramTest(), new ObjectName("test:name=Test,k1=k1val2,k2=k2val2")); } @Test void mbeanHasBeenQueried() { jmx.start(dispatcher); await().until(() -> dispatcher.first != null); List<Sample> samples = dispatcher.first; assertThat(samples).hasSize(9); samples = samples.stream() .map(sample -> sample.getMetric().sample(sample.getValue(), 0)) .collect(Collectors.toList()); Tags tags = Tags.of("key1", "value1", "k1", "k1val2", "k2", "k2val1"); Tags meta = Tags.of("key2", "value2"); Metric.Factory builder = Metric.builder() .key("histogram") .tags(tags) .meta(meta); assertThat(samples) .contains(builder.min("events").sample(1.0, 0)) .contains(builder.max("events").sample(2.0, 0)) .contains(builder.mean("events").sample(3.0, 0)) .contains(builder.percentile(50, "events").sample(50, 0)) .contains(builder.percentile(75, "events").sample(75, 0)) .contains(builder.percentile(90, "events").sample(90, 0)) .contains(builder.percentile(95, "events").sample(95, 0)) .contains(builder.percentile(99, "events").sample(99, 0)); } } private static class CumulativeDispatcher implements Dispatcher { private volatile List<Sample> first = null; @Override public void dispatch(@Nonnull Sample sample) { } @Override public void dispatch(@Nonnull List<Sample> samples) { if (first == null) { first = samples; } } } }<file_sep>/extensions/readers/anycollect-system-reader/src/main/java/io/github/anycollect/readers/process/Process.java package io.github.anycollect.readers.process; import io.github.anycollect.core.api.target.Target; import io.github.anycollect.core.exceptions.ConnectionException; import oshi.software.os.OSProcess; public interface Process extends Target { OSProcess snapshot() throws ConnectionException; } <file_sep>/extensions/readers/anycollect-jmx-reader/src/test/java/io/github/anycollect/readers/jmx/server/PooledServerTest.java package io.github.anycollect.readers.jmx.server; import io.github.anycollect.core.exceptions.ConnectionException; import io.github.anycollect.core.exceptions.QueryException; import io.github.anycollect.readers.jmx.server.pool.JmxConnectionPool; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import javax.management.MBeanServerConnection; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.*; class PooledServerTest { private JmxConnectionPool pool = mock(JmxConnectionPool.class); @Test void mustBorrowAndThenReturnConnectionToPool() throws ConnectionException, QueryException { JavaApp server = new PooledJavaApp("dummy-server", pool); JmxConnection jmxConnection = mock(JmxConnection.class); when(pool.borrowConnection()).thenReturn(jmxConnection); server.operate(connection -> null); verify(pool, times(1)).returnConnection(jmxConnection); } @Test void mustInvalidateConnectionIfExceptionDuringExecution() throws ConnectionException, QueryException { JavaApp server = new PooledJavaApp("dummy-server", pool); MBeanServerConnection serverConnection = mock(MBeanServerConnection.class); JmxConnection jmxConnection = new JmxConnection(null, serverConnection); when(pool.borrowConnection()).thenReturn(jmxConnection); ConnectionException ex = Assertions.assertThrows(ConnectionException.class, () -> server.operate(connection -> { throw new ConnectionException("timeout"); })); assertThat(ex).hasMessage("timeout"); verify(pool, times(1)).invalidateConnection(jmxConnection); } @Test void mustForwardBusinessExceptionFromPool() throws ConnectionException { JavaApp server = new PooledJavaApp("dummy-server", pool); when(pool.borrowConnection()).thenThrow(new ConnectionException("dummy")); ConnectionException ex = Assertions.assertThrows(ConnectionException.class, () -> server.operate(connection -> null)); assertThat(ex).hasMessage("dummy"); } @Test void mustForwardBusinessExceptionFromOperation() throws ConnectionException, QueryException { JavaApp server = new PooledJavaApp("dummy-server", pool); when(pool.borrowConnection()).thenReturn(new JmxConnection(null, mock(MBeanServerConnection.class))); QueryException ex = Assertions.assertThrows(QueryException.class, () -> server.operate(connection -> { throw new QueryException("dummy"); })); assertThat(ex).hasMessage("dummy"); } @Test void propertiesTest() { JavaApp server = new PooledJavaApp("dummy-server", pool); assertThat(server.getId()).isEqualTo("dummy-server"); } }<file_sep>/anycollect-extension-system/src/test/java/io/github/anycollect/extensions/samples/ExtensionPointWithoutAnnotaionImpl.java package io.github.anycollect.extensions.samples; import io.github.anycollect.extensions.annotations.ExtCreator; import io.github.anycollect.extensions.annotations.Extension; @Extension(name = "ExtensionPointWithoutAnnotation", contracts = ExtensionPointWithoutAnnotation.class) public class ExtensionPointWithoutAnnotaionImpl implements ExtensionPointWithoutAnnotation { @ExtCreator public ExtensionPointWithoutAnnotaionImpl() { } } <file_sep>/anycollect-core-api/src/main/java/io/github/anycollect/core/api/internal/AdaptiveSerializerImpl.java package io.github.anycollect.core.api.internal; import io.github.anycollect.core.api.Serializer; import io.github.anycollect.core.exceptions.SerialisationException; import io.github.anycollect.metric.Sample; import javax.annotation.Nonnull; import java.nio.ByteBuffer; import java.nio.charset.CoderResult; public final class AdaptiveSerializerImpl implements AdaptiveSerializer { private static final int DEFAULT_INIT_BUFFER_SIZE = 1024; private static final int DEFAULT_MAX_BUFFER_SIZE = 16 * DEFAULT_INIT_BUFFER_SIZE; private final Serializer serializer; private ByteBuffer buffer; private final int maxBufferSize; public AdaptiveSerializerImpl(@Nonnull final Serializer serializer) { this(serializer, DEFAULT_INIT_BUFFER_SIZE, DEFAULT_MAX_BUFFER_SIZE); } public AdaptiveSerializerImpl(@Nonnull final Serializer serializer, final int initBufferSize, final int maxBufferSize) { this.buffer = ByteBuffer.allocate(initBufferSize); this.serializer = serializer; this.maxBufferSize = maxBufferSize; } @Override public ByteBuffer serialize(@Nonnull final Sample sample) throws SerialisationException { serializer.serialize(sample, buffer); if (buffer == null) { throw new IllegalStateException("buffer has not been released yet"); } CoderResult coderResult; do { buffer.clear(); coderResult = serializer.serialize(sample, buffer); buffer.flip(); if (coderResult.isOverflow()) { if (buffer.capacity() == maxBufferSize) { throw new SerialisationException("overflow using maximal allowed buffer size"); } int newCapacity = buffer.capacity() * 2; if (newCapacity >= maxBufferSize) { newCapacity = maxBufferSize; } buffer = ByteBuffer.allocate(newCapacity); } } while (coderResult.isOverflow()); if (coderResult.isError()) { throw new SerialisationException("fail to serialize metric " + coderResult); } ByteBuffer buffer = this.buffer; this.buffer = null; return buffer; } @Override public void release(@Nonnull final ByteBuffer buffer) { this.buffer = buffer; } } <file_sep>/anycollect-jackson/src/main/java/io/github/anycollect/jackson/KeyDeserializer.java package io.github.anycollect.jackson; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import io.github.anycollect.metric.Key; import java.io.IOException; public final class KeyDeserializer extends StdDeserializer<Key> { protected KeyDeserializer() { super(Key.class); } @Override public Key deserialize(final JsonParser jsonParser, final DeserializationContext deserializationContext) throws IOException { String value = jsonParser.readValueAs(String.class); return Key.of(value); } } <file_sep>/anycollect-agent/src/main/java/io/github/anycollect/CliConfig.java package io.github.anycollect; import lombok.Getter; import picocli.CommandLine; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @Getter public final class CliConfig { @CommandLine.Option(names = {"-c", "--conf"}, required = false, description = "This is the path to configuration") private File configFile; @CommandLine.Option(names = {"-p", "--pid-file"}, description = "This is the path to store a PID file " + "which will contain the process ID of the anycollect process.") private File pidFile; @CommandLine.Option(names = {"-l", "--logback-conf"}, description = "This is the path to load logback configuration from") private File logbackConfig; @CommandLine.Option(names = {"-e", "--env"}, description = "This is the map of environment variables (can be referenced using \"!var\" tag in yaml") private Map<String, String> env = new HashMap<>(); @CommandLine.Option(names = {"-x", "--enable-preconfigured-extension"}, description = "This is the list of preconfigured extensions to be loaded") private List<String> enabledPreconfiguredExtensions = new ArrayList<>(); } <file_sep>/anycollect-core-api/src/main/java/io/github/anycollect/core/api/internal/AllQueryMatcher.java package io.github.anycollect.core.api.internal; import io.github.anycollect.core.api.query.Query; import io.github.anycollect.core.api.target.Target; import javax.annotation.Nonnull; import java.util.Objects; public final class AllQueryMatcher implements QueryMatcher { private final int period; public AllQueryMatcher(final int period) { this.period = period; } @Override public int getPeriodInSeconds(@Nonnull final Target target, @Nonnull final Query query, final int defaultPeriod) { Objects.requireNonNull(target, "target must not be null"); Objects.requireNonNull(query, "query must not be null"); if (defaultPeriod <= 0) { throw new IllegalArgumentException("default period must be greater than zero, given: " + defaultPeriod); } if (period <= 0) { return defaultPeriod; } else { return period; } } } <file_sep>/anycollect-agent/src/main/java/io/github/anycollect/shutdown/ShutdownTask.java package io.github.anycollect.shutdown; public interface ShutdownTask { void shutdown(); } <file_sep>/anycollect-core/src/main/java/io/github/anycollect/core/impl/writers/socket/SocketWriter.java package io.github.anycollect.core.impl.writers.socket; import io.github.anycollect.core.api.Serializer; import io.github.anycollect.core.api.Writer; import io.github.anycollect.core.api.common.Lifecycle; import io.github.anycollect.core.api.internal.AdaptiveSerializer; import io.github.anycollect.core.exceptions.ConfigurationException; import io.github.anycollect.core.exceptions.SerialisationException; import io.github.anycollect.extensions.annotations.*; import io.github.anycollect.metric.Sample; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nonnull; import javax.annotation.concurrent.NotThreadSafe; import java.io.IOException; import java.util.List; @NotThreadSafe @Extension(name = SocketWriter.NAME, contracts = Writer.class) public final class SocketWriter implements Writer, Lifecycle { public static final String NAME = "SocketWriter"; private static final Logger LOG = LoggerFactory.getLogger(SocketWriter.class); private final Sender sender; private final String id; @ExtCreator public SocketWriter(@ExtDependency(qualifier = "serializer") @Nonnull final Serializer serializer, @InstanceId @Nonnull final String id, @ExtConfig @Nonnull final SocketConfig config) { AdaptiveSerializer adaptiveSerializer = AdaptiveSerializer.wrap(serializer); if (config.getProtocol() == Protocol.TCP) { this.sender = new TcpSender(config.getHost(), config.getPort(), adaptiveSerializer); } else if (config.getProtocol() == Protocol.UDP) { this.sender = new UdpSender(config.getHost(), config.getPort(), adaptiveSerializer); } else { LOG.error("protocol {} is not supported", config.getProtocol()); throw new ConfigurationException("protocol " + config.getProtocol() + " is not supported"); } this.id = id; } @Override public void write(@Nonnull final List<? extends Sample> metrics) { for (Sample sample : metrics) { write(sample); } } private void write(@Nonnull final Sample sample) { try { sender.connected(); sender.send(sample); // TODO schedule flush sender.flush(); } catch (SerialisationException e) { LOG.debug("could not serialize metric {}", sample, e); } catch (IOException e) { LOG.trace("fail to send metric: {}", sample, e); sender.closed(); } } @Override public String getId() { return id; } @Override public void init() { LOG.info("{} has been successfully initialised", NAME); } @Override public void destroy() { LOG.info("{}({}) has been successfully destroyed", id, NAME); } } <file_sep>/anycollect-extension-system/src/test/java/io/github/anycollect/extensions/samples/SampleExtensionWithoutConfig.java package io.github.anycollect.extensions.samples; import io.github.anycollect.extensions.annotations.ExtCreator; import io.github.anycollect.extensions.annotations.Extension; @Extension(contracts = SampleExtensionPoint.class, name = "WithoutConfig") public class SampleExtensionWithoutConfig implements SampleExtensionPoint{ @ExtCreator public SampleExtensionWithoutConfig() { } } <file_sep>/anycollect-extension-system/src/test/java/io/github/anycollect/extensions/utils/ConstrictorUtils.java package io.github.anycollect.extensions.utils; import java.lang.reflect.Constructor; import java.util.Arrays; public class ConstrictorUtils { public static <T> Constructor<T> createFor(Class<T> type, Class<?>... args) { try { return type.getDeclaredConstructor(args); } catch (NoSuchMethodException e) { throw new IllegalArgumentException(type + " doesn't contain appropriate constructor with parameters: " + Arrays.toString(args), e); } } } <file_sep>/extensions/readers/anycollect-jmx-reader/src/main/java/io/github/anycollect/readers/jmx/server/JmxConnectorFactory.java package io.github.anycollect.readers.jmx.server; import javax.annotation.Nonnull; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; import java.io.IOException; import java.util.Map; public interface JmxConnectorFactory { JmxConnectorFactory DEFAULT = JMXConnectorFactory::connect; JMXConnector connect(@Nonnull JMXServiceURL url, @Nonnull Map<String, Object> environment) throws IOException; } <file_sep>/anycollect-benchmarks/src/main/java/io/github/anycollect/metric/Benchmarks.java package io.github.anycollect.metric; import org.openjdk.jmh.annotations.*; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.RunnerException; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import java.util.concurrent.TimeUnit; import static io.github.anycollect.metric.Utils.generate; import static org.openjdk.jmh.annotations.Mode.AverageTime; import static org.openjdk.jmh.annotations.Mode.Throughput; @Fork(1) @BenchmarkMode({Throughput, AverageTime}) @Warmup(iterations = 5, time = 500, timeUnit = TimeUnit.NANOSECONDS) @Measurement(iterations = 5, time = 500, timeUnit = TimeUnit.NANOSECONDS) @State(Scope.Benchmark) public class Benchmarks { private Tags first; private Tags second; private Tags persistentTags; private Tags immutableTags; @Setup public void init() { this.first = generate(5); this.second = generate(3); this.persistentTags = ConcatTags.of(first, second); this.immutableTags = Tags.builder() .concat(first) .concat(second) .build(); } @Benchmark public Tags iteratePersistent() { for (Tag tag : persistentTags) ; return persistentTags; } @Benchmark public Tags createPersistent() { return ConcatTags.of(first, second); } @Benchmark public Tags iterateImmutableTags() { for (Tag tag : immutableTags) ; return immutableTags; } @Benchmark public Tags createImmutableTags() { return Tags.builder() .concat(first) .concat(second) .build(); } public static void main(final String... args) throws RunnerException { Options opt = new OptionsBuilder() .include(Benchmarks.class.getSimpleName()) .build(); new Runner(opt).run(); } } <file_sep>/anycollect-core-api/src/main/java/io/github/anycollect/core/api/filter/Filter.java package io.github.anycollect.core.api.filter; import com.fasterxml.jackson.annotation.JsonTypeInfo; import io.github.anycollect.metric.Metric; import javax.annotation.Nonnull; @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, property = "type") public interface Filter { FilterReply accept(@Nonnull Metric metric); } <file_sep>/extensions/common/anycollect-common-expression/src/main/java/io/github/anycollect/extensions/common/expression/ast/VariableExpressionNode.java package io.github.anycollect.extensions.common.expression.ast; import io.github.anycollect.extensions.common.expression.EvaluationException; import io.github.anycollect.extensions.common.expression.ast.visitor.ExpressionNodeVisitor; import lombok.ToString; import java.util.regex.Matcher; import java.util.regex.Pattern; @ToString(doNotUseGetters = true) public final class VariableExpressionNode implements ValueExpressionNode { private static final Pattern VAR = Pattern.compile("\\$\\{(.*)}"); private final String name; private String value; public VariableExpressionNode(final String sequence) { Matcher matcher = VAR.matcher(sequence); if (matcher.find()) { name = matcher.group(1); } else { throw new IllegalArgumentException(sequence + " is not a variable expression"); } } @Override public void accept(final ExpressionNodeVisitor visitor) { visitor.visit(this); } @Override public String getValue() throws EvaluationException { if (!isResolved()) { throw new EvaluationException(name + "is not resolved"); } return value; } @Override public boolean isResolved() { return value != null; } public void setValue(final String value) { this.value = value; } public void reset() { this.value = null; } public String getName() { return name; } } <file_sep>/anycollect-core-api/src/main/java/io/github/anycollect/core/api/internal/QueryMatcherResolver.java package io.github.anycollect.core.api.internal; import javax.annotation.Nonnull; public interface QueryMatcherResolver { static QueryMatcherResolver consistent(@Nonnull QueryMatcher matcher) { return new ConsistentQueryMatcherResolver(matcher); } static QueryMatcherResolver alwaysAll(int period) { return consistent(QueryMatcher.all(period)); } @Nonnull QueryMatcher current(); } <file_sep>/extensions/anycollect-collectd/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>anycollect-parent</artifactId> <groupId>io.github.anycollect</groupId> <version>0.0.1-SNAPSHOT</version> <relativePath>../../anycollect-parent/pom.xml</relativePath> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>anycollect-collectd-plugin-dist</artifactId> <repositories> <repository> <id>clojars.org</id> <url>https://repo.clojars.org</url> </repository> </repositories> <dependencies> <dependency> <groupId>io.github.anycollect</groupId> <artifactId>anycollect-anycollect</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>io.github.anycollect</groupId> <artifactId>anycollect-core-api</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>io.github.anycollect</groupId> <artifactId>anycollect-common-expression</artifactId> <version>${project.version}</version> </dependency> <!-- YAML, CONFIGURATION --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.version}</version> </dependency> <!-- EXTENSIONS --> <dependency> <groupId>org.collectd</groupId> <artifactId>plugin-api</artifactId> </dependency> <!-- TESTING --> <dependency> <groupId>io.github.anycollect</groupId> <artifactId>anycollect-extension-test</artifactId> <version>${project.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>io.github.anycollect</groupId> <artifactId>anycollect-core</artifactId> <version>${project.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>io.github.anycollect</groupId> <artifactId>anycollect-meter</artifactId> <version>${project.version}</version> <scope>test</scope> </dependency> </dependencies> </project><file_sep>/anycollect-core/src/main/java/io/github/anycollect/core/impl/scheduler/SchedulerImpl.java package io.github.anycollect.core.impl.scheduler; import io.github.anycollect.core.api.internal.Cancellation; import io.github.anycollect.meter.api.MeterRegistry; import io.github.anycollect.metric.Tags; import javax.annotation.Nonnull; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; public final class SchedulerImpl implements Scheduler { private final ScheduledThreadPoolExecutor service; private final MeterRegistry registry; private final String prefix; private final Tags tags; public SchedulerImpl(@Nonnull final ScheduledThreadPoolExecutor service) { this.service = service; this.registry = MeterRegistry.noop(); this.prefix = ""; this.tags = Tags.empty(); } public SchedulerImpl(@Nonnull final ScheduledThreadPoolExecutor service, @Nonnull final MeterRegistry registry, @Nonnull final String prefix, @Nonnull final Tags tags) { this.service = service; this.registry = registry; this.prefix = prefix; this.tags = tags; } @Override public Cancellation scheduleAtFixedRate(@Nonnull final Runnable runnable, final long delay, final long period, @Nonnull final TimeUnit unit, final boolean allowOverworkAfterPause) { if (isShutdown()) { throw new IllegalStateException("scheduler is shutdown"); } ScheduledFuture<?> future; if (allowOverworkAfterPause) { future = service.scheduleAtFixedRate(runnable, delay, period, unit); } else { ThrottledRunnable throttled = new ThrottledRunnable(runnable, unit.toNanos(period), registry, prefix, tags); future = service.scheduleAtFixedRate(throttled, delay, period, unit); throttled.setDelayed(future); } return new ScheduledFeatureAdapter(future); } @Override public void shutdown() { service.shutdown(); } @Override public boolean isShutdown() { return service.isShutdown(); } public int getPoolSize() { return service.getCorePoolSize(); } final class ScheduledFeatureAdapter implements Cancellation { private final ScheduledFuture<?> future; ScheduledFeatureAdapter(@Nonnull final ScheduledFuture<?> future) { this.future = future; } @Override public void cancel() { future.cancel(true); } } } <file_sep>/extensions/readers/anycollect-jmx-reader/src/main/java/io/github/anycollect/readers/jmx/query/JvmThreads.java package io.github.anycollect.readers.jmx.query; import com.google.common.collect.HashMultiset; import com.google.common.collect.Multiset; import io.github.anycollect.core.api.internal.Clock; import io.github.anycollect.core.api.job.Job; import io.github.anycollect.core.api.job.TaggingJob; import io.github.anycollect.core.exceptions.ConnectionException; import io.github.anycollect.core.exceptions.QueryException; import io.github.anycollect.metric.Metric; import io.github.anycollect.metric.Sample; import io.github.anycollect.metric.Tags; import io.github.anycollect.readers.jmx.query.operations.InvokeOperation; import io.github.anycollect.readers.jmx.query.operations.QueryAttributes; import io.github.anycollect.readers.jmx.query.operations.QueryOperation; import io.github.anycollect.readers.jmx.server.JavaApp; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nonnull; import javax.management.Attribute; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import javax.management.openmbean.CompositeData; import java.util.ArrayList; import java.util.List; public final class JvmThreads extends JmxQuery { private static final Logger LOG = LoggerFactory.getLogger(JvmThreads.class); private static final ObjectName THREADING_OBJECT_NAME; private static final String THREAD_COUNT_ATTR_NAME = "ThreadCount"; private static final String DAEMON_THREAD_COUNT_ATTR_NAME = "DaemonThreadCount"; private static final String ALL_THREAD_IDS_ATTR_NAME = "AllThreadIds"; private static final String TOTAL_STARTED_THREAD_COUNT_ATTR_NAME = "TotalStartedThreadCount"; private static final String GET_THREAD_INFO_OP_NAME = "getThreadInfo"; private static final String THREAD_STATE_PROP = "threadState"; private static final String[] ATTRIBUTE_NAMES = new String[]{ THREAD_COUNT_ATTR_NAME, DAEMON_THREAD_COUNT_ATTR_NAME, ALL_THREAD_IDS_ATTR_NAME, TOTAL_STARTED_THREAD_COUNT_ATTR_NAME }; static { try { THREADING_OBJECT_NAME = new ObjectName("java.lang:type=Threading"); } catch (MalformedObjectNameException e) { throw new RuntimeException("could not create threading object name", e); } } private static final String LIVE_THREADS_KEY = "jvm/threads/live"; private static final String THREADS_STARTED_KEY = "jvm/threads/started"; private static final String THREADS_BY_STATE_KEY = "jvm/threads/states"; private final String prefix; private final Clock clock; public JvmThreads() { this("", Tags.empty(), Tags.empty()); } public JvmThreads(@Nonnull final String prefix, @Nonnull final Tags tags, @Nonnull final Tags meta) { super("jvm.threads", tags, meta); this.prefix = prefix; this.clock = Clock.getDefault(); } @Nonnull @Override public Job bind(@Nonnull final JavaApp app) { return new TaggingJob(prefix, app, this, new JvmThreadsJob(app)); } private final class JvmThreadsJob implements Job { private final JavaApp app; private final QueryOperation<List<Attribute>> queryAttributes; JvmThreadsJob(final JavaApp app) { this.app = app; this.queryAttributes = new QueryAttributes(THREADING_OBJECT_NAME, ATTRIBUTE_NAMES); } @Override public List<Sample> execute() throws QueryException, ConnectionException { List<Attribute> attributes = app.operate(queryAttributes); int threadCount = (int) attributes.get(0).getValue(); int daemonThreadCount = (int) attributes.get(1).getValue(); long[] allThreadIds = (long[]) attributes.get(2).getValue(); long totalStartedThreadCount = (long) attributes.get(3).getValue(); Object[] params = new Object[]{allThreadIds}; CompositeData[] threadInfos; InvokeOperation invoke = new InvokeOperation(THREADING_OBJECT_NAME, GET_THREAD_INFO_OP_NAME, params, new String[]{long[].class.getName()}); threadInfos = (CompositeData[]) app.operate(invoke); long timestamp = clock.wallTime(); List<Sample> samples = new ArrayList<>(); samples.add(Metric.builder() .key(THREADS_STARTED_KEY) .counter() .sample(totalStartedThreadCount, timestamp)); samples.add(Metric.builder() .key(LIVE_THREADS_KEY) .tag("type", "daemon") .gauge() .sample(daemonThreadCount, timestamp)); samples.add(Metric.builder() .key(LIVE_THREADS_KEY) .tag("type", "nondaemon") .gauge() .sample(threadCount - daemonThreadCount, timestamp)); Multiset<String> numberOfThreadsByState = HashMultiset.create(); for (CompositeData threadInfo : threadInfos) { String state = (String) threadInfo.get(THREAD_STATE_PROP); numberOfThreadsByState.add(state); } for (String state : numberOfThreadsByState.elementSet()) { samples.add(Metric.builder() .key(THREADS_BY_STATE_KEY) .tag("state", state) .gauge() .sample(numberOfThreadsByState.count(state), timestamp)); } return samples; } } } <file_sep>/anycollect-core/src/main/java/io/github/anycollect/core/impl/scheduler/MonitoredScheduledThreadPoolExecutor.java package io.github.anycollect.core.impl.scheduler; import com.google.common.util.concurrent.ThreadFactoryBuilder; import io.github.anycollect.core.api.internal.Clock; import io.github.anycollect.meter.api.*; import io.github.anycollect.metric.*; import javax.annotation.Nonnull; import java.util.Collections; import java.util.Map; import java.util.Set; import java.util.concurrent.*; public final class MonitoredScheduledThreadPoolExecutor extends ScheduledThreadPoolExecutor { private static final double ONE_HUNDRED_PERCENTS = 100.0; private final Clock clock; private final Map<CustomFuture<?>, Long> lastRunStartTimes = new ConcurrentHashMap<>(); private final Distribution discrepancySummary; private final Set<CustomFuture<?>> running = Collections.newSetFromMap(new ConcurrentHashMap<>()); private final Timer processingTimeSummary; private final Counter failedJobsCounter; private final Counter succeededJobsCounter; public MonitoredScheduledThreadPoolExecutor(final int corePoolSize, @Nonnull final MeterRegistry registry, @Nonnull final String prefix, @Nonnull final Tags tags) { this(corePoolSize, new ThreadFactoryBuilder().setNameFormat("thread-[%d]").build(), registry, prefix, tags); } public MonitoredScheduledThreadPoolExecutor(final int corePoolSize, final ThreadFactory threadFactory, @Nonnull final MeterRegistry registry, @Nonnull final String prefix, @Nonnull final Tags tags) { super(corePoolSize, threadFactory); this.clock = Clock.getDefault(); discrepancySummary = Distribution.key(Key.of("scheduler/discrepancy").withPrefix(prefix)) .unit("percents") .concatTags(tags) .meta(this.getClass()) .register(registry); processingTimeSummary = Timer.key(Key.of("scheduler/processing.time").withPrefix(prefix)) .unit(TimeUnit.MILLISECONDS) .concatTags(tags) .meta(this.getClass()) .register(registry); failedJobsCounter = Counter.key(Key.of("scheduler/jobs/failed").withPrefix(prefix)) .concatTags(tags) .meta(this.getClass()) .register(registry); succeededJobsCounter = Counter.key(Key.of("scheduler/jobs/succeeded").withPrefix(prefix)) .concatTags(tags) .meta(this.getClass()) .register(registry); Gauge.make(Key.of("scheduler/queue.size").withPrefix(prefix), this, executor -> executor.getQueue().size()) .concatTags(tags) .meta(this.getClass()) .register(registry); Gauge.make(Key.of("scheduler/threads.live").withPrefix(prefix), this, executor -> getPoolSize()) .concatTags(tags) .meta(this.getClass()) .register(registry); } @Override @Nonnull public ScheduledFuture<?> scheduleAtFixedRate(final Runnable command, final long initialDelay, final long period, final TimeUnit unit) { CustomFuture<?> future = (CustomFuture<?>) super.scheduleAtFixedRate(command, initialDelay, period, unit); future.setPeriodInNanos(unit.toNanos(period)); return future; } @Override protected <V> RunnableScheduledFuture<V> decorateTask(final Runnable runnable, final RunnableScheduledFuture<V> task) { return new CustomFuture<>(super.decorateTask(runnable, task)); } @Override protected void beforeExecute(final Thread t, final Runnable r) { super.beforeExecute(t, r); if (r instanceof CustomFuture) { CustomFuture<?> future = (CustomFuture<?>) r; Long lastTime = lastRunStartTimes.get(future); long now = clock.monotonicTime(); if (lastTime != null) { long period = future.getPeriodInNanos(); if (period != 0) { int discrepancy = (int) (ONE_HUNDRED_PERCENTS * (Math.abs(now - lastTime - period)) / period); discrepancySummary.record(discrepancy); } } lastRunStartTimes.put(future, now); running.add(future); } } @Override protected void afterExecute(final Runnable runnable, final Throwable throwable) { super.afterExecute(runnable, throwable); Throwable finalThrowable = throwable; if (runnable instanceof CustomFuture) { CustomFuture<?> future = (CustomFuture<?>) runnable; long processingTime = clock.monotonicTime() - lastRunStartTimes.get(future); processingTimeSummary.record(processingTime, TimeUnit.NANOSECONDS); running.remove(future); if (throwable == null && future.isDone()) { try { ((Future) runnable).get(); } catch (CancellationException ce) { finalThrowable = ce; } catch (ExecutionException ee) { finalThrowable = ee.getCause(); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } } if (finalThrowable != null) { failedJobsCounter.increment(); } else { succeededJobsCounter.increment(); } } } } <file_sep>/extensions/readers/anycollect-system-reader/src/main/java/io/github/anycollect/readers/system/CpuConfig.java package io.github.anycollect.readers.system; import org.immutables.value.Value; @Value.Immutable public interface CpuConfig { CpuConfig DEFAULT = new CpuConfig() { }; @Value.Default default int period() { return 5; } @Value.Default default boolean reportActive() { return true; } @Value.Default default boolean perCore() { return true; } @Value.Default default boolean totalCpu() { return true; } } <file_sep>/anycollect-metric/src/test/java/io/github/anycollect/metric/PercentileTest.java package io.github.anycollect.metric; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; class PercentileTest { @Test void percentileValueMustBePositive() { Assertions.assertThrows(IllegalArgumentException.class, () -> Percentile.of(Stat.max(), 0)); } @Test void doublePercentileMustBeConvertedToInteger() { assertThat(Stat.percentile(0.5).getTagValue()).isEqualTo("max_50"); assertThat(Stat.percentile(0.75).getTagValue()).isEqualTo("max_75"); assertThat(Stat.percentile(0.95).getTagValue()).isEqualTo("max_95"); assertThat(Stat.percentile(0.99).getTagValue()).isEqualTo("max_99"); assertThat(Stat.percentile(0.999).getTagValue()).isEqualTo("max_999"); } @Test void differentStatsCanBeUsedForPercentile() { assertThat(Stat.percentile(Stat.MEAN, 0.99).getStat()).isEqualTo(Stat.mean()); } }<file_sep>/anycollect-core/src/main/java/io/github/anycollect/core/impl/pull/PullJob.java package io.github.anycollect.core.impl.pull; import com.google.common.annotations.VisibleForTesting; import io.github.anycollect.core.api.dispatcher.Dispatcher; import io.github.anycollect.core.api.internal.Clock; import io.github.anycollect.core.api.job.Job; import io.github.anycollect.core.api.query.Query; import io.github.anycollect.core.api.target.Target; import io.github.anycollect.core.exceptions.ConnectionException; import io.github.anycollect.core.exceptions.QueryException; import io.github.anycollect.core.impl.pull.availability.Check; import io.github.anycollect.core.impl.pull.availability.CheckingTarget; import io.github.anycollect.meter.api.Counter; import io.github.anycollect.meter.api.MeterRegistry; import io.github.anycollect.metric.Sample; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; import javax.annotation.Nonnull; import java.util.List; import java.util.Objects; public final class PullJob<T extends Target, Q extends Query<T>> implements Runnable { private static final Logger LOG = LoggerFactory.getLogger(PullJob.class); private final CheckingTarget<T> target; private final Q query; private final String group; private final Job job; private final Dispatcher dispatcher; private final Clock clock; private final Counter failed; private final Counter succeeded; @VisibleForTesting PullJob(@Nonnull final CheckingTarget<T> target, @Nonnull final Q query, @Nonnull final Dispatcher dispatcher) { this(target, query, "test", dispatcher, MeterRegistry.noop(), Clock.getDefault()); } public PullJob(@Nonnull final CheckingTarget<T> target, @Nonnull final Q query, @Nonnull final String group, @Nonnull final Dispatcher dispatcher, @Nonnull final MeterRegistry registry, @Nonnull final Clock clock) { Objects.requireNonNull(target, "target must not be null"); Objects.requireNonNull(query, "query must not be null"); Objects.requireNonNull(registry, "registry must not be null"); Objects.requireNonNull(dispatcher, "dispatcher must not be null"); Objects.requireNonNull(clock, "clock must not be null"); this.target = target; this.query = query; this.group = group; this.job = query.bind(target.get()); this.dispatcher = dispatcher; this.clock = clock; this.failed = Counter.key("pull/jobs/failed") .tag("group", group) .tag("target", target.get().getId()) .meta(this.getClass()) .register(registry); this.succeeded = Counter.key("pull/jobs/succeeded") .tag("group", group) .tag("target", target.get().getId()) .meta(this.getClass()) .register(registry); } @Override public void run() { MDC.put("target.id", target.get().getId()); MDC.put("query.id", query.getId()); try { long start = clock.wallTime(); try { List<Sample> samples; synchronized (job) { samples = job.execute(); } succeeded.increment(); dispatcher.dispatch(samples); LOG.debug("success: {}.execute({}) taken {}ms and produces {} metrics", target.get().getId(), query.getId(), clock.wallTime() - start, samples.size()); target.update(Check.passed(start)); } catch (InterruptedException e) { LOG.debug("thread {} is interrupted", Thread.currentThread(), e); Thread.currentThread().interrupt(); } catch (QueryException | ConnectionException | RuntimeException e) { failed.increment(); LOG.debug("failed: {}.execute({}) taken {}ms and failed", target.get().getId(), query.getId(), clock.wallTime() - start, e); if (e instanceof ConnectionException) { target.update(Check.failed(start)); } else { target.update(Check.unknown(start)); } } } finally { MDC.remove("target.id"); MDC.remove("query.id"); } } } <file_sep>/anycollect-meter/src/main/java/io/github/anycollect/meter/impl/AnyCollectMeterRegistryConfig.java package io.github.anycollect.meter.impl; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import io.github.anycollect.metric.Tags; import org.immutables.value.Value; import javax.annotation.Nonnull; @Value.Immutable @Value.Style(builder = "new", stagedBuilder = true, passAnnotations = {Nonnull.class}) @JsonDeserialize(builder = ImmutableAnyCollectMeterRegistryConfig.Builder.class) public interface AnyCollectMeterRegistryConfig { static ImmutableAnyCollectMeterRegistryConfig.Builder builder() { return new ImmutableAnyCollectMeterRegistryConfig.Builder(); } AnyCollectMeterRegistryConfig DEFAULT = new AnyCollectMeterRegistryConfig() { }; @Nonnull @Value.Default default String globalPrefix() { return ""; } @Nonnull @Value.Default default Tags commonTags() { return Tags.empty(); } @Nonnull @Value.Default default Tags commonMeta() { return Tags.empty(); } } <file_sep>/anycollect-extension-system/src/main/java/io/github/anycollect/extensions/dependencies/Dependency.java package io.github.anycollect.extensions.dependencies; import io.github.anycollect.extensions.di.InjectionPoint; public interface Dependency { InjectionPoint inject(); } <file_sep>/anycollect-agent/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>anycollect-parent</artifactId> <groupId>io.github.anycollect</groupId> <version>0.0.1-SNAPSHOT</version> <relativePath>../anycollect-parent/pom.xml</relativePath> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>anycollect-agent</artifactId> <dependencyManagement> <dependencies> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>${logback.version}</version> <scope>compile</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>io.github.anycollect</groupId> <artifactId>anycollect-anycollect</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>io.github.anycollect</groupId> <artifactId>anycollect-core-api</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>io.github.anycollect</groupId> <artifactId>anycollect-core</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>io.github.anycollect</groupId> <artifactId>anycollect-extension-annotations</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>io.github.anycollect</groupId> <artifactId>anycollect-extension-system</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>io.github.anycollect</groupId> <artifactId>anycollect-common-expression</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>io.github.anycollect</groupId> <artifactId>anycollect-system-reader</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>io.github.anycollect</groupId> <artifactId>anycollect-jmx-reader</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>io.github.anycollect</groupId> <artifactId>anycollect-meter</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>io.github.anycollect</groupId> <artifactId>anycollect-consul-kv</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>io.github.anycollect</groupId> <artifactId>anycollect-async-socket-reader</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>io.github.anycollect</groupId> <artifactId>anycollect-jackson-guava</artifactId> <version>${project.version}</version> </dependency> <!-- CLI --> <dependency> <groupId>info.picocli</groupId> <artifactId>picocli</artifactId> </dependency> <!-- LOGGING --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <executions> <execution> <id>copy-dependencies</id> <phase>prepare-package</phase> <goals> <goal>copy-dependencies</goal> </goals> <configuration> <outputDirectory> target/libs </outputDirectory> </configuration> </execution> </executions> </plugin> <plugin> <groupId>com.spotify</groupId> <artifactId>dockerfile-maven-plugin</artifactId> <version>1.4.10</version> <executions> <execution> <id>default</id> <phase>deploy</phase> <goals> <goal>build</goal> </goals> </execution> </executions> <configuration> <skip>${docker.images.build.skip}</skip> <repository>anycollect/anycollect</repository> <buildArgs> <JAR_FILE>target/anycollect-${project.version}.jar</JAR_FILE> </buildArgs> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <version>3.2.1</version> <configuration> <dependencyReducedPomLocation>target/dependency-reduced-pom.xml</dependencyReducedPomLocation> </configuration> <executions> <execution> <goals> <goal>shade</goal> </goals> <configuration> <transformers> <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer"> <resource>anycollect-manifest.yaml</resource> </transformer> <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"> <mainClass>io.github.anycollect.Init</mainClass> </transformer> </transformers> </configuration> </execution> </executions> </plugin> </plugins> </build> </project><file_sep>/extensions/readers/anycollect-system-reader/src/main/java/io/github/anycollect/readers/process/EphemeralProcess.java package io.github.anycollect.readers.process; import io.github.anycollect.core.api.target.AbstractTarget; import io.github.anycollect.core.exceptions.ConnectionException; import io.github.anycollect.metric.Tags; import oshi.software.os.OSProcess; import javax.annotation.Nonnull; /** * The system process that have to be live but it is not. */ public final class EphemeralProcess extends AbstractTarget implements Process { public EphemeralProcess(@Nonnull final String id, @Nonnull final Tags tags, @Nonnull final Tags meta) { super(id, tags, meta); } @Override public OSProcess snapshot() throws ConnectionException { throw new ConnectionException("process is dead"); } } <file_sep>/anycollect-meter-api/src/main/java/io/github/anycollect/meter/api/Timer.java package io.github.anycollect.meter.api; import io.github.anycollect.metric.Key; import org.apiguardian.api.API; import javax.annotation.Nonnull; import java.util.concurrent.TimeUnit; @API(since = "0.1.0", status = API.Status.EXPERIMENTAL) public interface Timer { Timer NOOP = new Timer() { @Override public void record(final long amount, @Nonnull final TimeUnit timeUnit) { } @Override public void record(@Nonnull final Runnable runnable) { runnable.run(); } }; static TimerBuilder key(@Nonnull final String key) { return new TimerBuilder(Key.of(key)); } static TimerBuilder key(@Nonnull final Key key) { return new TimerBuilder(key); } void record(long amount, @Nonnull TimeUnit timeUnit); void record(@Nonnull Runnable runnable); final class TimerBuilder extends BaseMeterBuilder<TimerBuilder> { private TimeUnit timeUnit = TimeUnit.NANOSECONDS; TimerBuilder(@Nonnull final Key key) { super(key); } @Override protected TimerBuilder self() { return this; } public TimerBuilder unit(@Nonnull final TimeUnit timeUnit) { this.timeUnit = timeUnit; switch (timeUnit) { case NANOSECONDS: super.unit("ns"); break; case MILLISECONDS: super.unit("ms"); break; case SECONDS: super.unit("s"); break; default: super.unit(timeUnit.name().toLowerCase()); } return this; } public Timer register(@Nonnull final MeterRegistry registry) { ImmutableMeterId id = new ImmutableMeterId( getKey(), getUnit(), getTagsBuilder().build(), getMetaBuilder().build()); return registry.timer(id, timeUnit); } } } <file_sep>/anycollect-meter-api/src/main/java/io/github/anycollect/meter/api/NoopMeterRegistry.java package io.github.anycollect.meter.api; import javax.annotation.Nonnull; import java.util.concurrent.TimeUnit; import java.util.function.ToDoubleFunction; import java.util.function.ToLongFunction; final class NoopMeterRegistry extends MeterRegistry { static final NoopMeterRegistry INSTANCE = new NoopMeterRegistry(); private NoopMeterRegistry() { } @Nonnull @Override public <T> Gauge gauge(@Nonnull final MeterId id, @Nonnull final T obj, @Nonnull final ToDoubleFunction<T> value) { return Gauge.NOOP; } @Nonnull @Override public Counter counter(@Nonnull final MeterId id) { return Counter.NOOP; } @Nonnull @Override public <T> FunctionCounter counter(@Nonnull final MeterId id, @Nonnull final T obj, @Nonnull final ToLongFunction<T> value) { return FunctionCounter.NOOP; } @Nonnull @Override public Distribution distribution(@Nonnull final MeterId id) { return Distribution.NOOP; } @Nonnull @Override public Timer timer(@Nonnull final MeterId id, @Nonnull final TimeUnit timeUnit) { return Timer.NOOP; } } <file_sep>/extensions/readers/anycollect-jmx-reader/src/test/java/io/github/anycollect/readers/jmx/utils/HistogramTest.java package io.github.anycollect.readers.jmx.utils; public class HistogramTest implements HistogramTestMBean { @Override public double getMin() { return 1; } @Override public double getMax() { return 2; } @Override public double getMean() { return 3; } @Override public double getStdDev() { return 4; } @Override public double get50thPercentile() { return 50; } @Override public double get75thPercentile() { return 75; } @Override public double get90thPercentile() { return 90; } @Override public double get95thPercentile() { return 95; } @Override public double get99thPercentile() { return 99; } } <file_sep>/anycollect-core-api/src/main/java/io/github/anycollect/core/api/internal/Cancellation.java package io.github.anycollect.core.api.internal; public interface Cancellation { Cancellation NOOP = () -> { }; static Cancellation noop() { return NOOP; } default Cancellation andThen(Cancellation cancellation) { return () -> { cancel(); cancellation.cancel(); }; } void cancel(); } <file_sep>/anycollect-core/src/main/java/io/github/anycollect/core/impl/filters/CoreFiltersJacksonModule.java package io.github.anycollect.core.impl.filters; import com.fasterxml.jackson.core.Version; import com.fasterxml.jackson.databind.Module; import io.github.anycollect.core.impl.filters.tag.GenericTagFilter; import io.github.anycollect.extensions.annotations.Extension; @Extension( name = CoreFiltersJacksonModule.NAME, contracts = Module.class, autoload = @Extension.AutoLoad(instanceName = CoreFiltersJacksonModule.INSTANCE_NAME) ) public final class CoreFiltersJacksonModule extends Module { public static final String NAME = "CoreFiltersJacksonModule"; public static final String MODULE_NAME = "AnyCollectCoreFiltersModule"; public static final String INSTANCE_NAME = "coreFiltersJacksonModule"; @Override public String getModuleName() { return MODULE_NAME; } @Override public Version version() { return Version.unknownVersion(); } @Override public void setupModule(final SetupContext context) { context.registerSubtypes( AcceptAllFilter.class, AcceptKeyFilter.class, DenyAllFilter.class, DenyKeyFilter.class, GenericTagFilter.class ); } } <file_sep>/extensions/readers/anycollect-jmx-reader/src/test/java/io/github/anycollect/readers/jmx/server/pool/impl/CommonsJmxConnectionFactoryAdapterTest.java package io.github.anycollect.readers.jmx.server.pool.impl; import io.github.anycollect.readers.jmx.server.JmxConnection; import io.github.anycollect.readers.jmx.server.JmxConnectionFactory; import io.github.anycollect.readers.jmx.server.pool.AsyncConnectionCloser; import org.apache.commons.pool2.impl.DefaultPooledObject; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; class CommonsJmxConnectionFactoryAdapterTest { @Test void destroyConnectionTest() { JmxConnectionFactory factory = mock(JmxConnectionFactory.class); AsyncConnectionCloser closer = mock(AsyncConnectionCloser.class); CommonsJmxConnectionFactoryAdapter adapter = new CommonsJmxConnectionFactoryAdapter(factory, closer); JmxConnection jmxConnection = mock(JmxConnection.class); adapter.destroyObject(new DefaultPooledObject<>(jmxConnection)); verify(closer, times(1)).closeAsync(any()); verify(jmxConnection, times(1)).markAsDestroyed(); assertThat(jmxConnection.isAlive()).isFalse(); } }<file_sep>/anycollect-core/src/main/java/io/github/anycollect/core/impl/filters/tag/TagExistence.java package io.github.anycollect.core.impl.filters.tag; public enum TagExistence { PRESENT, ABSENT } <file_sep>/anycollect-core/src/main/java/io/github/anycollect/core/impl/self/SelfDiscoveryConfig.java package io.github.anycollect.core.impl.self; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import org.immutables.value.Value; @Value.Immutable @JsonSerialize(as = ImmutableSelfDiscoveryConfig.class) @JsonDeserialize(as = ImmutableSelfDiscoveryConfig.class) public interface SelfDiscoveryConfig { SelfDiscoveryConfig DEFAULT = new SelfDiscoveryConfig() { }; static ImmutableSelfDiscoveryConfig.Builder builder() { return ImmutableSelfDiscoveryConfig.builder(); } @Value.Default @JsonProperty("targetId") default String targetId() { return "anycollect-self"; } } <file_sep>/anycollect-core-api/src/main/java/io/github/anycollect/core/api/target/SelfDiscovery.java package io.github.anycollect.core.api.target; import java.util.Collections; import java.util.Set; public interface SelfDiscovery extends ServiceDiscovery<SelfTarget> { SelfTarget self(); @Override default Set<SelfTarget> discover() { return Collections.singleton(self()); } } <file_sep>/anycollect-test-utils/anycollect-jmx-stub/src/main/java/io/github/anycollect/testing/jmx/JmxStub.java package io.github.anycollect.testing.jmx; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; import com.fasterxml.jackson.datatype.guava.GuavaModule; import com.google.common.net.HostAndPort; import com.orbitz.consul.AgentClient; import com.orbitz.consul.Consul; import com.orbitz.consul.KeyValueClient; import com.orbitz.consul.cache.KVCache; import com.orbitz.consul.model.agent.ImmutableRegistration; import com.orbitz.consul.model.agent.Registration; import com.orbitz.consul.model.kv.Value; import oshi.SystemInfo; import javax.management.MBeanServer; import javax.management.ObjectName; import java.io.IOException; import java.lang.management.ManagementFactory; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.*; public final class JmxStub { private static final ObjectMapper JSON_OBJECT_MAPPER = new ObjectMapper(); private static final ObjectMapper YAML_OBJECT_MAPPER = new ObjectMapper(new YAMLFactory()); private volatile JmxConfig appliedConfig; private volatile long delay = 0; static { JSON_OBJECT_MAPPER.registerModule(new GuavaModule()); YAML_OBJECT_MAPPER.registerModule(new GuavaModule()); } private JmxStub() { this.appliedConfig = JmxConfig.empty(); } public static void main(final String... args) throws Exception { String host = System.getProperty("java.rmi.server.hostname"); String port = System.getProperty("com.sun.management.jmxremote.rmi.port"); System.out.println("jmx host: " + host + ", port: " + port); String node = args[0]; String serviceId = args[1]; String consulHost = args[2]; int consulPort = Integer.parseInt(args[3]); Consul client = Consul.builder() .withHostAndPort(HostAndPort.fromParts(consulHost, consulPort)) .build(); String pidFile = args[4]; System.out.println("pid file: \"" + pidFile + "\""); int pid = new SystemInfo().getOperatingSystem().getProcessId(); System.out.println("pid: " + pid); Files.write(Paths.get(pidFile), Collections.singletonList(Integer.toString(pid)), StandardOpenOption.CREATE, StandardOpenOption.WRITE); Registration service = ImmutableRegistration.builder() .id(serviceId) .name("stub") .build(); AgentClient agentClient = client.agentClient(); agentClient.register(service); KeyValueClient kvs = client.keyValueClient(); KVCache kvCache = KVCache.newCache(kvs, "jmx-stub/"); JmxStub jmxStub = new JmxStub(); kvCache.addListener(map -> { Value confValue = map.get("conf"); JmxConfig conf = JmxConfig.empty(); if (confValue != null) { conf = confValue.getValueAsString().map(str -> { try { return YAML_OBJECT_MAPPER.readValue(str, JmxConfig.class); } catch (IOException e) { e.printStackTrace(); return null; } }).orElse(JmxConfig.empty()); } Value delayValue = map.get(serviceId + "/delay"); long delay = 0L; if (delayValue != null) { delay = delayValue.getValueAsString().map(Long::parseLong).orElse(0L); } jmxStub.configure(conf, delay); }); kvCache.start(); ImmutableJmxRegistration jmxRegistration = JmxRegistration.builder() .id(serviceId) .host(host) .port(port) .build(); kvs.putValue( "/anycollect/jmx/" + node + "/" + serviceId, JSON_OBJECT_MAPPER.writeValueAsString(jmxRegistration) ); Thread thread = new Thread(() -> { while (true) { try { Thread.sleep(1000); if (Thread.currentThread().isInterrupted()) { System.out.println("stopping thread"); return; } } catch (InterruptedException e) { System.out.println("stopping thread"); Thread.currentThread().interrupt(); return; } } }); thread.setDaemon(false); thread.start(); Runtime.getRuntime().addShutdownHook(new Thread(() -> { System.out.println("graceful shutdown"); agentClient.deregister(serviceId); kvCache.stop(); kvs.deleteKey("/anycollect/jmx/" + node + "/" + serviceId); thread.interrupt(); System.out.println("service has been successfully deregistered from consul"); try { Files.delete(Paths.get(pidFile)); } catch (IOException e) { System.out.println("fail to delete pid file " + pidFile); } System.out.println("pid file has been successfully deleted"); })); } private void configure(final JmxConfig config, final long delay) { System.out.println("configure: " + config + " " + delay); if (config.equals(appliedConfig) && this.delay == delay) { System.out.println("no changes"); return; } String domain = config.domain(); MBeanServer server = ManagementFactory.getPlatformMBeanServer(); try { for (MBeanDefinition mBeanDefinition : appliedConfig.mbeans()) { List<ObjectName> objectNames = resolve(domain, mBeanDefinition); for (ObjectName objectName : objectNames) { System.out.println("unregister " + objectName); server.unregisterMBean(objectName); } } for (MBeanDefinition mBeanDefinition : config.mbeans()) { List<ObjectName> objectNames = resolve(domain, mBeanDefinition); for (ObjectName objectName : objectNames) { System.out.println("register " + objectName); if (mBeanDefinition.type() == MBeanType.HISTOGRAM) { server.registerMBean(new Histogram(delay), objectName); } if (mBeanDefinition.type() == MBeanType.COUNTER) { server.registerMBean(new Counter(delay), objectName); } if (mBeanDefinition.type() == MBeanType.GAUGE) { server.registerMBean(new Gauge(delay), objectName); } } } this.appliedConfig = config; this.delay = delay; } catch (Exception e) { e.printStackTrace(); } } private static List<ObjectName> resolve(final String domain, final MBeanDefinition mBeanDefinition) throws Exception { Set<Map.Entry<String, List<String>>> entries = mBeanDefinition.keys().entrySet(); List<Map.Entry<String, List<String>>> list = new ArrayList<>(entries); ArrayList<ObjectName> accumulator = new ArrayList<>(); resolve(domain, new HashMap<>(), list, accumulator, 0); return accumulator; } private static void resolve(final String domain, final Map<String, String> properties, final List<Map.Entry<String, List<String>>> entries, final List<ObjectName> accumulator, final int index) throws Exception { if (index == entries.size()) { ObjectName objectName = new ObjectName(domain, new Hashtable<>(properties)); accumulator.add(objectName); return; } Map.Entry<String, List<String>> entry = entries.get(index); String key = entry.getKey(); List<String> values = entry.getValue(); for (String value : values) { properties.put(key, value); resolve(domain, properties, entries, accumulator, index + 1); properties.remove(key, value); } } } <file_sep>/anycollect-metric/src/test/java/io/github/anycollect/metric/StatTest.java package io.github.anycollect.metric; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; class StatTest { @Test void parseStringTest() { assertThat(Stat.parse("min")).isSameAs(Stat.min()); assertThat(Stat.parse("max")).isSameAs(Stat.max()); assertThat(Stat.parse("mean")).isSameAs(Stat.mean()); assertThat(Stat.parse("std")).isSameAs(Stat.std()); assertThat(Stat.parse("max_99")).isEqualTo(Percentile.of(Stat.max(), 99)); assertThat(Stat.parse("le_Infinity")).isInstanceOf(LeBucket.class) .extracting(stat -> ((LeBucket) stat).getMax()) .isEqualTo(Double.POSITIVE_INFINITY); assertThat(Stat.parse("le_100")).isInstanceOf(LeBucket.class) .extracting(stat -> ((LeBucket) stat).getMax()) .isEqualTo(100.0); assertThat(Stat.parse("le_0.05")).isInstanceOf(LeBucket.class) .extracting(stat -> ((LeBucket) stat).getMax()) .isEqualTo(0.05); IllegalArgumentException ex = Assertions.assertThrows(IllegalArgumentException.class, () -> Stat.parse("undefined")); assertThat(ex).hasMessageContaining("undefined"); } @Test void tagValueTest() { assertThat(Stat.min().getTagValue()).isEqualTo("min").isEqualTo(Stat.min().toString()); assertThat(Stat.max().getTagValue()).isEqualTo("max").isEqualTo(Stat.max().toString()); assertThat(Stat.mean().getTagValue()).isEqualTo("mean").isEqualTo(Stat.mean().toString()); assertThat(Stat.std().getTagValue()).isEqualTo("std").isEqualTo(Stat.std().toString()); assertThat(Stat.percentile(99).getTagValue()).isEqualTo("max_99").isEqualTo(Stat.percentile(99).toString()); assertThat(Stat.percentile(999).getTagValue()).isEqualTo("max_999").isEqualTo(Stat.percentile(999).toString()); assertThat(Stat.le(0.4).getTagValue()).isEqualTo("le_0.4").isEqualTo(Stat.le(0.4).toString()); assertThat(Stat.le(120).getTagValue()).isEqualTo("le_120").isEqualTo(Stat.le(120).toString()); assertThat(Stat.leInf().getTagValue()).isEqualTo("le_Infinity").isEqualTo(Stat.leInf().toString()); assertThat(Stat.gauge().getTagValue()).isEqualTo("gauge").isEqualTo(Stat.gauge().toString()); assertThat(Stat.counter().getTagValue()).isEqualTo("counter").isEqualTo(Stat.counter().toString()); } @Test void validationTest() { assertThat(Stat.isValid(Stat.min())).isTrue(); assertThat(Stat.isValid(Stat.max())).isTrue(); assertThat(Stat.isValid(Stat.mean())).isTrue(); assertThat(Stat.isValid(Stat.std())).isTrue(); assertThat(Stat.isValid(Percentile.of(Stat.max(), 75))).isTrue(); assertThat(Stat.isValid(LeBucket.inf())).isTrue(); assertThat(Stat.isValid(LeBucket.of(100))).isTrue(); assertThat(Stat.isValid(LeBucket.of(0.6))).isTrue(); assertThat(Stat.isValid(new Stat() { @Override public StatType getType() { return StatType.MIN; } @Override public String getTagValue() { return "custom_min"; } })).isFalse(); } }<file_sep>/extensions/readers/anycollect-system-reader/src/main/java/io/github/anycollect/readers/process/discovery/pidfile/PidFileProcessDiscovery.java package io.github.anycollect.readers.process.discovery.pidfile; import io.github.anycollect.core.api.target.ServiceDiscovery; import io.github.anycollect.core.exceptions.ConfigurationException; import io.github.anycollect.extensions.annotations.ExtConfig; import io.github.anycollect.extensions.annotations.ExtCreator; import io.github.anycollect.extensions.annotations.Extension; import io.github.anycollect.metric.Tags; import io.github.anycollect.readers.process.EphemeralProcess; import io.github.anycollect.readers.process.LiveProcess; import io.github.anycollect.readers.process.Process; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import oshi.SystemInfo; import oshi.software.os.OSProcess; import oshi.software.os.OperatingSystem; import javax.annotation.Nonnull; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.*; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; @Extension(name = PidFileProcessDiscovery.NAME, contracts = ServiceDiscovery.class) public final class PidFileProcessDiscovery implements ServiceDiscovery<Process> { public static final String NAME = "PidFileProcessDiscovery"; private static final Logger LOG = LoggerFactory.getLogger(PidFileProcessDiscovery.class); private final WatchService watchService; private final Set<PidFileTargetDefinition> targets; private final Map<PidFileTargetDefinition, Process> processes; private final OperatingSystem os; @ExtCreator public PidFileProcessDiscovery(@ExtConfig @Nonnull final PidFileProcessDiscoveryConfig config) throws ConfigurationException { try { watchService = FileSystems.getDefault().newWatchService(); } catch (IOException e) { throw new ConfigurationException("could not create watch service to monitor changes in pid files", e); } os = new SystemInfo().getOperatingSystem(); processes = new HashMap<>(); targets = new HashSet<>(); for (PidFileTargetDefinition target : config.watch()) { Path pidFile = target.file(); if (pidFile.toFile().isDirectory()) { throw new ConfigurationException("pid file must not be directory"); } targets.add(target); Path pidDir = pidFile.getParent(); try { pidDir.register( watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY); } catch (IOException e) { throw new ConfigurationException("could not watch pid file: " + pidFile, e); } Process process = createProcess(target); processes.put(target, process); } } @Override public Set<Process> discover() { // remove processes whose pid files have been changed to refresh them WatchKey watchKey = watchService.poll(); if (watchKey != null) { for (WatchEvent<?> event : watchKey.pollEvents()) { Path pidFile = ((Path) watchKey.watchable()).resolve((Path) event.context()); PidFileTargetDefinition found = null; for (PidFileTargetDefinition def : targets) { if (def.file().equals(pidFile)) { found = def; break; } } if (found != null && (event.kind().equals(StandardWatchEventKinds.ENTRY_MODIFY) || event.kind().equals(StandardWatchEventKinds.ENTRY_CREATE) || event.kind().equals(StandardWatchEventKinds.ENTRY_DELETE))) { LOG.debug("pid file {} has been changed", pidFile); processes.remove(found); } } watchKey.reset(); } // delete ephemeral processes to refresh them for (PidFileTargetDefinition target : targets) { Process process = processes.get(target); if (process instanceof EphemeralProcess) { processes.remove(target); } } // form result target set Set<Process> result = new HashSet<>(); for (PidFileTargetDefinition target : targets) { if (!processes.containsKey(target)) { Process process = createProcess(target); result.add(process); processes.put(target, process); } else { result.add(processes.get(target)); } } return result; } @Nonnull private Process createProcess(final PidFileTargetDefinition def) { Path pidFile = def.file(); if (!pidFile.toFile().exists()) { LOG.debug("pid file {} has not been created yet", pidFile); return new EphemeralProcess(def.targetId(), def.tags(), Tags.empty()); } int pid; try { pid = Integer.parseInt(Files.readAllLines(pidFile, StandardCharsets.UTF_8).get(0)); } catch (IOException | NumberFormatException e) { LOG.warn("could not read pid from pid file {}", pidFile, e); return new EphemeralProcess(def.targetId(), def.tags(), Tags.empty()); } OSProcess process = os.getProcess(pid); if (process == null) { LOG.debug("there is no process with pid {} for now", pid); return new EphemeralProcess(def.targetId(), def.tags(), Tags.empty()); } return new LiveProcess(os, def.targetId(), pid, def.tags(), Tags.of("pid.file", pidFile.toFile().getAbsolutePath())); } } <file_sep>/extensions/readers/anycollect-jmx-reader/src/main/java/io/github/anycollect/readers/jmx/server/pool/JmxConnectionPool.java package io.github.anycollect.readers.jmx.server.pool; import io.github.anycollect.core.exceptions.ConnectionException; import io.github.anycollect.readers.jmx.server.JmxConnection; import javax.annotation.Nonnull; public interface JmxConnectionPool { @Nonnull JmxConnection borrowConnection() throws ConnectionException; void invalidateConnection(@Nonnull JmxConnection connection); void returnConnection(@Nonnull JmxConnection connection); int getNumActive(); int getNumIdle(); long getTotalInvalidated(); } <file_sep>/extensions/readers/anycollect-system-reader/src/main/java/io/github/anycollect/readers/process/discovery/current/CurrentProcessDiscovery.java package io.github.anycollect.readers.process.discovery.current; import io.github.anycollect.core.api.target.ServiceDiscovery; import io.github.anycollect.extensions.annotations.ExtConfig; import io.github.anycollect.extensions.annotations.ExtCreator; import io.github.anycollect.extensions.annotations.Extension; import io.github.anycollect.metric.Tags; import io.github.anycollect.readers.process.LiveProcess; import io.github.anycollect.readers.process.Process; import oshi.SystemInfo; import oshi.software.os.OperatingSystem; import javax.annotation.Nonnull; import java.util.Collections; import java.util.Set; @Extension(name = CurrentProcessDiscovery.NAME, contracts = ServiceDiscovery.class) public final class CurrentProcessDiscovery implements ServiceDiscovery<Process> { public static final String NAME = "CurrentProcessDiscovery"; private final Process process; @ExtCreator public CurrentProcessDiscovery(@ExtConfig @Nonnull final CurrentProcessDiscoveryConfig config) { OperatingSystem os = new SystemInfo().getOperatingSystem(); int pid = os.getProcessId(); this.process = new LiveProcess(new SystemInfo().getOperatingSystem(), config.targetId(), pid, config.tags(), Tags.empty()); } @Override public Set<Process> discover() { return Collections.singleton(process); } } <file_sep>/anycollect-agent/Dockerfile FROM openjdk:8-jre-alpine MAINTAINER <NAME> ARG JAR_FILE ADD ${JAR_FILE} app.jar ADD target/libs/* libs/ ENTRYPOINT /usr/bin/java -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.local.only=false -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Djava.rmi.server.hostname=${JMX_HOST} -Dcom.sun.management.jmxremote.rmi.port=${JMX_PORT} -Dcom.sun.management.jmxremote.port=${JMX_PORT} -Xms512m -Xmx512m -jar app.jar @/anycollect/args <file_sep>/extensions/readers/anycollect-jmx-reader/src/main/java/io/github/anycollect/readers/jmx/query/operations/Subscription.java package io.github.anycollect.readers.jmx.query.operations; public final class Subscription { private volatile boolean valid = true; public boolean isValid() { return valid; } public void invalidate() { this.valid = false; } } <file_sep>/anycollect-core/src/main/java/io/github/anycollect/core/impl/writers/socket/TcpSender.java package io.github.anycollect.core.impl.writers.socket; import io.github.anycollect.core.api.internal.AdaptiveSerializer; import io.github.anycollect.core.exceptions.SerialisationException; import io.github.anycollect.metric.Sample; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nonnull; import javax.net.SocketFactory; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.Socket; import java.nio.ByteBuffer; public final class TcpSender implements Sender { private static final Logger LOG = LoggerFactory.getLogger(TcpSender.class); private final InetSocketAddress address; private final SocketFactory socketFactory; private final AdaptiveSerializer serializer; private volatile Socket socket; private volatile OutputStream outputStream; public TcpSender(final String host, final int port, final AdaptiveSerializer serializer) { this.socketFactory = SocketFactory.getDefault(); this.address = new InetSocketAddress(host, port); this.serializer = serializer; } @Override public void connected() throws IOException { if (isConnected()) { return; } this.socket = socketFactory.createSocket(address.getAddress(), address.getPort()); this.outputStream = new BufferedOutputStream(socket.getOutputStream()); } @Override public boolean isConnected() { return socket != null && socket.isConnected() && !socket.isClosed(); } @Override public void send(@Nonnull final Sample sample) throws SerialisationException, IOException { ByteBuffer buffer = serializer.serialize(sample); try { outputStream.write(buffer.array(), 0, buffer.limit()); } finally { serializer.release(buffer); } } @Override public void flush() throws IOException { if (outputStream != null) { outputStream.flush(); } } @Override public void closed() { try { if (outputStream != null) { outputStream.close(); } } catch (IOException e) { LOG.debug("unable to close output stream", e); } finally { this.outputStream = null; } try { if (socket != null) { socket.close(); } } catch (IOException e) { LOG.debug("unable to close socket", e); } finally { this.socket = null; } } } <file_sep>/anycollect-metric/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>anycollect-parent</artifactId> <groupId>io.github.anycollect</groupId> <version>0.0.1-SNAPSHOT</version> <relativePath>../anycollect-parent/pom.xml</relativePath> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>anycollect-metric</artifactId> <dependencies> <!-- TESTING --> <dependency> <groupId>org.openjdk.jmh</groupId> <artifactId>jmh-core</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.openjdk.jmh</groupId> <artifactId>jmh-generator-annprocess</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> <version>3.1.1</version> <configuration> <quiet>true</quiet> <notimestamp>true</notimestamp> <show>public</show> <encoding>UTF-8</encoding> <docencoding>UTF-8</docencoding> <charset>UTF-8</charset> <additionalOptions> <additionalOption>-XDignore.symbol.file</additionalOption> <additionalOption>-Xdoclint:-html</additionalOption> </additionalOptions> </configuration> </plugin> </plugins> </build> <reporting> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> </plugin> </plugins> </reporting> </project><file_sep>/extensions/common/anycollect-common-expression/src/main/java/io/github/anycollect/extensions/common/expression/parser/Token.java package io.github.anycollect.extensions.common.expression.parser; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; @Getter @ToString @EqualsAndHashCode public final class Token { private final TokenType type; private final String sequence; public static Token of(final TokenType type, final String sequence) { return new Token(type, sequence); } private Token(final TokenType type, final String sequence) { this.type = type; this.sequence = sequence; } } <file_sep>/anycollect-core/src/main/java/io/github/anycollect/core/impl/matcher/RegExpMatchRule.java package io.github.anycollect.core.impl.matcher; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import io.github.anycollect.core.api.query.Query; import io.github.anycollect.core.api.target.Target; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; import java.util.regex.Pattern; @Immutable public class RegExpMatchRule implements MatchRule { private final Pattern instanceIdPattern; private final Pattern queryIdPattern; private final int periodInSeconds; @JsonCreator public RegExpMatchRule( @JsonProperty(value = "instanceId") @Nullable final String instanceIdPattern, @JsonProperty(value = "queryId", required = true) @Nonnull final String queryIdPattern, @JsonProperty(value = "period", required = true) final int periodInSeconds) { this.instanceIdPattern = instanceIdPattern != null ? Pattern.compile(instanceIdPattern) : Pattern.compile(".*"); this.queryIdPattern = Pattern.compile(queryIdPattern); this.periodInSeconds = periodInSeconds; } @Override public boolean match(@Nonnull final Target target, @Nonnull final Query query) { return instanceIdPattern.matcher(target.getId()).matches() && queryIdPattern.matcher(query.getId()).matches(); } @Override public int getPeriod() { return periodInSeconds; } } <file_sep>/extensions/common/anycollect-common-expression/src/main/java/io/github/anycollect/extensions/common/expression/ast/PipeExpressionNode.java package io.github.anycollect.extensions.common.expression.ast; import io.github.anycollect.extensions.common.expression.EvaluationException; import io.github.anycollect.extensions.common.expression.ast.visitor.ExpressionNodeVisitor; import lombok.ToString; import java.util.ArrayList; import java.util.List; @ToString public final class PipeExpressionNode implements ValueExpressionNode { private final ValueExpressionNode base; private final List<FilterExpressionNode> filters = new ArrayList<>(); public PipeExpressionNode(final ValueExpressionNode base) { this.base = base; } public void add(final FilterExpressionNode node) { this.filters.add(node); } @Override public void accept(final ExpressionNodeVisitor visitor) { visitor.visit(this); base.accept(visitor); for (FilterExpressionNode filter : filters) { filter.accept(visitor); } } @Override public String getValue() throws EvaluationException { String value = base.getValue(); for (FilterExpressionNode filter : filters) { value = filter.filter(value); } return value; } @Override public boolean isResolved() { return base.isResolved(); } } <file_sep>/anycollect-extension-annotations/src/main/java/io/github/anycollect/extensions/annotations/Extension.java package io.github.anycollect.extensions.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface Extension { String name(); Class<?>[] contracts() default {}; AutoLoad autoload() default @Extension.AutoLoad(instanceName = "", enabled = false); @interface AutoLoad { String instanceName(); InjectMode injectMode() default InjectMode.AUTO; boolean enabled() default true; } } <file_sep>/extensions/readers/anycollect-jmx-reader/src/main/java/io/github/anycollect/readers/jmx/query/operations/QueryOperation.java package io.github.anycollect.readers.jmx.query.operations; import io.github.anycollect.core.exceptions.ConnectionException; import io.github.anycollect.core.exceptions.QueryException; import io.github.anycollect.readers.jmx.server.JmxConnection; import javax.annotation.Nonnull; import javax.management.MBeanServerConnection; public interface QueryOperation<T> { default T operate(@Nonnull JmxConnection connection) throws QueryException, ConnectionException { return operate(connection.getConnection()); } T operate(@Nonnull MBeanServerConnection connection) throws QueryException, ConnectionException; } <file_sep>/extensions/readers/anycollect-jmx-reader/src/main/java/io/github/anycollect/readers/jmx/query/Restriction.java package io.github.anycollect.readers.jmx.query; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import javax.annotation.Nonnull; import javax.management.ObjectName; @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", defaultImpl = Whitelist.class) @JsonSubTypes( @JsonSubTypes.Type(value = Whitelist.class, name = "whitelist")) public interface Restriction { Restriction ALL = objectName -> true; @Nonnull static Restriction all() { return ALL; } boolean allows(@Nonnull ObjectName objectName); } <file_sep>/anycollect-core/src/main/java/io/github/anycollect/core/impl/router/MetricProcessor.java package io.github.anycollect.core.impl.router; public interface MetricProcessor extends MetricProducer, MetricConsumer, RouterNode { } <file_sep>/anycollect-core-api/src/main/java/io/github/anycollect/core/api/SyncReader.java package io.github.anycollect.core.api; import io.github.anycollect.core.api.dispatcher.Dispatcher; import io.github.anycollect.core.exceptions.ConnectionException; import io.github.anycollect.core.exceptions.QueryException; import javax.annotation.Nonnull; public interface SyncReader extends Route { void read(@Nonnull Dispatcher dispatcher) throws InterruptedException, QueryException, ConnectionException; void stop(); @Nonnull default String getTargetId() { return getId(); } @Nonnull default String getQueryId() { return getId(); } int getPeriod(); } <file_sep>/anycollect-core-api/src/main/java/io/github/anycollect/core/api/job/DeadTargetJob.java package io.github.anycollect.core.api.job; import io.github.anycollect.core.exceptions.ConnectionException; import io.github.anycollect.metric.Sample; import java.util.List; public final class DeadTargetJob implements Job { @Override public List<Sample> execute() throws ConnectionException { throw new ConnectionException("target is dead"); } } <file_sep>/extensions/readers/anycollect-system-reader/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>anycollect-parent</artifactId> <groupId>io.github.anycollect</groupId> <version>0.0.1-SNAPSHOT</version> <relativePath>../../../anycollect-parent/pom.xml</relativePath> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>anycollect-system-reader</artifactId> <dependencies> <dependency> <groupId>io.github.anycollect</groupId> <artifactId>anycollect-core-api</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>io.github.anycollect</groupId> <artifactId>anycollect-core</artifactId> <version>${project.version}</version> </dependency> <!-- EXTENSIONS --> <dependency> <groupId>com.github.oshi</groupId> <artifactId>oshi-core</artifactId> </dependency> </dependencies> </project><file_sep>/anycollect-core/src/main/java/io/github/anycollect/core/impl/scheduler/ThrottledRunnable.java package io.github.anycollect.core.impl.scheduler; import io.github.anycollect.meter.api.Counter; import io.github.anycollect.metric.Key; import io.github.anycollect.meter.api.MeterRegistry; import io.github.anycollect.metric.Tags; import java.util.concurrent.Delayed; import java.util.concurrent.TimeUnit; public final class ThrottledRunnable implements Runnable { private final Runnable delegate; private final long periodInNanos; private final Counter throttledJobsCounter; private volatile Delayed delayed; public ThrottledRunnable(final Runnable delegate, final long periodInNanos, final MeterRegistry registry, final String prefix, final Tags tags) { this.delegate = delegate; this.periodInNanos = periodInNanos; this.throttledJobsCounter = Counter.key(Key.of("scheduler/jobs/throttled").withPrefix(prefix)) .concatTags(tags) .meta(this.getClass()) .register(registry); } void setDelayed(final Delayed delayed) { this.delayed = delayed; } @Override public void run() { if (delayed == null) { this.delegate.run(); } else { long delay = delayed.getDelay(TimeUnit.NANOSECONDS); // throttle obsolete calls if (-1 * delay > periodInNanos) { throttledJobsCounter.increment(); } else { this.delegate.run(); } } } } <file_sep>/anycollect-agent/src/main/java/io/github/anycollect/shutdown/RemoveFileShutdownTask.java package io.github.anycollect.shutdown; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; public final class RemoveFileShutdownTask implements ShutdownTask { private static final Logger LOG = LoggerFactory.getLogger(RemoveFileShutdownTask.class); private final Path path; public RemoveFileShutdownTask(final Path path) { this.path = path; } @Override public void shutdown() { try { Files.deleteIfExists(path); LOG.info("file {} has been successfully deleted", path); } catch (IOException e) { LOG.warn("cannot remove {}", path); } } } <file_sep>/extensions/common/anycollect-common-expression/src/main/java/io/github/anycollect/extensions/common/expression/parser/UnexpectedTokenParseException.java package io.github.anycollect.extensions.common.expression.parser; import io.github.anycollect.extensions.common.expression.ParseException; import java.util.Arrays; public class UnexpectedTokenParseException extends ParseException { public UnexpectedTokenParseException(final Token found, final TokenType expected) { super(String.format("expecting: %s but found: %s: \"%s\"", expected, found.getType(), found.getSequence())); } public UnexpectedTokenParseException(final Token found, final TokenType... expected) { super(String.format("expecting: %s but found: %s: \"%s\"", Arrays.asList(expected), found.getType(), found.getSequence())); } } <file_sep>/extensions/common/anycollect-common-expression/src/test/java/io/github/anycollect/extensions/common/expression/std/StdExpressionTest.java package io.github.anycollect.extensions.common.expression.std; import io.github.anycollect.extensions.common.expression.Args; import io.github.anycollect.extensions.common.expression.EvaluationException; import io.github.anycollect.extensions.common.expression.MapArgs; import io.github.anycollect.extensions.common.expression.filters.Filter; import io.github.anycollect.extensions.common.expression.filters.JoinFilter; import io.github.anycollect.extensions.common.expression.filters.MatchReplaceFilter; import io.github.anycollect.extensions.common.expression.ParseException; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; class StdExpressionTest { @Test void complexTest() throws ParseException, EvaluationException { String expressionString = "\"site.${site}.host.\" | join((${host} | replace(\"\\.\", _)), \".port.${port}\")"; List<Filter> filters = new ArrayList<>(); filters.add(new MatchReplaceFilter()); filters.add(new JoinFilter()); StdExpressionFactory factory = new StdExpressionFactory(filters); StdExpression exp = factory.create(expressionString); Args args = MapArgs.builder() .add("site", "1") .add("host", "172.16.31.10") .add("port", "80") .build(); assertThat(exp.process(args)).isEqualTo("site.1.host.168_0_0_1.port.80"); } }<file_sep>/anycollect-extension-system/src/test/java/io/github/anycollect/extensions/samples/SampleExtensionPoint.java package io.github.anycollect.extensions.samples; public interface SampleExtensionPoint { } <file_sep>/extensions/readers/anycollect-jmx-reader/src/main/java/io/github/anycollect/readers/jmx/config/Credentials.java package io.github.anycollect.readers.jmx.config; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import javax.annotation.Nonnull; import java.util.Objects; @Getter @ToString @EqualsAndHashCode public final class Credentials { private final String username; private final String password; @JsonCreator public Credentials(@JsonProperty("username") @Nonnull final String username, @JsonProperty("password") @Nonnull final String password) { Objects.requireNonNull(username, "username must not be null"); Objects.requireNonNull(password, "password must not be null"); this.username = username; this.password = <PASSWORD>; } } <file_sep>/anycollect-extension-system/src/main/java/io/github/anycollect/extensions/dependencies/SimpleDependency.java package io.github.anycollect.extensions.dependencies; import io.github.anycollect.extensions.di.InjectionPoint; public final class SimpleDependency implements Dependency { private final InjectionPoint injectionPoint; public SimpleDependency(final Object dependency, final int position) { this.injectionPoint = new InjectionPoint(dependency, position); } @Override public InjectionPoint inject() { return injectionPoint; } } <file_sep>/anycollect-core-api/src/main/java/io/github/anycollect/core/api/Writer.java package io.github.anycollect.core.api; import io.github.anycollect.metric.Sample; import javax.annotation.Nonnull; import javax.annotation.concurrent.NotThreadSafe; import java.util.List; @NotThreadSafe public interface Writer extends Route { void write(@Nonnull List<? extends Sample> metrics); } <file_sep>/anycollect-extension-system/src/main/java/io/github/anycollect/extensions/di/Instantiator.java package io.github.anycollect.extensions.di; import io.github.anycollect.extensions.dependencies.Dependency; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.List; public interface Instantiator { Object instantiate(List<Dependency> dependencies) throws IllegalAccessException, InvocationTargetException, InstantiationException; static Instantiator forConstructor(Constructor<?> constructor) { return new InstantiatorImpl(constructor); } } <file_sep>/anycollect-core-api/src/main/java/io/github/anycollect/core/api/target/ServiceDiscovery.java package io.github.anycollect.core.api.target; import java.util.List; import java.util.Set; public interface ServiceDiscovery<T extends Target> { static <T extends Target> ServiceDiscovery<T> composite(List<? extends ServiceDiscovery<? extends T>> discoveries) { return new CompositeServiceDiscovery<>(discoveries); } static <T extends Target> ServiceDiscovery<T> singleton(T target) { return new SingletonServiceDiscovery<>(target); } Set<? extends T> discover(); } <file_sep>/anycollect-core-api/src/main/java/io/github/anycollect/core/api/dispatcher/Accumulator.java package io.github.anycollect.core.api.dispatcher; import io.github.anycollect.metric.Sample; import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.List; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; public final class Accumulator implements Dispatcher { private final Queue<Sample> samples; public Accumulator() { samples = new ConcurrentLinkedQueue<>(); } public List<Sample> purge() { return new ArrayList<>(samples); } @Override public void dispatch(@Nonnull final Sample sample) { this.samples.add(sample); } @Override public void dispatch(@Nonnull final List<Sample> samples) { this.samples.addAll(samples); } } <file_sep>/anycollect-extension-system/src/main/java/io/github/anycollect/extensions/PropertyActivation.java package io.github.anycollect.extensions; import com.fasterxml.jackson.annotation.JacksonInject; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import io.github.anycollect.extensions.substitution.VarSubstitutor; import javax.annotation.Nonnull; public final class PropertyActivation implements Activation { private final VarSubstitutor varSubstitutor; private final String propertyName; private final String propertyValue; @JsonCreator public PropertyActivation(@JacksonInject("environment") @Nonnull final VarSubstitutor varSubstitutor, @JsonProperty(value = "name", required = true) @Nonnull final String propertyName, @JsonProperty(value = "value", required = true) @Nonnull final String propertyValue) { this.varSubstitutor = varSubstitutor; this.propertyName = propertyName; this.propertyValue = propertyValue; } @Override public boolean isReached() { return propertyValue.equals(varSubstitutor.substitute(propertyName)); } } <file_sep>/anycollect-extension-system/src/test/java/io/github/anycollect/extensions/samples/MultipleDependency.java package io.github.anycollect.extensions.samples; import io.github.anycollect.extensions.annotations.ExtCreator; import io.github.anycollect.extensions.annotations.ExtDependency; import io.github.anycollect.extensions.annotations.Extension; import java.util.ArrayList; import java.util.List; public class MultipleDependency { @Extension(contracts = SampleExtensionPoint.class, name = "OneMultipleDependency") public static class OneMultipleDependency implements SampleExtensionPoint { @ExtCreator public OneMultipleDependency( @ExtDependency(qualifier = "delegates") List<SampleExtensionPoint> delegates) { } } @Extension(contracts = SampleExtensionPoint.class, name = "ArrayListDependency") public static class ArrayListDependency implements SampleExtensionPoint { @ExtCreator public ArrayListDependency( @ExtDependency(qualifier = "delegates") ArrayList<SampleExtensionPoint> delegates) { } } } <file_sep>/extensions/common/anycollect-common-expression/src/main/java/io/github/anycollect/extensions/common/expression/ast/visitor/SetVariables.java package io.github.anycollect.extensions.common.expression.ast.visitor; import io.github.anycollect.extensions.common.expression.Args; import io.github.anycollect.extensions.common.expression.ast.VariableExpressionNode; public final class SetVariables implements ExpressionNodeVisitor { private final Args args; public SetVariables(final Args args) { this.args = args; } @Override public void visit(final VariableExpressionNode variable) { variable.setValue(args.get(variable.getName())); } } <file_sep>/anycollect-extension-system/src/main/java/io/github/anycollect/extensions/exceptions/MissingRequiredPropertyException.java package io.github.anycollect.extensions.exceptions; import io.github.anycollect.core.exceptions.ConfigurationException; /** * Signals that configuration does not contain a required property. */ public final class MissingRequiredPropertyException extends ConfigurationException { private final String property; public MissingRequiredPropertyException(final String property) { super(String.format("property %s is missed", property)); this.property = property; } public String getProperty() { return property; } } <file_sep>/anycollect-metric/src/main/java/io/github/anycollect/metric/MutableMetric.java package io.github.anycollect.metric; import org.apiguardian.api.API; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.concurrent.NotThreadSafe; /** * Mutable view of metric. * Contains modify methods to efficiently change internal state of {@link Metric}. * The common way to create an instance is {@link Metric#modify()}. * To perform changes and create immutable {@link Metric} method {@link MutableMetric#commit()} is used. */ @API(since = "0.1.0", status = API.Status.EXPERIMENTAL) @NotThreadSafe public interface MutableMetric { /** * Appends prefix to the key. * * @param prefix - string to be added to key {@link Metric#getKey()} * @return {@link this} * @see Key#withPrefix(String) */ @Nonnull MutableMetric withPrefix(@Nullable String prefix); /** * Append tags in front of existing ones. * * @param prefix - tags to be added * @return {@link this} * @see Tags#concat(Tags) */ @Nonnull MutableMetric frontTags(@Nullable Tags prefix); /** * Append tags in back of existing ones. * * @param suffix - tags to be added * @return {@link this} * @see Tags#concat(Tags) */ @Nonnull MutableMetric backTags(@Nullable Tags suffix); /** * Append meta in front of existing ones. * * @param prefix - meta to be added * @return {@link this} * @see Tags#concat(Tags) */ @Nonnull MutableMetric frontMeta(@Nullable Tags prefix); /** * Append meta in back of existing ones. * * @param suffix - meta to be added * @return {@link this} * @see Tags#concat(Tags) */ @Nonnull MutableMetric backMeta(@Nullable Tags suffix); /** * Removes tag with key from tags. * * @param key - the key of tag to be deleted * @return {@link this} */ @Nonnull MutableMetric removeTag(@Nullable Key key); /** * Removes tag with key from meta. * * @param key - the key of meta to be deleted * @return {@link this} */ @Nonnull MutableMetric removeMeta(@Nullable Key key); /** * Returns immutable metric with all modifications applied. * * @return immutable metric with all modifications applied */ @Nonnull Metric commit(); } <file_sep>/anycollect-core/src/test/java/io/github/anycollect/core/impl/NoopCancelation.java package io.github.anycollect.core.impl; import io.github.anycollect.core.api.internal.Cancellation; public class NoopCancelation implements Cancellation { @Override public void cancel() { } } <file_sep>/anycollect-extension-system/src/main/java/io/github/anycollect/extensions/substitution/VarSubstitutor.java package io.github.anycollect.extensions.substitution; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URL; import java.util.HashMap; import java.util.Map; import java.util.Properties; public interface VarSubstitutor { VarSubstitutor EMPTY = new VarSubstitutor() { @Override @Nullable public String substitute(@Nonnull final String varName) { return null; } }; static VarSubstitutor firstNonNull(VarSubstitutor... substitutors) { return new FirstNonNullVarSubstitutor(substitutors); } static VarSubstitutor of(String... keyValues) { if (keyValues.length % 2 != 0) { throw new IllegalArgumentException("size must be event"); } Map<String, String> map = new HashMap<>(); for (int i = 0; i < keyValues.length / 2; i++) { map.put(keyValues[2 * i], keyValues[2 * i + 1]); } return new MapVarSubstitutor(map); } static VarSubstitutor ofMap(Map<String, String> map) { return new MapVarSubstitutor(map); } static VarSubstitutor env() { return new EnvVarSubstitutor(); } static VarSubstitutor ofClassPathFile(String propertyFileName) throws IOException { Properties properties = new Properties(); URL resource = VarSubstitutor.class.getClassLoader().getResource(propertyFileName); if (resource == null) { throw new FileNotFoundException("resource " + propertyFileName + " not found in classpath"); } properties.load(resource.openStream()); return new PropertiesVarSubstitutor(properties); } @Nullable String substitute(@Nonnull String varName); } <file_sep>/extensions/common/anycollect-common-expression/src/main/java/io/github/anycollect/extensions/common/expression/filters/TrimFilter.java package io.github.anycollect.extensions.common.expression.filters; import io.github.anycollect.extensions.annotations.ExtConfig; import io.github.anycollect.extensions.annotations.ExtCreator; import io.github.anycollect.extensions.annotations.Extension; import io.github.anycollect.extensions.common.expression.ArgValidationException; import java.util.Collections; import java.util.List; import static io.github.anycollect.extensions.common.expression.filters.TrimFilter.NAME; @Extension(name = NAME, contracts = Filter.class) public final class TrimFilter extends BaseFilter { public static final String NAME = "TrimFilter"; @ExtCreator public TrimFilter(@ExtConfig(key = "aliases") final List<String> aliases) { super("trim", aliases); } public TrimFilter() { super("trim", Collections.emptyList()); } @Override public String filter(final String source, final List<String> args) throws ArgValidationException { if (!args.isEmpty()) { throw new ArgValidationException(NAME + " filter requires no arguments, given: " + args); } return source.trim(); } } <file_sep>/anycollect-metric/src/main/java/io/github/anycollect/metric/Metric.java package io.github.anycollect.metric; import org.apiguardian.api.API; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; import java.util.Objects; /** * Metric represents a time series. * <p> * All implementation must be immutable and can be safely shared between threads. */ @Immutable @API(since = "0.1.0", status = API.Status.EXPERIMENTAL) public interface Metric { @Nonnull static KeyStageBuilder builder() { return new MetricBuilder(); } /** * Specifies the main property of the system that is measured. * * @return the key of time series * @see Key */ @Nonnull Key getKey(); /** * Specifies the key-value pairs related to the time series. * <p> * E.g. http.method=POST * * @return the tags of the time series */ @Nonnull Tags getTags(); /** * Specifies the meta information that is related to the time series. * <p> * This is not a part of metric identity but it can help to perform some filtering and transformation actions * to integrate with different external models of time series. * * @return meta information of the time series */ @Nonnull Tags getMeta(); @Nonnull Stat getStat(); @Nonnull String getUnit(); @Nonnull default MutableMetric modify() { return new MutableMetricImpl(this); } @Nonnull default Sample sample(double value, long timestamp) { return new DoubleSample(this, value, timestamp); } /** * Computes hash code based on general contract. * * @param metric - the instance whose hash code to compute * @return hash code */ static int hash(@Nonnull Metric metric) { return Objects.hash(metric.getKey(), metric.getTags(), metric.getStat(), metric.getUnit()); } /** * @param first - first metric to be compared * @param second - second metric to be compared * @return {@code true} if first is equal to second argument */ static boolean equals(@Nullable Metric first, @Nullable Metric second) { if (first == second) { return true; } if (first == null || second == null) { return false; } if (!first.getStat().equals(second.getStat())) { return false; } if (!first.getUnit().equals(second.getUnit())) { return false; } if (!first.getKey().equals(second.getKey())) { return false; } if (!first.getTags().equals(second.getTags())) { return false; } return true; } @Nonnull static String toString(@Nullable Metric metric) { if (metric == null) { return "null"; } return metric.getKey() + "[" + metric.getStat() + "]" + (metric.getUnit().isEmpty() ? "" : "(" + metric.getUnit() + ")") + (!metric.getTags().isEmpty() ? ";" + metric.getTags() : ""); } interface KeyStageBuilder { @Nonnull TagsStageBuilder key(@Nonnull String key); @Nonnull TagsStageBuilder key(@Nonnull Key key); } interface TagsStageBuilder extends Factory { @Nonnull default MetaStageBuilder empty() { return tags(Tags.empty()); } @Nonnull MetaStageBuilder tag(@Nonnull String key, @Nonnull String value); @Nonnull MetaStageBuilder tags(@Nonnull Tags tags); } interface MetaStageBuilder extends Factory { @Nonnull default Factory empty() { return meta(Tags.empty()); } @Nonnull Factory meta(@Nonnull String key, @Nonnull String value); @Nonnull Factory meta(@Nonnull Tags meta); } interface Factory { @Nonnull default Metric counter() { return counter(""); } @Nonnull default Metric counter(@Nonnull final String unit) { return metric(Stat.COUNTER, unit); } @Nonnull default Metric min() { return min(""); } @Nonnull default Metric min(@Nonnull final String unit) { return metric(Stat.MIN, unit); } @Nonnull default Metric max() { return max(""); } @Nonnull default Metric max(@Nonnull final String unit) { return metric(Stat.MAX, unit); } @Nonnull default Metric mean() { return mean(""); } @Nonnull default Metric mean(@Nonnull final String unit) { return metric(Stat.MEAN, unit); } @Nonnull default Metric std() { return std(""); } @Nonnull default Metric std(@Nonnull final String unit) { return metric(Stat.STD, unit); } @Nonnull default Metric percentile(final double quantile) { return percentile(quantile, ""); } @Nonnull default Metric percentile(final double quantile, @Nonnull final String unit) { return metric(Percentile.of(quantile), unit); } @Nonnull default Metric percentile(final int percentile) { return percentile(percentile, ""); } @Nonnull default Metric percentile(final int percentile, @Nonnull final String unit) { return metric(Percentile.of(percentile), unit); } @Nonnull default Metric gauge() { return gauge(""); } @Nonnull default Metric gauge(@Nonnull final String unit) { return metric(Stat.GAUGE, unit); } @Nonnull Metric metric(@Nonnull Stat stat, @Nonnull String unit); } } <file_sep>/anycollect-core-api/src/main/java/io/github/anycollect/core/api/query/SingletonQueryProvider.java package io.github.anycollect.core.api.query; import javax.annotation.Nonnull; import java.util.Collections; import java.util.Set; public class SingletonQueryProvider<Q extends Query> implements QueryProvider<Q> { private final Set<Q> singleton; public SingletonQueryProvider(@Nonnull final Q query) { this.singleton = Collections.singleton(query); } @Nonnull @Override public Set<Q> provide() { return singleton; } } <file_sep>/anycollect-core-api/src/main/java/io/github/anycollect/core/api/query/QueryProvider.java package io.github.anycollect.core.api.query; import javax.annotation.Nonnull; import java.util.List; import java.util.Set; public interface QueryProvider<Q extends Query> { static <Q extends Query> CompositeQueryProvider<Q> composite( final List<? extends QueryProvider<? extends Q>> providers) { return new CompositeQueryProvider<>(providers); } static <Q extends Query> SingletonQueryProvider<Q> singleton(final Q query) { return new SingletonQueryProvider<>(query); } @Nonnull Set<Q> provide(); } <file_sep>/extensions/readers/anycollect-jmx-reader/src/main/java/io/github/anycollect/readers/jmx/query/operations/SubscribeOperation.java package io.github.anycollect.readers.jmx.query.operations; import io.github.anycollect.core.exceptions.ConnectionException; import io.github.anycollect.readers.jmx.server.JmxConnection; import io.github.anycollect.readers.jmx.server.JmxConnectionDropListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nonnull; import javax.management.InstanceNotFoundException; import javax.management.MBeanServerConnection; import javax.management.NotificationListener; import javax.management.ObjectName; import java.io.IOException; import java.util.Collection; public final class SubscribeOperation implements QueryOperation<Subscription>, JmxConnectionDropListener { private static final Logger LOG = LoggerFactory.getLogger(SubscribeOperation.class); private final Collection<ObjectName> objectNames; private final NotificationListener listener; private volatile Subscription subscription; public SubscribeOperation(@Nonnull final Collection<ObjectName> objectNames, @Nonnull final NotificationListener listener) { this.objectNames = objectNames; this.listener = listener; } @Override public Subscription operate(@Nonnull final JmxConnection connection) throws ConnectionException { connection.onConnectionDrop(this); return operate(connection.getConnection()); } @Override public Subscription operate(@Nonnull final MBeanServerConnection connection) throws ConnectionException { for (ObjectName objectName : objectNames) { try { connection.addNotificationListener(objectName, listener, null, null); } catch (InstanceNotFoundException e) { LOG.warn("instance not found", e); } catch (IOException e) { throw new ConnectionException("could not subscribe", e); } } Subscription subscription = new Subscription(); this.subscription = subscription; return subscription; } @Override public void onDrop() { if (subscription != null) { subscription.invalidate(); subscription = null; } } } <file_sep>/anycollect-extension-system/src/main/java/io/github/anycollect/extensions/exceptions/ExtensionDescriptorException.java package io.github.anycollect.extensions.exceptions; public class ExtensionDescriptorException extends ExtensionException { public ExtensionDescriptorException(final String message) { super(message); } } <file_sep>/extensions/readers/anycollect-jmx-reader/src/main/java/io/github/anycollect/readers/jmx/discovery/DefaultJavaAppFactory.java package io.github.anycollect.readers.jmx.discovery; import io.github.anycollect.core.api.target.TargetCreationException; import io.github.anycollect.meter.api.MeterRegistry; import io.github.anycollect.metric.Tags; import io.github.anycollect.readers.jmx.config.JavaAppConfig; import io.github.anycollect.readers.jmx.server.JavaApp; import io.github.anycollect.readers.jmx.server.JmxConnectionFactory; import io.github.anycollect.readers.jmx.server.JmxConnectionFactoryImpl; import io.github.anycollect.readers.jmx.server.pool.JmxConnectionPoolFactory; import io.github.anycollect.readers.jmx.server.pool.impl.CommonsJmxConnectionPoolFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nonnull; import java.net.MalformedURLException; public class DefaultJavaAppFactory implements JavaAppFactory { private static final Logger LOG = LoggerFactory.getLogger(DefaultJavaAppFactory.class); private final JmxConnectionPoolFactory factory; private final MeterRegistry registry; public DefaultJavaAppFactory(@Nonnull final MeterRegistry registry) { factory = new CommonsJmxConnectionPoolFactory(); this.registry = registry; } @Nonnull @Override public JavaApp create(@Nonnull final JavaAppConfig definition) throws TargetCreationException { try { JmxConnectionFactory connectionFactory = new JmxConnectionFactoryImpl(definition); Tags tags = definition.getTags(); if (tags.isEmpty()) { tags = Tags.of("instance", definition.getInstanceId()); } return JavaApp.create( definition.getInstanceId(), tags, definition.getMeta(), factory.create(connectionFactory), registry); } catch (MalformedURLException e) { LOG.error("could not create java target because url \"{}\" is malformed", definition.getUrl(), e); throw new TargetCreationException("could not create java target", e); } } } <file_sep>/anycollect-core-api/src/main/java/io/github/anycollect/core/api/common/Lifecycle.java package io.github.anycollect.core.api.common; public interface Lifecycle { /** * Initializes the service or do nothing if it has been already initialized. * <p> * May took time */ default void init() { } /** * Destroys the service or do nothing if it has been already destroyed. * <p> * May took time */ default void destroy() { } } <file_sep>/anycollect-core-api/src/main/java/io/github/anycollect/core/api/Deserializer.java package io.github.anycollect.core.api; import io.github.anycollect.core.exceptions.SerialisationException; import io.github.anycollect.metric.Sample; import javax.annotation.Nonnull; public interface Deserializer { @Nonnull Sample deserialize(@Nonnull String string) throws SerialisationException; } <file_sep>/anycollect-core/src/main/java/io/github/anycollect/core/impl/pull/DesiredStateUpdateJob.java package io.github.anycollect.core.impl.pull; import io.github.anycollect.core.api.internal.DesiredStateProvider; import io.github.anycollect.core.api.internal.State; import io.github.anycollect.core.api.query.Query; import io.github.anycollect.core.api.target.Target; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nonnull; public final class DesiredStateUpdateJob<T extends Target, Q extends Query<T>> implements Runnable { private static final Logger LOG = LoggerFactory.getLogger(DesiredStateUpdateJob.class); private final DesiredStateProvider<T, Q> stateProvider; private final DesiredStateManager<T, Q> scheduler; private volatile State<T, Q> lastSuccessfullyPerformedDesiredState = State.empty(); public DesiredStateUpdateJob(@Nonnull final DesiredStateProvider<T, Q> stateProvider, @Nonnull final DesiredStateManager<T, Q> scheduler) { this.stateProvider = stateProvider; this.scheduler = scheduler; } @Override public void run() { try { LOG.debug("getting new desired state"); State<T, Q> state = stateProvider.current(); LOG.debug("updating state"); scheduler.update(state); LOG.debug("state has been successfully updated"); this.lastSuccessfullyPerformedDesiredState = state; } catch (RuntimeException e) { LOG.warn("Could not fully update state, do perform recovery actions, rollback to previous state", e); try { scheduler.cleanup(); scheduler.update(lastSuccessfullyPerformedDesiredState); LOG.info("Recovery actions for desired state manager have been successfully completed"); } catch (RuntimeException e2) { LOG.error("Recovery actions for desired state manager have been failed", e2); } } } } <file_sep>/extensions/readers/anycollect-jmx-reader/src/main/java/io/github/anycollect/readers/jmx/query/StdJmxQuery.java package io.github.anycollect.readers.jmx.query; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import io.github.anycollect.core.api.internal.Clock; import io.github.anycollect.core.api.job.Job; import io.github.anycollect.core.api.job.TaggingJob; import io.github.anycollect.core.api.target.Target; import io.github.anycollect.core.exceptions.ConfigurationException; import io.github.anycollect.core.exceptions.ConnectionException; import io.github.anycollect.core.exceptions.QueryException; import io.github.anycollect.metric.*; import io.github.anycollect.readers.jmx.query.operations.QueryAttributes; import io.github.anycollect.readers.jmx.query.operations.QueryObjectNames; import io.github.anycollect.readers.jmx.query.operations.QueryOperation; import io.github.anycollect.readers.jmx.server.JavaApp; import lombok.EqualsAndHashCode; import lombok.Getter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.management.Attribute; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import javax.management.openmbean.CompositeData; import javax.management.openmbean.TabularData; import java.util.*; @Getter @EqualsAndHashCode(callSuper = true) public final class StdJmxQuery extends JmxQuery { private static final Logger LOG = LoggerFactory.getLogger(StdJmxQuery.class); private final Clock clock; private final Key key; private final List<String> tagKeys; private final ObjectName objectPattern; @Nonnull private final Restriction restriction; private final String[] attributeNames; private final List<MeasurementPath> paths; private final MetricFactory factory; @JsonCreator public StdJmxQuery(@JsonProperty(value = "key", required = true) @Nonnull final Key key, @JsonProperty("tags") @Nullable final Tags tags, @JsonProperty("meta") @Nullable final Tags meta, @JsonProperty("tagKeys") @Nullable final List<String> tagKeys, @JsonProperty(value = "mbean", required = true) @Nonnull final String objectPattern, @JsonProperty("whitelist") @Nullable final Whitelist whitelist, @JsonProperty("measurements") @Nonnull final List<MeasurementPath> paths) { this(key, tags, meta, tagKeys, objectPattern, whitelist, paths, null); } public StdJmxQuery(@Nonnull final Key key, @Nullable final Tags tags, @Nullable final Tags meta, @Nullable final List<String> tagKeys, @Nonnull final String objectPattern, @Nullable final Whitelist whitelist, @Nonnull final List<MeasurementPath> paths, @Nullable final MetricFactory factory) { super(key.toString(), tags != null ? tags : Tags.empty(), meta != null ? meta : Tags.empty()); this.clock = Clock.getDefault(); this.key = key; this.tagKeys = tagKeys != null ? tagKeys : Collections.emptyList(); List<String> activeAttributes = new ArrayList<>(); for (MeasurementPath measurement : paths) { activeAttributes.add(measurement.getAttribute()); } try { this.objectPattern = new ObjectName(objectPattern); } catch (MalformedObjectNameException e) { throw new ConfigurationException("object name " + objectPattern + " is malformed", e); } if (whitelist != null) { this.restriction = whitelist; } else { this.restriction = Restriction.all(); } this.attributeNames = activeAttributes.toArray(new String[0]); this.paths = paths; this.factory = factory != null ? factory : new StdMetricIdFactory(); } @Nonnull @Override public Job bind(@Nonnull final JavaApp app) { return new TaggingJob(app, this, new JobImpl(app)); } private final class JobImpl implements Job { private final JavaApp app; private final QueryOperation<Set<ObjectName>> queryNames; private final Map<ObjectName, List<Metric>> cache; JobImpl(final JavaApp app) { this.app = app; this.queryNames = new QueryObjectNames(objectPattern); this.cache = new HashMap<>(); } @Override public List<Sample> execute() throws QueryException, ConnectionException { Set<ObjectName> objectNames = app.operate(queryNames); if (objectNames.isEmpty()) { LOG.warn("No mbeans matched to {}", objectPattern); } List<Sample> samples = new ArrayList<>(); for (ObjectName objectName : objectNames) { if (restriction.allows(objectName)) { List<Attribute> attributes = app.operate(new QueryAttributes(objectName, attributeNames)); if (attributes.size() != attributeNames.length) { List<String> missingAttributes = Arrays.asList(attributeNames); for (final Attribute attribute : attributes) { missingAttributes.remove(attribute.getName()); } LOG.warn("Missing some attributes in {}, did not retrieve: {}. This mbean will be skipped", objectName, missingAttributes); continue; } long timestamp = clock.wallTime(); List<Metric> ids = cache.computeIfAbsent(objectName, this::prepare); if (ids == null) { continue; } for (int i = 0; i < attributes.size(); ++i) { Metric id = ids.get(i); if (id == null) { continue; } Object value = attributes.get(i).getValue(); List<String> valuePath = paths.get(i).getValuePath(); for (int part = 1; part < valuePath.size(); part++) { String node = valuePath.get(part); if (value instanceof CompositeData) { value = ((CompositeData) value).get(node); } else if (value instanceof TabularData) { TabularData tabularValue = (TabularData) value; @SuppressWarnings("unchecked") Collection<CompositeData> tableData = (Collection<CompositeData>) tabularValue.values(); for (CompositeData compositeData : tableData) { if (compositeData.get("key").equals(node)) { value = compositeData.get("value"); break; } } } } if (value instanceof Long) { samples.add(id.sample((long) value, timestamp)); } else if (value instanceof Number) { samples.add(id.sample(((Number) value).doubleValue(), timestamp)); } else if (value instanceof Boolean) { samples.add(id.sample(((boolean) value) ? 1 : 0, timestamp)); } } } } return samples; } private List<Metric> prepare(@Nonnull final ObjectName objectName) { List<Metric> ids = new ArrayList<>(); for (final MeasurementPath attribute : paths) { ids.add(factory.create(app, objectName, attribute)); } return ids; } } public interface MetricFactory { @Nullable Metric create(@Nonnull Target target, @Nonnull ObjectName objectName, @Nonnull MeasurementPath attribute); } private class StdMetricIdFactory implements MetricFactory { @Override @Nullable public Metric create(@Nonnull final Target target, @Nonnull final ObjectName objectName, @Nonnull final MeasurementPath attribute) { Tags.Builder tags = Tags.builder(); for (String tagKey : tagKeys) { String tagValue = objectName.getKeyProperty(tagKey); if (tagValue == null) { LOG.warn("Could not create metric from {}, property {} is missing.", objectName, tagKey); return null; } tags.tag(tagKey, tagValue); } Metric.Factory builder = Metric.builder() .key(key) .tags(tags.build()) .empty(); return builder.metric(attribute.getStat(), attribute.getUnit()); } } } <file_sep>/extensions/readers/anycollect-jmx-reader/src/main/java/io/github/anycollect/readers/jmx/query/operations/QueryObjectNames.java package io.github.anycollect.readers.jmx.query.operations; import io.github.anycollect.core.exceptions.ConnectionException; import javax.annotation.Nonnull; import javax.management.MBeanServerConnection; import javax.management.ObjectName; import java.io.IOException; import java.util.Set; public final class QueryObjectNames implements QueryOperation<Set<ObjectName>> { private final ObjectName objectPattern; public QueryObjectNames(@Nonnull final ObjectName objectPattern) { this.objectPattern = objectPattern; } @Override public Set<ObjectName> operate(@Nonnull final MBeanServerConnection connection) throws ConnectionException { try { return connection.queryNames(objectPattern, null); } catch (IOException e) { throw new ConnectionException("could not query names", e); } } } <file_sep>/anycollect-extension-system/src/test/java/io/github/anycollect/extensions/samples/FakeImplementationSampleExtension.java package io.github.anycollect.extensions.samples; import io.github.anycollect.extensions.annotations.Extension; @Extension(name = "FakeSample", contracts = SampleExtensionPoint.class) public class FakeImplementationSampleExtension { } <file_sep>/anycollect-extension-system/src/test/java/io/github/anycollect/extensions/samples/Configs.java package io.github.anycollect.extensions.samples; import io.github.anycollect.extensions.annotations.ExtConfig; import io.github.anycollect.extensions.annotations.ExtCreator; import io.github.anycollect.extensions.annotations.Extension; import java.util.List; public class Configs { @Extension(name = "ListOfStrings", contracts = SampleExtensionPoint.class) public static class ListOfStrings implements SampleExtensionPoint { private final List<String> config; @ExtCreator public ListOfStrings(@ExtConfig List<String> config) { this.config = config; } public List<String> getConfig() { return config; } } @Extension(name = "ListOfStringsWithKey", contracts = SampleExtensionPoint.class) public static class ListOfStringsWithKey implements SampleExtensionPoint { private final List<String> aliases; @ExtCreator public ListOfStringsWithKey(@ExtConfig(key = "aliases") List<String> aliases) { this.aliases = aliases; } public List<String> getAliases() { return aliases; } } } <file_sep>/anycollect-core/src/main/java/io/github/anycollect/core/impl/transform/TransformerConfig.java package io.github.anycollect.core.impl.transform; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import io.github.anycollect.core.impl.filters.AcceptAllFilter; import io.github.anycollect.core.api.filter.Filter; import io.github.anycollect.core.impl.transform.transformations.Transformation; import org.immutables.value.Value; import java.util.Collections; import java.util.List; @Value.Immutable @JsonSerialize(as = ImmutableTransformerConfig.class) @JsonDeserialize(as = ImmutableTransformerConfig.class) public interface TransformerConfig { @Value.Default @JsonProperty("source") default MetricSourceAction metricSourceAction() { return MetricSourceAction.DROP; } @Value.Default @JsonProperty("filters") default List<Filter> filters() { return Collections.singletonList(new AcceptAllFilter()); } @JsonProperty("transformations") List<Transformation> transformations(); } <file_sep>/extensions/readers/anycollect-jmx-reader/src/test/java/io/github/anycollect/readers/jmx/discovery/StaticJavaAppDiscoveryTest.java package io.github.anycollect.readers.jmx.discovery; import io.github.anycollect.core.api.target.Target; import io.github.anycollect.extensions.Definition; import io.github.anycollect.extensions.Instance; import io.github.anycollect.extensions.context.ContextImpl; import io.github.anycollect.extensions.loaders.AnnotationDefinitionLoader; import io.github.anycollect.extensions.loaders.DefinitionLoader; import io.github.anycollect.extensions.loaders.InstanceLoader; import io.github.anycollect.extensions.loaders.snakeyaml.YamlInstanceLoader; import io.github.anycollect.meter.impl.NoopMeterRegistry; import io.github.anycollect.readers.jmx.server.JavaApp; import io.github.anycollect.readers.jmx.server.PooledJavaApp; import org.apache.commons.io.FileUtils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.io.File; import java.io.FileReader; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; class StaticJavaAppDiscoveryTest { private StaticJavaAppDiscovery discovery; @BeforeEach void createPullManager() throws Exception { DefinitionLoader definitionLoader = new AnnotationDefinitionLoader(Arrays.asList( NoopMeterRegistry.class, StaticJavaAppDiscovery.class)); Collection<Definition> definitions = definitionLoader.load(); File config = FileUtils.getFile("src", "test", "resources", "static-java-app-discovery.yaml"); InstanceLoader instanceLoader = new YamlInstanceLoader(new FileReader(config)); ContextImpl context = new ContextImpl(definitions); instanceLoader.load(context); List<Instance> instances = context.getInstances(); discovery = (StaticJavaAppDiscovery) instances.get(1).resolve(); } @Test @DisplayName("is successfully instantiated by extension system") void isInstantiatedBySystem() { assertThat(discovery).isNotNull(); } @Test void hasCorrectDiscoveredJavaApps() { Set<JavaApp> discover = discovery.discover(); assertThat(discover).hasSize(1).first() .isInstanceOf(PooledJavaApp.class) .extracting(Target::getId) .isEqualTo("cassandra-1"); } }<file_sep>/anycollect-tests/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>anycollect-parent</artifactId> <groupId>io.github.anycollect</groupId> <version>0.0.1-SNAPSHOT</version> <relativePath>../anycollect-parent/pom.xml</relativePath> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>anycollect-tests</artifactId> <dependencies> <dependency> <groupId>io.github.anycollect</groupId> <artifactId>anycollect-metric</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>io.github.anycollect</groupId> <artifactId>anycollect-extension-system</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>io.github.anycollect</groupId> <artifactId>anycollect-common-expression</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>io.github.anycollect</groupId> <artifactId>anycollect-jmx-reader</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>io.github.anycollect</groupId> <artifactId>anycollect-core</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>io.github.anycollect</groupId> <artifactId>anycollect-jackson</artifactId> <version>${project.version}</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.jacoco</groupId> <artifactId>jacoco-maven-plugin</artifactId> <version>${jacoco.plugin.version}</version> <executions> <execution> <id>report-aggregate</id> <phase>verify</phase> <goals> <goal>report-aggregate</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project><file_sep>/anycollect-core/src/main/java/io/github/anycollect/core/impl/pull/availability/Check.java package io.github.anycollect.core.impl.pull.availability; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import javax.annotation.concurrent.Immutable; @Getter @ToString @Immutable @EqualsAndHashCode public final class Check { private final Health health; private final long timestamp; public static Check passed(final long timestamp) { return new Check(Health.PASSED, timestamp); } public static Check failed(final long timestamp) { return new Check(Health.FAILED, timestamp); } public static Check unknown(final long timestamp) { return new Check(Health.UNKNOWN, timestamp); } private Check(final Health health, final long timestamp) { this.health = health; this.timestamp = timestamp; } } <file_sep>/extensions/kv/anycollect-consul-kv/src/main/java/io/github/anycollect/kv/consul/ConsulKeyValue.java package io.github.anycollect.kv.consul; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; import com.fasterxml.jackson.datatype.guava.GuavaModule; import com.google.common.net.HostAndPort; import com.orbitz.consul.Consul; import com.orbitz.consul.ConsulException; import com.orbitz.consul.KeyValueClient; import io.github.anycollect.core.api.common.Lifecycle; import io.github.anycollect.core.api.kv.KeyValue; import io.github.anycollect.core.api.kv.KeyValueStorageException; import io.github.anycollect.extensions.annotations.ExtConfig; import io.github.anycollect.extensions.annotations.ExtCreator; import io.github.anycollect.extensions.annotations.Extension; import io.github.anycollect.jackson.AnyCollectModule; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nonnull; import java.io.IOException; import java.net.ConnectException; import java.util.ArrayList; import java.util.List; @Extension(name = ConsulKeyValue.NAME, contracts = KeyValue.class) public final class ConsulKeyValue implements KeyValue, Lifecycle { public static final String NAME = "ConsulKv"; private static final Logger LOG = LoggerFactory.getLogger(ConsulKeyValue.class); // TODO use abstraction, probably is should be extension private final ObjectMapper objectMapper; private final Consul consul; private final KeyValueClient keyValueClient; @ExtCreator public ConsulKeyValue(@ExtConfig final ConsulConfig config) { this.objectMapper = new ObjectMapper(new YAMLFactory()); this.objectMapper.registerModule(new GuavaModule()); this.objectMapper.registerModule(new AnyCollectModule()); this.consul = Consul.builder() .withHostAndPort(HostAndPort.fromParts(config.host(), config.port())) .withPing(false) .build(); this.keyValueClient = this.consul.keyValueClient(); } @Override public <T> List<T> getValues(@Nonnull final String key, @Nonnull final Class<T> valueType) throws KeyValueStorageException { List<T> values = new ArrayList<>(); List<String> valuesAsString; try { valuesAsString = keyValueClient.getValuesAsString(key); } catch (ConsulException e) { if (e.getCause() instanceof ConnectException) { LOG.warn("could not connect to consul"); throw new KeyValueStorageException("could not connect to consul"); } LOG.debug("could not get values by key \"{}\" from consul", key, e); throw new KeyValueStorageException("could not get values from consul", e); } for (String valueString : valuesAsString) { T value; try { value = objectMapper.readValue(valueString, valueType); } catch (IOException e) { LOG.debug("cannot parse value {}", valueString); continue; } values.add(value); } return values; } @Override public void init() { LOG.info("{} has been successfully initialised", NAME); } @Override public void destroy() { consul.destroy(); LOG.info("{} has been successfully destroyed", NAME); } } <file_sep>/anycollect-extension-system/src/main/java/io/github/anycollect/extensions/exceptions/ExtensionException.java package io.github.anycollect.extensions.exceptions; public abstract class ExtensionException extends RuntimeException { public ExtensionException(final String message) { super(message); } public ExtensionException(final String message, final Throwable cause) { super(message, cause); } } <file_sep>/anycollect-core-api/src/main/java/io/github/anycollect/core/api/target/TargetCreationException.java package io.github.anycollect.core.api.target; public final class TargetCreationException extends Exception { public TargetCreationException(final String message, final Throwable cause) { super(message, cause); } } <file_sep>/anycollect-metric/src/main/java/io/github/anycollect/metric/Key.java package io.github.anycollect.metric; import org.apiguardian.api.API; import javax.annotation.Nonnull; import javax.annotation.concurrent.Immutable; import java.util.Objects; /** * Represents a hierarchical key that is used as time series key or tag key. * <p> * The slash character ("/") is used to separate domains (namespaces) * E.g. jvm/gc/pause/duration * The dot character (".") is used to separate words in domain (namespace) * E.g. jvm/gc/concurrent.phase/duration * Word should match regexp [a-z]* * <p> * Key is intended to be simple converted to different case formats (camel case, snake case, etc) * and storage schemas (hierarchical / multidimensional) */ @Immutable @API(since = "0.1.0", status = API.Status.EXPERIMENTAL) public interface Key { static Key empty() { return new StringKey(""); } static Key of(@Nonnull String normalized) { Objects.requireNonNull(normalized, "key must not be null"); return new StringKey(normalized); } @Nonnull default Key withPrefix(@Nonnull Key prefix) { return join(prefix, this); } @Nonnull default Key withPrefix(@Nonnull String word) { return join(new StringKey(word), this); } @Nonnull default Key withPrefix(@Nonnull String... phrase) { if (phrase.length == 0) { return this; } return join(new StringKey(phrase), this); } @Nonnull default Key withSuffix(@Nonnull Key suffix) { return join(this, suffix); } @Nonnull default Key withSuffix(@Nonnull String word) { return join(this, new StringKey(word)); } @Nonnull default Key withSuffix(@Nonnull String... phrase) { return join(this, new StringKey(phrase)); } static Key join(@Nonnull Key prefix, @Nonnull Key suffix) { if (prefix.isEmpty()) { if (suffix.isEmpty()) { return empty(); } else { return suffix; } } else { if (suffix.isEmpty()) { return prefix; } else { return new JoinKey(prefix, suffix); } } } String normalize(); default boolean isEmpty() { return normalize().isEmpty(); } void print(@Nonnull CaseFormat format, @Nonnull StringBuilder output); default String toString(@Nonnull CaseFormat format) { return toString(this, format); } static String toString(@Nonnull Key key, @Nonnull CaseFormat format) { StringBuilder stringBuilder = new StringBuilder(); key.print(format, stringBuilder); return stringBuilder.toString(); } interface CaseFormat { void startDomain(@Nonnull StringBuilder output); void startWord(@Nonnull StringBuilder output); void print(@Nonnull CharSequence sequence, int start, int end, @Nonnull StringBuilder output); void print(char elem, @Nonnull StringBuilder output); void finishWord(@Nonnull StringBuilder output); void finishDomain(@Nonnull StringBuilder output); void reset(); } abstract class StatefulCaseFormat implements CaseFormat { private boolean firstDomain = true; private boolean firstWordInDomain = true; private boolean firstCharInWord = true; @Override public final void startDomain(@Nonnull final StringBuilder output) { if (!firstDomain) { separateDomains(output); } } @Override public final void startWord(@Nonnull final StringBuilder output) { if (!firstWordInDomain) { separateWordsInDomain(output); } firstCharInWord = true; } @Override public final void print(@Nonnull final CharSequence sequence, final int start, final int end, @Nonnull final StringBuilder output) { for (int i = start; i < end; i++) { print(sequence.charAt(i), output); } } @Override public final void print(final char elem, @Nonnull final StringBuilder output) { print(elem, firstDomain, firstWordInDomain, firstCharInWord, output); firstCharInWord = false; } @Override public final void finishWord(@Nonnull final StringBuilder output) { if (firstWordInDomain) { firstWordInDomain = false; } } @Override public final void finishDomain(@Nonnull final StringBuilder output) { if (firstDomain) { firstDomain = false; } firstWordInDomain = true; } @Override public final void reset() { firstDomain = true; firstWordInDomain = true; firstCharInWord = true; } protected void separateDomains(@Nonnull final StringBuilder output) { } protected void separateWordsInDomain(@Nonnull final StringBuilder output) { } protected void print(final char elem, final boolean firstDomain, final boolean firstWordInDomain, final boolean firstCharInWord, @Nonnull final StringBuilder output) { output.append(elem); } } final class StdCaseFormat extends StatefulCaseFormat { @Override protected void separateDomains(@Nonnull final StringBuilder output) { output.append('/'); } @Override protected void separateWordsInDomain(@Nonnull final StringBuilder output) { output.append('.'); } @Override protected void print(final char elem, final boolean firstDomain, final boolean firstWordInDomain, final boolean firstCharInWord, @Nonnull final StringBuilder output) { output.append(elem); } } } <file_sep>/anycollect-core-api/src/main/java/io/github/anycollect/core/exceptions/ConfigurationException.java package io.github.anycollect.core.exceptions; /** * Signals that configuration that has been passed is wrong. * There is no way to recover from this exception. Because of that this exception is unchecked. * The user should fix his configuration. */ public class ConfigurationException extends RuntimeException { public ConfigurationException(final String message) { super(message); } public ConfigurationException(final String message, final Throwable cause) { super(message, cause); } } <file_sep>/extensions/readers/anycollect-async-socket-reader/src/main/java/io/github/anycollect/readers/socket/netty/DispatcherHandler.java package io.github.anycollect.readers.socket.netty; import io.github.anycollect.core.api.Deserializer; import io.github.anycollect.core.api.dispatcher.Dispatcher; import io.github.anycollect.core.exceptions.SerialisationException; import io.github.anycollect.metric.Sample; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nonnull; @ChannelHandler.Sharable public final class DispatcherHandler extends SimpleChannelInboundHandler<String> { private static final Logger LOG = LoggerFactory.getLogger(DispatcherHandler.class); private final Deserializer deserializer; private final Dispatcher dispatcher; public DispatcherHandler(@Nonnull final Deserializer deserializer, @Nonnull final Dispatcher dispatcher) { this.deserializer = deserializer; this.dispatcher = dispatcher; } @Override protected void channelRead0(final ChannelHandlerContext ctx, final String msg) throws Exception { Sample sample; try { sample = deserializer.deserialize(msg); } catch (SerialisationException e) { LOG.debug("could not deserialize string {}", msg, e); return; } dispatcher.dispatch(sample); } } <file_sep>/anycollect-extension-system/src/main/java/io/github/anycollect/extensions/scope/Scope.java package io.github.anycollect.extensions.scope; import javax.annotation.Nonnull; import javax.annotation.Nullable; public interface Scope { @Nullable Scope getParent(); @Nonnull String getId(); boolean isParent(@Nonnull Scope that); int distance(@Nonnull Scope that); } <file_sep>/extensions/readers/anycollect-system-reader/src/main/java/io/github/anycollect/readers/system/SystemReader.java package io.github.anycollect.readers.system; import io.github.anycollect.core.api.Reader; import io.github.anycollect.core.api.common.Lifecycle; import io.github.anycollect.core.api.dispatcher.Dispatcher; import io.github.anycollect.core.api.internal.Cancellation; import io.github.anycollect.core.api.internal.PullManager; import io.github.anycollect.extensions.annotations.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import oshi.SystemInfo; import oshi.hardware.CentralProcessor; import oshi.software.os.FileSystem; import javax.annotation.Nonnull; import javax.annotation.Nullable; @Extension(name = SystemReader.NAME, contracts = Reader.class) public final class SystemReader implements Reader, Lifecycle { public static final String NAME = "SystemReader"; private static final Logger LOG = LoggerFactory.getLogger(SystemReader.class); private final PullManager puller; private final SystemConfig config; private final String id; private volatile Cancellation cancellation; @ExtCreator public SystemReader(@ExtDependency(qualifier = "puller") @Nonnull final PullManager puller, @ExtConfig(optional = true) @Nullable final SystemConfig config, @InstanceId @Nonnull final String id) { this.puller = puller; this.config = config != null ? config : SystemConfig.DEFAULT; this.id = id; } @Override public void start(@Nonnull final Dispatcher dispatcher) { SystemInfo systemInfo = new SystemInfo(); CentralProcessor processor = systemInfo.getHardware().getProcessor(); CpuUsage cpuUsage = new CpuUsage(processor, config.cpu()); FileSystem fileSystem = systemInfo.getOperatingSystem().getFileSystem(); FileSystemUsage fsUsage = new FileSystemUsage(fileSystem, config.fs()); this.cancellation = puller.start(id, cpuUsage, dispatcher, config.cpu().period()) .andThen( puller.start(id, fsUsage, dispatcher, config.fs().period())); } @Override public void stop() { if (cancellation != null) { cancellation.cancel(); } LOG.info("{}({}) has been successfully stopped", id, NAME); } @Override public String getId() { return id; } @Override public void init() { LOG.info("{}({}) has been successfully initialized", id, NAME); } @Override public void destroy() { LOG.info("{}({}) has been successfully destroyed", id, NAME); } } <file_sep>/anycollect-core/src/main/java/io/github/anycollect/core/impl/filters/MetricKeyPredicate.java package io.github.anycollect.core.impl.filters; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import io.github.anycollect.metric.Metric; import javax.annotation.Nullable; import java.util.function.Predicate; import java.util.regex.Pattern; public final class MetricKeyPredicate implements Predicate<Metric> { private final Pattern pattern; private final String equals; private final String startsWith; private final String endsWith; private final String contains; @JsonCreator public MetricKeyPredicate(@JsonProperty("regexp") @Nullable final String regexp, @JsonProperty("equals") @Nullable final String equals, @JsonProperty("starts") @Nullable final String startsWith, @JsonProperty("ends") @Nullable final String endsWith, @JsonProperty("contains") @Nullable final String contains) { if (regexp != null) { this.pattern = Pattern.compile(regexp); } else { this.pattern = null; } this.equals = equals; this.startsWith = startsWith; this.endsWith = endsWith; this.contains = contains; } @Override public boolean test(final Metric frame) { if (equals != null && !frame.getKey().equals(equals)) { return false; } if (startsWith != null && !frame.getKey().normalize().startsWith(startsWith)) { return false; } if (endsWith != null && !frame.getKey().normalize().endsWith(endsWith)) { return false; } if (contains != null && !frame.getKey().normalize().contains(contains)) { return false; } if (pattern != null) { return pattern.matcher(frame.getKey().normalize()).matches(); } return true; } } <file_sep>/anycollect-core-api/src/main/java/io/github/anycollect/core/manifest/ModuleManifest.java package io.github.anycollect.core.manifest; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Getter; import javax.annotation.Nonnull; import java.util.Collections; import java.util.List; public final class ModuleManifest { @Getter private final String manifest; private final List<ExtensionManifest> extensions; @JsonCreator public ModuleManifest(@JsonProperty("manifest") @Nonnull final String manifest, @JsonProperty("extensions") @Nonnull final List<ExtensionManifest> extensions) { this.manifest = manifest; this.extensions = extensions; } public List<ExtensionManifest> getExtensions() { return Collections.unmodifiableList(extensions); } } <file_sep>/anycollect-extension-system/src/main/java/io/github/anycollect/extensions/loaders/InstanceLoader.java package io.github.anycollect.extensions.loaders; import io.github.anycollect.core.exceptions.ConfigurationException; import io.github.anycollect.extensions.context.ExtendableContext; import io.github.anycollect.extensions.scope.Scope; import io.github.anycollect.extensions.substitution.VarSubstitutor; import javax.annotation.Nonnull; public interface InstanceLoader { Scope getScope(); VarSubstitutor getVarSubstitutor(); /** * Returns all extensions instances definitions. * * @throws ConfigurationException if configuration is wrong and cannot be loaded */ void load(@Nonnull ExtendableContext context); } <file_sep>/anycollect-jackson/src/main/java/io/github/anycollect/jackson/SampleDeserializer.java package io.github.anycollect.jackson; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.ObjectCodec; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import io.github.anycollect.metric.*; import java.io.IOException; public final class SampleDeserializer extends StdDeserializer<Sample> { public SampleDeserializer() { super(Sample.class); } @Override public Sample deserialize(final JsonParser parser, final DeserializationContext ctx) throws IOException { ObjectCodec codec = parser.getCodec(); JsonNode node = codec.readTree(parser); Key key = node.get("key").traverse(codec).readValueAs(Key.class); Stat stat = node.get("stat").traverse(codec).readValueAs(Stat.class); Tags tags = node.has("tags") ? node.get("tags").traverse(codec).readValueAs(Tags.class) : Tags.empty(); Tags meta = node.has("meta") ? node.get("meta").traverse(codec).readValueAs(Tags.class) : Tags.empty(); String unit = node.has("unit") ? node.get("unit").asText() : ""; long timestamp = node.get("timestamp").longValue(); double value = node.get("value").asDouble(); return Metric.builder() .key(key) .tags(tags) .meta(meta) .metric(stat, unit) .sample(value, timestamp); } } <file_sep>/anycollect-core/src/main/java/io/github/anycollect/core/impl/pull/separate/RegExpConcurrencyRule.java package io.github.anycollect.core.impl.pull.separate; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import io.github.anycollect.core.api.target.Target; import lombok.ToString; import javax.annotation.Nonnull; import java.util.regex.Pattern; @ToString public final class RegExpConcurrencyRule implements ConcurrencyRule { private final Pattern idRegexp; private final int poolSize; @JsonCreator public RegExpConcurrencyRule(@Nonnull @JsonProperty("targetId") final String idRegexp, @JsonProperty("poolSize") final int poolSize) { this.idRegexp = Pattern.compile(idRegexp); this.poolSize = poolSize; } @Override public int getPoolSize(@Nonnull final Target target, final int fallback) { if (idRegexp.matcher(target.getId()).matches()) { return poolSize; } return fallback; } } <file_sep>/anycollect-meter/src/main/java/io/github/anycollect/meter/impl/AnyCollectMeterRegistry.java package io.github.anycollect.meter.impl; import io.github.anycollect.core.api.Reader; import io.github.anycollect.core.api.common.Lifecycle; import io.github.anycollect.core.api.dispatcher.Dispatcher; import io.github.anycollect.core.api.internal.Clock; import io.github.anycollect.extensions.annotations.ExtConfig; import io.github.anycollect.extensions.annotations.ExtCreator; import io.github.anycollect.extensions.annotations.Extension; import io.github.anycollect.extensions.annotations.InstanceId; import io.github.anycollect.meter.api.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.concurrent.*; import java.util.function.ToDoubleFunction; import java.util.function.ToLongFunction; import static java.util.stream.Collectors.toList; @Extension(name = AnyCollectMeterRegistry.NAME, contracts = {MeterRegistry.class, Reader.class}) public final class AnyCollectMeterRegistry extends MeterRegistry implements Reader, Lifecycle { public static final String NAME = "MeterRegistry"; private static final Logger LOG = LoggerFactory.getLogger(AnyCollectMeterRegistry.class); private static final double[] QUANTILES = new double[]{0.5, 0.75, 0.9, 0.95, 0.99, 0.999}; private final ConcurrentMap<MeterId, Meter> meters = new ConcurrentHashMap<>(); private final Clock clock = Clock.getDefault(); private final String id; private final AnyCollectMeterRegistryConfig config; private final ScheduledExecutorService scheduler; @ExtCreator public AnyCollectMeterRegistry(@ExtConfig(optional = true) @Nullable final AnyCollectMeterRegistryConfig config, @InstanceId @Nonnull final String id) { this.id = id; this.config = config != null ? config : AnyCollectMeterRegistryConfig.DEFAULT; this.scheduler = Executors.newScheduledThreadPool(1); } @Nonnull @Override protected <T> Gauge gauge(@Nonnull final MeterId id, @Nonnull final T obj, @Nonnull final ToDoubleFunction<T> value) { return (Gauge) meters.computeIfAbsent(id, meterId -> DefaultGauge.<T>builder() .id(meterId) .obj(obj) .value(value) .prefix(config.globalPrefix()) .tags(config.commonTags()) .meta(config.commonMeta()) .clock(clock) .build()); } @Nonnull @Override protected Counter counter(@Nonnull final MeterId id) { return (Counter) meters.computeIfAbsent(id, meterId -> CumulativeCounter.builder() .id(meterId) .prefix(config.globalPrefix()) .tags(config.commonTags()) .meta(config.commonMeta()) .clock(clock) .build()); } @Nonnull @Override protected <T> FunctionCounter counter(@Nonnull final MeterId id, @Nonnull final T obj, @Nonnull final ToLongFunction<T> value) { return (FunctionCounter) meters.computeIfAbsent(id, meterId -> DefaultFunctionCounter.<T>builder() .id(meterId) .obj(obj) .value(value) .prefix(config.globalPrefix()) .tags(config.commonTags()) .meta(config.commonMeta()) .clock(clock) .build()); } @Nonnull @Override protected Distribution distribution(@Nonnull final MeterId id) { // TODO configure window and percentiles for each id return (Distribution) meters.computeIfAbsent(id, this::makeDistribuition); } private DistributionMeter makeDistribuition(final MeterId id) { // TODO configure window and percentiles for each id return CodahaleSlidingTimeWindowDistributionSummary.builder() .id(id) .quantiles(QUANTILES) .window(100) .prefix(config.globalPrefix()) .tags(config.commonTags()) .meta(config.commonMeta()) .clock(clock) .build(); } @Nonnull @Override protected Timer timer(@Nonnull final MeterId id, @Nonnull final TimeUnit timeUnit) { return (Timer) meters.computeIfAbsent(id, meterId -> new DistributionDelegatingTimer(meterId, makeDistribuition(meterId), timeUnit)); } @Override public void start(@Nonnull final Dispatcher dispatcher) { scheduler.scheduleAtFixedRate(() -> { dispatcher.dispatch(meters.values().stream() .flatMap(measurable -> measurable.measure().stream()) .collect(toList())); }, 0L, 10, TimeUnit.SECONDS); } @Override public void stop() { scheduler.shutdownNow(); LOG.info("{}({}) has been successfully stopped", id, NAME); } @Override public String getId() { return id; } @Override public void init() { LOG.info("{} has been successfully initialised", NAME); } @Override public void destroy() { LOG.info("{}({}) has been successfully destroyed", id, NAME); } } <file_sep>/extensions/readers/anycollect-jmx-reader/src/test/java/io/github/anycollect/readers/jmx/query/JvmMemoryTest.java package io.github.anycollect.readers.jmx.query; import io.github.anycollect.metric.Sample; import io.github.anycollect.metric.Tags; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.ObjectName; import java.lang.management.MemoryPoolMXBean; import java.lang.management.MemoryType; import java.lang.management.MemoryUsage; import java.util.List; import static io.github.anycollect.assertj.AnyCollectAssertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; class JvmMemoryTest { private MBeanServer server; private JvmMemory jvmMemory; @BeforeEach void setUp() { server = MBeanServerFactory.createMBeanServer(); jvmMemory = new JvmMemory(); } @Test void usedMemory() throws Exception { MemoryPoolMXBean memoryPool = mock(MemoryPoolMXBean.class); when(memoryPool.getName()).thenReturn("Test"); MemoryUsage heap = new MemoryUsage(1, 2, 3, 4); when(memoryPool.getType()).thenReturn(MemoryType.HEAP); when(memoryPool.getUsage()).thenReturn(heap); server.registerMBean(memoryPool, new ObjectName("java.lang:type=MemoryPool,name=Test")); List<Sample> samples = new MockJavaApp(server, Tags.of("instance", "test")).bind(jvmMemory).execute(); assertThat(samples).hasSize(1); assertThat(samples.get(0)) .hasKey("jvm/memory/used") .hasGauge("bytes", 2.0) .hasTags("instance", "test", "pool", "Test", "type", "heap"); } }<file_sep>/anycollect-meter-api/src/test/java/io/github/anycollect/meter/api/NoopMetersTest.java package io.github.anycollect.meter.api; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; class NoopMetersTest { @Test void registryTest() { Object stub = new Object(); NoopMeterRegistry registry = NoopMeterRegistry.INSTANCE; assertThat(registry.counter(mock(MeterId.class))).isSameAs(Counter.NOOP); assertThat(registry.distribution(mock(MeterId.class))).isSameAs(Distribution.NOOP); assertThat(registry.counter(mock(MeterId.class), stub, obj -> 1)).isSameAs(FunctionCounter.NOOP); assertThat(registry.gauge(mock(MeterId.class), stub, obj -> 1.0)).isSameAs(Gauge.NOOP); } }<file_sep>/anycollect-core/src/test/java/io/github/anycollect/core/impl/TestJob.java package io.github.anycollect.core.impl; import io.github.anycollect.core.api.job.Job; import io.github.anycollect.core.exceptions.ConnectionException; import io.github.anycollect.core.exceptions.QueryException; import io.github.anycollect.metric.Sample; import java.util.List; public class TestJob implements Job { private final TestTarget target; private final TestQuery query; public TestJob(TestTarget target, TestQuery query) { this.target = target; this.query = query; } @Override public List<Sample> execute() throws QueryException, ConnectionException { return target.execute(query); } } <file_sep>/anycollect-core-api/src/main/java/io/github/anycollect/core/api/target/SelfTarget.java package io.github.anycollect.core.api.target; import io.github.anycollect.metric.Tags; import javax.annotation.Nonnull; public final class SelfTarget extends AbstractTarget { public SelfTarget(@Nonnull final String id) { super(id, Tags.empty(), Tags.empty()); } } <file_sep>/anycollect-test-utils/anycollect-jmx-stub/Dockerfile FROM openjdk:8-jre-alpine MAINTAINER <NAME> ARG JAR_FILE ADD ${JAR_FILE} app.jar ADD target/libs/* libs/ ENV NODE $NODE ENV JMX_HOST $JMX_HOST ENV JMX_PORT $JMX_PORT ENV SERVICE_ID $SERVICE_ID ENV CONSUL_HOST $CONSUL_HOST ENV CONSUL_PORT $CONSUL_PORT ENTRYPOINT /usr/bin/java -Xmx20m -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.local.only=false -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Djava.rmi.server.hostname=${JMX_HOST} -Dcom.sun.management.jmxremote.rmi.port=${JMX_PORT} -Dcom.sun.management.jmxremote.port=${JMX_PORT} -jar app.jar ${NODE} ${SERVICE_ID} ${CONSUL_HOST} ${CONSUL_PORT} /var/run/${SERVICE_ID}.pid <file_sep>/extensions/common/anycollect-common-expression/src/test/java/io/github/anycollect/extensions/common/expression/ArgsTest.java package io.github.anycollect.extensions.common.expression; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; class ArgsTest { @Test void nullsAreForbidden() { Args args = MapArgs.builder() .add("key", "1") .build(); IllegalArgumentException ex = Assertions.assertThrows(IllegalArgumentException.class, () -> args.get("wrong")); assertThat(ex).hasMessageContaining("wrong"); assertThat(args.get("key")).isEqualTo("1"); Assertions.assertThrows(NullPointerException.class, () -> args.get(null)); } }<file_sep>/extensions/readers/anycollect-jmx-reader/src/test/java/io/github/anycollect/readers/jmx/server/JmxConnectionFactoryImplTest.java package io.github.anycollect.readers.jmx.server; import io.github.anycollect.core.exceptions.ConnectionException; import io.github.anycollect.readers.jmx.config.JavaAppConfig; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import javax.management.MBeanServerConnection; import javax.management.remote.JMXConnector; import javax.management.remote.JMXServiceURL; import java.io.IOException; import java.util.Collections; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.*; class JmxConnectionFactoryImplTest { private JmxConnectorFactory connectorFactory; private JMXConnector connector; private MBeanServerConnection connection; @BeforeEach void setUp() throws Exception { connectorFactory = mock(JmxConnectorFactory.class); connector = mock(JMXConnector.class); when(connectorFactory.connect(any(), any())).thenReturn(connector); connection = mock(MBeanServerConnection.class); when(connector.getMBeanServerConnection()).thenReturn(connection); } @Test void credentialsLessWithoutSslTest() throws Exception { JavaAppConfig config = new JavaAppConfig( "instance-1", "service:jmx:sample://", null ); JmxConnectionFactoryImpl factory = new JmxConnectionFactoryImpl(connectorFactory, config); JmxConnection jmxConnection = factory.createJmxConnection(); verify(connectorFactory, times(1)).connect( new JMXServiceURL("service:jmx:sample://"), Collections.emptyMap() ); assertThat(jmxConnection.getConnection()).isSameAs(connection); } @Test void mustWrapIOException() throws Exception { JavaAppConfig config = new JavaAppConfig( "instance-1", "service:jmx:sample://", null ); JmxConnectionFactoryImpl factory = new JmxConnectionFactoryImpl(connectorFactory, config); IOException cause = new IOException(); when(connectorFactory.connect(any(), any())).thenThrow(cause); ConnectionException ex = Assertions.assertThrows(ConnectionException.class, factory::createJmxConnection); assertThat(ex) .hasCause(cause) .hasMessageContaining(config.getUrl()) .hasMessageContaining(config.getInstanceId()); } }<file_sep>/anycollect-core-api/src/main/java/io/github/anycollect/core/api/kv/KeyValueStorageException.java package io.github.anycollect.core.api.kv; public class KeyValueStorageException extends Exception { public KeyValueStorageException(final String message) { super(message); } public KeyValueStorageException(final String message, final Throwable cause) { super(message, cause); } } <file_sep>/anycollect-test-utils/anycollect-jmx-stub/src/main/java/io/github/anycollect/testing/jmx/CounterMBean.java package io.github.anycollect.testing.jmx; public interface CounterMBean { double getDoubleCount(); double getLongCount(); } <file_sep>/anycollect-core/src/main/java/io/github/anycollect/core/impl/router/MonitoredMetricProducer.java package io.github.anycollect.core.impl.router; import io.github.anycollect.core.api.dispatcher.Dispatcher; import io.github.anycollect.meter.api.Counter; import io.github.anycollect.meter.api.MeterRegistry; import io.github.anycollect.metric.Sample; import javax.annotation.Nonnull; import java.util.List; public final class MonitoredMetricProducer implements MetricProducer { private final MetricProducer delegate; private final MeterRegistry registry; public MonitoredMetricProducer(@Nonnull final MetricProducer delegate, @Nonnull final MeterRegistry registry) { this.delegate = delegate; this.registry = registry; } @Override public void start(@Nonnull final Dispatcher dispatcher) { MonitoredDispatcher monitoredDispatcher = new MonitoredDispatcher(dispatcher, registry, this); delegate.start(monitoredDispatcher); } @Nonnull @Override public String getAddress() { return delegate.getAddress(); } @Override public String toString() { return delegate.getAddress(); } private static final class MonitoredDispatcher implements Dispatcher { private final Dispatcher delegate; private final Counter producedMetrics; MonitoredDispatcher(@Nonnull final Dispatcher delegate, @Nonnull final MeterRegistry registry, @Nonnull final MetricProducer producer) { this.delegate = delegate; this.producedMetrics = Counter.key("router/route/dispatched.metrics") .tag("route", producer.getAddress()) .meta(this.getClass()) .register(registry); } @Override public void dispatch(@Nonnull final Sample sample) { producedMetrics.increment(); delegate.dispatch(sample); } @Override public void dispatch(@Nonnull final List<Sample> samples) { producedMetrics.increment(samples.size()); delegate.dispatch(samples); } } } <file_sep>/anycollect-core-api/src/main/java/io/github/anycollect/core/api/Processor.java package io.github.anycollect.core.api; import io.github.anycollect.core.api.dispatcher.Dispatcher; import io.github.anycollect.metric.Sample; import javax.annotation.Nonnull; import java.util.List; public interface Processor extends Route { void start(@Nonnull Dispatcher dispatcher); void submit(@Nonnull List<? extends Sample> sources); } <file_sep>/extensions/common/anycollect-common-expression/src/test/java/io/github/anycollect/extensions/common/expression/filters/JoinFilterTest.java package io.github.anycollect.extensions.common.expression.filters; import io.github.anycollect.extensions.common.expression.ArgValidationException; import org.junit.jupiter.api.Test; import java.util.Arrays; import static org.assertj.core.api.Assertions.assertThat; class JoinFilterTest { @Test void varargsTest() throws ArgValidationException { JoinFilter filter = new JoinFilter(); String result = filter.filter("left", Arrays.asList("-middle-", "right")); assertThat(result).isEqualTo("left-middle-right"); } }<file_sep>/extensions/readers/anycollect-system-reader/src/main/java/io/github/anycollect/readers/system/FileSystemUsage.java package io.github.anycollect.readers.system; import io.github.anycollect.core.api.internal.Clock; import io.github.anycollect.core.api.query.SelfQuery; import io.github.anycollect.metric.Metric; import io.github.anycollect.metric.Sample; import io.github.anycollect.metric.Tags; import oshi.software.os.FileSystem; import oshi.software.os.OSFileStore; import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.List; public final class FileSystemUsage extends SelfQuery { private final FileSystem fileSystem; private final FileSystemConfig config; private final Clock clock; public FileSystemUsage(@Nonnull final FileSystem fileSystem, @Nonnull final FileSystemConfig config) { super("fs.usage"); this.fileSystem = fileSystem; this.config = config; this.clock = Clock.getDefault(); } @Override public List<Sample> execute() { List<Sample> samples = new ArrayList<>(); long timestamp = clock.wallTime(); if (config.reportOpenDescriptors()) { long openFileDescriptors = fileSystem.getOpenFileDescriptors(); samples.add(Metric.builder() .key("fs/open.descriptors") .gauge() .sample(openFileDescriptors, timestamp) ); } for (OSFileStore fileStore : fileSystem.getFileStores()) { long usableSpace = fileStore.getUsableSpace(); long totalSpace = fileStore.getTotalSpace(); String fileSystem = fileStore.getType(); if (config.ignoreFileSystems().contains(fileSystem)) { continue; } double usage = 100.0 * (totalSpace - usableSpace) / totalSpace; String mount = fileStore.getMount(); String device = fileStore.getVolume(); samples.add(Metric.builder() .key("fs/usage") .tags(Tags.of("mount", mount, "fs", fileSystem, "device", device)) .gauge("percents") .sample(usage, timestamp) ); } return samples; } } <file_sep>/anycollect-core-api/src/main/java/io/github/anycollect/core/api/Serializer.java package io.github.anycollect.core.api; import io.github.anycollect.core.exceptions.SerialisationException; import io.github.anycollect.metric.Sample; import javax.annotation.Nonnull; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.CoderResult; public interface Serializer { @Nonnull default String serialize(@Nonnull Sample sample) throws SerialisationException { ByteBuffer buffer = ByteBuffer.allocate(2048); serialize(sample, buffer); buffer.flip(); try { CharBuffer decode = Charset.forName("UTF-8").newDecoder().decode(buffer); return new String(decode.array(), 0, decode.limit()); } catch (CharacterCodingException e) { throw new SerialisationException("could not serialize metric", e); } } CoderResult serialize(@Nonnull Sample sample, @Nonnull ByteBuffer buffer) throws SerialisationException; } <file_sep>/anycollect-core/src/main/java/io/github/anycollect/core/impl/pull/DesiredStateManager.java package io.github.anycollect.core.impl.pull; import io.github.anycollect.core.api.common.Lifecycle; import io.github.anycollect.core.api.internal.State; import io.github.anycollect.core.api.query.Query; import io.github.anycollect.core.api.target.Target; import javax.annotation.Nonnull; public interface DesiredStateManager<T extends Target, Q extends Query<T>> extends Lifecycle { void update(@Nonnull State<T, Q> desiredState); void cleanup(); } <file_sep>/anycollect-extension-system/src/main/java/io/github/anycollect/extensions/exceptions/WrongDependencyClassException.java package io.github.anycollect.extensions.exceptions; import io.github.anycollect.core.exceptions.ConfigurationException; import java.util.Set; public final class WrongDependencyClassException extends ConfigurationException { public WrongDependencyClassException(final String name, final Class<?> expected, final Set<Class<?>> actual) { super(String.format("dependency %s requires parameter of type %s, but given %s", name, expected, actual)); } } <file_sep>/extensions/common/anycollect-common-expression/src/main/java/io/github/anycollect/extensions/common/expression/ast/ArgumentsExpressionNode.java package io.github.anycollect.extensions.common.expression.ast; import io.github.anycollect.extensions.common.expression.ast.visitor.ExpressionNodeVisitor; import lombok.ToString; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; @ToString public final class ArgumentsExpressionNode implements ExpressionNode, Iterable<ArgumentExpressionNode> { private final List<ArgumentExpressionNode> arguments; public ArgumentsExpressionNode(final ArgumentExpressionNode base) { arguments = new ArrayList<>(); arguments.add(base); } @Override public void accept(final ExpressionNodeVisitor visitor) { visitor.visit(this); for (ArgumentExpressionNode argument : arguments) { argument.accept(visitor); } } public void add(final ArgumentExpressionNode argument) { this.arguments.add(argument); } @Override public Iterator<ArgumentExpressionNode> iterator() { return Collections.unmodifiableList(arguments).iterator(); } } <file_sep>/anycollect-meter-api/src/main/java/io/github/anycollect/meter/api/Distribution.java package io.github.anycollect.meter.api; import io.github.anycollect.metric.Key; import org.apiguardian.api.API; import javax.annotation.Nonnull; @API(since = "0.1.0", status = API.Status.EXPERIMENTAL) public interface Distribution { Distribution NOOP = amount -> { }; static DistributionBuilder key(@Nonnull final String key) { return new DistributionBuilder(Key.of(key)); } static DistributionBuilder key(@Nonnull final Key key) { return new DistributionBuilder(key); } void record(long amount); final class DistributionBuilder extends BaseMeterBuilder<DistributionBuilder> { DistributionBuilder(@Nonnull final Key key) { super(key); } @Override protected DistributionBuilder self() { return this; } public DistributionBuilder unit(@Nonnull final String unit) { return super.unit(unit); } public Distribution register(@Nonnull final MeterRegistry registry) { ImmutableMeterId id = new ImmutableMeterId( getKey(), getUnit(), getTagsBuilder().build(), getMetaBuilder().build()); return registry.distribution(id); } } } <file_sep>/anycollect-core/src/main/java/io/github/anycollect/core/impl/router/BackgroundMetricConsumer.java package io.github.anycollect.core.impl.router; import io.github.anycollect.meter.api.Counter; import io.github.anycollect.meter.api.Gauge; import io.github.anycollect.meter.api.MeterRegistry; import io.github.anycollect.metric.Sample; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nonnull; import javax.annotation.concurrent.ThreadSafe; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.atomic.AtomicLong; @ThreadSafe public final class BackgroundMetricConsumer implements MetricConsumer { private static final Logger LOG = LoggerFactory.getLogger(BackgroundMetricConsumer.class); private final ExecutorService executor; private final MetricConsumer delegate; private volatile boolean stopped = false; private final AtomicLong awaitingMetrics = new AtomicLong(0L); private final Counter rejected; public BackgroundMetricConsumer(@Nonnull final ExecutorService executor, @Nonnull final MetricConsumer delegate, @Nonnull final MeterRegistry registry) { this.executor = executor; this.delegate = delegate; Gauge.make("router/route/awaiting.metrics", awaitingMetrics, AtomicLong::get) .tag("route", getAddress()) .meta(this.getClass()) .register(registry); this.rejected = Counter.key("router/route/rejected.metrics") .tag("route", getAddress()) .meta(this.getClass()) .register(registry); } @Override public void consume(@Nonnull final List<? extends Sample> samples) { if (!stopped) { try { awaitingMetrics.addAndGet(samples.size()); executor.submit(() -> { awaitingMetrics.getAndAdd(-samples.size()); delegate.consume(samples); }); } catch (RejectedExecutionException e) { rejected.increment(samples.size()); } } } @Override public void stop() { stopped = true; delegate.stop(); LOG.info("Stopping async input queue workers for {}, there are currently {} unprocessed metrics", getAddress(), awaitingMetrics.get()); this.executor.shutdown(); LOG.info("Input queue worker for {} has been successfully stopped", getAddress()); } @Override public String toString() { return delegate.getAddress(); } @Nonnull @Override public String getAddress() { return delegate.getAddress(); } } <file_sep>/anycollect-extension-system/src/test/java/io/github/anycollect/extensions/samples/SampleExtensionConfig.java package io.github.anycollect.extensions.samples; public class SampleExtensionConfig { } <file_sep>/anycollect-core/src/test/java/io/github/anycollect/core/impl/pull/DesiredStateManagerImplTest.java package io.github.anycollect.core.impl.pull; import io.github.anycollect.core.api.dispatcher.Dispatcher; import io.github.anycollect.core.api.internal.Clock; import io.github.anycollect.core.api.internal.ImmutableState; import io.github.anycollect.core.api.internal.State; import io.github.anycollect.core.impl.NoopCancelation; import io.github.anycollect.core.impl.TestQuery; import io.github.anycollect.core.impl.TestTarget; import io.github.anycollect.core.impl.pull.availability.CheckingTarget; import io.github.anycollect.core.impl.pull.availability.HealthChecker; import io.github.anycollect.core.api.internal.Cancellation; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import static org.mockito.Mockito.*; class DesiredStateManagerImplTest { private PullScheduler pullScheduler = mock(PullScheduler.class); private Dispatcher dispatcher = Dispatcher.noop(); private DesiredStateManagerImpl<TestTarget, TestQuery> manager; @BeforeEach void setUp() { when(pullScheduler.schedulePull(any(), any(), any(), anyInt())).thenReturn(new NoopCancelation()); } @Test @DisplayName("is instantiated") void isInstantiatedWithNew() { new DesiredStateManagerImpl<>(pullScheduler, dispatcher, HealthChecker.noop()); } @Nested @DisplayName("after target with two queries added") class AfterTargetWithTwoQueriesAdded { private TestTarget target1 = mock(TestTarget.class); private CheckingTarget<TestTarget> checkingTarget1; private TestQuery query11 = new TestQuery("id11"); private TestQuery query12 = new TestQuery("id12"); private State<TestTarget, TestQuery> state; private Cancellation query11Cancellation = mock(Cancellation.class); private Cancellation query12Cancellation = mock(Cancellation.class); @BeforeEach void createManager() { Clock clock = mock(Clock.class); when(clock.wallTime()).thenReturn(0L); manager = new DesiredStateManagerImpl<>(pullScheduler, dispatcher, clock); state = ImmutableState.<TestTarget, TestQuery>builder() .put(target1, query11, 1) .put(target1, query12, 2) .build(); checkingTarget1 = new CheckingTarget<>(target1, 0); when(pullScheduler.schedulePull(eq(checkingTarget1), eq(query11), any(), anyInt())).thenReturn(query11Cancellation); when(pullScheduler.schedulePull(eq(checkingTarget1), eq(query12), any(), anyInt())).thenReturn(query12Cancellation); manager.update(state); } @Test @DisplayName("pull jobs have been scheduled") void pullJobsHaveBeenScheduled() { verify(pullScheduler, times(1)).schedulePull(eq(checkingTarget1), same(query11), same(dispatcher), eq(1)); verify(pullScheduler, times(1)).schedulePull(eq(checkingTarget1), same(query12), same(dispatcher), eq(2)); } @Nested @DisplayName("when remove target from new state") class WhenRemoveTargetFromNewState { private TestTarget target2 = mock(TestTarget.class); private TestQuery query21 = new TestQuery("id21"); private TestQuery query22 = new TestQuery("id22"); private State<TestTarget, TestQuery> state; @BeforeEach void updateState() { state = ImmutableState.<TestTarget, TestQuery>builder() .put(target2, query21, 3) .put(target2, query22, 4) .build(); manager.update(state); } @Test @DisplayName("obsolete target must be realised") void obsoleteTargetMustBeRealised() { verify(pullScheduler, times(1)).release(target1); } @Test @DisplayName("new target must be scheduled") void newOneMustBeScheduled() { verify(pullScheduler, times(1)).schedulePull(eq(new CheckingTarget<>(target2, 0)), same(query21), same(dispatcher), eq(3)); verify(pullScheduler, times(1)).schedulePull(eq(new CheckingTarget<>(target2, 0)), same(query22), same(dispatcher), eq(4)); } } @Nested @DisplayName("when change queries to existing target") class WhenChangeQueriesToExistingTarget { private TestQuery query13 = new TestQuery("id13"); private TestQuery query14 = new TestQuery("id14"); private State<TestTarget, TestQuery> state; @BeforeEach void updateState() { state = ImmutableState.<TestTarget, TestQuery>builder() .put(target1, query13, 5) .put(target1, query14, 6) .build(); manager.update(state); } @Test @DisplayName("this target must not be realised") void targetMustNotBeRealised() { verify(pullScheduler, never()).release(target1); } @Test @DisplayName("obsolete queries must be cancelled") void obsoleteQueriesMustBeCancelled() { verify(query11Cancellation, times(1)).cancel(); verify(query12Cancellation, times(1)).cancel(); } @Test @DisplayName("additional queries must be added") void additionalQueriesMustBeAdded() { verify(pullScheduler, times(1)).schedulePull(eq(checkingTarget1), same(query13), same(dispatcher), eq(5)); verify(pullScheduler, times(1)).schedulePull(eq(checkingTarget1), same(query14), same(dispatcher), eq(6)); } } @Nested @DisplayName("when add queries to existing target") class WhenAddQueriesToExistingTarget { private TestQuery query15 = new TestQuery("id15"); private TestQuery query16 = new TestQuery("id16"); private State<TestTarget, TestQuery> state; @BeforeEach void updateState() { state = ImmutableState.<TestTarget, TestQuery>builder() .put(target1, query11, 1) .put(target1, query12, 2) .put(target1, query15, 7) .put(target1, query16, 8) .build(); manager.update(state); } @Test @DisplayName("this target must not be realised") void targetMustNotBeRealised() { verify(pullScheduler, never()).release(target1); } @Test @DisplayName("previous queries must not be rescheduled") void previousQueriesMustNotBeRescheduled() { verify(query11Cancellation, times(0)).cancel(); verify(query12Cancellation, times(0)).cancel(); verify(pullScheduler, times(1)).schedulePull(eq(checkingTarget1), same(query11), same(dispatcher), eq(1)); verify(pullScheduler, times(1)).schedulePull(eq(checkingTarget1), same(query12), same(dispatcher), eq(2)); } @Test @DisplayName("additional queries must be added") void additionalQueriesMustBeAdded() { verify(pullScheduler, times(1)).schedulePull(eq(checkingTarget1), same(query15), same(dispatcher), eq(7)); verify(pullScheduler, times(1)).schedulePull(eq(checkingTarget1), same(query16), same(dispatcher), eq(8)); } } @Nested @DisplayName("when change period for existing queries") class WhenChangePeriodForExistingQueries { private State<TestTarget, TestQuery> state; @BeforeEach void updateState() { state = ImmutableState.<TestTarget, TestQuery>builder() .put(target1, query11, 9) .put(target1, query12, 10) .build(); manager.update(state); } @Test @DisplayName("this target must not be realised") void targetMustNotBeRealised() { verify(pullScheduler, never()).release(target1); } @Test @DisplayName("previous queries must be cancelled") void previousQueriesMustBeCancelled() { verify(query11Cancellation, times(1)).cancel(); verify(query12Cancellation, times(1)).cancel(); } @Test @DisplayName("queries with new period must be added") void queriesWithNewPeriodMustBeAdded() { verify(pullScheduler, times(1)).schedulePull(eq(checkingTarget1), same(query11), same(dispatcher), eq(9)); verify(pullScheduler, times(1)).schedulePull(eq(checkingTarget1), same(query12), same(dispatcher), eq(10)); } } @Nested @DisplayName("when destroy") class WhenDestroy { @BeforeEach void destroyManager() { manager.destroy(); } @Test @DisplayName("all queries must be cancelled") void allQueriesMustBeCancelled() { verify(query11Cancellation, times(1)).cancel(); verify(query12Cancellation, times(1)).cancel(); } @Test @DisplayName("all targets must be realised") void allTargetsMustBeRealised() { verify(pullScheduler, times(1)).release(target1); } } } // private static void verify() { // // } }<file_sep>/anycollect-test-utils/anycollect-assertj-extension/src/main/java/io/github/anycollect/assertj/SampleAssert.java package io.github.anycollect.assertj; import io.github.anycollect.metric.Key; import io.github.anycollect.metric.Sample; import io.github.anycollect.metric.Stat; import org.assertj.core.api.AbstractAssert; public final class SampleAssert extends AbstractAssert<SampleAssert, Sample> { public SampleAssert(final Sample actual) { super(actual, SampleAssert.class); } public static SampleAssert assertThat(final Sample actual) { return new SampleAssert(actual); } public SampleAssert hasKey(final Key key) { if (!key.equals(actual.getKey())) { failWithMessage("expected <%s> to have key %s but was <%s>", actual, key, actual.getKey()); } return this; } public SampleAssert hasKey(final String key) { if (!key.equals(actual.getKey().normalize())) { failWithMessage("expected <%s> to have key %s but was <%s>", actual, key, actual.getKey()); } return this; } public SampleAssert hasTags(final String... tags) { TagsAssert.assertThat(actual.getTags()).hasTags(tags); return this; } public SampleAssert hasMeta(final String... tags) { TagsAssert.assertThat(actual.getMeta()).hasTags(tags); return this; } public SampleAssert hasGauge(final double value) { return hasGauge("", value); } public SampleAssert hasGauge(final String unit, final double value) { return hasMetric(Stat.GAUGE, unit, value); } public SampleAssert hasMetric(final Stat stat, final String unit, final double value) { if (!stat.equals(actual.getStat()) || !unit.equals(actual.getUnit()) || value != actual.getValue()) { failWithMessage("Expected <%s> to have measurement of stat <%s>, unit <%s> and value <%s>", actual, stat, unit, value); } return this; } } <file_sep>/anycollect-core-api/src/main/java/io/github/anycollect/core/api/internal/PullManager.java package io.github.anycollect.core.api.internal; import io.github.anycollect.core.api.dispatcher.Dispatcher; import io.github.anycollect.core.api.query.Query; import io.github.anycollect.core.api.query.QueryProvider; import io.github.anycollect.core.api.query.SelfQuery; import io.github.anycollect.core.api.target.ServiceDiscovery; import io.github.anycollect.core.api.target.Target; import javax.annotation.Nonnull; public interface PullManager { <T extends Target, Q extends Query<T>> Cancellation start( @Nonnull String token, @Nonnull ServiceDiscovery<? extends T> discovery, @Nonnull QueryProvider<? extends Q> provider, @Nonnull QueryMatcherResolver resolver, @Nonnull Dispatcher dispatcher ); <Q extends SelfQuery> Cancellation start(@Nonnull String token, @Nonnull Q selfQuery, @Nonnull Dispatcher dispatcher); <Q extends SelfQuery> Cancellation start(@Nonnull String token, @Nonnull Q selfQuery, @Nonnull Dispatcher dispatcher, int periodInSeconds); <T extends Target, Q extends Query<T>> Cancellation start(@Nonnull String token, @Nonnull DesiredStateProvider<T, Q> stateProvider, @Nonnull Dispatcher dispatcher); } <file_sep>/anycollect-core-api/src/main/java/io/github/anycollect/core/api/internal/PeriodicQuery.java package io.github.anycollect.core.api.internal; public interface PeriodicQuery<Q> { Q getQuery(); int getPeriodInSeconds(); } <file_sep>/anycollect-core-api/src/main/java/io/github/anycollect/core/api/query/CompositeQueryProvider.java package io.github.anycollect.core.api.query; import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.List; import java.util.Set; import static java.util.stream.Collectors.toSet; public final class CompositeQueryProvider<Q extends Query> implements QueryProvider<Q> { private final List<? extends QueryProvider<? extends Q>> providers; public CompositeQueryProvider(final List<? extends QueryProvider<? extends Q>> providers) { this.providers = new ArrayList<>(providers); } @Nonnull @Override public Set<Q> provide() { return providers.stream().flatMap(provider -> provider.provide().stream()) .collect(toSet()); } } <file_sep>/extensions/readers/anycollect-jmx-reader/src/main/java/io/github/anycollect/readers/jmx/server/pool/impl/CommonsJmxConnectionPool.java package io.github.anycollect.readers.jmx.server.pool.impl; import io.github.anycollect.core.exceptions.ConnectionException; import io.github.anycollect.readers.jmx.server.JmxConnection; import io.github.anycollect.readers.jmx.server.pool.JmxConnectionPool; import org.apache.commons.pool2.impl.GenericObjectPool; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nonnull; import java.util.NoSuchElementException; import java.util.Objects; import java.util.concurrent.atomic.LongAdder; public final class CommonsJmxConnectionPool implements JmxConnectionPool { private static final Logger LOG = LoggerFactory.getLogger(CommonsJmxConnectionPool.class); private final GenericObjectPool<JmxConnection> pool; private final LongAdder totalInvalidated = new LongAdder(); public CommonsJmxConnectionPool(@Nonnull final GenericObjectPool<JmxConnection> pool) { Objects.requireNonNull(pool, "commons pool must not be null"); this.pool = pool; } @Nonnull @Override public JmxConnection borrowConnection() throws ConnectionException { try { return pool.borrowObject(); } catch (NoSuchElementException e) { throw new ConnectionException("unable to borrow jmx connection from pool due to timeout"); } catch (ConnectionException e) { throw e; } catch (Exception e) { LOG.warn("unable to borrow connection due to unexpected error, this should never happen", e); throw new ConnectionException("unable to borrow connection from pool due to unexpected error", e); } } @Override public void invalidateConnection(@Nonnull final JmxConnection connection) { try { totalInvalidated.increment(); pool.invalidateObject(connection); } catch (Exception e) { LOG.warn("unable to invalidate connection {}, this should never happen", connection, e); } } @Override public void returnConnection(@Nonnull final JmxConnection connection) { try { pool.returnObject(connection); } catch (Exception e) { LOG.warn("unable to return connection {}, this should never happen", connection, e); } } @Override public int getNumActive() { return pool.getNumActive(); } @Override public int getNumIdle() { return pool.getNumIdle(); } @Override public long getTotalInvalidated() { return totalInvalidated.longValue(); } } <file_sep>/anycollect-core-api/src/main/java/io/github/anycollect/core/api/target/CompositeServiceDiscovery.java package io.github.anycollect.core.api.target; import java.util.ArrayList; import java.util.List; import java.util.Set; import static java.util.stream.Collectors.toSet; public final class CompositeServiceDiscovery<T extends Target> implements ServiceDiscovery<T> { private final List<? extends ServiceDiscovery<? extends T>> discoveries; public CompositeServiceDiscovery(final List<? extends ServiceDiscovery<? extends T>> discoveries) { this.discoveries = new ArrayList<>(discoveries); } @Override public Set<T> discover() { return discoveries.stream().flatMap(discovery -> discovery.discover().stream()) .collect(toSet()); } } <file_sep>/anycollect-test-utils/anycollect-jmx-stub/src/main/java/io/github/anycollect/testing/jmx/MBeanType.java package io.github.anycollect.testing.jmx; public enum MBeanType { HISTOGRAM, COUNTER, GAUGE } <file_sep>/extensions/readers/anycollect-jmx-reader/src/test/java/io/github/anycollect/readers/jmx/server/pool/impl/CommonsJmxConnectionPoolFactoryTest.java package io.github.anycollect.readers.jmx.server.pool.impl; import io.github.anycollect.readers.jmx.server.JmxConnection; import io.github.anycollect.readers.jmx.server.JmxConnectionFactory; import io.github.anycollect.readers.jmx.server.pool.AsyncConnectionCloser; import io.github.anycollect.readers.jmx.server.pool.JmxConnectionPool; import org.junit.jupiter.api.Test; import javax.management.MBeanServerConnection; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; class CommonsJmxConnectionPoolFactoryTest { @Test void poolMustWrapGivenFactory() throws Exception { AsyncConnectionCloser closer = mock(AsyncConnectionCloser.class); CommonsJmxConnectionPoolFactory factory = new CommonsJmxConnectionPoolFactory(closer); JmxConnection jmxConnection = spy(new JmxConnection(null, mock(MBeanServerConnection.class))); JmxConnectionFactory jmxConnectionFactory = mock(JmxConnectionFactory.class); when(jmxConnectionFactory.createJmxConnection()).thenReturn(jmxConnection); JmxConnectionPool pool = factory.create(jmxConnectionFactory); JmxConnection actualConnection = pool.borrowConnection(); assertThat(actualConnection).isSameAs(jmxConnection); } }<file_sep>/extensions/readers/anycollect-jmx-reader/src/main/java/io/github/anycollect/readers/jmx/query/operations/InvokeOperation.java package io.github.anycollect.readers.jmx.query.operations; import io.github.anycollect.core.exceptions.ConnectionException; import io.github.anycollect.core.exceptions.QueryException; import javax.annotation.Nonnull; import javax.management.*; import java.io.IOException; public final class InvokeOperation implements QueryOperation<Object> { private final ObjectName objectName; private final String operationName; private final Object[] params; private final String[] signature; public InvokeOperation(final ObjectName objectName, final String operationName, final Object[] params, final String[] signature) { this.objectName = objectName; this.operationName = operationName; this.params = params; this.signature = signature; } @Override public Object operate(@Nonnull final MBeanServerConnection connection) throws QueryException, ConnectionException { try { return connection.invoke(objectName, operationName, params, signature); } catch (InstanceNotFoundException | MBeanException | ReflectionException e) { throw new QueryException("could not invoke operation", e); } catch (IOException e) { throw new ConnectionException("could not invoke operation", e); } } } <file_sep>/anycollect-core/src/main/java/io/github/anycollect/core/impl/pull/availability/HealthChecker.java package io.github.anycollect.core.impl.pull.availability; import io.github.anycollect.core.api.query.Query; import io.github.anycollect.core.api.target.Target; import javax.annotation.Nonnull; public interface HealthChecker<T extends Target, Q extends Query<T>> { @SuppressWarnings("rawtypes") HealthChecker NOOP = new HealthChecker() { @Override public void add(@Nonnull final CheckingTarget checkingTarget) { } @Override public void remove(@Nonnull final CheckingTarget checkingTarget) { } }; @SuppressWarnings("unchecked") static <T extends Target, Q extends Query<T>> HealthChecker<T, Q> noop() { return (HealthChecker<T, Q>) NOOP; } void add(@Nonnull CheckingTarget<T> checkingTarget); void remove(@Nonnull CheckingTarget<T> checkingTarget); } <file_sep>/anycollect-extension-system/src/main/java/io/github/anycollect/extensions/loaders/snakeyaml/CustomConstructor.java package io.github.anycollect.extensions.loaders.snakeyaml; import com.fasterxml.jackson.databind.InjectableValues; import com.fasterxml.jackson.databind.MapperFeature; import com.fasterxml.jackson.databind.Module; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; import io.github.anycollect.core.exceptions.ConfigurationException; import io.github.anycollect.extensions.Activation; import io.github.anycollect.extensions.Definition; import io.github.anycollect.extensions.Instance; import io.github.anycollect.extensions.annotations.InjectMode; import io.github.anycollect.extensions.api.JacksonModule; import io.github.anycollect.extensions.common.expression.*; import io.github.anycollect.extensions.common.expression.std.StdExpressionFactory; import io.github.anycollect.extensions.context.ExtendableContext; import io.github.anycollect.extensions.dependencies.ConfigDefinition; import io.github.anycollect.extensions.exceptions.MissingRequiredPropertyException; import io.github.anycollect.extensions.expression.VarSubstitutorToArgsAdapter; import io.github.anycollect.extensions.loaders.InstanceLoader; import io.github.anycollect.extensions.scope.Scope; import io.github.anycollect.extensions.substitution.VarSubstitutor; import lombok.Getter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.yaml.snakeyaml.constructor.AbstractConstruct; import org.yaml.snakeyaml.constructor.Constructor; import org.yaml.snakeyaml.nodes.*; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toMap; final class CustomConstructor extends Constructor { private static final Logger LOG = LoggerFactory.getLogger(CustomConstructor.class); private static final String DEPENDENCIES = "dependencies"; private static final String EXTENSION = "extension"; private static final String INSTANCE = "instance"; private static final String INJECT_MODE = "injectMode"; private static final String ACTIVATION = "activation"; private final ObjectMapper mapper; private static final String CONFIG = "config"; private final ExtendableContext context; private final Scope scope; private final VarSubstitutor environment; private final Args expressionVars; private final ExpressionFactory expressions; private final InjectableValues.Std values; private String extensionName; CustomConstructor(final ExtendableContext context, final Scope scope, final VarSubstitutor environment) { this.mapper = new ObjectMapper(new YAMLFactory()); this.mapper.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS); this.values = new InjectableValues.Std(); this.values.addValue("environment", environment); this.mapper.setInjectableValues(values); this.context = context; this.scope = scope; this.environment = environment; this.expressions = new StdExpressionFactory(); this.expressionVars = new VarSubstitutorToArgsAdapter(environment); yamlConstructors.put(new Tag("!load"), new PluginInstanceDefinitionConstruct()); yamlConstructors.put(new Tag("!ref"), new PluginRefConstruct()); yamlConstructors.put(new Tag("!refs"), new PluginRefsConstruct()); yamlConstructors.put(new Tag("!var"), new VarSubstituteConstruct()); yamlConstructors.put(new Tag("!exp"), new ExpressionConstruct()); for (Instance instance : context.getInstances()) { upgradeMapperIfNeeded(instance); } } private void upgradeMapperIfNeeded(final Instance instance) { Object resolved = instance.resolve(); if (resolved instanceof Module) { Module module = (Module) resolved; LOG.debug("register jackson module {}", module.getModuleName()); mapper.registerModule(module); } if (resolved instanceof JacksonModule) { Module module = ((JacksonModule) resolved).module(); LOG.debug("register jackson module {}", module.getModuleName()); mapper.registerModule(module); } } class PluginInstanceDefinitionConstruct extends AbstractConstruct { private MappingNode currentNode; private Map<Object, Object> values; @Override public Object construct(final Node node) { LOG.trace("start processing node: {}", node); if (!(node instanceof MappingNode)) { throw new ConfigurationException("Non-mapping use of tag !load is illegal: " + node); } this.currentNode = (MappingNode) node; extensionName = getExtensionName(); this.values = constructMapping(currentNode); Definition definition = getExtension(); String instanceName = getInstanceName(); LOG.info("Creating \"{}\".{}", scope, instanceName); Object config = getNullableConfig(definition, instanceName); Map<String, Instance> singleDependencies = getSingleDependencies(); Map<String, List<Instance>> multiDependencies = getMultiDependencies(); Activation activation = getActivation(); if (!activation.isReached()) { LOG.info("instance {} is not activated", instanceName); return null; } Instance instance = definition.createInstance( instanceName, config, singleDependencies, multiDependencies, context, getInjectMode(), scope); context.addInstance(instance); Object resolved = instance.resolve(); // TODO for (final Class<?> contract : instance.getDefinition().getContracts()) { if (context.getInstance(contract, scope) == instance) { CustomConstructor.this.values.addValue(contract, resolved); } } LOG.trace("instance has been successfully loaded: {}", instance); if (resolved instanceof InstanceLoader) { InstanceLoader childLoader = (InstanceLoader) resolved; LOG.info("Start child instance loader {}", instanceName); childLoader.load(context); } upgradeMapperIfNeeded(instance); return instance; } private String getInstanceName() { return values.containsKey(INSTANCE) ? (String) values.get(INSTANCE) : extensionName; } private String getExtensionName() { for (NodeTuple tuple : currentNode.getValue()) { if (EXTENSION.equals(((ScalarNode) tuple.getKeyNode()).getValue())) { extensionName = ((ScalarNode) tuple.getValueNode()).getValue(); } } if (extensionName == null) { LOG.error("there is no \"{}\" property in configuration in {}", EXTENSION, currentNode); throw new MissingRequiredPropertyException(EXTENSION); } return extensionName; } private InjectMode getInjectMode() { return values.containsKey(INJECT_MODE) ? InjectMode.valueOf(((String) values.get(INJECT_MODE)).toUpperCase()) : InjectMode.MANUAL; } private Map<String, Instance> getSingleDependencies() { if (values.containsKey(DEPENDENCIES)) { return ((Map<?, ?>) (values.get(DEPENDENCIES))).entrySet().stream() .filter(entry -> entry.getValue() instanceof Instance) .map(entry -> new InstanceBinding((String) entry.getKey(), (Instance) entry.getValue())) .collect(toMap(InstanceBinding::getName, InstanceBinding::getInstance)); } return Collections.emptyMap(); } @SuppressWarnings("unchecked") private Map<String, List<Instance>> getMultiDependencies() { if (values.containsKey(DEPENDENCIES)) { return ((Map<?, ?>) (values.get(DEPENDENCIES))).entrySet().stream() .filter(entry -> entry.getValue() instanceof List) .map(entry -> new InstancesBinding((String) entry.getKey(), (List<Instance>) entry.getValue())) .collect(toMap(InstancesBinding::getName, InstancesBinding::getInstances)); } return Collections.emptyMap(); } private Object getNullableConfig(final Definition definition, final String instanceName) { Object rawConfig = values.get(CONFIG); if (rawConfig == null) { if (!definition.getConfigDefinition().map(ConfigDefinition::isSingle).orElse(true)) { return Collections.emptyList(); } return null; } ConfigDefinition config = definition.getConfigDefinition().orElseThrow(() -> { LOG.error("extension {} is not configurable", definition); return new ConfigurationException("custom config for " + definition + " is not supported"); }); if (!config.getConfigKey().isEmpty()) { rawConfig = ((Map<?, ?>) rawConfig).get(config.getConfigKey()); } if (rawConfig == null) { return null; } try { if (!(config.isSingle())) { if (!(rawConfig instanceof List)) { throw new IllegalArgumentException("TODO"); } List<Object> listConfig = new ArrayList<>(); List<?> listRawConfig = (List<?>) rawConfig; for (Object elementRawConfig : listRawConfig) { Object elementConfig = mapper.readValue(mapper.writeValueAsString(elementRawConfig), config.getParameterType()); listConfig.add(elementConfig); } return listConfig; } return mapper.readValue(mapper.writeValueAsString(rawConfig), config.getParameterType()); } catch (IOException e) { LOG.error("unexpected error during parsing configuration of class {} for {}, config: {}", config.getParameterType().getName(), instanceName, rawConfig, e); throw new ConfigurationException("unexpected error during parsing configuration", e); } } private Activation getActivation() { if (values.containsKey(ACTIVATION)) { Object rawActivation = values.get(ACTIVATION); try { return mapper.readValue(mapper.writeValueAsString(rawActivation), Activation.class); } catch (IOException e) { LOG.error("could not parse activation {}", rawActivation, e); throw new ConfigurationException("could not parse activation", e); } } return Activation.active(); } } class VarSubstituteConstruct extends AbstractConstruct { @Override public Object construct(final Node node) { LOG.debug("start resolving environment variable: {}", node); if (!(node instanceof ScalarNode)) { throw new ConfigurationException("Non-scalar use of tag !var tag is illegal: " + node); } ScalarNode scalarNode = (ScalarNode) node; String varName = scalarNode.getValue(); Object var = environment.substitute(varName); LOG.debug("environment variable {} resolved to: {}", varName, var); return var; } } class ExpressionConstruct extends AbstractConstruct { @Override public Object construct(final Node node) { LOG.debug("start resolving expression: {}", node); if (!(node instanceof ScalarNode)) { throw new ConfigurationException("Non-scalar use of tag !var tag is illegal: " + node); } ScalarNode scalarNode = (ScalarNode) node; String exp = "\"" + scalarNode.getValue() + "\""; Expression expression; try { expression = expressions.create(exp); } catch (ParseException e) { LOG.error("expression {} is not valid", exp, e); throw new ConfigurationException("expression is not valid", e); } String resolved; try { resolved = expression.process(expressionVars); } catch (EvaluationException e) { LOG.error("expression {} could not be evaluated", exp, e); throw new ConfigurationException("expression could not be evaluated", e); } LOG.debug("expression {} resolved to: {}", exp, resolved); return resolved; } } class PluginRefConstruct extends AbstractConstruct { @Override public Instance construct(final Node node) { LOG.debug("start resolving instance dependency definition: {}", node); if (!(node instanceof ScalarNode)) { throw new ConfigurationException("Non-scalar use of tag !ref tag is illegal: " + node); } ScalarNode scalarNode = (ScalarNode) node; String instanceName = scalarNode.getValue(); Instance instance = getInstance(instanceName); LOG.debug("instance dependency definition has been successfully resolved: {}", instance); return instance; } } class PluginRefsConstruct extends AbstractConstruct { @Override public List<Instance> construct(final Node node) { LOG.debug("start resolving instance dependencies definition: {}", node); if (!(node instanceof SequenceNode)) { throw new ConfigurationException("Non-sequence use of tag !refs tag is illegal: " + node); } SequenceNode sequenceNode = (SequenceNode) node; List<Node> values = sequenceNode.getValue(); List<String> dependencyNames = values.stream() .map(n -> ((ScalarNode) n).getValue()) .map(String::trim) .collect(toList()); List<Instance> instances = new ArrayList<>(); for (String dependencyName : dependencyNames) { instances.add(getInstance(dependencyName)); } LOG.debug("instance dependencies definition has been successfully resolved: {}", instances); return instances; } } private Definition getExtension() { if (!context.hasDefinition(extensionName)) { LOG.error("could not find extension definition for {}", extensionName); throw new ConfigurationException("could not find extension definition for " + extensionName); } return context.getDefinition(extensionName); } private Instance getInstance(final String instanceName) { if (!context.hasInstance(instanceName, scope)) { Instance instance = context.getInstance(instanceName, scope); if (instance == null) { LOG.error("could not find definition for {}, define this extension before use", instanceName); throw new ConfigurationException("could not find definition for " + instanceName); } return instance; } return context.getInstance(instanceName, scope); } @Getter private static final class InstanceBinding { private final String name; private final Instance instance; private InstanceBinding(final String name, final Instance instance) { this.name = name; this.instance = instance; } } @Getter private static final class InstancesBinding { private final String name; private final List<Instance> instances; private InstancesBinding(final String name, final List<Instance> instances) { this.name = name; this.instances = instances; } } } <file_sep>/anycollect-core-api/src/main/java/io/github/anycollect/core/api/internal/ConsistentQueryMatcherResolver.java package io.github.anycollect.core.api.internal; import javax.annotation.Nonnull; public final class ConsistentQueryMatcherResolver implements QueryMatcherResolver { private final QueryMatcher matcher; public ConsistentQueryMatcherResolver(@Nonnull final QueryMatcher matcher) { this.matcher = matcher; } @Nonnull @Override public QueryMatcher current() { return matcher; } } <file_sep>/anycollect-core/src/test/java/io/github/anycollect/core/impl/scheduler/SchedulerImplTest.java package io.github.anycollect.core.impl.scheduler; import io.github.anycollect.core.api.internal.Cancellation; import org.junit.jupiter.api.*; import org.mockito.stubbing.Answer; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.*; @DisplayName("scheduler") class SchedulerImplTest { private ScheduledThreadPoolExecutor executorService = mock(ScheduledThreadPoolExecutor.class); private SchedulerImpl scheduler; @BeforeEach void createScheduler() { scheduler = new SchedulerImpl(executorService); } @Nested @DisplayName("when new") class WhenNew { @Test @DisplayName("is not shutdown") void isNotShutdown() { assertThat(scheduler.isShutdown()).isFalse(); } @Nested @DisplayName("when schedule job") class WhenScheduleJob { private Cancellation cancellation; private Runnable job = () -> { }; private ScheduledFuture future; @BeforeEach @SuppressWarnings("unchecked") void schedule() { when(executorService.scheduleAtFixedRate(job, 0L, 10L, TimeUnit.MILLISECONDS)).thenAnswer((Answer<ScheduledFuture<?>>) invocation -> { future = mock(ScheduledFuture.class); return future; }); cancellation = scheduler.scheduleAtFixedRate(job, 0L, 10L, TimeUnit.MILLISECONDS); } @Test @DisplayName("must submit job to executor") void mustSubmitJobToExecutor() { verify(executorService, times(1)).scheduleAtFixedRate(job, 0, 10, TimeUnit.MILLISECONDS); } @Nested @DisplayName("when cancel") class WhenCancel { @BeforeEach void cancel() { cancellation.cancel(); } @Test @DisplayName("must cancel future") void mustCancelFuture() { verify(future, times(1)).cancel(true); } } } @Nested @DisplayName("when shutdown") class WhenShutdown { @BeforeEach void shutdown() { when(executorService.isShutdown()).thenReturn(true); scheduler.shutdown(); } @Test @DisplayName("executor is shutdown") void executorIsShutdown() { verify(executorService, times(1)).shutdown(); } @Test @DisplayName("is shutdown") void isShutdown() { assertThat(scheduler.isShutdown()).isTrue(); } @Test @DisplayName("must not accept new jobs") void mustNotAcceptNewJobs() { Assertions.assertThrows(IllegalStateException.class, () -> scheduler.scheduleAtFixedRate(() -> { }, 10, TimeUnit.SECONDS)); } } } }<file_sep>/anycollect-core/src/main/java/io/github/anycollect/core/impl/pull/separate/ConcurrencyRule.java package io.github.anycollect.core.impl.pull.separate; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import io.github.anycollect.core.api.target.Target; import javax.annotation.Nonnull; @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", defaultImpl = RegExpConcurrencyRule.class) @JsonSubTypes({ @JsonSubTypes.Type(value = RegExpConcurrencyRule.class, name = "regexp")}) public interface ConcurrencyRule { int getPoolSize(@Nonnull Target target, int fallback); } <file_sep>/anycollect-core/src/main/java/io/github/anycollect/core/impl/router/RouterNode.java package io.github.anycollect.core.impl.router; import javax.annotation.Nonnull; public interface RouterNode { @Nonnull String getAddress(); } <file_sep>/extensions/common/anycollect-common-expression/src/main/java/io/github/anycollect/extensions/common/expression/parser/Parser.java package io.github.anycollect.extensions.common.expression.parser; import io.github.anycollect.extensions.common.expression.ParseException; import io.github.anycollect.extensions.common.expression.ast.*; import java.util.Deque; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; public final class Parser { private final Tokenizer tokenizer; private final Map<String, FilterStrategy> filters; private Deque<Token> tokens; private Token lookahead; public Parser(final Tokenizer tokenizer, final Map<String, FilterStrategy> filters) { this.tokenizer = tokenizer; this.filters = new HashMap<>(filters); } public ValueExpressionNode parse(final String input) throws ParseException { tokens = new LinkedList<>(tokenizer.tokenize(input)); lookahead = tokens.getFirst(); ValueExpressionNode ret = expression(); if (lookahead.getType() != TokenType.EPSILON) { throw new ParseException("unexpected symbol found " + lookahead.getSequence()); } tokens.clear(); lookahead = null; return ret; } private ValueExpressionNode expression() throws ParseException { // expression -> chain pipe_op ValueExpressionNode chain = chain(); return pipeOp(new PipeExpressionNode(chain)); } private ValueExpressionNode chain() throws ParseException { if (lookahead.getType() == TokenType.OPEN_BRACKET) { // part -> OPEN_BRACKET expression CLOSE_BRACKET nextToken(); ValueExpressionNode node = expression(); if (lookahead.getType() != TokenType.CLOSE_BRACKET) { throw new UnexpectedTokenParseException(lookahead, TokenType.CLOSE_BRACKET); } nextToken(); return node; } else { return value(); } } private PipeExpressionNode pipeOp(final PipeExpressionNode pipe) throws ParseException { if (lookahead.getType() == TokenType.PIPE) { // pipe_op -> PIPE filter pipe_op nextToken(); FilterExpressionNode filter = filter(); pipe.add(filter); pipeOp(pipe); return pipe; } // pipe_op -> EPSILON return pipe; } private ValueExpressionNode value() throws ParseException { if (lookahead.getType() == TokenType.DOUBLE_QUOTES) { // value -> DOUBLE_QUOTES value_op DOUBLE_QUOTES ComplexStringExpressionNode string = new ComplexStringExpressionNode(); nextToken(); valueOp(string); if (lookahead.getType() != TokenType.DOUBLE_QUOTES) { throw new IllegalArgumentException(lookahead.getSequence()); } nextToken(); return string; } else if (lookahead.getType() == TokenType.CONSTANT) { // value -> CONSTANT ConstantExpressionNode constant = new ConstantExpressionNode(lookahead.getSequence()); nextToken(); return constant; } else if (lookahead.getType() == TokenType.VARIABLE) { // value -> VARIABLE VariableExpressionNode variable = new VariableExpressionNode(lookahead.getSequence()); nextToken(); return variable; } else if (lookahead.getType() == TokenType.EPSILON) { throw new ParseException("unexpected end of expression"); } else { throw new UnexpectedTokenParseException(lookahead, TokenType.DOUBLE_QUOTES, TokenType.CONSTANT, TokenType.VARIABLE); } } private ComplexStringExpressionNode valueOp(final ComplexStringExpressionNode string) { if (lookahead.getType() == TokenType.CONSTANT) { // value_op -> CONSTANT value_op ConstantExpressionNode constant = new ConstantExpressionNode(lookahead.getSequence()); string.add(constant); nextToken(); valueOp(string); return string; } else if (lookahead.getType() == TokenType.VARIABLE) { // value_op -> VARIABLE value_op VariableExpressionNode variable = new VariableExpressionNode(lookahead.getSequence()); string.add(variable); nextToken(); valueOp(string); return string; } else { // value_op -> EPSILON return string; } } private FilterExpressionNode filter() throws ParseException { if (lookahead.getType() == TokenType.FILTER) { String filterName = lookahead.getSequence(); FilterStrategy strategy = filters.get(filterName); nextToken(); // filter -> FILTER OPEN_BRACKET arguments CLOSE_BRACKET if (lookahead.getType() == TokenType.OPEN_BRACKET) { nextToken(); ArgumentsExpressionNode arguments = arguments(); if (lookahead.getType() == TokenType.CLOSE_BRACKET) { nextToken(); return new FilterExpressionNode(filterName, arguments, strategy); } else { throw new UnexpectedTokenParseException(lookahead, TokenType.CLOSE_BRACKET); } } else { // filter -> FILTER return new FilterExpressionNode(filterName, strategy); } } else { throw new UnexpectedTokenParseException(lookahead, TokenType.FILTER); } } private ArgumentsExpressionNode arguments() throws ParseException { // arguments -> argument arguments_op ArgumentExpressionNode argument = argument(); return argumentsOp(new ArgumentsExpressionNode(argument)); } private ArgumentsExpressionNode argumentsOp(final ArgumentsExpressionNode arguments) throws ParseException { if (lookahead.getType() == TokenType.COLON) { // arguments_op -> COLON arguments_op nextToken(); ArgumentExpressionNode argument = argument(); arguments.add(argument); argumentsOp(arguments); return arguments; } // arguments_op -> EPSILON return arguments; } private ArgumentExpressionNode argument() throws ParseException { // argument -> expression return new ArgumentExpressionNode(expression()); } private void nextToken() { tokens.pop(); if (tokens.isEmpty()) { lookahead = Token.of(TokenType.EPSILON, ""); } else { lookahead = tokens.getFirst(); } } } <file_sep>/anycollect-metric/src/main/java/io/github/anycollect/metric/LeBucket.java package io.github.anycollect.metric; import org.apiguardian.api.API; /** * Less than or Equal to [max] bucket of events */ @API(since = "0.1.0", status = API.Status.EXPERIMENTAL) public final class LeBucket implements Stat, Comparable<LeBucket> { private static final LeBucket INF = new LeBucket(Double.POSITIVE_INFINITY); private final double max; public static LeBucket inf() { return INF; } public static LeBucket of(final double max) { if (max == Double.POSITIVE_INFINITY) { return inf(); } return new LeBucket(max); } private LeBucket(final double max) { this.max = max; } @Override public StatType getType() { return StatType.LE_BUCKET; } @Override public String getTagValue() { if ((int) max == max) { return "le_" + (int) max; } return "le_" + max; } public double getMax() { return max; } @Override public String toString() { return getTagValue(); } @Override public int compareTo(final LeBucket that) { return Double.compare(max, that.max); } } <file_sep>/extensions/readers/anycollect-jmx-reader/src/main/java/io/github/anycollect/readers/jmx/server/PooledJavaApp.java package io.github.anycollect.readers.jmx.server; import io.github.anycollect.core.api.target.AbstractTarget; import io.github.anycollect.core.exceptions.ConnectionException; import io.github.anycollect.core.exceptions.QueryException; import io.github.anycollect.meter.api.FunctionCounter; import io.github.anycollect.meter.api.Gauge; import io.github.anycollect.meter.api.MeterRegistry; import io.github.anycollect.metric.Tags; import io.github.anycollect.readers.jmx.query.operations.QueryOperation; import io.github.anycollect.readers.jmx.server.pool.JmxConnectionPool; import lombok.EqualsAndHashCode; import javax.annotation.Nonnull; import java.util.Objects; @EqualsAndHashCode(callSuper = true) public final class PooledJavaApp extends AbstractTarget implements JavaApp { private final JmxConnectionPool pool; public PooledJavaApp(@Nonnull final String id, @Nonnull final JmxConnectionPool pool) { super(id, Tags.empty(), Tags.empty()); Objects.requireNonNull(pool, "jmx connection pool must not be null"); this.pool = pool; } public PooledJavaApp(@Nonnull final String id, @Nonnull final Tags tags, @Nonnull final Tags meta, @Nonnull final JmxConnectionPool pool, @Nonnull final MeterRegistry registry) { super(id, tags, meta); Objects.requireNonNull(pool, "jmx connection pool must not be null"); this.pool = pool; Gauge.make("jmx/connection.pool/live.connections", pool, JmxConnectionPool::getNumActive) .concatTags(tags) .tag("state", "active") .meta(this.getClass()) .register(registry); Gauge.make("jmx/connection.pool/live.connections", pool, JmxConnectionPool::getNumIdle) .concatTags(tags) .tag("state", "idle") .meta(this.getClass()) .register(registry); FunctionCounter.make("jmx/connection.pool/invalidated.connections", pool, JmxConnectionPool::getTotalInvalidated) .concatTags(tags) .meta(this.getClass()) .register(registry); } @Override public <T> T operate(@Nonnull final QueryOperation<T> operation) throws QueryException, ConnectionException { JmxConnection jmxConnection = null; try { jmxConnection = pool.borrowConnection(); try { return operation.operate(jmxConnection); } catch (ConnectionException e) { pool.invalidateConnection(jmxConnection); throw e; } } finally { if (jmxConnection != null) { pool.returnConnection(jmxConnection); } } } } <file_sep>/anycollect-extension-system/src/main/java/io/github/anycollect/extensions/scope/SimpleScope.java package io.github.anycollect.extensions.scope; import javax.annotation.Nonnull; import javax.annotation.Nullable; public final class SimpleScope extends AbstractScope { private final String id; public SimpleScope(@Nonnull final String id) { super(null); this.id = id; } public SimpleScope(@Nullable final Scope parent, @Nonnull final String id) { super(parent); this.id = id; } @Nonnull @Override public String getId() { return id; } } <file_sep>/anycollect-core/src/main/java/io/github/anycollect/core/impl/filters/DenyAllFilter.java package io.github.anycollect.core.impl.filters; import com.fasterxml.jackson.annotation.JsonTypeName; import io.github.anycollect.core.api.filter.Filter; import io.github.anycollect.core.api.filter.FilterReply; import io.github.anycollect.metric.Metric; import javax.annotation.Nonnull; @JsonTypeName("deny") public final class DenyAllFilter implements Filter { @Override public FilterReply accept(@Nonnull final Metric metric) { return FilterReply.DENY; } } <file_sep>/anycollect-core/src/main/java/io/github/anycollect/core/impl/pull/PullManagerConfig.java package io.github.anycollect.core.impl.pull; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; import io.github.anycollect.core.api.internal.Clock; import io.github.anycollect.core.impl.pull.separate.ConcurrencyRule; import io.github.anycollect.core.impl.pull.separate.ConcurrencyRules; import lombok.Getter; import lombok.ToString; import javax.annotation.Nonnull; import java.util.List; @Getter @ToString @JsonDeserialize(builder = PullManagerConfig.Builder.class) public final class PullManagerConfig { private static final int DEFAULT_UPDATE_PERIOD_IN_SECONDS = 60; private static final int DEFAULT_PULL_PERIOD_IN_SECONDS = 30; private static final int DEFAULT_HEALTH_CHECK_PERIOD_IN_SECONDS = 10; private static final int DEFAULT_POOL_SIZE = 1; private final int updatePeriodInSeconds; private final int defaultPullPeriodInSeconds; private final int defaultPoolSize; private final ConcurrencyRule concurrencyRule; private final int healthCheckPeriodInSeconds; private final Clock clock; public static Builder builder() { return new Builder(); } private PullManagerConfig(final Builder builder) { this.updatePeriodInSeconds = builder.updatePeriodInSeconds; this.defaultPullPeriodInSeconds = builder.defaultPullPeriodInSeconds; this.defaultPoolSize = builder.defaultPoolSize; this.concurrencyRule = builder.concurrencyRulesBuilder.build(); this.healthCheckPeriodInSeconds = builder.healthCheckPeriodInSeconds; this.clock = builder.clock; } @JsonPOJOBuilder public static final class Builder { private int updatePeriodInSeconds = DEFAULT_UPDATE_PERIOD_IN_SECONDS; private int healthCheckPeriodInSeconds = DEFAULT_HEALTH_CHECK_PERIOD_IN_SECONDS; private int defaultPullPeriodInSeconds = DEFAULT_PULL_PERIOD_IN_SECONDS; private int defaultPoolSize = DEFAULT_POOL_SIZE; private ConcurrencyRules.Builder concurrencyRulesBuilder = ConcurrencyRules.builder(); private Clock clock = Clock.getDefault(); @JsonProperty("updatePeriod") public Builder withUpdatePeriod(final int seconds) { this.updatePeriodInSeconds = seconds; return this; } @JsonProperty("pullPeriod") public Builder withDefaultPullPeriod(final int seconds) { this.defaultPullPeriodInSeconds = seconds; return this; } @JsonProperty("defaultPoolSize") public Builder withDefaultPoolSize(final int numberOfThread) { this.defaultPoolSize = numberOfThread; return this; } public Builder withRule(@Nonnull final ConcurrencyRule rule) { this.concurrencyRulesBuilder.withRule(rule); return this; } @JsonProperty("rules") public Builder withRules(@Nonnull final List<ConcurrencyRule> rules) { this.concurrencyRulesBuilder.withRules(rules); return this; } @JsonProperty("healthCheckPeriod") public Builder withHealthCheckPeriod(final int seconds) { this.healthCheckPeriodInSeconds = seconds; return this; } public PullManagerConfig build() { return new PullManagerConfig(this); } } } <file_sep>/extensions/common/anycollect-common-expression/src/test/java/io/github/anycollect/extensions/common/expression/ast/VariableExpressionNodeTest.java package io.github.anycollect.extensions.common.expression.ast; import io.github.anycollect.extensions.common.expression.EvaluationException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; class VariableExpressionNodeTest { @Test void gettingUnresolvedVariableMustFail() { VariableExpressionNode node = new VariableExpressionNode("${arg}"); assertThat(node.isResolved()).isFalse(); EvaluationException ex = Assertions.assertThrows(EvaluationException.class, node::getValue); assertThat(ex).hasMessageContaining("arg"); } @Test void variablePassedToConstructorMustHaveCorrectSyntax() { Assertions.assertThrows(IllegalArgumentException.class, () -> new VariableExpressionNode("arg")); } }<file_sep>/README.md [![Build Status](https://travis-ci.org/anycollect/anycollect.svg?branch=master)](https://travis-ci.org/anycollect/anycollect) [![codecov](https://codecov.io/gh/anycollect/anycollect/branch/master/graph/badge.svg)](https://codecov.io/gh/anycollect/anycollect) # anycollect <file_sep>/extensions/readers/anycollect-system-reader/src/main/java/io/github/anycollect/readers/process/discovery/pidfile/PidFileProcessDiscoveryConfig.java package io.github.anycollect.readers.process.discovery.pidfile; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import org.immutables.value.Value; import java.util.Collections; import java.util.List; @Value.Immutable @JsonSerialize(as = ImmutablePidFileProcessDiscoveryConfig.class) @JsonDeserialize(as = ImmutablePidFileProcessDiscoveryConfig.class) public interface PidFileProcessDiscoveryConfig { @Value.Default @JsonProperty("watch") default List<PidFileTargetDefinition> watch() { return Collections.emptyList(); } } <file_sep>/anycollect-extension-system/src/main/java/io/github/anycollect/extensions/dependencies/AbstractDependencyDefinition.java package io.github.anycollect.extensions.dependencies; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; @Getter @ToString @EqualsAndHashCode public abstract class AbstractDependencyDefinition { private final String name; private final Class<?> parameterType; private final boolean optional; private final int position; private final boolean single; AbstractDependencyDefinition(final String name, final Class<?> parameterType, final boolean optional, final int position, final boolean single) { this.name = name; this.parameterType = parameterType; this.optional = optional; this.position = position; this.single = single; } } <file_sep>/anycollect-parent/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>anycollect</artifactId> <groupId>io.github.anycollect</groupId> <version>0.0.1-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>anycollect-parent</artifactId> <packaging>pom</packaging> <properties> <docker.images.build.skip>true</docker.images.build.skip> <includeTests/> <excludeTests>integration</excludeTests> <maven.compiler.target>1.8</maven.compiler.target> <maven.compiler.source>1.8</maven.compiler.source> <!-- INTERNAL MONITORING --> <micrometer.version>1.1.2</micrometer.version> <codahale-metrics.version>4.0.5</codahale-metrics.version> <!-- YAML, CONFIGURATION --> <jackson.version>2.9.9</jackson.version> <snakeyaml.version>1.23</snakeyaml.version> <!-- DISCOVERY --> <consul-client.version>1.3.2</consul-client.version> <!-- NETWORK --> <netty.version>4.1.33.Final</netty.version> <!-- EXTENSIONS --> <oshi.version>3.13.0</oshi.version> <plugin-api.version>5.4.0</plugin-api.version> <!-- CODE GENERATION --> <lombok.version>1.18.4</lombok.version> <immutables.version>2.7.4</immutables.version> <!-- LOGGING --> <slf4j.version>1.7.25</slf4j.version> <logback.version>1.2.3</logback.version> <!-- UTILS --> <commons-pool2.version>2.6.0</commons-pool2.version> <guava.version>27.0-jre</guava.version> <commons-lang.version>3.8.1</commons-lang.version> <!-- CLI --> <commons-cli.version>1.4</commons-cli.version> <picocli.version>3.9.5</picocli.version> <!-- CODE ANALYSIS--> <findbugs-annotations.version>3.0.1</findbugs-annotations.version> <apiguardian-api.version>1.1.0</apiguardian-api.version> <!-- TESTING --> <junit.version>5.3.1</junit.version> <assertj.version>3.11.1</assertj.version> <mockito.version>2.23.4</mockito.version> <awaitility.version>3.1.5</awaitility.version> <commons-io.version>2.6</commons-io.version> <jmh.version>1.21</jmh.version> <testcontainers.version>1.11.3</testcontainers.version> <!-- PLUGINS --> <compiler.version>3.6.1</compiler.version> <assembly.plugin.version>3.1.1</assembly.plugin.version> <surefire.plugin.version>2.22.2</surefire.plugin.version> <checkstyle.plugin.version>3.0.0</checkstyle.plugin.version> <pmd.plugin.version>3.11.0</pmd.plugin.version> <pmd.version>6.9.0</pmd.version> <jacoco.plugin.version>0.8.2</jacoco.plugin.version> <findbugs.plugin.version>3.0.4</findbugs.plugin.version> </properties> <profiles> <profile> <id>allTests</id> <properties> <includeTests>integration</includeTests> <excludeTests/> </properties> </profile> </profiles> <dependencyManagement> <dependencies> <!-- DATA STRUCTURES--> <dependency> <groupId>org.pcollections</groupId> <artifactId>pcollections</artifactId> <version>${pcollections.version}</version> </dependency> <!-- INTERNAL MONITORING --> <dependency> <groupId>io.micrometer</groupId> <artifactId>micrometer-core</artifactId> <version>${micrometer.version}</version> </dependency> <dependency> <groupId>io.dropwizard.metrics</groupId> <artifactId>metrics-core</artifactId> <version>${codahale-metrics.version}</version> </dependency> <!-- YAML, CONFIGURATION --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-yaml</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-guava</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>org.yaml</groupId> <artifactId>snakeyaml</artifactId> <version>${snakeyaml.version}</version> </dependency> <!-- DISCOVERY --> <dependency> <groupId>com.orbitz.consul</groupId> <artifactId>consul-client</artifactId> <version>${consul-client.version}</version> </dependency> <!-- NETWORK --> <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>${netty.version}</version> </dependency> <!-- EXTENSIONS --> <dependency> <groupId>com.github.oshi</groupId> <artifactId>oshi-core</artifactId> <version>${oshi.version}</version> </dependency> <dependency> <groupId>org.collectd</groupId> <artifactId>plugin-api</artifactId> <version>${plugin-api.version}</version> </dependency> <!-- CODE GENERATION --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>${lombok.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.immutables</groupId> <artifactId>value</artifactId> <version>${immutables.version}</version> <scope>provided</scope> </dependency> <!-- UTILS --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> <version>${commons-pool2.version}</version> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>${guava.version}</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>${commons-io.version}</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>${commons-lang.version}</version> </dependency> <!-- CLI --> <dependency> <groupId>commons-cli</groupId> <artifactId>commons-cli</artifactId> <version>${commons-cli.version}</version> </dependency> <dependency> <groupId>info.picocli</groupId> <artifactId>picocli</artifactId> <version>${picocli.version}</version> </dependency> <!-- LOGGING --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>${logback.version}</version> <scope>test</scope> </dependency> <!-- CODE ANALYSIS --> <dependency> <groupId>org.apiguardian</groupId> <artifactId>apiguardian-api</artifactId> <version>${apiguardian-api.version}</version> <scope>compile</scope> </dependency> <dependency> <groupId>com.google.code.findbugs</groupId> <artifactId>annotations</artifactId> <version>${findbugs-annotations.version}</version> <scope>compile</scope> </dependency> <!-- TESTING --> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-params</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.assertj</groupId> <artifactId>assertj-core</artifactId> <version>${assertj.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>${mockito.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.awaitility</groupId> <artifactId>awaitility</artifactId> <version>${awaitility.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.testcontainers</groupId> <artifactId>testcontainers</artifactId> <version>${testcontainers.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.openjdk.jmh</groupId> <artifactId>jmh-core</artifactId> <version>${jmh.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.openjdk.jmh</groupId> <artifactId>jmh-generator-annprocess</artifactId> <version>${jmh.version}</version> <scope>test</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <!-- CODE GENERATION --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <scope>provided</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.immutables</groupId> <artifactId>value</artifactId> <scope>provided</scope> <optional>true</optional> </dependency> <!-- CODE ANALYSIS --> <dependency> <groupId>org.apiguardian</groupId> <artifactId>apiguardian-api</artifactId> <scope>compile</scope> </dependency> <dependency> <groupId>com.google.code.findbugs</groupId> <artifactId>annotations</artifactId> <scope>compile</scope> </dependency> <!-- TESTING --> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-params</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.assertj</groupId> <artifactId>assertj-core</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.awaitility</groupId> <artifactId>awaitility</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.testcontainers</groupId> <artifactId>testcontainers</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-pmd-plugin</artifactId> <version>${pmd.plugin.version}</version> <dependencies> <dependency> <groupId>net.sourceforge.pmd</groupId> <artifactId>pmd-core</artifactId> <version>${pmd.version}</version> </dependency> <dependency> <groupId>net.sourceforge.pmd</groupId> <artifactId>pmd-java</artifactId> <version>${pmd.version}</version> </dependency> </dependencies> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-assembly-plugin</artifactId> <version>${assembly.plugin.version}</version> </plugin> </plugins> </pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>${compiler.version}</version> <configuration> <source>${maven.compiler.source}</source> <target>${maven.compiler.target}</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>${surefire.plugin.version}</version> <configuration> <groups>${includeTests}</groups> <excludedGroups>${excludeTests}</excludedGroups> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-checkstyle-plugin</artifactId> <version>${checkstyle.plugin.version}</version> <dependencies> <dependency> <groupId>io.github.anycollect</groupId> <artifactId>anycollect-build-tools</artifactId> <version>${project.version}</version> </dependency> </dependencies> <executions> <!--<execution>--> <!--<id>checkstyle-validate</id>--> <!--<phase>validate</phase>--> <!--<configuration>--> <!--<configLocation>anycollect/checkstyle.xml</configLocation>--> <!--<encoding>${encoding}</encoding>--> <!--<consoleOutput>true</consoleOutput>--> <!--<failsOnError>true</failsOnError>--> <!--</configuration>--> <!--<goals>--> <!--<goal>check</goal>--> <!--</goals>--> <!--</execution>--> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-pmd-plugin</artifactId> <version>${pmd.plugin.version}</version> <dependencies> <dependency> <groupId>io.github.anycollect</groupId> <artifactId>anycollect-build-tools</artifactId> <version>${project.version}</version> </dependency> </dependencies> <configuration> <printFailingErrors>true</printFailingErrors> <failOnViolation>true</failOnViolation> <linkXRef>false</linkXRef> <rulesets> <ruleset>anycollect/pmd-ruleset.xml</ruleset> </rulesets> </configuration> <!--<executions>--> <!--<execution>--> <!--<id>pmd-validate</id>--> <!--<phase>test</phase>--> <!--<goals>--> <!--<goal>check</goal>--> <!--</goals>--> <!--</execution>--> <!--</executions>--> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>findbugs-maven-plugin</artifactId> <version>${findbugs.plugin.version}</version> </plugin> <plugin> <groupId>org.jacoco</groupId> <artifactId>jacoco-maven-plugin</artifactId> <version>${jacoco.plugin.version}</version> <executions> <execution> <goals> <goal>prepare-agent</goal> </goals> </execution> <execution> <id>jacoco-report</id> <phase>prepare-package</phase> <goals> <goal>report</goal> </goals> </execution> <!--<execution>--> <!--<id>jacoco-check</id>--> <!--<goals>--> <!--<goal>check</goal>--> <!--</goals>--> <!--<configuration>--> <!--<rules>--> <!--<rule>--> <!--<element>CLASS</element>--> <!--<excludes>--> <!--<exclude>*Test</exclude>--> <!--</excludes>--> <!--<limits>--> <!--<limit>--> <!--<counter>LINE</counter>--> <!--<value>COVEREDRATIO</value>--> <!--<minimum>75%</minimum>--> <!--</limit>--> <!--<limit >--> <!--<counter>BRANCH</counter>--> <!--<value>COVEREDRATIO</value>--> <!--<minimum>70%</minimum>--> <!--</limit>--> <!--</limits>--> <!--</rule>--> <!--</rules>--> <!--</configuration>--> <!--</execution>--> </executions> </plugin> </plugins> </build> </project><file_sep>/extensions/common/anycollect-common-expression/src/main/java/io/github/anycollect/extensions/common/expression/std/StdExpression.java package io.github.anycollect.extensions.common.expression.std; import io.github.anycollect.extensions.common.expression.Args; import io.github.anycollect.extensions.common.expression.EvaluationException; import io.github.anycollect.extensions.common.expression.Expression; import io.github.anycollect.extensions.common.expression.ast.ValueExpressionNode; import io.github.anycollect.extensions.common.expression.ast.visitor.ExpressionNodeVisitor; import io.github.anycollect.extensions.common.expression.ast.visitor.SetVariables; public final class StdExpression implements Expression { private final ValueExpressionNode root; public StdExpression(final ValueExpressionNode root) { this.root = root; } @Override public String process(final Args args) throws EvaluationException { root.accept(new SetVariables(args)); String value = root.getValue(); root.accept(ExpressionNodeVisitor.reset()); return value; } } <file_sep>/anycollect-metric/src/test/java/io/github/anycollect/metric/RemoveTagsTest.java package io.github.anycollect.metric; import org.assertj.core.util.Sets; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import java.util.Collections; import static org.assertj.core.api.Assertions.assertThat; class RemoveTagsTest { @Nested class ReturnsEmptyTags { @Test void whenGivenEmptyBase() { assertThat(RemoveTags.of(Tags.empty(), Collections.emptySet())).isSameAs(Tags.empty()); } @Test void whenRemoveSingleTag() { assertThat(RemoveTags.of(Tags.of("k", "v"), Collections.singleton(Key.of("k")))).isSameAs(Tags.empty()); } @Test void whenRemoveAllMultiTags() { assertThat(RemoveTags.of( Tags.builder() .tag("k1", "v1") .tag("k2", "v2") .build(), Sets.newLinkedHashSet(Key.of("k1"), Key.of("k2"))) ).isSameAs(Tags.empty()); } } }<file_sep>/anycollect-benchmarks/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>anycollect-parent</artifactId> <groupId>io.github.anycollect</groupId> <version>0.0.1-SNAPSHOT</version> <relativePath>../anycollect-parent/pom.xml</relativePath> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>anycollect-benchmarks</artifactId> <dependencies> <dependency> <groupId>io.github.anycollect</groupId> <artifactId>anycollect-core</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>org.openjdk.jmh</groupId> <artifactId>jmh-core</artifactId> <scope>compile</scope> </dependency> <dependency> <groupId>org.openjdk.jmh</groupId> <artifactId>jmh-generator-annprocess</artifactId> <scope>compile</scope> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <scope>compile</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <version>3.2.1</version> <configuration> <dependencyReducedPomLocation>${project.build.directory}/dependency-reduced-pom.xml</dependencyReducedPomLocation> </configuration> <executions> <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> <configuration> <finalName>benchmarks</finalName> <transformers> <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"> <mainClass>org.openjdk.jmh.Main</mainClass> </transformer> </transformers> </configuration> </execution> </executions> </plugin> </plugins> </build> </project><file_sep>/anycollect-core/src/main/java/io/github/anycollect/core/impl/pull/separate/SeparatePullScheduler.java package io.github.anycollect.core.impl.pull.separate; import com.google.common.annotations.VisibleForTesting; import io.github.anycollect.core.api.dispatcher.Dispatcher; import io.github.anycollect.core.api.internal.Cancellation; import io.github.anycollect.core.api.internal.Clock; import io.github.anycollect.core.api.query.Query; import io.github.anycollect.core.api.target.Target; import io.github.anycollect.core.impl.pull.PullJob; import io.github.anycollect.core.impl.pull.PullScheduler; import io.github.anycollect.core.impl.pull.availability.CheckingTarget; import io.github.anycollect.core.impl.scheduler.Scheduler; import io.github.anycollect.meter.api.MeterRegistry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nonnull; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; public final class SeparatePullScheduler implements PullScheduler { private static final Logger LOG = LoggerFactory.getLogger(SeparatePullScheduler.class); private final ConcurrentHashMap<Target, Scheduler> activeSchedulers = new ConcurrentHashMap<>(); private final SchedulerFactory factory; private final MeterRegistry registry; private final Clock clock; private final String name; private volatile boolean stopped = false; @VisibleForTesting SeparatePullScheduler(@Nonnull final SchedulerFactory factory, @Nonnull final Clock clock) { this.factory = factory; this.registry = MeterRegistry.noop(); this.clock = clock; this.name = "scheduler"; } public SeparatePullScheduler(@Nonnull final SchedulerFactory factory, @Nonnull final MeterRegistry registry, @Nonnull final String name) { this.factory = factory; this.registry = registry; this.name = name; this.clock = Clock.getDefault(); } @Nonnull @Override public <T extends Target, Q extends Query<T>> Cancellation schedulePull( @Nonnull final CheckingTarget<T> target, @Nonnull final Q query, @Nonnull final Dispatcher dispatcher, final int periodInSeconds) { if (stopped) { return Cancellation.NOOP; } PullJob<T, Q> job = new PullJob<>(target, query, name, dispatcher, registry, clock); Scheduler scheduler = activeSchedulers.computeIfAbsent(target.get(), aTarget -> factory.create(aTarget, name)); long initialDelay = ThreadLocalRandom.current().nextLong(periodInSeconds); return scheduler.scheduleAtFixedRate(job, initialDelay, periodInSeconds, TimeUnit.SECONDS, false); } @Override public void release(@Nonnull final Target target) { if (stopped) { return; } Scheduler scheduler = activeSchedulers.remove(target); if (scheduler != null) { LOG.info("Stopping scheduler for {}", target.getId()); // all jobs associated with target will be terminated scheduler.shutdown(); } } @Override public void shutdown() { if (stopped) { return; } stopped = true; LOG.info("Stopping separate pull scheduler {}", name); for (Map.Entry<Target, Scheduler> entry : activeSchedulers.entrySet()) { Target target = entry.getKey(); Scheduler scheduler = entry.getValue(); LOG.info("Stopping scheduler for {}", target.getId()); scheduler.shutdown(); } } } <file_sep>/extensions/readers/anycollect-system-reader/src/main/java/io/github/anycollect/readers/process/ProcessQuery.java package io.github.anycollect.readers.process; import io.github.anycollect.core.api.internal.Clock; import io.github.anycollect.core.api.job.Job; import io.github.anycollect.core.api.job.TaggingJob; import io.github.anycollect.core.api.query.AbstractQuery; import io.github.anycollect.metric.Key; import io.github.anycollect.metric.Metric; import io.github.anycollect.metric.Sample; import oshi.hardware.GlobalMemory; import oshi.software.os.OSProcess; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; public final class ProcessQuery extends AbstractQuery<Process> { private final String prefix; private final String cpuUsageKey; private final String memUsageKey; private final Clock clock; private final long totalMemory; public ProcessQuery(@Nonnull final String prefix, @Nonnull final String cpuUsageKey, @Nonnull final String memUsageKey, @Nonnull final GlobalMemory memory) { super("processes"); this.prefix = prefix; this.cpuUsageKey = cpuUsageKey; this.memUsageKey = memUsageKey; this.totalMemory = memory.getTotal(); this.clock = Clock.getDefault(); } public List<Sample> execute(@Nullable final OSProcess previous, @Nonnull final OSProcess current) { List<Sample> samples = new ArrayList<>(); long rss = current.getResidentSetSize(); double memoryUsagePercent = 100.0 * rss / totalMemory; long timestamp = clock.wallTime(); samples.add(Metric.builder() .key(Key.of(memUsageKey).withPrefix(prefix)) .gauge("percents") .sample(memoryUsagePercent, timestamp)); samples.add(Metric.builder() .key(Key.of(memUsageKey).withPrefix(prefix)) .gauge("bytes") .sample(rss, timestamp)); if (previous == null) { return samples; } long userTimeDelta = current.getUserTime() - previous.getUserTime(); long kernelTimeDelta = current.getKernelTime() - previous.getKernelTime(); long upTimeDelta = current.getUpTime() - previous.getUpTime(); double cpuUsage = 100.0 * (userTimeDelta + kernelTimeDelta) / upTimeDelta; samples.add(Metric.builder() .key(Key.of(cpuUsageKey).withPrefix(prefix)) .gauge("percents") .sample(cpuUsage, timestamp)); return samples; } @Nonnull @Override public Job bind(@Nonnull final Process target) { return new TaggingJob(null, target, this, new ProcessJob(target, this)); } }
f2adf764d3a701d1feb832caa732cad7a3ddcaf1
[ "Markdown", "Maven POM", "Java", "Dockerfile", "Shell" ]
192
Java
anycollect/anycollect
9ba7f8fb1cff3460c331e7b5595b82613cee6736
86cce994327ec7eae0d2482699f808e740f2e951
refs/heads/master
<file_sep>#include "Sprite.h" #include "raymath.h" Sprite::Sprite(char path[60]) { image = LoadImage(path); texture = LoadTextureFromImage(image); X = -Width / 2; Y = -Height / 2; } void Sprite::Draw() { Vector2 drawThis(); drawThis.y = YAbsolute(); drawThis.x = XAbsolute(); DrawTextureEx( texture, drawThis, GetRotation() * (float)(180.0f / PI), GetScale(), WHITE); base.Draw(); } <file_sep>#include "Actor.h" #include<math.h> Actor::Actor() { } Actor::~Actor() { } float Actor::XAbsolute() { return GlobalTransform.m8; } float Actor::YAbsolute() { return 0.0f; } float Actor::GetRotation() { return (float)std::atan2(GlobalTransform.m1, GlobalTransform.m0); } float Actor::GetScale() { return 0.0f; } void Actor::AddChild(Actor child) { //## Implement AddChild(Actor) ##// if (child.parent != nullptr) { return; } child.parent = this; additions.push_front(child); } void Actor::RemoveChild(Actor child) { } void Actor::UpdateTransform() { } void Actor::Update() { } void Actor::Start() { started = true; } void Actor::Draw() { } <file_sep>//#include "Node.h" // // //template<class T> //Node(T)::Node //{ //} // //template<class T> //Node<T>::~Node //{ //} <file_sep>//#pragma once //class UnorderedList : // public List //{ //public: // UnorderedList(); // ~UnorderedList(); //}; // <file_sep>//#include "List.h" //#include <iostream> //#include <set> // //template<class T> //void List<T>::front() //{ // return startPtr; //} // //template<class T> //void List<T>::back() //{ // return endptr; //} // //template<class T> //void List<T>::insertFirst(const T &) //{ // if (isEmpty()) // { // startPtr = newPtr; // endptr = newPtr; // } // else // { // Node<T>* newPtr = new Node<>(dataIn); // // startPtr = newPtr; // endptr = newPtr; // } // //} // // //template<class T> //void List<T>::insertLast(const T &) //{ // if (isEmpty()) // { // startPtr = newPtr; // endptr = newPtr; // } // else // { // // Node<T>* newPtr = new Node<>(dataIn); // // startPtr = newPtr; // endptr = newPtr; // } //} // //template<class T> //void List<T>::push(Node<T>* head_ref, T NewDate) //{ // Node new_node = new Node(); // // new_node->Node<T> = NewDate; // // new_node->next = (*head_ref); // // (*head_ref) = new_node; //} // //template<class T> //void List<T>::pushBack(Node<T>* End_ref, T NewDate) //{ // Node new_node = new Node(); // // new_node->Node<T> = NewDate; // // new_node->next = (*End_ref); // // (*End_ref) = new_node; //} // // //template<class T> //bool List<T>::isEmpty() //{ // //checks if list is empty // if (startPtr == NULL && endPtr == NULL) { return 1 } // else { return 0 } //} <file_sep>#pragma once class AABB { public: float Width; float Height; static bool canDrawHitbox; private: };
21081d175d29e026978a9c8ecf54bdcc8b42344b
[ "C", "C++" ]
6
C++
brionnafranklin/Restrainment-of-El
7a9469f9f05d4e25147f58829329088d71ada19a
e718e1cfb4c40f722bfe60efea426016a8ff5051
refs/heads/master
<file_sep>import React from 'react'; import RenderText from './RenderText'; // class App extends React.Component { class InputComponent extends React.Component { constructor(props) { super(props); this.state = { text: '' }; } handleInputChange = event => { //handling input change // console.log(event.target.value); this.setState({ text: event.target.value }); // console.log(this.state); }; render() { return ( <div> <input onChange={this.handleInputChange} /> <div>{this.state.text}</div> <RenderText myText={this.state.text} /> </div> ); } } export default InputComponent; //GOAL -> Have our input box display the text on our webpage as we type // -> on clicking "BOLD" make the data display bold //make an event handler -> on change that runs function handleInputChange //handleInput Change -> Take our keystrokes, and save the data in state //TO make our text display in our DOM -> do something to read the state, and display to the DOM
40e9f411e9a31d35e62f4f484a7361df60829ce9
[ "JavaScript" ]
1
JavaScript
fredricklou523/GenericApp
dc01ae9a258df8dcb1feef19fe6e1409d2740177
c1808ac3d00c1d270848d1073b9744b69a68b478
refs/heads/master
<file_sep>[![Go Report Card](https://goreportcard.com/badge/github.com/Luzifer/shareport)](https://goreportcard.com/report/github.com/Luzifer/shareport) ![](https://badges.fyi/github/license/Luzifer/shareport) ![](https://badges.fyi/github/downloads/Luzifer/shareport) ![](https://badges.fyi/github/latest-release/Luzifer/shareport) ![](https://knut.in/project-status/shareport) # Luzifer / shareport `shareport` is a kept simple self-hosted alternative to ngrok to share local development webservers through a remote SSH connection. The only feature supported is to forward the port: All other features like analysing, introspecting or replaying the HTTP traffic are not supported. If you need them you should go with ngrok (and its payed plan for custom domain support). ## How to use it - Prepare your setup including webserver, SSH key and so on (see below for my setup) - Start a webserver for your development and note the port - Execute `shareport`: It then will - Create a SSH connection - By default listen on a random port on the remote machine - Execute the given script or command on the remote machine - After you're done just quit the shareport command and it will - Terminate the remote script - Stop listening on the port - Close the connection ## My Setup - The server - Small [Hetzner Cloud CX11 machine](https://www.hetzner.com/cloud#pricing) - Ubuntu 19.04 and nginx - Domain `knut.dev` with a [LetsEncrypt](https://letsencrypt.org/) wildcard certificate mapped to the machine - Extra user for for shareport with a SSH key deployed - A directory in users home to house nginx server configuration - `sudoers` file to allow `systemctl reload nginx.service` on the unprivileged user - The script: See [`example/remote-script.bash`](example/remote-script.bash) In this setup Ubuntu **19.04** is a quite important part: For the script to properly being shut down the SSH connection needs to be able to transmit a TERM signal. This was implemented somewhere between OpenSSL 7.6 and 7.9 and Ubuntu 19.04 is the first version to ship OpenSSL 7.9. Every other Linux system with a recent OpenSSL version also should work. As an example lets take a Python webserver and expose it: ```console # echo "Ohai" >hello.txt # python -m http.server --bind localhost 3000 Serving HTTP on 127.0.0.1 port 3000 (http://127.0.0.1:3000/) ... # cat .env IDENTITY_FILE=id_rsa IDENTITY_FILE_PASSWORD=<PASSWORD> REMOTE_HOST=knut.dev:22 REMOTE_SCRIPT=example/remote-script.bash REMOTE_USER=shareport # envrun -- shareport --local-addr localhost:3000 Listening on https://4neg7kj4.knut.dev/ # curl https://4neg7kj4.knut.dev/hello.txt Ohai ``` <file_sep>module github.com/Luzifer/shareport go 1.13 require ( github.com/Luzifer/go_helpers/v2 v2.10.0 github.com/Luzifer/rconfig/v2 v2.2.1 github.com/pkg/errors v0.8.1 github.com/sirupsen/logrus v1.4.2 golang.org/x/crypto v0.0.0-20191122220453-ac88ee75c92c ) <file_sep>function gen_prefix() { cat /dev/urandom | tr -dc 'a-z0-9' | head -c 8 || true } # Generate an unique ID and set config path for it share_id=${FQDN_PREFIX:-} while :; do config_file="/home/shareport/nginx/shareport_${share_id}.conf" if [[ -z $share_id ]] || [[ -e $config_file ]]; then share_id=$(gen_prefix) continue fi break done # Ensure configuration directory is there mkdir -p $(dirname ${config_file}) # Create nginx configuration for new share cat -s <<EOF >${config_file} server { listen 443 ssl http2; server_name ${share_id}.knut.dev; ssl_certificate /data/ssl/nginxle/knut.dev.pem; ssl_certificate_key /data/ssl/nginxle/knut.dev.key; location / { proxy_pass http://${LISTEN}; proxy_set_header Upgrade \$http_upgrade; proxy_set_header Connection "Upgrade"; proxy_set_header Host \$host; proxy_set_header X-Real-IP \$remote_addr; proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto \$scheme; } } EOF # Register cleanup for script exit function cleanup() { rm -f \ ${config_file} sudo /bin/systemctl reload nginx.service } trap cleanup EXIT # Reload nginx to apply new config sudo /bin/systemctl reload nginx.service # Let user know where to look echo echo "Listening on https://${share_id}.knut.dev/" echo # Keep active until program exits while :; do sleep 5m; done <file_sep>package main import ( "bytes" "fmt" "io" "io/ioutil" "net" "os" "os/signal" "os/user" "path" "syscall" "github.com/pkg/errors" log "github.com/sirupsen/logrus" "golang.org/x/crypto/ssh" "github.com/Luzifer/go_helpers/v2/env" "github.com/Luzifer/rconfig/v2" ) var ( cfg = struct { DebugRemote bool `flag:"debug-remote" default:"false" description:"Send remote stderr local terminal"` IdentityFile string `flag:"identity-file,i" vardefault:"ssh_key" description:"Identity file to use for connecting to the remote"` IdentityFilePassword string `flag:"identity-file-password" default:"" description:"Password for the identity file"` LocalAddr string `flag:"local-addr,l" default:"" description:"Local address / port to forward" validate:"nonzero"` LogLevel string `flag:"log-level" default:"info" description:"Log level (debug, info, warn, error, fatal)"` RemoteHost string `flag:"remote-host" default:"" description:"Remote host and port in format host:port" validate:"nonzero"` RemoteCommand string `flag:"remote-command" default:"" description:"Remote command to execute after connect"` RemoteListen string `flag:"remote-listen" default:"localhost:0" description:"Address to listen on remote (port is available in script)"` RemoteScript string `flag:"remote-script" default:"" description:"Bash script to push and execute (overwrites remote-command)"` RemoteUser string `flag:"remote-user" vardefault:"remote_user" description:"User to use to connect to remote host"` Vars []string `flag:"var,v" default:"" description:"Environment variables to pass to the script (Format VAR=value)"` VersionAndExit bool `flag:"version" default:"false" description:"Prints current version and exits"` }{} running = true version = "dev" ) func forward(remoteConn net.Conn) { defer remoteConn.Close() localConn, err := net.Dial("tcp", cfg.LocalAddr) if err != nil { log.WithError(err).Error("Unable to connect to local address") return } defer localConn.Close() copyConn := func(w, r net.Conn, wg chan struct{}) { _, err := io.Copy(w, r) if err != nil { log.WithError(err).Debug("IO copy caused an error, terminating connection") } wg <- struct{}{} } var wg = make(chan struct{}, 2) go copyConn(localConn, remoteConn, wg) go copyConn(remoteConn, localConn, wg) <-wg } func genDefaults() map[string]string { defs := map[string]string{} if userHome, err := os.UserHomeDir(); err == nil { defs["ssh_key"] = path.Join(userHome, ".ssh", "id_rsa") } if user, err := user.Current(); err == nil { defs["remote_user"] = user.Username } return defs } func init() { rconfig.SetVariableDefaults(genDefaults()) rconfig.AutoEnv(true) if err := rconfig.ParseAndValidate(&cfg); err != nil { log.Fatalf("Unable to parse commandline options: %s", err) } if cfg.VersionAndExit { fmt.Printf("shareport %s\n", version) os.Exit(0) } if l, err := log.ParseLevel(cfg.LogLevel); err != nil { log.WithError(err).Fatal("Unable to parse log level") } else { log.SetLevel(l) } } func loadPrivateKey() (ssh.AuthMethod, error) { kf, err := ioutil.ReadFile(cfg.IdentityFile) if err != nil { return nil, errors.Wrap(err, "Unable to read key file") } pk, err := signerFromPem(kf, []byte(cfg.IdentityFilePassword)) return ssh.PublicKeys(pk), errors.Wrap(err, "Unable to parse private key") } func main() { sigC := make(chan os.Signal) signal.Notify(sigC, syscall.SIGINT, syscall.SIGTERM) privateKey, err := loadPrivateKey() if err != nil { log.WithError(err).Fatal("Unable to load key") } config := &ssh.ClientConfig{ User: cfg.RemoteUser, Auth: []ssh.AuthMethod{privateKey}, //#nosec G106 // For now no validation is supported HostKeyCallback: ssh.InsecureIgnoreHostKey(), } // Connect to remote client, err := ssh.Dial("tcp", cfg.RemoteHost, config) if err != nil { log.WithError(err).Fatal("Unable to connect to remote host") } // Open port for us to listen on remoteListener, err := client.Listen("tcp", cfg.RemoteListen) if err != nil { log.WithError(err).Fatal("Unable to listen for connection") } defer remoteListener.Close() _, port, err := net.SplitHostPort(remoteListener.Addr().String()) if err != nil { log.WithError(err).Fatal("Unable to get port of remote listen socket") } log.WithField("port", port).Debug("Remote port established") go func() { for running { remoteConn, err := remoteListener.Accept() if err != nil { log.WithError(err).Error("Unable to accept remote connection") continue } go forward(remoteConn) } }() // Initialize script var scriptIn = new(bytes.Buffer) fmt.Fprintln(scriptIn, "set -euxo pipefail") // Create remote script session session, err := client.NewSession() if err != nil { log.WithError(err).Fatal("Unable to open remote session") } defer session.Close() envVars := env.ListToMap(cfg.Vars) envVars["PORT"] = port envVars["LISTEN"] = remoteListener.Addr().String() for k, v := range envVars { fmt.Fprintf(scriptIn, "export %s=%q\n", k, v) } switch { case cfg.RemoteScript != "": script, err := ioutil.ReadFile(cfg.RemoteScript) if err != nil { log.WithError(err).Fatal("Unable to load remote-script") } scriptIn.Write(script) case cfg.RemoteCommand != "": fmt.Fprintf(scriptIn, "exec %s", cfg.RemoteCommand) default: log.Fatal("Neither remote-command nor remote-script specified") } if cfg.DebugRemote { session.Stderr = os.Stderr } else { session.Stderr = ioutil.Discard } session.Stdin = scriptIn session.Stdout = os.Stdout if err := session.Start("/bin/bash -euxo pipefail"); err != nil { log.WithError(err).Fatal("Unable to spawn remote command") } go func() { if err := session.Wait(); err != nil { log.WithError(err).Error("Remote process caused an error") } sigC <- syscall.SIGINT }() // Wait for signal to occur <-sigC // Do a proper teardown log.Info("Signal triggered, shutting down") running = false if err := session.Signal(ssh.SIGHUP); err != nil { log.WithError(err).Error("Unable to send TERM signal to remote process") } } <file_sep>package main import ( "crypto/x509" "encoding/pem" "github.com/pkg/errors" "golang.org/x/crypto/ssh" ) func signerFromPem(pemBytes []byte, password []byte) (ssh.Signer, error) { var err error // read pem block pemBlock, _ := pem.Decode(pemBytes) if pemBlock == nil { return nil, errors.New("Pem decode failed, no key found") } // handle encrypted key if x509.IsEncryptedPEMBlock(pemBlock) { // decrypt PEM pemBlock.Bytes, err = x509.DecryptPEMBlock(pemBlock, password) if err != nil { return nil, errors.Wrap(err, "Decrypting PEM block failed") } // get RSA, EC or DSA key key, err := parsePemBlock(pemBlock) if err != nil { return nil, err } // generate signer instance from key signer, err := ssh.NewSignerFromKey(key) if err != nil { return nil, errors.Wrap(err, "Creating signer from encrypted key failed") } return signer, nil } // generate signer instance from plain key signer, err := ssh.ParsePrivateKey(pemBytes) if err != nil { return nil, errors.Wrap(err, "Parsing plain private key failed") } return signer, nil } func parsePemBlock(block *pem.Block) (interface{}, error) { switch block.Type { case "RSA PRIVATE KEY": key, err := x509.ParsePKCS1PrivateKey(block.Bytes) if err != nil { return nil, errors.Wrap(err, "Parsing PKCS private key failed") } return key, nil case "EC PRIVATE KEY": key, err := x509.ParseECPrivateKey(block.Bytes) if err != nil { return nil, errors.Wrap(err, "Parsing EC private key failed") } return key, nil case "DSA PRIVATE KEY": key, err := ssh.ParseDSAPrivateKey(block.Bytes) if err != nil { return nil, errors.Wrap(err, "Parsing DSA private key failed") } return key, nil default: return nil, errors.Errorf("Parsing private key failed, unsupported key type %q", block.Type) } } <file_sep># 0.1.0 / 2019-11-29 * Initial version
4ff74197d50c3d7021ca4f119fd0dd1a479558fd
[ "Markdown", "Go Module", "Go", "Shell" ]
6
Markdown
Luzifer/shareport
c85d819169fc6590fde61ad5023bac2c5ff87a8f
171f9b85fe84928381934bf24a7726a043ed9c04
refs/heads/main
<file_sep>add mediaquery to big screen(1200+) add menu with download and share options big todos: add stickers saved memes gallery with local storage <file_sep>var gElCanvas; var gCtx; var gDragStartPos; var gIsDragging = false; var gTouchEvs = ['touchstart', 'touchmove', 'touchend']; function init() { gElCanvas = document.getElementById('meme-canvas'); gCtx = gElCanvas.getContext('2d'); renderImages(); addEventListeners(); } ///////////////// event listeners //////////////////// function addEventListeners() { addMouseListeners(); addTouchListeners(); //// typing listeners document.getElementById('text-input').addEventListener('keyup', addText); window.addEventListener('keydown', handleInlineInput); }; function addMouseListeners() { gElCanvas.addEventListener('mousedown', onDown); gElCanvas.addEventListener('mousemove', onMove); gElCanvas.addEventListener('mouseup', onUp); } function addTouchListeners() { gElCanvas.addEventListener('touchmove', onMove); gElCanvas.addEventListener('touchstart', onDown); gElCanvas.addEventListener('touchend', onUp); } //////////////// gallery & editor rendering or toggling //////////////// function onLogoClick() { var elGallery = document.querySelector('.gallery'); if (elGallery.classList.contains('hidden')) onBack(); } function renderImages() { images = getImgsForDisplay(); var strHTMLs = images.map(img => { return `<div class="gallery-item ${img.id}" onclick="onSetImg(${img.id})"> <img src="./${img.url}" alt=""></div>` }); document.querySelector('.gallery').innerHTML = strHTMLs.join(''); } function onSetImg(id) { setImg(id); renderCanvas(); toggleEditor(); } function onFilterBy(filter) { setFilter(filter); renderImages(); } function toggleEditor() { document.querySelector('.editor-container').classList.toggle('hidden'); document.querySelectorAll('.home').forEach(element => { element.classList.toggle('hidden') }); } //////////////// canvas //////////////// function renderCanvas() { const img = new Image(); var currImg = getCurrImg(); img.src = `${currImg.url}`; img.onload = () => { gCtx.drawImage(img, 0, 0, gElCanvas.width, gElCanvas.height); drawText(); markActiveLine(); } } function resetCanvas() { resetLines(true); gCtx.clearRect(0, 0, gElCanvas.width, gElCanvas.height) emptyInput(); } //////////////// editor controllers //////////////// function onAddLine() { addLine(); emptyInput(); renderCanvas(); } function onDeleteLine() { if (!getActiveLine()) return; deleteLine(); emptyInput(); renderCanvas(); } function onChangeFontSize(prefix) { if (!getActiveLine()) return; changeFontSize(prefix); renderCanvas(); } function onSetFont(font) { changeProperty('font', font); document.querySelector('#font-select').style.fontFamily = font; renderCanvas(); } function onChangeTextColor(color) { if (!getActiveLine()) return; changeProperty('color', color); updateInputs(); renderCanvas(); } function onChangeStrokeColor(color) { if (!getActiveLine()) return; changeProperty('stroke', color); updateInputs(); renderCanvas(); } function onClearText() { resetLines(); emptyInput(); renderCanvas(); } function onBack() { resetCanvas(); toggleEditor(); } function onReady() { updateActiveLine(-1); renderCanvas(); } function onDownloadCanvas(elLink) { const data = gElCanvas.toDataURL() elLink.href = data; elLink.download = 'mySpongeMeme'; } /////////////////text change & mark//////////////////// function addText() { var line = getActiveLine(); if (!line) addLine(); var txt = document.getElementById('text-input').value; changeProperty('txt', txt); renderCanvas(); } function handleInlineInput(ev) { if (!getActiveLine()) addLine(); var char = ev.key; var line = getActiveLine(); if (line.txt === 'your text here') line.txt = '' if (char === 'Backspace') line.txt = line.txt.substring(0, line.txt.length - 1); else if (char === 'Escape' || char === 'Enter') updateActiveLine(-1); else if (char === 'Delete') onDeleteLine(); else if (!String.fromCharCode(ev.keyCode).match(/(\w|\s)/g)) return; else line.txt += char; renderCanvas(); } function drawText() { var lines = getMemeLines(); lines.forEach(line => { gCtx.beginPath(); gCtx.lineWidth = 2; gCtx.strokeStyle = line.stroke; gCtx.fillStyle = line.color; gCtx.font = `${line.size}px ${line.font} `; gCtx.textAlign = line.align; gCtx.fillText(line.txt, line.x, line.y, gElCanvas.width); if (line.font !== 'sponge') gCtx.strokeText(line.txt, line.x, line.y, gElCanvas.width); }); } function markActiveLine() { var line = getActiveLine(); if (!line) return; gCtx.font = `${line.size}px ${line.font}`; var width = gCtx.measureText(line.txt).width; changeProperty('width', width); gCtx.beginPath(); gCtx.setLineDash([6, 5]); gCtx.strokeStyle = "#ffffff"; var x = line.x - (line.width / 2); var y = line.y - line.size; gCtx.rect(x - 10, y, line.width + 20, line.size + 10); gCtx.stroke(); gCtx.setLineDash([]); } ///////////////// line dragging related functions //////////////////// function onDown(ev) { emptyInput(); const pos = getEvPos(ev); if (!lineClicked(pos)) return; gDragStartPos = pos; } function onMove(ev) { var activeLine = getActiveLine(); if (gIsDragging) { const pos = getEvPos(ev); const dx = pos.x - gDragStartPos.x; const dy = pos.y - gDragStartPos.y; activeLine.x += dx activeLine.y += dy gDragStartPos = pos; renderCanvas(); } } function onUp() { document.body.style.cursor = 'default'; var activeLine = getActiveLine(); if (!activeLine) return; gIsDragging = false; } function lineClicked(pos) { var idx = findClickedLineIdx(pos); updateActiveLine(idx); renderCanvas(); if (idx !== -1) { updateInputs(); gIsDragging = true; document.body.style.cursor = 'grabbing'; return true; } else return false; } function getEvPos(ev) { var pos = { x: ev.offsetX, y: ev.offsetY } if (gTouchEvs.includes(ev.type)) { ev.preventDefault() ev = ev.changedTouches[0] pos = { x: ev.pageX - ev.target.offsetLeft - ev.target.clientLeft, y: ev.pageY - ev.target.offsetTop - ev.target.clientTop } } return pos } //////////// inputs updates function emptyInput() { var elInput = document.getElementById('text-input'); elInput.value = ''; } function updateInputs() { var activeLine = getActiveLine() document.querySelector('#text-fill').value = activeLine.color; document.querySelector('#text-stroke').value = activeLine.stroke; if (activeLine.txt !== 'your text here') document.querySelector('#text-input').value = activeLine.txt; } <file_sep>var gImgs = [{ id: 1, url: 'img/memes-sqr/spongebob-mocking.jpg', keywords: ['spongebob', 'mocking'] }, { id: 2, url: 'img/memes-sqr/spongebob-panting.jpg', keywords: ['spongebob', 'panting'] }, { id: 3, url: 'img/memes-sqr/patrick-evil.jpg', keywords: ['patrick', 'evil'] }, { id: 4, url: 'img/memes-sqr/krabs-blurred.jpg', keywords: ['krabs', 'confused'] }, { id: 5, url: 'img/memes-sqr/krabs-sado.jpg', keywords: ['krabs'] }, { id: 6, url: 'img/memes-sqr/krabs-wack.jpg', keywords: ['krabs', 'cool'] }, { id: 7, url: 'img/memes-sqr/krabs-crazy.jpg', keywords: ['krabs', 'crazy'] }, { id: 8, url: 'img/memes-sqr/squidward-watching.jpg', keywords: ['squidward', 'lonely', 'watching', 'patrick', 'spongebob'] }, { id: 9, url: 'img/memes-sqr/squidward-leaving.jpg', keywords: ['squidward', 'leaving'] }, { id: 10, url: 'img/memes-sqr/squidward-loser.jpg', keywords: ['squidward', 'loser'] }, { id: 11, url: 'img/memes-sqr/squidward-shy.jpg', keywords: ['squidward', 'shy'] }, { id: 12, url: 'img/memes-sqr/patrick-planning.jpg', keywords: ['patrick', 'evil', 'planning'] }, { id: 13, url: 'img/memes-sqr/patrick-stupid.jpg', keywords: ['patrick', 'stupid'] }, { id: 14, url: 'img/memes-sqr/spongebob-worshiping.jpg', keywords: ['spongebob', 'worshiping'] }, { id: 15, url: 'img/memes-sqr/patrick-naked.png', keywords: ['patrick', 'naked'] }, { id: 16, url: 'img/memes-sqr/spongebob-coffin.jpg', keywords: ['spongebob', 'patrick', 'coffin'] }, { id: 17, url: 'img/memes-sqr/spongebob-treasure.jpg', keywords: ['spongebob', 'treasure'] }, { id: 18, url: 'img/memes-sqr/patrick-yelling.jpeg', keywords: ['patrick', 'yelling'] }, { id: 19, url: 'img/memes-sqr/spongebob-laughing.jpg', keywords: ['spongebob', 'laughing'] }, { id: 20, url: 'img/memes-sqr/patrick-trumpet.jpg', keywords: ['patrick', 'trumpet'] }, ]; var gCanvasSize = 300; var gFilter = 'all'; var gMeme = { selectedImgId: null, activeLineIdx: 0, lines: [_createLine(40)] } //////////// images //////////// function getImgsForDisplay() { if (gFilter === 'all') return gImgs; var imgs = gImgs.filter(img => { return img.keywords.some(keyword => keyword === gFilter); }); return imgs; } function setFilter(filter) { gFilter = filter; } function setImg(id) { gMeme.selectedImgId = id; } function getImgById(id) { return gImgs.find(img => img.id === id); } function getCurrImg() { return gImgs[gMeme.selectedImgId - 1]; } //////////// lines related functions //////////// ///get & find function getMemeLines() { return gMeme.lines; } function getActiveLine() { return gMeme.lines[gMeme.activeLineIdx]; } function findClickedLineIdx(pos) { var idx = gMeme.lines.findIndex(line => { return pos.x > line.x - (line.width / 2) - 10 && pos.x < line.x + (line.width / 2) + 10 && pos.y > line.y - line.size && pos.y < gElCanvas.height - (gElCanvas.height - line.y - 10) }); return idx; } function _createLine(yPos) { return { x: gCanvasSize / 2, y: yPos, txt: 'your text here', size: 30, color: '#ffffff', stroke: '#000000', font: 'impact', align: 'center', gIsDragging: false }; } ///deletions & resets function resetLines(isInitial) { gMeme.lines = []; if (isInitial) gMeme.lines.push(_createLine(40)); gMeme.activeLineIdx = 0; } function deleteLine() { var idx = gMeme.activeLineIdx; gMeme.lines.splice(idx, 1); gMeme.activeLineIdx = idx - 1; if (gMeme.activeLineIdx < 0) gMeme.activeLineIdx = 0; } // updates & changes function updateActiveLine(idx) { gMeme.activeLineIdx = idx; } function changeProperty(property, value) { gMeme.lines[gMeme.activeLineIdx][property] = value; } function changeFontSize(prefix) { var diff = prefix * 5; gMeme.lines[gMeme.activeLineIdx].size += diff; } //// new line addition function addLine() { var linesNum = gMeme.lines.length; var yPos; if (linesNum < 1) yPos = 40; else if (linesNum === 1) yPos = 280; else if (linesNum > 1) yPos = 150; var newLine = _createLine(yPos); gMeme.lines.push(newLine); gMeme.activeLineIdx = gMeme.lines.length - 1; }
e7707bd0971cab5453314e93bd8b110e8ba3414e
[ "JavaScript", "Text" ]
3
Text
Almoglem/memegenerator
d2dfaa5abf75021b34b5c2ece1bef6add49724dd
7ab10a21f9cced58c5d22e881f3dd4754974ca85
refs/heads/master
<repo_name>zhouhanxiaoxiao/easyflytracker<file_sep>/src/main.js import Vue from 'vue' import App from './App.vue' import router from "@/router/router"; import i18n from "@/i18n"; import 'iview/dist/styles/iview.css'; import "bootstrap/dist/css/bootstrap.min.css"; import "bootstrap/dist/js/bootstrap.min.js"; import $ from "jquery"; import iView from "iview"; Vue.use(iView); Vue.prototype.$ = $; Vue.config.productionTip = false new Vue({ render: h => h(App), router, i18n }).$mount('#app') <file_sep>/src/router/router.js import Vue from "vue"; import VueRouter from "vue-router"; import Home from "@/components/home/Home"; Vue.use(VueRouter) const routes = [ {path: '',name:"stockEdit",component: Home,meta: {index: 0}}, {path: '/home',name:"stockEdit",component: Home,meta: {index: 0}}, ] /*实例化路由*/ const router = new VueRouter({ routes:routes, // (简写)相当于 routes: routes }); /*导出路由模块*/ export default router
dec25a3f9a35e04bdfa8325e3dd0022d1652a9de
[ "JavaScript" ]
2
JavaScript
zhouhanxiaoxiao/easyflytracker
d975e486479d80ea8c1b3b4a01832ebbc37f98e5
cc5c79e323bcf4298ab5f43c6d3c55f6046469e7
refs/heads/master
<repo_name>GoPixel-lab/pixel-avatars<file_sep>/src/components/search.js import React from 'react' import { API_URL } from '../constants/api' const search = props => { return ( <React.Fragment> <h1>Enter your own seed!</h1> <small>(Don't use sensitive or personal data as seed!)</small> <div className="avatar-container"> <div className="item"> <img src={`${API_URL}/male/${props.query}.svg`} alt=""/> <button className="btn" onClick={() => props.saveAvatar(props.query, 'male')} type="button">Add to favorites</button> </div> <div className="item"> <img src={`${API_URL}/female/${props.query}.svg`} alt=""/> <button className="btn" type="button" onClick={() => props.saveAvatar(props.query, 'female')}>Add to favorites</button> </div> <div className="item"> <img src={`${API_URL}/identicon/${props.query}.svg`} alt=""/> <button className="btn" type="button" onClick={() => props.saveAvatar(props.query, 'identicon')}>Add to favorites</button> </div> </div> <input type="text" onChange={(event) => props.getAvatars(event.target.value)} /> </React.Fragment> ) } export default search <file_sep>/src/modules/avatars.js const GET_AVATAR = 'GET_AVATAR' const SAVE_AVATAR = 'SAVE_AVATAR' const DELETE_AVATAR = 'DELETE_AVATAR' const initialState = { avatarQuery: '', favoritesArr: [], } export default (state = initialState, action) => { switch (action.type) { case GET_AVATAR: return { ...state, avatarQuery: action.payload.query } case SAVE_AVATAR : return { ...state, favoritesArr: [...state.favoritesArr, action.payload] } case DELETE_AVATAR : return { ...state, favoritesArr: state.favoritesArr.filter(item => action.payload.id !== item.id), } default: return state } } <file_sep>/README.md ## Simple pixel avatar generator created with react/redux and https://avatars.dicebear.com/ <img src="https://avatars.dicebear.com/v2/male/pixel.svg" alt="drawing" width="150"/> React pixel avatars generator ## APP DEMO https://chernavskikh.github.io/pixel-avatars/ Used boilerplate https://github.com/notrab/create-react-app-redux.git ## Installation yarn ## Get started yarn start ## Build yarn build <file_sep>/src/modules/index.js import { combineReducers } from 'redux' import { connectRouter } from 'connected-react-router' import avatars from './avatars' const createRootReducer = (history) => combineReducers({ router: connectRouter(history), // rest of your reducers avatars, }) export default createRootReducer <file_sep>/src/components/savedItem.js import React from 'react' import { API_URL } from '../constants/api' const savedItem = ({ item, deleteAvatar }) => { return ( <div className="favorite-item"> <button className="btn-delete" onClick={() => deleteAvatar(item.id)}>X</button> <img src={`${API_URL}/${item.type}/${item.query}.svg`} alt="avatar"/> </div> ) } export default savedItem <file_sep>/src/containers/home/index.js import React from 'react' import { connect } from 'react-redux' import { getAvatar, saveAvatar, deleteAvatar } from '../../actions/avatars' import Favorites from '../../components/favorites' import Search from '../../components/search' const Home = props => ( <div className="wrapper"> <Search query={props.query} saveAvatar={props.saveAvatar} getAvatars={props.getAvatars} /> { props.favoritesArr.length > 0 && <Favorites avatars={props.favoritesArr} deleteAvatar={props.deleteAvatar} />} </div> ) const mapStateToProps = state => { return { query: state.avatars.avatarQuery, favoritesArr: state.avatars.favoritesArr, } } const mapDispatchToProps = dispatch => { return { getAvatars: query => { dispatch(getAvatar(query)); }, saveAvatar: (query, type) => { dispatch(saveAvatar(query, type)); }, deleteAvatar: (id) => { dispatch(deleteAvatar(id)); } }; }; export default connect( mapStateToProps, mapDispatchToProps )(Home)
7b33df56f1def0ed938bf87540615ae129462f28
[ "JavaScript", "Markdown" ]
6
JavaScript
GoPixel-lab/pixel-avatars
0b73acc59e97451e0b0eae6fd1befc2aac2d7d1e
ff5a2dc8da981fec34ca91ae4bf9eebde8587e0f
refs/heads/master
<file_sep>package com.zuohaomeng.anna_news.Util; public class Constant { public static String baseUrl = "http://192.168.127.12:8001/get_news/"; // public static String baseUrl = "http://127.0.0.1:8000/get_news/"; public static String TECENT_NEWS_URL_INTERFACE = "tencent"; public static String NETEASE_NEWS_URL_INTERFACE = "netease"; public static String SOHU_NEWS_URL_INTERFACE = "sohu"; }
532ea636c78e30aef01aafbed9ae48da7ef90ff0
[ "Java" ]
1
Java
bigbigx/anna-news
68c65d12bdd06082dde8273238ac5f2e84054a75
0d2d9cab1bd25643b7a85ee0d5b152ae9edc55fe
refs/heads/master
<repo_name>evejweinberg/SuperHero<file_sep>/js/sketch.js function setup() { $('#battery').show(); //create p5 canvas canvas = createCanvas(windowWidth, windowHeight); centerH = (windowWidth / 2); calimgX = (windowWidth / 2) - 200; calimgY = (windowHeight / 2) - 160; //create HTML elements readyforschool = createImg('assets/readyforschool.png'); readyforschool.class('class7').id('readyforschool'); gd = new getCalibrationSensorValChange(); //pause loading video loadingOvervid = document.getElementById("loadingOver"); loadingOvervid.pause(); // loadingOvervid.remove(); spacebg = loadImage('assets/spaceEdges3.png'); colors = [ color(57, 42, 48), //brown color(246, 209, 68), //yellow color(236, 115, 105), //pink color(123, 200, 166), //green color(244, 179, 100), //orange color(165, 218, 194), //light green color(231, 82, 68), //drkpink color(0, 166, 155) //blue ] //scene6 for (var i = 0; i < 200; i++) { scn6BGsprite.push(new Scn6Jitter()); } rotateDiv = createDiv(''); scene6buttons = createDiv(''); scene6buttons.class('class6').id('scene6buttonholder') retakePhotoButton = createButton('Retake Photo').class('class6').addClass('scene6buttons').id('playbutton'); retakePhotoButton.class('class6').addClass('scene6buttons').parent(scene6buttons); retakePhotoButton.mousePressed(function() { //reset this array if they want to retake photo photoBurst = []; photoIndex = 0; loopPhotos = 0; takePhotoBurst = setInterval(photoBooth, 20); }); rotateDiv.class('class6').addClass('newspaperDiv'); videoInput = createCapture(VIDEO); videoInput.size(575, 340); videoInput.position(575, 330); videoInput.hide(); //p5js way of doing random var newsRandom = floor(random(0, 1.9)); if (newsRandom == 0) { // console.log('newspaper is 0') newspaperImage = createImg('assets/newspaper2.png'); newspaperImage.class('class6').parent(rotateDiv).id('scene6newspaper'); } else { // console.log('newspaper is 1') newspaperImage = createImg('assets/newspaper3.png'); newspaperImage.class('class6').parent(rotateDiv).id('scene6newspaper'); } //scene 7 callibration calibrateSteadyType = createP(''); calibrationHeader = createP('Put Your Arms Out \r\n Like This'); calibrationHeader.class('class7').addClass('header3').id('calibrationHeaderid'); calibrateSteadyType.class('class7').id('calibrateHoldSteady'); callibrationImage = loadImage('assets/Callibration.png'); shadow = loadImage('assets/shadow.png'); CapeCalibrationSign = createImg('assets/CapeCalibrationSign2.png'); CapeCalibrationSign.class('class7').addClass('capesign'); // scene 3 flight test flapTemp1 = createImg('assets/flightTest01.gif'); flapTemp2 = createImg('assets/turbo.gif'); var flapdiv = createDiv(''); flapdiv.class('flapdiv'); flapTemp1.class('class3').addClass('flap1').id('flap1').position(windowWidth / 2 - 250, 240); flapTemp2.class('class3').addClass('flyIn3').id('flap2').size(462, 440).position(windowWidth / 2 - 250, 240); $("#flap2").hide(); FlightSchoolSign = createImg('assets/FlightSchoolSign3.png'); FlightSchoolSign.class('class3').addClass('sign').id('flightschoolsign'); for (var m = 0; m < totalstars; m++) { singlestar.push(new starfield1()); } // scene4 scene4Script = createP(''); scene4Script.class('class4').addClass('voiceover'); currentText = scene4Script.html(); words = split(transcript[0], '#'); flysmall = createImg('assets/flying.gif'); flysmall.class('class4'); flyingOverhead2 = createImg('assets/flyingOverhead.png'); flyingOverhead2.class('flyingoverhead').position(flythroughX, flythroughY).size(1400, 1250); $('.flyingoverhead').hide(); squeezeFistGif = createImg('assets/fist4.gif').class('class4').id('squeezeFistGif'); squeezeFistGif.position(squeezeFistGifX, squeezeFistGifY).size(500,936); //scene5 keepgoing01 = loadImage('assets/keepgoing01.png'); scene5countdown = createP('3'); scene5countdown.class('countdown').addClass('class5').id('countdowntofly'); //subtract element width/2 and hright //at the end of setup, start scene 1 changeScene(1); } ///SETUP ENDS function draw() { centerH = (windowWidth / 2); AverageAcellerometerNums(); getSpeed(); bgmusic(); //this is a p5 thing to clear the background of the canvas clear(); if (scene1 === true) { if (moveOnDebug == 1) { console.log('moveOnDebug 1 was called') // changeScene(1); $('#defaultCanvas0').show(); $('#loadingvideo').hide(); $('#loadingOver').show(); //this is the transition video to scene 4 loadingOvervid.play(); $('#loadingOver').bind('ended', function() { console.log('transition vide oended') changeScene(4); $('#loading').remove(); }); // loadingOvervid.loop = false; moveOnDebug = 0 // $('#battery').html('') } } else if (scene2 == true) { } else if (scene3 == true) { document.getElementById("yourSpeed").innerHTML = AllScenesMPH; if (scene3A == true) { if (AllScenesMPH > 100) { $("#flap1").addClass('FlyAway2'); $("#flap2").show(); document.getElementById('targetSpeed').innerHTML = '450'; $("#flap2").addClass('FlyIn3'); var readytoswitch = setInterval(function() { scene3A = false; scene3B = true; }, 2000); } } if (scene3B == true) { if (AllScenesMPH > 480) { for (var i = 0; i < totalParticles; i++) { arrayOfBalls.push(new flapWin1(width / 1.6, height / 2, width / 2 + random(-width, width), height / 2 + random(-height, height))); //push new particles arrayOfBalls.push(new flapWin2(width / 1.6, height / 2, width / 2 + random(-width, width), height / 2 + random(-height, height))); //push new particles } readyfortrans = true; } } image(Allclouds[3], round(cloudMovex), 50); image(Allclouds[3], round(cloudMovex) + 1600, 350); image(Allclouds[0], floor(cloudMovex) + 500, 200); image(Allclouds[1], floor(cloudMovex) + 300, 400); image(Allclouds[2], round(cloudMovex) + 1000, 100); image(spacebg, 0, 0, windowWidth, windowHeight); if (frameCount % 30 == 0) { cloudMovex = cloudMovex + 2; } if (readyfortrans == true) { $('#flightschoolsign').animate({ height: '-200' }, 1200); transitionTicker = transitionTicker + .3; image(transitionToStory[round(transitionTicker)], 0, 0, windowWidth, windowHeight); if (transitionTicker > 12) { changeScene(5); readyfortrans = false; } } for (var i = 0; i < arrayOfBalls.length; i++) { arrayOfBalls[i].display(); //display them all arrayOfBalls[i].explode(); //explode them all } for (var i = 0; i < arrayOfBalls.length; i++) { if (arrayOfBalls[i].size === 0) { arrayOfBalls.splice(i, 1); } } } else if (scene4 === true) { //mission story playSwoosh(); if (frameCount % 30 == 0) { cloudMovex = cloudMovex + 2; } image(Allclouds[3], round(cloudMovex) + 1000, 600, 135, 45); //get exact dimensions image(Allclouds[3], round(cloudMovex) + 1100, 320, 135, 45); image(Allclouds[0], floor(cloudMovex) + 810, 250, 135, 45); image(Allclouds[1], floor(cloudMovex) + 1200, 400, 135, 45); image(Allclouds[2], round(cloudMovex) + 850, 500, 135, 45); if (moveOnDebug == 2) { changeScene(7); } fill(255, 0, 0); // flyingOverhead.position(flythroughX - 40, flythroughY + 40); flyingOverhead2.position(flythroughX, flythroughY); flythroughX = flythroughX + 20; flythroughY = flythroughY - 20; if (flythroughX > windowWidth + 400) { $('.flyingoverhead').hide(); } Scn4_textcounter++; dearEarthVO(); if (Scn4_textcounter - lastCue > timings[index]) { currentText = scene4Script.html(); lastCue = Scn4_textcounter; index = index + 1; } scene4Script.html(currentText + words[index]); Scn4_textcounter++; angleMode(DEGREES); angle = angle + .5; if (angle > 360) { angle = 0; firstround = false; } squeezeFistGif.position(squeezeFistGifX, squeezeFistGifY); if (Scn4_textcounter > 1490) { //change this to instructions about using your phone $('#squeezeFistGif').show(); squeezeFistGifY = squeezeFistGifY - 20; if (squeezeFistGifY < height-800) { squeezeFistGifY = height-800; } } //this is the circle of particles trialing the aniamtion var circl = map(millis(), 0, 30000, 0, 10); //30 sec to ten? var offsetX = ffcenterX; var offsetY = ffcenterY; var circx = cos(angle) * orbitRadius + ffcenterX + orbitRadius / 2 - 30; var circy = sin(angle) * orbitRadius + ffcenterY + orbitRadius / 2 - 30; flyingOrbitRate = (flyingOrbitRate + .55); flysmall.position(circx, circy).size(flyingSize, flyingSize).rotate(180 + flyingOrbitRate); if (Scn4_textcounter > 850) { asteroidHitandBounce(); } if (Math.round(Scn4_frmct) >= earthSpinFrames) { Scn4_frmct = 0; } image(earthspin_frames[Math.round(Scn4_frmct)], ffcenterX, ffcenterY, 300, 300); //center of circle Scn4_frmct = Scn4_frmct + .3; if (angle < 360 && firstround == true) { particles.push(new FFParticle(circx + flyingSize / 2, circy + flyingSize / 2)); } for (var i = 0; i < particles.length; i++) { particles[i].update(); particles[i].display(); } if (readyfortrans == true) { transitionTicker = transitionTicker + .3; image(transitionToStory[round(transitionTicker)], 0, 0, windowWidth, windowHeight); if (transitionTicker > 12) { changeScene(7); readyfortrans = false; } } } else if (scene5 == true) { if (Scn5_frmct == 240) { takePhotoBurst = setInterval(photoBooth, 20); } Scn5_frmct++; if (readGameOver == true) { $('#userSpeedDiv').hide(); gameoverclock++; if (gameoverclock > 240) { changeScene(6); } } if (Scn5_frmct > 180) { if (fuckthis == true) { CountDownTry4(); } } if (AllScenesMPH > 520) { //hitting turbo for (var l = 0; l < 2; l++) { torus = createMesh(new THREE.TorusGeometry(37, 4, 10, 6, Math.PI * 2)); torus.position.z = (camZ - 500) + (l * 30); torus.position.x = 0; torus.position.y = camY; scene.add(torus); torusMesh.push(torus); } } if (Scn5_frmct > 980 && Scn5_frmct < 1280) { image(keepgoing01, 0, 450); } document.getElementById("update-speed").innerHTML = AllScenesMPH; dearEarth.stop(); if (Scn5_frmct == 1) { cd_3.play(); } if (Scn5_frmct == 60) { cd_2.play(); } if (Scn5_frmct == 120) { cd_1.play(); } if (Scn5_frmct == 180) { cd_fly.play(); } if (Scn5_frmct > 60 && Scn5_frmct < 120) { document.getElementById('countdowntofly').innerHTML = '2'; } else if (Scn5_frmct > 120 && Scn5_frmct < 180) { document.getElementById('countdowntofly').innerHTML = '1'; } else if (Scn5_frmct > 180 && Scn5_frmct < 240) { document.getElementById('countdowntofly').innerHTML = 'FLY!'; } else if (Scn5_frmct == 240) { $('#userSpeedDiv').show(); document.getElementById('countdowntofly').innerHTML = ''; gameSongPlaying(); counter = setInterval(timer, 33); //1000 will run it every 1 second } } else if (scene6 == true) { videoInput.position(windowWidth / 2 - 200, (windowHeight / 2) + 610); roveBothax = cos(millis() / 10) * 7; roveBothay = sin(millis() / 10) * 7; roveBothbx = sin(millis() / 10) * 7; roveBothby = cos(millis() / 10) * 7; for (var i = 0; i < scn6BGsprite.length; i++) { scn6BGsprite[i].display(); } if (photoBurst.length > 0) { image(photoBurst[loopPhotos], (width / 2) - 215, (height / 2) + 35); loopPhotos = (loopPhotos + 1) % photoBurst.length; } Scene6counter++; for (var i = 0; i < arrayOfBalls.length; i++) { arrayOfBalls[i].display(); //display them all arrayOfBalls[i].explode(); //explode them all } for (var i = 0; i < arrayOfBalls.length; i++) { if (arrayOfBalls[i].size === 0) { arrayOfBalls.splice(i, 1); } } if (Scene6counter < 10) { for (var i = 0; i < totalParticles; i++) { arrayOfBalls.push(new flapWin1(width / 3, height / 2, width / 2 + random(-width, width), height / 2 + random(-height, height))); //push new particles arrayOfBalls.push(new flapWin2(width / 3, height / 2, width / 2 + random(-width, width), height / 2 + random(-height, height))); //push new particles } } } else if (scene7 == true) { //callibration sceen //add these images image(spacebg, 0, 0, windowWidth, windowHeight); image(callibrationImage, calimgX, calimgY, 400, 400); image(shadow, (windowWidth / 2) - 92, windowHeight * .73); if (calibrateFinal == true) { console.log('cal final') calimgX = calimgX + 7; calimgY = calimgY - 7; textSize(100); textAlign(CENTER); $('#readyforschool').show(); var up = -1; document.getElementById('calibrationHeaderid').innerHTML = ''; readyforschool = true; $('.bluebgup').animate({ height: '900' }, 1200); calcountdown = window.setInterval(function() { // calibrationOver(); //once over call this //this changes to scene 3 if calibrateFinal == true }, 3000); //every 3 seconds } if (callibrationStage === true) { console.log('callibrationStage') $('#readyforschool').hide(); textSize(80); textAlign(CENTER); text('HOLD STEADY FOR: ' + callibrationCountdown, windowWidth / 2, 730); calimgX = (windowWidth / 2) - 200; calimgY = (windowHeight / 2) - 160; if (callibrationCountdown <= 0) { //this will change 'calibrationfinal' to true CalibrationSensorValChangeges2(); window.clearInterval(calcountdown); } textSize(20); //stream new numbers into this array, keep 100 numbers at a time NumstoCallibrate.push(newDataZ); //now that we're steady, lets gather the actual number if (NumstoCallibrate.length > 100) { // write over the 100 numbers in the array NumstoCallibrate.splice(0, 1); } sum = 0; for (var i = 0; i < NumstoCallibrate.length; i++) { //100 times var num = Number(NumstoCallibrate[i]); //raw sensor numbers sum = sum + num; //add them all up } CallibratedRestingNum = sum / NumstoCallibrate.length; } ///callibration over if (callibrationPreStage === true) { console.log('prestate') var t = document.getElementById('calibrateHoldSteady'); t.innerHTML = ''; textSize(30); textAlign(CENTER); calimgX = (windowWidth / 2) - 200; calimgY = (windowHeight / 2) - 160; textSize(60); if (distanceofvalues > 6) { textSize(80); textAlign(CENTER); text('NOT STEADY ENOUGH', windowWidth / 2, 730); // t.innerHTML = 'NOT STEADY'; } else if (distanceofvalues < 6) { // t.innerHTML = 'HOLD STEADY FOR ' + callibrationCountdown; textSize(80); textAlign(CENTER); text('HOLD STEADY', windowWidth / 2, 730); } isCallibrationReady.push(distanceofvalues); if (isCallibrationReady.length > 10) { // write over the 10 numbers in the array isCallibrationReady.splice(0, 1); } sum = 0; for (var i = 0; i < isCallibrationReady.length; i++) { var num = Number(isCallibrationReady[i]); sum = sum + num; } averageValpreCal = sum / isCallibrationReady.length; } ///pre-callibration over if (averageValpreCal > 6) { window.clearTimeout(timer) timer = setTimeout(function() { //this function switches us to callibration stage CalibrationSensorValChangeges(); }, 3000); } } //scene 7 ends } ///DRAW ENDS//////// // function loadfirstinstruction() { // $('.class2').show(); // } // function myHandler(e) { // scene1 = false; // scene7 = true; // changeScene(7); // } function toCalibration() { if ($('#loading').is(':visible')) { $('#loadingvideo').hide(); } scene1 = false; scene7 = true; changeScene(7); } //scene1 function EndIntro() { if ($('#loadingvideo').is(':visible')) { $('#loadingvideo').hide(); } scene1 = false; scene7 = true; changeScene(7); } //scene4 function asteroidHitandBounce() { var targetastx = ffcenterX - 150; var targetasty = ffcenterY; var targetastx2 = 300; var targetasty2 = 1200; if (dist(ast_x, ast_y, targetastx, targetasty) < 19) { switchAstMove = true; } if (switchAstMove == false) { var targetsize = 120; ast_x += (targetastx - ast_x) * .015; ast_y += (targetasty - ast_y) * .015; ast_size -= (ast_size - targetsize) * .05; image(asteroid, ast_x, ast_y, ast_size, ast_size); } if (switchAstMove == true) { ast_x += (targetastx2 - ast_x) * .018; ast_y += (targetasty2 - ast_y) * .018; image(asteroid, ast_x, ast_y, ast_size, ast_size); } } function FFParticle(_x, _y) { this.x = _x; this.y = _y; this.initSize = random(5, 12); this.straySize = random(10, 35); this.size = this.initSize; this.h = 130 + random(70, 150); this.s = 100; this.b = 100; this.a = random(0.1, 1.0); this.spd = random(0.02, 0.08); this.noiseX = 0; this.noiseY = 0; this.noiseSpdX = random(0.001, 0.02); this.noiseSpdY = random(0.001, 0.02); this.update = function() { this.size = this.initSize + sin(frameCount * this.spd) * 8; this.noiseX = (noise(frameCount * this.noiseSpdX) - 0.5) * 20; this.noiseY = (noise(frameCount * this.noiseSpdY) - 0.5) * 20; } this.display = function() { push(); noStroke(); colorMode(HSB); fill(this.h, this.s, this.b, this.a); ellipse(this.x + this.straySize + this.noiseX, this.y + this.straySize + this.noiseY, this.size, this.size); ellipse(this.x + this.straySize + this.noiseX, this.y + this.straySize + this.noiseY, this.size, this.size); pop(); } } //scene5 function CountDownTry4() { console.log('try 4 working') if (fuckthis == true) { countdownIdB = setInterval(countdownTry3, 1000); fuckthis = false; } } function countdownTry3() { console.log('try 3 working') if (clockB > 0) { clockB = clockB - 1; document.getElementById('timerStopWatch').innerHTML = '00:' + clockB; // clearInterval(countdownIdB); } else { playCheers(); //Stop clock clearInterval(countdownIdB); $('.gamveoverDiv').show(); var randomCongrats = round(random(0, 3.4)); if (randomCongrats == 0) { document.getElementById('gameoverText').innerHTML = 'HOLEY MOLEY!'; } else if (randomCongrats == 1) { document.getElementById('gameoverText').innerHTML = 'YOU DID IT'; } else if (randomCongrats == 2) { document.getElementById('gameoverText').innerHTML = 'WOAHHHH'; } else if (randomCongrats == 3) { document.getElementById('gameoverText').innerHTML = 'SUPER STAR'; } // var milesFlown = String(floor((30000 - camZ))); document.getElementById('gameoverStat').innerHTML = 'You Flew ' + addCommas(floor((30000 - camZ))) + ' Miles'; readGameOver = true; } } //scene6 function savePicture() { save(canvas); } //scene7 function CalibrationSensorValChangeges() { if (callibrationPreStage == true) { callibrationPreStage = false; callibrationStage = true; Begincountdown(); //move onto real countdown } } function CalibrationSensorValChangeges2() { if (callibrationStage == true) { callibrationStage = false; UserArmOutNum = CallibratedRestingNum; calibrateFinal = true; } } function getCalibrationSensorValChange() { this.currentVal = newDataZ; this.previousVal = newDataZ; this.lastcheck = 0; this.display = function() { this.currentVal = newDataZ; if (millis() - this.lastcheck > 120) { //read every 10th of a second distanceofvalues = abs(this.currentVal - this.previousVal); this.previousVal = this.currentVal; this.lastcheck = millis(); } } } function AverageAcellerometerNums() { NumstoCallibrateDuringFlight.push(newDataZ); if (NumstoCallibrateDuringFlight.length > 100) { // write over the 100 numbers in the array NumstoCallibrateDuringFlight.splice(0, 1); } sum = 0; for (var i = 0; i < NumstoCallibrateDuringFlight.length; i++) { //100 times var num = Number(NumstoCallibrateDuringFlight[i]); //raw sensor numbers sum = sum + num; //add them all up } // MovingAverage = sum / NumstoCallibrateDuringFlight.length; ////////if the sensor breaks!!!!//////// if (sensorConnected == true) { if (scene3 == true && scene3B == true || scene5 == true) { distanceofvaluesFlying = speedMultiplier*round(abs(CallibratedRestingNum - newDataZ)); } else if (scene3A == true && scene3 == true) { distanceofvaluesFlying = speedRnd1Multiplier* round(abs(CallibratedRestingNum - newDataZ)); } // console.log(distanceofvaluesFlying); } else if (sensorConnected == false) { if (scene3 == true && scene3A == true) { // console.log('3A') distanceofvaluesFlying = random(35, 170); } else if (scene3B == true && scene3 == true) { // console.log('3B') distanceofvaluesFlying = random(200, 620); } else if (scene5 == true) { // console.log('5') distanceofvaluesFlying = random(155, 795); } } } function getSpeed() { if (distanceofvaluesFlying < 100) { range1 = 0; range1hit = true; } if (distanceofvaluesFlying > 120) { range2hit = true; range2 = range2 + 0.3; if (range2 > 3) { range2 = 3; } } if (distanceofvaluesFlying > 160) { range3hit = true; range3 = range3 + 0.5; if (range3 > 4) { range3 = 4; } } if (distanceofvaluesFlying > 250) { range4 = range4 + 0.6; range4hit = true; if (range4 > 4) { range4 = 4; } } if (distanceofvaluesFlying > 500) { range5hit = true; if (range5 == true) { } range5 = range5 + 0.6; if (range5 > 6.1) { range5 = 6.1; } } if (distanceofvaluesFlying > 750) { range6hit = true; range6 = range6 + 0.5; if (range6 > 10) { range6 = 10; } } CamSpeed = range1 + range2 + range3 + range4 + range5 + range6; if (frameCount % 15 == 0) { AllScenesMPH = round(map(CamSpeed, 0, 24, 0, 600)); } if (range2hit == false) { range2 = range2 - 0.06 * decreasemult; } if (range3hit == false) { range3 = range3 - 0.04 * decreasemult; } if (range4hit == false) { range4 = range4 - 0.03 * decreasemult; } if (range5hit == false) { range5 = range5 - 0.02 * decreasemult; } if (range6hit == false) { range6 = range6 - 0.03 * decreasemult; } if (range2 < 0) { range2 = 0; } if (range3 < 0) { range3 = 0; } if (range4 < 0) { range4 = 0; } if (range5 < 0) { range5 = 0; } if (range6 < 0) { range6 = 0; } range1hit = false; range2hit = false; range3hit = false; range4hit = false; range5hit = false; range6hit = false; } <file_sep>/js/variables.js //all scenes var moveOnDebug = 0; var sensorConnected = false; var noGloves = true; var speedMultiplier = 1.2; var speedRnd1Multiplier = .9; var timeDiv, swoosh; var swooshplaying = false; var AllScenesMPH = 0; var shadow; var centerH = 0; var spacebg; var earthspin; var earthspin_frames = []; var NumstoCallibrateDuringFlight = []; var MovingAverage = 0; var CamSpeed = 0; var scene1 = false; var scene2 = false; var scene3 = false; var scene4 = false; var scene5 = false; var scene6 = false; var scene7 = false; //callibration scene var count = 30; var counter; var cd_3, cd_2, cd_1, cd_fly, game, inst, saveme, bg01, asteroid, scene3header, scene2header, flapTemp, dearEarth, scene5countdown, cappink, capblue; var instscaledown = 300; var colors =[]; var fist, fistinst; var fistx = -100; var fisty = 200; //scene2 var Scn2_frames = []; var Scn2frmct = 0; var showbatterysign = true; //scene3 var readyforschool = false; var totalParticles = 12; //number of total particles var arrayOfBalls = []; //empty array to be filled var arrayOfLines = []; var flightschool1; var flap1type, flap2type; var FlightSchoolSign; var cloud; var Allclouds = []; var cloudMovex = 0; var Scn3_frmct = 0; var scene3A = true; var scene3B = false; //scene4var var squeezeFistGifX = 200, squeezeFistGifY = 500; var asteroidHit; var flythroughX = -100, flythroughY = 500; var scene4Script; var Scn4_textcounter = -30; var index = 0; var lastCue = 0; var Scn4_frmct = 0; var words = []; var timings = [90, 120, 160, 200, 220, 230, 235, 240, 260]; var transcript, currentText; var earthSpinFrames = 26; var flysmall; var flyingOrbitRate = 0; var dearEarthScript; var totalgameframes = 720; var game_frames = []; var totalScn2frames = 325; var aspect = 1920 / 1080; var aftercape, TotalSeconds; var playSecondVid = false; var instructionsready = false; var strokevar = 1; var singlestar = []; var savmeplaying = false; var bgplaying = false; var dearEarthplaying = false; //astroid var ast_x = -100; var ast_y = -100; var ast_size = 766; var scene3counter = 0; var totalstars = 20; //FFParticle var particles = []; var flyingSize = 100; var ffcenterX = 900; var ffcenterY = 300; var angle = 0; var firstround = true; var orbitRadius = 250; var switchAstMove = false; // scene5var var mountains = []; var texture; var trees = []; var gameSongs = []; var songpicker; var gameSongIsPlaying = false; var videoInput, oneSnap; var photoIndex = 0; var takePhotoBurst, loopPhotos = 0; var photoBurst = []; var decreasemult = 2.6; var camspeedmax = 25; var camY = 0; var webGLRenderer; var gameoverclock = 0; var readGameOver = false; var fuckthis = false; var clockB = 30; //### var countdownIdB = 0; var Countfrom30 = parseInt(30); var seaofMonsters; var turbo = false; var turbo_frames = []; var turboFrameNum = 0; var turboTotalFrames = 30; var currentframe = 0; var Scn5_frmct = 0; var transitionCounter = 0; var gameTimeSecInterval; // var secondMarkerGame = 30; //change this to 30 $$$$ var sliderTempCamMove; var scene, camera, renderer; var camZ = 30000; var torusY = 40; torusMesh = []; var cubeBs = []; var allRainbows = []; var Allclouds = []; var moveforwardRate = 0; //if 16...it will go 28,800 px is 30 sec var sun, earth, building; var bgcolor; var gmapped = 0; var rmapped = 0; var bmapped = 0; var light2; var r, g, b; var keepgoing01; // var sliderTemp; var UserArmNum = 500; var range1hit = false; range2hit = false, range3hit = false, range4hit = false, range5hit = false, range6hit = false, range1 = 0, range2 = 0, range3 = 0, range4 = 0, range5 = 0; range6 = 0; var t = 0; var text1a, text1b, text2a, text3a, text3b; var stars; var numStars = 10; var cloud; //scene6var //photobooth var cheersSongIsPlaying = false; var cheers = []; var scn6BGsprite = []; //all jitter objects go in here var spriteLibrary = []; //png sequence var spriteAssets = []; var sprite1Total = 58; var roveBothax, roveBothay, roveBothbx, roveBothby, wiggleaway, scn6Bgsprites; var randomScene6bg = 1; var canvas, capture, mycam, button, img; var newspaperImage, newspaperImage3; var rotateDiv; var Scene6counter = 0; var newspaperRotate = 0; var newspaperscale = 0; retakePhotoRequest = false; // var newspapertempheader; //scene7var callibration var readyforschool; var calimgX, calimgY; var calibrationStillGoing = true; var calibrateSteadyType; var callibrationImage; var callibrationHeader, callibrationExplainer; var sliderTemp; //the sensor will replace this later var restingNumbers = []; var isCallibrationReady = []; var NumstoCallibrate = []; var gd; var distanceofvalues = 0; var distanceofvaluesFlying = 0; var averageValpreCal = 0; var sum = 0; var callibrationPreStage = true; var callibrationStage = false; var calibrateFinal = false; var calibrationHeader; var sceneNextScene = false; var timer; var CallibratedRestingNum = 0; var callibrationCountdown = 3; var calcountdown; var UserArmOutNum = 0; //serial var newDataZ = newDataX = newDataY = 0; var xPos = 0; var loadingOvervid; var CapeCalibrationSign; var cc; var isccplaying = false; var transitionToStory = []; var trans; var readyfortrans; var transitionTicker = 0; //PRE LOAD HAPPENS DURING LOADING SCREEN function preload() { //load sounds for ending cheers[0] = loadSound('audio/cheers1.wav'); cheers[1] = loadSound('audio/cheers2.wav'); cheers[2] = loadSound('audio/cheers3.wav'); cheers[3] = loadSound('audio/cheers4.wav'); cheers[4] = loadSound('audio/cheers5.wav'); gameSong1 = loadSound('audio/game01.mp3'); gameSong2 = loadSound('audio/fuge2.m4a'); gameSong3 = loadSound('audio/dontStopBelieving.wav'); gameSong4 = loadSound('audio/letItHappen.m4a'); gameSong5 = loadSound('audio/DosesAndMimosas.wav'); gameSong6 = loadSound('audio/dontStopMeNow.wav'); gameSong7 = loadSound('audio/dontStopBelieving.wav'); gameSong8 = loadSound('audio/classicxSm.wav'); gameSong9 = loadSound('audio/groupLoveSm.wav'); gameSong0 = loadSound('audio/BeyonceGoSm.wav'); cc = loadSound('assets/cc.wav'); swoosh = loadSound('assets/swoosh2.wav'); bg01 = loadSound('assets/bg01.mp3'); dearEarth = loadSound('assets/DearEarthlings_01.m4a'); cd_3 = loadSound('assets/three.m4a'); cd_2 = loadSound('assets/two.m4a'); cd_1 = loadSound('assets/one.m4a'); cd_fly = loadSound('assets/fly.m4a'); //scene4 audio saveme = loadSound('assets/saveme.m4a'); asteroid = loadImage('assets/asteroid3.png'); //load images for pngs at ending in scene6 sprites for (var i = 0; i < sprite1Total; i++) { //load all the image names if (i < 10) { //for 1 digit ones, add the zero scn6Bgsprites = "assets/flash_0" + i + ".png"; } else { //for 2 digit ones dont scn6Bgsprites = "assets/flash_" + i + ".png"; } spriteLibrary.push(loadImage(scn6Bgsprites)); //push them all into an array //these will be called inside the jitter object } for (var i = 0; i < 13; i++) { //load all the image names trans = "assets/spaceCompressB_" + nf(i, 2) + ".png"; transitionToStory.push(loadImage(trans)); //push them all into an array } for (var i = 0; i < 4; i++) { //load all the image names cloud = "assets/cloud_" + nf(i, 2) + ".png"; Allclouds.push(loadImage(cloud)); //push them all into an array } transcript = loadStrings('assets/script.txt'); for (var i = 0; i < earthSpinFrames; i++) { //load all the image names earthspin = "assets/earthSpin03_" + nf(Math.round(i), 3) + ".png"; earthspin_frames.push(loadImage(earthspin)); //push them all into an array } } /////////PRELOAD ENDS/////// <file_sep>/js/keypressEvents.js // in addition to sensor detection function keyPressed() { if (scene3 === true) { //flightschool if (keyCode == 'J') { // console.log('J'); } if (keyCode === 65 || keyCode === 97) { //A KEY // 'speed == 100mph' $("#flap1").addClass('FlyAway2'); $("#flap2").show(); document.getElementById('targetSpeed').innerHTML = '500'; $("#flap2").addClass('FlyIn3'); for (var i = 0; i < totalParticles; i++) { arrayOfBalls.push(new flapWin1(width / 3, height / 2, width / 2 + random(-width, width), height / 2 + random(-height, height))); //push new particles arrayOfBalls.push(new flapWin2(width / 3, height / 2, width / 2 + random(-width, width), height / 2 + random(-height, height))); //push new particles } } else if (keyCode === 67 || keyCode === 99 || keyCode === ENTER) { //C KEY for (var i = 0; i < totalParticles; i++) { arrayOfBalls.push(new flapWin1(width / 1.6, height / 2, width / 2 + random(-width, width), height / 2 + random(-height, height))); //push new particles arrayOfBalls.push(new flapWin2(width / 1.6, height / 2, width / 2 + random(-width, width), height / 2 + random(-height, height))); //push new particles } readyfortrans = true; } } else if (scene1 === true) { if (keyCode === ENTER) { $('#defaultCanvas0').show(); $('#loadingvideo').hide(); $('#loadingOver').show(); loadingOvervid.play(); $('video#loadingOver').bind('ended', function() { $('#loading').remove(); changeScene(4); }); } } else if (scene7 === true) { if (keyCode === ENTER) { changeScene(3); //flightschool } } else if (scene4 === true) { if (keyCode === ENTER) { // readyfortrans = true; changeScene(7); } } else if (scene5 === true) { //game if (keyCode === ENTER) { changeScene(6); } } else if (scene6 === true) { // if (keyCode === ENTER) { // changeScene(2); // } } else if (scene7 === true) { if (keyCode === ENTER) { changeScene(3); } } } ///KEYPRESS ENDS///////////// <file_sep>/README.md # SuperHero Eve and KC make kids believe that they are superheros
842ac5103c724e75765ea1966e90a26908e497fd
[ "JavaScript", "Markdown" ]
4
JavaScript
evejweinberg/SuperHero
ffab02fe40c78c9a4f70a193a6a15d75ae1f4818
b66711e9f1e51b51e8b545abb24eb478cb1df801
refs/heads/master
<file_sep>package stpdefinition; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; public class case4 { WebDriver driver; @Given("user launches TestMeApp") public void user_launches_TestMeApp() { System.setProperty("webdriver.chrome.driver", "src/main/resources/chromedriver.exe"); driver=new ChromeDriver(); driver.get("http://10.232.237.143:443/TestMeApp/fetchcat.htm"); driver.findElement(By.linkText("SignIn")).click(); } @When("user enters a username") public void user_enters_a_username() { driver.findElement(By.name("userName")).sendKeys("lalitha"); } @When("user enters a pssword") public void user_enters_a_pssword() { driver.findElement(By.name("password")).sendKeys("<PASSWORD>"); } @Then("user clicks on ok") public void user_clicks_on_ok() { driver.findElement(By.cssSelector("input[name='Login'][type='submit']")).click(); } @When("user search for product") public void user_search_for_product() { driver.findElement(By.name("products")).sendKeys("Shopping bag"); } @Then("clicks FIND DETAILS") public void clicks_FIND_DETAILS() { driver.findElement(By.cssSelector("input[value='FIND DETAILS'][type='submit']")).click(); } @When("user clicks Add to cart") public void user_clicks_Add_to_cart() { driver.findElement(By.xpath("/html/body/section/div/div/div[2]/div/div/div/div[2]/center/a")).click(); } @When("user clicks cart") public void user_clicks_cart() { driver.findElement(By.xpath("//*[@href='displayCart.htm']")).click(); } @When("user clicks Checkout") public void user_clicks_Checkout() { driver.findElement(By.xpath("//*[@id='cart']/tfoot/tr[2]/td[5]/a")).click(); } @When("user clicks proceed to pay") public void user_clicks_proceed_to_pay() throws InterruptedException { driver.findElement(By.xpath("//*[@value='Proceed to Pay'][@type='submit']")).click(); Thread.sleep(3000); } @When("user selects bank and clicks continue") public void user_selects_bank_and_clicks_continue() { driver.findElement(By.xpath("//label[contains(text(),'HDFC Bank')]")).click(); driver.findElement(By.xpath("//a[@id='btn']")).click(); } @When("user enters a username and password") public void user_enters_a_username_and_password() { driver.findElement(By.name("username")).sendKeys("lalitha"); driver.findElement(By.name("password")).sendKeys("<PASSWORD>"); } @Then("clicks Login") public void clicks_Login() { driver.findElement(By.cssSelector("input[value='LOGIN'][type='submit']")).click(); } } <file_sep>package stpdefinition; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.Select; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; public class case1 { WebDriver driver; @Given("user launch chrome browser And enters an TestMeApp url") public void user_launch_chrome_browser_And_enters_an_TestMeApp_url() { System.setProperty("webdriver.chrome.driver", "src/main/resources/chromedriver.exe"); driver=new ChromeDriver(); driver.get("http://10.232.237.143:443/TestMeApp/RegisterUser.htm"); } @When("user clicks SignUp") public void user_clicks_SignUp() { } @When("user enters User Name as {string}") public void user_enters_User_Name_as(String s1) { driver.findElement(By.name("userName")).sendKeys(s1); } @When("user enters First Name as {string}") public void user_enters_First_Name_as(String s2) { driver.findElement(By.name("firstName")).sendKeys(s2); } @When("user enters Last Name as {string}") public void user_enters_Last_Name_as(String s3) { driver.findElement(By.name("lastName")).sendKeys(s3); } @When("user enters password as {string}") public void user_enters_password_as(String s4) { driver.findElement(By.xpath("//input[@name='password']")).sendKeys(s4); } @When("user enters confirm password as {string}") public void user_enters_confirm_password_as(String s5) { driver.findElement(By.xpath("//input[@name='confirmPassword']")).sendKeys(s5); } @When("user selects Gender as {string}") public void user_selects_Gender_as(String string) { driver.findElement(By.xpath("//input[@type='radio'][@value='Female']")); } @When("user enters a E-Mail as {string}") public void user_enters_a_E_Mail_as(String s6) { driver.findElement(By.name("emailAddress")).sendKeys(s6); } @When("user enters a mobile number as {string}") public void user_enters_a_mobile_number_as(String s7) { driver.findElement(By.name("mobileNumber")).sendKeys(s7); } @When("user enters a DOB as {string}") public void user_enters_a_DOB_as(String s8) { driver.findElement(By.name("dob")).sendKeys(s8); } @When("user enters a Address as {string}") public void user_enters_a_Address_as(String s9) { driver.findElement(By.name("address")).sendKeys(s9); } @When("user selects a security question as {string}") public void user_selects_a_security_question_as(String string) { Select a=new Select(driver.findElement(By.xpath("//*[@id='securityQuestion']"))); a.selectByIndex(0); } @When("user enters a Answer as {string}") public void user_enters_a_Answer_as(String s10) { driver.findElement(By.name("answer")).sendKeys(s10); } @Then("the user clicks Register") public void the_user_clicks_Register() { driver.findElement(By.xpath("/html/body/main/div/div/form/fieldset/div/div[13]/div/input[1]")).click(); } }
aeae321ac8dc91769e03cf0c9035b5aa103182b7
[ "Java" ]
2
Java
akshayaaishu123456789pooh/Case
a471e739a44a0ea39d3e464f37c174168f4664a8
9d2289e5c28d8b50dcf6b32302495f824b626588
refs/heads/master
<file_sep># Datastore Redirects A tiny flask app to do v1 -> v2 datastore redirects. Based on [this excellent spreadsheet](https://docs.google.com/spreadsheets/d/19Qs6naJhoMIDpgbtNWr2Uab1mzzJge61_vfP4mEYCTs/edit) by [@markbrough](https://twitter.com/Mark_Brough). ## Test it out! Below are examples of requests equivalent in format to those made to the [v1 (old) datastore](http://datastore.iatistandard.org/). The requests are reshaped and redirected to the [v2 (new) datastore](https://store.staging.iati.cloud/). * [/api/1/access/activity.xml?iati-identifier=44000-P090807](https://v1-iati-datastore.herokuapp.com/api/1/access/activity.xml?iati-identifier=44000-P090807) * [/api/1/access/activity.xml?recipient-country=BD](https://v1-iati-datastore.herokuapp.com/api/1/access/activity.xml?recipient-country=BD) * [/api/1/access/activity.xml?reporting-org=GB-GOV-1](https://v1-iati-datastore.herokuapp.com/api/1/access/activity.xml?reporting-org=GB-GOV-1) * [/api/1/access/activity.xml?sector=11110](https://v1-iati-datastore.herokuapp.com/api/1/access/activity.xml?sector=11110) * …etc. All the stuff in [the spreadsheet](https://docs.google.com/spreadsheets/d/19Qs6naJhoMIDpgbtNWr2Uab1mzzJge61_vfP4mEYCTs/edit) should work. ## Installation ```shell $ git clone https://github.com/andylolz/datastore-redirects.git $ cd datastore-redirects $ pipenv install ``` ## Running ```shell $ pipenv run flask run ``` <file_sep>from urllib.parse import urlencode from flask import Flask, request, redirect application = Flask(__name__) @application.route('/api/1/access/activity.xml') def activity(): ''' Returns a redirect to the v2 (new) datastore. Request params are mapped onto OIPA filters. ''' # Current location of v2 (new) datastore base_url = 'https://store.staging.iati.cloud/api/activities/?' # We collect redirect request params here filters = { 'format': 'xml', } # From: https://docs.google.com/spreadsheets/d/19Qs6naJhoMIDpgbtNWr2Uab1mzzJge61_vfP4mEYCTs/edit mappings = { 'iati-identifier': 'iati_identifier', 'recipient-country': 'recipient_country', 'recipient-region': 'recipient_region', 'reporting-org': 'reporting_organisation_identifier', 'reporting-org.type': None, 'sector': 'sector', 'policy-marker': None, 'participating-org': 'participating_organisation', 'participating-org.role': None, 'related-activity': 'related_activity_id', 'transaction': None, 'transaction_provider-org': 'transaction_provider_organisation', 'transaction_provider-org.provider-activity-id': 'transaction_provider_activity', 'transaction_receiver-org': 'transaction_receiver_organisation', 'transaction_receiver-org.receiver-activity-id': 'transaction_receiver_activity', 'start-date__lt': 'actual_start_date_lte', 'start-date__gt': 'actual_start_date_gte', 'end-date__lt': 'actual_end_date_lte', 'end-date__gt': 'actual_end_date_gte', 'last-change__lt': None, 'last-change__gt': None, 'last-updated-datetime__lt': None, 'last-updated-datetime__gt': None, 'registry-dataset': None, } # Check if any unexpected URL params have been used ... unknown_filters = [x for x in request.args.keys() if x not in mappings.keys()] if unknown_filters != []: # ... if so, error return 'Unknown filter(s): {}'.format( ', '.join(unknown_filters)), 400 # Check if any of the undefined mappings have been used ... undefined_mappings = [x for x in request.args.keys() if not mappings.get(x)] if undefined_mappings != []: # ... if so, error return 'Mapping to new filter(s) not known: {}'.format( ', '.join(undefined_mappings)), 400 # Build the redirect request params for old_filter, value in request.args.items(): new_filter = mappings[old_filter] # v2 (new) datastore uses `,` as a separator # for lists of values, whereas # v1 (old) datastore used `|` filters[new_filter] = value.replace('|', ',') # Return the redirect return redirect(base_url + urlencode(filters)) @application.route('/') def home(): ''' Serve the homepage. Very simple - just read and return the contents of index.html ''' with open('index.html') as handler: html = handler.read() return html
26ae13537718f21b01099f59ce2d2fa47f34e940
[ "Markdown", "Python" ]
2
Markdown
andylolz/datastore-redirects
a7cfc8de9ae8533834c4982e0f9901348fa9e9ab
db09432e6a1c5f32de13b6aa6cc5d440eb83c19d
refs/heads/master
<file_sep><?xml version="1.0" encoding="UTF-8"?> <!-- Copyright 2017 The GreyCat Authors. All rights reserved. <p> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at <p> http://www.apache.org/licenses/LICENSE-2.0 <p> 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. --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <artifactId>greycat-websocket</artifactId> <version>4-SNAPSHOT</version> <name>greycat-websocket</name> <properties> <header.path>${basedir}/../../HEADER</header.path> </properties> <parent> <artifactId>greycat-parent</artifactId> <groupId>com.datathings</groupId> <version>4-SNAPSHOT</version> <relativePath>../..</relativePath> </parent> <dependencies> <dependency> <groupId>io.undertow</groupId> <artifactId>undertow-core</artifactId> <version>${undertow.version}</version> </dependency> <dependency> <groupId>com.datathings</groupId> <artifactId>greycat</artifactId> <version>${project.parent.version}</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-antrun-plugin</artifactId> <version>1.8</version> <executions> <execution> <id>compile</id> <phase>compile</phase> <configuration> <target> <copy file="${basedir}/src/main/ts/greycat.ws.ts" todir="${basedir}/target/classes-npm" /> <copy file="${basedir}/src/main/ts/package.json" todir="${basedir}/target/classes-npm" /> <replace file="${basedir}/target/classes-npm/package.json" token="GREYCAT_VERSION" value="${project.version}" /> <replace file="${basedir}/target/classes-npm/package.json" token="J2TS_VERSION" value="${java2typescript.plugin.version}" /> <replace file="${basedir}/target/classes-npm/package.json" token="-SNAPSHOT" value="" /> <copy file="${basedir}/src/main/ts/readme.md" todir="${basedir}/target/classes-npm" /> <exec executable="npm" dir="${basedir}/target/classes-npm" failonerror="true"> <arg value="link" /> <arg value="greycat" /> </exec> <exec executable="npm" dir="${basedir}/target/classes-npm" failonerror="true"> <arg value="install" /> </exec> <exec executable="${basedir}/target/classes-npm/node_modules/typescript/bin/tsc" dir="${basedir}/target/classes-npm" failonerror="true"> <arg value="-d" /> <arg value="--sourceMap" /> <arg value="--target" /> <arg value="es5" /> <arg value="${basedir}/target/classes-npm/greycat.ws.ts" /> </exec> <delete file="${basedir}/target/classes-npm/greycat.ws.ts" /> <exec executable="npm" dir="${basedir}/target/classes-npm" failonerror="true"> <arg value="link" /> </exec> </target> </configuration> <goals> <goal>run</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project> <file_sep>declare module java { module lang { class System { static gc(): void; static arraycopy(src: any[] | Float64Array | Int32Array | Int8Array, srcPos: number, dest: any[] | Float64Array | Int32Array | Int8Array, destPos: number, numElements: number): void; } class StringBuilder { private _buffer; length: number; append(val: any): StringBuilder; insert(position: number, val: any): StringBuilder; toString(): string; } class String { static valueOf(data: any, offset?: number, count?: number): string; static hashCode(str: string): number; static isEmpty(str: string): boolean; static join(delimiter: string, elements: string[]): string; } class Thread { static sleep(time: number): void; } class Double { static MAX_VALUE: number; static POSITIVE_INFINITY: number; static NEGATIVE_INFINITY: number; static NaN: number; } class Long { static parseLong(d: any): number; } class Integer { static parseInt(d: any): number; } } namespace util { namespace concurrent { namespace atomic { class AtomicIntegerArray { _internal: Int32Array; constructor(initialCapacity: number); set(index: number, newVal: number): void; get(index: number): number; getAndSet(index: number, newVal: number): number; compareAndSet(index: number, expect: number, update: number): boolean; } class AtomicLongArray { _internal: Float64Array; constructor(initialCapacity: number); set(index: number, newVal: number): void; get(index: number): number; getAndSet(index: number, newVal: number): number; compareAndSet(index: number, expect: number, update: number): boolean; length(): number; } class AtomicReferenceArray<A> { _internal: Array<A>; constructor(initialCapacity: number); set(index: number, newVal: A): void; get(index: number): A; getAndSet(index: number, newVal: A): A; compareAndSet(index: number, expect: A, update: A): boolean; length(): number; } class AtomicReference<A> { _internal: A; compareAndSet(expect: A, update: A): boolean; get(): A; set(newRef: A): void; getAndSet(newVal: A): A; } class AtomicLong { _internal: number; constructor(init: number); compareAndSet(expect: number, update: number): boolean; get(): number; incrementAndGet(): number; decrementAndGet(): number; } class AtomicBoolean { _internal: boolean; constructor(init: boolean); compareAndSet(expect: boolean, update: boolean): boolean; get(): boolean; set(newVal: boolean): void; } class AtomicInteger { _internal: number; constructor(init: number); compareAndSet(expect: number, update: number): boolean; get(): number; set(newVal: number): void; getAndSet(newVal: number): number; incrementAndGet(): number; decrementAndGet(): number; getAndIncrement(): number; getAndDecrement(): number; } } namespace locks { class ReentrantLock { lock(): void; unlock(): void; } } } class Random { private seed; nextInt(max?: number): number; nextDouble(): number; nextBoolean(): boolean; setSeed(seed: number): void; private nextSeeded(min?, max?); private haveNextNextGaussian; private nextNextGaussian; nextGaussian(): number; } interface Iterator<E> { hasNext(): boolean; next(): E; } class Arrays { static fill(data: any, begin: number, nbElem: number, param: number): void; static copyOf<T>(original: any[], newLength: number, ignore?: any): T[]; } class Collections { static swap(list: List<any>, i: number, j: number): void; } interface Collection<E> { add(val: E): void; addAll(vals: Collection<E>): void; get(index: number): E; remove(o: any): any; clear(): void; isEmpty(): boolean; size(): number; contains(o: E): boolean; toArray<E>(a: Array<E>): E[]; iterator(): Iterator<E>; containsAll(c: Collection<any>): boolean; addAll(c: Collection<any>): boolean; removeAll(c: Collection<any>): boolean; } interface List<E> extends Collection<E> { add(elem: E): void; add(index: number, elem: E): void; poll(): E; addAll(c: Collection<E>): boolean; addAll(index: number, c: Collection<E>): boolean; get(index: number): E; set(index: number, element: E): E; indexOf(o: E): number; lastIndexOf(o: E): number; remove(index: number): E; } interface Set<E> extends Collection<E> { forEach(f: (e: any) => void): void; } class Itr<E> implements Iterator<E> { cursor: number; lastRet: number; protected list: Collection<E>; constructor(list: Collection<E>); hasNext(): boolean; next(): E; } class HashSet<E> implements Set<E> { private content; add(val: E): void; clear(): void; contains(val: E): boolean; containsAll(elems: Collection<E>): boolean; addAll(vals: Collection<E>): boolean; remove(val: E): boolean; removeAll(): boolean; size(): number; isEmpty(): boolean; toArray<E>(a: Array<E>): E[]; iterator(): Iterator<E>; forEach(f: (e: any) => void): void; get(index: number): E; } class AbstractList<E> implements List<E> { private content; addAll(index: any, vals?: any): boolean; clear(): void; poll(): E; remove(indexOrElem: any): any; removeAll(): boolean; toArray(a: Array<E>): E[]; size(): number; add(index: any, elem?: E): void; get(index: number): E; contains(val: E): boolean; containsAll(elems: Collection<E>): boolean; isEmpty(): boolean; set(index: number, element: E): E; indexOf(element: E): number; lastIndexOf(element: E): number; iterator(): Iterator<E>; } class LinkedList<E> extends AbstractList<E> { } class ArrayList<E> extends AbstractList<E> { } class Stack<E> { content: any[]; pop(): E; push(t: E): void; isEmpty(): boolean; peek(): E; } interface Map<K, V> { get(key: K): V; put(key: K, value: V): V; containsKey(key: K): boolean; remove(key: K): V; keySet(): Set<K>; isEmpty(): boolean; values(): Set<V>; clear(): void; size(): number; } class HashMap<K, V> implements Map<K, V> { private content; get(key: K): V; put(key: K, value: V): V; containsKey(key: K): boolean; remove(key: K): V; keySet(): Set<K>; isEmpty(): boolean; values(): Set<V>; clear(): void; size(): number; } class ConcurrentHashMap<K, V> extends HashMap<K, V> { } } } declare function arrayInstanceOf(arr: any, arg: Function): boolean; declare class Long { private high; private low; private unsigned; private static INT_CACHE; private static UINT_CACHE; private static pow_dbl; private static TWO_PWR_16_DBL; private static TWO_PWR_24_DBL; private static TWO_PWR_32_DBL; private static TWO_PWR_64_DBL; private static TWO_PWR_63_DBL; private static TWO_PWR_24; static ZERO: Long; static UZERO: Long; static ONE: Long; static UONE: Long; static NEG_ONE: Long; static MAX_VALUE: Long; static MAX_UNSIGNED_VALUE: Long; static MIN_VALUE: Long; constructor(low?: number, high?: number, unsigned?: boolean); static isLong(obj: any): boolean; static fromInt(value: number, unsigned?: boolean): Long; static fromNumber(value: number, unsigned?: boolean): Long; static fromBits(lowBits?: number, highBits?: number, unsigned?: boolean): Long; static fromString(str: string, radix?: number, unsigned?: boolean): Long; static fromValue(val: any): Long; toInt(): number; toNumber(): number; toString(radix: number): string; getHighBits(): number; getHighBitsUnsigned(): number; getLowBits(): number; getLowBitsUnsigned(): number; getNumBitsAbs(): number; isZero(): boolean; isNegative(): boolean; isPositive(): boolean; isOdd(): boolean; isEven(): boolean; equals(other: any): boolean; eq: (other: any) => boolean; notEquals(other: any): boolean; neq: (other: any) => boolean; lessThan(other: any): boolean; lt: (other: any) => boolean; lessThanOrEqual(other: any): boolean; lte: (other: any) => boolean; greaterThan(other: any): boolean; gt: (other: any) => boolean; greaterThanOrEqual(other: any): boolean; gte: (other: any) => boolean; compare(other: any): number; comp: (other: any) => number; negate(): Long; neg: () => Long; add(addend: any): Long; subtract(subtrahend: any): Long; sub: (subtrahend: any) => Long; multiply(multiplier: any): Long; mul: (multiplier: any) => Long; divide(divisor: any): Long; div: (divisor: any) => Long; modulo(divisor: any): Long; mod: (divisor: any) => Long; not(): Long; and(other: any): Long; or(other: any): Long; xor(other: any): Long; shiftLeft(numBits: any): Long; shl: (numBits: any) => Long; shiftRight(numBits: any): Long; shr: (numBits: any) => Long; shiftRightUnsigned(numBits: any): Long; shru: (numBits: any) => Long; toSigned(): Long; toUnsigned(): Long; } declare module greycat { interface Action { eval(ctx: greycat.TaskContext): void; serialize(builder: java.lang.StringBuilder): void; } interface ActionFunction { (ctx: greycat.TaskContext): void; } interface Callback<A> { (result: A): void; } interface ConditionalFunction { (ctx: greycat.TaskContext): boolean; } class Constants { static KEY_SIZE: number; static LONG_SIZE: number; static PREFIX_SIZE: number; static BEGINNING_OF_TIME: number; static END_OF_TIME: number; static NULL_LONG: number; static KEY_PREFIX_MASK: number; static CACHE_MISS_ERROR: string; static TASK_PARAM_SEP: string; static TASK_SEP: string; static TASK_PARAM_OPEN: string; static TASK_PARAM_CLOSE: string; static SUB_TASK_OPEN: string; static SUB_TASK_CLOSE: string; static SUB_TASK_DECLR: string; static CHUNK_SEP: number; static CHUNK_ENODE_SEP: number; static CHUNK_ESEP: number; static CHUNK_VAL_SEP: number; static BUFFER_SEP: number; static KEY_SEP: number; static MAP_INITIAL_CAPACITY: number; static BOOL_TRUE: number; static BOOL_FALSE: number; static DEEP_WORLD: boolean; static WIDE_WORLD: boolean; static isDefined(param: any): boolean; static equals(src: string, other: string): boolean; static longArrayEquals(src: Float64Array, other: Float64Array): boolean; } interface DeferCounter { count(): void; getCount(): number; then(job: greycat.plugin.Job): void; wrap(): greycat.Callback<any>; } interface DeferCounterSync extends greycat.DeferCounter { waitResult(): any; } interface Graph { newNode(world: number, time: number): greycat.Node; newTypedNode(world: number, time: number, nodeType: string): greycat.Node; cloneNode(origin: greycat.Node): greycat.Node; lookup<A extends greycat.Node>(world: number, time: number, id: number, callback: greycat.Callback<A>): void; lookupBatch(worlds: Float64Array, times: Float64Array, ids: Float64Array, callback: greycat.Callback<greycat.Node[]>): void; lookupAll(world: number, time: number, ids: Float64Array, callback: greycat.Callback<greycat.Node[]>): void; lookupTimes(world: number, from: number, to: number, id: number, callback: greycat.Callback<greycat.Node[]>): void; lookupAllTimes(world: number, from: number, to: number, ids: Float64Array, callback: greycat.Callback<greycat.Node[]>): void; fork(world: number): number; save(callback: greycat.Callback<boolean>): void; connect(callback: greycat.Callback<boolean>): void; disconnect(callback: greycat.Callback<boolean>): void; index(world: number, time: number, name: string, callback: greycat.Callback<greycat.NodeIndex>): void; indexIfExists(world: number, time: number, name: string, callback: greycat.Callback<greycat.NodeIndex>): void; indexNames(world: number, time: number, callback: greycat.Callback<string[]>): void; newCounter(expectedEventsCount: number): greycat.DeferCounter; newSyncCounter(expectedEventsCount: number): greycat.DeferCounterSync; resolver(): greycat.plugin.Resolver; scheduler(): greycat.plugin.Scheduler; space(): greycat.chunk.ChunkSpace; storage(): greycat.plugin.Storage; newBuffer(): greycat.struct.Buffer; newQuery(): greycat.Query; freeNodes(nodes: greycat.Node[]): void; taskHooks(): greycat.TaskHook[]; actionRegistry(): greycat.plugin.ActionRegistry; nodeRegistry(): greycat.plugin.NodeRegistry; setMemoryFactory(factory: greycat.plugin.MemoryFactory): greycat.Graph; addGlobalTaskHook(taskHook: greycat.TaskHook): greycat.Graph; } class GraphBuilder { private _storage; private _scheduler; private _plugins; private _memorySize; private _readOnly; private _deepPriority; static newBuilder(): greycat.GraphBuilder; withStorage(storage: greycat.plugin.Storage): greycat.GraphBuilder; withReadOnlyStorage(storage: greycat.plugin.Storage): greycat.GraphBuilder; withMemorySize(numberOfElements: number): greycat.GraphBuilder; withScheduler(scheduler: greycat.plugin.Scheduler): greycat.GraphBuilder; withPlugin(plugin: greycat.plugin.Plugin): greycat.GraphBuilder; withDeepWorld(): greycat.GraphBuilder; withWideWorld(): greycat.GraphBuilder; build(): greycat.Graph; } interface Node { world(): number; time(): number; id(): number; get(name: string): any; getAt(index: number): any; type(name: string): number; typeAt(index: number): number; nodeTypeName(): string; set(name: string, type: number, value: any): greycat.Node; setAt(index: number, type: number, value: any): greycat.Node; forceSet(name: string, type: number, value: any): greycat.Node; forceSetAt(index: number, type: number, value: any): greycat.Node; remove(name: string): greycat.Node; removeAt(index: number): greycat.Node; getOrCreate(name: string, type: number): any; getOrCreateAt(index: number, type: number): any; relation(relationName: string, callback: greycat.Callback<greycat.Node[]>): void; relationAt(relationIndex: number, callback: greycat.Callback<greycat.Node[]>): void; addToRelation(relationName: string, relatedNode: greycat.Node, ...indexedAttributes: string[]): greycat.Node; addToRelationAt(relationIndex: number, relatedNode: greycat.Node, ...indexedAttributes: string[]): greycat.Node; removeFromRelation(relationName: string, relatedNode: greycat.Node, ...indexedAttributes: string[]): greycat.Node; removeFromRelationAt(relationIndex: number, relatedNode: greycat.Node, ...indexedAttributes: string[]): greycat.Node; timeDephasing(): number; lastModification(): number; rephase(): greycat.Node; timepoints(beginningOfSearch: number, endOfSearch: number, callback: greycat.Callback<Float64Array>): void; free(): void; graph(): greycat.Graph; travelInTime<A extends greycat.Node>(targetTime: number, callback: greycat.Callback<A>): void; setTimeSensitivity(deltaTime: number, offset: number): greycat.Node; timeSensitivity(): Float64Array; } interface NodeIndex extends greycat.Node { size(): number; all(): Float64Array; addToIndex(node: greycat.Node, ...attributeNames: string[]): greycat.NodeIndex; removeFromIndex(node: greycat.Node, ...attributeNames: string[]): greycat.NodeIndex; clear(): greycat.NodeIndex; find(callback: greycat.Callback<greycat.Node[]>, ...params: string[]): void; findByQuery(query: greycat.Query, callback: greycat.Callback<greycat.Node[]>): void; } interface Query { world(): number; setWorld(world: number): greycat.Query; time(): number; setTime(time: number): greycat.Query; add(attributeName: string, value: string): greycat.Query; hash(): number; attributes(): Int32Array; values(): any[]; } interface Task { then(nextAction: greycat.Action): greycat.Task; thenDo(nextActionFunction: greycat.ActionFunction): greycat.Task; doWhile(task: greycat.Task, cond: greycat.ConditionalFunction): greycat.Task; doWhileScript(task: greycat.Task, condScript: string): greycat.Task; loop(from: string, to: string, subTask: greycat.Task): greycat.Task; loopPar(from: string, to: string, subTask: greycat.Task): greycat.Task; forEach(subTask: greycat.Task): greycat.Task; forEachPar(subTask: greycat.Task): greycat.Task; flat(): greycat.Task; map(subTask: greycat.Task): greycat.Task; mapPar(subTask: greycat.Task): greycat.Task; ifThen(cond: greycat.ConditionalFunction, then: greycat.Task): greycat.Task; ifThenScript(condScript: string, then: greycat.Task): greycat.Task; ifThenElse(cond: greycat.ConditionalFunction, thenSub: greycat.Task, elseSub: greycat.Task): greycat.Task; ifThenElseScript(condScript: string, thenSub: greycat.Task, elseSub: greycat.Task): greycat.Task; whileDo(cond: greycat.ConditionalFunction, task: greycat.Task): greycat.Task; whileDoScript(condScript: string, task: greycat.Task): greycat.Task; pipe(...subTasks: greycat.Task[]): greycat.Task; pipePar(...subTasks: greycat.Task[]): greycat.Task; pipeTo(subTask: greycat.Task, ...vars: string[]): greycat.Task; parse(input: string, graph: greycat.Graph): greycat.Task; loadFromBuffer(buffer: greycat.struct.Buffer, graph: greycat.Graph): greycat.Task; saveToBuffer(buffer: greycat.struct.Buffer): greycat.Task; addHook(hook: greycat.TaskHook): greycat.Task; execute(graph: greycat.Graph, callback: greycat.Callback<greycat.TaskResult<any>>): void; executeSync(graph: greycat.Graph): greycat.TaskResult<any>; executeWith(graph: greycat.Graph, initial: any, callback: greycat.Callback<greycat.TaskResult<any>>): void; prepare(graph: greycat.Graph, initial: any, callback: greycat.Callback<greycat.TaskResult<any>>): greycat.TaskContext; executeUsing(preparedContext: greycat.TaskContext): void; executeFrom(parentContext: greycat.TaskContext, initial: greycat.TaskResult<any>, affinity: number, callback: greycat.Callback<greycat.TaskResult<any>>): void; executeFromUsing(parentContext: greycat.TaskContext, initial: greycat.TaskResult<any>, affinity: number, contextInitializer: greycat.Callback<greycat.TaskContext>, callback: greycat.Callback<greycat.TaskResult<any>>): void; travelInWorld(world: string): greycat.Task; travelInTime(time: string): greycat.Task; inject(input: any): greycat.Task; defineAsGlobalVar(name: string): greycat.Task; defineAsVar(name: string): greycat.Task; declareGlobalVar(name: string): greycat.Task; declareVar(name: string): greycat.Task; readVar(name: string): greycat.Task; setAsVar(name: string): greycat.Task; addToVar(name: string): greycat.Task; setAttribute(name: string, type: number, value: string): greycat.Task; timeSensitivity(delta: string, offset: string): greycat.Task; forceAttribute(name: string, type: number, value: string): greycat.Task; remove(name: string): greycat.Task; attributes(): greycat.Task; timepoints(from: string, to: string): greycat.Task; attributesWithType(filterType: number): greycat.Task; addVarToRelation(relName: string, varName: string, ...attributes: string[]): greycat.Task; removeVarFromRelation(relName: string, varFrom: string, ...attributes: string[]): greycat.Task; traverse(name: string, ...params: string[]): greycat.Task; attribute(name: string, ...params: string[]): greycat.Task; readGlobalIndex(indexName: string, ...query: string[]): greycat.Task; globalIndex(indexName: string): greycat.Task; addToGlobalIndex(name: string, ...attributes: string[]): greycat.Task; addToGlobalTimedIndex(name: string, ...attributes: string[]): greycat.Task; removeFromGlobalIndex(name: string, ...attributes: string[]): greycat.Task; removeFromGlobalTimedIndex(name: string, ...attributes: string[]): greycat.Task; indexNames(): greycat.Task; selectWith(name: string, pattern: string): greycat.Task; selectWithout(name: string, pattern: string): greycat.Task; select(filterFunction: greycat.TaskFunctionSelect): greycat.Task; selectScript(script: string): greycat.Task; selectObject(filterFunction: greycat.TaskFunctionSelectObject): greycat.Task; log(name: string): greycat.Task; print(name: string): greycat.Task; println(name: string): greycat.Task; executeExpression(expression: string): greycat.Task; createNode(): greycat.Task; createTypedNode(type: string): greycat.Task; save(): greycat.Task; script(script: string): greycat.Task; asyncScript(ascript: string): greycat.Task; lookup(nodeId: string): greycat.Task; lookupAll(nodeIds: string): greycat.Task; clearResult(): greycat.Task; action(name: string, ...params: string[]): greycat.Task; flipVar(name: string): greycat.Task; atomic(protectedTask: greycat.Task, ...variablesToLock: string[]): greycat.Task; } interface TaskContext { graph(): greycat.Graph; world(): number; setWorld(world: number): greycat.TaskContext; time(): number; setTime(time: number): greycat.TaskContext; variables(): greycat.utility.Tuple<string, greycat.TaskResult<any>>[]; variable(name: string): greycat.TaskResult<any>; isGlobal(name: string): boolean; wrap(input: any): greycat.TaskResult<any>; wrapClone(input: any): greycat.TaskResult<any>; newResult(): greycat.TaskResult<any>; declareVariable(name: string): greycat.TaskContext; defineVariable(name: string, initialResult: any): greycat.TaskContext; defineVariableForSubTask(name: string, initialResult: any): greycat.TaskContext; setGlobalVariable(name: string, value: any): greycat.TaskContext; setVariable(name: string, value: any): greycat.TaskContext; addToGlobalVariable(name: string, value: any): greycat.TaskContext; addToVariable(name: string, value: any): greycat.TaskContext; result(): greycat.TaskResult<any>; resultAsNodes(): greycat.TaskResult<greycat.Node>; resultAsStrings(): greycat.TaskResult<string>; continueTask(): void; continueWith(nextResult: greycat.TaskResult<any>): void; endTask(nextResult: greycat.TaskResult<any>, e: Error): void; template(input: string): string; templates(inputs: string[]): string[]; append(additionalOutput: string): void; } interface TaskFunctionSelect { (node: greycat.Node, context: greycat.TaskContext): boolean; } interface TaskFunctionSelectObject { (object: any, context: greycat.TaskContext): boolean; } interface TaskHook { start(initialContext: greycat.TaskContext): void; beforeAction(action: greycat.Action, context: greycat.TaskContext): void; afterAction(action: greycat.Action, context: greycat.TaskContext): void; beforeTask(parentContext: greycat.TaskContext, context: greycat.TaskContext): void; afterTask(context: greycat.TaskContext): void; end(finalContext: greycat.TaskContext): void; } interface TaskResult<A> { iterator(): greycat.TaskResultIterator<any>; get(index: number): A; set(index: number, input: A): greycat.TaskResult<A>; allocate(index: number): greycat.TaskResult<A>; add(input: A): greycat.TaskResult<A>; clear(): greycat.TaskResult<A>; clone(): greycat.TaskResult<A>; free(): void; size(): number; asArray(): any[]; exception(): Error; output(): string; setException(e: Error): greycat.TaskResult<A>; setOutput(output: string): greycat.TaskResult<A>; fillWith(source: greycat.TaskResult<A>): greycat.TaskResult<A>; } interface TaskResultIterator<A> { next(): A; nextWithIndex(): greycat.utility.Tuple<number, A>; } class Tasks { static cond(mathExpression: string): greycat.ConditionalFunction; static newTask(): greycat.Task; static emptyResult(): greycat.TaskResult<any>; static then(action: greycat.Action): greycat.Task; static thenDo(actionFunction: greycat.ActionFunction): greycat.Task; static loop(from: string, to: string, subTask: greycat.Task): greycat.Task; static loopPar(from: string, to: string, subTask: greycat.Task): greycat.Task; static forEach(subTask: greycat.Task): greycat.Task; static forEachPar(subTask: greycat.Task): greycat.Task; static map(subTask: greycat.Task): greycat.Task; static mapPar(subTask: greycat.Task): greycat.Task; static ifThen(cond: greycat.ConditionalFunction, then: greycat.Task): greycat.Task; static ifThenScript(condScript: string, then: greycat.Task): greycat.Task; static ifThenElse(cond: greycat.ConditionalFunction, thenSub: greycat.Task, elseSub: greycat.Task): greycat.Task; static ifThenElseScript(condScript: string, thenSub: greycat.Task, elseSub: greycat.Task): greycat.Task; static doWhile(task: greycat.Task, cond: greycat.ConditionalFunction): greycat.Task; static doWhileScript(task: greycat.Task, condScript: string): greycat.Task; static whileDo(cond: greycat.ConditionalFunction, task: greycat.Task): greycat.Task; static whileDoScript(condScript: string, task: greycat.Task): greycat.Task; static pipe(...subTasks: greycat.Task[]): greycat.Task; static pipePar(...subTasks: greycat.Task[]): greycat.Task; static pipeTo(subTask: greycat.Task, ...vars: string[]): greycat.Task; static atomic(protectedTask: greycat.Task, ...variablesToLock: string[]): greycat.Task; static parse(flat: string, graph: greycat.Graph): greycat.Task; } class Type { static BOOL: number; static STRING: number; static LONG: number; static INT: number; static DOUBLE: number; static DOUBLE_ARRAY: number; static LONG_ARRAY: number; static INT_ARRAY: number; static STRING_ARRAY: number; static LONG_TO_LONG_MAP: number; static LONG_TO_LONG_ARRAY_MAP: number; static STRING_TO_INT_MAP: number; static RELATION: number; static RELATION_INDEXED: number; static DMATRIX: number; static LMATRIX: number; static EGRAPH: number; static ENODE: number; static ERELATION: number; static TASK: number; static TASK_ARRAY: number; static KDTREE: number; static NDTREE: number; static typeName(p_type: number): string; static typeFromName(name: string): number; } module base { class BaseHook implements greycat.TaskHook { start(initialContext: greycat.TaskContext): void; beforeAction(action: greycat.Action, context: greycat.TaskContext): void; afterAction(action: greycat.Action, context: greycat.TaskContext): void; beforeTask(parentContext: greycat.TaskContext, context: greycat.TaskContext): void; afterTask(context: greycat.TaskContext): void; end(finalContext: greycat.TaskContext): void; } class BaseNode implements greycat.Node { private _world; private _time; private _id; private _graph; _resolver: greycat.plugin.Resolver; _index_worldOrder: number; _index_superTimeTree: number; _index_timeTree: number; _index_stateChunk: number; _world_magic: number; _super_time_magic: number; _time_magic: number; _dead: boolean; private _lock; constructor(p_world: number, p_time: number, p_id: number, p_graph: greycat.Graph); cacheLock(): void; cacheUnlock(): void; init(): void; nodeTypeName(): string; unphasedState(): greycat.plugin.NodeState; phasedState(): greycat.plugin.NodeState; newState(time: number): greycat.plugin.NodeState; graph(): greycat.Graph; world(): number; time(): number; id(): number; get(name: string): any; getAt(propIndex: number): any; forceSet(name: string, type: number, value: any): greycat.Node; forceSetAt(index: number, type: number, value: any): greycat.Node; setAt(index: number, type: number, value: any): greycat.Node; set(name: string, type: number, value: any): greycat.Node; private isEquals(obj1, obj2, type); getOrCreate(name: string, type: number): any; getOrCreateAt(index: number, type: number): any; type(name: string): number; typeAt(index: number): number; remove(name: string): greycat.Node; removeAt(index: number): greycat.Node; relation(relationName: string, callback: greycat.Callback<greycat.Node[]>): void; relationAt(relationIndex: number, callback: greycat.Callback<greycat.Node[]>): void; addToRelation(relationName: string, relatedNode: greycat.Node, ...attributes: string[]): greycat.Node; addToRelationAt(relationIndex: number, relatedNode: greycat.Node, ...attributes: string[]): greycat.Node; removeFromRelation(relationName: string, relatedNode: greycat.Node, ...attributes: string[]): greycat.Node; removeFromRelationAt(relationIndex: number, relatedNode: greycat.Node, ...attributes: string[]): greycat.Node; free(): void; timeDephasing(): number; lastModification(): number; rephase(): greycat.Node; timepoints(beginningOfSearch: number, endOfSearch: number, callback: greycat.Callback<Float64Array>): void; travelInTime<A extends greycat.Node>(targetTime: number, callback: greycat.Callback<A>): void; setTimeSensitivity(deltaTime: number, offset: number): greycat.Node; timeSensitivity(): Float64Array; static isNaN(toTest: number): boolean; toString(): string; } class BaseTaskResult<A> implements greycat.TaskResult<A> { private _backend; private _capacity; private _size; _exception: Error; _output: string; asArray(): any[]; exception(): Error; output(): string; setException(e: Error): greycat.TaskResult<A>; setOutput(output: string): greycat.TaskResult<A>; fillWith(source: greycat.TaskResult<A>): greycat.TaskResult<A>; constructor(toWrap: any, protect: boolean); iterator(): greycat.TaskResultIterator<any>; get(index: number): A; set(index: number, input: A): greycat.TaskResult<A>; allocate(index: number): greycat.TaskResult<A>; add(input: A): greycat.TaskResult<A>; clear(): greycat.TaskResult<A>; clone(): greycat.TaskResult<A>; free(): void; size(): number; private extendTil(index); toString(): string; private toJson(withContent); } class BaseTaskResultIterator<A> implements greycat.TaskResultIterator<A> { private _backend; private _size; private _current; constructor(p_backend: any[]); next(): A; nextWithIndex(): greycat.utility.Tuple<number, A>; } } module chunk { interface Chunk { world(): number; time(): number; id(): number; chunkType(): number; index(): number; save(buffer: greycat.struct.Buffer): void; saveDiff(buffer: greycat.struct.Buffer): void; load(buffer: greycat.struct.Buffer): void; loadDiff(buffer: greycat.struct.Buffer): void; } interface ChunkSpace { createAndMark(type: number, world: number, time: number, id: number): greycat.chunk.Chunk; getAndMark(type: number, world: number, time: number, id: number): greycat.chunk.Chunk; getOrLoadAndMark(type: number, world: number, time: number, id: number, callback: greycat.Callback<greycat.chunk.Chunk>): void; getOrLoadAndMarkAll(keys: Float64Array, callback: greycat.Callback<greycat.chunk.Chunk[]>): void; get(index: number): greycat.chunk.Chunk; unmark(index: number): void; mark(index: number): number; free(chunk: greycat.chunk.Chunk): void; notifyUpdate(index: number): void; graph(): greycat.Graph; save(callback: greycat.Callback<boolean>): void; clear(): void; freeAll(): void; available(): number; newVolatileGraph(): greycat.struct.EGraph; } class ChunkType { static STATE_CHUNK: number; static TIME_TREE_CHUNK: number; static WORLD_ORDER_CHUNK: number; static GEN_CHUNK: number; } interface GenChunk extends greycat.chunk.Chunk { newKey(): number; } interface Stack { enqueue(index: number): boolean; dequeueTail(): number; dequeue(index: number): boolean; free(): void; size(): number; } interface StateChunk extends greycat.chunk.Chunk, greycat.plugin.NodeState { loadFrom(origin: greycat.chunk.StateChunk): void; } interface TimeTreeChunk extends greycat.chunk.Chunk { insert(key: number): void; unsafe_insert(key: number): void; previousOrEqual(key: number): number; clearAt(max: number): void; range(startKey: number, endKey: number, maxElements: number, walker: greycat.chunk.TreeWalker): void; magic(): number; previous(key: number): number; next(key: number): number; size(): number; extra(): number; setExtra(extraValue: number): void; extra2(): number; setExtra2(extraValue: number): void; } interface TreeWalker { (t: number): void; } interface WorldOrderChunk extends greycat.chunk.Chunk, greycat.struct.LongLongMap { magic(): number; lock(): void; unlock(): void; externalLock(): void; externalUnlock(): void; extra(): number; setExtra(extraValue: number): void; } } module internal { class BlackHoleStorage implements greycat.plugin.Storage { private _graph; private prefix; get(keys: greycat.struct.Buffer, callback: greycat.Callback<greycat.struct.Buffer>): void; put(stream: greycat.struct.Buffer, callback: greycat.Callback<boolean>): void; remove(keys: greycat.struct.Buffer, callback: greycat.Callback<boolean>): void; connect(graph: greycat.Graph, callback: greycat.Callback<boolean>): void; lock(callback: greycat.Callback<greycat.struct.Buffer>): void; unlock(previousLock: greycat.struct.Buffer, callback: greycat.Callback<boolean>): void; disconnect(callback: greycat.Callback<boolean>): void; } class CoreConstants extends greycat.Constants { static PREFIX_TO_SAVE_SIZE: number; static NULL_KEY: Float64Array; static GLOBAL_UNIVERSE_KEY: Float64Array; static GLOBAL_DICTIONARY_KEY: Float64Array; static GLOBAL_INDEX_KEY: Float64Array; static INDEX_ATTRIBUTE: string; static DISCONNECTED_ERROR: string; static SCALE_1: number; static SCALE_2: number; static SCALE_3: number; static SCALE_4: number; static DEAD_NODE_ERROR: string; static fillBooleanArray(target: boolean[], elem: boolean): void; } class CoreDeferCounter implements greycat.DeferCounter { private _nb_down; private _counter; private _end; constructor(nb: number); count(): void; getCount(): number; then(p_callback: greycat.plugin.Job): void; wrap(): greycat.Callback<any>; } class CoreDeferCounterSync implements greycat.DeferCounterSync { private _nb_down; private _counter; private _end; private _result; constructor(nb: number); count(): void; getCount(): number; then(p_callback: greycat.plugin.Job): void; wrap(): greycat.Callback<any>; waitResult(): any; } class CoreGraph implements greycat.Graph { private _storage; private _space; private _scheduler; private _resolver; private _isConnected; private _lock; private _plugins; private _prefix; private _nodeKeyCalculator; private _worldKeyCalculator; private _actionRegistry; private _nodeRegistry; private _memoryFactory; private _taskHooks; constructor(p_storage: greycat.plugin.Storage, memorySize: number, p_scheduler: greycat.plugin.Scheduler, p_plugins: greycat.plugin.Plugin[], deepPriority: boolean); fork(world: number): number; newNode(world: number, time: number): greycat.Node; newTypedNode(world: number, time: number, nodeType: string): greycat.Node; cloneNode(origin: greycat.Node): greycat.Node; factoryByCode(code: number): greycat.plugin.NodeFactory; taskHooks(): greycat.TaskHook[]; actionRegistry(): greycat.plugin.ActionRegistry; nodeRegistry(): greycat.plugin.NodeRegistry; setMemoryFactory(factory: greycat.plugin.MemoryFactory): greycat.Graph; addGlobalTaskHook(newTaskHook: greycat.TaskHook): greycat.Graph; lookup<A extends greycat.Node>(world: number, time: number, id: number, callback: greycat.Callback<A>): void; lookupBatch(worlds: Float64Array, times: Float64Array, ids: Float64Array, callback: greycat.Callback<greycat.Node[]>): void; lookupAll(world: number, time: number, ids: Float64Array, callback: greycat.Callback<greycat.Node[]>): void; lookupTimes(world: number, from: number, to: number, id: number, callback: greycat.Callback<greycat.Node[]>): void; lookupAllTimes(world: number, from: number, to: number, ids: Float64Array, callback: greycat.Callback<greycat.Node[]>): void; save(callback: greycat.Callback<boolean>): void; connect(callback: greycat.Callback<boolean>): void; disconnect(callback: greycat.Callback<any>): void; newBuffer(): greycat.struct.Buffer; newQuery(): greycat.Query; index(world: number, time: number, name: string, callback: greycat.Callback<greycat.NodeIndex>): void; indexIfExists(world: number, time: number, name: string, callback: greycat.Callback<greycat.NodeIndex>): void; private internal_index(world, time, name, ifExists, callback); indexNames(world: number, time: number, callback: greycat.Callback<string[]>): void; newCounter(expectedCountCalls: number): greycat.DeferCounter; newSyncCounter(expectedCountCalls: number): greycat.DeferCounterSync; resolver(): greycat.plugin.Resolver; scheduler(): greycat.plugin.Scheduler; space(): greycat.chunk.ChunkSpace; storage(): greycat.plugin.Storage; freeNodes(nodes: greycat.Node[]): void; } class CoreNodeDeclaration implements greycat.plugin.NodeDeclaration { private _name; private _factory; constructor(name: string); name(): string; factory(): greycat.plugin.NodeFactory; setFactory(newFactory: greycat.plugin.NodeFactory): void; } class CoreNodeIndex extends greycat.base.BaseNode implements greycat.NodeIndex { static NAME: string; constructor(p_world: number, p_time: number, p_id: number, p_graph: greycat.Graph); init(): void; size(): number; all(): Float64Array; addToIndex(node: greycat.Node, ...attributeNames: string[]): greycat.NodeIndex; removeFromIndex(node: greycat.Node, ...attributeNames: string[]): greycat.NodeIndex; clear(): greycat.NodeIndex; find(callback: greycat.Callback<greycat.Node[]>, ...query: string[]): void; findByQuery(query: greycat.Query, callback: greycat.Callback<greycat.Node[]>): void; } class CoreNodeRegistry implements greycat.plugin.NodeRegistry { private backend; private backend_hash; constructor(); declaration(name: string): greycat.plugin.NodeDeclaration; declarationByHash(hash: number): greycat.plugin.NodeDeclaration; } class CoreQuery implements greycat.Query { private _resolver; private _graph; private capacity; private _attributes; private _values; private size; private _hash; private _world; private _time; constructor(graph: greycat.Graph, p_resolver: greycat.plugin.Resolver); world(): number; setWorld(p_world: number): greycat.Query; time(): number; setTime(p_time: number): greycat.Query; add(attributeName: string, value: string): greycat.Query; hash(): number; attributes(): Int32Array; values(): any[]; private internal_add(att, val); private compute(); } class MWGResolver implements greycat.plugin.Resolver { private _storage; private _space; private _graph; private dictionary; private globalWorldOrderChunk; private static KEY_SIZE; constructor(p_storage: greycat.plugin.Storage, p_space: greycat.chunk.ChunkSpace, p_graph: greycat.Graph); init(): void; free(): void; typeCode(node: greycat.Node): number; initNode(node: greycat.Node, codeType: number): void; initWorld(parentWorld: number, childWorld: number): void; freeNode(node: greycat.Node): void; externalLock(node: greycat.Node): void; externalUnlock(node: greycat.Node): void; setTimeSensitivity(node: greycat.Node, deltaTime: number, offset: number): void; getTimeSensitivity(node: greycat.Node): Float64Array; lookup<A extends greycat.Node>(world: number, time: number, id: number, callback: greycat.Callback<A>): void; lookupBatch(worlds: Float64Array, times: Float64Array, ids: Float64Array, callback: greycat.Callback<greycat.Node[]>): void; lookupTimes(world: number, from: number, to: number, id: number, callback: greycat.Callback<greycat.Node[]>): void; private lookupAll_end(finalResult, callback, sizeIds, worldOrders, superTimes, times, chunks); lookupAll(world: number, time: number, ids: Float64Array, callback: greycat.Callback<greycat.Node[]>): void; lookupAllTimes(world: number, from: number, to: number, ids: Float64Array, callback: greycat.Callback<greycat.Node[]>): void; private resolve_world(globalWorldOrder, nodeWorldOrder, timeToResolve, originWorld); private getOrLoadAndMarkAll(types, keys, callback); resolveState(node: greycat.Node): greycat.plugin.NodeState; private internal_resolveState(node, safe); alignState(node: greycat.Node): greycat.plugin.NodeState; newState(node: greycat.Node, world: number, time: number): greycat.plugin.NodeState; resolveTimepoints(node: greycat.Node, beginningOfSearch: number, endOfSearch: number, callback: greycat.Callback<Float64Array>): void; private resolveTimepointsFromWorlds(objectWorldOrder, node, beginningOfSearch, endOfSearch, collectedWorlds, collectedWorldsSize, callback); private resolveTimepointsFromSuperTimes(objectWorldOrder, node, beginningOfSearch, endOfSearch, collectedWorlds, collectedSuperTimes, collectedSize, callback); stringToHash(name: string, insertIfNotExists: boolean): number; hashToString(key: number): string; } class ReadOnlyStorage implements greycat.plugin.Storage { private wrapped; constructor(toWrap: greycat.plugin.Storage); get(keys: greycat.struct.Buffer, callback: greycat.Callback<greycat.struct.Buffer>): void; put(stream: greycat.struct.Buffer, callback: greycat.Callback<boolean>): void; remove(keys: greycat.struct.Buffer, callback: greycat.Callback<boolean>): void; connect(graph: greycat.Graph, callback: greycat.Callback<boolean>): void; disconnect(callback: greycat.Callback<boolean>): void; lock(callback: greycat.Callback<greycat.struct.Buffer>): void; unlock(previousLock: greycat.struct.Buffer, callback: greycat.Callback<boolean>): void; } module heap { class HeapAtomicByteArray { private _back; constructor(initialSize: number); get(index: number): number; set(index: number, value: number): void; } class HeapBuffer implements greycat.struct.Buffer { private buffer; private writeCursor; slice(initPos: number, endPos: number): Int8Array; write(b: number): void; private getNewSize(old, target); writeAll(bytes: Int8Array): void; read(position: number): number; data(): Int8Array; length(): number; free(): void; iterator(): greycat.struct.BufferIterator; removeLast(): void; toString(): string; } class HeapChunkSpace implements greycat.chunk.ChunkSpace { private static HASH_LOAD_FACTOR; private _maxEntries; private _hashEntries; private _lru; private _dirtiesStack; private _hashNext; private _hash; private _chunkWorlds; private _chunkTimes; private _chunkIds; private _chunkTypes; private _chunkValues; private _chunkMarks; private _graph; private _deep_priority; graph(): greycat.Graph; worldByIndex(index: number): number; timeByIndex(index: number): number; idByIndex(index: number): number; constructor(initialCapacity: number, p_graph: greycat.Graph, deepWorldPriority: boolean); getAndMark(type: number, world: number, time: number, id: number): greycat.chunk.Chunk; get(index: number): greycat.chunk.Chunk; getOrLoadAndMark(type: number, world: number, time: number, id: number, callback: greycat.Callback<greycat.chunk.Chunk>): void; getOrLoadAndMarkAll(keys: Float64Array, callback: greycat.Callback<greycat.chunk.Chunk[]>): void; mark(index: number): number; unmark(index: number): void; free(chunk: greycat.chunk.Chunk): void; createAndMark(type: number, world: number, time: number, id: number): greycat.chunk.Chunk; notifyUpdate(index: number): void; save(callback: greycat.Callback<boolean>): void; clear(): void; freeAll(): void; available(): number; newVolatileGraph(): greycat.struct.EGraph; printMarked(): void; } interface HeapContainer { declareDirty(): void; } class HeapDMatrix implements greycat.struct.DMatrix { private static INDEX_ROWS; private static INDEX_COLUMNS; private static INDEX_MAX_COLUMN; private static INDEX_OFFSET; private parent; private backend; private aligned; constructor(p_parent: greycat.internal.heap.HeapContainer, origin: greycat.internal.heap.HeapDMatrix); init(rows: number, columns: number): greycat.struct.DMatrix; private internal_init(rows, columns); appendColumn(newColumn: Float64Array): greycat.struct.DMatrix; private internal_appendColumn(newColumn); fill(value: number): greycat.struct.DMatrix; private internal_fill(value); fillWith(values: Float64Array): greycat.struct.DMatrix; private internal_fillWith(values); rows(): number; columns(): number; length(): number; column(index: number): Float64Array; get(rowIndex: number, columnIndex: number): number; set(rowIndex: number, columnIndex: number, value: number): greycat.struct.DMatrix; private internal_set(rowIndex, columnIndex, value); add(rowIndex: number, columnIndex: number, value: number): greycat.struct.DMatrix; private internal_add(rowIndex, columnIndex, value); data(): Float64Array; leadingDimension(): number; unsafeGet(index: number): number; unsafeSet(index: number, value: number): greycat.struct.DMatrix; private internal_unsafeSet(index, value); unsafe_data(): Float64Array; private unsafe_init(size); private unsafe_set(index, value); load(buffer: greycat.struct.Buffer, offset: number, max: number): number; } class HeapEGraph implements greycat.struct.EGraph { private _graph; private parent; _dirty: boolean; _nodes: greycat.internal.heap.HeapENode[]; private _nodes_capacity; private _nodes_index; constructor(p_parent: greycat.internal.heap.HeapContainer, origin: greycat.internal.heap.HeapEGraph, p_graph: greycat.Graph); size(): number; free(): void; graph(): greycat.Graph; private allocate(newCapacity); nodeByIndex(index: number, createIfAbsent: boolean): greycat.internal.heap.HeapENode; declareDirty(): void; newNode(): greycat.struct.ENode; node(nodeIndex: number): greycat.struct.ENode; root(): greycat.struct.ENode; setRoot(eNode: greycat.struct.ENode): greycat.struct.EGraph; drop(eNode: greycat.struct.ENode): greycat.struct.EGraph; toString(): string; load(buffer: greycat.struct.Buffer, offset: number, max: number): number; } class HeapENode implements greycat.struct.ENode, greycat.internal.heap.HeapContainer { private _eGraph; _id: number; private _capacity; private _size; private _k; private _v; private _next_hash; private _type; private _dirty; private static LOAD_WAITING_ALLOC; private static LOAD_WAITING_TYPE; private static LOAD_WAITING_KEY; private static LOAD_WAITING_VALUE; constructor(p_egraph: greycat.internal.heap.HeapEGraph, p_id: number, origin: greycat.internal.heap.HeapENode); clear(): greycat.struct.ENode; declareDirty(): void; rebase(): void; private allocate(newCapacity); private internal_find(p_key); private internal_get(p_key); private internal_set(p_key, p_type, p_unsafe_elem, replaceIfPresent, initial); set(name: string, type: number, value: any): greycat.struct.ENode; setAt(key: number, type: number, value: any): greycat.struct.ENode; get(name: string): any; getAt(key: number): any; getWithDefault<A>(key: string, defaultValue: A): A; getAtWithDefault<A>(key: number, defaultValue: A): A; drop(): void; egraph(): greycat.struct.EGraph; getOrCreate(key: string, type: number): any; getOrCreateAt(key: number, type: number): any; toString(): string; save(buffer: greycat.struct.Buffer): void; load(buffer: greycat.struct.Buffer, currentCursor: number, graph: greycat.Graph): number; private load_primitive(read_key, read_type, buffer, previous, cursor, initial); each(callBack: greycat.plugin.NodeStateCallback): void; } class HeapERelation implements greycat.struct.ERelation { private _back; private _size; private _capacity; private parent; constructor(p_parent: greycat.internal.heap.HeapContainer, origin: greycat.internal.heap.HeapERelation); rebase(newGraph: greycat.internal.heap.HeapEGraph): void; size(): number; nodes(): greycat.struct.ENode[]; node(index: number): greycat.struct.ENode; add(eNode: greycat.struct.ENode): greycat.struct.ERelation; addAll(eNodes: greycat.struct.ENode[]): greycat.struct.ERelation; clear(): greycat.struct.ERelation; toString(): string; allocate(newCapacity: number): void; } class HeapFixedStack implements greycat.chunk.Stack { private _next; private _prev; private _capacity; private _first; private _last; private _count; constructor(capacity: number, fill: boolean); enqueue(index: number): boolean; dequeueTail(): number; dequeue(index: number): boolean; free(): void; size(): number; } class HeapGenChunk implements greycat.chunk.GenChunk { private _space; private _index; private _prefix; private _seed; private _dirty; constructor(p_space: greycat.internal.heap.HeapChunkSpace, p_id: number, p_index: number); save(buffer: greycat.struct.Buffer): void; saveDiff(buffer: greycat.struct.Buffer): void; load(buffer: greycat.struct.Buffer): void; loadDiff(buffer: greycat.struct.Buffer): void; private internal_load(buffer, diff); newKey(): number; index(): number; world(): number; time(): number; id(): number; chunkType(): number; } class HeapLMatrix implements greycat.struct.LMatrix { private static INDEX_ROWS; private static INDEX_COLUMNS; private static INDEX_MAX_COLUMN; private static INDEX_OFFSET; private parent; private backend; private aligned; constructor(p_parent: greycat.internal.heap.HeapContainer, origin: greycat.internal.heap.HeapLMatrix); init(rows: number, columns: number): greycat.struct.LMatrix; private internal_init(rows, columns); appendColumn(newColumn: Float64Array): greycat.struct.LMatrix; private internal_appendColumn(newColumn); fill(value: number): greycat.struct.LMatrix; private internal_fill(value); fillWith(values: Float64Array): greycat.struct.LMatrix; private internal_fillWith(values); fillWithRandom(min: number, max: number, seed: number): greycat.struct.LMatrix; private internal_fillWithRandom(min, max, seed); rows(): number; columns(): number; column(index: number): Float64Array; get(rowIndex: number, columnIndex: number): number; set(rowIndex: number, columnIndex: number, value: number): greycat.struct.LMatrix; private internal_set(rowIndex, columnIndex, value); add(rowIndex: number, columnIndex: number, value: number): greycat.struct.LMatrix; private internal_add(rowIndex, columnIndex, value); data(): Float64Array; leadingDimension(): number; unsafeGet(index: number): number; unsafeSet(index: number, value: number): greycat.struct.LMatrix; private internal_unsafeSet(index, value); unsafe_data(): Float64Array; unsafe_init(size: number): void; unsafe_set(index: number, value: number): void; load(buffer: greycat.struct.Buffer, offset: number, max: number): number; } class HeapLongLongArrayMap implements greycat.struct.LongLongArrayMap { parent: greycat.internal.heap.HeapContainer; mapSize: number; capacity: number; keys: Float64Array; values: Float64Array; nexts: Int32Array; hashs: Int32Array; constructor(p_listener: greycat.internal.heap.HeapContainer); private key(i); private setKey(i, newValue); private value(i); private setValue(i, newValue); private next(i); private setNext(i, newValue); private hash(i); private setHash(i, newValue); reallocate(newCapacity: number): void; cloneFor(newParent: greycat.internal.heap.HeapContainer): greycat.internal.heap.HeapLongLongArrayMap; get(requestKey: number): Float64Array; contains(requestKey: number, requestValue: number): boolean; each(callback: greycat.struct.LongLongArrayMapCallBack): void; unsafe_each(callback: greycat.struct.LongLongArrayMapCallBack): void; size(): number; delete(requestKey: number, requestValue: number): void; put(insertKey: number, insertValue: number): void; load(buffer: greycat.struct.Buffer, offset: number, max: number): number; } class HeapLongLongMap implements greycat.struct.LongLongMap { private parent; private mapSize; private capacity; private keys; private values; private nexts; private hashs; constructor(p_listener: greycat.internal.heap.HeapContainer); private key(i); private setKey(i, newValue); private value(i); private setValue(i, newValue); private next(i); private setNext(i, newValue); private hash(i); private setHash(i, newValue); reallocate(newCapacity: number): void; cloneFor(newParent: greycat.internal.heap.HeapContainer): greycat.internal.heap.HeapLongLongMap; get(requestKey: number): number; each(callback: greycat.struct.LongLongMapCallBack): void; unsafe_each(callback: greycat.struct.LongLongMapCallBack): void; size(): number; remove(requestKey: number): void; put(insertKey: number, insertValue: number): void; load(buffer: greycat.struct.Buffer, offset: number, max: number): number; } class HeapMemoryFactory implements greycat.plugin.MemoryFactory { newSpace(memorySize: number, graph: greycat.Graph, deepWorld: boolean): greycat.chunk.ChunkSpace; newBuffer(): greycat.struct.Buffer; } class HeapRelation implements greycat.struct.Relation { private _back; private _size; private parent; private aligned; constructor(p_parent: greycat.internal.heap.HeapContainer, origin: greycat.internal.heap.HeapRelation); allocate(_capacity: number): void; all(): Float64Array; size(): number; get(index: number): number; set(index: number, value: number): void; unsafe_get(index: number): number; addNode(node: greycat.Node): greycat.struct.Relation; add(newValue: number): greycat.struct.Relation; addAll(newValues: Float64Array): greycat.struct.Relation; insert(targetIndex: number, newValue: number): greycat.struct.Relation; remove(oldValue: number): greycat.struct.Relation; delete(toRemoveIndex: number): greycat.struct.Relation; clear(): greycat.struct.Relation; toString(): string; load(buffer: greycat.struct.Buffer, offset: number, max: number): number; } class HeapRelationIndexed extends greycat.internal.heap.HeapLongLongArrayMap implements greycat.struct.RelationIndexed { private _graph; constructor(p_listener: greycat.internal.heap.HeapContainer, graph: greycat.Graph); add(node: greycat.Node, ...attributeNames: string[]): greycat.struct.RelationIndexed; remove(node: greycat.Node, ...attributeNames: string[]): greycat.struct.RelationIndexed; private internal_add_remove(isIndex, node, ...attributeNames); clear(): greycat.struct.RelationIndexed; find(callback: greycat.Callback<greycat.Node[]>, world: number, time: number, ...params: string[]): void; findByQuery(query: greycat.Query, callback: greycat.Callback<greycat.Node[]>): void; all(): Float64Array; cloneIRelFor(newParent: greycat.internal.heap.HeapContainer, graph: greycat.Graph): greycat.internal.heap.HeapRelationIndexed; } class HeapStateChunk implements greycat.chunk.StateChunk, greycat.internal.heap.HeapContainer { private _index; private _space; private _capacity; private _size; private _k; private _v; private _type; private next_and_hash; private _dirty; private static LOAD_WAITING_ALLOC; private static LOAD_WAITING_TYPE; private static LOAD_WAITING_KEY; private static LOAD_WAITING_VALUE; graph(): greycat.Graph; constructor(p_space: greycat.internal.heap.HeapChunkSpace, p_index: number); world(): number; time(): number; id(): number; chunkType(): number; index(): number; get(p_key: number): any; private internal_find(p_key); private internal_get(p_key); set(p_elementIndex: number, p_elemType: number, p_unsafe_elem: any): void; setFromKey(key: string, p_elemType: number, p_unsafe_elem: any): void; getFromKey(key: string): any; getFromKeyWithDefault<A>(key: string, defaultValue: A): A; getWithDefault<A>(key: number, defaultValue: A): A; getType(p_key: number): number; getTypeFromKey(key: string): number; getOrCreate(p_key: number, p_type: number): any; getOrCreateFromKey(key: string, elemType: number): any; declareDirty(): void; save(buffer: greycat.struct.Buffer): void; saveDiff(buffer: greycat.struct.Buffer): void; each(callBack: greycat.plugin.NodeStateCallback): void; loadFrom(origin: greycat.chunk.StateChunk): void; private internal_set(p_key, p_type, p_unsafe_elem, replaceIfPresent, initial); private allocate(newCapacity); load(buffer: greycat.struct.Buffer): void; private load_primitive(read_key, read_type, buffer, previous, cursor, initial); loadDiff(buffer: greycat.struct.Buffer): void; } class HeapStringIntMap implements greycat.struct.StringIntMap { private parent; private mapSize; private capacity; private keys; private keysH; private values; private nexts; private hashs; constructor(p_parent: greycat.internal.heap.HeapContainer); private key(i); private setKey(i, newValue); private keyH(i); private setKeyH(i, newValue); private value(i); private setValue(i, newValue); private next(i); private setNext(i, newValue); private hash(i); private setHash(i, newValue); reallocate(newCapacity: number): void; cloneFor(newContainer: greycat.internal.heap.HeapContainer): greycat.internal.heap.HeapStringIntMap; getValue(requestString: string): number; getByHash(keyHash: number): string; containsHash(keyHash: number): boolean; each(callback: greycat.struct.StringLongMapCallBack): void; unsafe_each(callback: greycat.struct.StringLongMapCallBack): void; size(): number; remove(requestKey: string): void; put(insertKey: string, insertValue: number): void; load(buffer: greycat.struct.Buffer, offset: number, max: number): number; } class HeapTimeTreeChunk implements greycat.chunk.TimeTreeChunk { private static META_SIZE; private _index; private _space; private _root; private _back_meta; private _k; private _colors; private _diff; private _magic; private _size; private _dirty; private _extra; private _extra2; constructor(p_space: greycat.internal.heap.HeapChunkSpace, p_index: number); extra(): number; setExtra(extraValue: number): void; extra2(): number; setExtra2(extraValue: number): void; world(): number; time(): number; id(): number; size(): number; range(startKey: number, endKey: number, maxElements: number, walker: greycat.chunk.TreeWalker): void; save(buffer: greycat.struct.Buffer): void; saveDiff(buffer: greycat.struct.Buffer): void; load(buffer: greycat.struct.Buffer): void; loadDiff(buffer: greycat.struct.Buffer): void; private internal_load(buffer, initial); index(): number; previous(key: number): number; next(key: number): number; previousOrEqual(key: number): number; magic(): number; insert(p_key: number): void; unsafe_insert(p_key: number): void; chunkType(): number; clearAt(max: number): void; private reallocate(newCapacity); private key(p_currentIndex); private setKey(p_currentIndex, p_paramIndex, initial); private left(p_currentIndex); private setLeft(p_currentIndex, p_paramIndex); private right(p_currentIndex); private setRight(p_currentIndex, p_paramIndex); private parent(p_currentIndex); private setParent(p_currentIndex, p_paramIndex); private color(p_currentIndex); private setColor(p_currentIndex, p_paramIndex); private grandParent(p_currentIndex); private sibling(p_currentIndex); private uncle(p_currentIndex); private internal_previous(p_index); private internal_next(p_index); private internal_previousOrEqual_index(p_key); private internal_previous_index(p_key); private rotateLeft(n); private rotateRight(n); private replaceNode(oldn, newn); private insertCase1(n); private insertCase2(n); private insertCase3(n); private insertCase4(n_n); private insertCase5(n); private internal_insert(p_key, initial); private internal_set_dirty(); } class HeapWorldOrderChunk implements greycat.chunk.WorldOrderChunk { private _space; private _index; private _lock; private _externalLock; private _magic; private _extra; private _size; private _capacity; private _kv; private _diff; private _next; private _hash; private _dirty; constructor(p_space: greycat.internal.heap.HeapChunkSpace, p_index: number); world(): number; time(): number; id(): number; extra(): number; setExtra(extraValue: number): void; lock(): void; unlock(): void; externalLock(): void; externalUnlock(): void; magic(): number; each(callback: greycat.struct.LongLongMapCallBack): void; get(key: number): number; put(key: number, value: number): void; private internal_put(key, value, notifyUpdate); private resize(newCapacity); load(buffer: greycat.struct.Buffer): void; loadDiff(buffer: greycat.struct.Buffer): void; private internal_load(initial, buffer); index(): number; remove(key: number): void; size(): number; chunkType(): number; save(buffer: greycat.struct.Buffer): void; saveDiff(buffer: greycat.struct.Buffer): void; } } module task { class ActionAddRemoveToGlobalIndex implements greycat.Action { private _name; private _attributes; private _timed; private _remove; constructor(remove: boolean, timed: boolean, name: string, ...attributes: string[]); eval(ctx: greycat.TaskContext): void; serialize(builder: java.lang.StringBuilder): void; toString(): string; } class ActionAddRemoveVarToRelation implements greycat.Action { private _name; private _varFrom; private _attributes; private _isAdd; constructor(isAdd: boolean, name: string, varFrom: string, ...attributes: string[]); eval(ctx: greycat.TaskContext): void; serialize(builder: java.lang.StringBuilder): void; toString(): string; } class ActionAddToVar implements greycat.Action { private _name; constructor(p_name: string); eval(ctx: greycat.TaskContext): void; serialize(builder: java.lang.StringBuilder): void; toString(): string; } class ActionAttributes implements greycat.Action { private _filter; constructor(filterType: string); eval(ctx: greycat.TaskContext): void; serialize(builder: java.lang.StringBuilder): void; toString(): string; } class ActionClearResult implements greycat.Action { eval(ctx: greycat.TaskContext): void; serialize(builder: java.lang.StringBuilder): void; toString(): string; } class ActionCreateNode implements greycat.Action { private _typeNode; constructor(typeNode: string); eval(ctx: greycat.TaskContext): void; serialize(builder: java.lang.StringBuilder): void; toString(): string; } class ActionDeclareVar implements greycat.Action { private _name; private _isGlobal; constructor(isGlobal: boolean, p_name: string); eval(ctx: greycat.TaskContext): void; serialize(builder: java.lang.StringBuilder): void; toString(): string; } class ActionDefineAsVar implements greycat.Action { private _name; private _global; constructor(p_name: string, p_global: boolean); eval(ctx: greycat.TaskContext): void; serialize(builder: java.lang.StringBuilder): void; toString(): string; } class ActionExecuteExpression implements greycat.Action { private _engine; private _expression; constructor(mathExpression: string); eval(ctx: greycat.TaskContext): void; serialize(builder: java.lang.StringBuilder): void; toString(): string; } class ActionFlat implements greycat.Action { constructor(); eval(ctx: greycat.TaskContext): void; serialize(builder: java.lang.StringBuilder): void; toString(): string; } class ActionFlipVar implements greycat.Action { private _name; constructor(name: string); eval(ctx: greycat.TaskContext): void; serialize(builder: java.lang.StringBuilder): void; toString(): string; } class ActionGlobalIndex implements greycat.Action { private _name; constructor(p_indexName: string); eval(ctx: greycat.TaskContext): void; serialize(builder: java.lang.StringBuilder): void; toString(): string; } class ActionIndexNames implements greycat.Action { eval(ctx: greycat.TaskContext): void; serialize(builder: java.lang.StringBuilder): void; toString(): string; } class ActionInject implements greycat.Action { private _value; constructor(value: any); eval(ctx: greycat.TaskContext): void; serialize(builder: java.lang.StringBuilder): void; toString(): string; } class ActionLog implements greycat.Action { private _value; constructor(p_value: string); eval(ctx: greycat.TaskContext): void; serialize(builder: java.lang.StringBuilder): void; toString(): string; } class ActionLookup implements greycat.Action { private _id; constructor(p_id: string); eval(ctx: greycat.TaskContext): void; serialize(builder: java.lang.StringBuilder): void; toString(): string; } class ActionLookupAll implements greycat.Action { private _ids; constructor(p_ids: string); eval(ctx: greycat.TaskContext): void; serialize(builder: java.lang.StringBuilder): void; toString(): string; } class ActionNamed implements greycat.Action { private _name; private _params; constructor(name: string, ...params: string[]); eval(ctx: greycat.TaskContext): void; serialize(builder: java.lang.StringBuilder): void; toString(): string; } class ActionPrint implements greycat.Action { private _name; private _withLineBreak; constructor(p_name: string, withLineBreak: boolean); eval(ctx: greycat.TaskContext): void; serialize(builder: java.lang.StringBuilder): void; toString(): string; } class ActionQueryBoundedRadius implements greycat.Action { static NAME: string; private _key; private _n; private _radius; private _fetchNodes; constructor(n: number, radius: number, fetchNodes: boolean, key: Float64Array); eval(ctx: greycat.TaskContext): void; serialize(builder: java.lang.StringBuilder): void; toString(): string; } class ActionReadGlobalIndex implements greycat.Action { private _name; private _params; constructor(p_indexName: string, ...p_query: string[]); eval(ctx: greycat.TaskContext): void; serialize(builder: java.lang.StringBuilder): void; toString(): string; } class ActionReadVar implements greycat.Action { private _origin; private _name; private _index; constructor(p_name: string); eval(ctx: greycat.TaskContext): void; serialize(builder: java.lang.StringBuilder): void; toString(): string; } class ActionRemove implements greycat.Action { private _name; constructor(name: string); eval(ctx: greycat.TaskContext): void; serialize(builder: java.lang.StringBuilder): void; toString(): string; } class ActionSave implements greycat.Action { eval(ctx: greycat.TaskContext): void; serialize(builder: java.lang.StringBuilder): void; toString(): string; } class ActionScript implements greycat.Action { private _script; private _async; constructor(script: string, async: boolean); eval(ctx: greycat.TaskContext): void; serialize(builder: java.lang.StringBuilder): void; toString(): string; } class ActionSelect implements greycat.Action { private _script; private _filter; constructor(script: string, filter: greycat.TaskFunctionSelect); eval(ctx: greycat.TaskContext): void; private callScript(node, context); serialize(builder: java.lang.StringBuilder): void; toString(): string; } class ActionSelectObject implements greycat.Action { private _filter; constructor(filterFunction: greycat.TaskFunctionSelectObject); eval(ctx: greycat.TaskContext): void; serialize(builder: java.lang.StringBuilder): void; toString(): string; } class ActionSetAsVar implements greycat.Action { private _name; constructor(p_name: string); eval(ctx: greycat.TaskContext): void; serialize(builder: java.lang.StringBuilder): void; toString(): string; } class ActionSetAttribute implements greycat.Action { private _name; private _value; private _propertyType; private _force; constructor(name: string, propertyType: string, value: string, force: boolean); eval(ctx: greycat.TaskContext): void; private loadArray(valueAfterTemplate, type); private parseBoolean(booleanValue); serialize(builder: java.lang.StringBuilder): void; toString(): string; } class ActionTimeSensitivity implements greycat.Action { private _delta; private _offset; constructor(delta: string, offset: string); eval(ctx: greycat.TaskContext): void; serialize(builder: java.lang.StringBuilder): void; toString(): string; } class ActionTimepoints implements greycat.Action { private _from; private _to; constructor(from: string, to: string); eval(ctx: greycat.TaskContext): void; serialize(builder: java.lang.StringBuilder): void; toString(): string; } class ActionTravelInTime implements greycat.Action { private _time; constructor(time: string); eval(ctx: greycat.TaskContext): void; serialize(builder: java.lang.StringBuilder): void; toString(): string; } class ActionTravelInWorld implements greycat.Action { private _world; constructor(world: string); eval(ctx: greycat.TaskContext): void; serialize(builder: java.lang.StringBuilder): void; toString(): string; } class ActionTraverseOrAttribute implements greycat.Action { private _name; private _params; private _isAttribute; private _isUnknown; constructor(isAttribute: boolean, isUnknown: boolean, p_name: string, ...p_params: string[]); eval(ctx: greycat.TaskContext): void; serialize(builder: java.lang.StringBuilder): void; toString(): string; } class ActionWith implements greycat.Action { private _patternTemplate; private _name; constructor(name: string, stringPattern: string); eval(ctx: greycat.TaskContext): void; serialize(builder: java.lang.StringBuilder): void; toString(): string; } class ActionWithout implements greycat.Action { private _patternTemplate; private _name; constructor(name: string, stringPattern: string); eval(ctx: greycat.TaskContext): void; serialize(builder: java.lang.StringBuilder): void; toString(): string; } abstract class CF_Action implements greycat.Action { abstract children(): greycat.Task[]; abstract cf_serialize(builder: java.lang.StringBuilder, dagIDS: java.util.Map<number, number>): void; abstract eval(ctx: greycat.TaskContext): void; serialize(builder: java.lang.StringBuilder): void; toString(): string; } class CF_Atomic extends greycat.internal.task.CF_Action { private _variables; private _subTask; constructor(p_subTask: greycat.Task, ...variables: string[]); eval(ctx: greycat.TaskContext): void; children(): greycat.Task[]; cf_serialize(builder: java.lang.StringBuilder, dagIDS: java.util.Map<number, number>): void; } class CF_DoWhile extends greycat.internal.task.CF_Action { private _cond; private _then; private _conditionalScript; constructor(p_then: greycat.Task, p_cond: greycat.ConditionalFunction, conditionalScript: string); eval(ctx: greycat.TaskContext): void; children(): greycat.Task[]; cf_serialize(builder: java.lang.StringBuilder, dagIDS: java.util.Map<number, number>): void; } class CF_ForEach extends greycat.internal.task.CF_Action { private _subTask; constructor(p_subTask: greycat.Task); eval(ctx: greycat.TaskContext): void; children(): greycat.Task[]; cf_serialize(builder: java.lang.StringBuilder, dagIDS: java.util.Map<number, number>): void; } class CF_ForEachPar extends greycat.internal.task.CF_Action { private _subTask; constructor(p_subTask: greycat.Task); eval(ctx: greycat.TaskContext): void; children(): greycat.Task[]; cf_serialize(builder: java.lang.StringBuilder, dagIDS: java.util.Map<number, number>): void; } class CF_IfThen extends greycat.internal.task.CF_Action { private _condition; private _action; private _conditionalScript; constructor(cond: greycat.ConditionalFunction, action: greycat.Task, conditionalScript: string); eval(ctx: greycat.TaskContext): void; children(): greycat.Task[]; cf_serialize(builder: java.lang.StringBuilder, dagIDS: java.util.Map<number, number>): void; } class CF_IfThenElse extends greycat.internal.task.CF_Action { private _condition; private _thenSub; private _elseSub; private _conditionalScript; constructor(cond: greycat.ConditionalFunction, p_thenSub: greycat.Task, p_elseSub: greycat.Task, conditionalScript: string); eval(ctx: greycat.TaskContext): void; children(): greycat.Task[]; cf_serialize(builder: java.lang.StringBuilder, dagIDS: java.util.Map<number, number>): void; } class CF_Loop extends greycat.internal.task.CF_Action { private _lower; private _upper; private _subTask; constructor(p_lower: string, p_upper: string, p_subTask: greycat.Task); eval(ctx: greycat.TaskContext): void; children(): greycat.Task[]; cf_serialize(builder: java.lang.StringBuilder, dagIDS: java.util.Map<number, number>): void; } class CF_LoopPar extends greycat.internal.task.CF_Action { private _subTask; private _lower; private _upper; constructor(p_lower: string, p_upper: string, p_subTask: greycat.Task); eval(ctx: greycat.TaskContext): void; children(): greycat.Task[]; cf_serialize(builder: java.lang.StringBuilder, dagIDS: java.util.Map<number, number>): void; } class CF_Map extends greycat.internal.task.CF_Action { private _subTask; constructor(p_subTask: greycat.Task); eval(ctx: greycat.TaskContext): void; children(): greycat.Task[]; cf_serialize(builder: java.lang.StringBuilder, dagIDS: java.util.Map<number, number>): void; } class CF_MapPar extends greycat.internal.task.CF_Action { private _subTask; constructor(p_subTask: greycat.Task); eval(ctx: greycat.TaskContext): void; children(): greycat.Task[]; cf_serialize(builder: java.lang.StringBuilder, dagIDS: java.util.Map<number, number>): void; } class CF_Pipe extends greycat.internal.task.CF_Action { private _subTasks; constructor(...p_subTasks: greycat.Task[]); eval(ctx: greycat.TaskContext): void; children(): greycat.Task[]; cf_serialize(builder: java.lang.StringBuilder, dagIDS: java.util.Map<number, number>): void; } class CF_PipePar extends greycat.internal.task.CF_Action { private _subTasks; constructor(...p_subTasks: greycat.Task[]); eval(ctx: greycat.TaskContext): void; children(): greycat.Task[]; cf_serialize(builder: java.lang.StringBuilder, dagIDS: java.util.Map<number, number>): void; } class CF_PipeTo extends greycat.internal.task.CF_Action { private _subTask; private _targets; constructor(p_subTask: greycat.Task, ...p_targets: string[]); eval(ctx: greycat.TaskContext): void; children(): greycat.Task[]; cf_serialize(builder: java.lang.StringBuilder, dagIDS: java.util.Map<number, number>): void; } class CF_ThenDo implements greycat.Action { private _wrapped; constructor(p_wrapped: greycat.ActionFunction); eval(ctx: greycat.TaskContext): void; toString(): string; serialize(builder: java.lang.StringBuilder): void; } class CF_WhileDo extends greycat.internal.task.CF_Action { private _cond; private _then; private _conditionalScript; constructor(p_cond: greycat.ConditionalFunction, p_then: greycat.Task, conditionalScript: string); eval(ctx: greycat.TaskContext): void; children(): greycat.Task[]; cf_serialize(builder: java.lang.StringBuilder, dagIDS: java.util.Map<number, number>): void; } class CoreActionDeclaration implements greycat.plugin.ActionDeclaration { private _factory; private _params; private _description; private _name; constructor(name: string); factory(): greycat.plugin.ActionFactory; setFactory(factory: greycat.plugin.ActionFactory): greycat.plugin.ActionDeclaration; params(): Int8Array; setParams(...params: number[]): greycat.plugin.ActionDeclaration; description(): string; setDescription(description: string): greycat.plugin.ActionDeclaration; name(): string; } class CoreActionNames { static ADD_VAR_TO_RELATION: string; static REMOVE_VAR_TO_RELATION: string; static ADD_TO_GLOBAL_INDEX: string; static ADD_TO_GLOBAL_TIMED_INDEX: string; static ADD_TO_VAR: string; static ATTRIBUTES: string; static ATTRIBUTES_WITH_TYPE: string; static CLEAR_RESULT: string; static CREATE_NODE: string; static CREATE_TYPED_NODE: string; static DECLARE_GLOBAL_VAR: string; static DECLARE_VAR: string; static FLIP_VAR: string; static DEFINE_AS_GLOBAL_VAR: string; static DEFINE_AS_VAR: string; static EXECUTE_EXPRESSION: string; static INDEX_NAMES: string; static LOOKUP: string; static LOOKUP_ALL: string; static LOG: string; static PRINT: string; static PRINTLN: string; static READ_GLOBAL_INDEX: string; static GLOBAL_INDEX: string; static READ_VAR: string; static REMOVE: string; static REMOVE_FROM_GLOBAL_INDEX: string; static SAVE: string; static SCRIPT: string; static ASYNC_SCRIPT: string; static SELECT: string; static SET_AS_VAR: string; static FORCE_ATTRIBUTE: string; static SET_ATTRIBUTE: string; static TIME_SENSITIVITY: string; static TIMEPOINTS: string; static TRAVEL_IN_TIME: string; static TRAVEL_IN_WORLD: string; static WITH: string; static WITHOUT: string; static TRAVERSE: string; static ATTRIBUTE: string; static LOOP: string; static LOOP_PAR: string; static FOR_EACH: string; static FOR_EACH_PAR: string; static MAP: string; static MAP_PAR: string; static PIPE: string; static PIPE_PAR: string; static PIPE_TO: string; static DO_WHILE: string; static WHILE_DO: string; static IF_THEN: string; static IF_THEN_ELSE: string; static ATOMIC: string; static FLAT: string; } class CoreActionRegistry implements greycat.plugin.ActionRegistry { private backend; constructor(); declaration(name: string): greycat.plugin.ActionDeclaration; declarations(): greycat.plugin.ActionDeclaration[]; } class CoreActions { static flat(): greycat.Action; static travelInWorld(world: string): greycat.Action; static travelInTime(time: string): greycat.Action; static inject(input: any): greycat.Action; static defineAsGlobalVar(name: string): greycat.Action; static defineAsVar(name: string): greycat.Action; static declareGlobalVar(name: string): greycat.Action; static declareVar(name: string): greycat.Action; static readVar(name: string): greycat.Action; static flipVar(name: string): greycat.Action; static setAsVar(name: string): greycat.Action; static addToVar(name: string): greycat.Action; static setAttribute(name: string, type: number, value: string): greycat.Action; static timeSensitivity(delta: string, offset: string): greycat.Action; static forceAttribute(name: string, type: number, value: string): greycat.Action; static remove(name: string): greycat.Action; static attributes(): greycat.Action; static attributesWithTypes(filterType: number): greycat.Action; static addVarToRelation(relName: string, varName: string, ...attributes: string[]): greycat.Action; static removeVarFromRelation(relName: string, varFrom: string, ...attributes: string[]): greycat.Action; static traverse(name: string, ...params: string[]): greycat.Action; static attribute(name: string, ...params: string[]): greycat.Action; static readGlobalIndex(indexName: string, ...query: string[]): greycat.Action; static globalIndex(indexName: string): greycat.Action; static addToGlobalIndex(name: string, ...attributes: string[]): greycat.Action; static addToGlobalTimedIndex(name: string, ...attributes: string[]): greycat.Action; static removeFromGlobalIndex(name: string, ...attributes: string[]): greycat.Action; static removeFromGlobalTimedIndex(name: string, ...attributes: string[]): greycat.Action; static indexNames(): greycat.Action; static selectWith(name: string, pattern: string): greycat.Action; static selectWithout(name: string, pattern: string): greycat.Action; static select(filterFunction: greycat.TaskFunctionSelect): greycat.Action; static selectObject(filterFunction: greycat.TaskFunctionSelectObject): greycat.Action; static selectScript(script: string): greycat.Action; static log(value: string): greycat.Action; static print(name: string): greycat.Action; static println(name: string): greycat.Action; static executeExpression(expression: string): greycat.Action; static action(name: string, ...params: string[]): greycat.Action; static createNode(): greycat.Action; static createTypedNode(type: string): greycat.Action; static save(): greycat.Action; static script(script: string): greycat.Action; static asyncScript(script: string): greycat.Action; static lookup(nodeId: string): greycat.Action; static lookupAll(nodeIds: string): greycat.Action; static timepoints(from: string, to: string): greycat.Action; static clearResult(): greycat.Action; } class CoreTask implements greycat.Task { private insertCapacity; actions: greycat.Action[]; insertCursor: number; _hooks: greycat.TaskHook[]; addHook(p_hook: greycat.TaskHook): greycat.Task; then(nextAction: greycat.Action): greycat.Task; thenDo(nextActionFunction: greycat.ActionFunction): greycat.Task; doWhile(task: greycat.Task, cond: greycat.ConditionalFunction): greycat.Task; doWhileScript(task: greycat.Task, condScript: string): greycat.Task; loop(from: string, to: string, subTask: greycat.Task): greycat.Task; loopPar(from: string, to: string, subTask: greycat.Task): greycat.Task; forEach(subTask: greycat.Task): greycat.Task; forEachPar(subTask: greycat.Task): greycat.Task; map(subTask: greycat.Task): greycat.Task; mapPar(subTask: greycat.Task): greycat.Task; ifThen(cond: greycat.ConditionalFunction, then: greycat.Task): greycat.Task; ifThenScript(condScript: string, then: greycat.Task): greycat.Task; ifThenElse(cond: greycat.ConditionalFunction, thenSub: greycat.Task, elseSub: greycat.Task): greycat.Task; ifThenElseScript(condScript: string, thenSub: greycat.Task, elseSub: greycat.Task): greycat.Task; whileDo(cond: greycat.ConditionalFunction, task: greycat.Task): greycat.Task; whileDoScript(condScript: string, task: greycat.Task): greycat.Task; pipe(...subTasks: greycat.Task[]): greycat.Task; pipePar(...subTasks: greycat.Task[]): greycat.Task; pipeTo(subTask: greycat.Task, ...vars: string[]): greycat.Task; atomic(protectedTask: greycat.Task, ...variablesToLock: string[]): greycat.Task; execute(graph: greycat.Graph, callback: greycat.Callback<greycat.TaskResult<any>>): void; executeSync(graph: greycat.Graph): greycat.TaskResult<any>; executeWith(graph: greycat.Graph, initial: any, callback: greycat.Callback<greycat.TaskResult<any>>): void; prepare(graph: greycat.Graph, initial: any, callback: greycat.Callback<greycat.TaskResult<any>>): greycat.TaskContext; executeUsing(preparedContext: greycat.TaskContext): void; executeFrom(parentContext: greycat.TaskContext, initial: greycat.TaskResult<any>, affinity: number, callback: greycat.Callback<greycat.TaskResult<any>>): void; executeFromUsing(parentContext: greycat.TaskContext, initial: greycat.TaskResult<any>, affinity: number, contextInitializer: greycat.Callback<greycat.TaskContext>, callback: greycat.Callback<greycat.TaskResult<any>>): void; loadFromBuffer(buffer: greycat.struct.Buffer, graph: greycat.Graph): greycat.Task; saveToBuffer(buffer: greycat.struct.Buffer): greycat.Task; parse(flat: string, graph: greycat.Graph): greycat.Task; private sub_parse(reader, graph, contextTasks); static loadAction(registry: greycat.plugin.ActionRegistry, actionName: string, params: string[], contextTasks: java.util.Map<number, greycat.Task>): greycat.Action; private static condFromScript(script); private static executeScript(script, context); static fillDefault(registry: greycat.plugin.ActionRegistry): void; private static getOrCreate(contextTasks, param); hashCode(): number; toString(): string; serialize(builder: java.lang.StringBuilder, dagCounters: java.util.Map<number, number>): void; private static deep_analyze(t, counters, dagCollector); travelInWorld(world: string): greycat.Task; travelInTime(time: string): greycat.Task; inject(input: any): greycat.Task; defineAsGlobalVar(name: string): greycat.Task; defineAsVar(name: string): greycat.Task; declareGlobalVar(name: string): greycat.Task; declareVar(name: string): greycat.Task; readVar(name: string): greycat.Task; setAsVar(name: string): greycat.Task; addToVar(name: string): greycat.Task; setAttribute(name: string, type: number, value: string): greycat.Task; timeSensitivity(delta: string, offset: string): greycat.Task; forceAttribute(name: string, type: number, value: string): greycat.Task; remove(name: string): greycat.Task; attributes(): greycat.Task; timepoints(from: string, to: string): greycat.Task; attributesWithType(filterType: number): greycat.Task; addVarToRelation(relName: string, varName: string, ...attributes: string[]): greycat.Task; removeVarFromRelation(relName: string, varFrom: string, ...attributes: string[]): greycat.Task; traverse(name: string, ...params: string[]): greycat.Task; attribute(name: string, ...params: string[]): greycat.Task; readGlobalIndex(name: string, ...query: string[]): greycat.Task; globalIndex(indexName: string): greycat.Task; addToGlobalIndex(name: string, ...attributes: string[]): greycat.Task; addToGlobalTimedIndex(name: string, ...attributes: string[]): greycat.Task; removeFromGlobalIndex(name: string, ...attributes: string[]): greycat.Task; removeFromGlobalTimedIndex(name: string, ...attributes: string[]): greycat.Task; indexNames(): greycat.Task; selectWith(name: string, pattern: string): greycat.Task; selectWithout(name: string, pattern: string): greycat.Task; select(filterFunction: greycat.TaskFunctionSelect): greycat.Task; selectObject(filterFunction: greycat.TaskFunctionSelectObject): greycat.Task; log(name: string): greycat.Task; selectScript(script: string): greycat.Task; print(name: string): greycat.Task; println(name: string): greycat.Task; executeExpression(expression: string): greycat.Task; createNode(): greycat.Task; createTypedNode(type: string): greycat.Task; save(): greycat.Task; script(script: string): greycat.Task; asyncScript(ascript: string): greycat.Task; lookup(nodeId: string): greycat.Task; lookupAll(nodeIds: string): greycat.Task; clearResult(): greycat.Task; action(name: string, ...params: string[]): greycat.Task; flipVar(name: string): greycat.Task; flat(): greycat.Task; } class CoreTaskContext implements greycat.TaskContext { private _globalVariables; private _parent; private _graph; _callback: greycat.Callback<greycat.TaskResult<any>>; private _localVariables; private _nextVariables; _result: greycat.TaskResult<any>; private _world; private _time; private _origin; private cursor; _hooks: greycat.TaskHook[]; private _output; constructor(origin: greycat.internal.task.CoreTask, p_hooks: greycat.TaskHook[], parentContext: greycat.TaskContext, initial: greycat.TaskResult<any>, p_graph: greycat.Graph, p_callback: greycat.Callback<greycat.TaskResult<any>>); graph(): greycat.Graph; world(): number; setWorld(p_world: number): greycat.TaskContext; time(): number; setTime(p_time: number): greycat.TaskContext; variables(): greycat.utility.Tuple<string, greycat.TaskResult<any>>[]; private recursive_collect(ctx, collector); variable(name: string): greycat.TaskResult<any>; isGlobal(name: string): boolean; private internal_deep_resolve(name); wrap(input: any): greycat.TaskResult<any>; wrapClone(input: any): greycat.TaskResult<any>; newResult(): greycat.TaskResult<any>; declareVariable(name: string): greycat.TaskContext; private lazyWrap(input); defineVariable(name: string, initialResult: any): greycat.TaskContext; defineVariableForSubTask(name: string, initialResult: any): greycat.TaskContext; setGlobalVariable(name: string, value: any): greycat.TaskContext; setVariable(name: string, value: any): greycat.TaskContext; private internal_deep_resolve_map(name); addToGlobalVariable(name: string, value: any): greycat.TaskContext; addToVariable(name: string, value: any): greycat.TaskContext; globalVariables(): java.util.Map<string, greycat.TaskResult<any>>; localVariables(): java.util.Map<string, greycat.TaskResult<any>>; result(): greycat.TaskResult<any>; resultAsNodes(): greycat.TaskResult<greycat.Node>; resultAsStrings(): greycat.TaskResult<string>; continueWith(nextResult: greycat.TaskResult<any>): void; continueTask(): void; endTask(preFinalResult: greycat.TaskResult<any>, e: Error): void; execute(): void; template(input: string): string; templates(inputs: string[]): string[]; append(additionalOutput: string): void; toString(): string; } class CoreTaskReader { private flat; private offset; private _end; constructor(p_flat: string, p_offset: number); available(): number; charAt(cursor: number): string; extract(begin: number, end: number): string; markend(p_end: number): void; end(): number; slice(cursor: number): greycat.internal.task.CoreTaskReader; } class CoreTaskResultIterator<A> implements greycat.TaskResultIterator<A> { private _backend; private _size; private _current; constructor(p_backend: any[]); next(): A; nextWithIndex(): greycat.utility.Tuple<number, A>; } class TaskHelper { static flatNodes(toFLat: any, strict: boolean): greycat.Node[]; static parseInt(s: string): number; static serializeString(param: string, builder: java.lang.StringBuilder, singleQuote: boolean): void; static serializeType(type: number, builder: java.lang.StringBuilder): void; static serializeStringParams(params: string[], builder: java.lang.StringBuilder): void; static serializeNameAndStringParams(name: string, params: string[], builder: java.lang.StringBuilder): void; } module math { class CoreMathExpressionEngine implements greycat.internal.task.math.MathExpressionEngine { static decimalSeparator: string; static minusSign: string; private _cacheAST; constructor(expression: string); static parse(p_expression: string): greycat.internal.task.math.MathExpressionEngine; static isNumber(st: string): boolean; static isDigit(c: string): boolean; static isLetter(c: string): boolean; static isWhitespace(c: string): boolean; private shuntingYard(expression); eval(context: greycat.Node, taskContext: greycat.TaskContext, variables: java.util.Map<string, number>): number; private buildAST(rpn); private parseDouble(val); private parseInt(val); } class MathConditional { private _engine; private _expression; constructor(mathExpression: string); conditional(): greycat.ConditionalFunction; toString(): string; } class MathDoubleToken implements greycat.internal.task.math.MathToken { private _content; constructor(_content: number); type(): number; content(): number; } class MathEntities { private static INSTANCE; operators: java.util.HashMap<string, greycat.internal.task.math.MathOperation>; functions: java.util.HashMap<string, greycat.internal.task.math.MathFunction>; static getINSTANCE(): greycat.internal.task.math.MathEntities; constructor(); } interface MathExpressionEngine { eval(context: greycat.Node, taskContext: greycat.TaskContext, variables: java.util.Map<string, number>): number; } class MathExpressionTokenizer { private pos; private input; private previousToken; constructor(input: string); hasNext(): boolean; private peekNextChar(); next(): string; getPos(): number; } class MathFreeToken implements greycat.internal.task.math.MathToken { private _content; constructor(content: string); content(): string; type(): number; } class MathFunction implements greycat.internal.task.math.MathToken { private name; private numParams; constructor(name: string, numParams: number); getName(): string; getNumParams(): number; eval(p: Float64Array): number; private date_to_seconds(value); private date_to_minutes(value); private date_to_hours(value); private date_to_days(value); private date_to_months(value); private date_to_year(value); private date_to_dayofweek(value); type(): number; } class MathOperation implements greycat.internal.task.math.MathToken { private oper; private precedence; private leftAssoc; constructor(oper: string, precedence: number, leftAssoc: boolean); getOper(): string; getPrecedence(): number; isLeftAssoc(): boolean; eval(v1: number, v2: number): number; type(): number; } interface MathToken { type(): number; } } } module tree { class HRect { min: Float64Array; max: Float64Array; constructor(vmin: Float64Array, vmax: Float64Array); clone(): any; closest(t: Float64Array): Float64Array; static infiniteHRect(d: number): greycat.internal.tree.HRect; toString(): string; } class KDTree implements greycat.struct.Tree { static RESOLUTION: number; static DISTANCE: number; private static E_SUBTREE_NODES; private static E_KEY; private static E_SUM_KEY; private static E_VALUE; private static E_SUBTREE_VALUES; private static E_RIGHT; private static E_LEFT; private static STRATEGY; private static DIM; private eGraph; constructor(eGraph: greycat.struct.EGraph); private static checkCreateLevels(key1, key2, resolutions); private static rangeSearch(lowk, uppk, center, distance, node, lev, dim, nnl); private static recursiveTraverse(node, nnl, distance, target, hr, lev, dim, max_dist_sqd, radius); private static internalInsert(node, key, value, strategyType, lev, resolution); private static createNode(parent, right); setDistance(distanceType: number): void; setResolution(resolution: Float64Array): void; setMinBound(min: Float64Array): void; setMaxBound(max: Float64Array): void; insert(keys: Float64Array, value: number): void; queryAround(keys: Float64Array, max: number): greycat.struct.TreeResult; queryRadius(keys: Float64Array, radius: number): greycat.struct.TreeResult; queryBoundedRadius(keys: Float64Array, radius: number, max: number): greycat.struct.TreeResult; queryArea(min: Float64Array, max: Float64Array): greycat.struct.TreeResult; size(): number; treeSize(): number; } class KDTreeNode extends greycat.base.BaseNode implements greycat.struct.Tree { static NAME: string; static BOUND_MIN: string; static BOUND_MAX: string; static RESOLUTION: string; private static E_TREE; private _kdTree; constructor(p_world: number, p_time: number, p_id: number, p_graph: greycat.Graph); private getTree(); set(name: string, type: number, value: any): greycat.Node; setDistance(distanceType: number): void; setResolution(resolution: Float64Array): void; setMinBound(min: Float64Array): void; setMaxBound(max: Float64Array): void; insert(keys: Float64Array, value: number): void; queryAround(keys: Float64Array, max: number): greycat.struct.TreeResult; queryRadius(keys: Float64Array, radius: number): greycat.struct.TreeResult; queryBoundedRadius(keys: Float64Array, radius: number, max: number): greycat.struct.TreeResult; queryArea(min: Float64Array, max: Float64Array): greycat.struct.TreeResult; size(): number; treeSize(): number; } class NDTree implements greycat.struct.Profile { static BUFFER_SIZE_DEF: number; static RESOLUTION: number; static BUFFER_SIZE: number; static DISTANCE: number; private static STRATEGY; private static E_TOTAL; private static E_SUBNODES; private static E_TOTAL_SUBNODES; private static E_MIN; private static E_MAX; private static E_BUFFER_KEYS; private static E_BUFFER_VALUES; private static E_VALUE; private static E_PROFILE; private static E_OFFSET_REL; private eGraph; constructor(eGraph: greycat.struct.EGraph); private static getRelationId(centerKey, keyToInsert); private static checkCreateLevels(min, max, resolutions); private static getCenterMinMax(min, max); private static getCenter(node); private static check(values, min, max); private static createNewNode(parent, root, index, min, max, center, keyToInsert, buffersize); private static subInsert(parent, key, value, strategyType, min, max, center, resolution, buffersize, root, bufferupdate); private static internalInsert(node, key, value, strategyType, min, max, center, resolution, buffersize, root); private static compare(key1, key2, resolution); setDistance(distanceType: number): void; setResolution(resolution: Float64Array): void; setMinBound(min: Float64Array): void; setMaxBound(max: Float64Array): void; setBufferSize(bufferSize: number): void; insert(keys: Float64Array, value: number): void; profile(keys: Float64Array): void; profileWith(keys: Float64Array, occurrence: number): void; queryAround(keys: Float64Array, max: number): greycat.struct.ProfileResult; queryRadius(keys: Float64Array, radius: number): greycat.struct.ProfileResult; queryBoundedRadius(keys: Float64Array, radius: number, max: number): greycat.struct.ProfileResult; queryArea(min: Float64Array, max: Float64Array): greycat.struct.ProfileResult; size(): number; treeSize(): number; private static binaryFromLong(value, dim); private static reccursiveTraverse(node, calcZone, nnl, strategyType, distance, target, targetmin, targetmax, targetcenter, radius); } class NDTreeNode extends greycat.base.BaseNode implements greycat.struct.Profile { static NAME: string; static BOUND_MIN: string; static BOUND_MAX: string; static RESOLUTION: string; private static E_TREE; private _ndTree; constructor(p_world: number, p_time: number, p_id: number, p_graph: greycat.Graph); private getTree(); set(name: string, type: number, value: any): greycat.Node; setDistance(distanceType: number): void; setResolution(resolution: Float64Array): void; setMinBound(min: Float64Array): void; setMaxBound(max: Float64Array): void; insert(keys: Float64Array, value: number): void; setBufferSize(bufferSize: number): void; profile(keys: Float64Array): void; profileWith(keys: Float64Array, occurrence: number): void; queryAround(keys: Float64Array, nbElem: number): greycat.struct.ProfileResult; queryRadius(keys: Float64Array, radius: number): greycat.struct.ProfileResult; queryBoundedRadius(keys: Float64Array, radius: number, max: number): greycat.struct.ProfileResult; queryArea(min: Float64Array, max: Float64Array): greycat.struct.ProfileResult; size(): number; treeSize(): number; } class TreeHelper { static checkBoundsIntersection(targetmin: Float64Array, targetmax: Float64Array, boundMin: Float64Array, boundMax: Float64Array): boolean; static checkKeyInsideBounds(key: Float64Array, boundMin: Float64Array, boundMax: Float64Array): boolean; static getclosestDistance(target: Float64Array, boundMin: Float64Array, boundMax: Float64Array, distance: greycat.utility.distance.Distance): number; static filterAndInsert(key: Float64Array, value: number, target: Float64Array, targetmin: Float64Array, targetmax: Float64Array, targetcenter: Float64Array, distance: greycat.utility.distance.Distance, radius: number, nnl: greycat.internal.tree.VolatileTreeResult): void; } class TreeStrategy { static INDEX: number; static PROFILE: number; static DEFAULT: number; } class VolatileTreeResult implements greycat.struct.ProfileResult { private static maxPriority; private static _KEYS; private static _VALUES; private static _DISTANCES; private node; private capacity; private count; private worst; private _keys; private _values; private _distances; constructor(node: greycat.struct.ENode, capacity: number); size(): number; groupBy(resolutions: Float64Array): greycat.struct.TreeResult; insert(key: Float64Array, value: number, distance: number): boolean; private add(key, value, distance, remove); private remove(); private bubbleUp(pos); private bubbleDown(pos); keys(index: number): Float64Array; value(index: number): number; distance(index: number): number; getWorstDistance(): number; free(): void; isCapacityReached(): boolean; private swap(i, j); private partition(l, h, ascending); private quickSort(l, h, ascending); sort(ascending: boolean): void; } } } module plugin { interface ActionDeclaration { factory(): greycat.plugin.ActionFactory; setFactory(factory: greycat.plugin.ActionFactory): greycat.plugin.ActionDeclaration; params(): Int8Array; setParams(...params: number[]): greycat.plugin.ActionDeclaration; description(): string; setDescription(description: string): greycat.plugin.ActionDeclaration; name(): string; } interface ActionFactory { (params: any[]): greycat.Action; } interface ActionRegistry { declaration(name: string): greycat.plugin.ActionDeclaration; declarations(): greycat.plugin.ActionDeclaration[]; } interface Job { (): void; } interface MemoryFactory { newSpace(memorySize: number, graph: greycat.Graph, deepPriority: boolean): greycat.chunk.ChunkSpace; newBuffer(): greycat.struct.Buffer; } interface NodeDeclaration { name(): string; factory(): greycat.plugin.NodeFactory; setFactory(newFactory: greycat.plugin.NodeFactory): void; } interface NodeFactory { (world: number, time: number, id: number, graph: greycat.Graph): greycat.Node; } interface NodeRegistry { declaration(name: string): greycat.plugin.NodeDeclaration; declarationByHash(hash: number): greycat.plugin.NodeDeclaration; } interface NodeState { world(): number; time(): number; set(index: number, elemType: number, elem: any): void; setFromKey(key: string, elemType: number, elem: any): void; get(index: number): any; getFromKey(key: string): any; getFromKeyWithDefault<A>(key: string, defaultValue: A): A; getWithDefault<A>(key: number, defaultValue: A): A; getOrCreate(index: number, elemType: number): any; getOrCreateFromKey(key: string, elemType: number): any; getType(index: number): number; getTypeFromKey(key: string): number; each(callBack: greycat.plugin.NodeStateCallback): void; } interface NodeStateCallback { (attributeKey: number, elemType: number, elem: any): void; } interface Plugin { start(graph: greycat.Graph): void; stop(): void; } interface Resolver { init(): void; free(): void; initNode(node: greycat.Node, typeCode: number): void; initWorld(parentWorld: number, childWorld: number): void; freeNode(node: greycat.Node): void; typeCode(node: greycat.Node): number; lookup<A extends greycat.Node>(world: number, time: number, id: number, callback: greycat.Callback<A>): void; lookupBatch(worlds: Float64Array, times: Float64Array, ids: Float64Array, callback: greycat.Callback<greycat.Node[]>): void; lookupTimes(world: number, from: number, to: number, id: number, callback: greycat.Callback<greycat.Node[]>): void; lookupAll(world: number, time: number, ids: Float64Array, callback: greycat.Callback<greycat.Node[]>): void; lookupAllTimes(world: number, from: number, to: number, ids: Float64Array, callback: greycat.Callback<greycat.Node[]>): void; resolveState(node: greycat.Node): greycat.plugin.NodeState; alignState(node: greycat.Node): greycat.plugin.NodeState; newState(node: greycat.Node, world: number, time: number): greycat.plugin.NodeState; resolveTimepoints(node: greycat.Node, beginningOfSearch: number, endOfSearch: number, callback: greycat.Callback<Float64Array>): void; stringToHash(name: string, insertIfNotExists: boolean): number; hashToString(key: number): string; externalLock(node: greycat.Node): void; externalUnlock(node: greycat.Node): void; setTimeSensitivity(node: greycat.Node, deltaTime: number, delta: number): void; getTimeSensitivity(node: greycat.Node): Float64Array; } interface ResolverFactory { newResolver(storage: greycat.plugin.Storage, space: greycat.chunk.ChunkSpace): greycat.plugin.Resolver; } interface Scheduler { dispatch(affinity: number, job: greycat.plugin.Job): void; start(): void; stop(): void; workers(): number; } class SchedulerAffinity { static SAME_THREAD: number; static ANY_LOCAL_THREAD: number; static OTHER_LOCAL_THREAD: number; static ANY_REMOTE_THREAD: number; } interface Storage { get(keys: greycat.struct.Buffer, callback: greycat.Callback<greycat.struct.Buffer>): void; put(stream: greycat.struct.Buffer, callback: greycat.Callback<boolean>): void; remove(keys: greycat.struct.Buffer, callback: greycat.Callback<boolean>): void; connect(graph: greycat.Graph, callback: greycat.Callback<boolean>): void; lock(callback: greycat.Callback<greycat.struct.Buffer>): void; unlock(previousLock: greycat.struct.Buffer, callback: greycat.Callback<boolean>): void; disconnect(callback: greycat.Callback<boolean>): void; } interface TaskExecutor { executeTasks(callback: greycat.Callback<string[]>, ...tasks: greycat.Task[]): void; } } module scheduler { class JobQueue { private first; private last; add(item: greycat.plugin.Job): void; poll(): greycat.plugin.Job; } module JobQueue { class JobQueueElem { _ptr: greycat.plugin.Job; _next: greycat.scheduler.JobQueue.JobQueueElem; constructor(ptr: greycat.plugin.Job, next: greycat.scheduler.JobQueue.JobQueueElem); } } class NoopScheduler implements greycat.plugin.Scheduler { dispatch(affinity: number, job: greycat.plugin.Job): void; start(): void; stop(): void; workers(): number; } class TrampolineScheduler implements greycat.plugin.Scheduler { private queue; private wip; dispatch(affinity: number, job: greycat.plugin.Job): void; start(): void; stop(): void; workers(): number; } } module struct { interface Buffer { write(b: number): void; writeAll(bytes: Int8Array): void; read(position: number): number; data(): Int8Array; length(): number; free(): void; iterator(): greycat.struct.BufferIterator; removeLast(): void; slice(initPos: number, endPos: number): Int8Array; } interface BufferIterator { hasNext(): boolean; next(): greycat.struct.Buffer; } interface DMatrix { init(rows: number, columns: number): greycat.struct.DMatrix; fill(value: number): greycat.struct.DMatrix; fillWith(values: Float64Array): greycat.struct.DMatrix; rows(): number; columns(): number; length(): number; column(i: number): Float64Array; get(rowIndex: number, columnIndex: number): number; set(rowIndex: number, columnIndex: number, value: number): greycat.struct.DMatrix; add(rowIndex: number, columnIndex: number, value: number): greycat.struct.DMatrix; appendColumn(newColumn: Float64Array): greycat.struct.DMatrix; data(): Float64Array; leadingDimension(): number; unsafeGet(index: number): number; unsafeSet(index: number, value: number): greycat.struct.DMatrix; } interface EGraph { root(): greycat.struct.ENode; newNode(): greycat.struct.ENode; node(index: number): greycat.struct.ENode; setRoot(eNode: greycat.struct.ENode): greycat.struct.EGraph; drop(eNode: greycat.struct.ENode): greycat.struct.EGraph; size(): number; free(): void; graph(): greycat.Graph; } interface ENode { set(name: string, type: number, value: any): greycat.struct.ENode; setAt(key: number, type: number, value: any): greycat.struct.ENode; get(name: string): any; getAt(key: number): any; getWithDefault<A>(key: string, defaultValue: A): A; getAtWithDefault<A>(key: number, defaultValue: A): A; getOrCreate(key: string, type: number): any; getOrCreateAt(key: number, type: number): any; drop(): void; egraph(): greycat.struct.EGraph; each(callBack: greycat.plugin.NodeStateCallback): void; clear(): greycat.struct.ENode; } interface ERelation { nodes(): greycat.struct.ENode[]; node(index: number): greycat.struct.ENode; size(): number; add(eNode: greycat.struct.ENode): greycat.struct.ERelation; addAll(eNodes: greycat.struct.ENode[]): greycat.struct.ERelation; clear(): greycat.struct.ERelation; } interface LMatrix { init(rows: number, columns: number): greycat.struct.LMatrix; fill(value: number): greycat.struct.LMatrix; fillWith(values: Float64Array): greycat.struct.LMatrix; fillWithRandom(min: number, max: number, seed: number): greycat.struct.LMatrix; rows(): number; columns(): number; column(i: number): Float64Array; get(rowIndex: number, columnIndex: number): number; set(rowIndex: number, columnIndex: number, value: number): greycat.struct.LMatrix; add(rowIndex: number, columnIndex: number, value: number): greycat.struct.LMatrix; appendColumn(newColumn: Float64Array): greycat.struct.LMatrix; data(): Float64Array; leadingDimension(): number; unsafeGet(index: number): number; unsafeSet(index: number, value: number): greycat.struct.LMatrix; } interface LongLongArrayMap extends greycat.struct.Map { get(key: number): Float64Array; put(key: number, value: number): void; delete(key: number, value: number): void; each(callback: greycat.struct.LongLongArrayMapCallBack): void; contains(key: number, value: number): boolean; } interface LongLongArrayMapCallBack { (key: number, value: number): void; } interface LongLongMap extends greycat.struct.Map { get(key: number): number; put(key: number, value: number): void; remove(key: number): void; each(callback: greycat.struct.LongLongMapCallBack): void; } interface LongLongMapCallBack { (key: number, value: number): void; } interface Map { size(): number; } interface Profile extends greycat.struct.Tree { setBufferSize(bufferSize: number): void; profile(keys: Float64Array): void; profileWith(keys: Float64Array, occurrence: number): void; queryAround(keys: Float64Array, max: number): greycat.struct.ProfileResult; queryRadius(keys: Float64Array, radius: number): greycat.struct.ProfileResult; queryBoundedRadius(keys: Float64Array, radius: number, max: number): greycat.struct.ProfileResult; queryArea(min: Float64Array, max: Float64Array): greycat.struct.ProfileResult; } interface ProfileResult extends greycat.struct.TreeResult { groupBy(resolutions: Float64Array): greycat.struct.TreeResult; } interface Relation { all(): Float64Array; size(): number; get(index: number): number; set(index: number, value: number): void; add(newValue: number): greycat.struct.Relation; addAll(newValues: Float64Array): greycat.struct.Relation; addNode(node: greycat.Node): greycat.struct.Relation; insert(index: number, newValue: number): greycat.struct.Relation; remove(oldValue: number): greycat.struct.Relation; delete(oldValue: number): greycat.struct.Relation; clear(): greycat.struct.Relation; } interface RelationIndexed { size(): number; all(): Float64Array; add(node: greycat.Node, ...attributeNames: string[]): greycat.struct.RelationIndexed; remove(node: greycat.Node, ...attributeNames: string[]): greycat.struct.RelationIndexed; clear(): greycat.struct.RelationIndexed; find(callback: greycat.Callback<greycat.Node[]>, world: number, time: number, ...params: string[]): void; findByQuery(query: greycat.Query, callback: greycat.Callback<greycat.Node[]>): void; } interface StringIntMap extends greycat.struct.Map { getValue(key: string): number; getByHash(index: number): string; containsHash(index: number): boolean; put(key: string, value: number): void; remove(key: string): void; each(callback: greycat.struct.StringLongMapCallBack): void; } interface StringLongMapCallBack { (key: string, value: number): void; } interface Tree { setDistance(distanceType: number): void; setResolution(resolution: Float64Array): void; setMinBound(min: Float64Array): void; setMaxBound(max: Float64Array): void; insert(keys: Float64Array, value: number): void; queryAround(keys: Float64Array, max: number): greycat.struct.TreeResult; queryRadius(keys: Float64Array, radius: number): greycat.struct.TreeResult; queryBoundedRadius(keys: Float64Array, radius: number, max: number): greycat.struct.TreeResult; queryArea(min: Float64Array, max: Float64Array): greycat.struct.TreeResult; size(): number; treeSize(): number; } interface TreeResult { insert(key: Float64Array, value: number, distance: number): boolean; keys(index: number): Float64Array; value(index: number): number; distance(index: number): number; getWorstDistance(): number; isCapacityReached(): boolean; sort(ascending: boolean): void; free(): void; size(): number; } } module utility { class Base64 { private static dictionary; private static powTwo; private static longIndexes; static encodeLongToBuffer(l: number, buffer: greycat.struct.Buffer): void; static encodeIntToBuffer(l: number, buffer: greycat.struct.Buffer): void; static decodeToLong(s: greycat.struct.Buffer): number; static decodeToLongWithBounds(s: greycat.struct.Buffer, offsetBegin: number, offsetEnd: number): number; static decodeToInt(s: greycat.struct.Buffer): number; static decodeToIntWithBounds(s: greycat.struct.Buffer, offsetBegin: number, offsetEnd: number): number; static encodeDoubleToBuffer(d: number, buffer: greycat.struct.Buffer): void; static decodeToDouble(s: greycat.struct.Buffer): number; static decodeToDoubleWithBounds(s: greycat.struct.Buffer, offsetBegin: number, offsetEnd: number): number; static encodeBoolArrayToBuffer(boolArr: Array<boolean>, buffer: greycat.struct.Buffer): void; static decodeBoolArray(s: greycat.struct.Buffer, arraySize: number): any[]; static decodeToBoolArrayWithBounds(s: greycat.struct.Buffer, offsetBegin: number, offsetEnd: number, arraySize: number): any[]; static encodeStringToBuffer(s: string, buffer: greycat.struct.Buffer): void; static decodeString(s: greycat.struct.Buffer): string; static decodeToStringWithBounds(s: greycat.struct.Buffer, offsetBegin: number, offsetEnd: number): string; } class BufferView implements greycat.struct.Buffer { private _origin; private _initPos; private _endPos; constructor(p_origin: greycat.struct.Buffer, p_initPos: number, p_endPos: number); write(b: number): void; writeAll(bytes: Int8Array): void; read(position: number): number; data(): Int8Array; length(): number; free(): void; iterator(): greycat.struct.BufferIterator; removeLast(): void; slice(initPos: number, endPos: number): Int8Array; } class DefaultBufferIterator implements greycat.struct.BufferIterator { private _origin; private _originSize; private _cursor; constructor(p_origin: greycat.struct.Buffer); hasNext(): boolean; next(): greycat.struct.Buffer; } class Enforcer { private checkers; asBool(propertyName: string): greycat.utility.Enforcer; asString(propertyName: string): greycat.utility.Enforcer; asLong(propertyName: string): greycat.utility.Enforcer; asLongWithin(propertyName: string, min: number, max: number): greycat.utility.Enforcer; asDouble(propertyName: string): greycat.utility.Enforcer; asDoubleWithin(propertyName: string, min: number, max: number): greycat.utility.Enforcer; asInt(propertyName: string): greycat.utility.Enforcer; asIntWithin(propertyName: string, min: number, max: number): greycat.utility.Enforcer; asIntGreaterOrEquals(propertyName: string, min: number): greycat.utility.Enforcer; asDoubleArray(propertyName: string): greycat.utility.Enforcer; asPositiveInt(propertyName: string): greycat.utility.Enforcer; asNonNegativeDouble(propertyName: string): greycat.utility.Enforcer; asPositiveDouble(propertyName: string): greycat.utility.Enforcer; asNonNegativeOrNanDouble(propertyName: string): greycat.utility.Enforcer; asPositiveLong(propertyName: string): greycat.utility.Enforcer; declare(propertyName: string, checker: greycat.utility.EnforcerChecker): greycat.utility.Enforcer; check(propertyName: string, propertyType: number, propertyValue: any): void; } interface EnforcerChecker { check(inputType: number, input: any): void; } class HashHelper { private static PRIME1; private static PRIME2; private static PRIME3; private static PRIME4; private static PRIME5; private static len; private static byteTable; private static HSTART; private static HMULT; static longHash(number: number, max: number): number; static simpleTripleHash(p0: number, p1: number, p2: number, p3: number, max: number): number; static tripleHash(p0: number, p1: number, p2: number, p3: number, max: number): number; static rand(): number; static equals(src: string, other: string): boolean; static DOUBLE_MIN_VALUE(): number; static DOUBLE_MAX_VALUE(): number; static isDefined(param: any): boolean; static hash(data: string): number; static hashBytes(data: Int8Array): number; } class KeyHelper { static keyToBuffer(buffer: greycat.struct.Buffer, chunkType: number, world: number, time: number, id: number): void; } class Tuple<A, B> { private _left; private _right; constructor(p_left: A, p_right: B); left(): A; right(): B; } class VerboseHook implements greycat.TaskHook { private ctxIdents; start(initialContext: greycat.TaskContext): void; beforeAction(action: greycat.Action, context: greycat.TaskContext): void; afterAction(action: greycat.Action, context: greycat.TaskContext): void; beforeTask(parentContext: greycat.TaskContext, context: greycat.TaskContext): void; afterTask(context: greycat.TaskContext): void; end(finalContext: greycat.TaskContext): void; } class VerbosePlugin implements greycat.plugin.Plugin { start(graph: greycat.Graph): void; stop(): void; } module distance { class CosineDistance implements greycat.utility.distance.Distance { private static static_instance; static instance(): greycat.utility.distance.CosineDistance; constructor(); measure(x: Float64Array, y: Float64Array): number; compare(x: number, y: number): boolean; getMinValue(): number; getMaxValue(): number; } interface Distance { measure(x: Float64Array, y: Float64Array): number; compare(x: number, y: number): boolean; getMinValue(): number; getMaxValue(): number; } class Distances { static EUCLIDEAN: number; static GEODISTANCE: number; static COSINE: number; static PEARSON: number; static GAUSSIAN: number; static DEFAULT: number; static getDistance(distance: number, distancearg: Float64Array): greycat.utility.distance.Distance; } class EuclideanDistance implements greycat.utility.distance.Distance { private static static_instance; static instance(): greycat.utility.distance.EuclideanDistance; constructor(); measure(x: Float64Array, y: Float64Array): number; compare(x: number, y: number): boolean; getMinValue(): number; getMaxValue(): number; } class GaussianDistance implements greycat.utility.distance.Distance { err: Float64Array; constructor(covariance: Float64Array); measure(x: Float64Array, y: Float64Array): number; compare(x: number, y: number): boolean; getMinValue(): number; getMaxValue(): number; } class GeoDistance implements greycat.utility.distance.Distance { private static static_instance; static instance(): greycat.utility.distance.GeoDistance; constructor(); measure(x: Float64Array, y: Float64Array): number; private static toRadians(angledeg); compare(x: number, y: number): boolean; getMinValue(): number; getMaxValue(): number; } class PearsonDistance implements greycat.utility.distance.Distance { private static static_instance; static instance(): greycat.utility.distance.PearsonDistance; constructor(); measure(a: Float64Array, b: Float64Array): number; compare(x: number, y: number): boolean; getMinValue(): number; getMaxValue(): number; } } } } <file_sep>/** * Copyright 2017 The GreyCat Authors. All rights reserved. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 greycat.model; import greycat.Graph; import greycat.base.BaseNode; public class MetaClass extends BaseNode { static final String NAME = "MetaClass"; MetaClass(long p_world, long p_time, long p_id, Graph p_graph) { super(p_world, p_time, p_id, p_graph); } } <file_sep>/// /// Copyright 2017 The GreyCat Authors. All rights reserved. /// <p> /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// <p> /// http://www.apache.org/licenses/LICENSE-2.0 /// <p> /// 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. /// import * as greycat from "greycat"; export class WSClient implements greycat.plugin.Storage { private url: string; private callbacks; private ws: WebSocket = null; private graph: greycat.Graph = null; private generator: number = 0; private REQ_GET = 0; private REQ_PUT = 1; private REQ_LOCK = 2; private REQ_UNLOCK = 3; private REQ_REMOVE = 4; private REQ_UPDATE = 5; private REQ_TASK = 6; private RESP_GET = 7; private RESP_PUT = 8; private RESP_REMOVE = 9; private RESP_LOCK = 10; private RESP_UNLOCK = 11; private RESP_TASK = 12; constructor(p_url: string) { this.url = p_url; this.callbacks = {}; } connect(p_graph: greycat.Graph, callback: greycat.Callback<boolean>): void { this.graph = p_graph; if (this.ws == null) { let selfPointer = this; this.ws = new WebSocket(this.url); this.ws.onopen = function (event: MessageEvent) { callback(true); }; this.ws.onmessage = function (msg: MessageEvent) { let fr = new FileReader(); fr.onload = function(){ selfPointer.process_rpc_resp(new Int8Array(fr.result)); }; fr.readAsArrayBuffer(msg.data); }; } else { //do nothing callback(true); } } disconnect(callback: greycat.Callback<boolean>): void { if (this.ws != null) { this.ws.close(); this.ws = null; callback(true); } } get(keys: greycat.struct.Buffer, callback: greycat.Callback<greycat.struct.Buffer>): void { this.send_rpc_req(this.REQ_GET, keys, callback); } put(stream: greycat.struct.Buffer, callback: greycat.Callback<boolean>): void { this.send_rpc_req(this.REQ_PUT, stream, callback); } remove(keys: greycat.struct.Buffer, callback: greycat.Callback<boolean>): void { this.send_rpc_req(this.REQ_REMOVE, keys, callback); } lock(callback: greycat.Callback<greycat.struct.Buffer>): void { this.send_rpc_req(this.REQ_LOCK, null, callback); } unlock(previousLock: greycat.struct.Buffer, callback: greycat.Callback<boolean>): void { this.send_rpc_req(this.REQ_UNLOCK, previousLock, callback); } executeTasks(callback: greycat.Callback<String[]>, ...tasks: greycat.Task[]): void { let tasksBuffer = this.graph.newBuffer(); for (let i = 0; i < tasks.length; i++) { if (i != 0) { tasksBuffer.write(greycat.Constants.BUFFER_SEP); } tasks[i].saveToBuffer(tasksBuffer); } let finalCB = callback; this.send_rpc_req(this.REQ_TASK, tasksBuffer, function (resultBuffer) { let result = []; let it = resultBuffer.iterator(); while (it.hasNext()) { let view = it.next(); result.push(greycat.utility.Base64.decodeToStringWithBounds(view, 0, view.length())); } resultBuffer.free(); finalCB(result); }); } process_rpc_resp(payload: Int8Array) { let payloadBuf = this.graph.newBuffer(); payloadBuf.writeAll(payload); let it = payloadBuf.iterator(); let codeView = it.next(); if (codeView != null && codeView.length() != 0) { let firstCode = codeView.read(0); if (firstCode == this.REQ_UPDATE) { //console.log("NOTIFY UPDATE"); //TODO } else { let callbackCodeView = it.next(); if (callbackCodeView != null) { let callbackCode = greycat.utility.Base64.decodeToIntWithBounds(callbackCodeView, 0, callbackCodeView.length()); let resolvedCallback = this.callbacks[callbackCode]; this.callbacks[callbackCode] = undefined; if (resolvedCallback != null) { if (firstCode == this.RESP_GET || firstCode == this.RESP_LOCK || firstCode == this.RESP_TASK) { let newBuf = this.graph.newBuffer(); let isFirst = true; while (it.hasNext()) { if (isFirst) { isFirst = false; } else { newBuf.write(greycat.Constants.BUFFER_SEP); } newBuf.writeAll(it.next().data()); } resolvedCallback(newBuf); } else { resolvedCallback(true); } } } } } } send_rpc_req(code: number, payload: greycat.struct.Buffer, callback: greycat.Callback<any>): void { if (this.ws == null) { throw new Error("Not connected!"); } let buffer: greycat.struct.Buffer = this.graph.newBuffer(); buffer.write(code); buffer.write(greycat.Constants.BUFFER_SEP); let hash = this.generator; this.generator = this.generator + 1 % 1000000; this.callbacks[hash] = callback; greycat.utility.Base64.encodeIntToBuffer(hash, buffer); if (payload != null) { buffer.write(greycat.Constants.BUFFER_SEP); buffer.writeAll(payload.data()); } let flatData = buffer.data(); buffer.free(); this.ws.send(flatData); } } <file_sep>GreyCat documentation is coming soon ... stay tuned ! ================== For any questions please contact us via our Gitter: [![Join the chat at https://gitter.im/datathings/greycat](https://badges.gitter.im/datathings/greycat.svg)](https://gitter.im/datathings/greycat?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![Build Status](https://travis-ci.org/datathings/greycat.svg?branch=master)](https://travis-ci.org/datathings/greycat) # Changelog ## Version 4 (planned for 03/03/17) - fix free bug in flat task action - define interfaces for Blas plugin - cleanup build scripts - implement multi-get within RocksDB plugin ## Version 3 (27/02/17) - fix apriori dirty element on get - fix dirty flag after remote state chunk load *(need global check)* - fix dirty flag after remote timetree chunk load *(need global check)* - switch test execution with full NPM management - use J2TS-JUNIT (https://www.npmjs.com/search?q=j2ts-junit) - rename sub test package as greycatTest to avoid conflict for NPM - new RocksDB support for ARM-V7 processor - closing issue #3 add TypeScript correct typing header to NPM - alignement of interface NodeState, StateChunk and Node (all inherit from container) ## Version 2 (17/02/17) - introduce new NPM packaging (https://www.npmjs.com/package/greycat) - use J2TS-JRE (https://www.npmjs.com/search?q=j2ts-junit) - rename base package as greycat - closing #2 ## Version 1 - first release with the GreyCat name, mostly renamed from ManyWorldGraph project <file_sep>/** * Copyright 2017 The GreyCat Authors. All rights reserved. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 greycat.ml; import greycat.*; import greycat.struct.EGraph; import greycat.struct.ENode; /** * Created by assaad on 23/02/2017. */ public class BugTest { public static void main(String[] arg) { Graph g = GraphBuilder.newBuilder().build(); g.connect(new Callback<Boolean>() { @Override public void on(Boolean result) { Node hostnode = g.newNode(0, 0); //Creating an egraph at time 0, will call it eg0 EGraph eg0 = (EGraph) hostnode.getOrCreate("egraph", Type.EGRAPH); ENode enode0 = eg0.newNode(); enode0.set("total", Type.INT, 1); enode0.set("sum", Type.DOUBLE_ARRAY, new double[]{0, 0, 0}); hostnode.travelInTime(1, new Callback<Node>() { @Override public void on(Node hostnode1) { hostnode1.rephase(); //rephase the state EGraph eg1 = (EGraph) hostnode1.getOrCreate("egraph",Type.EGRAPH); ENode enode1 = eg1.root(); int total= (int) enode1.get("total"); enode1.set("total", Type.INT,total+1); double[] sum= ((double[]) enode1.get("sum")); sum[0]++; sum[1]++; sum[2]++; enode1.set("sum", Type.DOUBLE_ARRAY, sum); } }); hostnode.travelInTime(0, new Callback<Node>() { @Override public void on(Node res0) { EGraph egres0 = (EGraph) res0.getOrCreate("egraph",Type.EGRAPH); ENode enoderes0 = egres0.root(); int total= (int) enoderes0.get("total"); double[] sum= (double[]) enoderes0.get("sum"); System.out.println("time 0: total: "+total+" sum:["+sum[0]+","+sum[1]+","+sum[2]+"]"); } }); hostnode.travelInTime(1, new Callback<Node>() { @Override public void on(Node res1) { EGraph egres1 = (EGraph) res1.getOrCreate("egraph",Type.EGRAPH); ENode enoderes1 = egres1.root(); int total= (int) enoderes1.get("total"); double[] sum= (double[]) enoderes1.get("sum"); System.out.println("time 1: total: "+total+" sum:["+sum[0]+","+sum[1]+","+sum[2]+"]"); } }); } }); } }
4ca5b793251230fd3ef1900b009b2d79c0a4b850
[ "Markdown", "Java", "TypeScript", "Maven POM" ]
6
Maven POM
nikosantoniadis/greycat
9e6c798e877119aa4bb582d766364b9fe3b03ee6
d9393f3c09f298aacb115e4db282f1f909629684
refs/heads/master
<repo_name>softwareSJ/softwareSJ.github.io<file_sep>/Tea/js/register.js function $(id){ return typeof id==='string'?document.getElementById(id):id; } function getLength(str){ return str.replace(/[^\x00-xff]/g,"xx").length; } window.onload=function(){ var count=document.getElementById("count"); document.getElementById("input1").onfocus=function(){ document.getElementById("span1").style.display="block"; } var name_length=0; document.getElementById("input1").onkeyup=function(){ name_length=name_length+1; document.getElementById("count").innerHTML=name_length+"个字符"; document.getElementById("count").style.display="block"; name_length=getLength(this.value); // document.getElementById("count").innerHTML=name_lenght; if(name_length==0){ count.style.display="none"; } } document.getElementById("input1").onblur=function(){ var re=/[^\w\u4e00-\u9fa5]/g; if(re.test(this.value)){ document.getElementById("span1").innerText="含有非法字符!" } else if(this.value==""){ document.getElementById("span1").innerText="不能为空!" } else if(name_length>25){ document.getElementById("span1").innerText="长度超过25个字符!请重新输入!" } else if(name_length<6){ document.getElementById("span1").innerText="长度少于6个字符!请重新输入!" } else{ document.getElementById("span1").style.color="green" document.getElementById("span1").innerText="OK" } } var em=document.getElementsByTagName("em"); var pwd=document.getElementById("input2"); pwd.onkeyup=function(){ if(this.value.length>5){ em[1].className="active"; document.getElementById("span2").innerText="中" document.getElementById("span2").style.display="block"; if(this.value.length>12){ em[2].className="active"; document.getElementById("span2").innerText="强" document.getElementById("span2").style.display="block"; } else if(this.value.length<12){ em[2].className=""; } else if(this.value.length==0){ em[2].className=""; } } else{ em[1].className=""; document.getElementById("span2").innerText="弱" document.getElementById("span2").style.display="block"; } } function findStr(str,n){ var tmp=0; for(var i=0;i<str.length;i++){ if(str.charAt(i)==n){ tmp++; } } return tmp; } pwd.onblur=function(){ //var m=findStr(pwd.value,pwd.value[0]); var re_n=/[^\d]/g; var re_t=/[^a-zA-Z]/g; if(this.value==""){ document.getElementById("span2").innerText="密码不能为空!" //document.getElementById("span2").style.display="block"; } else if(findStr(pwd.value,pwd.value[0])==this.value.length){ document.getElementById("span2").innerText="不能使用相同字符!" } else if(this.value.length<6||this.value.length>16){ document.getElementById("span2").innerText="长度应为6-16个字符!" } else if(!re_n.test(this.value)){ document.getElementById("span2").innerText="不能全为数字!" } else if(!re_t.test(this.value)){ document.getElementById("span2").innerText="不能全为字母!" } else{ document.getElementById("span2").style.color="green" document.getElementById("span2").innerText="OK" } } var rpwd=document.getElementById("input3"); document.getElementById("input3").onblur=function(){ if(this.value!=document.getElementById("input2").value){ document.getElementById("span3").innerText="两次输入不一致,请再次确认!" document.getElementById("span3").style.display="block"; } else if(this.value==""){ document.getElementById("span3").style.display="none"; } else{ document.getElementById("span3").style.color="green" document.getElementById("span3").innerText="OK" } } // document.getElementById('input4').onblur=function (obj,str,allowNull){ // var pattern = /^((\(\d{3}\))|(\d{3}\-))?13\d{9}$/; // //if(!isNotNull(obj,str,allowNull)) return false; // if(!(pattern.test(document.getElementById('input4').value))){ // // document.getElementById('doing').style.visibility='hidden'; // document.getElementById("span4").innerText="不是正确的手机号!" // //alert(str+" 不是正确的手机号码!"); // document.getElementById('input4').focus(); // return false; // } //// else if(pattern.test(document.getElementById('input4').value)){ //// document.getElementById("span4").innerText="OK!" //// } // else return true; // } var inp = document.getElementById("input6"); var code = document.getElementById("span6"); var c = new KinerCode({ len: 4, chars: [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' ], question:false, copy: false, bgColor:"", bgImg:"bg.jpg", randomBg : false, inputArea: inp, codeArea: code, click2refresh:true, false2refresh:true, validateEven : "blur", validateFn : function(result,code){ if(result){ document.getElementById("codemsg").style.color="green" document.getElementById("codemsg").innerHTML="验证成功!" }else{ if(this.opt.question){ }else{ document.getElementById("codemsg").style.color="red" document.getElementById("codemsg").innerHTML="验证失败!" // alert('验证失败:'+code.strCode); // alert('验证失败:' + code.arrCode); } } } }); // var input=$('table').getElementsByTagName('input'); //var spanmsg=$('table').getElementsByTagName('span'); //for(var i=0;i<input.length;i++){ // input[i].id=i; //} // var test_input=document.getElementsByTagName("input"); // var uesername=test_input[0]; // var psd=test_input[1]; // var rpsd=test_input[2]; // var phone=test_input[3]; // var email=test_input[4]; // var code=test_input[5]; // var b_span=document.getElementsByTagName("span"); // var uesername-t=b_span[0]; // var psd-t=b_span[1]; // var rpsd-t=b_span[2]; // var phone-t=b_span[3]; // var email-t=b_span[4]; // var code-t=b_span[5]; // var re=/[^\w\u4e00-\u9fa5]/g; // uesername.onfocus=function(){ // uesername-t.style.display="block"; // } } <file_sep>/dongyuan1/js/ss.js $(document).ready(function () { $("#a1").click(function () { $("#p1").slideToggle(); }); }); $(document).ready(function () { $("#a2").click(function () { $("#p2").slideToggle(); }); }); $(document).ready(function () { $("#a3").click(function () { $("#p3").slideToggle(); }); }); $(document).ready(function () { $("#a4").click(function () { $("#p4").slideToggle(); }); });<file_sep>/dongyuan1/js/new_file.js $(document).ready(function () { $("#img1").click(function(){ document.getElementById("text1").style.display="none"; document.getElementById("text2").style.display="none"; document.getElementById("text3").style.display="none"; document.getElementById("text4").style.display="none"; $("#text1").fadeIn(3000); }); }); $(document).ready(function () { $("#img2").click(function(){ document.getElementById("text1").style.display="none"; document.getElementById("text2").style.display="none"; document.getElementById("text3").style.display="none"; document.getElementById("text4").style.display="none"; $("#text2").fadeIn(3000); }); }); $(document).ready(function () { $("#img3").click(function(){ document.getElementById("text1").style.display="none"; document.getElementById("text2").style.display="none"; document.getElementById("text3").style.display="none"; document.getElementById("text4").style.display="none"; $("#text3").fadeIn(3000); }); }); $(document).ready(function () { $("#img4").click(function(){ document.getElementById("text1").style.display="none"; document.getElementById("text2").style.display="none"; document.getElementById("text3").style.display="none"; document.getElementById("text4").style.display="none"; $("#text4").fadeIn(3000); }); });<file_sep>/Fish/js/small_fish.js var sfishObj=function(){ this.x; this.y; this.angle; this.smallEye=new Image(); this.smallBody=new Image(); this.smallTail=new Image(); this.sfishTailTimer=0; this.sfishTailCount=0; this.sfishEyeTimer=0; this.sfishEyeCount=0; this.sfishEyeInterval=1000; this.sfishBodyTimer=0; this.sfishBodyCount=0; } sfishObj.prototype.init=function(){ this.x=canWidth*0.5-50; this.y=canHeight*0.5+50; this.angle=0; this.smallBody.src="./image/babyFade0.png"; } sfishObj.prototype.draw=function(){ this.x=lerpDistance(bfish.x, this.x, 0.98); this.y=lerpDistance(bfish.y, this.y, 0.98); var deltaY=bfish.y-this.y; var deltaX=bfish.x-this.x; var beta=Math.atan2(deltaY,deltaX)+Math.PI; this.angle=lerpAngle(beta,this.angle,0.6); // tail this.sfishTailTimer+=deltaTime; if(this.sfishTailTimer>50){ this.sfishTailCount=(this.sfishTailCount+1)%8; this.sfishTailTimer%=50; } // babyEye this.sfishEyeTimer+=deltaTime; if(this.sfishEyeTimer>this.sfishEyeInterval){ this.sfishEyeCount=(this.sfishEyeCount+1)%2; this.sfishEyeTimer%=this.sfishEyeInterval; if(this.sfishEyeCount==0){ this.sfishEyeInterval=Math.random()*1500+2000; }else{ this.sfishEyeInterval=200; } } // babyBody this.sfishBodyTimer+=deltaTime; if(this.sfishBodyTimer>300){ this.sfishBodyCount=this.sfishBodyCount+1; this.sfishBodyTimer%=300; if(this.sfishBodyCount>19){ this.sfishBodyCount=19; data.gameOver=true; } } ctx1.save(); ctx1.translate(this.x,this.y); ctx1.rotate(this.angle); var sfishTailCount=this.sfishTailCount; ctx1.drawImage(sfishTail[sfishTailCount],-sfishTail[sfishTailCount].width*0.5+25,-sfishTail[sfishTailCount].height*0.5); var sfishBodyCount=this.sfishBodyCount; ctx1.drawImage(sfishBody[sfishBodyCount],-sfishBody[sfishBodyCount].width*0.5,-sfishBody[sfishBodyCount].height*0.5); var sfishEyeCount=this.sfishEyeCount; ctx1.drawImage(sfishEye[sfishEyeCount],-sfishEye[sfishEyeCount].width*0.5,-sfishEye[sfishEyeCount].height*0.5); ctx1.restore(); }<file_sep>/dongyuan1/js/script.js $(document).ready(function () { $("#bt1").click(function(){ $("#bt2,#bt3,#bt4").removeClass(); $(this).addClass("tuchu-style"); $(".show_1").show(); $(".show_2,.show_3,.show_4").hide(); }); $("#bt2").click(function(){ $("#bt1,#bt3,#bt4").removeClass(); $(this).addClass("tuchu-style"); $(".show_2").show(); $(".show_1,.show_3,.show_4").hide(); }); $("#bt3").click(function(){ $("#bt1,#bt2,#bt4").removeClass(); $(this).addClass("tuchu-style"); $(".show_3").show(); $(".show_1,.show_2,.show_4").hide(); }); $("#bt4").click(function(){ $("#bt1,#bt2,#bt3").removeClass(); $(this).addClass("tuchu-style"); $(".show_4").show(); $(".show_1,.show_2,.show_3").hide(); }); }); //function $(id){ // return typeof id==='string'?document.getElementById(id):id; //} // //window.onload=tab; //var lis=$('ulstyle').getElementsByTagName('li'); //var divs=$('show').getElementsByTagName('div'); //function tab(){ // ////if(lis.length!=divs.length) return; //for(var i=0;i<lis.length;i++){ // lis[i].id=i; // lis[i].onclick=function(){ // for(var j=0;j<lis.length;j++){ // lis[j].className=''; // divs[j].style.display='none'; // } // // this.className='tuchu-style'; // divs[this.id].style.display='block'; // // } // //} //} //function changeOption(curIndex){ // for(var j=0;j<lis.length;j++){ // lis[j].className=''; // divs[j].style.display='none'; // } // lis[curIndex].className='select'; // divs[curIndex].style.display='block'; // index=curIndex; //} <file_sep>/Fish/js/big_fish.js var bfishObj=function(){ this.x; this.y; this.angle; this.bigEye=new Image(); this.bigBody=new Image(); this.bigTail=new Image(); this.bfishTailTimer=0; this.bfishTailCount=0; this.bfishEyeTimer=0; this.bfishEyeCount=0; this.bfishEyeInterval=1000; this.bfishBodyTimer=0; this.bfishBodyCount=0; } bfishObj.prototype.init=function(){ this.x=canWidth*0.5; this.y=canHeight*0.5; this.angle=0; this.bigEye.src="./image/bigEye0.png"; this.bigBody.src="./image/bigSwim0.png"; } bfishObj.prototype.draw=function(){ this.x=lerpDistance(mx, this.x, 0.98); this.y=lerpDistance(my, this.y, 0.98); var deltaY=my-this.y; var deltaX=mx-this.x; var beta=Math.atan2(deltaY,deltaX)+Math.PI; this.angle=lerpAngle(beta,this.angle,0.6); // tail this.bfishTailTimer+=deltaTime; if(this.bfishTailTimer>50){ this.bfishTailCount=(this.bfishTailCount+1)%8; this.bfishTailTimer%=50; } // eye this.bfishEyeTimer+=deltaTime; if(this.bfishEyeTimer>this.bfishEyeInterval){ this.bfishEyeCount=(this.bfishEyeCount+1)%2; this.bfishEyeTimer%=this.bfishEyeInterval; if(this.bfishEyeCount==0){ this.bfishEyeInterval=Math.random()*1500+2000; }else{ this.bfishEyeInterval=200; } } // body this.bfishBodyTimer+=deltaTime; if(this.bfishBodyTimer>300){ this.bfishBodyCount=this.bfishBodyCount+1; this.bfishBodyTimer%=300; if(this.bfishBodyCount>7){ this.bfishBodyCount=7; } } ctx1.save(); ctx1.translate(this.x,this.y); ctx1.rotate(this.angle); // tail var bfishTailCount=this.bfishTailCount; ctx1.drawImage(bfishTail[bfishTailCount],-bfishTail[bfishTailCount].width*0.5+30,-bfishTail[bfishTailCount].height*0.5); var bfishBodyCount=this.bfishBodyCount; if(data.double==1){ ctx1.drawImage(bfishBodyOrange[bfishBodyCount],-bfishBodyOrange[bfishBodyCount].width*0.5,-bfishBodyOrange[bfishBodyCount].height*0.5); } else{ ctx1.drawImage(bfishBodyBlue[bfishBodyCount],-bfishBodyBlue[bfishBodyCount].width*0.5,-bfishBodyBlue[bfishBodyCount].height*0.5); } var bfishEyeCount=this.bfishEyeCount; ctx1.drawImage(bfishEye[bfishEyeCount],-bfishEye[bfishEyeCount].width*0.5,-bfishEye[bfishEyeCount].height*0.5); // bigEye ctx1.restore(); }<file_sep>/Fish/js/pengzhuang.js // 判断鱼和果实的距离 function bfishandfruit(){ if(!data.gameOver){ for(var i=0;i<fruit.num;i++){ if(fruit.alive[i]){ var l=calLength2(fruit.x[i],fruit.y[i],bfish.x,bfish.y); if(l<500){ fruit.dead(i); data.fruitNum++; bfish.bfishBodyCount++; if(bfish.bfishBodyCount>7) bfish.bfishBodyCount=7; if(fruit.fruitType[i]=="blue"){ data.double=2; } wave.born(fruit.x[i],fruit.y[i]); } } } } } // 大鱼和小鱼的距离 function bfishandsfish(){ if(data.fruitNum>0 && !data.gameOver){ var l=calLength2(bfish.x,bfish.y,sfish.x,sfish.y); if(l<900){ sfish.sfishBodyCount=0; bfish.bfishBodyCount=0; // score data.addScore(); wavefish.born(sfish.x,sfish.y); } } }<file_sep>/Tea/js/login.js window.onload function(){ var username=document.getElementById("username"); var table=document.getElementsByTagName() username.onfocus=function(){ } } <file_sep>/Christmas/script.js /** * Created by Administrator on 16-8-29. */ var canvas = document.getElementById("canvas"), context = canvas.getContext("2d"), animateButton = document.getElementById("animateButton"), snow = new Image(), sled = new Image(), snow1=new Image(), snow2=new Image(), background = new Image(), paused = true, lastTime = 0, fps = 60, backgroundOffset = 0, snowOffset = 0, sledOffset = 0, SNOW_VELOCITY = 35, SLED_VELOCITY = 40, BCK_VELOCITY=25; function erase(){ context.clearRect(0,0,canvas.width,canvas.height); } function draw(){ context.save(); //计算出绘制四个图层时需要对坐标系进行平移的距离 backgroundOffset = backgroundOffset<canvas.width?backgroundOffset+BCK_VELOCITY/fps:0; snowOffset = snowOffset<canvas.width?snowOffset+SNOW_VELOCITY/fps:0; sledOffset = sledOffset<canvas.width?sledOffset+SLED_VELOCITY/fps:0; context.save(); context.translate(backgroundOffset,0); context.drawImage(background,0,0); context.drawImage(background,-(background.width-2),0); context.restore(); context.save(); context.translate(0,snowOffset); context.drawImage(snow,500,0); context.drawImage(snow,100,100); context.drawImage(snow,200,50); context.drawImage(snow1,450,20); context.drawImage(snow1,350,70); context.drawImage(snow2,300,50); context.drawImage(snow1,500,-100); context.drawImage(snow2,100,-150); context.drawImage(snow,200,-250); context.drawImage(snow1,450,-220); context.drawImage(snow1,350,-370); context.drawImage(snow2,300,-150); context.drawImage(snow,100,-120); context.drawImage(snow,200,-50); context.restore(); context.save(); context.translate(-sledOffset,0); context.drawImage(sled,canvas.width,230); context.restore(); } function calculateFps(now){ var fps = 1000/(now-lastTime); lastTime = now; return fps; } function animate(now){ if(now===undefined){ now=+new Date; } fps = calculateFps(now); if(!paused){ erase(); draw(); } requestNextAnimationFrame(animate); } animateButton.onclick = function(e){ paused = paused ? false:true; if(paused){ animateButton.value = "Animate"; } else { animateButton.value = "Pause"; } } context.font="48px Helvetia"; snow.src = "image/雪花.png"; sled.src = "image/雪橇.png"; snow1.src = "image/雪花1.png"; snow2.src = "image/雪花2.png"; background.src = "image/背景.png"; background.onload = function(e){ draw(); }; requestNextAnimationFrame(animate);
57ed9cbd502bedfc4e31bde6b67597647143cfb5
[ "JavaScript" ]
9
JavaScript
softwareSJ/softwareSJ.github.io
28c7c6e229edc0e00e2a39218b1c603c1e5870a7
cc3753fa4ba94165f9dd67a0f908f8374180b247
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace CRUD_Operations_Using_EF.Models { public class Student { private int Id; private string Name; private string Email; private string City; private string PhoneNumber; public List<Student> StudentDetails { get; set; } [Required(ErrorMessage="Id is required !!")] public int ID { get { return Id; } set { Id = value; } } [Required(ErrorMessage="Name is required !!")] public string NAME { get { return Name; } set { Name = value; } } [CustomEmailValidator] // [Required(ErrorMessage="Email id is required !!")] public string EMAIL { get { return Email; } set { Email = value; } } [Required(ErrorMessage="City is needed, for better alignment.")] public string CITY { get { return City; } set { City = value; } } [CustomPhoneNumberValidator] public string PHONENUMBER { get { return PhoneNumber; } set { PhoneNumber = value; } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using CRUD_Operations_Using_EF.Models; using System.Configuration; using System.Web.Mvc; using System.Data.SqlClient; namespace CRUD_Operations_Using_EF.SqlUtility { public static class SqlUtilityClass { public static string ConnectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ToString(); public static void Insertion(Student modelData) { string InsertQuery = "INSERT INTO Student_TB (Id, Name, Email, City) VALUES ('" + modelData.ID + "','" + modelData.NAME + "','" + modelData.EMAIL + "','" + modelData.CITY + "','"+modelData.PHONENUMBER+"')"; try { using (SqlConnection connection = new SqlConnection(ConnectionString)) { using (SqlCommand command = new SqlCommand(InsertQuery)) { command.Connection = connection; connection.Open(); command.ExecuteNonQuery(); connection.Close(); } } } catch (Exception) { new Exception("Could not save data, please try again !!"); } } public static void Update(Student modelData) { string UpdateQuery = "UPDATE Student_TB SET Id='" + modelData.ID + "', Name='" + modelData.NAME + "', Email='" + modelData.EMAIL + "', City='" + modelData.CITY + "',PhoneNumber='" + modelData.PHONENUMBER + "'"; try { using (SqlConnection connection = new SqlConnection(ConnectionString)) { using (SqlCommand command = new SqlCommand(UpdateQuery)) { command.Connection = connection; connection.Open(); command.ExecuteNonQuery(); connection.Close(); } } } catch (Exception) { new Exception("Could not save data, please try again !!"); } } public static void Delete(Student modelData) { string DeleteQuery = "DELETE FROM Student_TB where (Student_TB.Id = '" + modelData.ID + "')"; try { using (SqlConnection connection = new SqlConnection(ConnectionString)) { using (SqlCommand command = new SqlCommand(DeleteQuery)) { command.Connection = connection; connection.Open(); command.ExecuteNonQuery(); connection.Close(); } } } catch (Exception) { new Exception("Could not save data, please try again !!"); } } public static void StudentDetails(Student studentDetails) { string DetailsQuery = "SELECT * FROM Student_TB where (Student_TB.Id = '" + studentDetails.ID + "')"; try { using (SqlConnection connection = new SqlConnection(ConnectionString)) { using (SqlCommand command = new SqlCommand(DetailsQuery)) { command.Connection = connection; connection.Open(); command.ExecuteNonQuery(); connection.Close(); } } } catch (Exception) { new Exception("Could not save data, please try again !!"); } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using CRUD_Operations_Using_EF.Models; using System.Configuration; using System.Data.SqlClient; using CRUD_Operations_Using_EF.SqlUtility; namespace CRUD_Operations_Using_EF.Controllers { public class StudentController : Controller { public ActionResult Index() { return View(); } [HttpPost] public ActionResult Index(Student modelData) { if (ModelState.IsValid) { try { SqlUtilityClass.Insertion(modelData); ViewBag.SuccessMessage = "Data saved scuccessfully !!"; } catch (Exception) { new Exception("Data could not be saved, please try again !!"); } } else { return View(); } ModelState.Clear(); return View(); } public ActionResult UpdateData(Student modelData) { if (ModelState.IsValid) { try { SqlUtilityClass.Update(modelData); ViewBag.UpdateMessage = "Data updated scuccessfully !!"; } catch (Exception) { new Exception("Data could not be saved, please try again !!"); } ModelState.Clear(); } else { Console.WriteLine("Invalid entry of data, please try again !!"); } return View(); } [HttpDelete] public ActionResult Delete(Student modelData) { if (ModelState.IsValid) { try { SqlUtilityClass.Delete(modelData); ViewBag.UpdateMessage = "Data deleted scuccessfully !!"; } catch (Exception) { new Exception("Data could not be deleted, please try again !!"); } ModelState.Clear(); } else { Console.WriteLine("Something went wrong, please try again !!"); } return View(); } public ActionResult Details(Student modelData) { if (ModelState.IsValid) { try { SqlUtilityClass.StudentDetails(modelData); ViewBag.UpdateMessage = "Data deleted scuccessfully !!"; } catch (Exception) { new Exception("Data could not be deleted, please try again !!"); } ModelState.Clear(); } else { Console.WriteLine("Something went wrong, please try again !!"); } return View(modelData); } } }<file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text.RegularExpressions; using System.Web; namespace CRUD_Operations_Using_EF.Models { public class CustomEmailValidator : ValidationAttribute { protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (value != null) { string Email = value.ToString(); if (Regex.IsMatch(Email, @"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}", RegexOptions.IgnoreCase)) { return ValidationResult.Success; } else { return new ValidationResult("Kindly enter valid email id ed. <EMAIL> "); } } else { return new ValidationResult("Email id is required, kindly enter !!"); } } } public class CustomPhoneNumberValidator : ValidationAttribute { protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (value != null) { string PhoneNumber = value.ToString(); if (Regex.IsMatch(PhoneNumber, @"^\d{10}$", RegexOptions.IgnoreCase)) { return ValidationResult.Success; } else { return new ValidationResult("Kindly enter 10 digit Phone number !!!!!"); } } else { return new ValidationResult("Phone Number is required !!"); } } } }
cab083c2b4040d18e1cdeea917d6b45be83d1528
[ "C#" ]
4
C#
Ankz29/CRUD_Operations_MVC
fc82963189e0bb95f5544c962d391424e52e4777
331132aaef90a6de673f8f463319b86346418875
refs/heads/main
<repo_name>rustylife42/guiGuesserGame<file_sep>/StartGame.py import tkinter as tk from random import randrange class NumberGuesser: """Number Guessing Class Framework""" def __init__(self): global buttons, secretNumber, lblLogs secretNumber = randrange(10) print(secretNumber) # remove all logs on init for lblLog in lblLogs: lblLog.grid_forget() lblLogs = [] def add_guess(self, g): global buttons # check if guess matches secret number if g == secretNumber: lbl = tk.Label(window, text="Your guess was right. You won! :) ", fg="green") lbl.grid(row=4, column=0, columnspan=5) lblLogs.append(lbl) for b in buttons: b["state"] = tk.DISABLED buttons[g]["state"] = tk.DISABLED # _______________________________________________________________________________________________________________ game = NumberGuesser window = tk.Tk() window.title("Guessing Game") lblInst = tk.Label(window, text="Guess a number from 0 to 9") lblLine1 = tk.Label(window, text="*********************************************************************") lblLogs = tk.Label(window, text="Game Logs") lblLine2 = tk.Label(window, text="*********************************************************************") # create the buttons buttons = [] for index in range(0, 10): button = tk.Button(window, text=index, command=lambda g=index: game.add_guess(g), state=tk.DISABLED) buttons.append(button) btnStartGameList = [] for index in range(0, 1): btnStartGame = tk.Button(window, text="Start Game", command=lambda: start_game(index)) btnStartGameList.append(btnStartGame) # append elements to grid lblInst.grid(row=0, column=0, columnspan=5) lblLine1.grid(row=1, column=0, columnspan=5) lblLogs.grid(row=2, column=0, columnspan=5) # row 2 - 6 is reserved for showing logs lblLine2.grid(row=7, column=0, columnspan=5) for row in range(0, 2): for col in range(0, 5): i = (row * 5) + col # convert 2d index to 1d. 5= total number of columns buttons[i].grid(row=row+10, column=col) btnStartGameList[0].grid(row=13, column=0, columnspan=5) # Main game logic guess = 0 secretNumber = randrange(10) print(secretNumber) lblLogs = [] status = "none" def start_game(i): global status for b in buttons: b["state"] = tk.NORMAL if status == "none": status = "started" btnStartGameList[i]["text"] = "Restart Game" else: status = "restarted" game.__init__() print("Game started") window.mainloop()
4e9eaab45d221a21306c646fc816e7d63274fedb
[ "Python" ]
1
Python
rustylife42/guiGuesserGame
b6505675192edc5e19b3a5b914179d86f7f11427
f5ac4fa71e4bada2bfe1b66811a8a41462754ff0
refs/heads/master
<repo_name>myurikuro/SmallestDifference<file_sep>/src/main/java/de/kohnlehome/SmallestDifference.java package de.kohnlehome; public class SmallestDifference implements ISmallestDifference { @Override public int SmallestDifference(int[] array1, int[] array2) { int smallest = Math.abs(array1[0] - array2[0]); for (int i = 1; i < Math.min(array1.length, array2.length); i++) { if (Math.abs(array1[i] - array2[i]) < smallest) { smallest = Math.abs(array1[i] - array2[i]); } } System.out.println(smallest); return smallest; } }
a62284d998529929b813183ad76f5bf4ed2ac01d
[ "Java" ]
1
Java
myurikuro/SmallestDifference
b752766c40840e490e7a74bd5b44e3cc7ecf134d
4a91db91d3aa40e443b440bf45d8a08806e699c3
refs/heads/master
<repo_name>mahzam/SWISS<file_sep>/Dockerfile FROM ubuntu:latest # https://askubuntu.com/questions/909277/avoiding-user-interaction-with-tzdata-when-installing-certbot-in-a-docker-contai ARG DEBIAN_FRONTEND=noninteractive RUN apt-get update RUN apt-get install -y clang RUN apt-get install -y python3-pip RUN pip3 install matplotlib RUN pip3 install z3-solver RUN pip3 install networkx RUN pip3 install typing-extensions RUN apt-get install -y wget ### cvc4 COPY cvc4 /home/root/cvc4 WORKDIR /home/root/cvc4 RUN ./contrib/get-antlr-3.4 RUN apt-get install -y cmake RUN apt-get install -y libgmp3-dev RUN pip3 install toml RUN apt-get install -y default-jre RUN ./configure.sh WORKDIR /home/root/cvc4/build RUN make -j4 RUN make install ### swiss dependencies RUN apt-get install -y python2 COPY scripts/installing/get-pip.py /home/root/get-pip.py WORKDIR /home/root RUN python2 get-pip.py RUN pip2 install ply RUN pip2 install tarjan ENV LD_LIBRARY_PATH=/usr/local/lib/ # z3 #RUN pip2 install z3-solver RUN ln -s /usr/bin/python2 /usr/bin/python COPY scripts/installing/install-z3.sh /home/root/install-z3.sh RUN bash install-z3.sh ENV PYTHONPATH=/usr/local/lib/python2.7/site-packages # swiss RUN mkdir /home/root/swiss COPY mypyvy /home/root/swiss/mypyvy COPY ivy /home/root/swiss/ivy COPY Makefile /home/root/swiss/Makefile COPY LICENSE /home/root/swiss/LICENSE COPY README.md /home/root/swiss/README.md COPY benchmarks /home/root/swiss/benchmarks COPY run-simple.sh /home/root/swiss/run-simple.sh COPY run.sh /home/root/swiss/run.sh COPY save.sh /home/root/swiss/save.sh COPY scripts /home/root/swiss/scripts COPY src /home/root/swiss/src WORKDIR /home/root/swiss RUN mkdir logs RUN make -j4 <file_sep>/scripts/table.py import sys import os import graphs if __name__ == '__main__': input_directory = sys.argv[1] which = int(sys.argv[2]) graphs.make_comparison_table(input_directory, which) <file_sep>/benchmarks/README.md Collects benchmarks from [IVy](https://github.com/kenmcmil/ivy), [I4](https://github.com/GLaDOS-Michigan/I4), [FOL Separators](https://github.com/jrkoenig/folseparators), [Paxos made EPR](https://www.cs.tau.ac.il/~odedp/paxos-made-epr.html), [mypyvy](https://github.com/wilcoxjay/mypyvy), as well as some benchmarks written for SWISS. In most cases, there is both a .ivy version and a .pyv version. For some, the .ivy is the original; for others, the .pyv is the original. In each case, the other one was translated by hand. <file_sep>/src/alt_depth2_synth_enumerator.cpp #include "alt_depth2_synth_enumerator.h" #include "enumerator.h" #include "var_lex_graph.h" #include "utils.h" using namespace std; AltDepth2CandidateSolver::AltDepth2CandidateSolver( shared_ptr<Module> module, TemplateSpace const& tspace) : module(module) , total_arity(tspace.k) , progress(0) , tspace(tspace) , taqd(v_template_hole()) , start_from(-1) , done_cutoff(0) , finish_at_cutoff(false) { cout << "Using AltDepth2CandidateSolver" << endl; cout << "total_arity: " << total_arity << endl; assert (tspace.depth == 2); value templ = tspace.make_templ(module); taqd = TopAlternatingQuantifierDesc(templ); EnumInfo ei(module, templ); pieces = ei.clauses; tree_shapes = get_tree_shapes_up_to(total_arity); //for (TreeShape const& ts : tree_shapes) { // cout << ts.to_string() << endl; //} //cout << "Using " << pieces.size() << " terms" << endl; //for (value p : pieces) { // cout << "piece: " << p->to_string() << endl; //} //assert(false); tree_shape_idx = -1; cur_indices = {}; done = false; var_index_states.resize(total_arity + 2); ts = build_transition_system( get_var_index_init_state(module, templ), ei.var_index_transitions, -1); } void AltDepth2CandidateSolver::addCounterexample(Counterexample cex) { cout << "add counterexample" << endl; assert (!cex.none); assert (cex.is_true || cex.is_false || (cex.hypothesis && cex.conclusion)); cexes.push_back(cex); int i = cexes.size() - 1; AlternationBitsetEvaluator abe1; AlternationBitsetEvaluator abe2; if (cex.is_true) { abe2 = AlternationBitsetEvaluator::make_evaluator( cex.is_true, pieces[0]); } else if (cex.is_false) { abe1 = AlternationBitsetEvaluator::make_evaluator( cex.is_false, pieces[0]); } else { assert(cex.hypothesis); assert(cex.conclusion); abe1 = AlternationBitsetEvaluator::make_evaluator( cex.hypothesis, pieces[0]); abe2 = AlternationBitsetEvaluator::make_evaluator( cex.conclusion, pieces[0]); } abes.push_back(make_pair(move(abe1), move(abe2))); cex_results.push_back({}); cex_results[i].resize(pieces.size()); for (int j = 0; j < (int)pieces.size(); j++) { if (cex.is_true) { cex_results[i][j].second = BitsetEvalResult::eval_over_alternating_quantifiers(cex.is_true, pieces[j]); } else if (cex.is_false) { cex_results[i][j].first = BitsetEvalResult::eval_over_alternating_quantifiers(cex.is_false, pieces[j]); } else { cex_results[i][j].first = BitsetEvalResult::eval_over_alternating_quantifiers(cex.hypothesis, pieces[j]); cex_results[i][j].second = BitsetEvalResult::eval_over_alternating_quantifiers(cex.conclusion, pieces[j]); } } } void AltDepth2CandidateSolver::addExistingInvariant(value inv0) { assert(false); /*for (value inv : taqd.rename_into_all_possibilities(inv0)) { auto indices = get_indices_of_value(inv); existing_invariants_append(indices); value norm = inv->totally_normalize(); existing_invariant_set.insert(ComparableValue(norm)); }*/ } value AltDepth2CandidateSolver::get_clause(int i) { value v = pieces[i]; while (true) { if (Forall* f = dynamic_cast<Forall*>(v.get())) { v = f->body; } else if (Exists* f = dynamic_cast<Exists*>(v.get())) { v = f->body; } else { break; } } return v; } value AltDepth2CandidateSolver::get_current_value() { vector<value> top_level; TreeShape const& ts = tree_shapes[tree_shape_idx]; int k = 0; for (int i = 0; i < (int)ts.parts.size(); i++) { vector<value> mid_level; for (int j = 0; j < ts.parts[i]; j++) { mid_level.push_back(get_clause(cur_indices[k])); k++; } top_level.push_back( ts.top_level_is_conj ? v_or(mid_level) : v_and(mid_level)); } value body = ts.top_level_is_conj ? v_and(top_level) : v_or(top_level); return taqd.with_body(body); } //int t = 0; value AltDepth2CandidateSolver::getNext() { while (true) { while (true) { increment(); if (done) { return nullptr; } if (sub_ts.next( var_index_states[cur_indices_sub.size()-1], cur_indices_sub[cur_indices_sub.size()-1]) == target_state) { break; } } progress++; for (int i = 0; i < (int)cur_indices.size(); i++) { cur_indices[i] = slice_index_map[cur_indices_sub[i]]; } /*t++; if (t == 50000) { cout << "incrementing... "; dump_cur_indices(); t = 0; }*/ // TODO comment this //dump_cur_indices(); //value sanity_v = get_current_value(); //cout << "genning >>>>>>>>>>>>>>>>>>>>>>>>> " << sanity_v->to_string() << endl; bool failed = false; //// Check if it violates a countereample for (int i = 0; i < (int)cexes.size(); i++) { if (cexes[i].is_true) { setup_abe2(abes[i].second, cex_results[i], cur_indices); bool res = abes[i].second.evaluate(); //if (res != cexes[i].is_true->eval_predicate(sanity_v)) { /*cexes[i].is_true->dump(); cout << sanity_v->to_string() << endl; cout << "result shoudl be " << cexes[i].is_true->eval_predicate(sanity_v) << endl; for (int k = 0; k < arity1 + arity2; k++) { cex_results[i][cur_indices[k]].second.dump(); }*/ // assert(false); //} if (!res) { failed = true; break; } } else if (cexes[i].is_false) { setup_abe1(abes[i].first, cex_results[i], cur_indices); bool res = abes[i].first.evaluate(); //assert (res == cexes[i].is_false->eval_predicate(sanity_v)); if (res) { failed = true; break; } } else { setup_abe1(abes[i].first, cex_results[i], cur_indices); bool res = abes[i].first.evaluate(); //assert (res == cexes[i].hypothesis->eval_predicate(sanity_v)); if (res) { setup_abe2(abes[i].second, cex_results[i], cur_indices); bool res2 = abes[i].second.evaluate(); //assert (res2 == cexes[i].conclusion->eval_predicate(sanity_v)); if (!res2) { failed = true; break; } } } } if (failed) continue; value v = get_current_value(); //// Check if it's equivalent to an existing invariant //// by some normalization. /*if (existing_invariant_set.count(ComparableValue(v->totally_normalize())) > 0) { existing_invariants_append(make_pair(simple_indices, ci)); continue; }*/ dump_cur_indices(); return v; } } void AltDepth2CandidateSolver::dump_cur_indices() { cout << "cur_indices_sub:"; for (int i : cur_indices_sub) { cout << " " << i; } cout << " / " << slice_index_map.size() << " in tree shape (idx = " << tree_shape_idx << ") " << tree_shapes[tree_shape_idx].to_string() << endl; } void AltDepth2CandidateSolver::increment() { int n = slice_index_map.size(); int t = cur_indices_sub.size(); if (tree_shape_idx == -1) { goto level_size_top; } if (start_from != -1) { t = start_from; start_from = -1; goto body_start; } goto body_end; level_size_top: tree_shape_idx++; if (tree_shape_idx >= (int)tree_shapes.size()) { this->done = true; return; } cout << "moving to tree " << tree_shapes[tree_shape_idx].to_string() << endl; cout << "progress " << progress << endl; cur_indices_sub.resize(tree_shapes[tree_shape_idx].total); t = 0; goto body_start; body_start: if (t == (int)cur_indices_sub.size()) { if (is_normalized_for_tree_shape(tree_shapes[tree_shape_idx], cur_indices_sub)) { return; } else { goto body_end; } } if (t > 0) { var_index_states[t] = sub_ts.next( var_index_states[t-1], cur_indices_sub[t-1]); } { SymmEdge const& symm_edge = tree_shapes[tree_shape_idx].symmetry_back_edges[t]; cur_indices_sub[t] = symm_edge.idx == -1 ? 0 : cur_indices_sub[symm_edge.idx] + symm_edge.inc; } goto loop_start_before_check; loop_start: if (sub_ts.next(var_index_states[t], cur_indices_sub[t]) != -1) { t++; goto body_start; } call_end: cur_indices_sub[t]++; loop_start_before_check: if (cur_indices_sub[t] >= n) { goto body_end; } goto loop_start; body_end: if (t == done_cutoff) { if (finish_at_cutoff) { done = true; return; } goto level_size_top; } else { t--; goto call_end; } } void AltDepth2CandidateSolver::setup_abe1(AlternationBitsetEvaluator& abe, std::vector<std::pair<BitsetEvalResult, BitsetEvalResult>> const& cex_result, std::vector<int> const& cur_indices) { TreeShape const& ts = tree_shapes[tree_shape_idx]; if (ts.top_level_is_conj) { abe.reset_for_conj(); } else { abe.reset_for_disj(); } int k = 0; int sz = cex_result[cur_indices[k]].first.v.size(); if ((int)evaluator_buf.size() < sz) { evaluator_buf.resize(sz); } for (int i = 0; i < (int)ts.parts.size(); i++) { if (ts.parts[i] == 1) { if (ts.top_level_is_conj) { abe.add_conj(cex_result[cur_indices[k]].first); } else { abe.add_disj(cex_result[cur_indices[k]].first); } k++; } else { vec_copy_ber(evaluator_buf, cex_result[cur_indices[k]].first); k++; for (int j = 1; j < (int)ts.parts[i]; j++) { if (ts.top_level_is_conj) { vec_apply_disj(evaluator_buf, cex_result[cur_indices[k]].first); } else { vec_apply_conj(evaluator_buf, cex_result[cur_indices[k]].first); } k++; } if (ts.top_level_is_conj) { abe.add_conj(sz, evaluator_buf); } else { abe.add_disj(sz, evaluator_buf); } } } } void AltDepth2CandidateSolver::setup_abe2(AlternationBitsetEvaluator& abe, std::vector<std::pair<BitsetEvalResult, BitsetEvalResult>> const& cex_result, std::vector<int> const& cur_indices) { TreeShape const& ts = tree_shapes[tree_shape_idx]; if (ts.top_level_is_conj) { abe.reset_for_conj(); } else { abe.reset_for_disj(); } int k = 0; int sz = cex_result[cur_indices[k]].second.v.size(); if ((int)evaluator_buf.size() < sz) { evaluator_buf.resize(sz); } for (int i = 0; i < (int)ts.parts.size(); i++) { if (ts.parts[i] == 1) { if (ts.top_level_is_conj) { abe.add_conj(cex_result[cur_indices[k]].second); } else { abe.add_disj(cex_result[cur_indices[k]].second); } k++; } else { vec_copy_ber(evaluator_buf, cex_result[cur_indices[k]].second); k++; for (int j = 1; j < (int)ts.parts[i]; j++) { if (ts.top_level_is_conj) { vec_apply_disj(evaluator_buf, cex_result[cur_indices[k]].second); } else { vec_apply_conj(evaluator_buf, cex_result[cur_indices[k]].second); } k++; } if (ts.top_level_is_conj) { abe.add_conj(sz, evaluator_buf); } else { abe.add_disj(sz, evaluator_buf); } } } } void AltDepth2CandidateSolver::setSubSlice(TemplateSubSlice const& tss) { this->tss = tss; auto p = get_subslice_index_map(ts, tss.ts); slice_index_map = p.first.first; sub_ts = p.first.second; target_state = p.second; assert (target_state != -1); //cout << "chunk: " << sc.nums.size() << " / " << sc.size << endl; assert (0 <= tss.tree_idx && tss.tree_idx < (int)tree_shapes.size()); tree_shape_idx = tss.tree_idx; TreeShape const& ts = tree_shapes[tree_shape_idx]; assert (ts.total == tss.ts.k); cur_indices.resize(ts.total); cur_indices_sub.resize(ts.total); assert (tss.prefix.size() <= cur_indices.size()); for (int i = 0; i < (int)tss.prefix.size(); i++) { cur_indices_sub[i] = tss.prefix[i]; } for (int i = 1; i <= (int)tss.prefix.size(); i++) { var_index_states[i] = this->sub_ts.next( var_index_states[i-1], cur_indices_sub[i-1]); } start_from = tss.prefix.size(); done_cutoff = tss.prefix.size(); done = false; finish_at_cutoff = true; } long long AltDepth2CandidateSolver::getPreSymmCount() { long long ans = 1; for (int i = 0; i < total_arity; i++) ans *= (long long)pieces.size(); long long mul; if (total_arity == 1) mul = 1; else mul = 2 * (long long)((1 << (total_arity - 1)) - 1); return ans * mul; } <file_sep>/src/logic.h #ifndef LOGIC_H #define LOGIC_H #include <string> #include <vector> #include <memory> #include <map> #include <set> #include "lib/json11/json11.hpp" /* Sort */ class Sort { public: virtual ~Sort() {} virtual std::string to_string() const = 0; virtual json11::Json to_json() const = 0; virtual std::vector<std::shared_ptr<Sort>> get_domain_as_function() const = 0; virtual std::shared_ptr<Sort> get_range_as_function() const = 0; }; class BooleanSort : public Sort { std::string to_string() const override; json11::Json to_json() const override; std::vector<std::shared_ptr<Sort>> get_domain_as_function() const override; std::shared_ptr<Sort> get_range_as_function() const override; }; class UninterpretedSort : public Sort { public: std::string const name; UninterpretedSort(std::string const& name) : name(name) { } std::string to_string() const override; json11::Json to_json() const override; std::vector<std::shared_ptr<Sort>> get_domain_as_function() const override; std::shared_ptr<Sort> get_range_as_function() const override; }; class FunctionSort : public Sort { public: std::vector<std::shared_ptr<Sort>> const domain; std::shared_ptr<Sort> range; FunctionSort( std::vector<std::shared_ptr<Sort>> const& domain, std::shared_ptr<Sort> range) : domain(domain), range(range) { } std::string to_string() const override; json11::Json to_json() const override; std::vector<std::shared_ptr<Sort>> get_domain_as_function() const override; std::shared_ptr<Sort> get_range_as_function() const override; }; /* VarDecl */ typedef uint32_t iden; std::string iden_to_string(iden); iden string_to_iden(std::string const&); class VarDecl { public: iden name; std::shared_ptr<Sort> sort; VarDecl( iden name, std::shared_ptr<Sort> sort) : name(name), sort(sort) { } std::string to_string() { return iden_to_string(name) + ": " + sort->to_string(); } }; /* Value */ struct ScopeState; class Value { public: virtual ~Value() {} virtual std::string to_string() const = 0; virtual json11::Json to_json() const = 0; virtual std::shared_ptr<Sort> get_sort() const = 0; static std::shared_ptr<Value> from_json(json11::Json); virtual std::shared_ptr<Value> subst(iden x, std::shared_ptr<Value> e) const = 0; virtual std::shared_ptr<Value> replace_const_with_var(std::map<iden, iden> const& s) const = 0; virtual std::shared_ptr<Value> replace_var_with_var(std::map<iden, iden> const& s) const = 0; virtual std::shared_ptr<Value> subst_fun(iden func, std::vector<VarDecl> const& decls, std::shared_ptr<Value> body) const = 0; virtual std::shared_ptr<Value> negate() const = 0; virtual std::shared_ptr<Value> simplify() const = 0; virtual bool uses_var(iden name) const = 0; virtual std::shared_ptr<Value> uniquify_vars(std::map<iden, iden> const&) const = 0; virtual std::shared_ptr<Value> indexify_vars(std::map<iden, iden> const&) const = 0; // only call this after uniquify_vars virtual std::shared_ptr<Value> structurally_normalize_() const = 0; virtual std::shared_ptr<Value> normalize_symmetries(ScopeState const& ss, std::set<iden> const& vars_used) const = 0; virtual std::shared_ptr<Value> order_and_or_eq(ScopeState const& ss) const = 0; virtual void get_used_vars(std::set<iden>&) const = 0; std::shared_ptr<Value> structurally_normalize() const { return this->uniquify_vars({})->structurally_normalize_(); } std::shared_ptr<Value> totally_normalize() const; std::shared_ptr<Value> reduce_quants() const; virtual int kind_id() const = 0; }; class Forall : public Value { public: std::vector<VarDecl> const decls; std::shared_ptr<Value> const body; Forall( std::vector<VarDecl> const& decls, std::shared_ptr<Value> body) : decls(decls), body(body) { } std::string to_string() const override; json11::Json to_json() const override; std::shared_ptr<Sort> get_sort() const override; std::shared_ptr<Value> subst(iden x, std::shared_ptr<Value> e) const override; std::shared_ptr<Value> replace_const_with_var(std::map<iden, iden> const& s) const override; std::shared_ptr<Value> replace_var_with_var(std::map<iden, iden> const& s) const override; std::shared_ptr<Value> subst_fun(iden func, std::vector<VarDecl> const& decls, std::shared_ptr<Value> body) const override; std::shared_ptr<Value> negate() const override; std::shared_ptr<Value> simplify() const override; bool uses_var(iden name) const override; std::shared_ptr<Value> uniquify_vars(std::map<iden, iden> const&) const override; std::shared_ptr<Value> indexify_vars(std::map<iden, iden> const&) const override; std::shared_ptr<Value> structurally_normalize_() const override; std::shared_ptr<Value> normalize_symmetries(ScopeState const& ss, std::set<iden> const& vars_used) const override; std::shared_ptr<Value> order_and_or_eq(ScopeState const& ss) const override; void get_used_vars(std::set<iden>&) const override; int kind_id() const override { return 1; } }; class NearlyForall : public Value { public: std::vector<VarDecl> const decls; std::shared_ptr<Value> const body; NearlyForall( std::vector<VarDecl> const& decls, std::shared_ptr<Value> body) : decls(decls), body(body) { } std::string to_string() const override; json11::Json to_json() const override; std::shared_ptr<Sort> get_sort() const override; std::shared_ptr<Value> subst(iden x, std::shared_ptr<Value> e) const override; std::shared_ptr<Value> replace_const_with_var(std::map<iden, iden> const& s) const override; std::shared_ptr<Value> replace_var_with_var(std::map<iden, iden> const& s) const override; std::shared_ptr<Value> subst_fun(iden func, std::vector<VarDecl> const& decls, std::shared_ptr<Value> body) const override; std::shared_ptr<Value> negate() const override; std::shared_ptr<Value> simplify() const override; bool uses_var(iden name) const override; std::shared_ptr<Value> uniquify_vars(std::map<iden, iden> const&) const override; std::shared_ptr<Value> indexify_vars(std::map<iden, iden> const&) const override; std::shared_ptr<Value> structurally_normalize_() const override; std::shared_ptr<Value> normalize_symmetries(ScopeState const& ss, std::set<iden> const& vars_used) const override; std::shared_ptr<Value> order_and_or_eq(ScopeState const& ss) const override; void get_used_vars(std::set<iden>&) const override; int kind_id() const override { return 2; } }; class Exists : public Value { public: std::vector<VarDecl> const decls; std::shared_ptr<Value> const body; Exists( std::vector<VarDecl> const& decls, std::shared_ptr<Value> body) : decls(decls), body(body) { } std::string to_string() const override; json11::Json to_json() const override; std::shared_ptr<Sort> get_sort() const override; std::shared_ptr<Value> subst(iden x, std::shared_ptr<Value> e) const override; std::shared_ptr<Value> replace_const_with_var(std::map<iden, iden> const& s) const override; std::shared_ptr<Value> replace_var_with_var(std::map<iden, iden> const& s) const override; std::shared_ptr<Value> subst_fun(iden func, std::vector<VarDecl> const& decls, std::shared_ptr<Value> body) const override; std::shared_ptr<Value> negate() const override; std::shared_ptr<Value> simplify() const override; bool uses_var(iden name) const override; std::shared_ptr<Value> uniquify_vars(std::map<iden, iden> const&) const override; std::shared_ptr<Value> indexify_vars(std::map<iden, iden> const&) const override; std::shared_ptr<Value> structurally_normalize_() const override; std::shared_ptr<Value> normalize_symmetries(ScopeState const& ss, std::set<iden> const& vars_used) const override; std::shared_ptr<Value> order_and_or_eq(ScopeState const& ss) const override; void get_used_vars(std::set<iden>&) const override; int kind_id() const override { return 3; } }; class Var : public Value { public: iden const name; std::shared_ptr<Sort> sort; Var( iden name, std::shared_ptr<Sort> sort) : name(name), sort(sort) { } std::string to_string() const override; json11::Json to_json() const override; std::shared_ptr<Sort> get_sort() const override; std::shared_ptr<Value> subst(iden x, std::shared_ptr<Value> e) const override; std::shared_ptr<Value> replace_const_with_var(std::map<iden, iden> const& s) const override; std::shared_ptr<Value> replace_var_with_var(std::map<iden, iden> const& s) const override; std::shared_ptr<Value> subst_fun(iden func, std::vector<VarDecl> const& decls, std::shared_ptr<Value> body) const override; std::shared_ptr<Value> negate() const override; std::shared_ptr<Value> simplify() const override; bool uses_var(iden name) const override; std::shared_ptr<Value> uniquify_vars(std::map<iden, iden> const&) const override; std::shared_ptr<Value> indexify_vars(std::map<iden, iden> const&) const override; std::shared_ptr<Value> structurally_normalize_() const override; std::shared_ptr<Value> normalize_symmetries(ScopeState const& ss, std::set<iden> const& vars_used) const override; std::shared_ptr<Value> order_and_or_eq(ScopeState const& ss) const override; void get_used_vars(std::set<iden>&) const override; int kind_id() const override { return 50; } }; class Const : public Value { public: iden const name; std::shared_ptr<Sort> sort; Const( iden name, std::shared_ptr<Sort> sort) : name(name), sort(sort) { } std::string to_string() const override; json11::Json to_json() const override; std::shared_ptr<Sort> get_sort() const override; std::shared_ptr<Value> subst(iden x, std::shared_ptr<Value> e) const override; std::shared_ptr<Value> replace_const_with_var(std::map<iden, iden> const& s) const override; std::shared_ptr<Value> replace_var_with_var(std::map<iden, iden> const& s) const override; std::shared_ptr<Value> subst_fun(iden func, std::vector<VarDecl> const& decls, std::shared_ptr<Value> body) const override; std::shared_ptr<Value> negate() const override; std::shared_ptr<Value> simplify() const override; bool uses_var(iden name) const override; std::shared_ptr<Value> uniquify_vars(std::map<iden, iden> const&) const override; std::shared_ptr<Value> indexify_vars(std::map<iden, iden> const&) const override; std::shared_ptr<Value> structurally_normalize_() const override; std::shared_ptr<Value> normalize_symmetries(ScopeState const& ss, std::set<iden> const& vars_used) const override; std::shared_ptr<Value> order_and_or_eq(ScopeState const& ss) const override; void get_used_vars(std::set<iden>&) const override; int kind_id() const override { return 4; } }; class Eq : public Value { public: std::shared_ptr<Value> left; std::shared_ptr<Value> right; Eq( std::shared_ptr<Value> left, std::shared_ptr<Value> right) : left(left), right(right) { } std::string to_string() const override; json11::Json to_json() const override; std::shared_ptr<Sort> get_sort() const override; std::shared_ptr<Value> subst(iden x, std::shared_ptr<Value> e) const override; std::shared_ptr<Value> replace_const_with_var(std::map<iden, iden> const& s) const override; std::shared_ptr<Value> replace_var_with_var(std::map<iden, iden> const& s) const override; std::shared_ptr<Value> subst_fun(iden func, std::vector<VarDecl> const& decls, std::shared_ptr<Value> body) const override; std::shared_ptr<Value> negate() const override; std::shared_ptr<Value> simplify() const override; bool uses_var(iden name) const override; std::shared_ptr<Value> uniquify_vars(std::map<iden, iden> const&) const override; std::shared_ptr<Value> indexify_vars(std::map<iden, iden> const&) const override; std::shared_ptr<Value> structurally_normalize_() const override; std::shared_ptr<Value> normalize_symmetries(ScopeState const& ss, std::set<iden> const& vars_used) const override; std::shared_ptr<Value> order_and_or_eq(ScopeState const& ss) const override; void get_used_vars(std::set<iden>&) const override; int kind_id() const override { return 100; } }; class Not : public Value { public: std::shared_ptr<Value> val; Not( std::shared_ptr<Value> val) : val(val) { } std::string to_string() const override; json11::Json to_json() const override; std::shared_ptr<Sort> get_sort() const override; std::shared_ptr<Value> subst(iden x, std::shared_ptr<Value> e) const override; std::shared_ptr<Value> replace_const_with_var(std::map<iden, iden> const& s) const override; std::shared_ptr<Value> replace_var_with_var(std::map<iden, iden> const& s) const override; std::shared_ptr<Value> subst_fun(iden func, std::vector<VarDecl> const& decls, std::shared_ptr<Value> body) const override; std::shared_ptr<Value> negate() const override; std::shared_ptr<Value> simplify() const override; bool uses_var(iden name) const override; std::shared_ptr<Value> uniquify_vars(std::map<iden, iden> const&) const override; std::shared_ptr<Value> indexify_vars(std::map<iden, iden> const&) const override; std::shared_ptr<Value> structurally_normalize_() const override; std::shared_ptr<Value> normalize_symmetries(ScopeState const& ss, std::set<iden> const& vars_used) const override; std::shared_ptr<Value> order_and_or_eq(ScopeState const& ss) const override; void get_used_vars(std::set<iden>&) const override; int kind_id() const override { return 6; } }; class Implies : public Value { public: std::shared_ptr<Value> left; std::shared_ptr<Value> right; Implies( std::shared_ptr<Value> left, std::shared_ptr<Value> right) : left(left), right(right) { } std::string to_string() const override; json11::Json to_json() const override; std::shared_ptr<Sort> get_sort() const override; std::shared_ptr<Value> subst(iden x, std::shared_ptr<Value> e) const override; std::shared_ptr<Value> replace_const_with_var(std::map<iden, iden> const& s) const override; std::shared_ptr<Value> replace_var_with_var(std::map<iden, iden> const& s) const override; std::shared_ptr<Value> subst_fun(iden func, std::vector<VarDecl> const& decls, std::shared_ptr<Value> body) const override; std::shared_ptr<Value> negate() const override; std::shared_ptr<Value> simplify() const override; bool uses_var(iden name) const override; std::shared_ptr<Value> uniquify_vars(std::map<iden, iden> const&) const override; std::shared_ptr<Value> indexify_vars(std::map<iden, iden> const&) const override; std::shared_ptr<Value> structurally_normalize_() const override; std::shared_ptr<Value> normalize_symmetries(ScopeState const& ss, std::set<iden> const& vars_used) const override; std::shared_ptr<Value> order_and_or_eq(ScopeState const& ss) const override; void get_used_vars(std::set<iden>&) const override; int kind_id() const override { return 7; } }; class Apply : public Value { public: std::shared_ptr<Value> func; std::vector<std::shared_ptr<Value>> args; Apply( std::shared_ptr<Value> func, std::vector<std::shared_ptr<Value>> const& args) : func(func), args(args) { } std::string to_string() const override; json11::Json to_json() const override; std::shared_ptr<Sort> get_sort() const override; std::shared_ptr<Value> subst(iden x, std::shared_ptr<Value> e) const override; std::shared_ptr<Value> replace_const_with_var(std::map<iden, iden> const& s) const override; std::shared_ptr<Value> replace_var_with_var(std::map<iden, iden> const& s) const override; std::shared_ptr<Value> subst_fun(iden func, std::vector<VarDecl> const& decls, std::shared_ptr<Value> body) const override; std::shared_ptr<Value> negate() const override; std::shared_ptr<Value> simplify() const override; bool uses_var(iden name) const override; std::shared_ptr<Value> uniquify_vars(std::map<iden, iden> const&) const override; std::shared_ptr<Value> indexify_vars(std::map<iden, iden> const&) const override; std::shared_ptr<Value> structurally_normalize_() const override; std::shared_ptr<Value> normalize_symmetries(ScopeState const& ss, std::set<iden> const& vars_used) const override; std::shared_ptr<Value> order_and_or_eq(ScopeState const& ss) const override; void get_used_vars(std::set<iden>&) const override; int kind_id() const override { return 8; } }; class And : public Value { public: std::vector<std::shared_ptr<Value>> args; And( std::vector<std::shared_ptr<Value>> const& args) : args(args) { } std::string to_string() const override; json11::Json to_json() const override; std::shared_ptr<Sort> get_sort() const override; std::shared_ptr<Value> subst(iden x, std::shared_ptr<Value> e) const override; std::shared_ptr<Value> replace_const_with_var(std::map<iden, iden> const& s) const override; std::shared_ptr<Value> replace_var_with_var(std::map<iden, iden> const& s) const override; std::shared_ptr<Value> subst_fun(iden func, std::vector<VarDecl> const& decls, std::shared_ptr<Value> body) const override; std::shared_ptr<Value> negate() const override; std::shared_ptr<Value> simplify() const override; bool uses_var(iden name) const override; std::shared_ptr<Value> uniquify_vars(std::map<iden, iden> const&) const override; std::shared_ptr<Value> indexify_vars(std::map<iden, iden> const&) const override; std::shared_ptr<Value> structurally_normalize_() const override; std::shared_ptr<Value> normalize_symmetries(ScopeState const& ss, std::set<iden> const& vars_used) const override; std::shared_ptr<Value> order_and_or_eq(ScopeState const& ss) const override; void get_used_vars(std::set<iden>&) const override; int kind_id() const override { return 9; } }; class Or : public Value { public: std::vector<std::shared_ptr<Value>> args; Or( std::vector<std::shared_ptr<Value>> const& args) : args(args) { } std::string to_string() const override; json11::Json to_json() const override; std::shared_ptr<Sort> get_sort() const override; std::shared_ptr<Value> subst(iden x, std::shared_ptr<Value> e) const override; std::shared_ptr<Value> replace_const_with_var(std::map<iden, iden> const& s) const override; std::shared_ptr<Value> replace_var_with_var(std::map<iden, iden> const& s) const override; std::shared_ptr<Value> subst_fun(iden func, std::vector<VarDecl> const& decls, std::shared_ptr<Value> body) const override; std::shared_ptr<Value> negate() const override; std::shared_ptr<Value> simplify() const override; bool uses_var(iden name) const override; std::shared_ptr<Value> uniquify_vars(std::map<iden, iden> const&) const override; std::shared_ptr<Value> indexify_vars(std::map<iden, iden> const&) const override; std::shared_ptr<Value> structurally_normalize_() const override; std::shared_ptr<Value> normalize_symmetries(ScopeState const& ss, std::set<iden> const& vars_used) const override; std::shared_ptr<Value> order_and_or_eq(ScopeState const& ss) const override; void get_used_vars(std::set<iden>&) const override; int kind_id() const override { return 10; } }; class IfThenElse : public Value { public: std::shared_ptr<Value> cond; std::shared_ptr<Value> then_value; std::shared_ptr<Value> else_value; IfThenElse( std::shared_ptr<Value> cond, std::shared_ptr<Value> then_value, std::shared_ptr<Value> else_value) : cond(cond), then_value(then_value), else_value(else_value) { } std::string to_string() const override; json11::Json to_json() const override; std::shared_ptr<Sort> get_sort() const override; std::shared_ptr<Value> subst(iden x, std::shared_ptr<Value> e) const override; std::shared_ptr<Value> replace_const_with_var(std::map<iden, iden> const& s) const override; std::shared_ptr<Value> replace_var_with_var(std::map<iden, iden> const& s) const override; std::shared_ptr<Value> subst_fun(iden func, std::vector<VarDecl> const& decls, std::shared_ptr<Value> body) const override; std::shared_ptr<Value> negate() const override; std::shared_ptr<Value> simplify() const override; bool uses_var(iden name) const override; std::shared_ptr<Value> uniquify_vars(std::map<iden, iden> const&) const override; std::shared_ptr<Value> indexify_vars(std::map<iden, iden> const&) const override; std::shared_ptr<Value> structurally_normalize_() const override; std::shared_ptr<Value> normalize_symmetries(ScopeState const& ss, std::set<iden> const& vars_used) const override; std::shared_ptr<Value> order_and_or_eq(ScopeState const& ss) const override; void get_used_vars(std::set<iden>&) const override; int kind_id() const override { return 11; } }; class TemplateHole : public Value { public: TemplateHole() { } std::string to_string() const override; json11::Json to_json() const override; std::shared_ptr<Sort> get_sort() const override; std::shared_ptr<Value> subst(iden x, std::shared_ptr<Value> e) const override; std::shared_ptr<Value> replace_const_with_var(std::map<iden, iden> const& s) const override; std::shared_ptr<Value> replace_var_with_var(std::map<iden, iden> const& s) const override; std::shared_ptr<Value> subst_fun(iden func, std::vector<VarDecl> const& decls, std::shared_ptr<Value> body) const override; std::shared_ptr<Value> negate() const override; std::shared_ptr<Value> simplify() const override; bool uses_var(iden name) const override; std::shared_ptr<Value> uniquify_vars(std::map<iden, iden> const&) const override; std::shared_ptr<Value> indexify_vars(std::map<iden, iden> const&) const override; std::shared_ptr<Value> structurally_normalize_() const override; std::shared_ptr<Value> normalize_symmetries(ScopeState const& ss, std::set<iden> const& vars_used) const override; std::shared_ptr<Value> order_and_or_eq(ScopeState const& ss) const override; void get_used_vars(std::set<iden>&) const override; int kind_id() const override { return 12; } }; /* Action */ class Action { public: virtual ~Action() {} }; class RelationAction : public Action { public: std::vector<std::string> mods; std::shared_ptr<Value> rel; RelationAction( std::vector<std::string> const& mods, std::shared_ptr<Value> rel) : mods(mods), rel(rel) { } }; class LocalAction : public Action { public: std::vector<VarDecl> args; std::shared_ptr<Action> body; LocalAction( std::vector<VarDecl> const& args, std::shared_ptr<Action> body) : args(args), body(body) { } }; class SequenceAction : public Action { public: std::vector<std::shared_ptr<Action>> actions; SequenceAction( std::vector<std::shared_ptr<Action>> const& actions) : actions(actions) { } }; class ChoiceAction : public Action { public: std::vector<std::shared_ptr<Action>> actions; ChoiceAction( std::vector<std::shared_ptr<Action>> const& actions) : actions(actions) { } }; class Assume : public Action { public: std::shared_ptr<Value> body; Assume( std::shared_ptr<Value> body) : body(body) { } }; class Assign : public Action { public: std::shared_ptr<Value> left; std::shared_ptr<Value> right; Assign( std::shared_ptr<Value> left, std::shared_ptr<Value> right) : left(left), right(right) { } }; class Havoc : public Action { public: std::shared_ptr<Value> left; Havoc( std::shared_ptr<Value> left) : left(left) { } }; class IfElse : public Action { public: std::shared_ptr<Value> condition; std::shared_ptr<Action> then_body; std::shared_ptr<Action> else_body; IfElse( std::shared_ptr<Value> condition, std::shared_ptr<Action> then_body, std::shared_ptr<Action> else_body) : condition(condition), then_body(then_body), else_body(else_body) { } }; class If : public Action { public: std::shared_ptr<Value> condition; std::shared_ptr<Action> then_body; If( std::shared_ptr<Value> condition, std::shared_ptr<Action> then_body) : condition(condition), then_body(then_body) { } }; /* Module */ class Module { public: std::vector<std::string> sorts; std::vector<VarDecl> functions; std::vector<std::shared_ptr<Value>> axioms; std::vector<std::shared_ptr<Value>> inits; std::vector<std::shared_ptr<Value>> conjectures; std::vector<std::shared_ptr<Value>> templates; std::vector<std::shared_ptr<Action>> actions; std::vector<std::string> action_names; Module( std::vector<std::string> const& sorts, std::vector<VarDecl> const& functions, std::vector<std::shared_ptr<Value>> const& axioms, std::vector<std::shared_ptr<Value>> const& inits, std::vector<std::shared_ptr<Value>> const& conjectures, std::vector<std::shared_ptr<Value>> const& templates, std::vector<std::shared_ptr<Action>> const& actions, std::vector<std::string> const& action_names) : sorts(sorts), functions(functions), axioms(axioms), inits(inits), conjectures(conjectures), templates(templates), actions(actions), action_names(action_names) { } std::shared_ptr<Module> add_conjectures(std::vector<std::shared_ptr<Value>> const& values); int get_template_idx(std::shared_ptr<Value> templ); }; typedef std::shared_ptr<Value> value; typedef std::shared_ptr<Sort> lsort; std::shared_ptr<Module> parse_module(std::string const& src); std::vector<value> parse_value_array(std::string const& src); inline value v_forall(std::vector<VarDecl> const& decls, value const& body) { return std::shared_ptr<Value>(new Forall(decls, body)); } inline value v_nearlyforall(std::vector<VarDecl> const& decls, value const& body) { return std::shared_ptr<Value>(new NearlyForall(decls, body)); } inline value v_exists(std::vector<VarDecl> const& decls, value const& body) { return std::shared_ptr<Value>(new Exists(decls, body)); } inline value v_var(iden name, lsort sort) { return std::shared_ptr<Value>(new Var(name, sort)); } inline value v_const(iden name, lsort sort) { return std::shared_ptr<Value>(new Const(name, sort)); } inline value v_eq(value a, value b) { return std::shared_ptr<Value>(new Eq(a, b)); } inline value v_not(value a) { if (Not* n = dynamic_cast<Not*>(a.get())) { return n->val; } else { return std::shared_ptr<Value>(new Not(a)); } } inline value v_implies(value a, value b) { return std::shared_ptr<Value>(new Implies(a, b)); } inline value v_apply(value func, std::vector<value> const& args) { return std::shared_ptr<Value>(new Apply(func, args)); } inline value v_and(std::vector<value> const& args) { if (args.size() == 1) return args[0]; return std::shared_ptr<Value>(new And(args)); } inline value v_true() { return std::shared_ptr<Value>(new And({})); } inline value v_false() { return std::shared_ptr<Value>(new Or({})); } inline value v_or(std::vector<value> const& args) { if (args.size() == 1) return args[0]; return std::shared_ptr<Value>(new Or(args)); } inline value v_if_then_else(value cond, value then_value, value else_value) { return std::shared_ptr<Value>(new IfThenElse(cond, then_value, else_value)); } inline value v_template_hole() { return std::shared_ptr<Value>(new TemplateHole()); } inline lsort s_bool() { return std::shared_ptr<Sort>(new BooleanSort()); } inline lsort s_uninterp(std::string name) { return std::shared_ptr<Sort>(new UninterpretedSort(name)); } inline lsort s_fun(std::vector<lsort> inputs, lsort output) { return std::shared_ptr<Sort>(new FunctionSort(inputs, output)); } bool sorts_eq(lsort s, lsort t); bool values_equal(value a, value b); bool lt_value(value a_, value b_); struct ComparableValue { value v; ComparableValue(value v) : v(v) { } inline bool operator<(ComparableValue const& other) const { return lt_value(v, other.v); } }; VarDecl freshVarDecl(lsort sort); std::vector<value> aggressively_split_into_conjuncts(value); value remove_unneeded_quants(Value const * v); struct FormulaDump { std::vector<value> base_invs; std::vector<value> new_invs; std::vector<value> all_invs; std::vector<value> conjectures; bool success; }; FormulaDump parse_formula_dump(std::string const& src); std::string marshall_formula_dump(FormulaDump const& fd); value order_and_or_eq(value v); #endif <file_sep>/src/benchmarking.h #ifndef BENCHMARKING_H #define BENCHMARKING_H #include <chrono> #include <string> #include <unordered_map> class Benchmarking { public: Benchmarking(bool include_in_global = true) : include_in_global(include_in_global) , in_bench(false), bench_name("") { } void start(std::string s); void end(); void dump(); private: std::unordered_map<std::string, long long> bench; bool include_in_global; bool in_bench; std::string bench_name; std::chrono::time_point<std::chrono::high_resolution_clock> last; }; void benchmarking_dump_totals(); inline std::chrono::time_point<std::chrono::high_resolution_clock> now() { return std::chrono::high_resolution_clock::now(); } inline long long as_ms(std::chrono::high_resolution_clock::duration dur) { return std::chrono::duration_cast<std::chrono::milliseconds>(dur).count(); } inline long long as_ns(std::chrono::high_resolution_clock::duration dur) { return std::chrono::duration_cast<std::chrono::nanoseconds>(dur).count(); } #endif <file_sep>/src/tree_shapes.cpp #include "tree_shapes.h" #include <iostream> using namespace std; void get_tree_shapes_of_size_rec( vector<TreeShape>& res, int n, vector<int> const& parts, int bound, int totalSoFar) { if (totalSoFar > n) { return; } if (totalSoFar == n) { TreeShape ts; ts.top_level_is_conj = true; ts.total = n; ts.parts = parts; res.push_back(ts); ts.top_level_is_conj = false; res.push_back(ts); return; } for (int i = 1; i <= bound; i++) { vector<int> parts1 = parts; parts1.push_back(i); get_tree_shapes_of_size_rec(res, n, parts1, i, totalSoFar + i); } } void get_tree_shapes_of_size( vector<TreeShape>& res, int n) { if (n == 1) { TreeShape ts; ts.top_level_is_conj = true; ts.total = 1; ts.parts.push_back(1); res.push_back(ts); } else { for (int i = 1; i < n; i++) { vector<int> parts; parts.push_back(i); get_tree_shapes_of_size_rec(res, n, parts, i, i); } } } void make_back_edges(TreeShape& ts) { vector<int> starts; for (int i = 0; i < (int)ts.parts.size(); i++) { starts.push_back(ts.symmetry_back_edges.size()); for (int j = 0; j < (int)ts.parts[i]; j++) { if (j > 0) { ts.symmetry_back_edges.push_back(SymmEdge( ts.symmetry_back_edges.size() - 1, 1)); } else { if (i > 0 && ts.parts[i] == ts.parts[i-1]) { ts.symmetry_back_edges.push_back(SymmEdge( starts[i-1], ts.parts[i] == 1 ? 1 : 0)); } else { ts.symmetry_back_edges.push_back(SymmEdge(-1, -1)); } } } } } vector<TreeShape> get_tree_shapes_up_to(int n) { vector<TreeShape> res; for (int i = 1; i <= n; i++) { get_tree_shapes_of_size(res, i); } for (int i = 0; i < (int)res.size(); i++) { make_back_edges(res[i]); } return res; } bool is_lexicographically_lt(vector<int> const& pieces, int a, int b, int len) { for (int i = 0; i < len; i++) { if (pieces[a+i] < pieces[b+i]) return true; if (pieces[a+i] > pieces[b+i]) return false; } return false; } bool is_normalized_for_tree_shape(TreeShape const& ts, vector<int> const& pieces) { int pos = ts.parts[0]; for (int i = 1; i < (int)ts.parts.size(); i++) { if (ts.parts[i] == ts.parts[i-1]) { if (!is_lexicographically_lt(pieces, pos - ts.parts[i], pos, ts.parts[i])) { return false; } } pos += ts.parts[i]; } return true; } std::string TreeShape::to_string() const { string s = top_level_is_conj ? "AND" : "OR"; s += " ["; for (int i = 0; i < (int)parts.size(); i++) { if (i > 0) s += ", "; s += ::to_string(parts[i]); } return s + "]"; } TreeShape tree_shape_for(bool top_level_is_conj, std::vector<int> const& parts) { TreeShape ts; ts.top_level_is_conj = top_level_is_conj; ts.parts = parts; ts.total = 0; for (int i : parts) { ts.total += i; } make_back_edges(ts); return ts; } <file_sep>/save.sh #!/bin/bash set -e make if [[ -z "${SYNTHESIS_LOGDIR}" ]]; then DT=$(date +"%Y-%m-%d_%H.%M.%S") if [[ -z "${SCRATCH}" ]]; then LOGDIR=$(mktemp -d "./logs/log.$DT-XXXXXXXXX") else LOGDIR=$(mktemp -d "$SCRATCH/log.$DT-XXXXXXXXX") fi else LOGDIR=$SYNTHESIS_LOGDIR fi echo "logging to $LOGDIR/driver" echo "python3 scripts/driver.py $@" >> $LOGDIR/driver echo "" >> $LOGDIR/driver z3 --version >> $LOGDIR/driver echo "" >> $LOGDIR/driver git rev-parse --verify HEAD >> $LOGDIR/driver echo "" >> $LOGDIR/driver git diff >> $LOGDIR/driver echo "" >> $LOGDIR/driver set +e { time python3 ./scripts/driver.py $@ --logdir $LOGDIR ; } 2>&1 | tee -a $LOGDIR/driver echo "logged to $LOGDIR/driver" exit $RETCODE <file_sep>/scripts/misc_stats.py import sys import os import graphs if __name__ == '__main__': input_directory = sys.argv[1] median_of = int(sys.argv[2]) graphs.misc_stats(input_directory, median_of) <file_sep>/src/solve.cpp #include "solve.h" #include <iostream> #include <cassert> #include "stats.h" #include "benchmarking.h" using namespace std; extern int numRetries; extern int numTryHardFailures; smt::context _z3_ctx_normal; smt::context _z3_ctx_quick; smt::context _cvc4_ctx_normal; smt::context _cvc4_ctx_quick; void context_reset() { _z3_ctx_normal = smt::context(); _z3_ctx_quick = smt::context(); _cvc4_ctx_normal = smt::context(); _cvc4_ctx_quick = smt::context(); } smt::context z3_ctx_normal() { if (!_z3_ctx_normal.p) { _z3_ctx_normal = smt::context(smt::Backend::z3); _z3_ctx_normal.set_timeout(45000); } return _z3_ctx_normal; } smt::context z3_ctx_quick() { if (!_z3_ctx_quick.p) { _z3_ctx_quick = smt::context(smt::Backend::z3); _z3_ctx_quick.set_timeout(15000); } return _z3_ctx_quick; } smt::context cvc4_ctx_normal() { if (!_cvc4_ctx_normal.p) { _cvc4_ctx_normal = smt::context(smt::Backend::cvc4); _cvc4_ctx_normal.set_timeout(45000); } return _cvc4_ctx_normal; } smt::context cvc4_ctx_quick() { if (!_cvc4_ctx_quick.p) { _cvc4_ctx_quick = smt::context(smt::Backend::cvc4); _cvc4_ctx_quick.set_timeout(15000); } return _cvc4_ctx_quick; } ContextSolverResult context_solve( std::string const& log_info, std::shared_ptr<Module> module, ModelType mt, Strictness st, value hint, std::function< std::vector<std::shared_ptr<ModelEmbedding>>(std::shared_ptr<BackgroundContext>) > f) { auto t1 = now(); int num_fails = 0; while (true) { smt::context ctx = (num_fails % 2 == 0 ? (st == Strictness::Quick ? z3_ctx_quick() : z3_ctx_normal()) : (st == Strictness::Quick ? cvc4_ctx_quick() : cvc4_ctx_normal()) ); shared_ptr<BackgroundContext> bgc; bgc.reset(new BackgroundContext(ctx, module)); vector<shared_ptr<ModelEmbedding>> es = f(bgc); bgc->solver.set_log_info(log_info); smt::SolverResult res = bgc->solver.check_result(); if ( st == Strictness::Indef || st == Strictness::Quick || (st == Strictness::TryHard && (num_fails == 10 || res != smt::SolverResult::Unknown)) || (st == Strictness::Strict && res != smt::SolverResult::Unknown) ) { auto t2 = now(); long long ms = as_ms(t2 - t1); global_stats.add_total(ms); if (num_fails > 0) { smt::add_stat_smt_long(ms); } ContextSolverResult csr; csr.res = res; if (es.size() > 0) { if (res == smt::SolverResult::Sat) { if (mt == ModelType::Any) { for (int i = 0; i < (int)es.size(); i++) { csr.models.push_back(Model::extract_model_from_z3( bgc->ctx, bgc->solver, module, *es[i])); } csr.models[0]->dump_sizes(); } else { auto t1 = now(); csr.models = Model::extract_minimal_models_from_z3( bgc->ctx, bgc->solver, module, es, hint); auto t2 = now(); long long ms = as_ms(t2 - t1); global_stats.add_model_min(ms); } } } if (st == Strictness::TryHard && res == smt::SolverResult::Unknown) { cout << "TryHard failure" << endl; numTryHardFailures++; } return csr; } num_fails++; numRetries++; assert(num_fails < 20); cout << "failure encountered, retrying" << endl; } } <file_sep>/src/strengthen_invariant.h #ifndef STRENGTHEN_INVARIANT_H #define STRENGTHEN_INVARIANT_H #include "logic.h" value strengthen_invariant( std::shared_ptr<Module> module, value invariant_so_far, value new_invariant); #endif <file_sep>/src/obviously_implies.cpp #include "obviously_implies.h" #include <map> #include <vector> #include <cassert> #include "top_quantifier_desc.h" using namespace std; vector<value> get_disjuncts(value v) { if (Or* o = dynamic_cast<Or*>(v.get())) { return o->args; } else { return {v}; } } vector<value> all_sub_disjunctions(value v) { auto p = get_tqd_and_body(v); TopQuantifierDesc tqd = p.first; value body = p.second; vector<value> disjuncts = get_disjuncts(body); int n = disjuncts.size(); assert(n < 30); vector<value> res; for (int i = 1; i < (1 << n); i++) { vector<value> v; for (int j = 0; j < n; j++) { if (i & (1 << j)) { v.push_back(disjuncts[j]); } } res.push_back(tqd.with_body(v_or(v))); } return res; } /*bool disj_subset( vector<value> const& ad, vector<value> const& bd, int ad_idx, map<string, string> const& emptyVarMapping) { if (ad_idx == ad.size()) { return true; } } bool obviously_implies(shared_ptr<Module> module, value a, value b) { Forall* af = dynamic_cast<Forall*>(a.get()) Forall* bf = dynamic_cast<Forall*>(b.get()) if (af != NULL) { assert (bf != NULL); assert (af.decls == bf.decls); return obviously_implies(module, a->body, b->body); } assert (bf == NULL); vector<value> ad = get_disjuncts(a); vector<value> bd = get_disjuncts(b); if (ad.size() <= bd.size()) { map<string, string> emptyVarMapping; return disj_subset(ad, bd, 0, emptyVarMapping); } else { return false; } }*/ <file_sep>/src/main.cpp #include "logic.h" #include "contexts.h" #include "model.h" #include "benchmarking.h" #include "bmc.h" #include "enumerator.h" #include "utils.h" #include "synth_loop.h" #include "wpr.h" #include "filter.h" #include "template_counter.h" #include "template_priority.h" #include "z3++.h" #include "stats.h" #include <iostream> #include <iterator> #include <string> #include <sstream> #include <cstdlib> #include <cstdio> #include <fstream> using namespace std; Stats global_stats; bool do_invariants_imply_conjecture(shared_ptr<ConjectureContext> conjctx) { smt::solver& solver = conjctx->ctx->solver; return !solver.check_sat(); } bool is_redundant( shared_ptr<InvariantsContext> invctx, shared_ptr<Value> formula) { smt::solver& solver = invctx->ctx->solver; solver.push(); solver.add(invctx->e->value2expr(shared_ptr<Value>(new Not(formula)))); bool res = !solver.check_sat(); solver.pop(); return res; } value augment_invariant(value a, value b) { if (Forall* f = dynamic_cast<Forall*>(a.get())) { return v_forall(f->decls, augment_invariant(f->body, b)); } else if (Or* o = dynamic_cast<Or*>(a.get())) { vector<value> args = o->args; args.push_back(b); return v_or(args); } else { return v_or({a, b}); } } void enumerate_next_level( vector<value> const& fills, vector<value>& next_level, value invariant, QuantifierInstantiation const& qi) { for (value fill : fills) { if (eval_qi(qi, fill)) { value newv = augment_invariant(invariant, fill); next_level.push_back(newv); } } } void print_wpr(shared_ptr<Module> module, int count) { shared_ptr<Action> action = shared_ptr<Action>(new ChoiceAction(module->actions)); value conj = v_and(module->conjectures); cout << "conjecture: " << conj->to_string() << endl; vector<value> all_conjs; value w = conj; all_conjs.push_back(w); for (int i = 0; i < count; i++) { w = wpr(w, action)->simplify(); all_conjs.push_back(w); } /*cout << "list:" << endl; for (value conj : all_conjs) { for (value part : aggressively_split_into_conjuncts(conj)) { cout << part->to_string() << endl; } } cout << endl;*/ cout << "wpr: " << w->to_string() << endl; if (is_itself_invariant(module, all_conjs)) { //if (is_wpr_itself_inductive(module, conj, count)) { printf("yes\n"); } else{ printf("no\n"); } } int run_id; extern bool enable_smt_logging; struct EnumOptions { int template_idx; string template_str; // Naive solving int disj_arity; bool depth2_shape; }; struct Strategy { bool finisher; bool breadth; TemplateSpace tspace; Strategy() { finisher = false; breadth = false; } }; void split_into_invariants_conjectures( shared_ptr<Module> module, vector<value>& invs, vector<value>& conjs) { invs.clear(); conjs = module->conjectures; while (true) { bool change = false; for (int i = 0; i < (int)conjs.size(); i++) { if (is_invariant_wrt(module, v_and(invs), conjs[i])) { invs.push_back(conjs[i]); conjs.erase(conjs.begin() + i); i--; change = true; } } if (!change) { break; } } } FormulaDump read_formula_dump(string const& filename) { ifstream f; f.open(filename); std::istreambuf_iterator<char> begin(f), end; std::string json_src(begin, end); FormulaDump fd = parse_formula_dump(json_src); return fd; } FormulaDump get_default_formula_dump(shared_ptr<Module> module) { FormulaDump fd; fd.success = false; split_into_invariants_conjectures( module, fd.base_invs /* output */, fd.conjectures /* output */); return fd; } void write_formulas(string const& filename, FormulaDump const& fd) { ofstream f; f.open(filename); string s = marshall_formula_dump(fd); f << s; f << endl; } void augment_fd(FormulaDump& fd, SynthesisResult const& synres) { if (synres.done) fd.success = true; for (value v : synres.new_values) { fd.new_invs.push_back(v); } for (value v : synres.all_values) { fd.all_invs.push_back(v); } } shared_ptr<Module> read_module(string const& module_filename) { ifstream f; f.open(module_filename); std::istreambuf_iterator<char> begin(f), end; std::string json_src(begin, end); return parse_module(json_src); } vector<value> read_value_array(string const& value_array_filename) { ifstream f; f.open(value_array_filename); std::istreambuf_iterator<char> begin(f), end; std::string json_src(begin, end); return parse_value_array(json_src); } vector<TemplateSubSlice> read_template_sub_slice_file( shared_ptr<Module> module, string const& filename) { ifstream f; f.open(filename); int sz; f >> sz; int sorts_sz; f >> sorts_sz; for (int i = 0; i < sorts_sz; i++) { string so; f >> so; assert (so == module->sorts[i] && "template file uses wrong sort order"); } vector<TemplateSubSlice> tds; for (int i = 0; i < sz; i++) { TemplateSubSlice td; f >> td; tds.push_back(td); } return tds; } void write_template_sub_slice_file( shared_ptr<Module> module, string const& filename, vector<TemplateSubSlice> const& tds) { ofstream f; f.open(filename); f << tds.size() << endl; f << module->sorts.size(); for (string so : module->sorts) { f << " " << so; } f << endl; for (TemplateSubSlice const& td : tds) { f << td << endl; } } void output_sub_slices_mult( shared_ptr<Module> module, string const& dir, vector<vector<vector<TemplateSubSlice>>> const& sub_slices, bool by_size) { assert (dir != ""); string d = (dir[dir.size() - 1] == '/' ? dir : dir + "/"); if (by_size) { for (int i = 0; i < (int)sub_slices.size(); i++) { assert (sub_slices[i].size() > 0); // driver code won't read the files right if this isn't true for (int j = 0; j < (int)sub_slices[i].size(); j++) { write_template_sub_slice_file(module, d + to_string(i+1) + "." + to_string(j+1), sub_slices[i][j]); } } } else { assert (sub_slices.size() == 1); for (int i = 0; i < (int)sub_slices[0].size(); i++) { write_template_sub_slice_file(module, d + to_string(i+1), sub_slices[0][i]); } } } value parse_templ(string const& s) { vector<char> new_s; for (int i = 0; i < (int)s.size(); i++) { if (s[i] == '-') new_s.push_back(' '); else new_s.push_back(s[i]); } string t(new_s.begin(), new_s.end()); std::stringstream ss; ss << t; vector<pair<bool, vector<VarDecl>>> all_decls; bool is_forall = false; bool is_exists = false; vector<VarDecl> decls; int varname = 0; while (true) { string s; ss >> s; if (s == "") { break; } if (!is_forall && !is_exists) { assert (s == "forall" || s == "exists"); if (s == "forall") { is_forall = true; } else { is_exists = true; } } else if (s == ".") { assert (decls.size() > 0); assert (is_forall || is_exists); all_decls.push_back(make_pair(is_exists, decls)); is_forall = false; is_exists = false; decls.clear(); } else { lsort so = s_uninterp(s); string name = to_string(varname); varname++; assert (name.size() <= 3); while (name.size() < 3) { name = "0" + name; } name = "A" + name; decls.push_back(VarDecl(string_to_iden(name), so)); } } if (decls.size() > 0) { assert (is_forall || is_exists); all_decls.push_back(make_pair(is_exists, decls)); } value templ = v_template_hole(); for (int i = (int)all_decls.size() - 1; i >= 0; i--) { if (all_decls[i].first) { templ = v_exists(all_decls[i].second, templ); } else { templ = v_forall(all_decls[i].second, templ); } } cout << "parsed template " << templ->to_string() << endl; return templ; } TemplateSpace template_space_from_enum_options( shared_ptr<Module> module, EnumOptions const& options) { TemplateSpace ts; value templ; if (options.template_str != "") { templ = parse_templ(options.template_str); } else { int idx = options.template_idx == -1 ? 0 : options.template_idx; assert (0 <= idx && idx < (int)module->templates.size()); templ = module->templates[idx]; } TopAlternatingQuantifierDesc taqd(templ); for (int i = 0; i < (int)module->sorts.size(); i++) { ts.vars.push_back(0); ts.quantifiers.push_back(Quantifier::Forall); } for (Alternation const& alter : taqd.alternations()) { for (VarDecl const& decl : alter.decls) { int idx = -1; for (int i = 0; i < (int)module->sorts.size(); i++) { if (sorts_eq(s_uninterp(module->sorts[i]), decl.sort)) { idx = i; break; } } assert (idx != -1); Quantifier q = (alter.altType == AltType::Forall ? Quantifier::Forall : Quantifier::Exists); if (ts.vars[idx] > 0) { assert (ts.quantifiers[idx] == q); } ts.quantifiers[idx] = q; ts.vars[idx]++; } } ts.depth = (options.depth2_shape ? 2 : 1); ts.k = options.disj_arity; return ts; } long long pre_symm_count_templ(shared_ptr<Module> module, int kmax, int d, int e, vector<int> const& t) { assert (d == 1 || d == 2); TemplateSpace ts; ts.vars = t; for (int i = 0; i < (int)t.size(); i++) { ts.quantifiers.push_back(Quantifier::Forall); } ts.depth = d; ts.k = kmax; value templ = ts.make_templ(module); EnumInfo ei(module, templ); int numClauses = ei.clauses.size(); long long total = 0; for (int k = 1; k <= kmax; k++) { long long prod = 1; for (int i = 0; i < k; i++) { prod *= (long long)numClauses; } if (d == 2) { prod *= 2 * (long long)((1 << (k - 1)) - 1); } total += prod; } cout << "total " << total << endl; int nsorts = t.size(); long long numCombos = 0; for (int j = 0; j < (1 << nsorts); j++) { int num_e = 0; bool okay = true; for (int k = 0; k < nsorts; k++) { if ((j >> k) & 1) { num_e += t[k]; if (t[k] == 0) { okay = false; break; } } } if (okay && num_e <= e) { numCombos++; } } return total * numCombos; } long long pre_symm_count(shared_ptr<Module> module, int k, int d, int m, int e) { int nsorts = module->sorts.size(); long long total = 0; vector<int> t; t.resize(nsorts); while (true) { int sum = 0; for (int i = 0; i < (int)t.size(); i++) { sum += t[i]; } if (sum == m) { total += pre_symm_count_templ(module, k, d, e, t); } int i; for (i = 0; i < (int)t.size(); i++) { t[i]++; if (t[i] == m+1) { t[i] = 0; } else { break; } } if (i == (int)t.size()) { break; } } return total; } void do_counts(shared_ptr<Module> module, vector<TemplateSlice> const& slices, int k, int d, int m, int e) { long long pre_count = pre_symm_count(module, k, d, m, e); cout << "Pre-symmetries: " << pre_count << endl; long long total = 0; for (TemplateSlice const& ts : slices) { total += ts.count; } cout << "Post-symmetries: " << total << endl; cout << "Num template slices: " << slices.size() << endl; /*int i = 0; for (TemplateSlice const& ts : slices) { if (ts.vars[0] == 2 && ts.vars[1] == 2 && ts.vars[2] == 1 && ts.vars[3] == 1) { cout << i+4 << endl; cout << ts.count << endl; return; } i++; for (int j = 0; j < 4; j++) { if (ts.vars[j] == 1) { i++; } } }*/ } long long presymm_of_template_space(shared_ptr<Module> module, TemplateSpace const& ts) { value templ = ts.make_templ(module); EnumInfo ei(module, templ); long long c = ei.clauses.size(); long long total = 0; for (int k = 1; k <= ts.k; k++) { long long p = 1; for (int i = 0; i < k; i++) { p *= (long long)c; } if (ts.depth == 2) { p *= 2 * (long long)((1 << (k - 1)) - 1); } total += p; } return total; } void count_strats(shared_ptr<Module> module, vector<Strategy> const& strats) { long long pre_count = 0; vector<TemplateSlice> slices; for (Strategy const& strat : strats) { vector_append(slices, break_into_slices(module, strat.tspace)); pre_count += presymm_of_template_space(module, strat.tspace); } cout << "Pre-symmetries: " << pre_count << endl; long long total = 0; for (TemplateSlice const& ts : slices) { total += ts.count; } cout << "Post-symmetries: " << total << endl; } void maybe_set_success(shared_ptr<Module> module, FormulaDump& fd) { cout << "checking if we're done" << endl; vector<value> t; for (value v : fd.base_invs) { t.push_back(v); } for (value v : fd.new_invs) { t.push_back(v); } if (is_invariant_wrt(module, v_and(t), fd.conjectures)) { cout << "is invariant!" << endl; fd.success = true; } cout << "is not invariant" << endl; } void do_check_ind_linear(shared_ptr<Module> module, string filename) { vector<value> a = read_value_array(filename); cout << "checking full inductivness..." << endl; if (!is_invariant_wrt(module, v_and(a), v_and(module->conjectures))) { cout << "no" << endl; exit(1); } cout << "yes" << endl; for (int i = 0; i < (int)a.size(); i++) { cout << "checking first " << i << "..." << endl; vector<value> rest = module->conjectures; for (int j = 0; j < i; j++) { rest.push_back(a[j]); } if (!is_invariant_wrt(module, v_and(rest), a[i])) { cout << "no" << endl; exit(1); } cout << "yes" << endl; } } int main(int argc, char* argv[]) { for (int i = 0; i < argc; i++) { cout << argv[i] << " "; } cout << endl; srand((int)time(NULL)); run_id = rand(); Options options; options.with_conjs = false; options.breadth_with_conjs = false; options.whole_space = false; options.pre_bmc = false; options.post_bmc = false; options.get_space_size = false; options.minimal_models = false; options.non_accumulative = false; //options.threads = 1; string output_chunk_dir; string input_chunk_file; int nthreads = -1; vector<string> input_formula_files; string output_formula_file; string module_filename; int seed = 1234; bool check_inductiveness = false; string check_inductiveness_linear; bool check_rel_inductiveness = false; bool check_implication = false; bool wpr = false; int wpr_index = 0; bool coalesce = false; int chunk_size_to_use = -1; bool template_counter = false; int template_counter_k; int template_counter_d; bool counts_only = false; bool template_sorter = false; int template_sorter_k; int template_sorter_d; int template_sorter_mvars; int template_sorter_e; string template_outfile; bool one_breadth = false; bool one_finisher = false; bool by_size = false; string big_impl_check_lhs; string big_impl_check_rhs; string stats_filename; int i; for (i = 1; i < argc; i++) { if (argv[i] == string("--random")) { seed = (int)time(NULL); } else if (argv[i] == string("--seed")) { assert(i + 1 < argc); seed = atoi(argv[i+1]); i++; } else if (argv[i] == string("--wpr")) { assert(i + 1 < argc); wpr_index = atoi(argv[i+1]); wpr = true; i++; } else if (argv[i] == string("--check-inductiveness")) { check_inductiveness = true; } else if (argv[i] == string("--check-inductiveness-linear")) { assert (i + 1 < argc); check_inductiveness_linear = argv[i+1]; i++; } else if (argv[i] == string("--check-rel-inductiveness")) { check_rel_inductiveness = true; } else if (argv[i] == string("--check-implication")) { check_implication = true; } else if (argv[i] == string("--one-finisher")) { one_finisher = true; } else if (argv[i] == string("--one-breadth")) { one_breadth = true; } else if (argv[i] == string("--finisher")) { break; } else if (argv[i] == string("--breadth")) { break; } else if (argv[i] == string("--whole-space")) { options.whole_space = true; } else if (argv[i] == string("--non-accumulative")) { options.non_accumulative = true; } else if (argv[i] == string("--by-size")) { by_size = true; } else if (argv[i] == string("--with-conjs")) { options.with_conjs = true; } else if (argv[i] == string("--breadth-with-conjs")) { options.breadth_with_conjs = true; } else if (argv[i] == string("--log-smt-files")) { enable_smt_logging = true; } else if (argv[i] == string("--pre-bmc")) { options.pre_bmc = true; } else if (argv[i] == string("--post-bmc")) { options.post_bmc = true; } else if (argv[i] == string("--get-space-size")) { options.get_space_size = true; } else if (argv[i] == string("--coalesce")) { coalesce = true; } else if (argv[i] == string("--minimal-models")) { options.minimal_models = true; } else if (argv[i] == string("--output-chunk-dir")) { assert(i + 1 < argc); assert (output_chunk_dir == ""); output_chunk_dir = argv[i+1]; i++; } else if (argv[i] == string("--nthreads")) { assert(i + 1 < argc); assert (nthreads == -1); nthreads = atoi(argv[i+1]); i++; } else if (argv[i] == string("--input-module")) { assert(i + 1 < argc); assert(module_filename == ""); module_filename = argv[i+1]; i++; } else if (argv[i] == string("--stats-file")) { assert(i + 1 < argc); assert(stats_filename == ""); stats_filename = argv[i+1]; i++; } else if (argv[i] == string("--input-chunk-file")) { assert(i + 1 < argc); assert(input_chunk_file == ""); input_chunk_file = argv[i+1]; i++; } else if (argv[i] == string("--output-formula-file")) { assert(i + 1 < argc); assert(output_formula_file == ""); output_formula_file = argv[i+1]; i++; } else if (argv[i] == string("--input-formula-file")) { assert(i + 1 < argc); input_formula_files.push_back(argv[i+1]); i++; } else if (argv[i] == string("--chunk-size-to-use")) { assert(i + 1 < argc); chunk_size_to_use = atoi(argv[i+1]); assert(false && "TODO implement"); i++; } else if (argv[i] == string("--template-counter")) { assert(i + 2 < argc); template_counter = true; template_counter_k = atoi(argv[i+1]); template_counter_d = atoi(argv[i+2]); i += 2; } else if (argv[i] == string("--template-sorter")) { assert(i + 4 < argc); template_sorter = true; template_sorter_k = atoi(argv[i+1]); template_sorter_d = atoi(argv[i+2]); template_sorter_mvars = atoi(argv[i+3]); template_sorter_e = atoi(argv[i+4]); i += 4; } else if (argv[i] == string("--invariant-log-file")) { assert(i + 1 < argc); assert(options.invariant_log_filename == ""); options.invariant_log_filename = argv[i+1]; i++; } else if (argv[i] == string("--counts-only")) { counts_only = true; } else if (argv[i] == string("--big-impl-check")) { assert (i + 2 < argc); big_impl_check_lhs = argv[i+1]; big_impl_check_rhs = argv[i+2]; assert(big_impl_check_lhs != ""); assert(big_impl_check_rhs != ""); i += 2; } /*else if (argv[i] == string("--threads")) { assert(i + 1 < argc); options.threads = atoi(argv[i+1]); i++; }*/ else { cout << "unreocgnized argument " << argv[i] << endl; return 1; } } shared_ptr<Module> module = read_module(module_filename); if (big_impl_check_lhs != "") { vector<value> a = read_value_array(big_impl_check_lhs); vector<value> b = read_value_array(big_impl_check_rhs); int total = 0; for (int i = 0; i < (int)b.size(); i++) { cout << i << endl; vector<value> vs; for (value v : a) { vs.push_back(v); } vs.push_back(v_not(b[i])); if (!is_satisfiable_tryhard(module, v_and(vs))) { total++; cout << "is provable: " << b[i]->to_string() << endl; } else { cout << "is not provable: " << b[i]->to_string() << endl; } } cout << "could prove " << total << " / " << b.size() << endl; cerr << "could prove " << total << " / " << b.size() << endl; return 0; } cout << "conjectures:" << endl; for (value v : module->conjectures) { cout << v->to_string() << endl; } if (template_counter) { assert (template_counter_d == 1 || template_counter_d == 2); long long res = count_template(module, module->templates[0], template_counter_k, template_counter_d == 2, false); cout << "total: " << res << endl; return 0; } if (template_sorter) { assert (template_sorter_d == 1 || template_sorter_d == 2); auto forall_slices = count_many_templates(module, template_sorter_k, template_sorter_d == 2, template_sorter_mvars); auto slices = quantifier_combos(module, forall_slices, template_sorter_e); if (counts_only) { do_counts(module, slices, template_sorter_k, template_sorter_d, template_sorter_mvars, template_sorter_e); return 0; } if (output_chunk_dir != "") { assert (nthreads != -1); assert (one_breadth ^ one_finisher); auto sub_slices = prioritize_sub_slices(module, slices, nthreads, one_breadth, by_size, false); output_sub_slices_mult(module, output_chunk_dir, sub_slices, by_size); } return 0; } if (wpr) { print_wpr(module, wpr_index); return 0; } if (check_inductiveness) { printf("just checking inductiveness...\n"); if (is_itself_invariant(module, module->conjectures)) { printf("yes\n"); } else{ printf("no\n"); } return 0; } if (check_inductiveness_linear != "") { do_check_ind_linear(module, check_inductiveness_linear); return 0; } if (check_rel_inductiveness) { printf("just inductiveness of the last one...\n"); value v = module->conjectures[module->conjectures.size() - 1]; vector<value> others; for (int i = 0; i < (int)module->conjectures.size() - 1; i++) { others.push_back(module->conjectures[i]); } if (is_invariant_wrt(module, v_and(others), v)) { printf("yes\n"); } else{ printf("no\n"); } return 0; } if (check_implication) { printf("just checking inductiveness...\n"); vector<value> vs; for (int i = 0; i < (int)module->conjectures.size(); i++) { vs.push_back(i == 0 ? v_not(module->conjectures[i]) : module->conjectures[i]); } if (is_satisfiable(module, v_and(vs))) { printf("first is NOT implied by the rest\n"); } else { printf("first IS implied by the rest\n"); } return 0; } if (coalesce) { FormulaDump res_fd; res_fd.success = false; for (string const& filename : input_formula_files) { FormulaDump fd = read_formula_dump(filename); vector_append(res_fd.base_invs, fd.base_invs); vector_append(res_fd.new_invs, fd.new_invs); vector_append(res_fd.all_invs, fd.all_invs); vector_append(res_fd.conjectures, fd.conjectures); if (fd.success) res_fd.success = true; } res_fd.base_invs = filter_unique_formulas(res_fd.base_invs); res_fd.new_invs = filter_redundant_formulas(module, res_fd.new_invs); res_fd.all_invs = filter_unique_formulas(res_fd.all_invs); res_fd.conjectures = filter_unique_formulas(res_fd.conjectures); if (!options.whole_space && !res_fd.success && input_formula_files.size() > 1) { maybe_set_success(module, res_fd); } assert (output_formula_file != ""); write_formulas(output_formula_file, res_fd); return 0; } vector<Strategy> strats; while (i < argc) { Strategy strat; if (argv[i] == string("--finisher")) { strat.finisher = true; } else if (argv[i] == string("--breadth")) { strat.breadth = true; } else { assert (false); } EnumOptions enum_options; enum_options.template_idx = -1; enum_options.disj_arity = -1; enum_options.depth2_shape = false; for (i++; i < argc; i++) { if (argv[i] == string("--finisher")) { break; } else if (argv[i] == string("--breadth")) { break; } else if (argv[i] == string("--template-space")) { assert(i + 1 < argc); enum_options.template_str = string(argv[i+1]); i++; } else if (argv[i] == string("--template")) { assert(i + 1 < argc); enum_options.template_idx = atoi(argv[i+1]); assert(0 <= enum_options.template_idx && enum_options.template_idx < (int)module->templates.size()); i++; } else if (argv[i] == string("--disj-arity")) { assert(i + 1 < argc); enum_options.disj_arity = atoi(argv[i+1]); i++; } else if (argv[i] == string("--depth2-shape")) { enum_options.depth2_shape = true; } else { cout << "unreocgnized enum_options argument " << argv[i] << endl; return 1; } } strat.tspace = template_space_from_enum_options(module, enum_options); strats.push_back(strat); } printf("random seed = %d\n", seed); srand(seed); FormulaDump input_fd; assert (input_formula_files.size() <= 1); if (input_formula_files.size() == 1) { cout << "Reading in formulas from " << input_formula_files[0] << endl; input_fd = read_formula_dump(input_formula_files[0]); } else { cout << "Retrieving base_invs / conjectures from module spec" << endl; input_fd = get_default_formula_dump(module); } for (value v : input_fd.base_invs) { cout << "[invariant] " << v->to_string() << endl; } for (value v : input_fd.conjectures) { cout << "[conjecture] " << v->to_string() << endl; } cout << "|all_invs| = " << input_fd.all_invs.size() << endl; cout << "|new_invs| = " << input_fd.new_invs.size() << endl; if (output_chunk_dir != "" || input_chunk_file != "") { for (int i = 1; i < (int)strats.size(); i++) { assert (strats[0].breadth == strats[i].breadth); assert (strats[0].finisher == strats[i].finisher); } } vector<TemplateSubSlice> sub_slices_breadth; vector<TemplateSubSlice> sub_slices_finisher; if (input_chunk_file != "") { assert (strats.size() == 0); assert (output_chunk_dir == ""); auto ss = read_template_sub_slice_file(module, input_chunk_file); assert (one_breadth || one_finisher); assert (!(one_breadth && one_finisher)); if (one_breadth) sub_slices_breadth = ss; else if (one_finisher) sub_slices_finisher = ss; } else { if (strats.size() == 0) { cout << "No strategy given ???" << endl; return 1; } if (counts_only) { count_strats(module, strats); return 0; } else if (output_chunk_dir != "") { vector<TemplateSlice> slices; for (Strategy const& strat : strats) { vector_append(slices, break_into_slices(module, strat.tspace)); } assert (nthreads != -1); auto sub_slices = prioritize_sub_slices(module, slices, nthreads, strats[0].breadth, by_size, true); output_sub_slices_mult(module, output_chunk_dir, sub_slices, by_size); return 0; } else { vector<TemplateSlice> slices_finisher; vector<TemplateSlice> slices_breadth; for (int i = 0; i < (int)strats.size(); i++) { if (strats[i].breadth) { vector_append(slices_breadth, break_into_slices(module, strats[i].tspace)); } else if (strats[i].finisher) { vector_append(slices_finisher, break_into_slices(module, strats[i].tspace)); } else { assert (false); } } assert (false); // TODO not implemented because the size of the return vector isn't guaranteed //assert (!by_size); //sub_slices_breadth = prioritize_sub_slices(module, slices_breadth, 1, true)[0]; //sub_slices_finisher = prioritize_sub_slices(module, slices_finisher, 1, false)[0]; } } FormulaDump output_fd; output_fd.success = false; output_fd.base_invs = input_fd.base_invs; output_fd.conjectures = input_fd.conjectures; if (options.get_space_size) { long long b_pre_symm = -1; long long b_post_symm = -1; long long f_pre_symm = -1; long long f_post_symm = -1; if (sub_slices_breadth.size() > 0) { shared_ptr<CandidateSolver> cs = make_candidate_solver(module, sub_slices_breadth, true); b_pre_symm = cs->getPreSymmCount(); cout << "b_pre_symm " << b_pre_symm << endl; b_post_symm = cs->getSpaceSize(); cout << "b_post_symm " << b_post_symm << endl; } if (sub_slices_finisher.size() > 0) { shared_ptr<CandidateSolver> cs = make_candidate_solver( module, sub_slices_finisher, false); f_pre_symm = cs->getPreSymmCount(); cout << "f_pre_symm " << f_pre_symm << endl; f_post_symm = cs->getSpaceSize(); cout << "f_post_symm " << f_post_symm << endl; } cout << "pre_symm counts (" << (b_pre_symm == -1 ? "None" : to_string(b_pre_symm)) << ", " << (f_pre_symm == -1 ? "None" : to_string(f_pre_symm)) << ")" << endl; cout << "post_symm counts (" << (b_post_symm == -1 ? "None" : to_string(b_post_symm)) << ", " << (f_post_symm == -1 ? "None" : to_string(f_post_symm)) << ")" << endl; return 0; } try { bool single_round = (one_breadth || one_finisher); if (sub_slices_breadth.size()) { SynthesisResult synres; cout << endl; cout << ">>>>>>>>>>>>>> Starting breadth algorithm" << endl; cout << endl; synres = synth_loop_incremental_breadth(module, sub_slices_breadth, options, input_fd, single_round); augment_fd(output_fd, synres); if (synres.done) { cout << "Synthesis success!" << endl; goto finish; } module = module->add_conjectures(synres.new_values); } if (sub_slices_finisher.size()) { cout << endl; cout << ">>>>>>>>>>>>>> Starting finisher algorithm" << endl; cout << endl; SynthesisResult synres = synth_loop(module, sub_slices_finisher, options, input_fd); augment_fd(output_fd, synres); if (synres.done) { cout << "Finisher algorithm: Synthesis success!" << endl; } else { cout << "Finisher algorithm unable to find invariant." << endl; } } finish: if (output_formula_file != "") { cout << "Writing result to " << output_formula_file << endl; write_formulas(output_formula_file, output_fd); } if (stats_filename != "") { global_stats.dump(stats_filename); } return 0; } catch (z3::exception exc) { printf("got z3 exception: %s\n", exc.msg()); throw; } } <file_sep>/src/filter.cpp #include "filter.h" #include "contexts.h" #include "solve.h" using namespace std; bool is_necessary( shared_ptr<Module> module, vector<value> const& values, int i) { ContextSolverResult csr = context_solve( "is-necessary", module, ModelType::Any, Strictness::TryHard, nullptr, [module, &values, i](shared_ptr<BackgroundContext> bgctx) { BasicContext basic_ctx(bgctx, module); smt::solver& solver = basic_ctx.ctx->solver; for (int j = 0; j < (int)values.size(); j++) { if (j == i) { solver.add(basic_ctx.e->value2expr(v_not(values[j]))); } else { solver.add(basic_ctx.e->value2expr(values[j])); } } return vector<shared_ptr<ModelEmbedding>>{}; }); // If unknown, assume necessary return csr.res != smt::SolverResult::Unsat; } vector<value> filter_redundant_formulas( shared_ptr<Module> module, vector<value> const& values0) { vector<value> values; set<ComparableValue> cvs; for (int i = 0; i < (int)values0.size(); i++) { ComparableValue cv(values0[i]); if (cvs.find(cv) == cvs.end()) { values.push_back(values0[i]); cvs.insert(values0[i]); } } for (int i = 0; i < (int)values.size(); i++) { if (!is_necessary(module, values, i)) { for (int j = i; j < (int)values.size() - 1; j++) { values[j] = values[j+1]; } values.pop_back(); i--; } } return values; } vector<value> filter_unique_formulas( vector<value> const& values0) { vector<value> values; set<ComparableValue> cvs; for (int i = 0; i < (int)values0.size(); i++) { ComparableValue cv(values0[i]); if (cvs.find(cv) == cvs.end()) { values.push_back(values0[i]); cvs.insert(values0[i]); } } return values; } <file_sep>/src/contexts.h #ifndef CONTEXTS_H #define CONTEXTS_H #include <unordered_map> #include <string> #include "smt.h" #include "logic.h" /** * Contains a mapping from Sorts to z3 sorts. */ class BackgroundContext { public: smt::context ctx; smt::solver solver; std::unordered_map<std::string, smt::sort> sorts; BackgroundContext(smt::context& ctx, std::shared_ptr<Module> module); smt::sort getUninterpretedSort(std::string name); smt::sort getSort(std::shared_ptr<Sort> sort); }; /** * Contains a mapping from functions to z3 function decls. */ class ModelEmbedding { public: std::shared_ptr<BackgroundContext> ctx; std::unordered_map<iden, smt::func_decl> mapping; ModelEmbedding( std::shared_ptr<BackgroundContext> ctx, std::unordered_map<iden, smt::func_decl> const& mapping) : ctx(ctx), mapping(mapping) { } static std::shared_ptr<ModelEmbedding> makeEmbedding( std::shared_ptr<BackgroundContext> ctx, std::shared_ptr<Module> module); smt::func_decl getFunc(iden) const; smt::expr value2expr(std::shared_ptr<Value>); smt::expr value2expr(std::shared_ptr<Value>, std::unordered_map<iden, smt::expr> const& consts); smt::expr value2expr_with_vars(std::shared_ptr<Value>, std::unordered_map<iden, smt::expr> const& vars); smt::expr value2expr(std::shared_ptr<Value>, std::unordered_map<iden, smt::expr> const& consts, std::unordered_map<iden, smt::expr> const& vars); void dump(); }; class InductionContext { public: std::shared_ptr<BackgroundContext> ctx; std::shared_ptr<ModelEmbedding> e1; std::shared_ptr<ModelEmbedding> e2; int action_idx; InductionContext(smt::context& ctx, std::shared_ptr<Module> module, int action_idx = -1); InductionContext(std::shared_ptr<BackgroundContext>, std::shared_ptr<Module> module, int action_idx = -1); private: void init(std::shared_ptr<Module> module); }; class ChainContext { public: std::shared_ptr<BackgroundContext> ctx; std::vector<std::shared_ptr<ModelEmbedding>> es; ChainContext(smt::context& ctx, std::shared_ptr<Module> module, int numTransitions); }; class ConjectureContext { public: std::shared_ptr<BackgroundContext> ctx; std::shared_ptr<ModelEmbedding> e; ConjectureContext(smt::context& ctx, std::shared_ptr<Module> module); }; class BasicContext { public: std::shared_ptr<BackgroundContext> ctx; std::shared_ptr<ModelEmbedding> e; BasicContext(smt::context& ctx, std::shared_ptr<Module> module); BasicContext(std::shared_ptr<BackgroundContext>, std::shared_ptr<Module> module); }; class InitContext { public: std::shared_ptr<BackgroundContext> ctx; std::shared_ptr<ModelEmbedding> e; InitContext(smt::context& ctx, std::shared_ptr<Module> module); InitContext(std::shared_ptr<BackgroundContext>, std::shared_ptr<Module> module); private: void init(std::shared_ptr<Module> module); }; class InvariantsContext { public: std::shared_ptr<BackgroundContext> ctx; std::shared_ptr<ModelEmbedding> e; InvariantsContext(smt::context& ctx, std::shared_ptr<Module> module); }; std::string name(std::string const& basename); std::string name(iden basename); struct ActionResult { std::shared_ptr<ModelEmbedding> e; smt::expr constraint; ActionResult( std::shared_ptr<ModelEmbedding> e, smt::expr constraint) : e(e), constraint(constraint) { } }; ActionResult applyAction( std::shared_ptr<ModelEmbedding> e, std::shared_ptr<Action> action, std::unordered_map<iden, smt::expr> const& consts); bool is_satisfiable(std::shared_ptr<Module>, value); /* * Returns 'true' in the 'SAT' or 'unknown' case. */ bool is_satisfiable_tryhard(std::shared_ptr<Module>, value); bool is_complete_invariant(std::shared_ptr<Module>, value); bool is_itself_invariant(std::shared_ptr<Module>, value); bool is_itself_invariant(std::shared_ptr<Module>, std::vector<value>); // Check if wpr^n(value) is inductive (no init check) // Here, wpr includes the 'empty action'. bool is_wpr_itself_inductive(std::shared_ptr<Module>, value, int wprIter); bool is_invariant_with_conjectures(std::shared_ptr<Module>, value); bool is_invariant_with_conjectures(std::shared_ptr<Module>, std::vector<value>); bool is_invariant_wrt(std::shared_ptr<Module>, value invariant_so_far, value candidate); bool is_invariant_wrt(std::shared_ptr<Module>, value invariant_so_far, std::vector<value> const& candidate); bool is_invariant_wrt_tryhard( std::shared_ptr<Module>, value invariant_so_far, value candidate); #endif <file_sep>/src/synth_loop.cpp #include "synth_loop.h" #include <iostream> #include <fstream> #include <streambuf> #include "lib/json11/json11.hpp" #include "model.h" #include "enumerator.h" #include "benchmarking.h" #include "bmc.h" #include "quantifier_permutations.h" #include "top_quantifier_desc.h" #include "strengthen_invariant.h" #include "filter.h" #include "synth_enumerator.h" #include "utils.h" #include "solve.h" using namespace std; using namespace json11; int numRetries = 0; int numTryHardFailures = 0; Counterexample get_bmc_counterexample( BMCContext& bmc, value candidate, Options const& options) { if (!options.pre_bmc) { Counterexample cex; cex.none = true; return cex; } shared_ptr<Model> model = bmc.get_k_invariance_violation_maybe(candidate, options.minimal_models); if (model) { printf("counterexample type: INIT (after some steps)\n"); Counterexample cex; cex.is_true = model; return cex; } else { Counterexample cex; cex.none = true; return cex; } } shared_ptr<InductionContext> get_counterexample_test_with_conjs_make_indctx( shared_ptr<Module> module, Options const& options, shared_ptr<BackgroundContext> bgctx, value cur_invariant, value candidate, vector<value> conjectures, int j) { auto indctx = shared_ptr<InductionContext>(new InductionContext(bgctx, module, j)); smt::solver& solver = indctx->ctx->solver; if (cur_invariant) { solver.add(indctx->e1->value2expr(cur_invariant)); } solver.add(indctx->e1->value2expr(candidate)); for (value conj : conjectures) { solver.add(indctx->e1->value2expr(conj)); } return indctx; } Counterexample get_counterexample_test_with_conjs( shared_ptr<Module> module, Options const& options, value cur_invariant, value candidate, vector<value> conjectures) { Counterexample cex; cex.none = false; ContextSolverResult csr = context_solve( "init-check", module, options.minimal_models ? ModelType::Min : ModelType::Any, Strictness::TryHard, candidate /* hint */, [module, candidate](shared_ptr<BackgroundContext> bgctx) { auto initctx = shared_ptr<InitContext>(new InitContext(bgctx, module)); smt::solver& init_solver = initctx->ctx->solver; init_solver.add(initctx->e->value2expr(v_not(candidate))); return vector<shared_ptr<ModelEmbedding>>{initctx->e}; }); if (csr.res == smt::SolverResult::Unknown) { return cex; } if (csr.res == smt::SolverResult::Sat) { cex.is_true = csr.models[0]; printf("counterexample type: INIT\n"); return cex; } for (int k = 0; k < (int)conjectures.size(); k++) { for (int j = 0; j < (int)module->actions.size(); j++) { ContextSolverResult csr = context_solve( "inductivity-check-with-conj: " + module->action_names[j], module, options.minimal_models ? ModelType::Min : ModelType::Any, Strictness::TryHard, candidate /* hint */, [module, k, j, &options, cur_invariant, candidate, &conjectures](shared_ptr<BackgroundContext> bgctx) { auto indctx = get_counterexample_test_with_conjs_make_indctx( module, options, bgctx, cur_invariant, candidate, conjectures, j); smt::solver& solver = indctx->ctx->solver; solver.add(indctx->e2->value2expr(v_not(conjectures[k]))); return vector<shared_ptr<ModelEmbedding>>{indctx->e1}; }); if (csr.res == smt::SolverResult::Unknown) { return cex; } if (csr.res == smt::SolverResult::Sat) { cex.is_false = csr.models[0]; printf("counterexample type: SAFETY\n"); return cex; } } } for (int j = 0; j < (int)module->actions.size(); j++) { ContextSolverResult csr = context_solve( "inductivity-check: " + module->action_names[j], module, options.minimal_models ? ModelType::Min : ModelType::Any, Strictness::TryHard, candidate /* hint */, [module, &options, cur_invariant, candidate, &conjectures, j](shared_ptr<BackgroundContext> bgctx) { auto indctx = get_counterexample_test_with_conjs_make_indctx( module, options, bgctx, cur_invariant, candidate, conjectures, j); smt::solver& solver = indctx->ctx->solver; solver.add(indctx->e2->value2expr(v_not(candidate))); return vector<shared_ptr<ModelEmbedding>>{indctx->e1, indctx->e2}; }); if (csr.res == smt::SolverResult::Unknown) { return cex; } if (csr.res == smt::SolverResult::Sat) { cex.hypothesis = csr.models[0]; cex.conclusion = csr.models[1]; printf("counterexample type: INDUCTIVE\n"); return cex; } } cex.none = true; return cex; } Counterexample get_counterexample_simple( shared_ptr<Module> module, Options const& options, BMCContext& bmc, bool check_implies_conj, vector<value> const& conjs, value cur_invariant, value candidate) { Counterexample cex; cex.none = false; ContextSolverResult csr = context_solve( "init-check", module, options.minimal_models ? ModelType::Min : ModelType::Any, Strictness::TryHard, candidate /* hint */, [module, candidate](shared_ptr<BackgroundContext> bgctx) { auto initctx = shared_ptr<InitContext>(new InitContext(bgctx, module)); smt::solver& init_solver = initctx->ctx->solver; init_solver.add(initctx->e->value2expr(v_not(candidate))); return vector<shared_ptr<ModelEmbedding>>{initctx->e}; }); if (csr.res == smt::SolverResult::Unknown) { return cex; } if (csr.res == smt::SolverResult::Sat) { cex.is_true = csr.models[0]; printf("counterexample type: INIT\n"); return cex; } if (check_implies_conj) { ContextSolverResult csr = context_solve( "conj-check", module, options.minimal_models ? ModelType::Min : ModelType::Any, Strictness::TryHard, candidate /* hint */, [module, candidate, &conjs, cur_invariant](shared_ptr<BackgroundContext> bgctx) { auto conjctx = shared_ptr<BasicContext>(new BasicContext(bgctx, module)); smt::solver& conj_solver = conjctx->ctx->solver; conj_solver.add(conjctx->e->value2expr(v_not(v_and(conjs)))); if (cur_invariant) { conj_solver.add(conjctx->e->value2expr(cur_invariant)); } conj_solver.add(conjctx->e->value2expr(candidate)); return vector<shared_ptr<ModelEmbedding>>{conjctx->e}; }); if (csr.res == smt::SolverResult::Unknown) { return cex; } if (csr.res == smt::SolverResult::Sat) { cex.is_false = csr.models[0]; printf("counterexample type: SAFETY\n"); return cex; } } if (options.pre_bmc) { Counterexample bmc_cex = get_bmc_counterexample(bmc, candidate, options); if (!bmc_cex.none) { return bmc_cex; } } for (int j = 0; j < (int)module->actions.size(); j++) { ContextSolverResult csr = context_solve( "inductivity-check: " + module->action_names[j], module, options.minimal_models ? ModelType::Min : ModelType::Any, Strictness::TryHard, candidate /* hint */, [module, candidate, j, cur_invariant](shared_ptr<BackgroundContext> bgctx) { auto indctx = shared_ptr<InductionContext>(new InductionContext(bgctx, module, j)); smt::solver& solver = indctx->ctx->solver; if (cur_invariant) { solver.add(indctx->e1->value2expr(cur_invariant)); } solver.add(indctx->e1->value2expr(candidate)); solver.add(indctx->e2->value2expr(v_not(candidate))); return vector<shared_ptr<ModelEmbedding>>{indctx->e1, indctx->e2}; }); if (csr.res == smt::SolverResult::Unknown) { return cex; } if (csr.res == smt::SolverResult::Sat) { cex.hypothesis = csr.models[0]; cex.conclusion = csr.models[1]; printf("counterexample type: INDUCTIVE\n"); return cex; } } cex.none = true; return cex; } bool conjectures_inv( shared_ptr<Module> module, vector<value> const& filtered_simplified_strengthened_invs, vector<value> const& conjectures) { return is_invariant_wrt( module, v_and(filtered_simplified_strengthened_invs), conjectures); } void cex_stats(Counterexample cex) { shared_ptr<Model> model; if (cex.is_true) { model = cex.is_true; } else if (cex.is_false) { model = cex.is_false; } else if (cex.hypothesis) { model = cex.hypothesis; } else { return; } model->dump_sizes(); } Counterexample simplify_cex_nosafety(shared_ptr<Module> module, Counterexample cex, Options const& options, BMCContext& bmc) { if (!options.post_bmc) { return cex; } if (cex.hypothesis) { if (bmc.is_reachable_returning_false_if_unknown(cex.conclusion) || bmc.is_reachable_returning_false_if_unknown(cex.hypothesis)) { Counterexample res; res.is_true = cex.conclusion; printf("simplifying -> INIT\n"); return res; } return cex; } else { return cex; } } Counterexample simplify_cex(shared_ptr<Module> module, Counterexample cex, Options const& options, BMCContext& bmc, BMCContext& antibmc) { if (!options.post_bmc) { return cex; } if (cex.hypothesis) { if (bmc.is_reachable_returning_false_if_unknown(cex.conclusion) || bmc.is_reachable_exact_steps_returning_false_if_unknown(cex.hypothesis)) { Counterexample res; res.is_true = cex.conclusion; printf("simplifying -> INIT\n"); return res; } if (antibmc.is_reachable_exact_steps_returning_false_if_unknown(cex.conclusion) || antibmc.is_reachable_returning_false_if_unknown(cex.hypothesis)) { Counterexample res; res.is_false = cex.hypothesis; printf("simplifying -> SAFETY\n"); return res; } return cex; } else { return cex; } } struct Transcript { vector<pair<Counterexample, value>> entries; Json to_json() const; static Transcript from_json(Json, shared_ptr<Module>); }; Json Counterexample::to_json() const { if (none) { return Json(); } else if (is_true) { return Json(vector<Json>{Json("is_true"), is_true->to_json()}); } else if (is_false) { return Json(vector<Json>{Json("is_false"), is_false->to_json()}); } else { assert(hypothesis != nullptr); assert(conclusion != nullptr); return Json({Json("ind"), hypothesis->to_json(), conclusion->to_json()}); } } Counterexample Counterexample::from_json(Json j, shared_ptr<Module> module) { Counterexample cex; if (j.is_null()) { cex.none = true; return cex; } assert(j.is_array()); assert(j.array_items().size() >= 2); assert(j[0].is_string()); string type = j[0].string_value(); if (type == "is_true") { assert(j.array_items().size() == 2); cex.is_true = Model::from_json(j[1], module); } else if (type == "is_false") { assert(j.array_items().size() == 2); cex.is_false = Model::from_json(j[1], module); } else if (type == "ind") { assert(j.array_items().size() == 3); cex.hypothesis = Model::from_json(j[1], module); cex.conclusion = Model::from_json(j[2], module); } else { assert(false); } return cex; } Json Transcript::to_json() const { vector<Json> ar; for (auto p : entries) { map<string, Json> o_ent; o_ent.insert(make_pair("cex", p.first.to_json())); o_ent.insert(make_pair("candidate", p.second->to_json())); ar.push_back(Json(o_ent)); } return Json(ar); } Transcript Transcript::from_json(Json j, shared_ptr<Module> module) { Transcript t; assert(j.is_array()); for (auto ent : j.array_items()) { assert(ent.is_object()); Counterexample cex = Counterexample::from_json(ent["cex"], module); value v = Value::from_json(ent["candidate"]); t.entries.push_back(make_pair(cex, v)); } return t; } vector<pair<Counterexample, value>> filter_unneeded_cexes( vector<pair<Counterexample, value>> const& cexes, value invariant_so_far) { vector<pair<Counterexample, value>> res; for (auto p : cexes) { Counterexample cex = p.first; if (cex.is_true || (cex.hypothesis && cex.hypothesis->eval_predicate(invariant_so_far))) { res.push_back(p); } } return res; } bool invariant_is_nonredundant(shared_ptr<Module> module, vector<value> existingInvariants, value newInvariant) { ContextSolverResult csr = context_solve( "redundancy check", module, ModelType::Any, Strictness::TryHard, nullptr, [module, &existingInvariants, newInvariant](shared_ptr<BackgroundContext> bgctx) { BasicContext basic(bgctx, module); for (value v : existingInvariants) { basic.ctx->solver.add(basic.e->value2expr(v)); } basic.ctx->solver.add(basic.e->value2expr(v_not(newInvariant))); return vector<shared_ptr<ModelEmbedding>>{}; }); // Assume it's nonredundant in the Unknown case. return csr.res != smt::SolverResult::Unsat; } struct CexStats { int count_true; int count_false; int count_ind; CexStats() : count_true(0), count_false(0), count_ind(0) { } void add(Counterexample const& cex) { if (cex.is_true) { count_true++; } else if (cex.is_false) { count_false++; } else { count_ind++; } } void dump() const { cout << "Counterexamples of type TRUE: " << count_true << endl; cout << "Counterexamples of type FALSE: " << count_false << endl; cout << "Counterexamples of type TRANSITION: " << count_ind << endl; } }; int numEnumeratedFilteredRedundantInvariants = 0; void dump_stats(long long progress, CexStats const& cs, std::chrono::time_point<std::chrono::high_resolution_clock> init, int num_redundant, int num_nonredundant, long long filtering_ms, long long num_finishers_found, long long addCounterexample_ms, long long addCounterexample_count, long long cex_process_ns, long long redundant_process_ns, long long nonredundant_process_ns, long long indef_count, long long indef_ns) { cout << "================= Stats =================" << endl; cout << "progress: " << progress << endl; cout << "total time running so far: " << as_ms(now() - init) << " ms" << endl; cout << "total time filtering: " << filtering_ms << " ms" << endl; cout << "total time addCounterexample: " << addCounterexample_ms << " ms" << endl; if (addCounterexample_count > 0) { cout << "avg time addCounterexample: " << (addCounterexample_ms/addCounterexample_count) << " ops" << endl; } cout << "total time processing counterexamples: " << cex_process_ns / 1000000 << " ms" << endl; cout << "total time processing redundant: " << redundant_process_ns / 1000000 << " ms" << endl; cout << "total time processing nonredundant: " << nonredundant_process_ns / 1000000 << " ms" << endl; cout << "total time processing indef: " << indef_ns / 1000000 << " ms" << endl; cs.dump(); cout << "number of redundant invariants found: " << num_redundant << endl; cout << "number of non-redundant invariants found: " << num_nonredundant << endl; cout << "number of finisher invariants found: " << num_finishers_found << endl; cout << "number of retries: " << numRetries << endl; cout << "number of TryHard failures: " << numTryHardFailures << endl; cout << "number of candidates could not determine inductiveness: " << indef_count << endl; cout << "number of enumerated filtered redundant invariants: " << numEnumeratedFilteredRedundantInvariants << endl; smt::dump_smt_stats(); cout << "=========================================" << endl; cout.flush(); } int get_k(value v) { if (And* a = dynamic_cast<And*>(v.get())) { int k = 0; for (value arg : a->args) { k += get_k(arg); } return k; } else if (Or* a = dynamic_cast<Or*>(v.get())) { int k = 0; for (value arg : a->args) { k += get_k(arg); } return k; } else { return 1; } } bool has_and(value v) { if (dynamic_cast<And*>(v.get())) { return true; } else if (Or* a = dynamic_cast<Or*>(v.get())) { for (value arg : a->args) { bool d = has_and(arg); if (d) return true; } return false; } else { return false; } } void dump_inv_params(value v) { pair<TopAlternatingQuantifierDesc, value> p = get_taqd_and_body(v); TopAlternatingQuantifierDesc taqd = p.first; value body = p.second; int m = 0, e = 0; for (Alternation const& alt : taqd.alternations()) { if (alt.is_exists()) { e += alt.decls.size(); } m += alt.decls.size(); } int k = get_k(body); int d = has_and(body) ? 2 : 1; cout << "Resulting invariant: " << v->to_string() << endl; cout << "Resulting invariant parameters: " << "k=" << k << " " << "d=" << d << " " << "m=" << m << " " << "e=" << e << endl; } extern const int TIMEOUT = 45 * 1000; SynthesisResult synth_loop( shared_ptr<Module> module, vector<TemplateSubSlice> const& slices, Options const& options, FormulaDump const& fd) { shared_ptr<CandidateSolver> cs = make_candidate_solver( module, slices, false); SynthesisResult synres; synres.done = false; auto t_init = now(); smt::context bmcctx(smt::Backend::z3); int bmc_depth = 4; printf("bmc_depth = %d\n", bmc_depth); BMCContext bmc(bmcctx, module, bmc_depth); BMCContext antibmc(bmcctx, module, bmc_depth, true); bmcctx.set_timeout(15000); // 15 seconds int num_iterations = 0; /*if (init_transcript) { printf("using init_transcript with %d entries\n", (int)init_transcript->entries.size()); for (auto p : init_transcript->entries) { Counterexample cex = p.first; value candidate = p.second; add_counterexample(module, sf, cex, candidate); } printf("done\n"); }*/ value cur_invariant = v_and(fd.base_invs); //Transcript transcript; CexStats cexstats; if (options.get_space_size) { long long s = cs->getSpaceSize(); cout << "space size: " << s << endl; exit(0); } bool logging_invs = false; ofstream inv_log; if (options.invariant_log_filename != "") { logging_invs = true; inv_log.open(options.invariant_log_filename); } long long filtering_ns = 0; long long num_finishers_found = 0; long long process_cex_ns = 0; long long process_indef_ns = 0; long long indef_count = 0; value result_inv; while (true) { num_iterations++; printf("\n"); //log_smtlib(solver_sf); //printf("number of boolean variables: %d\n", sf.get_bool_count()); cout << "num iterations " << num_iterations << endl; std::cout.flush(); auto filtering_t1 = now(); value candidate = cs->getNext(); filtering_ns += as_ns(now() - filtering_t1); context_reset(); auto process_start_t = now(); if (!candidate) { printf("unable to synthesize any formula\n"); break; } cout << "candidate: " << candidate->to_string() << endl; Counterexample cex; if (options.with_conjs) { cex = get_counterexample_test_with_conjs(module, options, cur_invariant, candidate, fd.conjectures); if (!cex.is_valid()) { long long process_ns = as_ns(now() - process_start_t); process_indef_ns += process_ns; indef_count++; cout << "WARNING: COULD NOT DETERMINE INDUCTIVENESS" << endl; continue; } cex = simplify_cex_nosafety(module, cex, options, bmc); } else { cex = get_counterexample_simple(module, options, bmc, true, fd.conjectures, nullptr, candidate); if (!cex.is_valid()) { long long process_ns = as_ns(now() - process_start_t); process_indef_ns += process_ns; indef_count++; cout << "WARNING: COULD NOT DETERMINE INDUCTIVENESS" << endl; continue; } cex = simplify_cex(module, cex, options, bmc, antibmc); } cexstats.add(cex); if (cex.none) { num_finishers_found++; // Extra verification: // (If we get here, then it should definitely be invariant, // this is just a sanity check that our code is right.) bool is_inv = true; // cutting out this sanity check because it's slow :/ /*if (options.with_conjs) { vector<value> conjs = module->conjectures; conjs.push_back(candidate); vector_append(conjs, fd.base_invs); is_inv = is_itself_invariant(module, conjs); } else { is_inv = is_complete_invariant(module, candidate); }*/ if (is_inv) { printf("found invariant: %s\n", candidate->to_string().c_str()); synres.done = true; synres.new_values.push_back(candidate); result_inv = candidate; if (logging_invs) { inv_log << candidate->to_json().dump() << endl; } } else { printf("ERROR: invariant is not actually invariant"); assert(false); } if (!options.whole_space) { break; } } else { cex_stats(cex); cs->addCounterexample(cex); //transcript.entries.push_back(make_pair(cex, candidate)); } long long process_ns = as_ns(now() - process_start_t); if (!cex.none) { process_cex_ns += process_ns; } dump_stats(cs->getProgress(), cexstats, t_init, 0, 0, filtering_ns/1000000, num_finishers_found, 0, 0, process_cex_ns, 0, 0, indef_count, process_indef_ns); } //cout << transcript.to_json().dump() << endl; dump_stats(cs->getProgress(), cexstats, t_init, 0, 0, filtering_ns/1000000, num_finishers_found, 0, 0, process_cex_ns, 0, 0, indef_count, process_indef_ns); if (result_inv) { dump_inv_params(result_inv); } cout << "complete!" << endl; return synres; } template <typename T> vector<T> vector_concat(vector<T> const& a, vector<T> const& b) { vector<T> res = a; for (int i = 0; i < (int)b.size(); i++) { res.push_back(b[i]); } return res; } SynthesisResult synth_loop_incremental_breadth( shared_ptr<Module> module, vector<TemplateSubSlice> const& slices, Options const& options, FormulaDump const& fd, bool single_round) { auto t_init = now(); smt::context bmcctx(smt::Backend::z3); if (fd.conjectures.size() == 0) { cout << "already invariant, done" << endl; return SynthesisResult(true, {}, {}); } vector<value> all_invs = fd.all_invs; vector<value> new_invs = fd.new_invs; //vector<value> strengthened_invs = all_invs; //vector<value> filtered_simplified_strengthened_invs = new_invs; vector<value> base_invs_plus_new_invs = vector_concat( fd.base_invs, fd.new_invs); vector<value> conjs_plus_base_invs_plus_new_invs = vector_concat( fd.conjectures, base_invs_plus_new_invs); vector<value> base_invs_plus_conjs = vector_concat( fd.base_invs, fd.conjectures); int bmc_depth = 4; printf("bmc_depth = %d\n", bmc_depth); BMCContext bmc(bmcctx, module, bmc_depth); bmcctx.set_timeout(15000); // 15 seconds bool logging_invs = false; ofstream inv_log; if (options.invariant_log_filename != "") { logging_invs = true; inv_log.open(options.invariant_log_filename); } int num_iterations_total = 0; int num_iterations_outer = 0; int num_redundant = 0; int num_nonredundant = 0; CexStats cexstats; long long filtering_ns = 0; long long addCounterexample_ns = 0; long long addCounterexample_count = 0; long long cex_process_ns = 0; long long redundant_process_ns = 0; long long nonredundant_process_ns = 0; long long process_indef_ns = 0; long long indef_count = 0; while (true) { num_iterations_outer++; shared_ptr<CandidateSolver> cs = make_candidate_solver(module, slices, true); if (options.get_space_size) { long long s = cs->getSpaceSize(); cout << "space size: " << s << endl; exit(0); } for (value inv : all_invs) { cs->addExistingInvariant(inv); } int num_iterations = 0; bool any_formula_synthesized_this_round = false; while (true) { num_iterations++; num_iterations_total++; cout << endl; auto filtering_t1 = now(); value candidate0 = cs->getNext(); filtering_ns += as_ns(now() - filtering_t1); context_reset(); auto process_start_t = now(); if (!candidate0) { break; } cout << "total iterations: " << num_iterations_total << " (" << num_iterations_outer << " outer + " << num_iterations << ")" << endl; cout << "candidate: " << candidate0->to_string() << endl; value candidate = candidate0->reduce_quants(); Counterexample cex = get_counterexample_simple( module, options, bmc, false /* check_implies_conj */, fd.conjectures, v_and( options.non_accumulative ? (options.breadth_with_conjs ? base_invs_plus_conjs : fd.base_invs) : (options.breadth_with_conjs ? conjs_plus_base_invs_plus_new_invs : base_invs_plus_new_invs) ), candidate); if (!cex.is_valid()) { long long process_ns = as_ns(now() - process_start_t); process_indef_ns += process_ns; indef_count++; cout << "WARNING: COULD NOT DETERMINE INDUCTIVENESS" << endl; continue; } Benchmarking bench2; bench2.start("simplification"); cex = simplify_cex_nosafety(module, cex, options, bmc); bench2.end(); bench2.dump(); assert(cex.is_false == nullptr); cexstats.add(cex); bool is_nonredundant; if (cex.none) { //Benchmarking bench_strengthen; //bench_strengthen.start("strengthen"); value strengthened_inv = options.non_accumulative ? candidate0 : strengthen_invariant(module, v_and( (options.breadth_with_conjs ? conjs_plus_base_invs_plus_new_invs : base_invs_plus_new_invs) ), candidate0); value simplified_strengthened_inv = strengthened_inv->simplify()->reduce_quants(); //bench_strengthen.end(); //bench_strengthen.dump(); cout << "strengthened " << strengthened_inv->to_string() << endl; is_nonredundant = invariant_is_nonredundant(module, (options.breadth_with_conjs ? conjs_plus_base_invs_plus_new_invs : base_invs_plus_new_invs), simplified_strengthened_inv); all_invs.push_back(strengthened_inv); if (is_nonredundant) { any_formula_synthesized_this_round = true; base_invs_plus_new_invs.push_back(simplified_strengthened_inv); conjs_plus_base_invs_plus_new_invs.push_back(simplified_strengthened_inv); new_invs.push_back(simplified_strengthened_inv); cout << "\nfound new invariant! all so far:\n"; for (value found_inv : new_invs) { cout << " " << found_inv->to_string() << endl; } if (logging_invs) { inv_log << simplified_strengthened_inv->to_json().dump() << endl; } //if (!options.whole_space && is_invariant_with_conjectures(module, filtered_simplified_strengthened_invs)) { /*if (!options.whole_space && conjectures_inv(module, filtered_simplified_strengthened_invs, conjectures)) { cout << "invariant implies safety condition, done!" << endl; dump_stats(cs->getProgress(), cexstats, t_init, num_redundant, filtering_ns/1000000, 0); return SynthesisResult(true, filtered_simplified_strengthened_invs, all_invs); }*/ num_nonredundant++; } else { cout << "invariant is redundant" << endl; num_redundant++; } cs->addExistingInvariant(strengthened_inv); } else { cex_stats(cex); auto t1 = now(); cs->addCounterexample(cex); auto t2 = now(); addCounterexample_ns += as_ns(t2 - t1); addCounterexample_count++; cout << "addCounterexample: " << addCounterexample_ns / 1000000 << endl; } long long process_ns = as_ns(now() - process_start_t); if (!cex.none) { cex_process_ns += process_ns; } else if (is_nonredundant) { nonredundant_process_ns += process_ns; } else { redundant_process_ns += process_ns; } dump_stats(cs->getProgress(), cexstats, t_init, num_redundant, num_nonredundant, filtering_ns/1000000, 0, addCounterexample_ns / 1000000, addCounterexample_count, cex_process_ns, redundant_process_ns, nonredundant_process_ns, indef_count, process_indef_ns); } dump_stats(cs->getProgress(), cexstats, t_init, num_redundant, num_nonredundant, filtering_ns/1000000, 0, addCounterexample_ns / 1000000, addCounterexample_count, cex_process_ns, redundant_process_ns, nonredundant_process_ns, indef_count, process_indef_ns); if (!any_formula_synthesized_this_round) { cout << "unable to synthesize any formula" << endl; break; } //if (!options.whole_space && conjectures_inv(module, new_invs, conjectures)) if (!options.whole_space && is_invariant_wrt(module, v_and(base_invs_plus_new_invs), fd.conjectures)) { cout << "invariant implies safety condition, done!" << endl; dump_stats(cs->getProgress(), cexstats, t_init, num_redundant, num_nonredundant, filtering_ns/1000000, 0, addCounterexample_ns / 1000000, addCounterexample_count, cex_process_ns, redundant_process_ns, nonredundant_process_ns, indef_count, process_indef_ns); return SynthesisResult(true, new_invs, all_invs); } if (single_round) { cout << "terminating because of single_round mode" << endl; break; } } return SynthesisResult(false, new_invs, all_invs); } <file_sep>/src/wpr.h #ifndef WPR_H #define WPR_H #include "logic.h" value wpr(value v, std::shared_ptr<Action> action); #endif <file_sep>/scripts/paper_benchmarks.py import sys import os import subprocess import shutil import time from pathlib import Path import queue import threading import signal import atexit import traceback import protocol_parsing import json NUM_PARTS = 100 TIMEOUT_SECS = 6*3600 MAX_SEED = 5 all_procs = [] DEFAULT_THREADS = 8 class PaperBench(object): def __init__(self, partition, ivyname, config, threads=DEFAULT_THREADS, seed=1, mm=True, pre_bmc=False, post_bmc=False, nonacc=False, whole=False, expect_success=True, finisher_only=False, main=False, is_long=False): self.partition = partition self.ivyname = ivyname self.config = config self.threads = threads self.seed = seed self.mm = mm self.pre_bmc = pre_bmc self.post_bmc = post_bmc self.nonacc = nonacc self.whole = whole self.expect_success = expect_success self.finisher_only = finisher_only self.is_long = is_long self.args = self.get_args() self.name = self.get_name() self.main = main def get_name(self): name = "" if self.post_bmc: name += "postbmc_" if self.pre_bmc: name += "prebmc_" if self.mm: name += "mm_" if self.nonacc: name += "nonacc_" if self.whole: name += "whole_" if self.finisher_only: name += "fonly_" name += "_" assert self.ivyname.endswith(".pyv") or self.ivyname.endswith(".ivy") if self.ivyname.endswith(".ivy"): name += self.ivyname[:-4] else: name += self.ivyname[:-4] + "_pyv" name += "__" + self.config name += "__seed" + str(self.seed) + "_t" + str(self.threads) return name def get_args(self): p = os.path.join("benchmarks", self.ivyname) return ([p, "--config", self.config, "--threads", str(self.threads), "--seed", str(self.seed), "--with-conjs", "--breadth-with-conjs"] + (["--minimal-models"] if self.mm else []) + (["--pre-bmc"] if self.pre_bmc else []) + (["--post-bmc"] if self.post_bmc else []) + (["--by-size", "--non-accumulative"] if self.nonacc else []) + (["--whole-space"] if self.whole else []) + (["--finisher-only"] if self.finisher_only else []) ) benches = [ ] THREADS = 8 #benches.append(PaperBench(6, "paxos.ivy", config="auto_breadth", seed=1, nonacc=True)) #benches.append(PaperBench(1, "multi_paxos.ivy", config="auto_breadth", seed=1, nonacc=True)) #benches.append(PaperBench(6, "flexible_paxos.ivy", config="auto_breadth", seed=1, nonacc=True)) #benches.append(PaperBench(1, "fast_paxos.ivy", config="auto", seed=1, nonacc=True)) #benches.append(PaperBench(1, "stoppable_paxos.ivy", config="auto", seed=1, nonacc=True)) #benches.append(PaperBench(1, "vertical_paxos.ivy", config="auto", seed=1, nonacc=True)) # protocol filename # config # expect timeout # expect timeout on f_only MAIN_BENCHMARKS = [ ("simple-de-lock.ivy", "auto", False, False, ), ("leader-election.ivy", "auto_full", False, False, ), ("learning-switch-ternary.ivy", "auto_e0_full", False, True, ), ("lock-server-sync.ivy", "auto_full", False, False, ), ("2PC.ivy", "auto_full", False, False, ), ("paxos.ivy", "auto", False, True, ), ("multi_paxos.ivy", "basic", False, True, ), ("multi_paxos.ivy", "auto", True, True, ), ("flexible_paxos.ivy", "auto", False, True, ), ("fast_paxos.ivy", "auto", True, True, ), ("stoppable_paxos.ivy", "auto", True, True, ), ("vertical_paxos.ivy", "auto", True, True, ), ("chain.ivy", "auto", True, True, ), ("chord.ivy", "auto", True, True, ), ("distributed_lock.ivy", "auto9", False, True, ), ("client_server_ae.pyv", "auto", False, False, ), ("client_server_db_ae.pyv", "auto", False, False, ), ("consensus_epr.pyv", "auto", False, True, ), ("consensus_forall.pyv", "auto", False, True, ), ("consensus_wo_decide.pyv", "auto", False, True, ), ("hybrid_reliable_broadcast_cisa.pyv", "auto", True, True, ), ("learning-switch-quad.pyv", "auto", False, False, ), ("lock-server-async.pyv", "auto9", False, False, ), ("sharded_kv.pyv", "auto9", False, True, ), ("ticket.pyv", "auto9", False, False, ), ("toy_consensus_epr.pyv", "auto", False, False, ), ("toy_consensus_forall.pyv", "auto", False, False, ), ("sharded_kv_no_lost_keys.pyv", "auto_e2", False, True, ), ] for ivy_name, config_name, expect_timeout, expect_timeout_fonly in MAIN_BENCHMARKS: for seed in range(1, MAX_SEED + 1): for fonly in (False, True): if fonly and seed > 2: continue if expect_timeout and seed > 1: continue is_long = (fonly and expect_timeout_fonly) main = not fonly benches.append(PaperBench(1, ivy_name, config_name, seed=seed, nonacc=True, finisher_only=fonly, main=main, is_long=is_long)) benches.append(PaperBench(2, "paxos.ivy", config="auto_breadth", nonacc=True, expect_success=False)) benches.append(PaperBench(2, "paxos.ivy", config="auto_finisher", nonacc=True, expect_success=False)) benches.append(PaperBench(3, "paxos_epr_missing1.ivy", config="wrong1", nonacc=True, expect_success=False)) benches.append(PaperBench(3, "paxos_epr_missing1.ivy", config="wrong2", nonacc=True, expect_success=False)) benches.append(PaperBench(3, "paxos_epr_missing1.ivy", config="wrong3", nonacc=True, expect_success=False)) benches.append(PaperBench(3, "paxos_epr_missing1.ivy", config="wrong4", nonacc=True, expect_success=False)) benches.append(PaperBench(3, "paxos_epr_missing1.ivy", config="wrong5", nonacc=True, expect_success=False)) benches.append(PaperBench(3, "paxos_epr_missing1.ivy", config="basic", nonacc=True, expect_success=False, whole=True)) benches.append(PaperBench(3, "paxos_epr_missing1.ivy", config="basic2", nonacc=True, expect_success=False, whole=True)) benches.append(PaperBench(4, "paxos_epr_missing1.ivy", config="basic", nonacc=True)) benches.append(PaperBench(4, "paxos_epr_missing1.ivy", config="basic2", nonacc=True)) for i in (8,4,2,1): benches.append(PaperBench(6, "paxos.ivy", "basic_b", nonacc=True, threads=i, expect_success=False)) benches.append(PaperBench(6, "paxos.ivy", "basic_b", threads=i, expect_success=False)) benches.append(PaperBench(11, "paxos_epr_missing1.ivy", "basic", threads=i, whole=True, expect_success=False)) #benches.append(PaperBench(29, "chord-gimme-1.ivy", "basic", threads=i)) #benches.append(PaperBench(29, "chord-gimme-1.ivy", "basic", threads=i, nonacc=True)) #benches.append(PaperBench(30, "multi_paxos.ivy", "basic", threads=i, whole=True, expect_success=False)) #benches.append(PaperBench(30, "multi_paxos.ivy", "basic", threads=i, whole=True, expect_success=False, nonacc=True)) #benches.append(PaperBench(31, "flexible_paxos.ivy", "basic", threads=i, whole=True, expect_success=False)) #benches.append(PaperBench(31, "flexible_paxos.ivy", "basic", threads=i, whole=True, expect_success=False, nonacc=True)) for minmodels in (True, False): for postbmc in [False]: #(False, True): for prebmc in (False, True): for nonacc in [True]: #(False, True): c = ( (1 if minmodels else 0) + (2 if prebmc else 0) + (4 if nonacc else 0) ) c += 32 c = 6 args = {"mm" : minmodels, "post_bmc" : postbmc, "pre_bmc" : prebmc, "nonacc" : nonacc, "threads" : 8 } #benches.append(PaperBench(c, "simple-de-lock.ivy", config="basic", **args)) benches.append(PaperBench(c, "leader-election.ivy", config="basic_b", **args)) #benches.append(PaperBench(c, "leader-election.ivy", config="basic_f", **args)) benches.append(PaperBench(c, "learning-switch-ternary.ivy", config="basic", **args)) #benches.append(PaperBench(c, "lock-server-sync.ivy", config="basic", **args)) benches.append(PaperBench(c, "2PC.ivy", config="basic", **args)) benches.append(PaperBench(c, "paxos.ivy", config="basic", **args)) benches.append(PaperBench(c, "multi_paxos.ivy", config="basic", **args)) benches.append(PaperBench(c, "flexible_paxos.ivy", config="basic", **args)) #benches.append(PaperBench(c, "chord-gimme-1.ivy", config="basic", **args)) #benches.append(PaperBench(c, "decentralized-lock-gimme-1.ivy", config="basic", **args)) #for seed in range(1, 9): #benches.append(PaperBench(40, "learning-switch-ternary.ivy", "basic", threads=THREADS, seed=seed, nonacc=True)) #benches.append(PaperBench(40, "learning-switch-ternary.ivy", "basic", threads=THREADS, seed=seed)) #benches.append(PaperBench(41, "paxos.ivy", "basic", threads=THREADS, seed=seed, nonacc=True)) #benches.append(PaperBench(7, "paxos.ivy", "basic", threads=THREADS, seed=seed)) # benches.append(PaperBench(42, "paxos.ivy", "basic_b", threads=THREADS, seed=seed, nonacc=True, expect_success=False)) # benches.append(PaperBench(7, "paxos.ivy", "basic_b", threads=THREADS, seed=seed, expect_success=False)) # # benches.append(PaperBench(7, "paxos_epr_missing1.ivy", "basic", threads=THREADS, whole=True, seed=seed, expect_success=False)) #all_names = list(set([b.name for b in benches])) #assert len(all_names) == len(list(set(all_names))) # check uniqueness def unique_benches(old_benches): benches = [] names = set() for b in old_benches: assert 1 <= b.partition <= NUM_PARTS if b.name not in names: names.add(b.name) benches.append(b) return benches old_benches = benches benches = unique_benches(benches) #for b in benches: # print(b.get_args()[0]) # assert os.path.exists(b.get_args()[0]) def get_statfile(out): for line in out.split(b'\n'): if line.startswith(b"statfile: "): t = line.split() assert len(t) == 2 return t[1] return None def exists(directory, bench): result_filename = os.path.join(directory, bench.name) return os.path.exists(result_filename) def success_true(out): return b"\nSuccess: True" in out def collect_partial_invariants(logdir): try: inv_file = os.path.join(logdir, "invariants") if os.path.exists(inv_file): print("WARNING: invariants file already exists, this is unexpected") return i = 0 while True: if os.path.exists(os.path.join(logdir, "partial_invs." + str(i+1) + ".base")): i += 1 else: break if i == 0: print("WARNING: collect_partial_invariants found no base file???") return t = [] with open(os.path.join(logdir, "partial_invs." + str(i) + ".base")) as f: j = f.read() if j != "empty\n": j = json.loads(j) t = j["base_invs"] + j["new_invs"] for fname in os.listdir(logdir): if fname.startswith("partial_invs." + str(i) + "."): spl = fname.split('.') if spl[2] != 'base': with open(os.path.join(logdir, fname), "r") as f: for line in f: if line.strip() != '': j = json.loads(line) assert type(j) == list t.append(j) strs = [ protocol_parsing.value_json_to_string(j) for j in t ] with open(os.path.join(logdir, "invariants"), "w") as f: f.write("# timed out and extracted\n") for j in strs: f.write("conjecture " + j + "\n") except Exception: print("WARNING: failed to collect partial invariants for " + logdir) traceback.print_exc() def copy_dir(out_directory, logdir, bench, out): summary_filename = os.path.join(logdir, "summary") inv_filename = os.path.join(logdir, "invariants") if ( not os.path.exists(summary_filename) or not os.path.exists(inv_filename)): return "crash" newdir = os.path.join(out_directory, bench.name) summary_filename_new = os.path.join(newdir, "summary") inv_filename_new = os.path.join(newdir, "invariants") os.mkdir(newdir) shutil.copy(summary_filename, summary_filename_new) shutil.copy(inv_filename, inv_filename_new) if success_true(out): return "success" else: return "fail" def make_logfile(): proc = subprocess.Popen(["date", "+%Y-%m-%d_%H.%M.%S"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = proc.communicate() ret = proc.wait() assert ret == 0 dt = out.strip().decode("utf-8") if "SCRATCH" in os.environ: scratch = os.environ["SCRATCH"] assert "pylon5" in scratch log_start = os.path.join(scratch, "log.") else: log_start = "./logs/log." proc = subprocess.Popen(["mktemp", "-d", log_start+dt+"-XXXXXXXXX"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = proc.communicate() ret = proc.wait() assert ret == 0 logfile = out.strip().decode("utf-8") assert logfile.startswith(log_start) return logfile def run(directory, bench): if exists(directory, bench): print("already done " + bench.name) return logdir = make_logfile() print("doing " + bench.name + " " + logdir) sys.stdout.flush() t1 = time.time() env = dict(os.environ) env["SYNTHESIS_LOGDIR"] = logdir proc = subprocess.Popen(["./save.sh"] + bench.args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env, preexec_fn=os.setsid) all_procs.append(proc) try: out, err = proc.communicate(timeout=TIMEOUT_SECS) timed_out = False except subprocess.TimeoutExpired: os.killpg(os.getpgid(proc.pid), signal.SIGTERM) timed_out = True if timed_out: print("timed out " + bench.name + " (" + str(TIMEOUT_SECS) + " seconds) " + logdir) newdir = os.path.join(directory, bench.name) os.mkdir(newdir) result_filename = os.path.join(newdir, "summary") with open(result_filename, "w") as f: f.write(" ".join(["./save.sh"] + bench.args) + "\n") f.write("TIMED OUT " + str(TIMEOUT_SECS) + " seconds\n") f.write(logdir + "\n") collect_partial_invariants(logdir) shutil.copy( os.path.join(logdir, "invariants"), os.path.join(newdir, "invariants") ) return False else: ret = proc.wait() assert ret == 0 t2 = time.time() seconds = t2 - t1 all_procs.remove(proc) result = copy_dir(directory, logdir, bench, out) assert result in ('crash', 'success', 'fail') if result == "crash": print("failed " + bench.name + " (" + str(seconds) + " seconds) " + logdir) return False else: print("done " + bench.name + " (" + str(seconds) + " seconds) " + logdir) if bench.expect_success and result != 'success': print("WARNING: " + bench.name + " did not succeed") def run_wrapper(directory, bench, idx, q): run(directory, bench) q.put(idx) def awesome_async_run(directory, benches, j): for bench in benches: assert bench.threads <= j benches = sorted(benches, key = lambda b : -b.threads) done = [False] * len(benches) started = [False] * len(benches) c = 0 for i in range(len(benches)): if exists(directory, benches[i]): print("already done " + benches[i].name) done[i] = True c += 1 t = 0 q = queue.Queue() while c < len(benches): cur = None for i in range(len(benches)): if (not done[i]) and (not started[i]) and benches[i].threads + t <= j: cur = i break if cur is None: idx = q.get() done[idx] = True c += 1 t -= benches[idx].threads else: thr = threading.Thread(target=run_wrapper, daemon=True, args=(directory, benches[cur], cur, q)) thr.start() t += benches[cur].threads started[cur] = True def get_all_main_benchmarks(): res = [] for b in old_benches: if b.main: res.append(b) return res def does_exist(name): return any(b.name == name for b in benches) def parse_args(args): res = [] j = None p = None q1 = None q2 = None one = None skip_long = False median_of = MAX_SEED i = 0 while i < len(args): if args[i] == '-j': j = int(args[i+1]) i += 1 elif args[i] == '-p': p = int(args[i+1]) i += 1 elif args[i] == '-q': q1 = int(args[i+1]) q2 = int(args[i+2]) i += 2 elif args[i] == '--one': one = args[i+1] i += 1 elif args[i] == '--skip-long': skip_long = True elif args[i] == '--median-of': median_of = int(args[i+1]) assert 1 <= median_of <= MAX_SEED i += 1 else: res.append(args[i]) i += 1 if p != None: assert q1 != None return j, p, q1, q2, one, res, skip_long, median_of #for b in benches: # print(b.name) #print('IGNORING nonacc') #benches = [b for b in benches if not b.nonacc] def cleanup(): for proc in all_procs: # list of your processes try: print('killing pid ' + str(proc.pid)) os.killpg(os.getpgid(proc.pid), signal.SIGTERM) except Exception: print("warning: could not kill sub process " + str(proc.pid)) pass atexit.register(cleanup) def filter_benches(benches, skip_long, median_of): res = [] for b in benches: if b.seed > median_of: print("skipping", b.name, "[ --median-of", median_of, "]") elif b.is_long and skip_long: print("skipping", b.name, "[ --skip-long ]") else: res.append(b) return res def auto_partition(b, q1, q2): assert 1 <= q1 <= q2 if q1 == q2: q1 = 0 t = [] for i in range(len(b)): if i % q2 == q1: t.append(b[i]) return t def main(): args = sys.argv[1:] j, p, q1, q2, one, args, skip_long, median_of = parse_args(args) assert len(args) == 1 directory = args[0] Path(directory).mkdir(parents=True, exist_ok=True) assert directory.startswith("paperlogs/") my_benches = filter_benches(benches, skip_long, median_of) if q1 != None: my_benches = auto_partition(my_benches, q1, q2) if j == None: for b in my_benches: if (p == None or p == b.partition) and (b.name == one or one == None): run(directory, b) else: if p == None: awesome_async_run(directory, my_benches, j) else: awesome_async_run(directory, [b for b in my_benches if b.partition == p], j) print('done') if __name__ == "__main__": main() <file_sep>/scripts/part_scripts.py import sys paperlog_bucket = sys.argv[1] nparts = int(sys.argv[2]) print("paperlogs/" + paperlog_bucket) print("num parts: " + str(nparts)) queue_script = """#!/bin/bash """ for partition in range(1, nparts+1): queue_script += "sbatch part" + str(partition) + "\n" s = """#!/bin/bash #SBATCH -N 1 #SBATCH -p RM #SBATCH -t 72:00:00 # set duration of the job #SBATCH -o paper_benchmarks.o%j # set output name of log file #echo commands to stdout set -x make python3 scripts/paper_benchmarks.py paperlogs/""" + str(paperlog_bucket) + """ -j 24 -p """ + str(partition) + """ """ with open("part" + str(partition), "w") as f: f.write(s) with open("queue.sh", "w") as f: f.write(queue_script) <file_sep>/src/wpr.cpp #include "wpr.h" #include <cassert> using namespace std; value wpr(value v, shared_ptr<Action> a) { if (LocalAction* action = dynamic_cast<LocalAction*>(a.get())) { map<iden, iden> newLocals; vector<VarDecl> forallDecls; for (auto arg : action->args) { VarDecl d = freshVarDecl(arg.sort); newLocals.insert(make_pair(arg.name, d.name)); forallDecls.push_back(d); } return v_forall(forallDecls, wpr(v, action->body)->replace_const_with_var(newLocals)); } else if (SequenceAction* action = dynamic_cast<SequenceAction*>(a.get())) { for (int i = action->actions.size() - 1; i >= 0; i--) { v = wpr(v, action->actions[i]); } return v; } else if (Assume* action = dynamic_cast<Assume*>(a.get())) { return v_implies(action->body, v); } else if (If* action = dynamic_cast<If*>(a.get())) { vector<value> values; values.push_back(v_implies(action->condition, wpr(v, action->then_body))); values.push_back(v_implies(v_not(action->condition), v)); return v_and(values); } else if (IfElse* action = dynamic_cast<IfElse*>(a.get())) { vector<value> values; values.push_back(v_implies(action->condition, wpr(v, action->then_body))); values.push_back(v_implies(v_not(action->condition), wpr(v, action->else_body))); return v_and(values); } else if (ChoiceAction* action = dynamic_cast<ChoiceAction*>(a.get())) { vector<value> values; for (int i = 0; i < (int)action->actions.size(); i++) { values.push_back(wpr(v, action->actions[i])); } return v_and(values); } else if (Assign* action = dynamic_cast<Assign*>(a.get())) { Apply* apply = dynamic_cast<Apply*>(action->left.get()); assert(apply != NULL); vector<VarDecl> decls; vector<value> eqs; vector<value> args; Const* c = dynamic_cast<Const*>(apply->func.get()); assert(c != NULL); for (int i = 0; i < (int)apply->args.size(); i++) { value arg = apply->args[i]; if (Var* arg_var = dynamic_cast<Var*>(arg.get())) { args.push_back(arg); decls.push_back(VarDecl(arg_var->name, arg_var->sort)); } else { VarDecl arg_decl = freshVarDecl(c->sort->get_domain_as_function()[i]); decls.push_back(arg_decl); value placeholder = v_var(arg_decl.name, arg_decl.sort); args.push_back(placeholder); eqs.push_back(v_eq(placeholder, arg)); } } value expr = v_if_then_else( v_and(eqs), action->right, v_apply(apply->func, args)); return v->subst_fun(c->name, decls, expr); } else if (dynamic_cast<Havoc*>(a.get())) { assert(false); } else { assert(false && "applyAction does not implement this unknown case"); } assert(false); } <file_sep>/src/smt.h #ifndef SMT_H #define SMT_H #include <memory> #include <vector> #include <string> #include <fstream> #include <cassert> namespace smt { struct _sort { virtual ~_sort() { } }; struct sort { std::shared_ptr<_sort> p; sort(std::shared_ptr<_sort> p) : p(p) { } }; struct _expr { virtual ~_expr() { } virtual std::shared_ptr<_expr> equals(_expr* a) const = 0; virtual std::shared_ptr<_expr> not_equals(_expr* a) const = 0; virtual std::shared_ptr<_expr> logic_negate() const = 0; virtual std::shared_ptr<_expr> logic_or(_expr* a) const = 0; virtual std::shared_ptr<_expr> logic_and(_expr* a) const = 0; virtual std::shared_ptr<_expr> ite(_expr*, _expr*) const = 0; virtual std::shared_ptr<_expr> implies(_expr*) const = 0; }; struct expr { std::shared_ptr<_expr> p; expr(std::shared_ptr<_expr> p) : p(p) { } expr operator==(expr const& a) const { return p->equals(a.p.get()); } expr operator!=(expr const& a) const { return p->not_equals(a.p.get()); } expr operator!() const { return p->logic_negate(); } expr operator||(expr const& a) const { return p->logic_or(a.p.get()); } expr operator&&(expr const& a) const { return p->logic_and(a.p.get()); } }; struct expr_vector; struct _expr_vector; struct sort_vector; struct _sort_vector; struct solver; struct _solver; struct _func_decl { virtual ~_func_decl() { } virtual size_t arity() = 0; virtual std::shared_ptr<_sort> domain(int i) = 0; virtual std::shared_ptr<_sort> range() = 0; virtual std::shared_ptr<_expr> call(_expr_vector* args) = 0; virtual std::shared_ptr<_expr> call() = 0; virtual std::string get_name() = 0; virtual bool eq(_func_decl*) = 0; }; struct func_decl { std::shared_ptr<_func_decl> p; func_decl(std::shared_ptr<_func_decl> p) : p(p) { } size_t arity() { return p->arity(); } sort domain(int i) { return p->domain(i); } sort range() { return p->range(); } inline expr call(expr_vector args); inline expr call(); std::string get_name() { return p->get_name(); } }; enum class Backend { z3, cvc4 }; struct _context { virtual ~_context() { } virtual void set_timeout(int ms) = 0; virtual std::shared_ptr<_sort> bool_sort() = 0; virtual std::shared_ptr<_expr> bool_val(bool) = 0; virtual std::shared_ptr<_sort> uninterpreted_sort(std::string const& name) = 0; virtual std::shared_ptr<_func_decl> function( std::string const& name, _sort_vector* domain, _sort* range) = 0; virtual std::shared_ptr<_func_decl> function( std::string const& name, _sort* range) = 0; virtual std::shared_ptr<_expr> var( std::string const& name, _sort* range) = 0; virtual std::shared_ptr<_expr> bound_var( std::string const& name, _sort* so) = 0; virtual std::shared_ptr<_expr_vector> new_expr_vector() = 0; virtual std::shared_ptr<_sort_vector> new_sort_vector() = 0; virtual std::shared_ptr<_solver> make_solver() = 0; }; std::shared_ptr<_context> make_z3_context(); std::shared_ptr<_context> make_cvc4_context(); struct context { std::shared_ptr<_context> p; context() { } context(Backend backend) { if (backend == Backend::z3) { p = make_z3_context(); } else { p = make_cvc4_context(); } } void set_timeout(int ms) { p->set_timeout(ms); } sort bool_sort() { return p->bool_sort(); } expr bool_val(bool b) { return p->bool_val(b); } sort uninterpreted_sort(std::string const& name) { return p->uninterpreted_sort(name); } inline func_decl function( std::string const& name, sort_vector domain, sort range); inline func_decl function( std::string const& name, sort range); inline expr var( std::string const& name, sort so); inline expr bound_var( std::string const& name, sort so); inline solver make_solver(); }; struct _sort_vector { virtual ~_sort_vector() { } virtual void push_back(_sort* s) = 0; virtual size_t size() = 0; virtual std::shared_ptr<_sort> get_at(int i) = 0; }; struct sort_vector { std::shared_ptr<_sort_vector> p; sort_vector(context& ctx) : p(ctx.p->new_sort_vector()) { } void push_back(sort s) { p->push_back(s.p.get()); } size_t size() { return p->size(); } sort operator[] (int i) { return p->get_at(i); } }; struct _expr_vector { virtual ~_expr_vector() { } virtual void push_back(_expr* e) = 0; virtual size_t size() = 0; virtual std::shared_ptr<_expr> get_at(int i) = 0; virtual std::shared_ptr<_expr> forall(_expr* body) = 0; virtual std::shared_ptr<_expr> exists(_expr* body) = 0; virtual std::shared_ptr<_expr> mk_and() = 0; virtual std::shared_ptr<_expr> mk_or() = 0; }; struct expr_vector { std::shared_ptr<_expr_vector> p; expr_vector(context& ctx) : p(ctx.p->new_expr_vector()) { } void push_back(expr s) { p->push_back(s.p.get()); } size_t size() { return p->size(); } expr operator[] (int i) { return p->get_at(i); } }; enum class SolverResult { Sat, Unsat, Unknown }; struct _solver { virtual ~_solver() { } std::string log_info; void set_log_info(std::string const& s) { log_info = s; } void log_smtlib(long long ms, std::string const& res); virtual void dump(std::ofstream& of) = 0; virtual SolverResult check_result() = 0; bool check_sat() { SolverResult res = check_result(); assert (res == SolverResult::Sat || res == SolverResult::Unsat); return res == SolverResult::Sat; } virtual void push() = 0; virtual void pop() = 0; virtual void add(_expr* e) = 0; }; struct solver { std::shared_ptr<_solver> p; solver(std::shared_ptr<_solver> p) : p(p) { } void set_log_info(std::string const& s) { p->set_log_info(s); } SolverResult check_result() { return p->check_result(); } bool check_sat() { return p->check_sat(); } void push() { p->push(); } void pop() { p->pop(); } void add(expr e) { p->add(e.p.get()); } }; inline expr forall(expr_vector args, expr body) { return args.p->forall(body.p.get()); } inline expr exists(expr_vector args, expr body) { return args.p->exists(body.p.get()); } inline expr mk_and(expr_vector args) { return args.p->mk_and(); } inline expr mk_or(expr_vector args) { return args.p->mk_or(); } inline expr ite(expr a, expr b, expr c) { return a.p->ite(b.p.get(), c.p.get()); } inline expr implies(expr a, expr b) { return a.p->implies(b.p.get()); } inline expr func_decl::call(expr_vector args) { return this->p->call(args.p.get()); } inline expr func_decl::call() { return this->p->call(); } inline func_decl context::function( std::string const& name, sort_vector domain, sort range) { return p->function(name, domain.p.get(), range.p.get()); } inline func_decl context::function( std::string const& name, sort range) { return p->function(name, range.p.get()); } inline expr context::var( std::string const& name, sort so) { return p->var(name, so.p.get()); } inline expr context::bound_var( std::string const& name, sort so) { return p->bound_var(name, so.p.get()); } inline bool func_decl_eq(func_decl a, func_decl b) { return a.p->eq(b.p.get()); } inline solver context::make_solver() { return p->make_solver(); } void log_to_stdout(long long ms, bool is_cvc4, std::string const& log_info, std::string const& res); bool is_z3_context(context&); void dump_smt_stats(); void add_stat_smt_long(long long ms); } #endif <file_sep>/src/stats.h #ifndef STATS_H #define STATS_H #include <vector> #include <string> #include <fstream> struct Stats { std::vector<long long> z3_times; std::vector<long long> cvc4_times; std::vector<long long> total_times; std::vector<long long> model_min_times; void add_z3(long long a) { z3_times.push_back(a); } void add_cvc4(long long a) { cvc4_times.push_back(a); } void add_total(long long a) { total_times.push_back(a); } void add_model_min(long long a) { model_min_times.push_back(a); } void dump_vec(std::ofstream& f, std::string const& name, std::vector<long long> const& vec) { f << name << "\n"; for (long long i : vec) { f << i << "\n"; } } void dump(std::string const& filename) { std::ofstream f; f.open(filename); dump_vec(f, "z3", z3_times); dump_vec(f, "cvc4", cvc4_times); dump_vec(f, "total", total_times); dump_vec(f, "model_min", model_min_times); f << std::endl; } }; extern Stats global_stats; #endif <file_sep>/src/utils.cpp #include "utils.h" #include <algorithm> #include <vector> #include <cassert> using namespace std; namespace { struct NormalizeState { vector<iden> names; iden get_name(iden name) { int idx = -1; for (int i = 0; i < (int)names.size(); i++) { if (names[i] == name) { idx = i; break; } } if (idx == -1) { names.push_back(name); idx = names.size() - 1; } return idx; } }; value normalize(value v, NormalizeState& ns) { assert(v.get() != NULL); if (Forall* va = dynamic_cast<Forall*>(v.get())) { return v_forall(va->decls, normalize(va->body, ns)); } else if (Exists* va = dynamic_cast<Exists*>(v.get())) { return v_exists(va->decls, normalize(va->body, ns)); } else if (Var* va = dynamic_cast<Var*>(v.get())) { return v_var(ns.get_name(va->name), va->sort); } else if (dynamic_cast<Const*>(v.get())) { return v; } else if (Eq* va = dynamic_cast<Eq*>(v.get())) { return v_eq( normalize(va->left, ns), normalize(va->right, ns)); } else if (Not* va = dynamic_cast<Not*>(v.get())) { return v_not( normalize(va->val, ns)); } else if (Implies* va = dynamic_cast<Implies*>(v.get())) { return v_implies( normalize(va->left, ns), normalize(va->right, ns)); } else if (Apply* va = dynamic_cast<Apply*>(v.get())) { value func = normalize(va->func, ns); vector<value> args; for (value arg : va->args) { args.push_back(normalize(arg, ns)); } return v_apply(func, args); } else if (And* va = dynamic_cast<And*>(v.get())) { vector<value> args; for (value arg : va->args) { args.push_back(normalize(arg, ns)); } return v_and(args); } else if (Or* va = dynamic_cast<Or*>(v.get())) { vector<value> args; for (value arg : va->args) { args.push_back(normalize(arg, ns)); } return v_or(args); } else { //printf("value2expr got: %s\n", templ->to_string().c_str()); assert(false && "value2expr does not support this case"); } } } bool is_redundant_quick(value a, value b) { while (true) { Forall* a_f = dynamic_cast<Forall*>(a.get()); Forall* b_f = dynamic_cast<Forall*>(b.get()); if (a_f == NULL || b_f == NULL) { break; } if (a_f->decls.size() != b_f->decls.size()) { return false; } for (int i = 0; i < (int)a_f->decls.size(); i++) { if (a_f->decls[i].name != b_f->decls[i].name) { return false; } } a = a_f->body; b = b_f->body; } Not* a_n = dynamic_cast<Not*>(a.get()); Not* b_n = dynamic_cast<Not*>(b.get()); if (a_n == NULL || b_n == NULL) { return false; } And* a_and = dynamic_cast<And*>(a_n->val.get()); And* b_and = dynamic_cast<And*>(b_n->val.get()); vector<value> a_and_args; vector<value> b_and_args; if (a_and == NULL) { a_and_args.push_back(a_n->val); } else { a_and_args = a_and->args; } if (b_and == NULL) { b_and_args.push_back(b_n->val); } else { b_and_args = b_and->args; } int n = a_and_args.size(); int m = b_and_args.size(); if (!(n < m)) { return false; } NormalizeState ns; string a_str = normalize(v_and(a_and_args), ns)->to_string(); vector<int> perm; for (int i = 0; i < m; i++) { perm.push_back(i); } do { vector<value> b_subset; for (int i = 0; i < n; i++) { b_subset.push_back(b_and_args[perm[i]]); } value b_and_subset = v_and(b_subset); NormalizeState ns; string b_str = normalize(b_and_subset, ns)->to_string(); //printf("cmp %s %s %s\n", a_str.c_str(), b_str.c_str(), a_str == b_str ? "yes" : "no"); if (a_str == b_str) { return true; } reverse(perm.begin() + n, perm.end()); } while (next_permutation(perm.begin(), perm.end())); return false; } vector<int> sort_and_uniquify(vector<int> const& v) { vector<int> t = v; sort(t.begin(), t.end()); vector<int> u; for (int i = 0; i < (int)t.size(); i++) { if (i == 0 || t[i] != t[i-1]) { u.push_back(t[i]); } } return u; } <file_sep>/scripts/protocol_parsing.py import subprocess import tempfile import json import tempfile import predicate_parsing ### Parsing def ivy_file_json_file(ivy_filename): t = tempfile.mktemp() with open(t, "w") as f: proc = subprocess.Popen(["python2", "./scripts/file_to_json.py", ivy_filename], stdout=f) ret = proc.wait() assert ret == 0, "file_to_json.py failed" return t def pyv_file_json_file(pyv_filename): t = tempfile.mktemp() with open(t, "w") as f: proc = subprocess.Popen(["python3", "./scripts/file_mypyvy_to_json.py", pyv_filename], stdout=f) ret = proc.wait() assert ret == 0, "file_mypyvy_to_json.py failed" return t def protocol_file_json_file(protocol_filename): assert protocol_filename.endswith(".pyv") or protocol_filename.endswith(".ivy") if protocol_filename.endswith(".pyv"): return pyv_file_json_file(protocol_filename) else: return ivy_file_json_file(protocol_filename) # Parse and get in-memory json def ivy_file_json(ivy_filename): t = tempfile.mktemp() proc = subprocess.Popen(["python2", "./scripts/file_to_json.py", ivy_filename], stdout=subprocess.PIPE) out, err = proc.communicate() ret = proc.wait() assert ret == 0, "file_to_json.py failed: " + ivy_filename return out def pyv_file_json(pyv_filename): t = tempfile.mktemp() proc = subprocess.Popen(["python3", "./scripts/file_mypyvy_to_json.py", pyv_filename], stdout=subprocess.PIPE) out, err = proc.communicate() ret = proc.wait() assert ret == 0, "file_mypyvy_to_json.py failed" return out def protocol_file_json(protocol_filename): assert protocol_filename.endswith(".pyv") or protocol_filename.endswith(".ivy") if protocol_filename.endswith(".pyv"): return pyv_file_json(protocol_filename) else: return ivy_file_json(protocol_filename) def parse_invs(protocol_filename, inv_contents): js = protocol_file_json(protocol_filename) return parse_invs_from_json(js, inv_contents) def parse_invs_from_json_filename(protocol_json_filename, inv_contents): with open(protocol_json_filename) as f: j = f.read() return parse_invs_from_json(j, inv_contents) def parse_invs_from_json(protocol_json, inv_contents): j = json.loads(protocol_json) i = ["#lang ivy1.5"] def get_domain(so): if so[0] == "functionSort": return so[1] else: return [] def get_range(so): if so[0] == "functionSort": return so[2] else: return so n = {"n": 1} def sort_to_name_with_id(so): i = n["n"] n["n"] += 1 assert so[0] == "uninterpretedSort" return "X" + str(i) + ": " + so[1] def sort_to_name(so): assert so[0] == "uninterpretedSort" return so[1] for so in j["sorts"]: i.append("type " + so) for f in j["functions"]: assert f[0] in ('var', 'const') so = f[2] domain = get_domain(so) rng = get_range(so) i.append( ('relation ' if rng[0] == 'booleanSort' else 'function ') + f[1] + ('(' + ', '.join(sort_to_name_with_id(d) for d in domain) + ')' if len(domain) > 0 else '') + (': ' + sort_to_name(rng) if rng[0] != 'booleanSort' else '') ) i = "\n".join(i) + "\n\n" + inv_contents + "\n" tmpivy = tempfile.mktemp() with open(tmpivy, "w") as f: f.write(i) t = ivy_file_json(tmpivy) return (j, json.loads(t)["conjectures"]) ### Serializing def value_json_to_string(inv): return inv_to_str(inv) def inv_to_str(inv): #print(inv) assert type(inv) == list if inv[0] == 'forall' or inv[0] == 'exists': return '(' + inv[0] + " " + ", ".join(decl_to_str(decl) for decl in inv[1]) + " . (" + inv_to_str(inv[2]) + '))' elif inv[0] == 'or': return '(' + ' | '.join(inv_to_str(i) for i in inv[1]) + ')' elif inv[0] == 'and': return '(' + ' & '.join(inv_to_str(i) for i in inv[1]) + ')' elif inv[0] == 'not': return '(~(' + inv_to_str(inv[1]) + '))' elif inv[0] == 'apply': return const_name(inv[1]) + '(' + ', '.join(inv_to_str(i) for i in inv[2]) + ')' elif inv[0] == 'var': return inv[1] elif inv[0] == 'const': return inv[1] elif inv[0] == 'eq': return '(' + inv_to_str(inv[1]) + ' = ' + inv_to_str(inv[2]) + ')' elif inv[0] == 'implies': return '(' + inv_to_str(inv[1]) + ' -> ' + inv_to_str(inv[2]) + ')' else: print("inv_to_str") print(repr(inv)) assert False def decl_to_str(decl): assert decl[0] == 'var' assert decl[2][0] == 'uninterpretedSort' return decl[1] + ':' + decl[2][1] def const_name(c): assert c[0] == 'const' return c[1] def parse_module_invs_invs_invs(protocol_filename, inv_filename1, inv_filename2): module_json_filename = protocol_file_json_file(protocol_filename) with open(module_json_filename) as f: j = f.read() with open(inv_filename1) as f: inv_contents1 = f.read() if inv_filename2 != None: with open(inv_filename2) as f: inv_contents2 = f.read() i1 = parse_invs_from_json_filename(module_json_filename, inv_contents1)[1] if inv_filename2 != None: i2 = parse_invs_from_json_filename(module_json_filename, inv_contents2)[1] else: i2 = None j = json.loads(j) return (module_json_filename, j["conjectures"], i1, i2) def parse_module_and_invs_myparser(protocol_filename, inv_filename): module_json_filename = protocol_file_json_file(protocol_filename) with open(module_json_filename) as f: j = f.read() j = json.loads(j) with open(inv_filename) as f: invs_contents = f.read() invs = predicate_parsing.parse_inv_contents(invs_contents, j) return (module_json_filename, j, invs) def parse_module_and_invs_invs_myparser(protocol_filename, inv_filename1, inv_filename2): module_json_filename = protocol_file_json_file(protocol_filename) with open(module_json_filename) as f: j = f.read() j = json.loads(j) with open(inv_filename1) as f: invs_contents1 = f.read() invs1 = predicate_parsing.parse_inv_contents(invs_contents1, j) if inv_filename2 != None: with open(inv_filename2) as f: invs_contents2 = f.read() invs2 = predicate_parsing.parse_inv_contents(invs_contents2, j) else: invs2 = None return (module_json_filename, j, invs1, invs2) <file_sep>/src/template_priority.h #ifndef TEMPLATE_PRIORITY_H #define TEMPLATE_PRIORITY_H #include "template_desc.h" #include <vector> std::vector<TemplateSlice> break_into_slices( std::shared_ptr<Module> module, TemplateSpace const& ts); std::vector<std::vector<std::vector<TemplateSubSlice>>> prioritize_sub_slices( std::shared_ptr<Module> module, std::vector<TemplateSlice> const&, int nthreads, bool is_for_breadth, bool by_size, bool basic_split); std::vector<TemplateSlice> quantifier_combos( std::shared_ptr<Module> module, std::vector<TemplateSlice> const& forall_slices, int maxExists); #endif <file_sep>/src/var_lex_graph.h #ifndef VAR_LEX_GRAPH_H #define VAR_LEX_GRAPH_H #include "logic.h" struct VarIndexState { // Minimum index reached (0 for none at all, 1 for having reached // the first one, etc.) std::vector<int> indices; VarIndexState(size_t sz) : indices(sz) { } bool operator==(VarIndexState const& other) const { if (indices.size() != other.indices.size()) { return false; } for (int i = 0; i < (int)indices.size(); i++) { if (indices[i] != other.indices[i]) { return false; } } return true; } std::string to_string() const { std::string s = "["; for (int i = 0; i < (int)indices.size(); i++) { if (i > 0) s += " "; s += std::to_string(indices[i]); } return s + "]"; } }; template <class T> inline void hash_combine(std::size_t& seed, T const& v) { seed ^= std::hash<T>()(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2); } template <> struct std::hash<VarIndexState> { size_t operator()(const VarIndexState& s) const { size_t seed = 0; for (int i = 0; i < (int)s.indices.size(); i++) { hash_combine(seed, s.indices[i]); } return seed; } }; struct VarIndexTransitionPrecondition { // Largest number which needs to have been reached before going in. // (e.g., if the term has 1 2 5, then the index stored here would be 4.) // (e.g., if the term has 3 2, then the index stored here would be 2.) // (e.g., if the term has 2 3, then the index stored here would be 1.) std::vector<int> indices; std::string to_string() const { std::string s = "["; for (int i = 0; i < (int)indices.size(); i++) { if (i > 0) s += " "; s += std::to_string(indices[i]); } return s + "]"; } }; struct VarIndexTransitionResult { // Minimum index reached (0 for none at all, 1 for having reached // the first one, etc.) std::vector<int> indices; std::string to_string() const { std::string s = "["; for (int i = 0; i < (int)indices.size(); i++) { if (i > 0) s += " "; s += std::to_string(indices[i]); } return s + "]"; } }; inline void var_index_do_transition( VarIndexState const& state, VarIndexTransitionResult const& trans, VarIndexState& result) { for (int i = 0; i < (int)state.indices.size(); i++) { result.indices[i] = state.indices[i] > trans.indices[i] ? state.indices[i] : trans.indices[i]; } } inline bool var_index_is_valid_transition( VarIndexState const& state, VarIndexTransitionPrecondition const& pre) { for (int i = 0; i < (int)state.indices.size(); i++) { if (pre.indices[i] > state.indices[i]) { return false; } } return true; } struct VarIndexTransition { VarIndexTransitionPrecondition pre; VarIndexTransitionResult res; }; std::vector<VarIndexTransition> get_var_index_transitions( std::shared_ptr<Module>, value templ, std::vector<value> const& values); VarIndexState get_var_index_init_state( std::shared_ptr<Module>, value templ); #endif <file_sep>/src/bmc.h #ifndef BMC_H #define BMC_H #include "contexts.h" #include "logic.h" #include "model.h" // Bounded model checking for exactly k steps. class FixedBMCContext { std::shared_ptr<Module> module; std::shared_ptr<BackgroundContext> ctx; std::shared_ptr<ModelEmbedding> e1; std::shared_ptr<ModelEmbedding> e2; bool from_safety; int k; public: FixedBMCContext(smt::context& ctx, std::shared_ptr<Module> module, int k, bool from_safety); bool is_exactly_k_invariant(value v); std::shared_ptr<Model> get_k_invariance_violation(value v, bool get_minimal); std::shared_ptr<Model> get_k_invariance_violation_maybe(value v, bool get_minimal); bool is_reachable(std::shared_ptr<Model> model); bool is_reachable_returning_false_if_unknown(std::shared_ptr<Model> model); }; // Bounded model checking for <= k steps. class BMCContext { std::vector<std::shared_ptr<FixedBMCContext>> bmcs; public: BMCContext(smt::context& ctx, std::shared_ptr<Module> module, int k, bool from_safety = false); bool is_k_invariant(value v); std::shared_ptr<Model> get_k_invariance_violation(value v, bool get_minimal = false); std::shared_ptr<Model> get_k_invariance_violation_maybe(value v, bool get_minimal = false); bool is_reachable(std::shared_ptr<Model> model); bool is_reachable_returning_false_if_unknown(std::shared_ptr<Model> model); bool is_reachable_exact_steps(std::shared_ptr<Model> model); bool is_reachable_exact_steps_returning_false_if_unknown(std::shared_ptr<Model> model); }; #endif <file_sep>/src/filter.h #ifndef FILTER_H #define FILTER_H #include "logic.h" std::vector<value> filter_redundant_formulas( std::shared_ptr<Module>, std::vector<value> const&); std::vector<value> filter_unique_formulas( std::vector<value> const&); #endif <file_sep>/scripts/predicate_parsing.py def parse_comma_sep(tokens, i): e1, i = parse1(tokens, i) es = [e1] while True: if i < len(tokens) and tokens[i] == ',': enext, i = parse1(tokens, i+1) es.append(enext) else: return es, i def parse1(tokens, i): e1, i = parse2(tokens, i) if i < len(tokens) and tokens[i] == '->': e2, i = parse2(tokens, i+1) return ['implies', e1, e2], i else: return e1, i def parse2(tokens, i): e1, i = parse3(tokens, i) do_or = (i < len(tokens) and tokens[i] == '|') do_and = (i < len(tokens) and tokens[i] == '&') if (not do_or) and (not do_and): return e1, i the_chr = '|' if do_or else '&' es = [e1] while True: if i < len(tokens) and tokens[i] == the_chr: enext, i = parse3(tokens, i+1) es.append(enext) else: return [("or" if do_or else "and"), es], i def parse3(tokens, i): e1, i = parse_atom(tokens, i) if i < len(tokens) and (tokens[i] == '=' or tokens[i] == '~='): tok = tokens[i] e2, i = parse_atom(tokens, i+1) if tok == '=': return ['eq', e1, e2], i else: return ['not', ['eq', e1, e2]], i else: return e1, i def is_var(c): return 'A' <= c[0] <= 'Z' def is_const(c): return 'a' <= c[0] <= 'z' def is_id(c): return is_var(c) or is_const(c) def parse_atom(tokens, i): assert i < len(tokens) if tokens[i] == '(': e, i = parse1(tokens, i+1) if not (i < len(tokens) and tokens[i] == ')'): print(tokens, i) assert False return e, i+1 elif tokens[i] == '~': e, i = parse_atom(tokens, i+1) return ["not", e], i elif tokens[i] in ('forall', 'exists'): qtype = tokens[i] decls = [] i += 1 while True: assert is_id(tokens[i]) id_name = tokens[i] i += 2 if tokens[i-1] == ':': sort_name = tokens[i] i += 2 assert tokens[i-1] == ',' or tokens[i-1] == '.' decls.append(['var', id_name, ["uninterpretedSort", sort_name]]) else: decls.append(['var', id_name]) assert tokens[i-1] == ',' or tokens[i-1] == '.' if tokens[i-1] == '.': break ebody, i = parse1(tokens, i) return [qtype, decls, ebody], i elif is_id(tokens[i]): c = tokens[i] if tokens[i] == 'true': return ["and", []], i+1 elif tokens[i] == 'false': return ["or", []], i+1 elif is_var(c): return ["var", c], i+1 elif is_const(c): if i+1 < len(tokens) and tokens[i+1] == '(': es, i = parse_comma_sep(tokens, i + 2) assert tokens[i] == ')' return ["apply", ["const", c], es], i+1 else: return ["const", c], i+1 else: assert False def tokenize_cont(c): tokens = [] i = 0 while i < len(c): if ('a' <= c[i] <= 'z') or ('A' <= c[i] <= 'Z'): j = i + 1 while j < len(c) and (('a' <= c[j] <= 'z') or ('A' <= c[j] <= 'Z') or ('0' <= c[j] <= '9') or c[j] == '_'): j += 1 tokens.append(c[i:j]) i = j elif i+1 < len(c) and c[i] == '-' and c[i+1] == '>': tokens.append('->') i += 2 elif i+1 < len(c) and c[i] == '~' and c[i+1] == '=': tokens.append('~=') i += 2 else: tokens.append(c[i]) i += 1 return tokens def tokenize(s): s = s.split() tokens = [] for c in s: ts = tokenize_cont(c) tokens.extend(ts) return tokens def parse_string(module, s): tokens = tokenize(s) e, i = parse1(tokens, 0) assert i == len(tokens) e = type_infer(module, e) return e class Scope(object): def __init__(self, consts, vars): self.vars = vars self.consts = consts def add_var(self, new_var, new_type): assert new_var not in self.vars self.vars[new_var] = new_type def remove_var(self, var): if var in self.vars: del self.vars[var] def get_arg(self, c, i): funcsort = self.consts[c] assert funcsort[0] == "functionSort" return funcsort[1][i] def get_range(self, c): funcsort = self.consts[c[1]] assert funcsort[0] == "functionSort" return funcsort[2] def get_vars(v, decls): if v[0] in ('forall', 'exists'): return get_vars(v[2], decls + [decl[1] for decl in v[1]]) elif v[0] in ('and', 'or'): t = set() for arg in v[1]: t = t.union(get_vars(arg, decls)) return t elif v[0] == 'not': return get_vars(v[1], decls) elif v[0] == 'implies': t = set() t = t.union(get_vars(v[1], decls)) t = t.union(get_vars(v[2], decls)) return t elif v[0] == 'apply': t = set() for arg in v[2]: t = t.union(get_vars(arg, decls)) return t elif v[0] == 'const': return set() elif v[0] == 'var': if v[1] not in decls: return {v[1]} else: return set() elif v[0] == 'eq': t = set() t = t.union(get_vars(v[1], decls)) t = t.union(get_vars(v[2], decls)) return t else: assert False def has_any_uninferred(v): if v[0] in ('forall', 'exists'): r = has_any_uninferred(v[2]) or any(len(l) == 2 for l in v[1]) elif v[0] in ('and', 'or'): r = any(has_any_uninferred(a) for a in v[1]) elif v[0] == 'not': r = has_any_uninferred(v[1]) elif v[0] == 'implies': r = has_any_uninferred(v[1]) or has_any_uninferred(v[2]) elif v[0] == 'apply': r = has_any_uninferred(v[1]) or any(has_any_uninferred(a) for a in v[2]) elif v[0] == 'const': r = len(v) == 2 elif v[0] == 'var': r = len(v) == 2 elif v[0] == 'eq': r = has_any_uninferred(v[1]) or has_any_uninferred(v[2]) else: assert False return r def do_infer(v, scope): if v[0] in ('forall', 'exists'): for decl in v[1]: if len(decl) == 3: scope.add_var(decl[1], decl[2]) body = do_infer(v[2], scope) new_decls = [] for decl in v[1]: if len(decl) == 3: new_decls.append(decl) elif decl[1] in scope.vars: new_decls.append(["var", decl[1], scope.vars[decl[1]]]) else: new_decls.append(decl) scope.remove_var(decl[1]) return [v[0], new_decls, body] elif v[0] in ('and', 'or'): return [v[0], [do_infer(arg, scope) for arg in v[1]]] elif v[0] == 'not': return ['not', do_infer(v[1], scope)] elif v[0] == 'implies': return ['implies', do_infer(v[1], scope), do_infer(v[2], scope)] elif v[0] == 'apply': c = do_infer(v[1], scope) args = [do_infer(arg, scope) for arg in v[2]] for i in range(len(args)): if args[i][0] == 'var' and len(args[i]) == 2: args[i] = ['var', args[i][1], scope.get_arg(c[1], i)] return ["apply", c, args] elif v[0] == 'const': if len(v) == 3: return v else: return ["const", v[1], scope.consts[v[1]]] elif v[0] == 'var': if len(v) == 3: if v[1] in scope.vars: if repr(scope.vars[v[1]]) != repr(v[2]): print(v, scope.vars[v[1]], v[2]) assert False else: scope.vars[v[1]] = v[2] return v elif v[1] in scope.vars: return ["var", v[1], scope.vars[v[1]]] else: return v elif v[0] == 'eq': a = do_infer(v[1], scope) b = do_infer(v[2], scope) a = maybe_infer(a, b, scope) b = maybe_infer(b, a, scope) return ['eq', a, b] else: assert False def const_types_of_module(module): d = {} for func in module["functions"]: d[func[1]] = func[2] return d def try_infer_sort(v, scope): if v[0] == 'var' and len(v) == 3: return v[2] elif v[0] == 'const' and len(v) == 3: return v[2] elif v[0] == 'apply': return scope.get_range(v[1]) else: return None def maybe_infer(a, b, scope): if a[0] == 'var' and len(a) == 2: so = try_infer_sort(b, scope) if so != None: return [a[0], a[1], so] else: return a else: return a def type_infer(module, e): vs = get_vars(e, []) if len(vs) > 0: e = ['forall', [["var", x] for x in vs], e] const_types = const_types_of_module(module) while True: if not has_any_uninferred(e): return e e1 = do_infer(e, Scope(const_types, {})) if repr(e) == repr(e1): print(e) print(e1) assert False e = e1 def parse_inv_contents(invs_contents, module): lines = invs_contents.split('\n') lines = [l.split('#')[0] for l in lines] al = '\n'.join(lines) cs = al.split('conjecture') assert cs[0].strip() == '' cs = cs[1:] return [parse_string(module, c) for c in cs] def parse_inv_contents_I4(invs_contents, module): lines = invs_contents.split('\n') nums = [] invs = [] for line in lines: if line.startswith("invariant "): l = line.split() num = l[1] inv = ' '.join(l[2:]) nums.append(num) invs.append(inv) assert nums[0] == '[1000000]' res = [] for c in invs: try: new_inv = parse_string(module, c) res.append(new_inv) except Exception as e: return c return res <file_sep>/src/alt_depth2_synth_enumerator.h #ifndef ALT_DEPTH2_SYNTH_ENUMERATOR_H #define ALT_DEPTH2_SYNTH_ENUMERATOR_H #include "synth_enumerator.h" #include "bitset_eval_result.h" #include "var_lex_graph.h" #include "subsequence_trie.h" #include "tree_shapes.h" #include "template_desc.h" class AltDepth2CandidateSolver : public CandidateSolver { public: AltDepth2CandidateSolver( std::shared_ptr<Module>, TemplateSpace const& tspce); value getNext(); void addCounterexample(Counterexample cex); void addExistingInvariant(value inv); long long getProgress() { return progress; } long long getPreSymmCount(); long long getSpaceSize() { assert(false); } //private: std::shared_ptr<Module> module; int total_arity; long long progress; TemplateSpace tspace; TopAlternatingQuantifierDesc taqd; std::vector<value> pieces; std::vector<TreeShape> tree_shapes; TemplateSubSlice tss; std::vector<int> slice_index_map; TransitionSystem sub_ts; int target_state; int tree_shape_idx; std::vector<int> cur_indices_sub; std::vector<int> cur_indices; std::vector<int> var_index_states; int start_from; int done_cutoff; bool finish_at_cutoff; bool done; std::vector<Counterexample> cexes; std::vector<std::vector<std::pair<BitsetEvalResult, BitsetEvalResult>>> cex_results; std::vector<std::pair<AlternationBitsetEvaluator, AlternationBitsetEvaluator>> abes; TransitionSystem ts; void increment(); //void skipAhead(int upTo); void dump_cur_indices(); value get_current_value(); value get_clause(int); void setup_abe1(AlternationBitsetEvaluator& abe, std::vector<std::pair<BitsetEvalResult, BitsetEvalResult>> const& cex_result, std::vector<int> const& cur_indices); void setup_abe2(AlternationBitsetEvaluator& abe, std::vector<std::pair<BitsetEvalResult, BitsetEvalResult>> const& cex_result, std::vector<int> const& cur_indices); void setSubSlice(TemplateSubSlice const&); std::vector<uint64_t> evaluator_buf; }; #endif <file_sep>/src/quantifier_permutations.h #ifndef QUANTIFIER_PERMUTATIONS_H #define QUANTIFIER_PERMUTATIONS_H #include "logic.h" #include "top_quantifier_desc.h" std::vector<std::vector<unsigned int>> get_quantifier_permutations( TopQuantifierDesc const& tqd, std::vector<unsigned int> const& ovs); std::vector<std::vector<std::vector<unsigned int>>> get_multiqi_quantifier_permutations( TopQuantifierDesc const& tqd, std::vector<std::vector<unsigned int>> const& ovs); #endif <file_sep>/src/logic.cpp #include "logic.h" #include <cassert> #include <iostream> #include <algorithm> #include "lib/json11/json11.hpp" #include "benchmarking.h" using namespace std; using namespace json11; shared_ptr<Module> json2module(Json j); vector<string> json2string_array(Json j); vector<shared_ptr<Value>> json2value_array(Json j); vector<shared_ptr<Action>> json2action_array(Json j); pair<vector<shared_ptr<Action>>, vector<string>> json2action_array_from_map(Json j); vector<shared_ptr<Sort>> json2sort_array(Json j); vector<VarDecl> json2decl_array(Json j); shared_ptr<Value> json2value(Json j); shared_ptr<Sort> json2sort(Json j); shared_ptr<Action> json2action(Json j); shared_ptr<Module> parse_module(string const& src) { string err; Json j = Json::parse(src, err); return json2module(j); } vector<value> parse_value_array(string const& src) { string err; Json j = Json::parse(src, err); return json2value_array(j); } shared_ptr<Module> json2module(Json j) { assert(j.is_object()); auto p = json2action_array_from_map(j["actions"]); return shared_ptr<Module>(new Module( json2string_array(j["sorts"]), json2decl_array(j["functions"]), json2value_array(j["axioms"]), json2value_array(j["inits"]), json2value_array(j["conjectures"]), json2value_array(j["templates"]), p.first, p.second)); } vector<string> json2string_array(Json j) { assert(j.is_array()); vector<string> res; for (Json elem : j.array_items()) { assert(elem.is_string()); res.push_back(elem.string_value()); } return res; } vector<shared_ptr<Value>> json2value_array(Json j) { assert(j.is_array()); vector<shared_ptr<Value>> res; for (Json elem : j.array_items()) { res.push_back(json2value(elem)); } return res; } vector<shared_ptr<Action>> json2action_array(Json j) { assert(j.is_array()); vector<shared_ptr<Action>> res; for (Json elem : j.array_items()) { res.push_back(json2action(elem)); } return res; } pair<vector<shared_ptr<Action>>, vector<string>> json2action_array_from_map(Json j) { assert(j.is_object()); vector<shared_ptr<Action>> res; vector<string> names; for (auto p : j.object_items()) { res.push_back(json2action(p.second)); names.push_back(p.first); } return make_pair(res, names); } vector<shared_ptr<Sort>> json2sort_array(Json j) { assert(j.is_array()); vector<shared_ptr<Sort>> res; for (Json elem : j.array_items()) { res.push_back(json2sort(elem)); } return res; } vector<VarDecl> json2decl_array(Json j) { assert(j.is_array()); vector<VarDecl> res; for (Json elem : j.array_items()) { assert(elem.is_array()); assert(elem.array_items().size() == 3); assert(elem[0] == "const" || elem[0] == "var"); assert(elem[1].is_string()); res.push_back(VarDecl(string_to_iden(elem[1].string_value()), json2sort(elem[2]))); } return res; } set<iden> add_names(set<iden> names, vector<VarDecl> const& decls) { for (VarDecl const& decl : decls) { // sanity check if (names.find(decl.name) != names.end()) { cout << decl.name << endl; assert (false && "duplicate variable name in input"); } names.insert(decl.name); } return names; } shared_ptr<Value> json2value(Json j, set<iden> const& names) { assert(j.is_array()); assert(j.array_items().size() >= 1); assert(j[0].is_string()); string type = j[0].string_value(); if (type == "forall") { assert (j.array_items().size() == 3); vector<VarDecl> decls = json2decl_array(j[1]); set<iden> new_names = add_names(names, decls); return shared_ptr<Value>(new Forall(decls, json2value(j[2], new_names))); } if (type == "nearlyforall") { assert (j.array_items().size() == 3); vector<VarDecl> decls = json2decl_array(j[1]); set<iden> new_names = add_names(names, decls); return shared_ptr<Value>(new NearlyForall(decls, json2value(j[2], new_names))); } else if (type == "exists") { assert (j.array_items().size() == 3); vector<VarDecl> decls = json2decl_array(j[1]); set<iden> new_names = add_names(names, decls); return shared_ptr<Value>(new Exists(decls, json2value(j[2], new_names))); } else if (type == "var") { assert (j.array_items().size() == 3); assert (j[1].is_string()); return shared_ptr<Value>(new Var(string_to_iden(j[1].string_value()), json2sort(j[2]))); } else if (type == "const") { assert (j.array_items().size() == 3); assert (j[1].is_string()); return shared_ptr<Value>(new Const(string_to_iden(j[1].string_value()), json2sort(j[2]))); } else if (type == "implies") { assert (j.array_items().size() == 3); return shared_ptr<Value>(new Implies(json2value(j[1], names), json2value(j[2], names))); } else if (type == "eq") { assert (j.array_items().size() == 3); return shared_ptr<Value>(new Eq(json2value(j[1], names), json2value(j[2], names))); } else if (type == "not") { assert (j.array_items().size() == 2); return shared_ptr<Value>(new Not(json2value(j[1], names))); } else if (type == "apply") { assert (j.array_items().size() == 3); return shared_ptr<Value>(new Apply(json2value(j[1], names), json2value_array(j[2]))); } else if (type == "and") { assert (j.array_items().size() == 2); return shared_ptr<Value>(new And(json2value_array(j[1]))); } else if (type == "or") { assert (j.array_items().size() == 2); return shared_ptr<Value>(new Or(json2value_array(j[1]))); } else if (type == "ite") { assert (j.array_items().size() == 4); return shared_ptr<Value>(new IfThenElse( json2value(j[1]), json2value(j[2]), json2value(j[3]) )); } else if (type == "__wild") { assert (j.array_items().size() == 1); return shared_ptr<Value>(new TemplateHole()); } else { printf("value type: %s\n", type.c_str()); assert(false && "unrecognized Value type"); } } shared_ptr<Value> json2value(Json j) { return json2value(j, {}); } shared_ptr<Value> Value::from_json(Json j) { return json2value(j); } shared_ptr<Sort> json2sort(Json j) { assert(j.is_array()); assert(j.array_items().size() >= 1); assert(j[0].is_string()); string type = j[0].string_value(); if (type == "booleanSort") { return shared_ptr<Sort>(new BooleanSort()); } else if (type == "uninterpretedSort") { assert (j.array_items().size() == 2); return shared_ptr<Sort>(new UninterpretedSort(j[1].string_value())); } else if (type == "functionSort") { return shared_ptr<FunctionSort>( new FunctionSort(json2sort_array(j[1]), json2sort(j[2]))); } else { assert(false && "unrecognized Sort type"); } } shared_ptr<Action> json2action(Json j) { assert(j.is_array()); assert(j.array_items().size() >= 1); assert(j[0].is_string()); string type = j[0].string_value(); if (type == "localAction") { assert(j.array_items().size() == 3); return shared_ptr<Action>(new LocalAction(json2decl_array(j[1]), json2action(j[2]))); } else if (type == "relation") { assert(j.array_items().size() == 3); return shared_ptr<Action>(new RelationAction( json2string_array(j[1]), json2value(j[2]))); } else if (type == "sequence") { assert(j.array_items().size() == 2); return shared_ptr<Action>(new SequenceAction(json2action_array(j[1]))); } else if (type == "choice") { assert(j.array_items().size() == 2); return shared_ptr<Action>(new ChoiceAction(json2action_array(j[1]))); } else if (type == "assume") { assert(j.array_items().size() == 2); return shared_ptr<Action>(new Assume(json2value(j[1]))); } else if (type == "assign") { assert(j.array_items().size() == 3); return shared_ptr<Action>(new Assign(json2value(j[1]), json2value(j[2]))); } else if (type == "havoc") { assert(j.array_items().size() == 2); return shared_ptr<Action>(new Havoc(json2value(j[1]))); } else if (type == "if") { assert(j.array_items().size() == 3); return shared_ptr<Action>(new If(json2value(j[1]), json2action(j[2]))); } else if (type == "ifelse") { assert(j.array_items().size() == 4); return shared_ptr<Action>(new IfElse( json2value(j[1]), json2action(j[2]), json2action(j[3]))); } else { assert(false && "unrecognized Action type"); } } vector<Json> sort_array_2_json(vector<lsort> const& sorts) { vector<Json> res; for (lsort s : sorts) { res.push_back(s->to_json()); } return res; } vector<Json> value_array_2_json(vector<value> const& values) { vector<Json> res; for (value v : values) { res.push_back(v->to_json()); } return res; } vector<Json> decl_array_2_json(vector<VarDecl> const& decls) { vector<Json> res; for (VarDecl const& decl : decls) { res.push_back(Json({ Json("var"), Json(iden_to_string(decl.name)), decl.sort->to_json() })); } return res; } Json BooleanSort::to_json() const { return Json(vector<Json>{Json("booleanSort")}); } Json UninterpretedSort::to_json() const { return Json(vector<Json>{Json("uninterpretedSort"), Json(name)}); } Json FunctionSort::to_json() const { return Json(vector<Json>{Json("functionSort"), sort_array_2_json(domain), range->to_json()}); } Json Forall::to_json() const { return Json(vector<Json>{Json("forall"), decl_array_2_json(decls), body->to_json()}); } Json NearlyForall::to_json() const { return Json(vector<Json>{Json("nearlyforall"), decl_array_2_json(decls), body->to_json()}); } Json Exists::to_json() const { return Json(vector<Json>{Json("exists"), decl_array_2_json(decls), body->to_json()}); } Json Var::to_json() const { return Json(vector<Json>{Json("var"), Json(iden_to_string(name)), sort->to_json()}); } Json Const::to_json() const { return Json(vector<Json>{Json("const"), Json(iden_to_string(name)), sort->to_json()}); } Json Implies::to_json() const { return Json(vector<Json>{Json("implies"), left->to_json(), right->to_json()}); } Json IfThenElse::to_json() const { return Json(vector<Json>{Json("ite"), cond->to_json(), then_value->to_json(), else_value->to_json()}); } Json Eq::to_json() const { return Json(vector<Json>{Json("eq"), left->to_json(), right->to_json()}); } Json Not::to_json() const { return Json(vector<Json>{Json("not"), val->to_json()}); } Json Apply::to_json() const { return Json(vector<Json>{Json("apply"), func->to_json(), value_array_2_json(args)}); } Json And::to_json() const { return Json(vector<Json>{Json("and"), value_array_2_json(args)}); } Json Or::to_json() const { return Json(vector<Json>{Json("or"), value_array_2_json(args)}); } Json TemplateHole::to_json() const { return Json(vector<Json>{Json("__wild")}); } FormulaDump parse_formula_dump(std::string const& src) { string err; Json j = Json::parse(src, err); assert(j.is_object()); Json succ = j["success"]; assert(succ.is_bool()); FormulaDump fd; fd.success = succ.bool_value(); fd.base_invs = json2value_array(j["base_invs"]); fd.new_invs = json2value_array(j["new_invs"]); fd.all_invs = json2value_array(j["all_invs"]); fd.conjectures = json2value_array(j["conjectures"]); return fd; } std::string marshall_formula_dump(FormulaDump const& fd) { map<string, Json> m; m["success"] = Json(fd.success); m["base_invs"] = value_array_2_json(fd.base_invs); m["new_invs"] = value_array_2_json(fd.new_invs); m["all_invs"] = value_array_2_json(fd.all_invs); m["conjectures"] = value_array_2_json(fd.conjectures); Json j(m); return j.dump(); } string BooleanSort::to_string() const { return "bool"; } string UninterpretedSort::to_string() const { return name; } string FunctionSort::to_string() const { string res = "("; for (int i = 0; i < (int)domain.size(); i++) { if (i != 0) res += ", "; res += domain[i]->to_string(); } return res + " -> " + range->to_string(); } string Forall::to_string() const { string res = "forall "; for (int i = 0; i < (int)decls.size(); i++) { if (i > 0) { res += ", "; } res += iden_to_string(decls[i].name) + ":" + decls[i].sort->to_string(); } res += " . (" + body->to_string() + ")"; return res; } string NearlyForall::to_string() const { string res = "nearlyforall "; for (int i = 0; i < (int)decls.size(); i++) { if (i > 0) { res += ", "; } res += iden_to_string(decls[i].name) + ":" + decls[i].sort->to_string(); } res += " . (" + body->to_string() + ")"; return res; } string Exists::to_string() const { string res = "exists "; for (int i = 0; i < (int)decls.size(); i++) { if (i > 0) { res += ", "; } res += iden_to_string(decls[i].name) + ":" + decls[i].sort->to_string(); } res += " . (" + body->to_string() + ")"; return res; } string Var::to_string() const { return iden_to_string(name); } string Const::to_string() const { return iden_to_string(name); } string Eq::to_string() const { return "(" + left->to_string() + ") = (" + right->to_string() + ")"; } string Not::to_string() const { if (Eq* e = dynamic_cast<Eq*>(val.get())) { return "(" + e->left->to_string() + ") ~= (" + e->right->to_string() + ")"; } else { return "~(" + val->to_string() + ")"; } } string Implies::to_string() const { return "(" + left->to_string() + ") -> (" + right->to_string() + ")"; } string And::to_string() const { if (args.size() == 0) return "true"; string res = ""; if (args.size() <= 1) res += "AND["; for (int i = 0; i < (int)args.size(); i++) { if (i > 0) { res += " & "; } res += "(" + args[i]->to_string() + ")"; } if (args.size() <= 1) res += "]"; return res; } string Or::to_string() const { if (args.size() == 0) return "false"; string res = ""; if (args.size() <= 1) res += "OR["; for (int i = 0; i < (int)args.size(); i++) { if (i > 0) { res += " | "; } res += "(" + args[i]->to_string() + ")"; } if (args.size() <= 1) res += "]"; return res; } string IfThenElse::to_string() const { return cond->to_string() + " ? " + then_value->to_string() + " : " + else_value->to_string(); } string Apply::to_string() const { string res = func->to_string() + "("; for (int i = 0; i < (int)args.size(); i++) { if (i > 0) { res += ", "; } res += args[i]->to_string(); } return res + ")"; } string TemplateHole::to_string() const { return "WILD"; } lsort bsort = s_bool(); lsort Forall::get_sort() const { return bsort; } lsort NearlyForall::get_sort() const { return bsort; } lsort Exists::get_sort() const { return bsort; } lsort Var::get_sort() const { return sort; } lsort Const::get_sort() const { return sort; } lsort IfThenElse::get_sort() const { return then_value->get_sort(); } lsort Eq::get_sort() const { return bsort; } lsort Not::get_sort() const { return bsort; } lsort Implies::get_sort() const { return bsort; } lsort Apply::get_sort() const { Const* f = dynamic_cast<Const*>(func.get()); assert(f != NULL); return f->sort->get_range_as_function(); } lsort And::get_sort() const { return bsort; } lsort Or::get_sort() const { return bsort; } lsort TemplateHole::get_sort() const { assert(false); } value Forall::subst(iden x, value e) const { return v_forall(decls, body->subst(x, e)); } value NearlyForall::subst(iden x, value e) const { return v_nearlyforall(decls, body->subst(x, e)); } value Exists::subst(iden x, value e) const { return v_exists(decls, body->subst(x, e)); } value Var::subst(iden x, value e) const { if (x == name) { return e; } else { return v_var(name, sort); } } value Const::subst(iden x, value e) const { return v_const(name, sort); } value Eq::subst(iden x, value e) const { return v_eq(left->subst(x, e), right->subst(x, e)); } value Not::subst(iden x, value e) const { return v_not(this->val->subst(x, e)); } value Implies::subst(iden x, value e) const { return v_implies(left->subst(x, e), right->subst(x, e)); } value IfThenElse::subst(iden x, value e) const { return v_if_then_else(cond->subst(x, e), then_value->subst(x, e), else_value->subst(x, e)); } value Apply::subst(iden x, value e) const { vector<value> new_args; for (value const& arg : args) { new_args.push_back(arg->subst(x, e)); } return v_apply(func->subst(x, e), move(new_args)); } value And::subst(iden x, value e) const { vector<value> new_args; for (value const& arg : args) { new_args.push_back(arg->subst(x, e)); } return v_and(move(new_args)); } value Or::subst(iden x, value e) const { vector<value> new_args; for (value const& arg : args) { new_args.push_back(arg->subst(x, e)); } return v_or(move(new_args)); } value TemplateHole::subst(iden x, value e) const { return v_template_hole(); } value Forall::subst_fun(iden func, vector<VarDecl> const& d, value e) const { return v_forall(decls, body->subst_fun(func, d, e)); } value NearlyForall::subst_fun(iden func, vector<VarDecl> const& d, value e) const { return v_nearlyforall(decls, body->subst_fun(func, d, e)); } value Exists::subst_fun(iden func, vector<VarDecl> const& d, value e) const { return v_exists(decls, body->subst_fun(func, d, e)); } value Var::subst_fun(iden func, vector<VarDecl> const& d, value e) const { return v_var(name, sort); } value Const::subst_fun(iden func, vector<VarDecl> const& d, value e) const { assert(name != func && "not sure if this will happen"); return v_const(name, sort); } value Eq::subst_fun(iden func, vector<VarDecl> const& d, value e) const { return v_eq( left->subst_fun(func, d, e), right->subst_fun(func, d, e)); } value Not::subst_fun(iden func, vector<VarDecl> const& d, value e) const { return v_not( val->subst_fun(func, d, e)); } value Implies::subst_fun(iden func, vector<VarDecl> const& d, value e) const { return v_implies( left->subst_fun(func, d, e), right->subst_fun(func, d, e)); } value Apply::subst_fun(iden f, vector<VarDecl> const& d, value e) const { vector<value> new_args; for (value v : args) { new_args.push_back(v->subst_fun(f, d, e)); } Const* c = dynamic_cast<Const*>(func.get()); assert (c != NULL); if (c->name == f) { value res = e; assert (d.size() == args.size()); for (int i = 0; i < (int)d.size(); i++) { res = res->subst(d[i].name, args[i]); } return res; } else { return v_apply(func, new_args); } } value And::subst_fun(iden func, vector<VarDecl> const& d, value e) const { vector<value> new_args; for (value v : args) { new_args.push_back(v->subst_fun(func, d, e)); } return v_and(new_args); } value Or::subst_fun(iden func, vector<VarDecl> const& d, value e) const { vector<value> new_args; for (value v : args) { new_args.push_back(v->subst_fun(func, d, e)); } return v_or(new_args); } value IfThenElse::subst_fun(iden func, vector<VarDecl> const& d, value e) const { return v_if_then_else( cond->subst_fun(func, d, e), then_value->subst_fun(func, d, e), else_value->subst_fun(func, d, e)); } value TemplateHole::subst_fun(iden func, vector<VarDecl> const& d, value e) const { assert(false); } value Forall::negate() const { return v_exists(decls, body->negate()); } value NearlyForall::negate() const { assert(false && "NearlyForall::negate() not implemented"); } value Exists::negate() const { return v_forall(decls, body->negate()); } value Var::negate() const { return v_not(v_var(name, sort)); } value Const::negate() const { return v_not(v_const(name, sort)); } value Eq::negate() const { return v_not(v_eq(left, right)); } value Not::negate() const { return val; } value Implies::negate() const { return v_and({left, right->negate()}); } value IfThenElse::negate() const { return v_if_then_else(cond, then_value->negate(), else_value->negate()); } value Apply::negate() const { return v_not(v_apply(func, args)); } value And::negate() const { vector<value> new_args; for (value const& arg : args) { new_args.push_back(arg->negate()); } return v_or(move(new_args)); } value Or::negate() const { vector<value> new_args; for (value const& arg : args) { new_args.push_back(arg->negate()); } return v_and(move(new_args)); } value TemplateHole::negate() const { return v_not(v_template_hole()); } bool Forall::uses_var(iden name) const { return body->uses_var(name); } bool Exists::uses_var(iden name) const { return body->uses_var(name); } bool NearlyForall::uses_var(iden name) const { return body->uses_var(name); } bool Var::uses_var(iden name) const { return this->name == name; } bool Const::uses_var(iden name) const { return false; } bool Not::uses_var(iden name) const { return val->uses_var(name); } bool Eq::uses_var(iden name) const { return left->uses_var(name) || right->uses_var(name); } bool Implies::uses_var(iden name) const { return left->uses_var(name) || right->uses_var(name); } bool IfThenElse::uses_var(iden name) const { return cond->uses_var(name) || then_value->uses_var(name) || else_value->uses_var(name); } bool And::uses_var(iden name) const { for (value arg : args) { if (arg->uses_var(name)) return true; } return false; } bool Or::uses_var(iden name) const { for (value arg : args) { if (arg->uses_var(name)) return true; } return false; } bool Apply::uses_var(iden name) const { if (func->uses_var(name)) return true; for (value arg : args) { if (arg->uses_var(name)) return true; } return false; } bool TemplateHole::uses_var(iden name) const { assert(false); } value Forall::simplify() const { return v_forall(decls, body->simplify()); } value NearlyForall::simplify() const { return v_nearlyforall(decls, body->simplify()); } value Exists::simplify() const { return v_exists(decls, body->simplify()); } value Var::simplify() const { return v_var(name, sort); } value Const::simplify() const { return v_const(name, sort); } value Eq::simplify() const { value l = left->simplify(); value r = right->simplify(); if (values_equal(l, r)) { return v_true(); } else { return v_eq(l, r); } } value Not::simplify() const { return val->simplify()->negate(); } value Implies::simplify() const { return v_or({v_not(left), right})->simplify(); } bool is_const_true(value v) { And* a = dynamic_cast<And*>(v.get()); return a != NULL && a->args.size() == 0; } bool is_const_false(value v) { Or* a = dynamic_cast<Or*>(v.get()); return a != NULL && a->args.size() == 0; } template <typename T> void extend(vector<T> & a, vector<T> const& b) { for (T const& t : b) { a.push_back(t); } } vector<value> remove_redundant(vector<value> const& vs) { vector<value> t; for (value v : vs) { bool redun = false; for (value w : t) { if (values_equal(v, w)) { redun = true; break; } } if (!redun) { t.push_back(v); } } return t; } value And::simplify() const { vector<value> a; for (value v : args) { v = v->simplify(); if (And* inner = dynamic_cast<And*>(v.get())) { extend(a, inner->args); } else if (is_const_false(v)) { return v_false(); } else { a.push_back(v); } } a = remove_redundant(a); value res = a.size() == 1 ? a[0] : v_and(a); return res; } value Or::simplify() const { vector<value> a; for (value v : args) { v = v->simplify(); if (Or* inner = dynamic_cast<Or*>(v.get())) { extend(a, inner->args); } else if (is_const_true(v)) { return v_true(); } else { a.push_back(v); } } a = remove_redundant(a); value res = a.size() == 1 ? a[0] : v_or(a); return res; } value IfThenElse::simplify() const { value c = cond->simplify(); value a = then_value->simplify(); value b = else_value->simplify(); if (is_const_true(c)) return a; if (is_const_false(c)) return b; if (is_const_true(a)) { if (is_const_true(b)) { return v_true(); } else if (is_const_false(b)) { return c; } else { return v_or({c, b}); } } else if (is_const_false(a)) { if (is_const_true(b)) { return c->negate(); } else if (is_const_false(b)) { return v_false(); } else { return v_and({c->negate(), b}); } } else { if (is_const_true(b)) { return v_or({c->negate(), a}); } else if (is_const_false(b)) { return v_and({c, a}); } else { return v_if_then_else(c, a, b); } } } value Apply::simplify() const { vector<value> a; for (value v : args) { a.push_back(v->simplify()); } return v_apply(func, a); } value TemplateHole::simplify() const { return v_template_hole(); } uint32_t uid = 0; uint32_t new_var_id() { return (uid++); } value Forall::uniquify_vars(map<iden, iden> const& m) const { map<iden, iden> new_m = m; vector<VarDecl> new_decls; for (VarDecl const& decl : this->decls) { iden new_name = new_var_id(); new_m[decl.name] = new_name; new_decls.push_back(VarDecl(new_name, decl.sort)); } return v_forall(new_decls, body->uniquify_vars(new_m)); } value NearlyForall::uniquify_vars(map<iden, iden> const& m) const { assert(false && "NearlyForall::uniquify_vars not implemented"); } value Exists::uniquify_vars(map<iden, iden> const& m) const { map<iden, iden> new_m = m; vector<VarDecl> new_decls; for (VarDecl const& decl : this->decls) { iden new_name = new_var_id(); new_m[decl.name] = new_name; new_decls.push_back(VarDecl(new_name, decl.sort)); } return v_forall(new_decls, body->uniquify_vars(new_m)); } value Var::uniquify_vars(map<iden, iden> const& m) const { auto iter = m.find(this->name); assert(iter != m.end()); return v_var(iter->second, this->sort); } value Const::uniquify_vars(map<iden, iden> const& m) const { return v_const(name, sort); } value Eq::uniquify_vars(map<iden, iden> const& m) const { return v_eq(left->uniquify_vars(m), right->uniquify_vars(m)); } value Not::uniquify_vars(map<iden, iden> const& m) const { return v_not(this->val->uniquify_vars(m)); } value Implies::uniquify_vars(map<iden, iden> const& m) const { return v_implies(left->uniquify_vars(m), right->uniquify_vars(m)); } value IfThenElse::uniquify_vars(map<iden, iden> const& m) const { return v_if_then_else(cond->uniquify_vars(m), then_value->uniquify_vars(m), else_value->uniquify_vars(m)); } value Apply::uniquify_vars(map<iden, iden> const& m) const { vector<value> new_args; for (value const& arg : args) { new_args.push_back(arg->uniquify_vars(m)); } return v_apply(func->uniquify_vars(m), move(new_args)); } value And::uniquify_vars(map<iden, iden> const& m) const { vector<value> new_args; for (value const& arg : args) { new_args.push_back(arg->uniquify_vars(m)); } return v_and(move(new_args)); } value Or::uniquify_vars(map<iden, iden> const& m) const { vector<value> new_args; for (value const& arg : args) { new_args.push_back(arg->uniquify_vars(m)); } return v_or(move(new_args)); } value TemplateHole::uniquify_vars(map<iden, iden> const& m) const { return v_template_hole(); } void sort_decls(vector<VarDecl>& decls) { sort(decls.begin(), decls.end(), [](VarDecl const& a, VarDecl const& b) { string a_name, b_name; if (dynamic_cast<BooleanSort*>(a.sort.get())) { a_name = ""; } else if (auto v = dynamic_cast<UninterpretedSort*>(a.sort.get())) { a_name = v->name; } if (dynamic_cast<BooleanSort*>(b.sort.get())) { b_name = ""; } else if (auto v = dynamic_cast<UninterpretedSort*>(b.sort.get())) { b_name = v->name; } return a_name < b_name; }); } value Forall::structurally_normalize_() const { value b = this->body->structurally_normalize_(); if (Forall* inner = dynamic_cast<Forall*>(b.get())) { vector<VarDecl> new_decls = this->decls; extend(new_decls, inner->decls); sort_decls(new_decls); return v_forall(new_decls, inner->body); } else { return v_forall(this->decls, b); } } value NearlyForall::structurally_normalize_() const { assert (false && "NearlyForall::structurally_normalize_ not implemented"); } value Exists::structurally_normalize_() const { value b = this->body->structurally_normalize_(); if (Exists* inner = dynamic_cast<Exists*>(b.get())) { vector<VarDecl> new_decls = this->decls; extend(new_decls, inner->decls); sort_decls(new_decls); return v_exists(new_decls, inner->body); } else { return v_exists(this->decls, b); } } value Var::structurally_normalize_() const { return v_var(name, sort); } value Const::structurally_normalize_() const { return v_const(name, sort); } value Eq::structurally_normalize_() const { return v_eq(left->structurally_normalize_(), right->structurally_normalize_()); } value Not::structurally_normalize_() const { return val->structurally_normalize_()->negate(); } value Implies::structurally_normalize_() const { return v_or({v_not(left), right})->structurally_normalize_(); } value Apply::structurally_normalize_() const { vector<value> new_args; for (value const& arg : args) { new_args.push_back(arg->structurally_normalize_()); } return v_apply(func->structurally_normalize_(), move(new_args)); } value structurally_normalize_and_or_or(Value const * the_value) { And const * the_and = dynamic_cast<And const*>(the_value); Or const * the_or = dynamic_cast<Or const*>(the_value); vector<value> args = the_and ? the_and->args : the_or->args; for (int i = 0; i < (int)args.size(); i++) { args[i] = args[i]->structurally_normalize_(); } vector<vector<VarDecl>> forall_decl_lists; vector<vector<VarDecl>> exists_decl_lists; while (true) { vector<VarDecl> forall_decls; vector<VarDecl> exists_decls; vector<value> new_args; bool found = false; for (value arg : args) { if (Forall* forall = dynamic_cast<Forall*>(arg.get())) { extend(forall_decls, forall->decls); arg = forall->body; found = true; } if (Exists* exists = dynamic_cast<Exists*>(arg.get())) { extend(exists_decls, exists->decls); arg = exists->body; found = true; } new_args.push_back(arg); } forall_decl_lists.push_back(move(forall_decls)); exists_decl_lists.push_back(move(exists_decls)); args = move(new_args); if (!found) { break; } } vector<value> new_args; for (value arg : args) { And* sub_and; Or* sub_or; if (the_and && (sub_and = dynamic_cast<And*>(arg.get()))) { extend(new_args, sub_and->args); } else if (the_or && (sub_or = dynamic_cast<Or*>(arg.get()))) { extend(new_args, sub_or->args); } else { new_args.push_back(arg); } } value res = the_and ? v_and(new_args) : v_or(new_args); for (int i = forall_decl_lists.size() - 1; i >= 0; i--) { vector<VarDecl> const& f_decls = forall_decl_lists[i]; vector<VarDecl> const& e_decls = exists_decl_lists[i]; if (e_decls.size() > 0) { res = v_exists(e_decls, res); } if (f_decls.size() > 0) { res = v_exists(f_decls, res); } } return res; } value And::structurally_normalize_() const { return structurally_normalize_and_or_or(this); } value Or::structurally_normalize_() const { return structurally_normalize_and_or_or(this); } value IfThenElse::structurally_normalize_() const { assert(false && "unimplemented"); } value TemplateHole::structurally_normalize_() const { return v_template_hole(); } struct ScopeState { vector<VarDecl> decls; }; bool lt_value(value a_, value b_, ScopeState const& ss_a, ScopeState const& ss_b); int cmp_sort(lsort a, lsort b) { if (dynamic_cast<BooleanSort*>(a.get())) { if (dynamic_cast<BooleanSort*>(b.get())) { return 0; } else if (dynamic_cast<UninterpretedSort*>(b.get())) { return -1; } else { assert(false); } } else if (UninterpretedSort* usort = dynamic_cast<UninterpretedSort*>(a.get())) { if (dynamic_cast<BooleanSort*>(a.get())) { return 1; } else if (UninterpretedSort* usort2 = dynamic_cast<UninterpretedSort*>(b.get())) { string const& a_name = usort->name; string const& b_name = usort2->name; if (a_name < b_name) return -1; if (a_name > b_name) return 1; return 0; } else { assert(false); } } else { assert(false); } } bool eq_sort(lsort a, lsort b) { return cmp_sort(a, b) == 0; } vector<iden> get_front_quantifier_order(value body, vector<VarDecl> const& decls, set<iden> const& vars_used); value forall_exists_normalize_symmetries( vector<VarDecl> const& decls, set<iden> const& vars_used, value body, bool is_forall, int idx, ScopeState const& ss) { if (idx == (int)decls.size()) { return body->normalize_symmetries(ss, vars_used); } // XXX wtf I'm not sure if this is right int idx_end = (int)decls.size(); //int idx_end = idx + 1; //while (idx_end < (int)decls.size() && eq_sort(decls[idx].sort, decls[idx_end].sort)) { // idx_end++; //} vector<iden> front_vars = get_front_quantifier_order(body, decls, vars_used); vector<int> perm; vector<int> perm_mid; vector<int> perm_back; for (iden name : front_vars) { int this_idx = -1; for (int i = idx; i < idx_end; i++) { if (decls[i].name == name) { this_idx = i; break; } } assert(this_idx != -1); perm.push_back(this_idx); } for (int i = idx; i < idx_end; i++) { if (vars_used.find(decls[i].name) == vars_used.end()) { perm_back.push_back(i); } else { bool in_perm = false; for (int j : perm) { if (j == i) { in_perm = true; break; } } if (!in_perm) { perm_mid.push_back(i); } } } // We know what's at the front and back. Iterate over permutations // of the middle segment. int perm_start = perm.size(); int perm_end = perm.size() + perm_mid.size(); extend(perm, perm_mid); extend(perm, perm_back); /* for (int p : perm) { printf("%d ", p); } printf(" : %d -- %d\n\n", perm_start, perm_end); */ value smallest; vector<VarDecl> smallest_decls; ScopeState ss_smallest; do { ScopeState ss_ = ss; for (int i : perm) { ss_.decls.push_back(decls[i]); } value inner = forall_exists_normalize_symmetries(decls, vars_used, body, is_forall, idx_end, ss_); if (smallest == nullptr || lt_value(inner, smallest, ss_, ss_smallest)) { smallest = inner; ss_smallest = move(ss_); smallest_decls.clear(); for (int i : perm) { smallest_decls.push_back(decls[i]); } } } while (next_permutation(perm.begin() + perm_start, perm.begin() + perm_end)); if (idx_end < (int)decls.size()) { if (Forall* inner = dynamic_cast<Forall*>(smallest.get())) { smallest = inner->body; extend(smallest_decls, inner->decls); } else if (Exists* inner = dynamic_cast<Exists*>(smallest.get())) { smallest = inner->body; extend(smallest_decls, inner->decls); } else { assert(false); } } value res = is_forall ? v_forall(smallest_decls, smallest) : v_exists(smallest_decls, smallest); return res; } value Forall::normalize_symmetries(ScopeState const& ss, set<iden> const& vars_used) const { //printf("%s\n", this->to_string().c_str()); return forall_exists_normalize_symmetries(this->decls, vars_used, this->body, true, 0, ss); } value NearlyForall::normalize_symmetries(ScopeState const& ss, set<iden> const& vars_used) const { assert(false && "NearlyForall::normalize_symmetries not implemented"); } value Exists::normalize_symmetries(ScopeState const& ss, set<iden> const& vars_used) const { return forall_exists_normalize_symmetries(this->decls, vars_used, this->body, false, 0, ss); } value Var::normalize_symmetries(ScopeState const& ss, set<iden> const& vars_used) const { return v_var(name, sort); } value Const::normalize_symmetries(ScopeState const& ss, set<iden> const& vars_used) const { return v_const(name, sort); } value IfThenElse::normalize_symmetries(ScopeState const& ss, set<iden> const& vars_used) const { assert(false); } value Eq::normalize_symmetries(ScopeState const& ss, set<iden> const& vars_used) const { value a = left->normalize_symmetries(ss, vars_used); value b = right->normalize_symmetries(ss, vars_used); return lt_value(a, b, ss, ss) ? v_eq(a, b) : v_eq(b, a); } value Not::normalize_symmetries(ScopeState const& ss, set<iden> const& vars_used) const { return v_not(val->normalize_symmetries(ss, vars_used)); } value Implies::normalize_symmetries(ScopeState const& ss, set<iden> const& vars_used) const { assert(false && "implies should have been replaced by |"); } value Apply::normalize_symmetries(ScopeState const& ss, set<iden> const& vars_used) const { vector<value> new_args; for (value arg : args) { new_args.push_back(arg->normalize_symmetries(ss, vars_used)); } return v_apply(func->normalize_symmetries(ss, vars_used), move(new_args)); } void sort_values(ScopeState const& ss, vector<value> & values) { sort(values.begin(), values.end(), [&ss](value const& a, value const& b) { return lt_value(a, b, ss, ss); }); } value And::normalize_symmetries(ScopeState const& ss, set<iden> const& vars_used) const { vector<value> new_args; for (value arg : args) { new_args.push_back(arg->normalize_symmetries(ss, vars_used)); } sort_values(ss, new_args); return v_and(new_args); } value Or::normalize_symmetries(ScopeState const& ss, set<iden> const& vars_used) const { vector<value> new_args; for (value arg : args) { new_args.push_back(arg->normalize_symmetries(ss, vars_used)); } sort_values(ss, new_args); return v_or(new_args); } value TemplateHole::normalize_symmetries(ScopeState const& ss, set<iden> const& vars_used) const { return v_template_hole(); } int cmp_expr(value a_, value b_, ScopeState const& ss_a, ScopeState const& ss_b) { int a_id = a_->kind_id(); int b_id = b_->kind_id(); if (a_id != b_id) return a_id < b_id ? -1 : 1; if (Forall* a = dynamic_cast<Forall*>(a_.get())) { Forall* b = dynamic_cast<Forall*>(b_.get()); assert(b != NULL); if (a->decls.size() < b->decls.size()) return -1; if (a->decls.size() > b->decls.size()) return 1; ScopeState ss_a_new = ss_a; ScopeState ss_b_new = ss_b; for (int i = 0; i < (int)a->decls.size(); i++) { int c = cmp_sort(a->decls[i].sort, b->decls[i].sort); if (c != 0) { return c; } ss_a_new.decls.push_back(a->decls[i]); ss_b_new.decls.push_back(b->decls[i]); } return cmp_expr(a->body, b->body, ss_a_new, ss_b_new); } if (Exists* a = dynamic_cast<Exists*>(a_.get())) { Exists* b = dynamic_cast<Exists*>(b_.get()); assert(b != NULL); if (a->decls.size() < b->decls.size()) return -1; if (a->decls.size() > b->decls.size()) return 1; ScopeState ss_a_new = ss_a; ScopeState ss_b_new = ss_b; for (int i = 0; i < (int)a->decls.size(); i++) { if (int c = cmp_sort(a->decls[i].sort, b->decls[i].sort)) { return c; } ss_a_new.decls.push_back(a->decls[i]); ss_b_new.decls.push_back(b->decls[i]); } return cmp_expr(a->body, b->body, ss_a_new, ss_b_new); } if (Var* a = dynamic_cast<Var*>(a_.get())) { Var* b = dynamic_cast<Var*>(b_.get()); assert(b != NULL); int a_idx = -1, b_idx = -1; for (int i = 0; i < (int)ss_a.decls.size(); i++) { if (ss_a.decls[i].name == a->name) { a_idx = i; break; } } for (int i = 0; i < (int)ss_b.decls.size(); i++) { if (ss_b.decls[i].name == b->name) { b_idx = i; break; } } if (a_idx == -1) { if (b_idx == -1) { // free variables: compare by name string a_name = iden_to_string(a->name); string b_name = iden_to_string(b->name); return a_name < b_name ? -1 : (a_name == b_name ? 0 : 1); } else { // free var comes first return -1; } } else { if (b_idx == -1) { return 1; } else { // compare by index return a_idx < b_idx ? -1 : (a_idx == b_idx ? 0 : 1); } } } if (Const* a = dynamic_cast<Const*>(a_.get())) { Const* b = dynamic_cast<Const*>(b_.get()); assert(b != NULL); string a_name = iden_to_string(a->name); string b_name = iden_to_string(b->name); return a_name < b_name ? -1 : (a_name == b_name ? 0 : 1); } if (Eq* a = dynamic_cast<Eq*>(a_.get())) { Eq* b = dynamic_cast<Eq*>(b_.get()); assert(b != NULL); if (int c = cmp_expr(a->left, b->left, ss_a, ss_b)) return c; return cmp_expr(a->right, b->right, ss_a, ss_b); } if (Not* a = dynamic_cast<Not*>(a_.get())) { Not* b = dynamic_cast<Not*>(b_.get()); assert(b != NULL); return cmp_expr(a->val, b->val, ss_a, ss_b); } if (Implies* a = dynamic_cast<Implies*>(a_.get())) { Implies* b = dynamic_cast<Implies*>(b_.get()); assert(b != NULL); if (int c = cmp_expr(a->left, b->left, ss_a, ss_b)) return c; return cmp_expr(a->right, b->right, ss_a, ss_b); } if (Apply* a = dynamic_cast<Apply*>(a_.get())) { Apply* b = dynamic_cast<Apply*>(b_.get()); assert(b != NULL); if (int c = cmp_expr(a->func, b->func, ss_a, ss_b)) return c; if (a->args.size() < b->args.size()) return -1; if (a->args.size() > b->args.size()) return 1; for (int i = 0; i < (int)a->args.size(); i++) { if (int c = cmp_expr(a->args[i], b->args[i], ss_a, ss_b)) { return c; } } return 0; } if (And* a = dynamic_cast<And*>(a_.get())) { And* b = dynamic_cast<And*>(b_.get()); assert(b != NULL); if (a->args.size() < b->args.size()) return -1; if (a->args.size() > b->args.size()) return 1; for (int i = 0; i < (int)a->args.size(); i++) { if (int c = cmp_expr(a->args[i], b->args[i], ss_a, ss_b)) { return c; } } return 0; } if (Or* a = dynamic_cast<Or*>(a_.get())) { Or* b = dynamic_cast<Or*>(b_.get()); assert(b != NULL); if (a->args.size() < b->args.size()) return -1; if (a->args.size() > b->args.size()) return 1; for (int i = 0; i < (int)a->args.size(); i++) { if (int c = cmp_expr(a->args[i], b->args[i], ss_a, ss_b)) { return c; } } return 0; } if (dynamic_cast<TemplateHole*>(a_.get())) { TemplateHole* b = dynamic_cast<TemplateHole*>(b_.get()); assert(b != NULL); return 0; } assert(false); } bool lt_value(value a_, value b_, ScopeState const& ss_a, ScopeState const& ss_b) { return cmp_expr(a_, b_, ss_a, ss_b) < 0; } bool lt_value(value a_, value b_) { ScopeState ss_a; ScopeState ss_b; return cmp_expr(a_, b_, ss_a, ss_b) < 0; } int cmp_expr_def(value a_, value b_) { int a_id = a_->kind_id(); int b_id = b_->kind_id(); if (a_id != b_id) return a_id < b_id ? -1 : 1; if (Forall* a = dynamic_cast<Forall*>(a_.get())) { Forall* b = dynamic_cast<Forall*>(b_.get()); assert(b != NULL); return cmp_expr_def(a->body, b->body); } if (Exists* a = dynamic_cast<Exists*>(a_.get())) { Exists* b = dynamic_cast<Exists*>(b_.get()); assert(b != NULL); return cmp_expr_def(a->body, b->body); } if (dynamic_cast<Var*>(a_.get())) { return 0; } if (Const* a = dynamic_cast<Const*>(a_.get())) { Const* b = dynamic_cast<Const*>(b_.get()); assert(b != NULL); return a->name < b->name ? -1 : (a->name == b->name ? 0 : 1); } if (dynamic_cast<Eq*>(a_.get())) { Eq* b = dynamic_cast<Eq*>(b_.get()); assert(b != NULL); return 0; } if (Not* a = dynamic_cast<Not*>(a_.get())) { Not* b = dynamic_cast<Not*>(b_.get()); assert(b != NULL); return cmp_expr_def(a->val, b->val); } if (dynamic_cast<Implies*>(a_.get())) { assert(false); } if (Apply* a = dynamic_cast<Apply*>(a_.get())) { Apply* b = dynamic_cast<Apply*>(b_.get()); assert(b != NULL); if (int c = cmp_expr_def(a->func, b->func)) return c; if (a->args.size() < b->args.size()) return -1; if (a->args.size() > b->args.size()) return 1; for (int i = 0; i < (int)a->args.size(); i++) { if (int c = cmp_expr_def(a->args[i], b->args[i])) { return c; } } return 0; } if (dynamic_cast<And*>(a_.get())) { return 0; } if (dynamic_cast<Or*>(a_.get())) { return 0; } assert(false); } bool get_certain_variable_order( value a_, vector<VarDecl> const& d, vector<iden> & res, int n) { if (Forall* a = dynamic_cast<Forall*>(a_.get())) { return get_certain_variable_order(a->body, d, res, n); } else if (Exists* a = dynamic_cast<Exists*>(a_.get())) { return get_certain_variable_order(a->body, d, res, n); } else if (Var* a = dynamic_cast<Var*>(a_.get())) { for (int i = 0; i < (int)d.size(); i++) { if (d[i].name == a->name) { bool contains = false; for (int j = 0; j < (int)res.size(); j++) { if (res[j] == a->name) { contains = true; break; } } if (!contains) { res.push_back(a->name); } break; } } return true; } else if (dynamic_cast<Const*>(a_.get())) { return true; } else if (Eq* a = dynamic_cast<Eq*>(a_.get())) { int c = cmp_expr_def(a->left, a->right); if (c == -1) { if (!get_certain_variable_order(a->left, d, res, n)) return false; return get_certain_variable_order(a->right, d, res, n); } else if (c == 1) { if (!get_certain_variable_order(a->right, d, res, n)) return false; return get_certain_variable_order(a->left, d, res, n); } else { // If we don't know which order the == goes in, but there's only one // additional variable anyway, it's fine. int cur_size = res.size(); bool okay = get_certain_variable_order(a->left, d, res, n); if (okay) { okay = get_certain_variable_order(a->right, d, res, n); } if (okay && (int)res.size() <= cur_size + 1) { return true; } else if (okay && (int)res.size() == n && cur_size == n - 2 && dynamic_cast<Var*>(a->left.get()) && dynamic_cast<Var*>(a->right.get())) { // A=B case where A and B are the last two // In this case, we learn nothing about the ordering from this term. res.resize(cur_size); return true; } else { res.resize(cur_size); return false; } } } if (Not* a = dynamic_cast<Not*>(a_.get())) { return get_certain_variable_order(a->val, d, res, n); } if (dynamic_cast<Implies*>(a_.get())) { assert(false); } if (Apply* a = dynamic_cast<Apply*>(a_.get())) { if (!get_certain_variable_order(a->func, d, res, n)) return false; for (value arg : a->args) { if (!get_certain_variable_order(arg, d, res, n)) return false; } return true; } if (And* a = dynamic_cast<And*>(a_.get())) { for (value arg : a->args) { if (!get_certain_variable_order(arg, d, res, n)) return false; } return true; } if (Or* a = dynamic_cast<Or*>(a_.get())) { for (value arg : a->args) { if (!get_certain_variable_order(arg, d, res, n)) return false; } return true; } assert(false); } vector<iden> get_front_quantifier_order( value body, vector<VarDecl> const& decls, set<iden> const& vars_used) { while (true) { if (Forall* b = dynamic_cast<Forall*>(body.get())) { body = b->body; } else if (Exists* b = dynamic_cast<Exists*>(body.get())) { body = b->body; } else { break; } } vector<value> juncts; if (And* b = dynamic_cast<And*>(body.get())) { juncts = b->args; } else if (Or* b = dynamic_cast<Or*>(body.get())) { juncts = b->args; } else { juncts.push_back(body); } if (juncts.size() == 0) { vector<iden> res; return res; } sort(juncts.begin(), juncts.end(), [](value const& a, value const& b) { return cmp_expr_def(a, b) < 0; }); int certain = 0; while (certain < (int)juncts.size() - 1 && cmp_expr_def(juncts[certain], juncts[certain+1]) < 0) { certain++; } if (certain == (int)juncts.size() - 1) { certain++; } vector<iden> used_decl_names; for (int i = 0; i < (int)decls.size(); i++) { if (vars_used.count(decls[i].name)) { used_decl_names.push_back(decls[i].name); } } vector<iden> certain_order; bool failed = false; for (int i = 0; i < certain; i++) { if (!get_certain_variable_order(juncts[i], decls, certain_order, used_decl_names.size())) { failed = true; break; } } if (!failed && certain == (int)juncts.size()) { for (iden name : used_decl_names) { bool used = false; for (iden s : certain_order) { if (s == name) { used = true; break; } } if (!used) { certain_order.push_back(name); } } } return certain_order; } value Forall::indexify_vars(map<iden, iden> const& m) const { map<iden, iden> new_m = m; vector<VarDecl> new_decls; for (VarDecl const& decl : this->decls) { iden new_name = new_m.size(); new_m[decl.name] = new_name; new_decls.push_back(VarDecl(new_name, decl.sort)); } return v_forall(new_decls, body->indexify_vars(new_m)); } value NearlyForall::indexify_vars(map<iden, iden> const& m) const { assert(false && "NearlyForall::indexify_vars not implemented"); } value Exists::indexify_vars(map<iden, iden> const& m) const { map<iden, iden> new_m = m; vector<VarDecl> new_decls; for (VarDecl const& decl : this->decls) { iden new_name = new_m.size(); new_m[decl.name] = new_name; new_decls.push_back(VarDecl(new_name, decl.sort)); } return v_forall(new_decls, body->indexify_vars(new_m)); } value Var::indexify_vars(map<iden, iden> const& m) const { auto iter = m.find(this->name); assert(iter != m.end()); return v_var(iter->second, this->sort); } value Const::indexify_vars(map<iden, iden> const& m) const { return v_const(name, sort); } value Eq::indexify_vars(map<iden, iden> const& m) const { return v_eq(left->indexify_vars(m), right->indexify_vars(m)); } value Not::indexify_vars(map<iden, iden> const& m) const { return v_not(this->val->indexify_vars(m)); } value Implies::indexify_vars(map<iden, iden> const& m) const { return v_implies(left->indexify_vars(m), right->indexify_vars(m)); } value Apply::indexify_vars(map<iden, iden> const& m) const { vector<value> new_args; for (value const& arg : args) { new_args.push_back(arg->indexify_vars(m)); } return v_apply(func->indexify_vars(m), move(new_args)); } value And::indexify_vars(map<iden, iden> const& m) const { vector<value> new_args; for (value const& arg : args) { new_args.push_back(arg->indexify_vars(m)); } return v_and(move(new_args)); } value Or::indexify_vars(map<iden, iden> const& m) const { vector<value> new_args; for (value const& arg : args) { new_args.push_back(arg->indexify_vars(m)); } return v_or(move(new_args)); } value IfThenElse::indexify_vars(map<iden, iden> const& m) const { return v_if_then_else(cond->indexify_vars(m), then_value->indexify_vars(m), else_value->indexify_vars(m)); } value TemplateHole::indexify_vars(map<iden, iden> const& m) const { return v_template_hole(); } void Forall::get_used_vars(set<iden>& s) const { body->get_used_vars(s); } void NearlyForall::get_used_vars(set<iden>& s) const { body->get_used_vars(s); } void Exists::get_used_vars(set<iden>& s) const { body->get_used_vars(s); } void Var::get_used_vars(set<iden>& s) const { s.insert(name); } void Const::get_used_vars(set<iden>& s) const { } void Eq::get_used_vars(set<iden>& s) const { left->get_used_vars(s); right->get_used_vars(s); } void Not::get_used_vars(set<iden>& s) const { val->get_used_vars(s); } void Implies::get_used_vars(set<iden>& s) const { left->get_used_vars(s); right->get_used_vars(s); } void Apply::get_used_vars(set<iden>& s) const { func->get_used_vars(s); for (value arg : args) { arg->get_used_vars(s); } } void And::get_used_vars(set<iden>& s) const { for (value arg : args) { arg->get_used_vars(s); } } void Or::get_used_vars(set<iden>& s) const { for (value arg : args) { arg->get_used_vars(s); } } void IfThenElse::get_used_vars(set<iden>& s) const { cond->get_used_vars(s); then_value->get_used_vars(s); else_value->get_used_vars(s); } void TemplateHole::get_used_vars(set<iden>& s) const { } //int counter = 0; //Benchmarking bench; value Value::totally_normalize() const { ScopeState ss; //bench.start("structurally_normalize"); value res = this->structurally_normalize(); //bench.end(); set<iden> vars_used; res->get_used_vars(vars_used); //bench.start("normalize_symmetries"); res = res->normalize_symmetries(ss, vars_used); //bench.end(); //bench.start("indexify_vars"); res = res->indexify_vars({}); //bench.end(); /* counter++; if (counter % 1000 == 0) { printf("count = %d\n", counter); bench.dump(); } */ return res; } vector<string> iden_to_string_map; map<string, iden> string_to_iden_map; std::string iden_to_string(iden id) { if (id < iden_to_string_map.size()) { return iden_to_string_map[id]; } else { return "UNKNOWN__" + to_string(id); } } iden string_to_iden(std::string const& s) { auto iter = string_to_iden_map.find(s); if (iter == string_to_iden_map.end()) { iden id = iden_to_string_map.size(); iden_to_string_map.push_back(s); string_to_iden_map.insert(make_pair(s, id)); return id; } else { return iter->second; } } std::vector<std::shared_ptr<Sort>> BooleanSort::get_domain_as_function() const { return {}; } std::shared_ptr<Sort> BooleanSort::get_range_as_function() const { return s_bool(); } std::vector<std::shared_ptr<Sort>> UninterpretedSort::get_domain_as_function() const { return {}; } std::shared_ptr<Sort> UninterpretedSort::get_range_as_function() const { return s_uninterp(name); } std::vector<std::shared_ptr<Sort>> FunctionSort::get_domain_as_function() const { return domain; } std::shared_ptr<Sort> FunctionSort::get_range_as_function() const { return range; } bool sorts_eq(lsort s, lsort t) { if (dynamic_cast<BooleanSort*>(s.get())) { return dynamic_cast<BooleanSort*>(t.get()) != NULL; } else if (UninterpretedSort* u1 = dynamic_cast<UninterpretedSort*>(s.get())) { UninterpretedSort* u2 = dynamic_cast<UninterpretedSort*>(t.get()); return u2 != NULL && u1->name == u2->name; } else if (FunctionSort* u1 = dynamic_cast<FunctionSort*>(s.get())) { FunctionSort* u2 = dynamic_cast<FunctionSort*>(t.get()); if (u2 == NULL) return false; if (u1->domain.size() != u2->domain.size()) return false; if (!sorts_eq(u1->range, u2->range)) return false; for (int i = 0; i < (int)u1->domain.size(); i++) { if (!sorts_eq(u1->domain[i], u2->domain[i])) return false; } return true; } else { assert(false); } } bool values_equal(value a, value b) { ScopeState ss_a; ScopeState ss_b; int c = cmp_expr(a, b, ss_a, ss_b); return c == 0; } value remove_unneeded_quants(Value const * v) { assert(v != NULL); if (Forall const* value = dynamic_cast<Forall const*>(v)) { vector<VarDecl> decls; for (VarDecl const& decl : value->decls) { if (value->uses_var(decl.name)) { decls.push_back(decl); } } auto b = remove_unneeded_quants(value->body.get()); return decls.size() > 0 ? v_forall(decls, b) : b; } else if (Exists const* value = dynamic_cast<Exists const*>(v)) { vector<VarDecl> decls; for (VarDecl const& decl : value->decls) { if (value->uses_var(decl.name)) { decls.push_back(decl); } } auto b = remove_unneeded_quants(value->body.get()); return decls.size() > 0 ? v_exists(decls, b) : b; } else if (NearlyForall const* value = dynamic_cast<NearlyForall const*>(v)) { return v_nearlyforall(value->decls, remove_unneeded_quants(value->body.get())); } else if (Var const* value = dynamic_cast<Var const*>(v)) { return v_var(value->name, value->sort); } else if (Const const* value = dynamic_cast<Const const*>(v)) { return v_const(value->name, value->sort); } else if (Eq const* value = dynamic_cast<Eq const*>(v)) { return v_eq( remove_unneeded_quants(value->left.get()), remove_unneeded_quants(value->right.get())); } else if (Not const* value = dynamic_cast<Not const*>(v)) { return v_not(remove_unneeded_quants(value->val.get())); } else if (Implies const* value = dynamic_cast<Implies const*>(v)) { return v_implies( remove_unneeded_quants(value->left.get()), remove_unneeded_quants(value->right.get())); } else if (Apply const* value = dynamic_cast<Apply const*>(v)) { vector<shared_ptr<Value>> args; for (auto a : value->args) { args.push_back(remove_unneeded_quants(a.get())); } return v_apply(value->func, args); } else if (And const* value = dynamic_cast<And const*>(v)) { vector<shared_ptr<Value>> args; for (auto a : value->args) { args.push_back(remove_unneeded_quants(a.get())); } return v_and(args); } else if (Or const* value = dynamic_cast<Or const*>(v)) { vector<shared_ptr<Value>> args; for (auto a : value->args) { args.push_back(remove_unneeded_quants(a.get())); } return v_or(args); } else { //printf("value2expr got: %s\n", v->to_string().c_str()); assert(false && "value2expr does not support this case"); } } bool vec_subset(vector<VarDecl> const& a, vector<VarDecl> const& b) { for (VarDecl const& decl : a) { for (VarDecl const& decl2 : b) { if (decl.name == decl2.name) { goto found; } } return false; found: {} } return true; } value factor_quants(value v) { value body = v; vector<VarDecl> decls; while (true) { if (Forall* f = dynamic_cast<Forall*>(body.get())) { extend(decls, f->decls); body = f->body; } else { break; } } if (decls.size() == 0) return v; vector<value> disj; if (Or* o = dynamic_cast<Or*>(body.get())) { disj = o->args; } else { return v; } if (disj.size() < 2) { return v; } vector<vector<VarDecl>> used; for (value d : disj) { vector<VarDecl> used_decls; for (VarDecl const& decl : decls) { if (d->uses_var(decl.name)) { used_decls.push_back(decl); } } used.push_back(used_decls); } int min_i = 0; for (int i = 1; i < (int)used.size(); i++) { if (used[i].size() < used[min_i].size()) min_i = i; } vector<VarDecl> first_decls = used[min_i]; if (first_decls.size() == decls.size()) { return v; } vector<VarDecl> second_decls; for (VarDecl const& decl : decls) { bool in_first = false; for (VarDecl const& fd : first_decls) { if (fd.name == decl.name) { in_first = true; break; } } if (!in_first) { second_decls.push_back(decl); } } vector<value> first_args; vector<value> second_args; for (int i = 0; i < (int)disj.size(); i++) { if (vec_subset(used[i], used[min_i])) { first_args.push_back(disj[i]); } else { second_args.push_back(disj[i]); } } if (second_args.size() == 0) { assert(first_decls.size() > 0); return v_forall(first_decls, v_or(first_args)); } else { assert(second_decls.size() > 0); assert(first_args.size() > 0); value inner = factor_quants(v_forall(second_decls, v_or(second_args))); vector<value> all_args = first_args; all_args.push_back(inner); return first_decls.size() == 0 ? v_or(all_args) : v_forall(first_decls, v_or(all_args)); } } value Value::reduce_quants() const { return factor_quants(remove_unneeded_quants(this)); } int freshVarDeclCounter = 0; VarDecl freshVarDecl(lsort sort) { string name = "_freshVarDecl_" + to_string(freshVarDeclCounter); freshVarDeclCounter++; return VarDecl(string_to_iden(name), sort); } value Forall::replace_const_with_var(map<iden, iden> const& x) const { return v_forall(decls, body->replace_const_with_var(x)); } value NearlyForall::replace_const_with_var(map<iden, iden> const& x) const { return v_nearlyforall(decls, body->replace_const_with_var(x)); } value Exists::replace_const_with_var(map<iden, iden> const& x) const { return v_exists(decls, body->replace_const_with_var(x)); } value Var::replace_const_with_var(map<iden, iden> const& x) const { return v_var(name, sort); } value Const::replace_const_with_var(map<iden, iden> const& x) const { auto it = x.find(name); if (it != x.end()) { return v_var(it->second, sort); } else { return v_const(name, sort); } } value Eq::replace_const_with_var(map<iden, iden> const& x) const { return v_eq(left->replace_const_with_var(x), right->replace_const_with_var(x)); } value Not::replace_const_with_var(map<iden, iden> const& x) const { return v_not(this->val->replace_const_with_var(x)); } value Implies::replace_const_with_var(map<iden, iden> const& x) const { return v_implies(left->replace_const_with_var(x), right->replace_const_with_var(x)); } value IfThenElse::replace_const_with_var(map<iden, iden> const& x) const { return v_if_then_else(cond->replace_const_with_var(x), then_value->replace_const_with_var(x), else_value->replace_const_with_var(x)); } value Apply::replace_const_with_var(map<iden, iden> const& x) const { vector<value> new_args; for (value const& arg : args) { new_args.push_back(arg->replace_const_with_var(x)); } return v_apply(func->replace_const_with_var(x), move(new_args)); } value And::replace_const_with_var(map<iden, iden> const& x) const { vector<value> new_args; for (value const& arg : args) { new_args.push_back(arg->replace_const_with_var(x)); } return v_and(move(new_args)); } value Or::replace_const_with_var(map<iden, iden> const& x) const { vector<value> new_args; for (value const& arg : args) { new_args.push_back(arg->replace_const_with_var(x)); } return v_or(move(new_args)); } value TemplateHole::replace_const_with_var(map<iden, iden> const& x) const { return v_template_hole(); } value Forall::replace_var_with_var(map<iden, iden> const& x) const { return v_forall(decls, body->replace_var_with_var(x)); } value NearlyForall::replace_var_with_var(map<iden, iden> const& x) const { return v_nearlyforall(decls, body->replace_var_with_var(x)); } value Exists::replace_var_with_var(map<iden, iden> const& x) const { return v_exists(decls, body->replace_var_with_var(x)); } value Var::replace_var_with_var(map<iden, iden> const& x) const { auto it = x.find(name); if (it != x.end()) { return v_var(it->second, sort); } else { return v_var(name, sort); } } value Const::replace_var_with_var(map<iden, iden> const& x) const { return v_const(name, sort); } value Eq::replace_var_with_var(map<iden, iden> const& x) const { return v_eq(left->replace_var_with_var(x), right->replace_var_with_var(x)); } value Not::replace_var_with_var(map<iden, iden> const& x) const { return v_not(this->val->replace_var_with_var(x)); } value Implies::replace_var_with_var(map<iden, iden> const& x) const { return v_implies(left->replace_var_with_var(x), right->replace_var_with_var(x)); } value IfThenElse::replace_var_with_var(map<iden, iden> const& x) const { return v_if_then_else(cond->replace_var_with_var(x), then_value->replace_var_with_var(x), else_value->replace_var_with_var(x)); } value Apply::replace_var_with_var(map<iden, iden> const& x) const { vector<value> new_args; for (value const& arg : args) { new_args.push_back(arg->replace_var_with_var(x)); } return v_apply(func->replace_var_with_var(x), move(new_args)); } value And::replace_var_with_var(map<iden, iden> const& x) const { vector<value> new_args; for (value const& arg : args) { new_args.push_back(arg->replace_var_with_var(x)); } return v_and(move(new_args)); } value Or::replace_var_with_var(map<iden, iden> const& x) const { vector<value> new_args; for (value const& arg : args) { new_args.push_back(arg->replace_var_with_var(x)); } return v_or(move(new_args)); } value TemplateHole::replace_var_with_var(map<iden, iden> const& x) const { return v_template_hole(); } template <typename A> vector<A> concat_vector(vector<A> const& a, vector<A> const& b) { vector<A> res = a; for (A const& x : b) { res.push_back(x); } return res; } template <typename A> void append_vector(vector<A>& a, vector<A> const& b) { for (A const& x : b) { a.push_back(x); } } vector<value> aggressively_split_into_conjuncts(value v) { assert(v.get() != NULL); if (Forall* val = dynamic_cast<Forall*>(v.get())) { vector<value> vs = aggressively_split_into_conjuncts(val->body); vector<value> res; for (int i = 0; i < (int)vs.size(); i++) { res.push_back(v_forall(val->decls, vs[i])); } return res; } else if (dynamic_cast<Exists*>(v.get())) { return {v}; } else if (dynamic_cast<NearlyForall*>(v.get())) { return {v}; } else if (dynamic_cast<Var*>(v.get())) { return {v}; } else if (dynamic_cast<Const*>(v.get())) { return {v}; } else if (dynamic_cast<Eq*>(v.get())) { return {v}; } else if (Not* val = dynamic_cast<Not*>(v.get())) { value w = val->val->negate(); vector<value> res; if (dynamic_cast<Not*>(w.get())) { res = {w}; } else { res = aggressively_split_into_conjuncts(w); } return res; } else if (Implies* val = dynamic_cast<Implies*>(v.get())) { return aggressively_split_into_conjuncts(v_or({v_not(val->left), val->right})); } else if (dynamic_cast<Apply*>(v.get())) { return {v}; } else if (And* val = dynamic_cast<And*>(v.get())) { vector<value> res; for (value c : val->args) { append_vector(res, aggressively_split_into_conjuncts(c)); } return res; } else if (Or* val = dynamic_cast<Or*>(v.get())) { vector<vector<value>> a; vector<int> inds; for (value c : val->args) { a.push_back(aggressively_split_into_conjuncts(c)); inds.push_back(0); if (a[a.size() - 1].size() == 0) { return {}; } } vector<value> res; while (true) { vector<value> ors; for (int i = 0; i < (int)inds.size(); i++) { ors.push_back(a[i][inds[i]]); } res.push_back(v_or(ors)); int i; for (i = 0; i < (int)inds.size(); i++) { inds[i]++; if (inds[i] == (int)a[i].size()) { inds[i] = 0; } else { break; } } if (i == (int)inds.size()) { break; } } cout << "v: " << v->to_string() << endl; for (value r : res) { cout << "res: " << r->to_string() << endl; } return res; } else if (IfThenElse* val = dynamic_cast<IfThenElse*>(v.get())) { return concat_vector( aggressively_split_into_conjuncts(v_implies(val->cond, val->then_value)), aggressively_split_into_conjuncts(v_implies(v_not(val->cond), val->else_value)) ); } else { assert(false && "aggressively_split_into_conjuncts does not support this case"); } } std::shared_ptr<Module> Module::add_conjectures(std::vector<std::shared_ptr<Value>> const& values) { vector<value> new_conjectures = conjectures; for (value v : values) { new_conjectures.push_back(v); } return shared_ptr<Module>(new Module(sorts, functions, axioms, inits, new_conjectures, templates, actions, action_names)); } int Module::get_template_idx(std::shared_ptr<Value> templ) { for (int i = 0; i < (int)templates.size(); i++) { if (values_equal(templates[i], templ)) { return i; } } assert(false); } value Forall::order_and_or_eq(ScopeState const& ss) const { ScopeState ss_new = ss; append_vector(ss_new.decls, decls); return v_forall(decls, body->order_and_or_eq(ss_new)); } value NearlyForall::order_and_or_eq(ScopeState const& ss) const { assert(false && "NearlyForall::order_and_or_eq not implemented"); } value Exists::order_and_or_eq(ScopeState const& ss) const { ScopeState ss_new = ss; append_vector(ss_new.decls, decls); return v_exists(decls, body->order_and_or_eq(ss_new)); } value Var::order_and_or_eq(ScopeState const& ss) const { return v_var(name, sort); } value Const::order_and_or_eq(ScopeState const& ss) const { return v_const(name, sort); } value IfThenElse::order_and_or_eq(ScopeState const& ss) const { assert(false); } value Eq::order_and_or_eq(ScopeState const& ss) const { value a = left->order_and_or_eq(ss); value b = right->order_and_or_eq(ss); return lt_value(a, b, ss, ss) ? v_eq(a, b) : v_eq(b, a); } value Not::order_and_or_eq(ScopeState const& ss) const { return v_not(val->order_and_or_eq(ss)); } value Implies::order_and_or_eq(ScopeState const& ss) const { assert(false && "implies should have been replaced by |"); } value Apply::order_and_or_eq(ScopeState const& ss) const { vector<value> new_args; for (value arg : args) { new_args.push_back(arg->order_and_or_eq(ss)); } return v_apply(func->order_and_or_eq(ss), move(new_args)); } value And::order_and_or_eq(ScopeState const& ss) const { vector<value> new_args; for (value arg : args) { new_args.push_back(arg->order_and_or_eq(ss)); } sort_values(ss, new_args); return v_and(new_args); } value Or::order_and_or_eq(ScopeState const& ss) const { vector<value> new_args; for (value arg : args) { new_args.push_back(arg->order_and_or_eq(ss)); } sort_values(ss, new_args); return v_or(new_args); } value TemplateHole::order_and_or_eq(ScopeState const& ss) const { return v_template_hole(); } value order_and_or_eq(value v) { ScopeState ss; return v->order_and_or_eq(ss); } <file_sep>/src/contexts.cpp #include "contexts.h" #include <cstdlib> #include <iostream> #include <cassert> #include "model.h" #include "wpr.h" #include "solve.h" using namespace std; using smt::expr; int name_counter = 1; string name(iden basename) { return "x" + to_string(rand()) + "_" + iden_to_string(basename) + "__" + to_string(name_counter++); } string name(string const& basename) { return "x" + to_string(rand()) + "_" + basename + "__" + to_string(name_counter++); } /* * BackgroundContext */ BackgroundContext::BackgroundContext(smt::context& ctx, std::shared_ptr<Module> module) : ctx(ctx), solver(ctx.make_solver()) { for (string sort : module->sorts) { this->sorts.insert(make_pair(sort, ctx.uninterpreted_sort(sort))); } } smt::sort BackgroundContext::getUninterpretedSort(std::string name) { auto iter = sorts.find(name); if (iter == sorts.end()) { printf("failed to find sort %s\n", name.c_str()); assert(false); } return iter->second; } smt::sort BackgroundContext::getSort(std::shared_ptr<Sort> sort) { Sort* s = sort.get(); if (dynamic_cast<BooleanSort*>(s)) { return ctx.bool_sort(); } else if (UninterpretedSort* usort = dynamic_cast<UninterpretedSort*>(s)) { return getUninterpretedSort(usort->name); } else if (dynamic_cast<FunctionSort*>(s)) { assert(false && "getSort does not support FunctionSort"); } else { assert(false && "getSort does not support unknown sort"); } } /* * ModelEmbedding */ shared_ptr<ModelEmbedding> ModelEmbedding::makeEmbedding( shared_ptr<BackgroundContext> ctx, shared_ptr<Module> module) { unordered_map<iden, smt::func_decl> mapping; for (VarDecl decl : module->functions) { Sort* s = decl.sort.get(); if (FunctionSort* fsort = dynamic_cast<FunctionSort*>(s)) { smt::sort_vector domain(ctx->ctx); for (std::shared_ptr<Sort> domain_sort : fsort->domain) { domain.push_back(ctx->getSort(domain_sort)); } smt::sort range = ctx->getSort(fsort->range); mapping.insert(make_pair(decl.name, ctx->ctx.function( name(decl.name), domain, range))); } else { mapping.insert(make_pair(decl.name, ctx->ctx.function( name(decl.name), ctx->getSort(decl.sort)))); } } return shared_ptr<ModelEmbedding>(new ModelEmbedding(ctx, mapping)); } smt::func_decl ModelEmbedding::getFunc(iden name) const { auto iter = mapping.find(name); if (iter == mapping.end()) { cout << "couldn't find function " << iden_to_string(name) << endl; assert(false); } return iter->second; } smt::expr ModelEmbedding::value2expr( shared_ptr<Value> value) { return value2expr(value, std::unordered_map<iden, smt::expr> {}, std::unordered_map<iden, smt::expr> {}); } smt::expr ModelEmbedding::value2expr( shared_ptr<Value> value, std::unordered_map<iden, smt::expr> const& consts) { return value2expr(value, consts, std::unordered_map<iden, smt::expr> {}); } smt::expr ModelEmbedding::value2expr_with_vars( shared_ptr<Value> value, std::unordered_map<iden, smt::expr> const& vars) { return value2expr(value, std::unordered_map<iden, smt::expr> {}, vars); } smt::expr ModelEmbedding::value2expr( shared_ptr<Value> v, std::unordered_map<iden, smt::expr> const& consts, std::unordered_map<iden, smt::expr> const& vars) { assert(v.get() != NULL); if (Forall* value = dynamic_cast<Forall*>(v.get())) { if (value->decls.size() == 0) { return value2expr(value->body, consts, vars); } smt::expr_vector vec_vars(ctx->ctx); std::unordered_map<iden, smt::expr> new_vars = vars; for (VarDecl decl : value->decls) { expr var = ctx->ctx.bound_var(name(decl.name), ctx->getSort(decl.sort)); vec_vars.push_back(var); new_vars.insert(make_pair(decl.name, var)); } return smt::forall(vec_vars, value2expr(value->body, consts, new_vars)); } else if (Exists* value = dynamic_cast<Exists*>(v.get())) { if (value->decls.size() == 0) { return value2expr(value->body, consts, vars); } smt::expr_vector vec_vars(ctx->ctx); std::unordered_map<iden, smt::expr> new_vars = vars; for (VarDecl decl : value->decls) { expr var = ctx->ctx.bound_var(name(decl.name), ctx->getSort(decl.sort)); vec_vars.push_back(var); new_vars.insert(make_pair(decl.name, var)); } return smt::exists(vec_vars, value2expr(value->body, consts, new_vars)); } else if (NearlyForall* value = dynamic_cast<NearlyForall*>(v.get())) { smt::expr_vector vec_vars(ctx->ctx); smt::expr_vector all_eq(ctx->ctx); std::unordered_map<iden, smt::expr> new_vars1 = vars; std::unordered_map<iden, smt::expr> new_vars2 = vars; for (VarDecl decl : value->decls) { expr var1 = ctx->ctx.bound_var(name(decl.name), ctx->getSort(decl.sort)); expr var2 = ctx->ctx.bound_var(name(decl.name), ctx->getSort(decl.sort)); vec_vars.push_back(var1); vec_vars.push_back(var2); new_vars1.insert(make_pair(decl.name, var1)); new_vars2.insert(make_pair(decl.name, var2)); all_eq.push_back(var1 == var2); } smt::expr_vector vec_or(ctx->ctx); vec_or.push_back(value2expr(value->body, consts, new_vars1)); vec_or.push_back(value2expr(value->body, consts, new_vars2)); vec_or.push_back(smt::mk_and(all_eq)); return smt::forall(vec_vars, smt::mk_or(vec_or)); } else if (Var* value = dynamic_cast<Var*>(v.get())) { auto iter = vars.find(value->name); if (iter == vars.end()) { printf("couldn't find var: %s\n", iden_to_string(value->name).c_str()); assert(false); } return iter->second; } else if (Const* value = dynamic_cast<Const*>(v.get())) { auto iter = consts.find(value->name); if (iter == consts.end()) { auto iter = mapping.find(value->name); if (iter == mapping.end()) { printf("could not find %s\n", iden_to_string(value->name).c_str()); assert(false); } smt::func_decl fd = iter->second; return fd.call(); } else { return iter->second; } } else if (Eq* value = dynamic_cast<Eq*>(v.get())) { return value2expr(value->left, consts, vars) == value2expr(value->right, consts, vars); } else if (Not* value = dynamic_cast<Not*>(v.get())) { return !value2expr(value->val, consts, vars); } else if (Implies* value = dynamic_cast<Implies*>(v.get())) { return !value2expr(value->left, consts, vars) || value2expr(value->right, consts, vars); } else if (Apply* value = dynamic_cast<Apply*>(v.get())) { smt::expr_vector args(ctx->ctx); for (shared_ptr<Value> arg : value->args) { args.push_back(value2expr(arg, consts, vars)); } Const* func_value = dynamic_cast<Const*>(value->func.get()); assert(func_value != NULL); return getFunc(func_value->name).call(args); } else if (And* value = dynamic_cast<And*>(v.get())) { if (value->args.size() == 0) { return ctx->ctx.bool_val(true); } else if (value->args.size() == 1) { return value2expr(value->args[0], consts, vars); } else { smt::expr_vector args(ctx->ctx); for (shared_ptr<Value> arg : value->args) { args.push_back(value2expr(arg, consts, vars)); } return mk_and(args); } } else if (Or* value = dynamic_cast<Or*>(v.get())) { if (value->args.size() == 0) { return ctx->ctx.bool_val(false); } else if (value->args.size() == 1) { return value2expr(value->args[0], consts, vars); } else { smt::expr_vector args(ctx->ctx); for (shared_ptr<Value> arg : value->args) { args.push_back(value2expr(arg, consts, vars)); } return mk_or(args); } } else if (IfThenElse* value = dynamic_cast<IfThenElse*>(v.get())) { return smt::ite( value2expr(value->cond, consts, vars), value2expr(value->then_value, consts, vars), value2expr(value->else_value, consts, vars) ); } else { //printf("value2expr got: %s\n", v->to_string().c_str()); assert(false && "value2expr does not support this case"); } } /* * InductionContext */ InductionContext::InductionContext( smt::context& z3ctx, std::shared_ptr<Module> module, int action_idx) : ctx(new BackgroundContext(z3ctx, module)), action_idx(action_idx) { init(module); } InductionContext::InductionContext( shared_ptr<BackgroundContext> bgctx, std::shared_ptr<Module> module, int action_idx) : ctx(bgctx), action_idx(action_idx) { init(module); } void InductionContext::init(std::shared_ptr<Module> module) { assert(-1 <= action_idx && action_idx < (int)module->actions.size()); this->e1 = ModelEmbedding::makeEmbedding(ctx, module); shared_ptr<Action> action = action_idx == -1 ? shared_ptr<Action>(new ChoiceAction(module->actions)) : module->actions[action_idx]; ActionResult res = applyAction(this->e1, action, std::unordered_map<iden, smt::expr> {}); this->e2 = res.e; // Add the relation between the two states ctx->solver.add(res.constraint); // Add the axioms for (shared_ptr<Value> axiom : module->axioms) { ctx->solver.add(this->e1->value2expr(axiom, std::unordered_map<iden, smt::expr> {})); } } /* * ChainContext */ ChainContext::ChainContext( smt::context& z3ctx, std::shared_ptr<Module> module, int numTransitions) : ctx(new BackgroundContext(z3ctx, module)) { this->es.resize(numTransitions + 1); this->es[0] = ModelEmbedding::makeEmbedding(ctx, module); shared_ptr<Action> action = shared_ptr<Action>(new ChoiceAction(module->actions)); for (int i = 0; i < numTransitions; i++) { ActionResult res = applyAction(this->es[i], action, std::unordered_map<iden, smt::expr> {}); this->es[i+1] = res.e; // Add the relation between the two states ctx->solver.add(res.constraint); } // Add the axioms for (shared_ptr<Value> axiom : module->axioms) { ctx->solver.add(this->es[0]->value2expr(axiom, std::unordered_map<iden, smt::expr> {})); } } ActionResult do_if_else( shared_ptr<ModelEmbedding> e, shared_ptr<Value> condition, shared_ptr<Action> then_body, shared_ptr<Action> else_body, unordered_map<iden, smt::expr> const& consts) { vector<shared_ptr<Action>> seq1; seq1.push_back(shared_ptr<Action>(new Assume(condition))); seq1.push_back(then_body); vector<shared_ptr<Action>> seq2; seq2.push_back(shared_ptr<Action>(new Assume(shared_ptr<Value>(new Not(condition))))); if (else_body.get() != nullptr) { seq2.push_back(else_body); } vector<shared_ptr<Action>> choices = { shared_ptr<Action>(new SequenceAction(seq1)), shared_ptr<Action>(new SequenceAction(seq2)) }; return applyAction(e, shared_ptr<Action>(new ChoiceAction(choices)), consts); } expr funcs_equal(smt::context& ctx, smt::func_decl a, smt::func_decl b) { smt::expr_vector args(ctx); for (int i = 0; i < (int)a.arity(); i++) { smt::sort arg_sort = a.domain(i); args.push_back(ctx.bound_var(name("arg"), arg_sort)); } if (args.size() == 0) { return a.call(args) == b.call(args); } else { return smt::forall(args, a.call(args) == b.call(args)); } } ActionResult applyAction( shared_ptr<ModelEmbedding> e, shared_ptr<Action> a, unordered_map<iden, expr> const& consts) { shared_ptr<BackgroundContext> ctx = e->ctx; if (LocalAction* action = dynamic_cast<LocalAction*>(a.get())) { unordered_map<iden, expr> new_consts(consts); for (VarDecl decl : action->args) { smt::func_decl d = ctx->ctx.function(name(decl.name), ctx->getSort(decl.sort)); expr ex = d.call(); new_consts.insert(make_pair(decl.name, ex)); } return applyAction(e, action->body, new_consts); } else if (RelationAction* action = dynamic_cast<RelationAction*>(a.get())) { unordered_map<iden, smt::func_decl> new_mapping = e->mapping; unordered_map<iden, smt::func_decl> twostate_mapping = e->mapping; for (string mod : action->mods) { iden mod_iden = string_to_iden(mod); smt::func_decl orig_func = e->getFunc(mod_iden); smt::sort_vector domain(ctx->ctx); for (int i = 0; i < (int)orig_func.arity(); i++) { domain.push_back(orig_func.domain(i)); } string new_name = name(mod); smt::func_decl new_func = ctx->ctx.function(new_name, domain, orig_func.range()); new_mapping.erase(mod_iden); new_mapping.insert(make_pair(mod_iden, new_func)); twostate_mapping.insert(make_pair(string_to_iden(mod+"'"), new_func)); } ModelEmbedding* twostate_e = new ModelEmbedding(ctx, twostate_mapping); smt::expr ex = twostate_e->value2expr(action->rel, consts); ModelEmbedding* new_e = new ModelEmbedding(ctx, new_mapping); return ActionResult(shared_ptr<ModelEmbedding>(new_e), ex); } else if (SequenceAction* action = dynamic_cast<SequenceAction*>(a.get())) { smt::expr_vector parts(ctx->ctx); for (shared_ptr<Action> sub_action : action->actions) { ActionResult res = applyAction(e, sub_action, consts); e = res.e; parts.push_back(res.constraint); } expr ex = smt::mk_and(parts); return ActionResult(e, smt::mk_and(parts)); } else if (Assume* action = dynamic_cast<Assume*>(a.get())) { return ActionResult(e, e->value2expr(action->body, consts)); } else if (If* action = dynamic_cast<If*>(a.get())) { return do_if_else(e, action->condition, action->then_body, nullptr, consts); } else if (IfElse* action = dynamic_cast<IfElse*>(a.get())) { return do_if_else(e, action->condition, action->then_body, action->else_body, consts); } else if (ChoiceAction* action = dynamic_cast<ChoiceAction*>(a.get())) { int len = action->actions.size(); vector<shared_ptr<ModelEmbedding>> es; vector<smt::expr> constraints; for (int i = 0; i < len; i++) { ActionResult res = applyAction(e, action->actions[i], consts); es.push_back(res.e); constraints.push_back(res.constraint); } unordered_map<iden, smt::func_decl> mapping; for (auto p : e->mapping) { iden func_name = p.first; bool is_ident = true; smt::func_decl new_func_decl = e->getFunc(func_name); for (int i = 0; i < len; i++) { if (!func_decl_eq(es[i]->getFunc(func_name), e->getFunc(func_name))) { is_ident = false; new_func_decl = es[i]->mapping.find(func_name)->second; break; } } mapping.insert(make_pair(func_name, new_func_decl)); if (!is_ident) { for (int i = 0; i < len; i++) { if (!func_decl_eq(es[i]->getFunc(func_name), new_func_decl)) { constraints[i] = funcs_equal(ctx->ctx, es[i]->getFunc(func_name), new_func_decl) && constraints[i]; } } } } smt::expr_vector constraints_vec(ctx->ctx); for (int i = 0; i < len; i++) { constraints_vec.push_back(constraints[i]); } return ActionResult( shared_ptr<ModelEmbedding>(new ModelEmbedding(e->ctx, mapping)), smt::mk_or(constraints_vec) ); } else if (Assign* action = dynamic_cast<Assign*>(a.get())) { Value* left = action->left.get(); Apply* apply = dynamic_cast<Apply*>(left); //assert(apply != NULL); Const* func_const = dynamic_cast<Const*>(apply != NULL ? apply->func.get() : left); assert(func_const != NULL); smt::func_decl orig_func = e->getFunc(func_const->name); smt::sort_vector domain(ctx->ctx); for (int i = 0; i < (int)orig_func.arity(); i++) { domain.push_back(orig_func.domain(i)); } string new_name = name(func_const->name); smt::func_decl new_func = ctx->ctx.function(new_name, domain, orig_func.range()); smt::expr_vector qvars(ctx->ctx); smt::expr_vector all_eq_parts(ctx->ctx); unordered_map<iden, smt::expr> vars; for (int i = 0; i < (int)orig_func.arity(); i++) { assert(apply != NULL); shared_ptr<Value> arg = apply->args[i]; if (Var* arg_var = dynamic_cast<Var*>(arg.get())) { expr qvar = ctx->ctx.bound_var(name(arg_var->name), ctx->getSort(arg_var->sort)); qvars.push_back(qvar); vars.insert(make_pair(arg_var->name, qvar)); } else { expr qvar = ctx->ctx.bound_var(name("arg"), domain[i]); qvars.push_back(qvar); all_eq_parts.push_back(qvar == e->value2expr(arg, consts)); } } unordered_map<iden, smt::func_decl> new_mapping = e->mapping; new_mapping.erase(func_const->name); new_mapping.insert(make_pair(func_const->name, new_func)); ModelEmbedding* new_e = new ModelEmbedding(ctx, new_mapping); smt::expr inner = new_func.call(qvars) == smt::ite( smt::mk_and(all_eq_parts), e->value2expr(action->right, consts, vars), orig_func.call(qvars)); smt::expr outer = qvars.size() == 0 ? inner : smt::forall(qvars, inner); ActionResult ar(shared_ptr<ModelEmbedding>(new_e), outer); return ar; } else if (Havoc* action = dynamic_cast<Havoc*>(a.get())) { Value* left = action->left.get(); Apply* apply = dynamic_cast<Apply*>(left); //assert(apply != NULL); Const* func_const = dynamic_cast<Const*>(apply != NULL ? apply->func.get() : left); assert(func_const != NULL); smt::func_decl orig_func = e->getFunc(func_const->name); smt::sort_vector domain(ctx->ctx); for (int i = 0; i < (int)orig_func.arity(); i++) { domain.push_back(orig_func.domain(i)); } string new_name = name(func_const->name); smt::func_decl new_func = ctx->ctx.function(new_name, domain, orig_func.range()); smt::expr_vector qvars(ctx->ctx); smt::expr_vector all_eq_parts(ctx->ctx); unordered_map<iden, smt::expr> vars; for (int i = 0; i < (int)orig_func.arity(); i++) { assert(apply != NULL); shared_ptr<Value> arg = apply->args[i]; if (Var* arg_var = dynamic_cast<Var*>(arg.get())) { expr qvar = ctx->ctx.bound_var(name(arg_var->name), ctx->getSort(arg_var->sort)); qvars.push_back(qvar); vars.insert(make_pair(arg_var->name, qvar)); } else { expr qvar = ctx->ctx.bound_var(name("arg"), domain[i]); qvars.push_back(qvar); all_eq_parts.push_back(qvar == e->value2expr(arg, consts)); } } unordered_map<iden, smt::func_decl> new_mapping = e->mapping; new_mapping.erase(func_const->name); new_mapping.insert(make_pair(func_const->name, new_func)); ModelEmbedding* new_e = new ModelEmbedding(ctx, new_mapping); smt::expr inner = smt::implies( !smt::mk_and(all_eq_parts), new_func.call(qvars) == orig_func.call(qvars)); smt::expr outer = qvars.size() == 0 ? inner : smt::forall(qvars, inner); ActionResult ar(shared_ptr<ModelEmbedding>(new_e), outer); return ar; } else { assert(false && "applyAction does not implement this unknown case"); } } void ModelEmbedding::dump() { for (auto p : mapping) { printf("%s -> %s\n", iden_to_string(p.first).c_str(), p.second.get_name().c_str()); } } /* * BasicContext */ BasicContext::BasicContext( smt::context& z3ctx, std::shared_ptr<Module> module) : ctx(new BackgroundContext(z3ctx, module)) { this->e = ModelEmbedding::makeEmbedding(ctx, module); // Add the axioms for (shared_ptr<Value> axiom : module->axioms) { ctx->solver.add(this->e->value2expr(axiom)); } } BasicContext::BasicContext( std::shared_ptr<BackgroundContext> bgctx, std::shared_ptr<Module> module) : ctx(bgctx) { this->e = ModelEmbedding::makeEmbedding(ctx, module); // Add the axioms for (shared_ptr<Value> axiom : module->axioms) { ctx->solver.add(this->e->value2expr(axiom)); } } /* * InitContext */ InitContext::InitContext( smt::context& z3ctx, std::shared_ptr<Module> module) : ctx(new BackgroundContext(z3ctx, module)) { init(module); } InitContext::InitContext( shared_ptr<BackgroundContext> bgctx, std::shared_ptr<Module> module) : ctx(bgctx) { init(module); } void InitContext::init(std::shared_ptr<Module> module) { this->e = ModelEmbedding::makeEmbedding(ctx, module); // Add the axioms for (shared_ptr<Value> axiom : module->axioms) { ctx->solver.add(this->e->value2expr(axiom)); } // Add the inits for (shared_ptr<Value> init : module->inits) { ctx->solver.add(this->e->value2expr(init)); } } /* * ConjectureContext */ ConjectureContext::ConjectureContext( smt::context& z3ctx, std::shared_ptr<Module> module) : ctx(new BackgroundContext(z3ctx, module)) { this->e = ModelEmbedding::makeEmbedding(ctx, module); // Add the axioms for (shared_ptr<Value> axiom : module->axioms) { ctx->solver.add(this->e->value2expr(axiom)); } // Add the conjectures shared_ptr<Value> all_conjectures = shared_ptr<Value>(new And(module->conjectures)); shared_ptr<Value> not_conjectures = shared_ptr<Value>(new Not(all_conjectures)); ctx->solver.add(this->e->value2expr(not_conjectures)); } /* * InvariantsContext */ InvariantsContext::InvariantsContext( smt::context& z3ctx, std::shared_ptr<Module> module) : ctx(new BackgroundContext(z3ctx, module)) { this->e = ModelEmbedding::makeEmbedding(ctx, module); // Add the axioms for (shared_ptr<Value> axiom : module->axioms) { ctx->solver.add(this->e->value2expr(axiom)); } } bool is_satisfiable(shared_ptr<Module> module, value candidate) { smt::context ctx(smt::Backend::z3); BasicContext basicctx(ctx, module); smt::solver& solver = basicctx.ctx->solver; solver.add(basicctx.e->value2expr(candidate)); return solver.check_sat(); } bool is_satisfiable_tryhard(shared_ptr<Module> module, value candidate) { ContextSolverResult res = context_solve( "is_satisfiable", module, ModelType::Any, Strictness::TryHard, nullptr, [module, candidate](shared_ptr<BackgroundContext> bgctx) { BasicContext basicctx(bgctx, module); smt::solver& solver = basicctx.ctx->solver; solver.add(basicctx.e->value2expr(candidate)); return vector<shared_ptr<ModelEmbedding>>{}; }); return res.res != smt::SolverResult::Unsat; } bool is_complete_invariant(shared_ptr<Module> module, value candidate) { smt::context ctx(smt::Backend::z3); { InitContext initctx(ctx, module); smt::solver& init_solver = initctx.ctx->solver; init_solver.add(initctx.e->value2expr(v_not(candidate))); init_solver.set_log_info("is_complete_invariant-init"); if (init_solver.check_sat()) { return false; } } { ConjectureContext conjctx(ctx, module); smt::solver& conj_solver = conjctx.ctx->solver; conj_solver.add(conjctx.e->value2expr(candidate)); conj_solver.set_log_info("is_complete_invariant-conj"); if (conj_solver.check_sat()) { return false; } } { InductionContext indctx(ctx, module); smt::solver& solver = indctx.ctx->solver; solver.add(indctx.e1->value2expr(candidate)); solver.add(indctx.e2->value2expr(v_not(candidate))); solver.set_log_info("is_complete_invariant-ind"); if (solver.check_sat()) { return false; } } return true; } bool is_itself_invariant(shared_ptr<Module> module, value candidate) { smt::context ctx(smt::Backend::z3); { InitContext initctx(ctx, module); smt::solver& init_solver = initctx.ctx->solver; init_solver.set_log_info("is_itself_invariant-init"); init_solver.add(initctx.e->value2expr(v_not(candidate))); if (init_solver.check_sat()) { return false; } } { InductionContext indctx(ctx, module); smt::solver& solver = indctx.ctx->solver; solver.set_log_info("is_itself_invariant-ind"); solver.add(indctx.e1->value2expr(candidate)); solver.add(indctx.e2->value2expr(v_not(candidate))); if (solver.check_sat()) { return false; } } return true; } bool is_invariant_with_conjectures(std::shared_ptr<Module> module, value v) { return is_itself_invariant(module, v_and({v, v_and(module->conjectures)})); } bool is_invariant_with_conjectures(std::shared_ptr<Module> module, vector<value> v) { for (value c : module->conjectures) { v.push_back(c); } return is_itself_invariant(module, v); } bool is_itself_invariant(shared_ptr<Module> module, vector<value> candidates) { //printf("is_itself_invariant\n"); smt::context ctx(smt::Backend::z3); value full = v_and(candidates); for (value candidate : candidates) { //printf("%s\n", candidate->to_string().c_str()); { InitContext initctx(ctx, module); smt::solver& init_solver = initctx.ctx->solver; init_solver.add(initctx.e->value2expr(v_not(candidate))); init_solver.set_log_info("is_itself_invariant-init"); //printf("checking init condition...\n"); if (init_solver.check_sat()) { //cout << "failed init with candidate " << candidate->to_string() << endl; return false; } } for (int i = 0; i < (int)module->actions.size(); i++) { InductionContext indctx(ctx, module, i); smt::solver& solver = indctx.ctx->solver; solver.set_log_info("is_itself_invariant-ind"); solver.add(indctx.e1->value2expr(full)); solver.add(indctx.e2->value2expr(v_not(candidate))); //printf("checking invariant condition...\n"); if (solver.check_sat()) { //cout << "failed with action " << module->action_names[i] << endl; //cout << "failed with candidate " << candidate->to_string() << endl; /*shared_ptr<Model> m1 = Model::extract_model_from_z3( indctx.ctx->ctx, solver, module, *indctx.e1); shared_ptr<Model> m2 = Model::extract_model_from_z3( indctx.ctx->ctx, solver, module, *indctx.e2); m1->dump(); m2->dump();*/ /*auto m = Model::extract_minimal_models_from_z3( indctx.ctx->ctx, solver, module, {indctx.e1, indctx.e2}, nullptr); m[0]->dump(); m[1]->dump();*/ //cout << "hey " << m[0]->eval_predicate(candidates[2]) << endl;*/ return false; } } } return true; } bool is_wpr_itself_inductive(shared_ptr<Module> module, value candidate, int wprIter) { smt::context ctx(smt::Backend::z3); shared_ptr<Action> action = shared_ptr<Action>(new ChoiceAction(module->actions)); value wpr_candidate = candidate; for (int j = 0; j < wprIter; j++) { wpr_candidate = wpr(wpr_candidate, action)->simplify(); } for (int i = 1; i <= wprIter + 1; i++) { cout << "is_wpr_itself_inductive: " << i << endl; ChainContext chainctx(ctx, module, i); smt::solver& solver = chainctx.ctx->solver; solver.add(chainctx.es[0]->value2expr(wpr_candidate)); solver.add(chainctx.es[i]->value2expr(v_not(candidate))); if (solver.check_sat()) { return false; } } return true; } smt::SolverResult is_invariant_wrt(shared_ptr<Module> module, value invariant_so_far, vector<value> const& candidates, Strictness strictness) { for (value candidate : candidates) { ContextSolverResult res = context_solve( "is_invariant_wrt init", module, ModelType::Any, strictness, nullptr, [module, candidate](shared_ptr<BackgroundContext> bgctx) { InitContext initctx(bgctx, module); smt::solver& init_solver = initctx.ctx->solver; init_solver.add(initctx.e->value2expr(v_not(candidate))); return vector<shared_ptr<ModelEmbedding>>{}; }); if (res.res != smt::SolverResult::Unsat) { return res.res; } } for (value candidate : candidates) { for (int i = 0; i < (int)module->actions.size(); i++) { ContextSolverResult res = context_solve( "is_invariant_wrt inductiveness", module, ModelType::Any, strictness, nullptr, [&candidate, candidates, module, i, invariant_so_far](shared_ptr<BackgroundContext> bgctx) { InductionContext indctx(bgctx, module, i); smt::solver& solver = indctx.ctx->solver; solver.set_log_info("is_invariant_wrt inductiveness"); solver.add(indctx.e1->value2expr(invariant_so_far)); solver.add(indctx.e1->value2expr(v_and(candidates))); solver.add(indctx.e2->value2expr(v_not(candidate))); return vector<shared_ptr<ModelEmbedding>>{}; }); if (res.res != smt::SolverResult::Unsat) { return res.res; } } } return smt::SolverResult::Unsat; } bool is_invariant_wrt(shared_ptr<Module> module, value invariant_so_far, vector<value> const& candidates) { return is_invariant_wrt(module, invariant_so_far, candidates, Strictness::Strict) == smt::SolverResult::Unsat; } bool is_invariant_wrt(shared_ptr<Module> module, value invariant_so_far, value candidate) { return is_invariant_wrt(module, invariant_so_far, vector<value>{candidate}); } bool is_invariant_wrt_tryhard(shared_ptr<Module> module, value invariant_so_far, vector<value> const& candidates) { return is_invariant_wrt(module, invariant_so_far, candidates, Strictness::TryHard) == smt::SolverResult::Unsat; } bool is_invariant_wrt_tryhard(shared_ptr<Module> module, value invariant_so_far, value candidate) { return is_invariant_wrt_tryhard(module, invariant_so_far, vector<value>{candidate}); } <file_sep>/src/strengthen_invariant.cpp #include "strengthen_invariant.h" #include "top_quantifier_desc.h" #include "contexts.h" using namespace std; vector<value> remove(vector<value> const& ar, int j) { vector<value> v; for (int i = 0; i < (int)ar.size(); i++) { if (i != j) { v.push_back(ar[i]); } } return v; } vector<value> replace(vector<value> const& ar, int j, value newv) { assert(0 <= j && j < (int)ar.size()); vector<value> v = ar; v[j] = newv; return v; } value try_replacing_exists_with_forall( shared_ptr<Module> module, value invariant_so_far, value new_invariant) { TopAlternatingQuantifierDesc taqd(new_invariant); value body = TopAlternatingQuantifierDesc::get_body(new_invariant); TopAlternatingQuantifierDesc taqd_mod = taqd.replace_exists_with_forall(); value inv0 = taqd_mod.with_body(body); if (is_invariant_wrt_tryhard(module, invariant_so_far, inv0)) { return inv0; } return new_invariant; } value strengthen_invariant_once( shared_ptr<Module> module, value invariant_so_far, value new_invariant) { new_invariant = try_replacing_exists_with_forall(module, invariant_so_far, new_invariant); TopAlternatingQuantifierDesc taqd(new_invariant); value body = TopAlternatingQuantifierDesc::get_body(new_invariant); Or* disj = dynamic_cast<Or*>(body.get()); if (!disj) { return new_invariant; } vector<value> args = disj->args; //cout << endl; for (int i = 0; i < (int)args.size(); i++) { vector<value> new_args = remove(args, i); value inv = taqd.with_body(v_or(new_args)); //cout << "trying " << inv->to_string(); if (is_invariant_wrt_tryhard(module, invariant_so_far, inv)) { //cout << "is inv" << endl << endl; args = new_args; i--; } else { //cout << "is not inv" << endl << endl; } } for (int i = 0; i < (int)args.size(); i++) { //cout << "i = " << i << endl; if (And* a = dynamic_cast<And*>(args[i].get())) { for (int j = 0; j < (int)a->args.size(); j++) { //cout << "j = " << j << endl; vector<value> new_conj = remove(a->args, j); vector<value> new_args = replace(args, i, v_and(new_conj)); value inv0 = taqd.with_body(v_or(args)); value inv1 = taqd.with_body(v_or(new_args)); if (!is_satisfiable(module, v_and({invariant_so_far, inv1, v_not(inv0)})) && is_invariant_wrt_tryhard(module, invariant_so_far, inv1)) { //cout << "is inv (and implies)" << endl << endl; args = new_args; a = dynamic_cast<And*>(args[i].get()); if (a == NULL) { break; } j--; //cout << "done with j = " << j << endl; //cout << "a->args.size() " << a->args.size() << endl; } else { //cout << "is not inv or not implies" << endl << endl; } } //cout << "done with i = " << i << endl; } } return taqd.with_body(v_or(args)); } value strengthen_invariant( shared_ptr<Module> module, value invariant_so_far, value new_invariant) { //cout << "strengthening " << new_invariant->to_string() << endl; value inv = new_invariant; int t = 0; while (true) { assert (t < 20); value inv0 = strengthen_invariant_once(module, invariant_so_far, inv); if (v_eq(inv, inv0)) { //cout << "got " << inv0->to_string() << endl; return inv0; } inv = inv0; } } <file_sep>/scripts/installing/install-z3.sh wget https://github.com/Z3Prover/z3/archive/z3-4.8.9.tar.gz tar xzf z3-4.8.9.tar.gz pushd . cd z3-z3-4.8.9/ python scripts/mk_make.py --prefix=/usr/local --python --pypkgdir=/usr/local/lib/python2.7/site-packages cd build make -j 4 make install export LD_LIBRARY_PATH=/usr/local/lib: export PYTHONPATH=/usr/local/lib/python2.7/site-packages:$PYTHONPATH popd <file_sep>/src/subsequence_trie.h #ifndef SUBSEQUENCE_TRIE_H #define SUBSEQUENCE_TRIE_H #include <vector> #include <memory> // Stores a set S of sequences // Supports the query: given a sequence t, does there exist subsequence s in S // such that s is a subsequence of t. // Query is exponential in t.size(), but we expect to use this where t.size() // is around 5. struct TrieNode { std::vector<std::unique_ptr<TrieNode>> children; bool isTerm; TrieNode(int n) { children.resize(n); isTerm = false; } }; inline bool subseq_query(std::vector<int> const& t, int idx, TrieNode* node, int& upTo) { if (node->isTerm) { upTo = idx; return true; } if (idx == (int)t.size()) { return false; } if (subseq_query(t, idx + 1, node, upTo)) { return true; } if (node->children[t[idx]] != nullptr) { return subseq_query(t, idx + 1, node->children[t[idx]].get(), upTo); } return false; } struct SubsequenceTrie { std::unique_ptr<TrieNode> root; int alphabet_size; SubsequenceTrie() { } SubsequenceTrie(int alpha) { alphabet_size = alpha; root = std::unique_ptr<TrieNode>(new TrieNode(alpha)); } void insert(std::vector<int> const& s) { TrieNode* node = root.get(); for (int i = 0; i < (int)s.size(); i++) { int j = s[i]; if (node->children[j] == nullptr) { node->children[j] = std::unique_ptr<TrieNode>(new TrieNode(alphabet_size)); } node = node->children[j].get(); } node->isTerm = true; } // Determine if a subsequence of t exists in s bool query(std::vector<int> const& t, int& upTo) { return subseq_query(t, 0, root.get(), upTo); } }; #endif <file_sep>/src/model_isomorphisms.cpp #include "model_isomorphisms.h" #include <algorithm> using namespace std; bool is_function_iso(shared_ptr<Model> m1, shared_ptr<Model> m2, shared_ptr<Module> module, VarDecl const& decl, vector<vector<int>> const& perms) { vector<object_value> args; vector<int> idx_for_arg; vector<int> domain_sizes; for (lsort so : decl.sort->get_domain_as_function()) { domain_sizes.push_back(m1->get_domain_size(so)); args.push_back(0); for (int i = 0; i < (int)module->sorts.size(); i++) { if (sorts_eq(so, s_uninterp(module->sorts[i]))) { idx_for_arg.push_back(i); goto end_of_loop; } } assert(false); end_of_loop: {} } int n = args.size(); while (true) { vector<object_value> perm_args(n); for (int i = 0; i < n; i++) { perm_args[i] = perms[idx_for_arg[i]][args[i]]; } object_value v1 = m1->func_eval(decl.name, args); object_value v2 = m1->func_eval(decl.name, perm_args); if (v1 != v2) { return false; } int i; for (i = 0; i < n; i++) { args[i]++; if ((int)args[i] == domain_sizes[i]) { args[i] = 0; } else { break; } } if (i == n) { break; } } return true; } bool do_test(shared_ptr<Model> m1, shared_ptr<Model> m2, shared_ptr<Module> module, vector<vector<int>> const& perms) { if (module->sorts.size() == perms.size()) { for (VarDecl decl : module->functions) { if (!is_function_iso(m1, m2, module, decl, perms)) { return false; } } return true; } else { int idx = perms.size(); string sort = module->sorts[idx]; vector<int> perm; int n = m1->get_domain_size(sort); for (int i = 0; i < n; i++) { perm.push_back(i); } do { vector<vector<int>> new_perms = perms; new_perms.push_back(perm); if (do_test(m1, m2, module, new_perms)) { return true; } } while (next_permutation(perm.begin(), perm.end())); return false; } } bool are_models_isomorphic(shared_ptr<Model> m1, shared_ptr<Model> m2) { assert(m1->module.get() == m2->module.get()); shared_ptr<Module> module = m1->module; for (string sort : module->sorts) { if (m1->get_domain_size(sort) != m2->get_domain_size(sort)) { return false; } } return do_test(m1, m2, module, {}); } <file_sep>/src/synth_loop.h #ifndef SYNTH_LOOP_H #define SYNTH_LOOP_H #include "logic.h" #include "synth_enumerator.h" struct Transcript; struct SynthesisResult { bool done; std::vector<value> new_values; std::vector<value> all_values; SynthesisResult() { } SynthesisResult(bool done, std::vector<value> const& new_values, std::vector<value> const& all_values) : done(done), new_values(new_values), all_values(all_values) { } }; SynthesisResult synth_loop( std::shared_ptr<Module> module, std::vector<TemplateSubSlice> const& slices, Options const& options, FormulaDump const& fd); SynthesisResult synth_loop_incremental_breadth( std::shared_ptr<Module> module, std::vector<TemplateSubSlice> const& slices, Options const& options, FormulaDump const& fd, bool single_round); //void synth_loop_from_transcript(std::shared_ptr<Module> module, int arity, int depth); #endif <file_sep>/src/model.cpp #include "model.h" #include <cassert> #include <map> #include <algorithm> #include "top_quantifier_desc.h" #include "bitset_eval_result.h" using namespace std; using namespace json11; enum class EvalExprType { Forall, Exists, NearlyForall, Var, Const, Eq, Not, Implies, Apply, And, Or, IfThenElse }; struct EvalExpr { EvalExprType type; vector<EvalExpr> args; object_value const_value; int quantifier_domain_size; int var_index; FunctionInfo const * function_info; vector<int> nearlyforall_quantifier_domain_sizes; vector<int> nearlyforall_var_indices; }; EvalExpr Model::value_to_eval_expr( shared_ptr<Value> v, vector<iden> const& names) const { assert(v.get() != NULL); EvalExpr ee; if (dynamic_cast<Forall*>(v.get()) || dynamic_cast<Exists*>(v.get()) || dynamic_cast<NearlyForall*>(v.get())) { std::vector<VarDecl> const * decls; std::shared_ptr<Value> body; if (Forall* value = dynamic_cast<Forall*>(v.get())) { decls = &value->decls; body = value->body; } else if (Exists* value = dynamic_cast<Exists*>(v.get())) { decls = &value->decls; body = value->body; } else if (NearlyForall* value = dynamic_cast<NearlyForall*>(v.get())) { decls = &value->decls; body = value->body; } else { assert(false); } vector<iden> new_names = names; for (VarDecl decl : *decls) { new_names.push_back(decl.name); } ee = value_to_eval_expr(body, new_names); if (dynamic_cast<NearlyForall*>(v.get())) { EvalExpr ee2; ee2.type = EvalExprType::NearlyForall; for (int i = 0; i < (int)decls->size(); i++) { VarDecl decl = (*decls)[i]; ee2.nearlyforall_quantifier_domain_sizes.push_back(get_domain_size(decl.sort.get())); ee2.nearlyforall_var_indices.push_back(names.size() + i); } ee2.args.push_back(move(ee)); ee = move(ee2); } else { for (int i = decls->size() - 1; i >= 0; i--) { VarDecl decl = (*decls)[i]; EvalExpr ee2; ee2.type = dynamic_cast<Forall*>(v.get()) ? EvalExprType::Forall : EvalExprType::Exists; ee2.quantifier_domain_size = get_domain_size(decl.sort.get()); ee2.var_index = names.size() + i; ee2.args.push_back(move(ee)); ee = move(ee2); } } } else if (Var* value = dynamic_cast<Var*>(v.get())) { int idx = -1; for (int i = 0; i < (int)names.size(); i++) { if (names[i] == value->name) { idx = i; break; } } if (idx == -1) { printf("could not find var: %s\n", iden_to_string(value->name).c_str()); assert(false); } ee.type = EvalExprType::Var; ee.var_index = idx; } else if (Const* value = dynamic_cast<Const*>(v.get())) { auto iter = function_info.find(value->name); if (iter == function_info.end()) { cout << "could not find " << iden_to_string(value->name) << endl; assert(false); } FunctionInfo const& finfo = iter->second; FunctionTable* ftable = finfo.table.get(); int val = ftable == NULL ? finfo.else_value : ftable->value; ee.type = EvalExprType::Const; ee.const_value = val; } else if (Eq* value = dynamic_cast<Eq*>(v.get())) { ee.type = EvalExprType::Eq; ee.args.push_back(value_to_eval_expr(value->left, names)); ee.args.push_back(value_to_eval_expr(value->right, names)); } else if (Not* value = dynamic_cast<Not*>(v.get())) { ee.type = EvalExprType::Not; ee.args.push_back(value_to_eval_expr(value->val, names)); } else if (Implies* value = dynamic_cast<Implies*>(v.get())) { ee.type = EvalExprType::Implies; ee.args.push_back(value_to_eval_expr(value->left, names)); ee.args.push_back(value_to_eval_expr(value->right, names)); } else if (Apply* value = dynamic_cast<Apply*>(v.get())) { Const* func = dynamic_cast<Const*>(value->func.get()); auto iter = function_info.find(func->name); if (iter == function_info.end()) { printf("could not find function name %s\n", iden_to_string(func->name).c_str()); assert(false); } FunctionInfo const& finfo = iter->second; ee.type = EvalExprType::Apply; ee.function_info = &finfo; for (auto arg : value->args) { ee.args.push_back(value_to_eval_expr(arg, names)); } } else if (And* value = dynamic_cast<And*>(v.get())) { ee.type = EvalExprType::And; for (auto arg : value->args) { ee.args.push_back(value_to_eval_expr(arg, names)); } } else if (Or* value = dynamic_cast<Or*>(v.get())) { ee.type = EvalExprType::Or; for (auto arg : value->args) { ee.args.push_back(value_to_eval_expr(arg, names)); } } else if (IfThenElse* value = dynamic_cast<IfThenElse*>(v.get())) { ee.type = EvalExprType::IfThenElse; ee.args.push_back(value_to_eval_expr(value->cond, names)); ee.args.push_back(value_to_eval_expr(value->then_value, names)); ee.args.push_back(value_to_eval_expr(value->else_value, names)); } else { assert(false && "value2eval_expr does not support this case"); } return ee; } int max_var(EvalExpr& ee) { int res = -1; for (EvalExpr& child : ee.args) { res = max(res, max_var(child)); } if (ee.type == EvalExprType::Forall || ee.type == EvalExprType::Exists) { res = max(res, ee.var_index); } if (ee.type == EvalExprType::NearlyForall) { for (int idx : ee.nearlyforall_var_indices) { res = max(res, idx); } } return res; } object_value eval(EvalExpr const& ee, int* var_values) { switch (ee.type) { case EvalExprType::Forall: { int idx = ee.var_index; int q = ee.quantifier_domain_size; EvalExpr const& body = ee.args[0]; for (int i = 0; i < q; i++) { //cout << "yolo" << endl; var_values[idx] = i; if (!eval(body, var_values)) { return 0; } } return 1; } case EvalExprType::Exists: { int idx = ee.var_index; int q = ee.quantifier_domain_size; EvalExpr const& body = ee.args[0]; for (int i = 0; i < q; i++) { var_values[idx] = i; if (eval(body, var_values)) { return 1; } } return 0; } case EvalExprType::NearlyForall: { int n = ee.nearlyforall_quantifier_domain_sizes.size(); for (int i = 0; i < n; i++) { var_values[ee.nearlyforall_var_indices[i]] = 0; } int bad_count = 0; EvalExpr const& body = ee.args[0]; while (true) { if (!eval(body, var_values)) { bad_count++; if (bad_count >= 2) { return 0; } } int i; for (i = 0; i < n; i++) { int idx = ee.nearlyforall_var_indices[i]; int sz = ee.nearlyforall_quantifier_domain_sizes[i]; var_values[idx]++; if (var_values[idx] == sz) { var_values[idx] = 0; } else { break; } } if (i == n) { break; } } return 1; } case EvalExprType::Var: return var_values[ee.var_index]; case EvalExprType::Const: return ee.const_value; case EvalExprType::Eq: return eval(ee.args[0], var_values) == eval(ee.args[1], var_values); case EvalExprType::Not: return 1 - eval(ee.args[0], var_values); case EvalExprType::Implies: return (int)(!eval(ee.args[0], var_values) || (bool)eval(ee.args[1], var_values)); case EvalExprType::Apply: { FunctionTable* ftable = ee.function_info->table.get(); for (EvalExpr const& arg : ee.args) { if (ftable == NULL) { break; } object_value arg_res = eval(arg, var_values); ftable = ftable->children[arg_res].get(); } return ftable == NULL ? ee.function_info->else_value : ftable->value; } case EvalExprType::And: for (EvalExpr const& arg : ee.args) { if (!eval(arg, var_values)) { return 0; } } return 1; case EvalExprType::Or: for (EvalExpr const& arg : ee.args) { if (eval(arg, var_values)) { return 1; } } return 0; case EvalExprType::IfThenElse: if (eval(ee.args[0], var_values)) { return eval(ee.args[1], var_values); } else { return eval(ee.args[2], var_values); } } } bool Model::eval_predicate(shared_ptr<Value> value) const { EvalExpr ee = value_to_eval_expr(value, {}); int n_vars = max_var(ee) + 1; int* var_values = new int[n_vars]; int ans = eval(ee, var_values); delete[] var_values; return ans == 1; } int get_num_forall_quantifiers_at_top(EvalExpr* ee); bool eval_get_counterexample( EvalExpr const& ee, int* var_values, QuantifierInstantiation& qi) { if (ee.type != EvalExprType::Forall) { return eval(ee, var_values) == 1; } int idx = ee.var_index; int q = ee.quantifier_domain_size; EvalExpr const& body = ee.args[0]; for (int i = 0; i < q; i++) { var_values[idx] = i; if (!eval_get_counterexample(body, var_values, qi)) { qi.variable_values[idx] = i; return false; } } return true; } QuantifierInstantiation get_counterexample(shared_ptr<Model> model, value v) { EvalExpr ee = model->value_to_eval_expr(v, {}); int n = get_num_forall_quantifiers_at_top(&ee); QuantifierInstantiation qi; qi.formula = v; qi.variable_values.resize(n); qi.model = model; value w = v; int idx = 0; for (int i = 0; i < n; i++) { Forall* f = dynamic_cast<Forall*>(w.get()); assert(f != NULL); qi.decls.push_back(f->decls[idx]); idx++; if (idx == (int)f->decls.size()) { idx = 0; w = f->body; } } int n_vars = max(max_var(ee), n) + 1; int* var_values = new int[n_vars]; bool ans = eval_get_counterexample(ee, var_values, qi); delete[] var_values; if (ans) { qi.non_null = false; qi.variable_values.clear(); } else { qi.non_null = true; } return qi; } int get_num_forall_or_nearlyforall_quantifiers_at_top(EvalExpr* ee) { int n = 0; while (true) { if (ee->type == EvalExprType::Forall) { n++; ee = &ee->args[0]; } else if (ee->type == EvalExprType::NearlyForall) { n += ee->nearlyforall_var_indices.size(); ee = &ee->args[0]; } else { break; } } return n; } template <typename A> void append_vector(vector<A>& a, vector<A> const& b) { for (A const& x : b) { a.push_back(x); } } bool eval_get_multiqi_counterexample( EvalExpr const& ee, int* var_values, vector<vector<object_value>>& res, int total_len) { if (ee.type == EvalExprType::Forall) { int idx = ee.var_index; int q = ee.quantifier_domain_size; EvalExpr const& body = ee.args[0]; for (int i = 0; i < q; i++) { var_values[idx] = i; if (!eval_get_multiqi_counterexample(body, var_values, res, total_len)) { for (vector<object_value>& qi : res) { qi[idx] = i; } return false; } } return true; } else if (ee.type == EvalExprType::NearlyForall) { int len = ee.nearlyforall_quantifier_domain_sizes.size(); for (int i = 0; i < len; i++) { var_values[ee.nearlyforall_var_indices[i]] = 0; } int bad_count = 0; EvalExpr const& body = ee.args[0]; while (true) { vector<vector<object_value>> r; if (!eval_get_multiqi_counterexample(body, var_values, r, total_len)) { for (vector<object_value>& qi : r) { for (int i = 0; i < len; i++) { qi[ee.nearlyforall_var_indices[i]] = var_values[ee.nearlyforall_var_indices[i]]; } } if (bad_count == 0) { res = move(r); bad_count++; } else { append_vector(res, r); return false; } } int i; for (i = 0; i < len; i++) { int idx = ee.nearlyforall_var_indices[i]; int sz = ee.nearlyforall_quantifier_domain_sizes[i]; var_values[idx]++; if (var_values[idx] == sz) { var_values[idx] = 0; } else { break; } } if (i == len) { break; } } res.clear(); return true; } else { if (eval(ee, var_values) == 1) { return true; } else { vector<object_value> os; os.resize(total_len); res.push_back(os); return false; } } } bool get_multiqi_counterexample(shared_ptr<Model> model, value v, vector<QuantifierInstantiation>& result) { EvalExpr ee = model->value_to_eval_expr(v, {}); int n = get_num_forall_or_nearlyforall_quantifiers_at_top(&ee); QuantifierInstantiation qi; qi.formula = v; qi.model = model; qi.non_null = true; value w = v; int idx = 0; for (int i = 0; i < n; i++) { int sz; value bd; if (Forall* f = dynamic_cast<Forall*>(w.get())) { qi.decls.push_back(f->decls[idx]); sz = f->decls.size(); bd = f->body; } else if (NearlyForall* f = dynamic_cast<NearlyForall*>(w.get())) { qi.decls.push_back(f->decls[idx]); sz = f->decls.size(); bd = f->body; } else { assert(false); } idx++; if (idx == sz) { idx = 0; w = bd; } } int n_vars = max(max_var(ee), n) + 1; int* var_values = new int[n_vars]; vector<vector<object_value>> qis; bool ans = eval_get_multiqi_counterexample(ee, var_values, qis, n); delete[] var_values; //cout << "get_multiqi_counterexample:" << endl; //model->dump(); //cout << "expr: " << v->to_string() << endl; result.clear(); if (ans) { //cout << "result: no counterexample found" << endl; return true; } else { qi.non_null = true; //cout << "result:" << endl; for (vector<object_value> const& q : qis) { //cout << "vals:"; //for (object_value ov : q) { // cout << " " << ov; //} //cout << endl; qi.variable_values = q; result.push_back(qi); } return false; } } int get_num_forall_quantifiers_at_top(EvalExpr* ee) { int n = 0; while (true) { if (ee->type == EvalExprType::Forall) { n++; ee = &ee->args[0]; } else { break; } } return n; } vector<shared_ptr<Model>> Model::extract_minimal_models_from_z3( smt::context& ctx, smt::solver& solver, shared_ptr<Module> module, vector<shared_ptr<ModelEmbedding>> es, value hint) { assert (es.size() > 0); vector<shared_ptr<Model>> all_models; for (auto e : es) { all_models.push_back(extract_model_from_z3(ctx, solver, module, *e)); } shared_ptr<Model> model0 = all_models[0]; cout << "extract_minimal_models_from_z3: initial sizes:\n"; cout.flush(); model0->dump_sizes(); BackgroundContext& bgctx = *es[0]->ctx; vector<string> sorts; vector<int> sizes; for (auto p : bgctx.sorts) { sorts.push_back(p.first); sizes.push_back(model0->get_domain_size(p.first)); } bool try_hint_sizes = false; vector<int> hint_sizes; if (hint) { //printf("hint: %s\n", hint->to_string().c_str()); TopQuantifierDesc tqd(hint); for (string sort : sorts) { int sz = tqd.weighted_sort_count(sort); hint_sizes.push_back(sz < 1 ? 1 : sz); } for (int i = 0; i < (int)sizes.size(); i++) { hint_sizes[i] = min(sizes[i], hint_sizes[i]); } try_hint_sizes = true; } int sort_idx = 0; int lower_bound_size = 0; while (sort_idx < (int)sorts.size()) { vector<int> new_sizes; if (try_hint_sizes) { new_sizes = hint_sizes; } else { if (sizes[sort_idx] <= lower_bound_size + 1) { lower_bound_size = 0; sort_idx++; continue; } new_sizes = sizes; int sz_to_try; if (hint_sizes.size() > 0 && lower_bound_size < hint_sizes[sort_idx] && hint_sizes[sort_idx] < sizes[sort_idx]) { sz_to_try = hint_sizes[sort_idx]; } else { int dumbBound = 9; if (lower_bound_size < dumbBound && dumbBound * 2 < sizes[sort_idx]) { sz_to_try = dumbBound; } else { sz_to_try = (lower_bound_size + sizes[sort_idx]) / 2; } } new_sizes[sort_idx] = sz_to_try; } cout << "trying sizes: "; for (int k : new_sizes) cout << k << " "; cout << endl; cout.flush(); solver.push(); for (int i = 0; i < (int)sorts.size(); i++) { smt::sort so = bgctx.getUninterpretedSort(sorts[i]); smt::expr_vector vec(ctx); smt::expr elem = ctx.bound_var(name("valvar").c_str(), so); for (int j = 0; j < new_sizes[i]; j++) { smt::expr c = ctx.var(name("val").c_str(), so); vec.push_back(elem == c); } smt::expr_vector qvars(ctx); qvars.push_back(elem); solver.add(smt::forall(qvars, mk_or(vec))); } solver.set_log_info("extract minimal"); smt::SolverResult res = solver.check_result(); if (res == smt::SolverResult::Sat) { all_models.clear(); for (auto e : es) { all_models.push_back(extract_model_from_z3(ctx, solver, module, *e)); } //sizes = new_sizes; shared_ptr<Model> model0 = all_models[0]; for (int j = 0; j < (int)sorts.size(); j++) { sizes[j] = model0->get_domain_size(sorts[j]); assert (sizes[j] <= new_sizes[j]); } cout << "got sizes: "; for (int k : sizes) cout << k << " "; cout << endl; cout.flush(); try_hint_sizes = false; } else { if (try_hint_sizes) { try_hint_sizes = false; } else { if (res == smt::SolverResult::Unknown) { // Stop trying to decrease the size of this domain, // it's unlikely to be worth it. lower_bound_size = sizes[sort_idx] - 1; } else { lower_bound_size = new_sizes[sort_idx]; } } } solver.pop(); } return all_models; } shared_ptr<Model> Model::extract_model_from_z3( smt::context& ctx, smt::solver& solver, std::shared_ptr<Module> module, ModelEmbedding const& e) { if (is_z3_context(ctx)) { return extract_z3(ctx, solver, module, e); } else { return extract_cvc4(ctx, solver, module, e); } } void Model::dump_sizes() const { cout << "Model sizes: "; bool start = true; for (string sort : module->sorts) { int domain_size = (int) get_domain_size(sort); if (!start) { cout << ", "; } cout << sort << ": " << domain_size; start = false; } cout << endl; cout.flush(); } void Model::dump() const { printf("Model:\n\n"); for (string sort : module->sorts) { int domain_size = (int) get_domain_size(sort); printf("%s: %d\n", sort.c_str(), domain_size); } printf("\n"); for (VarDecl decl : module->functions) { iden name = decl.name; FunctionInfo const& finfo = get_function_info(name); size_t num_args; Sort* range_sort; vector<Sort*> domain_sorts; if (FunctionSort* functionSort = dynamic_cast<FunctionSort*>(decl.sort.get())) { num_args = functionSort->domain.size(); range_sort = functionSort->range.get(); for (auto ptr : functionSort->domain) { Sort* argsort = ptr.get(); domain_sorts.push_back(argsort); } } else { num_args = 0; range_sort = decl.sort.get(); } printf("%s(default) -> %s\n", iden_to_string(name).c_str(), obj_to_string(range_sort, finfo.else_value).c_str()); vector<object_value> args; for (int i = 0; i < (int)num_args; i++) { args.push_back(0); } while (true) { FunctionTable* ftable = finfo.table.get(); for (int i = 0; i < (int)num_args; i++) { if (ftable == NULL) break; ftable = ftable->children[args[i]].get(); } if (ftable != NULL) { object_value res = ftable->value; printf("%s(", iden_to_string(name).c_str()); for (int i = 0; i < (int)num_args; i++) { if (i > 0) { printf(", "); } printf("%s", obj_to_string(domain_sorts[i], args[i]).c_str()); } printf(") -> %s\n", obj_to_string(range_sort, res).c_str()); } int i; for (i = num_args - 1; i >= 0; i--) { args[i]++; if (args[i] == get_domain_size(domain_sorts[i])) { args[i] = 0; } else { break; } } if (i == -1) { break; } } printf("\n"); } } string Model::obj_to_string(Sort* sort, object_value ov) const { if (dynamic_cast<BooleanSort*>(sort)) { if (ov == 0) { return "false"; } if (ov == 1) { return "true"; } assert(false); } else if (UninterpretedSort* usort = dynamic_cast<UninterpretedSort*>(sort)) { auto iter = sort_info.find(usort->name); assert(iter != sort_info.end()); SortInfo sinfo = iter->second; assert(0 <= ov && ov < sinfo.domain_size); return usort->name + ":" + to_string(ov + 1); } else { assert(false && "expected boolean sort or uninterpreted sort"); } } size_t Model::get_domain_size(Sort* s) const { if (dynamic_cast<BooleanSort*>(s)) { return 2; } else if (UninterpretedSort* usort = dynamic_cast<UninterpretedSort*>(s)) { return get_domain_size(usort->name); } else { assert(false && "expected boolean sort or uninterpreted sort"); } } size_t Model::get_domain_size(std::string name) const { auto iter = sort_info.find(name); assert(iter != sort_info.end()); return iter->second.domain_size; } size_t Model::get_domain_size(lsort s) const { return this->get_domain_size(s.get()); } FunctionInfo const& Model::get_function_info(iden name) const { auto iter = function_info.find(name); assert(iter != function_info.end()); return iter->second; } void Model::assert_model_is(shared_ptr<ModelEmbedding> e) { assert_model_is_or_isnt(e, true, false); } void Model::assert_model_is_not(shared_ptr<ModelEmbedding> e) { assert_model_is_or_isnt(e, true, true); } void Model::assert_model_does_not_have_substructure(shared_ptr<ModelEmbedding> e) { assert_model_is_or_isnt(e, false, true); } void Model::assert_model_is_or_isnt(shared_ptr<ModelEmbedding> e, bool exact, bool negate) { BackgroundContext& bgctx = *e->ctx; smt::solver& solver = bgctx.solver; unordered_map<string, smt::expr_vector> consts; smt::expr_vector assertions(bgctx.ctx); for (auto p : this->sort_info) { string sort_name = p.first; SortInfo sinfo = p.second; smt::sort so = bgctx.getUninterpretedSort(sort_name); smt::expr_vector vec(bgctx.ctx); for (int i = 0; i < (int)sinfo.domain_size; i++) { vec.push_back(bgctx.ctx.var(name(sort_name + "_val").c_str(), so)); } for (int i = 0; i < (int)vec.size(); i++) { for (int j = i+1; j < (int)vec.size(); j++) { assertions.push_back(vec[i] != vec[j]); } } if (exact) { smt::expr elem = bgctx.ctx.bound_var(name(sort_name).c_str(), so); smt::expr_vector eqs(bgctx.ctx); for (int i = 0; i < (int)vec.size(); i++) { eqs.push_back(vec[i] == elem); } smt::expr_vector qvars(bgctx.ctx); qvars.push_back(elem); assertions.push_back(smt::forall(qvars, mk_or(eqs))); } consts.insert(make_pair(sort_name, vec)); } auto mkExpr = [&bgctx, &consts](Sort* so, object_value val) { if (dynamic_cast<BooleanSort*>(so)) { return bgctx.ctx.bool_val((bool)val); } else if (UninterpretedSort* usort = dynamic_cast<UninterpretedSort*>(so)) { auto iter = consts.find(usort->name); assert(iter != consts.end()); assert(0 <= val && val < iter->second.size()); return iter->second[val]; } else { assert(false); } }; for (VarDecl decl : module->functions) { iden name = decl.name; FunctionInfo const& finfo = get_function_info(name); size_t num_args; Sort* range_sort; vector<Sort*> domain_sorts; if (FunctionSort* functionSort = dynamic_cast<FunctionSort*>(decl.sort.get())) { num_args = functionSort->domain.size(); range_sort = functionSort->range.get(); for (auto ptr : functionSort->domain) { Sort* argsort = ptr.get(); domain_sorts.push_back(argsort); } } else { num_args = 0; range_sort = decl.sort.get(); } vector<object_value> args; for (int i = 0; i < (int)num_args; i++) { args.push_back(0); } while (true) { object_value res = finfo.else_value; FunctionTable* ftable = finfo.table.get(); for (int i = 0; i < (int)num_args; i++) { if (ftable == NULL) break; ftable = ftable->children[args[i]].get(); } if (ftable != NULL) { res = ftable->value; } smt::expr_vector z3_args(bgctx.ctx); for (int i = 0; i < (int)domain_sorts.size(); i++) { z3_args.push_back(mkExpr(domain_sorts[i], args[i])); } assertions.push_back(e->getFunc(name).call(z3_args) == mkExpr(range_sort, res)); int i; for (i = num_args - 1; i >= 0; i--) { args[i]++; if (args[i] == get_domain_size(domain_sorts[i])) { args[i] = 0; } else { break; } } if (i == -1) { break; } } } if (negate) { solver.add(!smt::mk_and(assertions)); } else { solver.add(smt::mk_and(assertions)); } //printf("'%s'\n", solver.to_smt2().c_str()); } shared_ptr<Model> transition_model( smt::context& ctx, shared_ptr<Module> module, std::shared_ptr<Model> start_state, int which_action ) { shared_ptr<BackgroundContext> bgctx = make_shared<BackgroundContext>(ctx, module); smt::solver& solver = bgctx->solver; shared_ptr<ModelEmbedding> e1 = ModelEmbedding::makeEmbedding(bgctx, module); shared_ptr<Action> action; if (which_action == -1) { // allow any action action.reset(new ChoiceAction(module->actions)); } else { assert(0 <= which_action && which_action < (int)module->actions.size()); action = module->actions[which_action]; } ActionResult res = applyAction(e1, action, std::unordered_map<iden, smt::expr> {}); shared_ptr<ModelEmbedding> e2 = res.e; // Add the relation between the two states solver.add(res.constraint); // Add the axioms for (shared_ptr<Value> axiom : module->axioms) { solver.add(e1->value2expr(axiom, std::unordered_map<iden, smt::expr> {})); } start_state->assert_model_is(e1); if (solver.check_sat()) { return Model::extract_model_from_z3(ctx, solver, module, *e2); } else { return nullptr; } } void get_tree_of_models_( smt::context& ctx, shared_ptr<Module> module, std::shared_ptr<Model> start_state, int depth, vector<shared_ptr<Model>>& res ) { res.push_back(start_state); if (depth == 0) { return; } for (int i = 0; i < (int)module->actions.size(); i++) { shared_ptr<Model> next_state = transition_model(ctx, module, start_state, i); if (next_state != nullptr) { get_tree_of_models_(ctx, module, next_state, depth - 1, res); } } } vector<shared_ptr<Model>> get_tree_of_models( smt::context& ctx, shared_ptr<Module> module, std::shared_ptr<Model> start_state, int depth ) { vector<shared_ptr<Model>> res; get_tree_of_models_(ctx, module, start_state, depth, res); return res; } void get_tree_of_models2_( smt::context& z3ctx, shared_ptr<Module> module, vector<int> action_indices, int depth, int multiplicity, bool reversed, // find bad models starting at NOT(safety condition) vector<shared_ptr<Model>>& res ) { shared_ptr<BackgroundContext> ctx = make_shared<BackgroundContext>(z3ctx, module); smt::solver& solver = ctx->solver; shared_ptr<ModelEmbedding> e1 = ModelEmbedding::makeEmbedding(ctx, module); shared_ptr<ModelEmbedding> e2 = e1; vector<int> action_indices_ordered = action_indices; if (reversed) { reverse(action_indices_ordered.begin(), action_indices_ordered.end()); } for (int action_index : action_indices_ordered) { ActionResult res = applyAction(e2, module->actions[action_index], std::unordered_map<iden, smt::expr> {}); e2 = res.e; ctx->solver.add(res.constraint); } // Add the axioms for (shared_ptr<Value> axiom : module->axioms) { ctx->solver.add(e1->value2expr(axiom, std::unordered_map<iden, smt::expr> {})); } if (!reversed) { // Add initial conditions for (shared_ptr<Value> init : module->inits) { ctx->solver.add(e1->value2expr(init)); } } else { // Add the opposite of the safety condition ctx->solver.add(e2->value2expr(v_not(v_and(module->conjectures)))); } bool found_any = false; for (int j = 0; j < multiplicity; j++) { if (!solver.check_sat()) { break; } else { auto model = Model::extract_model_from_z3(z3ctx, solver, module, reversed ? *e1 : *e2); res.push_back(model); found_any = true; model->assert_model_is_not(reversed ? e1 : e2); } } // recurse if (found_any) { if ((int)action_indices.size() < depth) { action_indices.push_back(0); for (int i = 0; i < (int)module->actions.size(); i++) { action_indices[action_indices.size() - 1] = i; get_tree_of_models2_(z3ctx, module, action_indices, depth, multiplicity, reversed, res); } } } } vector<shared_ptr<Model>> get_tree_of_models2( smt::context& ctx, shared_ptr<Module> module, int depth, int multiplicity, bool reversed // find bad models instead of good ones (starting at NOT(safety condition)) ) { vector<shared_ptr<Model>> res; get_tree_of_models2_(ctx, module, {}, depth, multiplicity, reversed, res); return res; } /* Z3VarSet add_existential_constraint( shared_ptr<ModelEmbedding> me, value v) { shared_ptr<BackgroundContext> bgctx = me->ctx; smt::context& ctx = bgctx->ctx; smt::solver& solver = bgctx->solver; // Change NOT(forall ...) into a (exists ...) if (Not* n = dynamic_cast<Not*>(v.get())) { v = n->val->negate(); } Z3VarSet res; unordered_map<iden, smt::expr> vars; Exists* exists; while ((exists = dynamic_cast<Exists*>(v.get())) != NULL) { for (VarDecl decl : exists->decls) { smt::func_decl fd = ctx.function(name(decl.name).c_str(), 0, 0, bgctx->getSort(decl.sort)); smt::expr e = fd(); res.vars.push_back(e); vars.insert(make_pair(decl.name, e)); } v = exists->body; } solver.add(me->value2expr_with_vars(v, vars)); return res; } QuantifierInstantiation z3_var_set_2_quantifier_instantiation( Z3VarSet const&, smt::solver&, std::shared_ptr<Model>, value v) { QuantifierInstantiation qi; qi.non_null = true; qi.formula = v; qi. } */ bool eval_qi(QuantifierInstantiation const& qi, value v) { assert(qi.non_null); vector<iden> names; for (VarDecl const& decl : qi.decls) { names.push_back(decl.name); } EvalExpr ee = qi.model->value_to_eval_expr(v, names); int n_vars = max(max_var(ee), (int)qi.variable_values.size()) + 1; int* var_values = new int[n_vars]; for (int i = 0; i < (int)qi.variable_values.size(); i++) { var_values[i] = qi.variable_values[i]; } int ans = eval(ee, var_values); delete[] var_values; return ans == 1; } BitsetEvalResult BitsetEvalResult::eval_over_foralls(shared_ptr<Model> model, value val) { //model->dump(); //cout << "eval'ing for value: " << val->to_string() << endl; auto p = get_tqd_and_body(val); TopQuantifierDesc const& tqd = p.first; value bodyval = p.second; vector<VarDecl> decls = tqd.decls(); vector<iden> names; for (VarDecl const& decl : decls) { names.push_back(decl.name); } EvalExpr ee = model->value_to_eval_expr(bodyval, names); int n_vars = max(max_var(ee), (int)decls.size()) + 1; int* var_values = new int[n_vars]; BitsetEvalResult ber; vector<int> max_sizes; max_sizes.resize(decls.size()); for (int i = 0; i < (int)decls.size(); i++) { max_sizes[i] = model->get_domain_size(decls[i].sort); var_values[i] = 0; } uint64_t cur = 0; int bit_place = 0; while (true) { //cout << "bp: " << bit_place << endl; int ans = eval(ee, var_values); assert(ans == 0 || ans == 1); cur |= ((uint64_t)ans << bit_place); bit_place++; if (bit_place == 64) { ber.v.push_back(cur); cur = 0; bit_place = 0; } int i; for (i = 0; i < (int)decls.size(); i++) { var_values[i]++; if (var_values[i] == max_sizes[i]) { var_values[i] = 0; } else { break; } } if (i == (int)decls.size()) { break; } } if (bit_place > 0) { ber.v.push_back(cur); ber.last_bits = ((uint64_t)1 << bit_place) - 1; } else { ber.last_bits = (uint64_t)(-1); } delete[] var_values; //ber.dump(); return ber; } AlternationBitsetEvaluator AlternationBitsetEvaluator::make_evaluator( std::shared_ptr<Model> model, value v) { TopAlternatingQuantifierDesc taqd(v); vector<int> sizes; vector<Alternation> alternations = taqd.alternations(); if (alternations.size() == 0) { Alternation alt; alt.altType = AltType::Forall; alternations.push_back(alt); } for (Alternation const& alt : alternations) { int prod = 1; for (VarDecl const& decl : alt.decls) { prod *= model->get_domain_size(decl.sort); } sizes.push_back(prod); } AlternationBitsetEvaluator abe; abe.levels.resize(sizes.size() - 1); int p = 1; for (int i = 0; i < (int)sizes.size() - 1; i++) { p *= sizes[i]; abe.levels[abe.levels.size() - 1 - i].block_size = p; abe.levels[abe.levels.size() - 1 - i].num_blocks = sizes[i+1]; abe.levels[abe.levels.size() - 1 - i].conj = alternations[i+1].is_forall(); } p *= sizes[sizes.size() - 1]; abe.scratch.resize(p / 64 + 2); abe.final_conj = alternations[0].is_forall(); if (sizes[0] % 64 == 0) { abe.final_num_full_words_64 = sizes[0] / 64 - 1; abe.final_last_bits = (uint64_t)(-1); } else { abe.final_num_full_words_64 = sizes[0] / 64; abe.final_last_bits = (((uint64_t)1) << (sizes[0] % 64)) - 1; } if (p % 64 == 0) { abe.last_bits = (uint64_t)(-1); } else { abe.last_bits = (((uint64_t)1) << (p % 64)) - 1; } return abe; } BitsetEvalResult BitsetEvalResult::eval_over_alternating_quantifiers( shared_ptr<Model> model, value val) { //model->dump(); //cout << "eval'ing for value: " << val->to_string() << endl; TopAlternatingQuantifierDesc taqd(val); value bodyval = taqd.get_body(val); vector<Alternation> alternations = taqd.alternations(); vector<VarDecl> decls; for (int i = alternations.size() - 1; i >= 0; i--) { Alternation const& alt = alternations[i]; for (int j = 0; j < (int)alt.decls.size(); j++) { decls.push_back(alt.decls[j]); } } vector<iden> names; for (VarDecl const& decl : decls) { names.push_back(decl.name); } EvalExpr ee = model->value_to_eval_expr(bodyval, names); int n_vars = max(max_var(ee), (int)decls.size()) + 1; int* var_values = new int[n_vars]; BitsetEvalResult ber; vector<int> max_sizes; max_sizes.resize(decls.size()); for (int i = 0; i < (int)decls.size(); i++) { max_sizes[i] = model->get_domain_size(decls[i].sort); var_values[i] = 0; } uint64_t cur = 0; int bit_place = 0; while (true) { //cout << "bp: " << bit_place << endl; int ans = eval(ee, var_values); assert(ans == 0 || ans == 1); cur |= ((uint64_t)ans << bit_place); bit_place++; if (bit_place == 64) { ber.v.push_back(cur); cur = 0; bit_place = 0; } int i; for (i = (int)decls.size() - 1; i >= 0; i--) { var_values[i]++; if (var_values[i] == max_sizes[i]) { var_values[i] = 0; } else { break; } } if (i == -1) { break; } } if (bit_place > 0) { ber.v.push_back(cur); ber.last_bits = ((uint64_t)1 << bit_place) - 1; } else { ber.last_bits = (uint64_t)(-1); } delete[] var_values; //ber.dump(); return ber; } vector<size_t> Model::get_domain_sizes_for_function(iden name) const { lsort sort; for (VarDecl decl : module->functions) { if (decl.name == name) { sort = decl.sort; break; } } assert(sort != nullptr); vector<size_t> domain_sizes; if (FunctionSort* functionSort = dynamic_cast<FunctionSort*>(sort.get())) { for (auto so : functionSort->domain) { domain_sizes.push_back(get_domain_size(so)); } } return domain_sizes; } object_value Model::func_eval(iden name, std::vector<object_value> const& args) { FunctionInfo const& finfo = get_function_info(name); FunctionTable* ftable = finfo.table.get(); for (int i = 0; i < (int)args.size(); i++) { if (ftable == NULL) break; assert (args[i] < ftable->children.size()); ftable = ftable->children[args[i]].get(); } if (ftable != NULL) { assert (ftable->children.size() == 0); return ftable->value; } else { return finfo.else_value; } } std::vector<FunctionEntry> Model::getFunctionEntries(iden name) { vector<FunctionEntry> entries; lsort sort; for (VarDecl decl : module->functions) { if (decl.name == name) { sort = decl.sort; break; } } assert(sort != nullptr); FunctionInfo const& finfo = get_function_info(name); size_t num_args; Sort* range_sort; vector<Sort*> domain_sorts; if (FunctionSort* functionSort = dynamic_cast<FunctionSort*>(sort.get())) { num_args = functionSort->domain.size(); range_sort = functionSort->range.get(); for (auto ptr : functionSort->domain) { Sort* argsort = ptr.get(); domain_sorts.push_back(argsort); } } else { num_args = 0; range_sort = sort.get(); } vector<object_value> args; for (int i = 0; i < (int)num_args; i++) { args.push_back(0); } while (true) { FunctionEntry entry; FunctionTable* ftable = finfo.table.get(); for (int i = 0; i < (int)num_args; i++) { if (ftable == NULL) break; ftable = ftable->children[args[i]].get(); } for (int i = 0; i < (int)num_args; i++) { entry.args.push_back(args[i]); } if (ftable != NULL) { entry.res = ftable->value; } else { entry.res = finfo.else_value; } entries.push_back(entry); int i; for (i = num_args - 1; i >= 0; i--) { args[i]++; if (args[i] == get_domain_size(domain_sorts[i])) { args[i] = 0; } else { break; } } if (i == -1) { break; } } return entries; } Json Model::to_json() const { map<string, Json> o_sort_info; for (auto& p : sort_info) { o_sort_info.insert(make_pair(p.first, Json((int)p.second.domain_size))); } Json j_sort_info = Json(o_sort_info); map<string, Json> o_function_info; for (auto& p : function_info) { o_function_info.insert(make_pair(iden_to_string(p.first), p.second.to_json())); } Json j_function_info = Json(o_function_info); map<string, Json> o; o.insert(make_pair("sorts", j_sort_info)); o.insert(make_pair("functions", j_function_info)); return Json(o); } shared_ptr<Model> Model::from_json(Json j, shared_ptr<Module> module) { std::unordered_map<std::string, SortInfo> sort_info; std::unordered_map<iden, FunctionInfo> function_info; Json j_sort_info = j["sorts"]; Json j_func_info = j["functions"]; assert(j_sort_info.is_object()); assert(j_func_info.is_object()); for (auto p : j_sort_info.object_items()) { Json j = p.second; assert(j.is_number()); SortInfo si; si.domain_size = j.int_value(); sort_info.insert(make_pair(p.first, si)); } for (auto p : j_func_info.object_items()) { Json j = p.second; function_info.insert(make_pair(string_to_iden(p.first), FunctionInfo::from_json(j))); } return shared_ptr<Model>(new Model(module, move(sort_info), move(function_info))); } Json FunctionInfo::to_json() const { map<string, Json> o; o.insert(make_pair("else", Json((int)else_value))); o.insert(make_pair("table", table == nullptr ? Json() : table->to_json())); return Json(o); } FunctionInfo FunctionInfo::from_json(Json j) { assert(j.is_object()); FunctionInfo fi; assert(j["else"].is_number()); fi.else_value = (object_value) j["else"].int_value(); fi.table = FunctionTable::from_json(j["table"]); return fi; } Json FunctionTable::to_json() const { if (children.size() > 0) { vector<Json> v; for (auto& ftable : children) { v.push_back(ftable == nullptr ? Json() : ftable->to_json()); } return Json(v); } else { return Json((int)value); } } unique_ptr<FunctionTable> FunctionTable::from_json(Json j) { unique_ptr<FunctionTable> ft; if (j.is_null()) { return ft; } else if (j.is_array()) { ft.reset(new FunctionTable()); for (Json j1 : j.array_items()) { ft->children.push_back(FunctionTable::from_json(j1)); } } else { ft.reset(new FunctionTable()); assert(j.is_number()); ft->value = (object_value) j.int_value(); } return ft; } <file_sep>/src/top_quantifier_desc.h #ifndef TOP_QUANTIFIER_DESC_H #define TOP_QUANTIFIER_DESC_H #include "logic.h" enum class QType { Forall, NearlyForall, Exists, }; struct QRange { int start, end; std::vector<VarDecl> decls; QType qtype; }; struct QSRange { int start, end; std::vector<VarDecl> decls; QType qtype; lsort sort; }; class TopQuantifierDesc { public: TopQuantifierDesc(value); std::vector<VarDecl> decls() const; std::vector<QRange> with_foralls_grouped() const; std::vector<QRange> with_foralls_ungrouped() const; std::vector<QSRange> grouped_by_sort() const; value with_body(value body) const; int weighted_sort_count(std::string sort) const; //value rename_into(value); std::vector<value> rename_into_all_possibilities(value); private: std::vector<std::pair<QType, std::vector<VarDecl>>> d; }; std::pair<TopQuantifierDesc, value> get_tqd_and_body(value); enum class AltType { Forall, Exists, }; struct Alternation { AltType altType; std::vector<VarDecl> decls; bool is_forall() const { return altType == AltType::Forall; } bool is_exists() const { return altType == AltType::Exists; } }; class TopAlternatingQuantifierDesc { public: TopAlternatingQuantifierDesc(value v); std::vector<Alternation> alternations() { return alts; } static value get_body(value); value with_body(value); std::vector<QSRange> grouped_by_sort() const; TopAlternatingQuantifierDesc replace_exists_with_forall() const; //value rename_into(value); // Given this = forall A: node, B: node, C: node ... // and value = forall X: node, Y: node . f(X) & g(Y) // returns { // forall A: node, B: node, C: node . f(A) & g(B) // forall A: node, B: node, C: node . f(A) & g(C) // forall A: node, B: node, C: node . f(B) & g(C) // } std::vector<value> rename_into_all_possibilities(value); private: std::vector<Alternation> alts; TopAlternatingQuantifierDesc() { } //friend value rename_into(std::vector<Alternation> const& alts, value v); friend class TopQuantifierDesc; void rename_into_all_possibilities_rec( TopAlternatingQuantifierDesc const& v_taqd, int v_idx, int v_inner_idx, int this_idx, int this_inner_idx, value const& body, std::map<iden, iden>& var_map, std::vector<value>& results); }; std::pair<TopAlternatingQuantifierDesc, value> get_taqd_and_body(value); #endif <file_sep>/src/smt_cvc4.cpp #include "smt.h" #include <cvc4/cvc4.h> #include <cassert> #include <iostream> #include <string> #include <vector> #include "benchmarking.h" #include "model.h" #include "stats.h" using namespace std; using smt::_sort; using smt::_expr; using smt::_func_decl; using smt::_solver; using smt::_context; using smt::_expr_vector; using smt::_sort_vector; namespace smt_cvc4 { bool been_set; struct sort : public _sort { CVC4::Type ty; sort(CVC4::Type ty) : ty(ty) { } }; struct expr : public _expr { CVC4::Expr ex; expr(CVC4::Expr e) : ex(e) { } std::shared_ptr<_expr> equals(_expr* _a) const override { expr* a = dynamic_cast<expr*>(_a); assert(a != NULL); return shared_ptr<_expr>(new expr(ex.eqExpr(a->ex))); } std::shared_ptr<_expr> not_equals(_expr* _a) const override { expr* a = dynamic_cast<expr*>(_a); assert(a != NULL); return shared_ptr<_expr>(new expr(ex.eqExpr(a->ex).notExpr())); } std::shared_ptr<_expr> logic_negate() const override { return shared_ptr<_expr>(new expr(ex.notExpr())); } std::shared_ptr<_expr> logic_or(_expr* _a) const override { expr* a = dynamic_cast<expr*>(_a); assert(a != NULL); return shared_ptr<_expr>(new expr(ex.orExpr(a->ex))); } std::shared_ptr<_expr> logic_and(_expr* _a) const override { expr* a = dynamic_cast<expr*>(_a); assert(a != NULL); return shared_ptr<_expr>(new expr(ex.andExpr(a->ex))); } std::shared_ptr<_expr> ite(_expr* _b, _expr* _c) const override { expr* b = dynamic_cast<expr*>(_b); assert(b != NULL); expr* c = dynamic_cast<expr*>(_c); assert(c != NULL); CVC4::ExprManager* em = ex.getExprManager(); return shared_ptr<_expr>(new expr( em->mkExpr(CVC4::kind::ITE, ex, b->ex, c->ex) )); } std::shared_ptr<_expr> implies(_expr* _b) const override { expr* b = dynamic_cast<expr*>(_b); assert(b != NULL); CVC4::ExprManager* em = ex.getExprManager(); return shared_ptr<_expr>(new expr( em->mkExpr(CVC4::kind::IMPLIES, ex, b->ex) )); } }; struct func_decl : _func_decl { CVC4::Expr ex; CVC4::FunctionType ft; bool is_nullary; func_decl(CVC4::Expr ex, CVC4::FunctionType ft, bool is_nullary) : ex(ex), ft(ft), is_nullary(is_nullary) { } size_t arity() override { return ft.getArity(); } shared_ptr<_sort> domain(int i) override { return shared_ptr<_sort>(new sort(ft.getArgTypes()[i])); } shared_ptr<_sort> range() override { return shared_ptr<_sort>(new sort(ft.getRangeType())); } shared_ptr<_expr> call(_expr_vector* args) override; shared_ptr<_expr> call() override; std::string get_name() override { return "func_decl::get_name unimplemented"; } bool eq(_func_decl* _b) override { func_decl* b = dynamic_cast<func_decl*>(_b); assert (b != NULL); return ex == b->ex; } }; struct context : _context { CVC4::ExprManager em; bool been_set; int timeout_ms; context() : been_set(false), timeout_ms(-1) { } void set_timeout(int ms) override { timeout_ms = ms; //ctx.set("timeout", ms); //assert (false && "set_timeout not implemented"); } shared_ptr<_sort> bool_sort() override { return shared_ptr<_sort>(new sort(em.booleanType())); } shared_ptr<_expr> bool_val(bool b) override { return shared_ptr<_expr>(new expr(em.mkConst(b))); } shared_ptr<_sort> uninterpreted_sort(std::string const& name) override { return shared_ptr<_sort>(new sort(em.mkSort(name))); } std::shared_ptr<_func_decl> function( std::string const& name, _sort_vector* domain, _sort* range) override; std::shared_ptr<_func_decl> function( std::string const& name, _sort* range) override; std::shared_ptr<_expr> var( std::string const& name, _sort* range) override; std::shared_ptr<_expr> bound_var( std::string const& name, _sort* so) override; std::shared_ptr<_expr_vector> new_expr_vector() override; std::shared_ptr<_sort_vector> new_sort_vector() override; std::shared_ptr<_solver> make_solver() override; }; struct sort_vector : _sort_vector { std::vector<CVC4::Type> so_vec; sort_vector(context& ctx) { } void push_back(_sort* _s) override { sort* s = dynamic_cast<sort*>(_s); assert (s != NULL); so_vec.push_back(s->ty); } size_t size() override { return so_vec.size(); } std::shared_ptr<_sort> get_at(int i) override { return shared_ptr<_sort>(new sort(so_vec[i])); } }; struct expr_vector : _expr_vector { std::vector<CVC4::Expr> ex_vec; CVC4::ExprManager* em; expr_vector(context& ctx) : em(&ctx.em) { } void push_back(_expr* _s) override { expr* s = dynamic_cast<expr*>(_s); assert (s != NULL); ex_vec.push_back(s->ex); } size_t size() override { return ex_vec.size(); } std::shared_ptr<_expr> get_at(int i) override { return shared_ptr<_expr>(new expr(ex_vec[i])); } std::shared_ptr<_expr> forall(_expr* _body) override { expr* body = dynamic_cast<expr*>(_body); assert (body != NULL); CVC4::Expr var_list = em->mkExpr( CVC4::kind::BOUND_VAR_LIST, ex_vec); return shared_ptr<_expr>(new expr( em->mkExpr(CVC4::kind::FORALL, var_list, body->ex) )); } std::shared_ptr<_expr> exists(_expr* _body) override { expr* body = dynamic_cast<expr*>(_body); assert (body != NULL); CVC4::Expr var_list = em->mkExpr( CVC4::kind::BOUND_VAR_LIST, ex_vec); return shared_ptr<_expr>(new expr( em->mkExpr(CVC4::kind::EXISTS, var_list, body->ex) )); } std::shared_ptr<_expr> mk_and() override { if (size() == 0) { return shared_ptr<_expr>(new expr( em->mkConst(true) )); } else if (size() == 1) { return shared_ptr<_expr>(new expr( ex_vec[0] )); } else { return shared_ptr<_expr>(new expr( em->mkExpr(CVC4::kind::AND, ex_vec) )); } } std::shared_ptr<_expr> mk_or() override { if (size() == 0) { return shared_ptr<_expr>(new expr( em->mkConst(false) )); } else if (size() == 1) { return shared_ptr<_expr>(new expr( ex_vec[0] )); } else { return shared_ptr<_expr>(new expr( em->mkExpr(CVC4::kind::OR, ex_vec) )); } } }; struct solver : _solver { CVC4::SmtEngine smt; solver(context& ctx) : smt(&ctx.em) { if (ctx.timeout_ms != -1) { smt.setTimeLimit(ctx.timeout_ms); } if (!ctx.been_set) { smt.setOption("produce-models", true); ctx.been_set = true; } smt.setOption("finite-model-find", true); } //void enable_models() { //smt.setOption("produce-models", true); //} smt::SolverResult check_result() override; void push() override { smt.push(); } void pop() override { smt.pop(); } void add(_expr* _e) override { expr* e = dynamic_cast<expr*>(_e); assert (e != NULL); smt.assertFormula(e->ex); } void dump(ofstream&) override; }; shared_ptr<_expr> func_decl::call(_expr_vector* _args) { expr_vector* args = dynamic_cast<expr_vector*>(_args); assert (args != NULL); assert (args->size() == ft.getArgTypes().size()); if (args->size() == 0) { return call(); } else { assert (!is_nullary); CVC4::ExprManager* em = args->em; return shared_ptr<_expr>(new expr( em->mkExpr(CVC4::kind::APPLY_UF, this->ex, args->ex_vec) )); } } shared_ptr<_expr> func_decl::call() { assert (is_nullary); return shared_ptr<_expr>(new expr(this->ex)); } shared_ptr<_func_decl> context::function( std::string const& name, _sort_vector* _domain, _sort* _range) { if (_domain->size() == 0) { return function(name, _range); } else { sort_vector* domain = dynamic_cast<sort_vector*>(_domain); assert (domain != NULL); sort* range = dynamic_cast<sort*>(_range); assert (range != NULL); CVC4::FunctionType ft = em.mkFunctionType(domain->so_vec, range->ty); return shared_ptr<_func_decl>(new func_decl(em.mkVar(name, ft), ft, false)); } } shared_ptr<_func_decl> context::function( std::string const& name, _sort* _range) { sort* range = dynamic_cast<sort*>(_range); assert (range != NULL); std::vector<CVC4::Type> vec; CVC4::FunctionType ft = em.mkFunctionType(vec, range->ty); return shared_ptr<_func_decl>( new func_decl(em.mkVar(name, range->ty), ft, true) ); } shared_ptr<_expr> context::var( std::string const& name, _sort* _so) { sort* so = dynamic_cast<sort*>(_so); assert (so != NULL); return shared_ptr<_expr>(new expr(em.mkVar(name, so->ty))); } shared_ptr<_expr> context::bound_var( std::string const& name, _sort* _so) { sort* so = dynamic_cast<sort*>(_so); assert (so != NULL); return shared_ptr<_expr>(new expr(em.mkBoundVar(name, so->ty))); } std::shared_ptr<_solver> context::make_solver() { return shared_ptr<_solver>(new solver(*this)); } std::shared_ptr<_expr_vector> context::new_expr_vector() { return shared_ptr<_expr_vector>(new expr_vector(*this)); } std::shared_ptr<_sort_vector> context::new_sort_vector() { return shared_ptr<_sort_vector>(new sort_vector(*this)); } } namespace smt { std::shared_ptr<_context> make_cvc4_context() { return shared_ptr<_context>(new smt_cvc4::context()); } } //////////////////// ///// Model stuff shared_ptr<Model> Model::extract_cvc4( smt::context& smt_ctx, smt::solver& smt_solver, std::shared_ptr<Module> module, ModelEmbedding const& e) { smt_cvc4::context& ctx = *dynamic_cast<smt_cvc4::context*>(smt_ctx.p.get()); smt_cvc4::solver& solver = *dynamic_cast<smt_cvc4::solver*>(smt_solver.p.get()); CVC4::ExprManager& em = ctx.em; CVC4::SmtEngine& smt = solver.smt; // The cvc4 API, at least at the time of writing, does // not appear to expose any way of accessing the model. // We use a version with some modifications I made to expose // the Model interface. // Since the Model interface isn't intended to be exposed, // it's a little hard to use, and it segfaults if you don't // create an SmtScope object (whatever that is), which took // me a while to figure out. The SmtScope object *also* isn't // exposed, so I also modified the library by adding this // SmtScopeContainer object which handles the SmtScope for us. // // tl;dr // Make sure you're using the fork of the cvc4 lib which // is checked in to this repo. CVC4::Model* cvc4_model = smt.getModel(); CVC4::SmtScopeContainer smt_scope_container(cvc4_model); //std::cout << endl; //std::cout << endl; //std::cout << endl; //std::cout << *cvc4_model << endl; //std::cout << endl; //std::cout << endl; //std::cout << endl; map<string, vector<CVC4::Expr>> universes; std::unordered_map<std::string, SortInfo> sort_info; for (auto p : e.ctx->sorts) { string name = p.first; //cout << "doing sort " << name << endl; CVC4::Type ty = dynamic_cast<smt_cvc4::sort*>(p.second.p.get())->ty; vector<CVC4::Expr> exprs = cvc4_model->getDomainElements(ty); assert (exprs.size() > 0); for (int i = 0; i < (int)exprs.size(); i++) { //cout << "e is " << e << endl; exprs[i] = cvc4_model->getValue(exprs[i]); //cout << "e' is " << cvc4_model->getValue(e) << endl; } universes.insert(make_pair(name, exprs)); SortInfo si; si.domain_size = exprs.size(); sort_info.insert(make_pair(name, si)); } std::unordered_map<iden, FunctionInfo> function_info; for (VarDecl decl : module->functions) { iden name = decl.name; //cout << "doing function " << iden_to_string(name) << endl; smt::func_decl fd = e.getFunc(name); //cout << "doing " << iden_to_string(name) << endl; function_info.insert(make_pair(name, FunctionInfo())); FunctionInfo& fi = function_info.find(name)->second; fi.else_value = 0; vector<shared_ptr<Sort>> domain = decl.sort->get_domain_as_function(); shared_ptr<Sort> range = decl.sort->get_range_as_function(); vector<size_t> domain_sizes; for (int i = 0; i < (int)domain.size(); i++) { if (dynamic_cast<BooleanSort*>(domain[i].get())) { domain_sizes.push_back(2); } else if (UninterpretedSort* us = dynamic_cast<UninterpretedSort*>(domain[i].get())) { auto it = universes.find(us->name); assert (it != universes.end()); domain_sizes.push_back(it->second.size()); } else { assert (false); } assert(domain_sizes[i] > 0); } vector<object_value> args; args.resize(domain.size()); for (int i = 0; i < (int)domain.size(); i++) { args[i] = 0; } CVC4::Expr const_true = em.mkConst(true); CVC4::Expr const_false = em.mkConst(false); while (true) { smt_cvc4::expr_vector args_exprs(ctx); for (int i = 0; i < (int)domain.size(); i++) { if (dynamic_cast<BooleanSort*>(domain[i].get())) { args_exprs.ex_vec.push_back(args[i] == 0 ? const_false : const_true); } else if (UninterpretedSort* us = dynamic_cast<UninterpretedSort*>(domain[i].get())) { auto it = universes.find(us->name); assert (it != universes.end()); assert (0 <= args[i] && args[i] < it->second.size()); args_exprs.ex_vec.push_back(it->second[args[i]]); } else { assert (false); } } auto c = dynamic_cast<smt_cvc4::func_decl*>(fd.p.get())->call(&args_exprs); CVC4::Expr result_expr = cvc4_model->getValue(dynamic_cast<smt_cvc4::expr*>(c.get())->ex); object_value result; if (dynamic_cast<BooleanSort*>(range.get())) { if (result_expr == const_true) { result = 1; } else if (result_expr == const_false) { result = 0; } else { assert (false); } } else if (UninterpretedSort* us = dynamic_cast<UninterpretedSort*>(range.get())) { auto it = universes.find(us->name); assert (it != universes.end()); vector<CVC4::Expr>& univ = it->second; bool found = false; for (int j = 0; j < (int)univ.size(); j++) { if (univ[j] == result_expr) { result = j; found = true; break; } } //cout << "result_expr " << result_expr << endl; assert (found); } else { assert (false); } if (fi.table == nullptr) { fi.table = unique_ptr<FunctionTable>(new FunctionTable()); if (0 < domain_sizes.size()) { fi.table->children.resize(domain_sizes[0]); } } FunctionTable* ft = fi.table.get(); for (int i = 0; i < (int)domain.size(); i++) { if (ft->children[args[i]] == nullptr) { ft->children[args[i]] = unique_ptr<FunctionTable>(new FunctionTable()); if (i + 1 < (int)domain.size()) { ft->children[args[i]]->children.resize(domain_sizes[i+1]); } } ft = ft->children[args[i]].get(); } ft->value = result; int i; for (i = 0; i < (int)domain.size(); i++) { args[i]++; if (args[i] == domain_sizes[i]) { args[i] = 0; } else { break; } } if (i == (int)domain.size()) { break; } } } auto result = shared_ptr<Model>(new Model(module, move(sort_info), move(function_info))); //result->dump(); return result; } extern bool enable_smt_logging; namespace smt_cvc4 { ////////////////////// ///// solving string res_to_string(CVC4::Result::Sat res) { if (res == CVC4::Result::SAT) { return "sat"; } else if (res == CVC4::Result::UNSAT) { return "unsat"; } else if (res == CVC4::Result::SAT_UNKNOWN) { return "timeout/unknown"; } else { assert(false); } } smt::SolverResult solver::check_result() { //cout << "check_sat" << endl; auto t1 = now(); CVC4::Result::Sat res = smt.checkSat().isSat(); auto t2 = now(); long long ms = as_ms(t2 - t1); smt::log_to_stdout(ms, true, log_info, res_to_string(res)); if (enable_smt_logging) { log_smtlib(ms, res_to_string(res)); } global_stats.add_cvc4(ms); if (res == CVC4::Result::SAT) return smt::SolverResult::Sat; else if (res == CVC4::Result::UNSAT) return smt::SolverResult::Unsat; return smt::SolverResult::Unknown; } void solver::dump(ofstream& of) { of << "solver::dump not implemented for cvc4" << endl; } } <file_sep>/README.md SWISS (Small World Invariant Search System) is a research system to automatically infer inductive invariants of distributed systems. It supports [IVy](https://github.com/microsoft/ivy) and the [mypyvy](https://github.com/wilcoxjay/mypyvy) protocol description formats as input. ## Setup Easiest way to run is probably with Docker. ./get-deps.sh docker build -t swiss . Then head into the container with, docker run --name swiss-c -dit swiss /bin/bash docker exec -it swiss-c /bin/bash For a manual setup, you'll need to: * Run `./get-deps.sh` * Build and install `cvc4` (use the verison installed by `get-deps.sh`; see `./cvc4/INSTALL.md`) * Install [z3](https://github.com/Z3Prover/z3). I've been using 4.8.9. You can use `./scripts/installing/install-z3.sh`. * You'll need both python2 and python3 (sorry) * `pip3 install matplotlib z3-solver networkx typing-extensions toml` * `pip2 install ply tarjan` * You can see the Dockerfile for additional information on dependencies. Run `make` to build. ## Example usage One of the easiest examples is `leader-election.ivy`. You can try it out like so: ./run.sh benchmarks/leader-election.ivy --config basic_f --threads 1 --minimal-models --with-conjs The `--config` option specifies a search space, here `basic_f`, declared in the adjacent file `leader-election.config` (along with alternate configs). For this protocol, `basic_f` is one of the fastest configurations. The `--threads` option specifies the number of concurrent processes to run. Finally, `--minimal-models` and `--with-conjs` are additional algorithm options, both recommended. (See below.) If everything is set up right, it should succeed rather quickly, printing `Success: True`. The output should include a log directory, something like `logs/log.2021-04-19_15.02.42-710190115`. To find the invariants that SWISS synthesized, check out the produced `invariants` file. # use the log directory from the program output $ cat logs/log.2021-04-19_15.02.42-710190115/invariants You'll see something like, conjecture (forall A000:node, A001:node, A002:node . ((((~(btw(A000, A001, A002))) & (~((nid(A000) = nid(A001))))) | ((~(leader(A001))) & (~(pnd(nid(A001), A000)))) | le(nid(A002), nid(A001))))) ## Command-line options Usage `./run.sh protocol_file(.ivy|.pyv) [options]` Required options: * `--config CONFIG_NAME` - search space configuration to use (name of benchmark in the `.config` file) * `--threads N` - maximum number of concurrent processes to run Optimization flags: * `--minimal-models` - (recommended) SWISS will attempt to minimize models returned by SMT solver * `--with-conjs` - (recommended) SWISS Finisher will synthesize invariants that require the safety condition to prove are inductive. If SWISS fails to complete, then the predicates that it _does_ output will not be guaranteed invariant; they will only be invariant conditioned on the safety condition being invariant. * `--breadth-with-conjs` - (recommended) Same as above, for Breadth phase. * `--by-size --non-accumulative` - (recommended) Switch off "accumulative" mode. Accumulative was the default for a while, but its value is dubious. * `--pre-bmc` - Old optimization flag, mostly a failure. Tries to improve counterexample quality using a BMC check. * `--post-bmc` - Old optimization flag, mostly a failure. Variant of the previous. Other flags: * `--seed X` - Specify an RNG seed for repeatable runs. * `--finisher-only` - Skip breadth phase. (Occasionally useful if you don't want to write a separate config entry.) * `--whole-space` - Don't exit as soon as the safety condition is proved; instead, finish the current phase to completion. This will always appear to return an unsuccessful result. It's useful for some benchmarking purposes. ## Setting up a benchmark To create a benchmark, create a `.ivy` file. The `.ivy` file should start with the line `#ivy 1.5` or `#ivy 1.6`. (Unfortunately, SWISS doesn't support later version of IVy right now). SWISS also supports the [.pyv](https://github.com/wilcoxjay/mypyvy) format. Your input file should contain conjectures that represent the safety condition. Next, create a config file (same directory, same filename with the extension replaced by `.config`). Here's an example configuration (`benchmarks/paxos.config`): [bench basic] [breadth] template forall node value value quorum round round round # d=1 k=4 template forall round value . exists quorum . forall node node # d=1 k=3 [finisher] template forall round round value value quorum . exists node # d=2 k=6 [bench auto] [breadth] auto # d=1 k=3 mvars=5 e=1 [finisher] auto # d=2 k=6 mvars=6 e=1 Each configuration includes a `breadth` config, a `finisher` config, or both. Generally, you'll want to run both for best results. (A description of these phases can be found in our paper, below.) For any phase, the config can either be a single `auto` line or multiple `template` lines. The template line specifies a template for first-order logical predicates. The `d` and `k` parameters are mandatory. * `k`: maximum number of terms in the disjunction * `d`: maximum "depth" of predicate as a syntax tree of conjunction/disjunctions. (Only supported values are `1` and `2`.) So for example, `template forall node value value quorum round round round # d=1 k=4` would represent the space of logical predicates of the form `forall N:node, V1:value, V2:value, Q:quorum, R1:round, R2:round, R3:round . a | b | c | d`. An `auto` config will generate these templates automatically, given the constraints. `k` and `d` are as above, while we also have * `mvars`: maximum number of quantified variables (including both universal and existential quantifications) * `e`: maximum number of existentially quantified variables All the templates are given in a _fixed_ nesting order of the sorts, so that the resulting verification conditions will be in [EPR](https://en.wikipedia.org/wiki/Bernays%E2%80%93Sch%C3%B6nfinkel_class). This nesting order is determined by the declaration order of the sorts in the `.ivy` or `.pyv` file. ## Publications [Finding Invariants of Distributed Systems: It’s a Small (Enough) World After All](http://www.andrew.cmu.edu/user/bparno/papers/swiss.pdf) <NAME>, <NAME>, <NAME>, and <NAME>. NSDI 2021. <file_sep>/Makefile OBJECTS = $(addprefix bin/,\ contexts.o \ logic.o \ main.o \ model.o \ benchmarking.o \ bmc.o \ enumerator.o \ utils.o \ synth_loop.o \ quantifier_permutations.o \ top_quantifier_desc.o \ strengthen_invariant.o \ model_isomorphisms.o \ wpr.o \ filter.o \ synth_enumerator.o \ obviously_implies.o \ var_lex_graph.o \ alt_synth_enumerator.o \ alt_depth2_synth_enumerator.o \ smt.o \ smt_z3.o \ smt_cvc4.o \ tree_shapes.o \ template_counter.o \ template_desc.o \ template_priority.o \ clause_gen.o \ solve.o \ auto_redundancy_filters.o \ lib/json11/json11.o \ ) LIBS = DEP_DIR = bin/deps CXXFLAGS = -g -O2 -std=c++11 -Wall -Werror -Wsign-compare -Wunused-variable #-DSMT_CVC4 all: synthesis synthesis: $(OBJECTS) $(LIBS) clang++ -g -o synthesis $(LIBPATH) $(OBJECTS) $(LIBS) -lz3 -lcvc4 -lpthread bin/%.o: src/%.cpp @mkdir -p $(basename $@) @mkdir -p $(DEP_DIR)/$(basename $<) clang++ $(CXXFLAGS) $(INCLUDES) -c -o $@ $< -MMD -MP -MF "$(DEP_DIR)/$(<:.cpp=.d)" clean: rm -rf bin synthesis # Include these files which contain all the dependencies # between the source files and the header files, so if a header # file changes, the correct things will re-compile. # rwildcard is a helper to search recursively for .d files rwildcard=$(wildcard $1$2) $(foreach d,$(wildcard $1*),$(call rwildcard,$d/,$2)) -include $(call rwildcard,$(DEP_DIR)/,*.d) <file_sep>/scripts/driver.py #!/usr/bin/env python3 import sys import os from datetime import datetime import random import subprocess import tempfile import queue import threading import traceback import json import time import random import shutil import protocol_parsing import templates import stats from stats import Stats all_procs = {} killing = False random.seed(1234) def set_seed(seed): random.seed(seed) def args_add_seed(args): return ["--seed", str(random.randint(1, 10**6))] + args def reseed(args): new_args = [] i = 0 while i < len(args): if args[i] != "--seed": new_args.append(args[i]) i += 1 else: i += 2 return args_add_seed(new_args) def kill_all_procs(): global killing if not killing: killing = True keys = all_procs.keys() for k in keys: all_procs[k].kill() class RunSynthesisResult(object): def __init__(self, run_id, seconds, stopped, failed, logfile): self.run_id = run_id self.seconds = seconds self.stopped = stopped self.failed = failed self.logfile = logfile def get_input_files(args): t = [] for i in range(len(args) - 1): if args[i] in ('--input-module', "--input-chunk-file", "--input-formula-file"): t.append(args[i+1]) return t def log_inputs(logfilename, json_filename, args): try: input_files = [json_filename] + get_input_files(args) for i in range(len(input_files)): a = input_files[i] b = logfilename + ".error." + str(i) print(a + " -> " + b) shutil.copy(input_files[i], logfilename + ".error." + str(i)) except Exception: print("failed to log_inputs") pass class PartialInvariantLogger(object): def __init__(self, logdir): self.logdir = logdir self.base = 0 self.idx = 0 def new_base(self, inv_tmp_file): self.base += 1 self.idx = 0 filename = os.path.join(self.logdir, "partial_invs." + str(self.base) + ".base") if inv_tmp_file == None: with open(filename, "w") as f: f.write("empty\n") else: shutil.copy(inv_tmp_file, filename) def new_file_for_partial(self): self.idx += 1 return os.path.join(self.logdir, "partial_invs." + str(self.base) + "." + str(self.idx)) partialInvariantLogger = None all_stats_files = [] def make_stats_file(): f = tempfile.mktemp() all_stats_files.append(f) return f def run_synthesis_off_thread(logfile_base, run_id, json_filename, args, q): res = run_synthesis_retry(logfile_base, run_id, json_filename, args) q.put(res) def run_synthesis_retry(logfile_base, run_id, json_filename, args): nfails = 0 all_res = [] while True: extra = "" if nfails == 0 else ".retry." + str(nfails) res = run_synthesis(logfile_base, run_id+extra, json_filename, args) all_res.append(res) if killing: res.all_res = all_res return res if not res.failed: res.all_res = all_res return res nfails += 1 if nfails >= 3: res.all_res = all_res return res print('!!!!!!!!! synthesis', run_id, 'failed, re-seeding and trying again', '!!!!!!!!!') args = reseed(args) def run_synthesis(logfile_base, run_id, json_filename, args, use_stdout=False): try: logfilename = logfile_base + "/" + run_id cmd = ["./synthesis", "--input-module", json_filename, "--stats-file", make_stats_file()] + args print("run " + run_id + ": " + " ".join(cmd) + " > " + logfilename) sys.stdout.flush() with open(logfilename, "w") as logfile: t1 = time.time() if use_stdout: proc = subprocess.Popen(cmd, stdin=subprocess.PIPE) else: proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=logfile, stderr=logfile) all_procs[run_id] = proc if killing: print("run " + run_id + " stopped") proc.kill() return out, err = proc.communicate() ret = proc.wait() t2 = time.time() seconds = t2 - t1 if killing: print("stopped " + run_id + " (" + str(seconds) + " seconds)") sys.stdout.flush() else: if ret != 0: print("failed " + run_id + " (" + str(seconds) + " seconds) (ret " + str(ret) + ") (pid " + str(proc.pid) + ")") log_inputs(logfilename, json_filename, args) sys.stdout.flush() else: print("complete " + run_id + " (" + str(seconds) + " seconds)") sys.stdout.flush() return RunSynthesisResult(run_id, seconds, killing, ret != 0, logfilename) except Exception: traceback.print_exc() sys.stderr.flush() def unpack_args(args): main_args = [] iter_arg_lists = [] li = None for arg in args: assert arg != "--incremental" if arg in ("--finisher", "--breadth"): if li != None: iter_arg_lists.append(li) li = [] li.append(arg) else: if li == None: main_args.append(arg) else: li.append(arg) if li != None: iter_arg_lists.append(li) t = [] for li in iter_arg_lists: if len(t) > 0 and t[-1][0] == li[0]: t[-1] = t[-1] + li else: t.append(li) return (main_args, t) def do_threading(stats, ivy_filename, json_filename, logdir, nthreads, main_args, breadth_args, finisher_args, by_size): print(ivy_filename) print("json: ", json_filename) invfile = None success = False if not success and len(breadth_args) > 0: success, invfile = do_breadth("iteration", logdir, nthreads, json_filename, main_args, main_args + breadth_args, invfile, stats, by_size) if success: print("Invariant success!") if not success and len(finisher_args) > 0: success = do_finisher("finisher", logdir, nthreads, json_filename, main_args, main_args + finisher_args, invfile, stats) if success: print("Invariant success!") statfile = logdir + "/summary" stats.add_global_stat_files(all_stats_files) stats.print_stats(statfile) print("") print("statfile: " + statfile) print("") print("======== Summary ========") print("") with open(statfile, "r") as f: t = f.read() t = t.split("specifics:") print(t[0]) final_inv_file = logdir + "/invariants" with open(final_inv_file, "w") as f: if stats.was_success(): f.write("# Success: True\n") else: f.write("# Success: False\n") for inv in stats.get_invariants(): f.write("conjecture " + protocol_parsing.value_json_to_string(inv) + "\n") def parse_output_file(filename): with open(filename) as f: src = f.read() j = json.loads(src) return (j["success"], len(j["new_invs"]) > 0) def do_breadth(iterkey, logfile, nthreads, json_filename, main_args, args, invfile, stats, by_size): i = 0 while True: i += 1 success, hasany, invfile = do_breadth_single(iterkey+"."+str(i), logfile, nthreads, json_filename, main_args, args, invfile, i-1, stats, by_size) if success: return True, invfile if not hasany: return False, invfile def do_breadth_single(iterkey, logfile, nthreads, json_filename, main_args, args, invfile, iteration_num, stats, by_size): t1 = time.time() if by_size: c_by_size = chunkify_by_size(iterkey, logfile, nthreads, json_filename, args) total_has_any = False sz = 0 for chunks in c_by_size: sz += 1 success, has_any, output_invfile = breadth_run_in_parallel( iterkey+".size."+str(sz), logfile, json_filename, main_args, invfile, iteration_num, stats, nthreads, chunks) if has_any: total_has_any = True if success: stats.add_inc_result(iteration_num, output_invfile, time.time() - t1) return success, total_has_any, output_invfile invfile = output_invfile success = False has_any = total_has_any new_output_file = invfile else: chunk_files = chunkify(iterkey, logfile, nthreads, json_filename, args) success, has_any, new_output_file = breadth_run_in_parallel(iterkey, logfile, json_filename, main_args, invfile, iteration_num, stats, nthreads, chunk_files) new_output_file = update_base_invs(new_output_file) stats.add_inc_result(iteration_num, new_output_file, time.time() - t1) return success, has_any, new_output_file def update_base_invs(a): with open(a) as f: j = json.loads(f.read()) j["base_invs"] = j["base_invs"] + j["new_invs"] j["new_invs"] = [] c = tempfile.mktemp() with open(c, 'w') as f: f.write(json.dumps(j)) return c def chunkify(iterkey, logfile, nthreads, json_filename, args): d = tempfile.mkdtemp() chunk_file_args = ["--output-chunk-dir", d, "--nthreads", str(nthreads)] synres = run_synthesis_retry(logfile, iterkey+".chunkify", json_filename, args_add_seed(chunk_file_args + args)) assert not synres.failed, "chunkify failed" chunk_files = [] i = 0 while True: p = os.path.join(d, str(i + 1)) if os.path.exists(p): i += 1 chunk_files.append(p) else: break print("chunk_files:", i) if chunkify_only: print(d) sys.exit(1) return chunk_files def chunkify_by_size(iterkey, logfile, nthreads, json_filename, args): d = tempfile.mkdtemp() chunk_file_args = ["--output-chunk-dir", d, "--nthreads", str(nthreads), "--by-size"] synres = run_synthesis_retry(logfile, iterkey+".chunkify", json_filename, args_add_seed(chunk_file_args + args)) assert not synres.failed, "chunkify failed" all_chunk_files = [] j = 0 while True: chunk_files = [] i = 0 while True: p = os.path.join(d, str(j + 1) + "." + str(i + 1)) if os.path.exists(p): i += 1 chunk_files.append(p) else: break if len(chunk_files) > 0: all_chunk_files.append(chunk_files) j += 1 else: break print("chunk_files by size: ", ", ".join(str(len(f)) for f in all_chunk_files)) return all_chunk_files def coalesce(logfile, json_filename, iterkey, files, whole_space=False): new_output_file = tempfile.mktemp() coalesce_file_args = ["--coalesce", "--output-formula-file", new_output_file] if whole_space: coalesce_file_args.append("--whole-space") for f in files: coalesce_file_args.append("--input-formula-file") coalesce_file_args.append(f) synres = run_synthesis_retry(logfile, iterkey+".coalesce", json_filename, args_add_seed(coalesce_file_args)) assert not synres.failed, "breadth coalesce failed" return new_output_file def remove_one(s): assert len(s) > 0 t = min(s) s.remove(t) return t def breadth_run_in_parallel(iterkey, logfile, json_filename, main_args, invfile, iteration_num, stats, nthreads, chunk_files): partialInvariantLogger.new_base(invfile) if invfile != None: args_with_file = ["--input-formula-file", invfile, "--one-breadth"] else: args_with_file = ["--one-breadth"] q = queue.Queue() threads = [ ] output_files = {} column_ids = {} # assign each proc a column id in [1..nthreads] for graphing purposes avail_column_ids = set(range(1, nthreads + 1)) n_running = 0 i = 0 has_any = False any_success = False while ((not any_success) and i < len(chunk_files)) or n_running > 0: if (not any_success) and i < len(chunk_files) and n_running < nthreads: output_file = tempfile.mktemp() key = iterkey+".thread."+str(i) output_files[key] = output_file cid = remove_one(avail_column_ids) column_ids[key] = cid t = threading.Thread(target=run_synthesis_off_thread, args= (logfile, key, json_filename, args_add_seed( ["--invariant-log-file", partialInvariantLogger.new_file_for_partial(), "--input-chunk-file", chunk_files[i], "--output-formula-file", output_file] + main_args + args_with_file), q)) t.start() threads.append(t) i += 1 n_running += 1 else: synres = q.get() key = synres.all_res[0].run_id cid = column_ids[key] avail_column_ids.add(cid) n_running -= 1 if synres.failed and not synres.stopped: print("!!!!! WARNING PROC FAILED, SKIPPING !!!!!") for r in synres.all_res: stats.add_inc_log(iteration_num, r.logfile, r.seconds, cid, r.failed, r.stopped) output_files.pop(key) #kill_all_procs() #assert False, "breadth proper failed" else: for r in synres.all_res: stats.add_inc_log(iteration_num, r.logfile, r.seconds, cid, r.failed, r.stopped) if not synres.stopped and not killing: success, this_has_any = parse_output_file(output_files[key]) if this_has_any: has_any = True if success: kill_all_procs() any_success = True success_file = output_files[key] if any_success: return (True, has_any, success_file) new_output_file = coalesce(logfile, json_filename, iterkey, ([] if invfile == None else [invfile]) + [output_files[key] for key in output_files], whole_space=('--whole-space' in main_args)) return (False, has_any, new_output_file) def do_finisher(iterkey, logfile, nthreads, json_filename, main_args, args, invfile, stats): partialInvariantLogger.new_base(invfile) t1 = time.time() chunk_files = chunkify(iterkey, logfile, nthreads, json_filename, args) if invfile != None: args_with_file = ["--input-formula-file", invfile, "--one-finisher"] else: args_with_file = ["--one-finisher"] q = queue.Queue() threads = [ ] output_files = {} column_ids = {} # assign each proc a column id in [1..nthreads] for graphing purposes avail_column_ids = set(range(1, nthreads + 1)) n_running = 0 i = 0 any_success = False while ((not any_success) and i < len(chunk_files)) or n_running > 0: if (not any_success) and i < len(chunk_files) and n_running < nthreads: output_file = tempfile.mktemp() key = iterkey+".thread."+str(i) output_files[key] = output_file cid = remove_one(avail_column_ids) column_ids[key] = cid t = threading.Thread(target=run_synthesis_off_thread, args= (logfile, key, json_filename, args_add_seed( ["--input-chunk-file", chunk_files[i], "--output-formula-file", output_file] + main_args + args_with_file), q)) t.start() threads.append(t) i += 1 n_running += 1 else: synres = q.get() key = synres.all_res[0].run_id cid = column_ids[key] avail_column_ids.add(cid) n_running -= 1 if synres.failed and not synres.stopped: print("!!!!! WARNING PROC FAILED, SKIPPING !!!!!") for r in synres.all_res: stats.add_finisher_log(r.logfile, r.seconds, cid, r.failed, r.stopped) output_files.pop(key) #kill_all_procs() #assert False, "finisher proper failed" else: for r in synres.all_res: stats.add_finisher_log(r.logfile, r.seconds, cid, r.failed, r.stopped) if not synres.stopped and not killing: success, this_has_any = parse_output_file(output_files[key]) if success: any_success = True stats.add_finisher_result(output_files[key], time.time() - t1) kill_all_procs() some_key = None for some_key in output_files: break if not any_success: stats.add_finisher_result(output_files[some_key], time.time() - t1) chunkify_only = False def parse_args(ivy_filename, args): nthreads = None logdir = "" new_args = [] use_stdout = False by_size = False config = None finisher_only = False i = 0 while i < len(args): if args[i] == "--threads": nthreads = int(args[i+1]) i += 1 elif args[i] == "--logdir": logdir = args[i+1] i += 1 elif args[i] == "--seed": seed = int(args[i+1]) set_seed(seed) i += 1 elif args[i] == "--stdout": use_stdout = True elif args[i] == "--by-size": by_size = True elif args[i] == "--finisher-only": finisher_only = True elif args[i] == "--config": config = args[i+1] i += 1 elif args[i] == "--chunkify-only": global chunkify_only chunkify_only = True else: new_args.append(args[i]) i += 1 if logdir == "": rstr = "" for i in range(9): rstr += str(random.randint(0, 9)) logdir = ("logs/log." + datetime.now().strftime("%Y-%m-%d_%H.%M.%S") + "-" + rstr) os.mkdir(logdir) (main_args, iter_args) = unpack_args(new_args) if config != None: assert len(iter_args) == 0 suite = templates.read_suite(ivy_filename) bench = suite.get(config) b_args = bench.breadth_space.get_args("--breadth") f_args = bench.finisher_space.get_args("--finisher") if finisher_only: b_args = [] else: assert not finisher_only assert len(iter_args) > 0 b_args = [] f_args = [] for iter_arg_list in iter_args: if iter_arg_list[0] == "--breadth": b_args = b_args + iter_arg_list elif iter_arg_list[0] == "--finisher": f_args = f_args + iter_arg_list else: assert False return nthreads, logdir, by_size, main_args, b_args, f_args, use_stdout def main(): ivy_filename = sys.argv[1] json_filename = protocol_parsing.protocol_file_json_file(ivy_filename) args = sys.argv[2:] nthreads, logdir, by_size, main_args, breadth_args, finisher_args, use_stdout = ( parse_args(ivy_filename, args)) global partialInvariantLogger partialInvariantLogger = PartialInvariantLogger(logdir) if nthreads == None: if "--config" in args: print("You must supply --threads with --config") else: all_args = main_args + breadth_args + finisher_args run_synthesis(logdir, "main", json_filename, all_args, use_stdout=use_stdout) else: stats = Stats(nthreads, args, ivy_filename, json_filename, logdir) do_threading(stats, ivy_filename, json_filename, logdir, nthreads, main_args, breadth_args, finisher_args, by_size) if __name__ == "__main__": main() <file_sep>/src/smt.cpp #include "smt.h" #include <map> #include <fstream> #include <iostream> #include "benchmarking.h" using namespace std; bool enable_smt_logging = false; extern int run_id; thread_local map<string, pair<long long, long long>> stats; namespace smt { void _solver::log_smtlib( long long ms, std::string const& res) { static int log_num = 1; string filename = "./logs/smtlib/log." + to_string(run_id) + "." + to_string(log_num) + ".z3"; log_num++; ofstream myfile; myfile.open(filename); myfile << "; time: " << ms << " ms" << endl; myfile << "; result: " << res; myfile << "; " << log_info << endl; myfile << endl; dump(myfile); myfile.close(); cout << "logged smtlib to " << filename << endl; } void log_to_stdout(long long ms, bool is_cvc4, string const& log_info, string const& res) { string l; if (log_info == "") { l = "[???]"; } else { l = "[" + log_info + "]"; } string key; if (is_cvc4) { cout << "SMT result (cvc4) "; key = "cvc4 "; } else { cout << "SMT result (z3) "; key = "z3 "; } cout << l << " : " << res << " " << ms << " ms" << endl; for (int i = 0; i < 2; i++) { string newkey; if (i == 0) newkey = key + l + " " + res; else newkey = key + "TOTAL" + " " + res; while (newkey.size() < 58) newkey += " "; if (stats.find(newkey) == stats.end()) { stats.insert(make_pair(newkey, make_pair(0, 0))); } stats[newkey].first++; stats[newkey].second += ms; } } void add_stat_smt_long(long long ms) { string newkey = "long smtAllQueries"; if (stats.find(newkey) == stats.end()) { stats.insert(make_pair(newkey, make_pair(0, 0))); } stats[newkey].first++; stats[newkey].second += ms; } void dump_smt_stats() { for (auto& p : stats) { long long num = p.second.first; long long ms = p.second.second; long long avg = ms / num; cout << p.first << " total " << ms << " ms over " << num << " ops, average is " << avg << " ms" << endl; } } } <file_sep>/scripts/templates.py class TemplateSpace(object): def __init__(self, templ, k, d): self.templ = templ self.k = k self.d = d class TemplateGen(object): def __init__(self, k, d, mvars, e): self.k = k self.d = d self.mvars = mvars self.e = e class BigSpace(object): def __init__(self, spaces=None, gen=None): self.spaces = spaces self.gen = gen def get_args(self, alg): if self.gen != None: assert len(self.spaces) == 0 return [("--one-breadth" if alg == "--breadth" else "--one-finisher"), "--template-sorter", str(self.gen.k), str(self.gen.d), str(self.gen.mvars), str(self.gen.e)] elif len(self.spaces) > 0: res = [] for space in self.spaces: res = res + [alg, "--template-space", space.templ.replace(" ", "-"), "--disj-arity", str(space.k)] + (["--depth2-shape"] if space.d == 2 else []) return res else: return [] class Bench(object): def __init__(self, breadth_space, finisher_space): self.breadth_space = breadth_space self.finisher_space = finisher_space class BenchSuite(object): def __init__(self, benches): self.benches = benches def get(self, name): return self.benches[name] def parse_keyvals(line): d = {} for keyval in line.split(): s = keyval.split('=') d[s[0]] = int(s[1]) depth = d["d"] assert depth in (1, 2) return d def parse_line(line): s = line.split('#') t = s[0].split(' ') name = t[0] rest = ' '.join(t[1:]) keyvals = parse_keyvals(s[1]) if name == "template": assert len(keyvals) == 2 return TemplateSpace(rest, keyvals["k"], keyvals["d"]) elif name == "auto": assert len(keyvals) in (3, 4) e = -1 if "e" in keyvals: e = keyvals["e"] return TemplateGen(keyvals["k"], keyvals["d"], keyvals["mvars"], e) def parse_space(lines): spaces = [] gen = None for line in lines: thing = parse_line(line) if isinstance(thing, TemplateSpace): spaces.append(thing) else: assert gen == None gen = thing assert not (gen != None and len(spaces) > 0) return BigSpace(spaces, gen) def parse_bench(lines): breadth_lines = [] finisher_lines = [] doing_breadth = False doing_finisher = False for l in lines: if l == "[breadth]": doing_breadth = True doing_finisher = False elif l == "[finisher]": doing_breadth = False doing_finisher = True else: if doing_breadth: breadth_lines.append(l) elif doing_finisher: finisher_lines.append(l) else: assert False return Bench(parse_space(breadth_lines), parse_space(finisher_lines)) def get_suite_filename(ivy_filename): assert ivy_filename.endswith(".ivy") or ivy_filename.endswith(".pyv") return ivy_filename[:-4] + ".config" def read_suite(ivy_filename): suite_filename = get_suite_filename(ivy_filename) benches = {} bench_name = None cur_bench = None with open(suite_filename) as f: for line in f: line = line.strip() if line != "": if line.startswith("[bench "): s = line.split() assert len(s) == 2 assert s[1][-1] == "]" new_bench_name = s[1][:-1] if bench_name is not None: assert bench_name not in benches benches[bench_name] = parse_bench(cur_bench) bench_name = new_bench_name cur_bench = [] else: cur_bench.append(line) if bench_name is not None: benches[bench_name] = parse_bench(cur_bench) return BenchSuite(benches) <file_sep>/src/clause_gen.cpp #include "clause_gen.h" #include <cassert> #include <algorithm> #include "utils.h" using namespace std; vector<value> gen_uninterp(int depth, shared_ptr<Module> module, vector<VarDecl> const& decls, std::string const& sort_name, bool var_only); vector<value> gen_apps(int depth, shared_ptr<Module> module, vector<VarDecl> const& decls, VarDecl func) { assert (depth < 10); bool is_btw = (iden_to_string(func.name) == "btw"); vector<vector<value>> poss_args; vector<int> indices; vector<lsort> domains = func.sort->get_domain_as_function(); for (int i = 0; i < (int)domains.size(); i++) { UninterpretedSort* us = dynamic_cast<UninterpretedSort*>(domains[i].get()); assert (us != NULL); vector<value> vs = gen_uninterp(depth+1, module, decls, us->name, false); if (vs.size() == 0) { return {}; } poss_args.push_back(vs); indices.push_back(0); } vector<value> res; while (true) { bool skip = false; if (is_btw) { assert(indices.size() == 3); if (indices[0] == indices[1] || indices[1] == indices[2] || indices[2] == indices[0]) { skip = true; } } if (!skip) { vector<value> args; for (int i = 0; i < (int)indices.size(); i++) { args.push_back(poss_args[i][indices[i]]); } if (args.size() == 0) { res.push_back(v_const(func.name, func.sort)); } else { res.push_back(v_apply(v_const(func.name, func.sort), args)); } } int i; for (i = 0; i < (int)indices.size(); i++) { indices[i]++; if (indices[i] == (int)poss_args[i].size()) { indices[i] = 0; } else { break; } } if (i == (int)indices.size()) { break; } } return res; } vector<value> gen_bool(int depth, shared_ptr<Module> module, vector<VarDecl> const& decls) { assert (depth < 10); vector<value> res; for (VarDecl func : module->functions) { lsort so = func.sort->get_range_as_function(); if (dynamic_cast<BooleanSort*>(so.get())) { vector<value> apps = gen_apps(depth+1, module, decls, func); for (value v : apps) { res.push_back(v); res.push_back(v_not(v)); } } } for (string sort_name : module->sorts) { vector<value> equalands = gen_uninterp(depth+1, module, decls, sort_name, false /* var_only */); for (int i = 0; i < (int)equalands.size(); i++) { for (int j = 0; j < (int)equalands.size(); j++) { if (i != j && lt_value(equalands[i], equalands[j])) { res.push_back(v_eq(equalands[i], equalands[j])); res.push_back(v_not(v_eq(equalands[i], equalands[j]))); } } } } return res; } vector<value> gen_uninterp(int depth, shared_ptr<Module> module, vector<VarDecl> const& decls, std::string const& sort_name, bool var_only) { assert (depth < 10); vector<value> res; if (!var_only) { for (VarDecl func : module->functions) { lsort so = func.sort->get_range_as_function(); if (UninterpretedSort* us = dynamic_cast<UninterpretedSort*>(so.get())) { if (us->name == sort_name) { vector<value> apps = gen_apps(depth+1, module, decls, func); for (value v : apps) { res.push_back(v); } } } } } for (VarDecl d : decls) { lsort so = d.sort; if (UninterpretedSort* us = dynamic_cast<UninterpretedSort*>(so.get())) { if (us->name == sort_name) { res.push_back(v_var(d.name, d.sort)); } } } return res; } std::vector<value> gen_clauses( std::shared_ptr<Module> module, std::vector<VarDecl> const& decls) { vector<value> res = gen_bool(0, module, decls); std::sort(res.begin(), res.end(), [](value a, value b) { return lt_value(a, b); }); return res; } <file_sep>/src/top_quantifier_desc.cpp #include "top_quantifier_desc.h" #include <set> #include <cassert> #include <iostream> using namespace std; TopQuantifierDesc::TopQuantifierDesc(value v) { while (true) { if (Forall* f = dynamic_cast<Forall*>(v.get())) { for (VarDecl decl : f->decls) { d.push_back(make_pair(QType::Forall, vector<VarDecl>{decl})); } v = f->body; } else if (NearlyForall* f = dynamic_cast<NearlyForall*>(v.get())) { d.push_back(make_pair(QType::NearlyForall, f->decls)); v = f->body; } else { break; } } } pair<TopQuantifierDesc, value> get_tqd_and_body(value v) { TopQuantifierDesc tqd(v); while (true) { if (Forall* f = dynamic_cast<Forall*>(v.get())) { v = f->body; } else if (NearlyForall* f = dynamic_cast<NearlyForall*>(v.get())) { v = f->body; } else { break; } } return make_pair(tqd, v); } pair<TopAlternatingQuantifierDesc, value> get_taqd_and_body(value v) { TopAlternatingQuantifierDesc taqd(v); while (true) { if (Forall* f = dynamic_cast<Forall*>(v.get())) { v = f->body; } else if (Exists* e = dynamic_cast<Exists*>(v.get())) { v = e->body; } else { break; } } return make_pair(taqd, v); } vector<VarDecl> TopQuantifierDesc::decls() const { vector<VarDecl> res; for (auto p : d) { for (auto decl : p.second) { res.push_back(decl); } } return res; } vector<QRange> TopQuantifierDesc::with_foralls_grouped() const { vector<QRange> res; QRange cur; cur.start = 0; cur.end = 0; for (auto p : d) { QType ty = p.first; if (ty == QType::Forall) { cur.end++; cur.decls.push_back(p.second[0]); cur.qtype = ty; } else if (ty == QType::NearlyForall) { if (cur.end > cur.start) { res.push_back(cur); } cur.start = cur.end; cur.decls = p.second; cur.end = cur.start + cur.decls.size(); cur.qtype = ty; res.push_back(cur); cur.start = cur.end; cur.decls.clear(); } else { assert(false); } } if (cur.end > cur.start) { res.push_back(cur); } return res; } vector<QSRange> TopQuantifierDesc::grouped_by_sort() const { vector<QSRange> res; QSRange cur; cur.start = 0; cur.end = 0; for (auto p : d) { QType ty = p.first; for (auto decl : p.second) { if (cur.end > cur.start && !(cur.qtype == ty && sorts_eq(cur.decls[0].sort, decl.sort))) { res.push_back(cur); cur.start = cur.end; cur.decls.clear(); } cur.decls.push_back(decl); cur.qtype = ty; cur.sort = decl.sort; cur.end++; } if (ty == QType::NearlyForall && cur.end > cur.start) { res.push_back(cur); cur.start = cur.end; cur.decls.clear(); } } if (cur.end > cur.start) { res.push_back(cur); } set<string> names; for (int i = 0; i < (int)res.size(); i++) { if (i > 0 && res[i].qtype != res[i-1].qtype) { names.clear(); } UninterpretedSort* usort = dynamic_cast<UninterpretedSort*>(res[i].decls[0].sort.get()); assert(usort != NULL); if (res[i].qtype == QType::Forall) { assert (names.count(usort->name) == 0); } names.insert(usort->name); } return res; } value TopQuantifierDesc::with_body(value body) const { vector<QRange> qrs = with_foralls_grouped(); for (int i = qrs.size() - 1; i >= 0; i--) { QRange& qr = qrs[i]; if (qr.qtype == QType::Forall) { body = v_forall(qr.decls, body); } else if (qr.qtype == QType::NearlyForall) { body = v_nearlyforall(qr.decls, body); } else { assert(false); } } return body; } int TopQuantifierDesc::weighted_sort_count(std::string sort) const { lsort so = s_uninterp(sort); int count = 0; for (auto p : d) { QType ty = p.first; for (VarDecl const& decl : p.second) { if (sorts_eq(so, decl.sort)) { count += (ty == QType::NearlyForall ? 2 : 1); } } } return count; } TopAlternatingQuantifierDesc::TopAlternatingQuantifierDesc(value v) { Alternation alt; while (true) { if (Forall* f = dynamic_cast<Forall*>(v.get())) { if (alt.decls.size() > 0 && alt.altType != AltType::Forall) { alts.push_back(alt); alt.decls = {}; } alt.altType = AltType::Forall; for (VarDecl decl : f->decls) { alt.decls.push_back(decl); } v = f->body; } else if (/* NearlyForall* f = */ dynamic_cast<NearlyForall*>(v.get())) { assert(false); } else if (Exists* f = dynamic_cast<Exists*>(v.get())) { if (alt.decls.size() > 0 && alt.altType != AltType::Exists) { alts.push_back(alt); alt.decls = {}; } alt.altType = AltType::Exists; for (VarDecl decl : f->decls) { alt.decls.push_back(decl); } v = f->body; } else { break; } } if (alt.decls.size() > 0) { alts.push_back(alt); } } value TopAlternatingQuantifierDesc::get_body(value v) { while (true) { if (Forall* f = dynamic_cast<Forall*>(v.get())) { v = f->body; } else if (Exists* f = dynamic_cast<Exists*>(v.get())) { v = f->body; } else { break; } } return v; } value TopAlternatingQuantifierDesc::with_body(value v) { for (int i = alts.size() - 1; i >= 0; i--) { Alternation& alt = alts[i]; if (alt.altType == AltType::Forall) { v = v_forall(alt.decls, v); } else { v = v_exists(alt.decls, v); } } return v; } vector<QSRange> TopAlternatingQuantifierDesc::grouped_by_sort() const { vector<QSRange> res; QSRange cur; cur.start = 0; cur.end = 0; for (auto alt : alts) { assert(alt.altType == AltType::Forall || alt.altType == AltType::Exists); QType ty = alt.altType == AltType::Forall ? QType::Forall : QType::Exists; for (auto decl : alt.decls) { if (cur.end > cur.start && !(cur.qtype == ty && sorts_eq(cur.decls[0].sort, decl.sort))) { res.push_back(cur); cur.start = cur.end; cur.decls.clear(); } cur.decls.push_back(decl); cur.qtype = ty; cur.sort = decl.sort; cur.end++; } /*if (ty == QType::NearlyForall && cur.end > cur.start) { res.push_back(cur); cur.start = cur.end; cur.decls.clear(); }*/ } if (cur.end > cur.start) { res.push_back(cur); } set<string> names; for (int i = 0; i < (int)res.size(); i++) { if (i > 0 && res[i].qtype != res[i-1].qtype) { names.clear(); } UninterpretedSort* usort = dynamic_cast<UninterpretedSort*>(res[i].decls[0].sort.get()); assert(usort != NULL); if (res[i].qtype == QType::Forall) { assert (names.count(usort->name) == 0); } names.insert(usort->name); } return res; } TopAlternatingQuantifierDesc TopAlternatingQuantifierDesc:: replace_exists_with_forall() const { Alternation bigalt; bigalt.altType = AltType::Forall; for (Alternation const& alt : alts) { for (VarDecl decl : alt.decls) { bigalt.decls.push_back(decl); } } TopAlternatingQuantifierDesc res; res.alts.push_back(bigalt); return res; } /*value rename_into(vector<Alternation> const& alts, value v) { int alt_idx = 0; int inner_idx = 0; TopAlternatingQuantifierDesc atqd(v); vector<Alternation>& alts1 = atqd.alts; int alt_idx1 = 0; int inner_idx1 = 0; map<iden, iden> var_map; while (alt_idx1 < (int)alts1.size()) { while (inner_idx1 < (int)alts1[alt_idx1].decls.size()) { if (alt_idx == (int)alts.size()) { return nullptr; } if (inner_idx == (int)alts[alt_idx].decls.size()) { inner_idx = 0; alt_idx++; } else { if (alts[alt_idx].altType == alts1[alt_idx1].altType && sorts_eq( alts[alt_idx].decls[inner_idx].sort, alts1[alt_idx1].decls[inner_idx1].sort)) { var_map.insert(make_pair( alts1[alt_idx1].decls[inner_idx1].name, alts[alt_idx].decls[inner_idx].name)); inner_idx1++; } inner_idx++; } } inner_idx1 = 0; alt_idx1++; } value substed = v->replace_var_with_var(TopAlternatingQuantifierDesc::get_body(var_map)); TopAlternatingQuantifierDesc new_taqd; new_taqd.alts = alts; return new_taqd.with_body(substed); } value TopQuantifierDesc::rename_into(value v) { cout << "Top rename_into " << v->to_string() << endl; v = remove_unneeded_quants(v.get()); cout << "removed unneeded " << v->to_string() << endl; vector<Alternation> alts; alts.resize(d.size()); for (int i = 0; i < (int)d.size(); i++) { assert (d[i].first == QType::Forall); alts[i].decls = d[i].second; alts[i].altType = AltType::Forall; } value res = ::rename_into(alts, v); if (res) { cout << "result " << res->to_string() << endl; } else { cout << "result null" << endl; } return res; } value TopAlternatingQuantifierDesc::rename_into(value v) { cout << "Alt rename_into " << v->to_string() << endl; v = remove_unneeded_quants(v.get()); cout << "removed unneeded " << v->to_string() << endl; value res = ::rename_into(alts, v); if (res) { cout << "result " << res->to_string() << endl; } else { cout << "result null" << endl; } return res; }*/ /*void TopAlternatingQuantifierDesc::rename_into_all_possibilities_rec( TopAlternatingQuantifierDesc const& v_taqd, int v_idx, int v_inner_idx, int this_idx, int this_inner_idx, value const& body, map<iden, iden>& var_map, vector<value>& results) { if (v_idx == (int)v_taqd.alts.size()) { results.push_back(this->with_body(body->replace_var_with_var(var_map))); return; } if (v_inner_idx == (int)v_taqd.alts[v_idx].decls.size()) { rename_into_all_possibilities_rec( v_taqd, v_idx + 1, 0, this_idx, this_inner_idx, body, var_map, results); return; } if (this_idx == (int)this->alts.size()) { return; } if (this_inner_idx == (int)this->alts[this_idx].decls.size()) { rename_into_all_possibilities_rec( v_taqd, v_idx, v_inner_idx, this_idx + 1, 0, body, var_map, results); return; } if (v_taqd.alts[v_idx].altType != this->alts[this_idx].altType) { rename_into_all_possibilities_rec( v_taqd, v_idx, v_inner_idx, this_idx + 1, 0, body, var_map, results); return; } rename_into_all_possibilities_rec( v_taqd, v_idx, v_inner_idx, this_idx, this_inner_idx + 1, body, var_map, results); if (sorts_eq( v_taqd.alts[v_idx].decls[v_inner_idx].sort, this->alts[this_idx].decls[this_inner_idx].sort)) { var_map[v_taqd.alts[v_idx].decls[v_inner_idx].name] = this->alts[this_idx].decls[this_inner_idx].name; rename_into_all_possibilities_rec(v_taqd, v_idx, v_inner_idx + 1, this_idx, this_inner_idx + 1, body, var_map, results); } }*/ static bool is_valid(vector<vector<pair<int,int>>>& candidate) { for (int i = 0; i < (int)candidate.size(); i++) { for (int j = 0; j < (int)candidate[i].size(); j++) { for (int k = i; k < (int)candidate.size(); k++) { for (int l = 0; l < (int)candidate[k].size(); l++) { if (!(i == k && j == l) && candidate[i][j] == candidate[k][l]) { return false; } } } } } int last_min_x; int last_max_x; for (int i = 0; i < (int)candidate.size(); i++) { int min_x = candidate[i][0].first; int max_x = candidate[i][0].first; for (int j = 1; j < (int)candidate[i].size(); j++) { min_x = min(min_x, candidate[i][j].first); max_x = max(max_x, candidate[i][j].first); } if (i > 0) { if (min_x < last_max_x) { return false; } } last_min_x = min_x; last_max_x = max_x; } return true; } std::vector<value> TopAlternatingQuantifierDesc::rename_into_all_possibilities(value v) { cout << "rename_into_all_possibilities " << v->to_string() << endl; for (Alternation const& alt : alts) { cout << "type: " << (alt.altType == AltType::Forall ? "forall" : "exists"); cout << " "; } cout << endl; v = remove_unneeded_quants(v.get()); TopAlternatingQuantifierDesc taqd(v); value body = TopAlternatingQuantifierDesc::get_body(v); vector<vector<vector<pair<int,int>>>> possibilities; vector<vector<int>> indices; vector<vector<pair<int,int>>> candidate; possibilities.resize(taqd.alts.size()); indices.resize(taqd.alts.size()); candidate.resize(taqd.alts.size()); for (int i = 0; i < (int)taqd.alts.size(); i++) { possibilities[i].resize(taqd.alts[i].decls.size()); indices[i].resize(taqd.alts[i].decls.size()); candidate[i].resize(taqd.alts[i].decls.size()); for (int j = 0; j < (int)taqd.alts[i].decls.size(); j++) { indices[i][j] = 0; VarDecl const& decl = taqd.alts[i].decls[j]; for (int k = 0; k < (int)this->alts.size(); k++) { if (this->alts[k].altType == taqd.alts[i].altType || (taqd.alts[i].altType == AltType::Forall && this->alts[k].altType == AltType::Exists) ) { for (int l = 0; l < (int)this->alts[k].decls.size(); l++) { if (sorts_eq(decl.sort, this->alts[k].decls[l].sort)) { possibilities[i][j].push_back(make_pair(k, l)); } } } } if (possibilities[i][j].size() == 0) { return {}; } } } vector<value> results; while (true) { for (int i = 0; i < (int)taqd.alts.size(); i++) { for (int j = 0; j < (int)taqd.alts[i].decls.size(); j++) { candidate[i][j] = possibilities[i][j][indices[i][j]]; } } if (is_valid(candidate)) { map<iden, iden> var_map; for (int i = 0; i < (int)taqd.alts.size(); i++) { for (int j = 0; j < (int)taqd.alts[i].decls.size(); j++) { var_map.insert(make_pair(taqd.alts[i].decls[j].name, this->alts[candidate[i][j].first].decls[candidate[i][j].second].name)); } } results.push_back(order_and_or_eq(this->with_body(body->replace_var_with_var(var_map)))); } for (int i = 0; i < (int)taqd.alts.size(); i++) { for (int j = 0; j < (int)taqd.alts[i].decls.size(); j++) { indices[i][j]++; if (indices[i][j] == (int)possibilities[i][j].size()) { indices[i][j] = 0; } else { goto continue_loop; } } } break; continue_loop: { } } for (value res : results) { cout << "result: " << res->to_string() << endl; } return results; } std::vector<value> TopQuantifierDesc::rename_into_all_possibilities(value v) { vector<Alternation> alts; alts.resize(d.size()); for (int i = 0; i < (int)d.size(); i++) { assert (d[i].first == QType::Forall); alts[i].decls = d[i].second; alts[i].altType = AltType::Forall; } TopAlternatingQuantifierDesc taqd; taqd.alts = alts; return taqd.rename_into_all_possibilities(v); } <file_sep>/src/var_lex_graph.cpp #include "var_lex_graph.h" #include <cassert> #include <iostream> #include "top_quantifier_desc.h" using namespace std; struct GI { int group; int index; }; GI get_gi(vector<QSRange> const& groups, iden name) { for (int i = 0; i < (int)groups.size(); i++) { for (int j = 0; j < (int)groups[i].decls.size(); j++) { if (groups[i].decls[j].name == name) { GI gi; gi.group = i; gi.index = j + 1; return gi; } } } assert(false); } void get_var_index_transition_rec( vector<QSRange> const& groups, value v, VarIndexTransition& vit) { assert(v.get() != NULL); if (Forall* val = dynamic_cast<Forall*>(v.get())) { get_var_index_transition_rec(groups, val->body, vit); } else if (Exists* val = dynamic_cast<Exists*>(v.get())) { get_var_index_transition_rec(groups, val->body, vit); } else if (NearlyForall* val = dynamic_cast<NearlyForall*>(v.get())) { get_var_index_transition_rec(groups, val->body, vit); } else if (Var* val = dynamic_cast<Var*>(v.get())) { GI gi = get_gi(groups, val->name); // If the largest seen (`res`) jumps ahead by more than 1, // then update `pre`. if (gi.index - 1 > vit.res.indices[gi.group]) { vit.pre.indices[gi.group] = gi.index - 1; } // Update the largest seen (`res`) if (gi.index > vit.res.indices[gi.group]) { vit.res.indices[gi.group] = gi.index; } } else if (dynamic_cast<Const*>(v.get())) { } else if (Eq* val = dynamic_cast<Eq*>(v.get())) { get_var_index_transition_rec(groups, val->left, vit); get_var_index_transition_rec(groups, val->right, vit); } else if (Not* val = dynamic_cast<Not*>(v.get())) { get_var_index_transition_rec(groups, val->val, vit); } else if (Implies* val = dynamic_cast<Implies*>(v.get())) { get_var_index_transition_rec(groups, val->left, vit); get_var_index_transition_rec(groups, val->right, vit); } else if (Apply* val = dynamic_cast<Apply*>(v.get())) { get_var_index_transition_rec(groups, val->func, vit); for (value arg : val->args) { get_var_index_transition_rec(groups, arg, vit); } } else if (And* val = dynamic_cast<And*>(v.get())) { for (value arg : val->args) { get_var_index_transition_rec(groups, arg, vit); } } else if (Or* val = dynamic_cast<Or*>(v.get())) { for (value arg : val->args) { get_var_index_transition_rec(groups, arg, vit); } } else if (IfThenElse* val = dynamic_cast<IfThenElse*>(v.get())) { get_var_index_transition_rec(groups, val->cond, vit); get_var_index_transition_rec(groups, val->then_value, vit); get_var_index_transition_rec(groups, val->else_value, vit); } else { assert(false && "get_var_index_transition_rec does not support this case"); } } VarIndexTransition get_var_index_transition( vector<QSRange> const& groups, value v) { int n = groups.size(); VarIndexTransition vit; vit.pre.indices.resize(n); vit.res.indices.resize(n); for (int i = 0; i < n; i++) { vit.pre.indices[i] = 0; vit.res.indices[i] = 0; } get_var_index_transition_rec(groups, v, vit); return vit; } vector<QSRange> use_module_sort_order( shared_ptr<Module> module, vector<QSRange> const& qsr) { vector<QSRange> res; for (string so_name : module->sorts) { lsort so = s_uninterp(so_name); int idx = -1; for (int i = 0; i < (int)qsr.size(); i++) { if (sorts_eq(so, qsr[i].sort)) { assert(idx == -1); idx = i; } } if (idx == -1) { QSRange q; q.start = 0; q.end = 0; q.qtype = QType::Forall; q.sort = so; res.push_back(q); } else { res.push_back(qsr[idx]); } } return res; } vector<VarIndexTransition> get_var_index_transitions( shared_ptr<Module> module, value templ, vector<value> const& values) { TopAlternatingQuantifierDesc taqd(templ); vector<QSRange> groups = taqd.grouped_by_sort(); groups = use_module_sort_order(module, groups); int ngroups = groups.size(); for (int i = 0; i < ngroups; i++) { for (int j = 1; j < (int)groups[i].decls.size(); j++) { if (!(iden_to_string(groups[i].decls[j-1].name) < iden_to_string(groups[i].decls[j].name))) { for (VarDecl d : groups[i].decls) { cout << iden_to_string(d.name) << endl; } assert(false && "template args should be in alphabetical order (yeah it's dumb, but or else we might accidentally rely on two different sorting orders being the same or something)"); } } } vector<VarIndexTransition> vits; for (int i = 0; i < (int)values.size(); i++) { vits.push_back(get_var_index_transition(groups, values[i])); } return vits; } VarIndexState get_var_index_init_state(shared_ptr<Module> module, value templ) { TopQuantifierDesc taqd(templ); //vector<QSRange> groups = taqd.grouped_by_sort(); //groups = use_module_sort_order(module, groups); //int ngroups = groups.size(); int ngroups = module->sorts.size(); VarIndexState vis(ngroups); for (int i = 0; i < ngroups; i++) { vis.indices[i] = 0; } return vis; } <file_sep>/src/benchmarking.cpp #include "benchmarking.h" #include <chrono> #include <cassert> #include <iostream> using namespace std; std::unordered_map<std::string, long long> total_bench; void Benchmarking::start(string s) { assert(!in_bench); in_bench = true; bench_name = s; last = chrono::high_resolution_clock::now(); } void Benchmarking::end() { assert(in_bench); in_bench = false; auto end = chrono::high_resolution_clock::now(); auto dur = end - last; long long ms = std::chrono::duration_cast<std::chrono::milliseconds>(dur).count(); { auto iter = bench.find(bench_name); if (iter == bench.end()) { bench.insert(make_pair(bench_name, ms)); } else { iter->second = iter->second + ms; } } if (include_in_global) { auto iter = total_bench.find(bench_name); if (iter == total_bench.end()) { total_bench.insert(make_pair(bench_name, ms)); } else { iter->second = iter->second + ms; } } } void Benchmarking::dump() { for (auto p : bench) { std::cout << p.first << " : " << p.second << " ms" << std::endl; std::cout.flush(); } } void benchmarking_dump_totals() { for (auto p : total_bench) { std::cout << "TOTAL " << p.first << " : " << p.second << " ms" << std::endl; std::cout.flush(); } } <file_sep>/src/alt_synth_enumerator.h #ifndef ALT_SYNTH_ENUMERATOR_H #define ALT_SYNTH_ENUMERATOR_H #include "synth_enumerator.h" #include "bitset_eval_result.h" #include "var_lex_graph.h" #include "subsequence_trie.h" #include "template_desc.h" class AltDisjunctCandidateSolver : public CandidateSolver { public: AltDisjunctCandidateSolver( std::shared_ptr<Module>, TemplateSpace const& tspace); value getNext(); void addCounterexample(Counterexample cex); void addExistingInvariant(value inv); long long getProgress() { return progress; } long long getPreSymmCount(); long long getSpaceSize() { assert(false); } long long progress; //private: std::shared_ptr<Module> module; int disj_arity; TemplateSpace tspace; TopAlternatingQuantifierDesc taqd; std::vector<value> pieces; TemplateSubSlice tss; std::vector<int> slice_index_map; TransitionSystem sub_ts; int target_state; std::vector<int> cur_indices_sub; std::vector<int> cur_indices; std::vector<int> var_index_states; int start_from; int done_cutoff; bool finish_at_cutoff; bool done; std::vector<Counterexample> cexes; std::vector<std::vector<std::pair<BitsetEvalResult, BitsetEvalResult>>> cex_results; std::vector<std::pair<AlternationBitsetEvaluator, AlternationBitsetEvaluator>> abes; std::vector<std::vector<int>> existing_invariant_indices; SubsequenceTrie existing_invariant_trie; std::set<ComparableValue> existing_invariant_set; std::map<ComparableValue, int> piece_to_index; TransitionSystem ts; void increment(); void skipAhead(int upTo); void dump_cur_indices(); value disjunction_fuse(std::vector<value> values); std::vector<int> get_indices_of_value(value inv); int get_index_of_piece(value p); void init_piece_to_index(); void existing_invariants_append(std::vector<int> const& indices); void setSubSlice(TemplateSubSlice const&); }; #endif <file_sep>/scripts/template_table.py import sys import os import graphs if __name__ == '__main__': input_directory = sys.argv[1] graphs.templates_table(input_directory) <file_sep>/scripts/graphs.py import matplotlib.pyplot as plt import matplotlib.patches as patches import numpy as np from pathlib import Path import matplotlib.transforms as mtrans import sys import os import json import paper_benchmarks import get_counts import templates use_old_names = False def map_filename_maybe(filename): if not use_old_names: return filename if "learning-switch-quad_pyv" in filename: return filename.replace("learning-switch-quad_pyv", "learning_switch_pyv") if "learning-switch-ternary" in filename: return filename.replace("learning-switch-ternary", "learning-switch") if "lock-server-sync" in filename: return filename.replace("lock-server-sync", "lock_server") if "lock-server-async" in filename: return filename.replace("lock-server-async", "lockserv") return filename class ThreadStats(object): def __init__(self, input_directory, filename): times = {} stats = {} with open(os.path.join(input_directory, map_filename_maybe(filename), "summary")) as f: cur_name = None cur_stats = None state = 0 for line in f: if line.startswith("time for process "): l = line.split() name = self.get_name_from_log(l[3]) if l[-1] == "seconds": secs = float(l[-2]) elif l[-2] == "seconds": secs = float(l[-3]) else: assert False times[name] = secs elif state == 0 and (line.startswith("./logs/log.") or line.startswith("/pylon5/ms5pijp/tjhance/log.")): cur_name = self.get_name_from_log(line.strip()) state = 1 elif state == 1: assert line == "-------------------------------------------------\n" state = 2 cur_stats = {} elif state == 2 and line == "-------------------------------------------------\n": state = 0 stats[cur_name] = cur_stats elif state == 2: l = line.split('--->') assert len(l) == 2 key = l[0].strip() val = int(l[1].split()[0]) cur_stats[key] = val for k in times: stats[k]["total_time"] = times[k] self.uses_sizes = False for k in times: if ".size." in k: self.uses_sizes = True self.stats = stats def get_finisher_stats(self): res = [] for k in self.stats: if k.startswith("finisher.thread."): res.append(self.stats[k]) return res def get_breadth_stats(self): res = [] for k in self.stats: if k.startswith("iteration."): task_name = k.split('.') iternum = int(task_name[1]) if task_name[2] == 'size': size = int(task_name[3]) if task_name[4] == 'thread': thr = int(task_name[5]) else: assert False elif task_name[2] == 'thread': size = 1 thr = int(task_name[3]) else: assert False while len(res) < iternum: res.append([]) while len(res[iternum-1]) < size: res[iternum-1].append([]) res[iternum-1][size-1].append(self.stats[k]) return res def get_name_from_log(self, log): if use_old_names: if log.startswith("./logs/log."): name = '.'.join(log.split('.')[5:]) elif log.startswith("/pylon5/ms5pijp/tjhance/log."): name = '.'.join(log.split('.')[4:]) else: assert False return name else: if log.startswith("./logs/log."): name = log.split('/')[-1] elif log.startswith("/pylon5/ms5pijp/tjhance/log."): name = log.split('/')[-1] else: assert False return name class Breakdown(object): def __init__(self, stats, skip=False): if skip: return self.stats = stats self.total_smt_ms = 0 for k in stats: if "TOTAL sat time" in k or "TOTAL unsat time" in k: self.total_smt_ms += stats[k] self.total_smt_secs = self.total_smt_ms / 1000 self.filter_secs = stats["total time filtering"] / 1000 self.cex_secs = stats["total time processing counterexamples"] / 1000 self.nonredundant_secs = stats["total time processing nonredundant"] / 1000 self.redundant_secs = stats["total time processing redundant"] / 1000 self.total_cex = ( stats["Counterexamples of type FALSE"] + stats["Counterexamples of type TRUE"] + stats["Counterexamples of type TRANSITION"] ) self.total_invs = ( stats["number of non-redundant invariants found"] + stats["number of redundant invariants found"] ) def add(self, other): b = Breakdown(None, skip=True) for attr in ( "total_smt_ms", "filter_secs", "cex_secs", "nonredundant_secs", "redundant_secs", "total_cex"): setattr(b, attr, getattr(self, attr) + getattr(other, attr)) b.stats = {"total_time": self.stats["total_time"] + other.stats["total_time"]} return b def sum_breakdowns(l): t = l[0] for i in range(1, len(l)): t = t.add(l[i]) return t def get_longest(stat_list): assert len(stat_list) > 0 t = stat_list[0] for l in stat_list: if l["total_time"] > t["total_time"]: t = l return t def get_longest_that_succeed(stat_list): assert len(stat_list) > 0 t = stat_list[0] for l in stat_list: if l["total_time"] > t["total_time"] and l["number of finisher invariants found"] > 0: t = l return t class BasicStats(object): def __init__(self, input_directory, name, filename, I4=None): self.I4_time = I4 self.name = name self.filename = filename with open(os.path.join(input_directory, map_filename_maybe(filename), "summary")) as f: doing_total = False self.z3_sat_ops = 0 self.z3_sat_time = 0 self.z3_unsat_ops = 0 self.z3_unsat_time = 0 self.cvc4_sat_ops = 0 self.cvc4_sat_time = 0 self.cvc4_unsat_ops = 0 self.cvc4_unsat_time = 0 self.breadth_total_time_sec = 0 self.finisher_time_sec = 0 self.total_time_filtering_ms = 0 self.total_inductivity_check_time_ms = 0 self.num_inductivity_checks = 0 self.timed_out_6_hours = False self.global_stats = {} self.total_long_smtAllQueries_ops = 0 self.total_long_smtAllQueries_ms = 0 for line in f: if line.strip() == "total": doing_total = True if line.startswith("total time: "): self.total_time_sec = float(line.split()[2]) self.total_cpu_time_sec = float(line.split()[7]) elif line.startswith("Number of threads: "): self.num_threads = int(line.split()[3]) elif line.startswith("Number of invariants synthesized: "): self.num_inv = int(line.split()[4]) elif line.startswith("Number of iterations of BREADTH: "): self.num_breadth_iters = int(line.split()[5]) elif line.startswith("Number of iterations of FINISHER: "): self.num_finisher_iters = int(line.split()[5]) elif line.startswith("Success: True"): self.success = True elif line.startswith("Success: False"): self.success = False elif line.startswith("FINISHER time: "): self.finisher_time_sec= float(line.split()[2]) elif line.startswith("BREADTH iteration "): self.breadth_total_time_sec += float(line.split()[4]) elif line.strip() == "TIMED OUT 21600 seconds": self.timed_out_6_hours = True self.total_time_sec = 21600 elif line.startswith("global_stats "): s = line.split() name = s[1] key = s[2] rest = s[3:] if name not in self.global_stats: self.global_stats[name] = {} self.global_stats[name][key] = rest elif doing_total: if line.startswith("Counterexamples of type FALSE"): self.cex_false = int(line.split()[-1]) elif line.startswith("Counterexamples of type TRUE"): self.cex_true = int(line.split()[-1]) elif line.startswith("Counterexamples of type TRANSITION"): self.cex_trans = int(line.split()[-1]) elif line.startswith("number of candidates could not determine inductiveness"): self.inv_indef = int(line.split()[-1]) elif line.startswith("number of redundant invariants found"): self.num_redundant = int(line.split()[-1]) elif line.startswith("z3 TOTAL sat ops"): self.z3_sat_ops = int(line.split()[-1]) elif line.startswith("z3 TOTAL sat time"): self.z3_sat_time = int(line.split()[-2]) elif line.startswith("z3 TOTAL unsat ops"): self.z3_unsat_ops = int(line.split()[-1]) elif line.startswith("z3 TOTAL unsat time"): self.z3_unsat_time = int(line.split()[-2]) elif line.startswith("cvc4 TOTAL sat ops"): self.cvc4_sat_ops = int(line.split()[-1]) elif line.startswith("cvc4 TOTAL sat time"): self.cvc4_sat_time = int(line.split()[-2]) elif line.startswith("cvc4 TOTAL unsat ops"): self.cvc4_unsat_ops = int(line.split()[-1]) elif line.startswith("cvc4 TOTAL unsat time"): self.cvc4_unsat_time = int(line.split()[-2]) elif line.startswith("total time filtering"): self.total_time_filtering_ms = int(line.split()[-2]) elif line.startswith("long smtAllQueries ops"): self.total_long_smtAllQueries_ops = int(line.split()[-1]) elif line.startswith("long smtAllQueries time"): self.total_long_smtAllQueries_ms = int(line.split()[-2]) if "[init-check] sat ops" in line: self.num_inductivity_checks += int(line.split()[-1]) elif "[init-check] unsat ops" in line: self.num_inductivity_checks += int(line.split()[-1]) if ("[inductivity-check: " in line or "[init-check]" in line): s = line.split() if s[-1] == "ms" and s[-4] == "time": self.total_inductivity_check_time_ms += int(s[-2]) self.smt_time_sec = (self.z3_sat_time + self.z3_unsat_time + self.cvc4_sat_time + self.cvc4_unsat_time) // 1000 self.smt_ops = self.z3_sat_ops + self.z3_unsat_ops + self.cvc4_sat_ops + self.cvc4_unsat_ops self.total_inductivity_check_time_sec = ( self.total_inductivity_check_time_ms / 1000) self.total_time_filtering_sec = ( self.total_time_filtering_ms / 1000) def get_global_stat_avg(self, name): return float(self.global_stats[name]["avg"][0]) def get_global_stat_percentile(self, name, percentile): assert len(self.global_stats[name]["percentiles"]) == 101 return int(self.global_stats[name]["percentiles"][percentile]) class Hatch(object): def __init__(self): pass class Table(object): def __init__(self, column_names, rows, calc_fn, source_column=False, borderless=False): self.source_column = source_column self.column_names = [] self.column_alignments = [] self.column_double = [] self.borderless = borderless for stuff in column_names: if stuff != '||': alignment, c = stuff self.column_names.append(c) self.column_double.append(False) self.column_alignments.append(alignment) else: self.column_double[-1] = True self.rows = [] self.rows.append(self.column_names) self.row_double = [] hatch_ctr = 0 self.hatch_lines = [] for r in rows: if r == '||': self.row_double[-1] = True continue self.row_double.append(False) new_r = [] for column_double, c in zip(self.column_double, self.column_names): x = calc_fn(r, c) if isinstance(x, Hatch): hatch_ctr += 1 if column_double: new_r.append("\\hatchdouble{" + str(hatch_ctr) + "}{1}") else: new_r.append("\\hatch{" + str(hatch_ctr) + "}{1}") self.hatch_lines.append("\\HatchedCell{start"+str(hatch_ctr)+"}{end"+str(hatch_ctr)+"}{pattern color=black!70,pattern=north east lines}") else: assert x != None s = str(x) new_r.append(s) self.rows.append(new_r) def dump(self): colspec = "|" if self.source_column: colspec = "|c|" for (al, d) in zip(self.column_alignments, self.column_double): if d: colspec += al+"||" else: colspec += al+"|" source_col = [ "\\multirow{1}{*}{\\S\\ref{sec-sdl}}", "\\multirow{8}{*}{\\cite{I4}}", "\\multirow{13}{*}{\\cite{fol-sep}}", "\\multirow{7}{*}{\\cite{paxos-made-epr}}", ] source_col_idx = 0 if self.borderless: colspec = colspec[1 : -1] s = "\\begin{tabular}{" + colspec + "}\n" if not self.borderless: s += "\\hline\n" column_widths = [max(len(self.rows[r][c]) for r in range(len(self.rows))) + 1 for c in range(len(self.column_names))] for i in range(len(self.rows)): if self.source_column: if i == 0: s += "Source &" else: s += " &" for j in range(len(self.column_names)): s += (" " * (column_widths[j] - len(self.rows[i][j]))) + self.rows[i][j] if j == len(self.column_names) - 1: if i == 0 or self.row_double[i-1]: if self.borderless: s += " \\\\ \\hline" else: s += " \\\\ \\hline \\hline" if self.source_column: s += "\n" + source_col[source_col_idx] source_col_idx += 1 else: if self.source_column and i != len(self.rows) - 1: s += " \\\\ \\cline{2-"+str(len(self.column_names)+1)+"}" else: if self.borderless and (i == len(self.rows) - 1): s += " \\\\" else: s += " \\\\ \\hline" s += "\n" else: s += " &" s += "\\end{tabular}\n" for h in self.hatch_lines: s += h + "\n" print(s, end="") def read_I4_data(input_directory): def real_line_parse_secs(l): # e.g., real 0m0.285s k = l.split('\t')[1] t = k.split('m') minutes = int(t[0]) assert t[1][-1] == "s" seconds = float(t[1][:-1]) return minutes*60.0 + seconds i4_filename = os.path.join(input_directory, "I4-output.txt") if not os.path.exists(i4_filename): return None with open(i4_filename) as f: return json.loads(f.read()) def commaify(n): n = str(n) s = "" for i in range(0, len(n))[::-1]: if len(n) - i > 1 and (len(n) - i) % 3 == 1: s = "," + s s = n[i] + s return s def commaify1(n): if n == 820878178: return '$820 \cdot 10^6$~' elif n == 3461137: return '$3 \cdot 10^6$' elif n == 98828918711712: return '$99 \cdot 10^{12}$' elif n == 232460599445: return '$232 \cdot 10^{9}$' else: return commaify(n) def I4_get_res(d, r): if d == None: return None if get_bench_existential(r): return None #b1 = get_bench_name(r) #if b1 == 'sdl': # b1 = 'simple-de-lock' #if b1 == 'ring-election': # b1 = 'leader-election' #if b1 == 'two-phase-commit': # b1 = '2pc' #if b1 == 'distributed-lock': # b1 = 'distributed_lock' b1 = r.split('__')[1] if b1 == '2PC': b1 = '2pc' if b1.endswith("_pyv"): b1 = b1[:-4] if b1 == 'learning-switch-quad': b1 = 'learning-switch-quat' if not d[b1]["success"]: return None return d[b1]["time_secs"] def read_folsep_json(input_directory): json_file = os.path.join(input_directory, "folsep.json") if os.path.exists(json_file): with open(os.path.join(input_directory, "folsep.json")) as f: j = f.read() return json.loads(j) else: return None def folsep_json_get_res(j, r): if j == None: return None name = get_bench_name(r) fol_name = { "client-server-ae": "client_server_ae", "client-server-db-ae": "client_server_db_ae", "toy-consensus-epr": "toy_consensus_epr", "toy-consensus-forall": "toy_consensus_forall", "consensus-epr": "consensus_epr", "consensus-forall": "consensus_forall", "consensus-wo-decide": "consensus_wo_decide", "hybrid-reliable-broadcast": "hybrid_reliable_broadcast_cisa", "learning-switch-quad": "learning_switch", "lock-server-async": "lockserv", "sharded-kv": "sharded_kv", "sharded-kv-no-lost-keys": "sharded_kv_no_lost_keys", "ticket": "ticket", 'sdl': "simple-de-lock", 'ring-election': "ring_id", 'learning-switch-ternary': "learning_switch_ternary", 'lock-server-sync': "lock_server", 'two-phase-commit': "2PC", 'multi-paxos': "multi_paxos", 'flexible-paxos': "flexible_paxos", 'fast-paxos': "fast_paxos", 'vertical-paxos': "vertical_paxos", 'stoppable-paxos': "stoppable_paxos", 'chain': "chain", 'chord': "chord", 'distributed-lock': "distributed_lock", 'paxos': "paxos", }[name] for entry in j: if entry["name"] == fol_name: if entry["success"]: return entry["elapsed"] else: return None assert False, fol_name def get_bench_name(name): return get_bench_info(name)[1] def get_bench_existential(name): return get_bench_info(name)[2] #def get_bench_num_handwritten_invs(name): # return get_bench_info(name)[3] # #def get_bench_num_handwritten_terms(name): # return get_bench_info(name)[4] def get_bench_info(name): name = "_"+name if "pyv" in name: stuff = [ ("__client_server_ae_pyv__", "client-server-ae", True), ("__client_server_db_ae_pyv__", "client-server-db-ae", True), ("__toy_consensus_epr_pyv__", "toy-consensus-epr", True), ("__toy_consensus_forall_pyv__", "toy-consensus-forall", False), ("__consensus_epr_pyv__", "consensus-epr", True), ("__consensus_forall_pyv__", "consensus-forall", False), ("__consensus_wo_decide_pyv__", "consensus-wo-decide", False), ("__firewall_pyv__", "firewall", True), ("__hybrid_reliable_broadcast_cisa_pyv__", "hybrid-reliable-broadcast", True), ("__learning-switch-quad_pyv__", "learning-switch-quad", False), ("__lock-server-async_pyv__", "lock-server-async", False), #("__ring_id_pyv__", "ring-election-mypyvy"), ("__ring_id_not_dead_pyv__", "ring-election-not-dead", True), ("__sharded_kv_pyv__", "sharded-kv", False), ("__sharded_kv_no_lost_keys_pyv__", "sharded-kv-no-lost-keys", True), ("__ticket_pyv__", "ticket", False), ] else: stuff = [ ("__simple-de-lock__", 'sdl', False), ("__leader-election__", 'ring-election', False), ("__learning-switch-ternary__", 'learning-switch-ternary', False), ("__lock-server-sync__", 'lock-server-sync', False), ("__2PC__", 'two-phase-commit', False), ("__multi_paxos__", 'multi-paxos', True), ("__flexible_paxos__", 'flexible-paxos', True), ("__fast_paxos__", 'fast-paxos', True), ("__vertical_paxos__", 'vertical-paxos', True), ("__stoppable_paxos__", 'stoppable-paxos', True), ("__chain__", 'chain', False), ("__chord__", 'chord', False), ("__distributed_lock__", 'distributed-lock', False), ("__paxos__", 'paxos', True), ("__paxos_epr_missing1__", 'paxos-missing1', True), ] for a in stuff: if a[0] in name: return a print("need bench name for", name) assert False def get_basic_stats_or_fail(input_directory, r): return BasicStats(input_directory, get_bench_name(r), r) def get_basic_stats(input_directory, r): #assert paper_benchmarks.does_exist(r), r try: return BasicStats(input_directory, get_bench_name(r), r) except FileNotFoundError: return None def median(input_directory, r, a, b, fail_if_absent=False): t = [] for i in range(a, b+1): r1 = r.replace("#", str(i)) #if fail_if_absent: # s = get_basic_stats_or_fail(input_directory, r1) #else: s = get_basic_stats(input_directory, r1) if s != None: t.append(s) if len(t) == b - a + 1: assert len(t) % 2 == 1 t.sort(key=lambda s : s.total_time_sec) return t[len(t) // 2] else: if len(t) == 0: if fail_if_absent: raise Exception("median failed to get " + r + ": found none") return None all_timeout = all(s.timed_out_6_hours for s in t) if all_timeout: return t[0] else: if fail_if_absent: raise Exception("median failed to get " + r + ": did not time-out and there were not enough runs") return None def median_or_fail(input_directory, r, a, b): return median(input_directory, r, a, b, fail_if_absent=True) MAIN_TABLE_ROWS = [ "mm_nonacc__simple-de-lock__auto__seed#_t8", "||", "mm_nonacc__leader-election__auto_full__seed#_t8", "mm_nonacc__learning-switch-ternary__auto_e0_full__seed#_t8", "mm_nonacc__lock-server-sync__auto_full__seed#_t8", "mm_nonacc__2PC__auto_full__seed#_t8", "mm_nonacc__chain__auto__seed#_t8", "mm_nonacc__chord__auto__seed#_t8", "mm_nonacc__distributed_lock__auto9__seed#_t8", "||", "mm_nonacc__toy_consensus_forall_pyv__auto__seed#_t8", "mm_nonacc__consensus_forall_pyv__auto__seed#_t8", "mm_nonacc__consensus_wo_decide_pyv__auto__seed#_t8", "mm_nonacc__learning-switch-quad_pyv__auto__seed#_t8", "mm_nonacc__lock-server-async_pyv__auto9__seed#_t8", "mm_nonacc__sharded_kv_pyv__auto9__seed#_t8", "mm_nonacc__ticket_pyv__auto9__seed#_t8", "mm_nonacc__toy_consensus_epr_pyv__auto__seed#_t8", "mm_nonacc__consensus_epr_pyv__auto__seed#_t8", "mm_nonacc__client_server_ae_pyv__auto__seed#_t8", "mm_nonacc__client_server_db_ae_pyv__auto__seed#_t8", "mm_nonacc__sharded_kv_no_lost_keys_pyv__auto_e2__seed#_t8", "mm_nonacc__hybrid_reliable_broadcast_cisa_pyv__auto__seed#_t8", #"mm_nonacc__firewall_pyv__auto__seed#_t8", # ignoring because not EPR #"mm_nonacc__ring_id_pyv__auto__seed#_t8", #"mm_nonacc__ring_id_not_dead_pyv__auto__seed#_t8", # ignoring because not EPR "||", "mm_nonacc__paxos__auto__seed#_t8", "mm_nonacc__flexible_paxos__auto__seed#_t8", "mm_nonacc__multi_paxos__auto__seed#_t8", "mm_nonacc__multi_paxos__basic__seed1_t8", "mm_nonacc__fast_paxos__auto__seed#_t8", "mm_nonacc__stoppable_paxos__auto__seed#_t8", "mm_nonacc__vertical_paxos__auto__seed#_t8", ] def get_inv_analysis_info(input_directory, benchname): filename = os.path.join(input_directory, benchname, "inv_analysis") if os.path.exists(filename): with open(filename) as f: j = f.read() return json.loads(j) else: return {} def get_or_question_mark(inv_analysis_info, r, name, succ=None): if succ != None: if succ: name = "synthesized_" + name else: name = "handwritten_" + name if r in inv_analysis_info and name in inv_analysis_info[r]: return str(inv_analysis_info[r][name]) else: return "?" def make_comparison_table(input_directory, table, median_of=5): if "camera-ready-2020august-serenity" in input_directory: global use_old_names use_old_names = True rows = MAIN_TABLE_ROWS stats = { } # r : get_basic_stats(input_directory, r) for r in rows } inv_analysis_info = { } for r in rows: if r != '||': if use_old_names: r = r.replace("auto_full", "auto").replace("auto_e0_full","auto_e0") stats[r] = median(input_directory, r, 1, median_of) if stats[r]: fname = stats[r].filename inv_analysis_info[r] = get_inv_analysis_info( input_directory, fname) # l|r|c||r|r|r||r|r|r|r SWISS_INVS = '\\begin{tabular}{@{}c@{}}\\name \\\\ invs\\end{tabular}' SWISS_TERMS = '\\begin{tabular}{@{}c@{}}\\name \\\\ terms\\end{tabular}' #I4_COL = '\\begin{tabular}{@{}c@{}}I4 \\\\ \\cite{I4}\\end{tabular}' #FOL_COL = '\\begin{tabular}{@{}c@{}}FOL \\\\ \\cite{fol-sep}\\end{tabular}' I4_COL = 'I4~\\cite{I4}' FOL_COL = 'FOL~\\cite{fol-sep}' MAX_TERMS_STR = '$mt$' MAX_TERMS_M1_STR = '$mt_B$' SPLIT_COL = True cols1 = [ ('l', 'Benchmark'), #('r', 'invs'), #('r', 'terms'), ('c', '$\\exists$?'), '||', ('r', I4_COL), ('r', FOL_COL), ('r', '\\name'), ('r', 'Partial'), '||', ('r', '$t_B$'), ('r', '$t_F$'), ('r', '$n_B$'), #('r', SWISS_INVS), #('r', SWISS_TERMS), #('r', 'Partial'), '||', ('r', MAX_TERMS_STR), ('r', MAX_TERMS_M1_STR), ] LIST_NAME = 'list' cols2 = [ ('l', 'Benchmark'), ('l', 'Solved'), '||', ('r', 'total terms'), ('r', 'max vars'), ('r', LIST_NAME), #('r', 'Partial'), ] folsep_json = read_folsep_json(input_directory) i4_data = read_I4_data(input_directory) sec_suffix = " s." def format_secs(s): s = float(s) if s < 1.0: return "{:.1f}".format(s) + sec_suffix else: return str(int(s)) + sec_suffix def calc(r, c): if use_old_names: r = r.replace("auto_full", "auto").replace("auto_e0_full","auto_e0") did_succeed = (stats[r] != None and (not stats[r].timed_out_6_hours) and stats[r].success) if c == "Benchmark": bname = get_bench_name(r) if bname == "multi-paxos" and "basic" in r: return bname + "$^*$" return bname elif c == I4_COL: i4_time = I4_get_res(i4_data, r) if i4_time == None: return Hatch() else: return format_secs(i4_time) elif c == FOL_COL: folsep_time = folsep_json_get_res(folsep_json, r) if folsep_time == None: return Hatch() else: return format_secs(folsep_time) elif c == '$\\exists$?': return "$\\checkmark$" if get_bench_existential(r) else "" elif c == 'invs': return get_or_question_mark(inv_analysis_info, r, "invs", succ=did_succeed) elif c == 'total terms': return get_or_question_mark(inv_analysis_info, r, "terms", succ=did_succeed) elif c == 'max vars': return get_or_question_mark(inv_analysis_info, r, "max_vars", succ=did_succeed) elif c == 'Solved': return "$\\checkmark$" if did_succeed else "" elif c in (LIST_NAME, MAX_TERMS_STR, MAX_TERMS_M1_STR): names = (['synthesized'] if did_succeed else []) + ['handwritten'] t = [] for name1 in names: name = name1 + '_k_terms_by_inv' if r in inv_analysis_info and name in inv_analysis_info[r]: l = inv_analysis_info[r][name] a = max([0] + l[:-1]) b = l[-1] d = max(l) t.append((a,b,d)) if len(t) == 0: return '?' if len(t) == 1: a,b,d = t[0] if len(t) >= 2: t = sorted(t, key=lambda x : (x[2], x[0])) a,b,d = t[0] if c == LIST_NAME: if a == 0: return str(b) else: return "[" + str(a) + "...], " + str(b) elif c == MAX_TERMS_STR: return d elif c == MAX_TERMS_M1_STR: return ('' if a == 0 else a) else: assert False else: if stats[r] == None: return "TODO1" if stats[r].timed_out_6_hours: if (SPLIT_COL and c == 'Partial') or ((not SPLIT_COL) and c == '\\name'): invs_got = get_or_question_mark(inv_analysis_info, r, "invs_got") invs_total = get_or_question_mark(inv_analysis_info, r, "invs_total") return ( '(' + str(invs_got) + ' / ' + str(invs_total) + ')' ) elif c == '\\name': return Hatch() else: return "" if not stats[r].success: return "TODO2" if c == "$n_B$": return stats[r].num_breadth_iters elif c == "$t_F$": if stats[r].num_finisher_iters > 0: return format_secs(stats[r].finisher_time_sec) else: return "-" elif c == "$t_B$": return format_secs(stats[r].breadth_total_time_sec) elif c == "\\name": return format_secs(stats[r].total_time_sec) elif c == SWISS_INVS: return str(stats[r].num_inv) return get_or_question_mark(inv_analysis_info, r, "synthesized_invs") elif c == SWISS_TERMS: return get_or_question_mark(inv_analysis_info, r, "synthesized_terms") elif c == 'Partial': return '' else: assert False, c if table == 1: t = Table(cols1, rows, calc, source_column=True) t.dump() elif table == 2: t = Table(cols2, rows, calc) t.dump() else: assert False def make_optimization_step_table(input_directory): logfiles = [ "mm__paxos__basic_b__seed1_t1", "mm_whole__paxos_epr_missing1__basic__seed1_t1" ] thread_stats = { } counts = { } rows = [ ] for r in logfiles: s = median(input_directory, r, 1, 5) #assert s.success ts = ThreadStats(input_directory, s.filename) thread_stats[r] = ts full_name = os.path.join(input_directory, s.filename, "summary") for alg in ('breadth', 'finisher'): if alg == 'breadth': bs = ts.get_breadth_stats() if len(bs) != 0: rows.append((r, alg)) counts[(r, alg)] = get_counts.get_counts(full_name, alg) else: fs = ts.get_finisher_stats() if len(fs) != 0: rows.append((r, alg)) counts[(r, alg)] = get_counts.get_counts(full_name, alg) columns = [ ('l', ''), ('r', 'Baseline'), ('r', 'Sym.\\ '), ('r', 'Cex filters'), ('r', 'FastImpl'), #'||', ('r', 'Inv.'), ] def calc(row, col): r, alg = row ts = thread_stats[r] if alg == 'breadth': bs = ts.get_breadth_stats() stats = bs[0][-1][0] else: fs = ts.get_finisher_stats() stats = fs[0] if col == '': #return bench.name + (' (B)' if alg == 'breadth' else ' (F)') #rname = get_bench_name(r) #if rname == 'paxos-missing1': # rname = 'paxos' #return rname + (' (B)' if alg == 'breadth' else ' (F)') return '$\\B$' if alg == 'breadth' else '$\\F$' elif col == 'Baseline': return commaify1(counts[row].presymm) elif col == 'Sym.\\ ': return commaify1(counts[row].postsymm) elif col == 'Cex filters': return commaify(stats["Counterexamples of type FALSE"] + stats["Counterexamples of type TRANSITION"] + stats["Counterexamples of type TRUE"] + stats["number of non-redundant invariants found"] + stats["number of redundant invariants found"] + stats["number of finisher invariants found"] + stats["number of enumerated filtered redundant invariants"] ) elif col == 'FastImpl': return commaify(stats["Counterexamples of type FALSE"] + stats["Counterexamples of type TRANSITION"] + stats["Counterexamples of type TRUE"] + stats["number of non-redundant invariants found"] + stats["number of redundant invariants found"] + stats["number of finisher invariants found"] ) elif col == 'Inv.': return commaify( stats["number of non-redundant invariants found"] + stats["number of redundant invariants found"] + stats["number of finisher invariants found"] ) print("\\begin{center}") t = Table(columns, rows, calc, borderless=True) t.dump() print("\\end{center}") def get_files_with_prefix(input_directory, prefix): files = [] for filename in os.listdir(input_directory): if filename.startswith(prefix): files.append(filename) return files #def make_nonacc_cmp_graph(ax, input_directory): # a = get_files_with_prefix(input_directory, "paxos_breadth_seed_") # b = get_files_with_prefix(input_directory, "nonacc_paxos_breadth_seed_") # columns = ( # [(a[i], i+1, i+1) for i in range(len(a))] + # [(b[i], len(a) + 2 + i, i+1) for i in range(len(b))] # ) # ax.set_title("accumulation (paxos)") # make_segmented_graph(ax, input_directory, "", "", columns=columns) def make_parallel_graph(ax, input_directory, name, include_threads=False, include_breakdown=False, graph_cex_count=False, graph_inv_count=False, collapse_size_split=False, collapsed_breakdown=False, graph_title=None, smaller=False, legend=False): suffix = '' if graph_cex_count: suffix = ' (cex)' if graph_inv_count: suffix = ' (invs)' if graph_title == None: ax.set_title("parallel " + name + suffix) else: ax.set_title(graph_title) ax.set_ylabel("seconds") ax.set_xlabel("threads") make_segmented_graph(ax, input_directory, name, "_t", include_threads=include_threads, include_breakdown=include_breakdown, collapsed_breakdown=collapsed_breakdown, graph_cex_count=graph_cex_count, graph_inv_count=graph_inv_count, collapse_size_split=collapse_size_split, smaller=smaller,legend=legend) def make_seed_graph(ax, input_directory, name, title=None, include_threads=False, include_breakdown=False, skip_b=False, skip_f=False): if title is None: ax.set_title("seed " + name) else: ax.set_title(title) ax.set_ylabel("seconds") make_segmented_graph(ax, input_directory, name, "_seed_", include_threads=include_threads, include_breakdown=include_breakdown, skip_b=skip_b, skip_f=skip_f) ax.set_xticks([]) red = '#ff4040' lightred = '#ff8080' blue = '#4040ff' lightblue = '#8080ff' orange = '#ffa500' lightorange = '#ffd8b1' def slightly_darken(color): if color == red: return '#b02020' if color == lightred: return '#b06060' if color == blue: return '#6060b0' if color == lightblue: return '#6060b0' if color == orange: return '#ff8000' if color == lightorange: return '#ffa060' assert False def group_by_thread(s): res = [] a = 0 while a < len(s): b = a + 1 while b < len(s) and s[b][0] == s[a][0]: b += 1 res.append((s[a][0], sorted([s[i][2] for i in range(a, b)]))) a = b return res segment1_color = 'white' #'#009e73' segment2_color = 'white' #'#f0e442' filter_color = 'black' cex_color = '#d55e00' redundant_color = '#0072b2' nonredundant_color = '#56b4e9' inv_color = 'white' #'#0072b2' other_color = 'white' #'#cc79a7' other_hatch = '////' def make_segmented_graph(ax, input_directory, name, suffix, include_threads=False, include_breakdown=False, columns=None, graph_cex_count=False, graph_inv_count=False, skip_b=False, skip_f=False, collapse_size_split=False, collapsed_breakdown=False, smaller=False, legend=False): if legend: p = [ patches.Patch(edgecolor='black', facecolor=filter_color, label='Filtering'), patches.Patch(edgecolor='black', facecolor=cex_color, label='Counterex.'), patches.Patch(edgecolor='black', facecolor=inv_color, label='Inv.'), #patches.Patch(edgecolor='black', facecolor=nonredundant_color, label='Non-red.'), #patches.Patch(edgecolor='black', facecolor=other_color, label='Other', hatch=other_hatch) ] ax.legend(handles=p) if graph_cex_count or graph_inv_count: include_breakdown = True if columns is None: columns = [] for filename in os.listdir(input_directory): if filename.startswith(name + suffix): idx = int(filename[len(name + suffix) : ]) x_label = idx columns.append((filename, idx, x_label)) if smaller: columns = [c for c in columns if c[1] in (1,2,4,8)] if smaller: labels = [1,2,4,8] ticks = [1,2,3,4] else: labels = [a[2] for a in columns] ticks = [a[1] for a in columns] ax.set_xticks(ticks) ax.set_xticklabels(labels) for (filename, idx, label) in columns: ts = ThreadStats(input_directory, filename) times = [] thread_times = [] colors = [] breakdowns = [] stuff = [] if collapse_size_split: assert not include_breakdown assert not include_threads if not skip_b: bs = ts.get_breadth_stats() for i in range(len(bs)): this_size_time = 0 odd1 = i % 2 == 1 for j in range(len(bs[i])): inner_odd = j % 2 == 1 iternum = i+1 size = (j+1 if ts.uses_sizes else None) time_per_thread = sorted([s["total_time"] for s in bs[i][j]]) longest = get_longest(bs[i][j]) if not collapse_size_split: thread_times.append(time_per_thread) breakdowns.append(Breakdown(longest)) times.append(longest["total_time"]) if odd1: colors.append(segment1_color) else: colors.append(segment2_color) this_size_time += longest["total_time"] if collapse_size_split: times.append(this_size_time) if odd1: colors.append(segment1_color) else: colors.append(segment2_color) if not skip_f: fs = ts.get_finisher_stats() if len(fs) > 0: time_per_thread = sorted([s["total_time"] for s in fs]) thread_times.append(time_per_thread) longest = get_longest_that_succeed(fs) breakdowns.append(Breakdown(longest)) times.append(longest["total_time"]) colors.append(segment1_color) if collapsed_breakdown: assert not include_threads times = [sum(times)] breakdowns = [sum_breakdowns(breakdowns)] if smaller: idx = {1: 1, 2: 2, 4: 3, 8: 4}[idx] bottom = 0 for i in range(len(times)): if graph_cex_count or graph_inv_count: breakdown = breakdowns[i] c = (breakdown.total_cex if graph_cex_count else breakdown.total_invs) ax.bar(idx, c, bottom=bottom, color=colors[i], edgecolor='black') bottom += c else: t = times[i] if not collapsed_breakdown: if include_breakdown: ax.bar(idx - 0.2, t, bottom=bottom, width=0.4, color=colors[i], edgecolor='black') else: ax.bar(idx, t, bottom=bottom, color=colors[i], edgecolor='black') if include_breakdown or collapsed_breakdown: breakdown = breakdowns[i] a = bottom b = a + breakdown.filter_secs c = b + breakdown.cex_secs d = c + breakdown.nonredundant_secs e = d + breakdown.redundant_secs top = bottom + breakdown.stats["total_time"] e = top - breakdown.filter_secs d = e - breakdown.cex_secs c = d - breakdown.nonredundant_secs b = c - breakdown.redundant_secs a = bottom if collapsed_breakdown: center = idx width = 0.8 else: center = idx + 0.2 width = 0.4 ax.bar(center, b-a, bottom=a, width=width, color=other_color, edgecolor='black', hatch=other_hatch) ax.bar(center, c-b, bottom=b, width=width, color=inv_color, edgecolor='black') ax.bar(center, d-c, bottom=c, width=width, color=nonredundant_color, edgecolor='black') ax.bar(center, e-d, bottom=d, width=width, color=cex_color, edgecolor='black') ax.bar(center, top-e, bottom=e, width=width, color=filter_color, edgecolor='black') if not collapsed_breakdown: if include_threads: for j in range(len(thread_times[i])): thread_time = thread_times[i][j] m = len(thread_times[i]) if include_breakdown: ax.bar(idx - 0.4 + 0.4 * (j / float(m)) + 0.2 / float(m), thread_time, bottom=bottom, width = 0.4 / float(m), color=colors[i]) else: ax.bar(idx - 0.4 + 0.8 * (j / float(m)) + 0.4 / float(m), thread_time, bottom=bottom, width = 0.8 / float(m), color=colors[i]) bottom += t def get_total_time(input_directory, filename): with open(os.path.join(input_directory, map_filename_maybe(filename), "summary")) as f: for line in f: if line.startswith("total time: "): t = float(line.split()[2]) return t def make_opt_comparison_graph(ax, input_directory, opt_name): ax.set_yscale('log') #opts = ['mm_', 'postbmc_mm_', 'prebmc_mm_', 'postbmc_prebmc_mm_'] #if large_ones: # probs = ['flexible_paxos', 'learning_switch', 'paxos'] #else: # probs = ['2pc', 'leader_election_breadth', 'leader_election_fin', 'lock_server'] if opt_name == 'bmc': opts = ['mm_', 'prebmc_mm_'] #, 'postbmc_'] names = ['Baseline', 'With BMC'] elif opt_name == 'mm': opts = ['', 'mm_'] #, 'postbmc_'] names = ['Baseline', 'With minimal-models'] elif opt_name == 'both': if use_old_names: opts = ['', 'mm_', 'prebmc_mm_'] else: opts = ['nonacc_', 'mm_nonacc_', 'prebmc_mm_nonacc_'] names = ['Baseline', 'Min-models', 'Min-models + BMC'] else: assert False #colors = ['black', '#ff8080', '#8080ff', '#80ff80'] colors = ['black', '#E69F00', '#56b4e9'] prob_data = [ ('leader-election__basic_b__seed1_t8'), ('2PC__basic__seed1_t8'), ('learning-switch-ternary__basic__seed1_t8'), ('paxos__basic__seed1_t8'), ('flexible_paxos__basic__seed1_t8'), ('multi_paxos__basic__seed1_t8'), ] failures = [ 'prebmc__paxos__basic__seed1_t8', 'prebmc__multi_paxos__basic__seed1_t8', ] ax.set_xticks([i for i in range(1, len(prob_data) + 1)]) ax.set_xticklabels([get_bench_name("_"+prob) for prob in prob_data]) for tick in ax.get_xticklabels(): tick.set_rotation(30) tick.set_ha('right') patterns = [ None, "\\" , "/" , "+" ] idx = 0 for prob in prob_data: idx += 1 opt_idx = -1 for (opt, color, pattern) in zip(opts, colors, patterns): opt_idx += 1 name = opt + "_" + prob if name not in failures: t = get_total_time(input_directory, name) ax.bar(idx - 0.4 + 0.4/len(opts) + 0.8/len(opts) * opt_idx, t, bottom=0, width=0.8/len(opts), color=color, edgecolor='black') #hatch=pattern) p = [] for (opt, opt_name_label, color, pattern) in zip(opts, names, colors, patterns): p.append(patches.Patch(color=color, label=opt_name_label)) ax.legend(handles=p) PAXOS_FINISHER_THREAD_BENCH = "mm_whole__paxos_epr_missing1__basic__seed1" # _t1 _t2 ... _t8 PAXOS_NONACC_THREAD_BENCH = "mm_nonacc__paxos__basic_b__seed1" def make_parallel_graphs(input_directory, save=False): if "camera-ready-2020august-serenity" in input_directory: global use_old_names use_old_names = True output_directory = "graphs" Path(output_directory).mkdir(parents=True, exist_ok=True) fig, ax = plt.subplots(nrows=2, ncols=3, figsize=[7, 6]) plt.gcf().subplots_adjust(bottom=0.20) ax.flat[1].set_ylim(bottom=0, top=1500) ax.flat[2].set_ylim(bottom=0, top=1500) ax.flat[4].set_ylim(bottom=0, top=1500) ax.flat[5].set_ylim(bottom=0, top=1500) #finisher = "mm__paxos_epr_missing1__basic__seed1" # _t1 _t2 ... _t8 finisher = PAXOS_FINISHER_THREAD_BENCH breadth_acc = "mm__paxos__basic_b__seed1" breadth_nonacc = PAXOS_NONACC_THREAD_BENCH make_parallel_graph(ax.flat[0], input_directory, finisher, graph_title="Finisher", smaller=True) make_parallel_graph(ax.flat[1], input_directory, breadth_nonacc, collapse_size_split=True, graph_title="Breadth", smaller=True) make_parallel_graph(ax.flat[2], input_directory, breadth_acc, graph_title="BreadthAccumulative", smaller=True) make_parallel_graph(ax.flat[3], input_directory, finisher, collapsed_breakdown=True, graph_title="Finisher", smaller=True) make_parallel_graph(ax.flat[4], input_directory, breadth_nonacc, collapsed_breakdown=True, graph_title="Breadth", smaller=True) make_parallel_graph(ax.flat[5], input_directory, breadth_acc, collapsed_breakdown=True, graph_title="BreadthAccumulative", smaller=True, legend=True) #https://stackoverflow.com/questions/26084231/draw-a-separator-or-lines-between-subplots # Get the bounding boxes of the axes including text decorations axes = ax r = fig.canvas.get_renderer() get_bbox = lambda ax: ax.get_tightbbox(r).transformed(fig.transFigure.inverted()) bboxes = np.array(list(map(get_bbox, axes.flat)), mtrans.Bbox).reshape(axes.shape) #Get the minimum and maximum extent, get the coordinate half-way between those ymax = np.array(list(map(lambda b: b.y1, bboxes.flat))).reshape(axes.shape).max(axis=1) ymin = np.array(list(map(lambda b: b.y0, bboxes.flat))).reshape(axes.shape).min(axis=1) ys = np.c_[ymax[1:], ymin[:-1]].mean(axis=1) # Draw a horizontal lines at those coordinates for y in ys: line = plt.Line2D([0,1],[y-0.025,y-0.025], transform=fig.transFigure, color="black") fig.add_artist(line) plt.tight_layout() if save: fname = os.path.join(output_directory, 'paxos-parallel.png') print(fname) plt.savefig(fname) else: plt.show() def make_opt_graphs_main(input_directory, save=False, mm=False, both=False): if "camera-ready-2020august-serenity" in input_directory: global use_old_names use_old_names = True output_directory = "graphs" Path(output_directory).mkdir(parents=True, exist_ok=True) fig, ax = plt.subplots(nrows=1, ncols=1, figsize=[6.5, 4]) plt.gcf().subplots_adjust(bottom=0.45) ax.set_ylabel("seconds") if both: make_opt_comparison_graph(ax, input_directory, 'both') elif mm: make_opt_comparison_graph(ax, input_directory, 'mm') else: make_opt_comparison_graph(ax, input_directory, 'bmc') if save: if both: fname = os.path.join(output_directory, 'opt-comparison-both.png') elif mm: fname = os.path.join(output_directory, 'opt-comparison-mm.png') else: fname = os.path.join(output_directory, 'opt-comparison-bmc.png') print(fname) plt.savefig(fname) else: plt.show() #def make_seed_graphs_main(input_directory, save=False): # output_directory = "graphs" # Path(output_directory).mkdir(parents=True, exist_ok=True) # # fig, ax = plt.subplots(nrows=1, ncols=4, figsize=[12, 3]) # plt.gcf().subplots_adjust(bottom=0.20) # # make_seed_graph(ax.flat[0], input_directory, "wc_learning-switch-ternary", title="Learning switch (BreadthAccumulative)") # make_seed_graph(ax.flat[1], input_directory, "wc_bt_paxos", title="Paxos (BreadthAccumulative)", skip_f=True) # make_seed_graph(ax.flat[2], input_directory, "wc_bt_paxos", title="Paxos (Finisher)", skip_b=True) # make_seed_graph(ax.flat[3], input_directory, "wholespace_finisher_bt_paxos", title="Paxos (Finisher, entire space)") # fig.tight_layout() # if save: # plt.savefig(os.path.join(output_directory, 'seed.png')) # else: # plt.show() def misc_stats(input_directory, median_of=5): if "camera-ready-2020august-serenity" in input_directory: global use_old_names use_old_names = True def p(key, value, comment=""): print("\\newcommand{\\" + key + "}{" + str(value) + "}" + ("" if comment == "" else " % " + str(comment))) paxos_1_threads = get_basic_stats_or_fail(input_directory, PAXOS_FINISHER_THREAD_BENCH + "_t1") paxos_2_threads = get_basic_stats_or_fail(input_directory, PAXOS_FINISHER_THREAD_BENCH + "_t2") paxos_8_threads = get_basic_stats_or_fail(input_directory, PAXOS_FINISHER_THREAD_BENCH + "_t8") paxos_b_1_threads = get_basic_stats_or_fail(input_directory, PAXOS_NONACC_THREAD_BENCH + "_t1") paxos_b_8_threads = get_basic_stats_or_fail(input_directory, PAXOS_NONACC_THREAD_BENCH + "_t8") def speedup(s, t): x = t.total_time_sec / s.total_time_sec return "{:.1f}".format(x) p("paxosTwoThreadSpeedup", speedup(paxos_2_threads, paxos_1_threads)) p("paxosEightThreadSpeedup", speedup(paxos_8_threads, paxos_1_threads)) p("paxosBreadthNonaccEightThreadsSpeedup", speedup(paxos_b_8_threads, paxos_b_1_threads)) p("learningSwitchTernaryAutoEZeroNumTemplates", 45) p("learningSwitchTernaryAutoEZeroTotalSize", "\\ensuremath{\\sim 10^8}", 102141912) p("learningSwitchTernaryAutoNumTemplates", 69) p("learningSwitchTernaryAutoTotalSize", "\\ensuremath{\\sim 10^8}", 142327951) p("learningSwitchQuadAutoNumTemplates", 21) p("learningSwitchQuadAutoTotalSize", "\\ensuremath{8\\times 10^6}", 8174934) p("paxosBreadthNumTemplates", 684) p("paxosBreadthTotalSize", "\\ensuremath{3 \\times 10^5}", 366402) p("paxosFinisherTheOneSize", "\\ensuremath{1.6 \\times 10^{10}}", 16862630188) p("paxosBreadthNth", "\\ensuremath{569^{\\text{th}}}") if use_old_names: p("flexiblePaxosMMSpeedup", speedup( get_basic_stats_or_fail(input_directory, 'mm__flexible_paxos__basic__seed1_t8'), get_basic_stats_or_fail(input_directory, '_flexible_paxos__basic__seed1_t8'))) else: p("flexiblePaxosMMSpeedup", speedup( get_basic_stats_or_fail(input_directory, 'mm_nonacc__flexible_paxos__basic__seed1_t8'), get_basic_stats_or_fail(input_directory, 'nonacc__flexible_paxos__basic__seed1_t8'))) def read_counts(): d = [] with open("scripts/paxos-spaces-sorted.txt") as f: for l in f: s = l.split() k = int(s[2]) count = int(s[6]) vs = [int(s[8]), int(s[12]), int(s[16]), int(s[20])] d.append((k, count, vs)) return d counts = read_counts() def num_nonzero(vs): t = 0 for i in vs: if i != 0: t += 1 return t def sum_counts(counts, max_k, max_vs): total = 0 for (k, count, vs) in counts: #if (k <= max_k and # vs[0] <= max_vs[0] and # vs[1] <= max_vs[1] and # vs[2] <= max_vs[2] and # vs[3] <= max_vs[3]): if count <= 16862630188: total += count * (1 + num_nonzero(vs)) return total #p("paxosUpToTotal", sum_counts(counts, 6, [2,2,1,1])) #934,257,540,926 p("paxosUpToTotal", "\ensuremath{\sim 10^{12}}", 934257540926) p("paxosUpToTotalSmall", "\ensuremath{\sim 2 \\times 10^{11}}", 232460599445) p("paxosUserGuidanceSavingPercent", str(int((934257540926 - 232460599445) * 100 / 934257540926))) m = median_or_fail(input_directory, "mm_nonacc__paxos__auto__seed#_t8", 1, median_of) p("paxosUserGuidanceSavingTime", speedup( get_basic_stats_or_fail(input_directory, "mm_nonacc__paxos__basic__seed1_t8"), m)) p("paxosFinisherOneThreadSmtAverage", "{:.1f}".format(paxos_1_threads.get_global_stat_avg("total"))) p("paxosFinisherOneThreadSmtMedian", paxos_1_threads.get_global_stat_percentile("total", 50)) p("paxosFinisherOneThreadSmtNinetyFifthPercentile", paxos_1_threads.get_global_stat_percentile("total", 95)) p("paxosFinisherOneThreadSmtNinetyNinthPercentile", paxos_1_threads.get_global_stat_percentile("total", 95)) p("paxosFinisherOneThreadFilterAvg", int(paxos_1_threads.total_time_filtering_ms * (10**6) / 232460599445)) p("paxosFinisherOneThreadCandidateAvg", int(paxos_1_threads.total_time_filtering_ms * (10**6) / 232460599445)) p("paxosNumCexes", paxos_1_threads.cex_false + paxos_1_threads.cex_true + paxos_1_threads.cex_trans) p("paxosNumInductivityChecks", paxos_1_threads.cex_false + paxos_1_threads.cex_true + paxos_1_threads.cex_trans + paxos_1_threads.inv_indef + ThreadStats(input_directory, paxos_1_threads.filename).get_finisher_stats()[0]["number of finisher invariants found"]) total_solved = 0 total_solved_breadth_only = 0 total_solved_finisher_only = 0 for r in MAIN_TABLE_ROWS: if r == '||': continue if use_old_names: r = r.replace("auto_full", "auto").replace("auto_e0_full","auto_e0") stats = median_or_fail(input_directory, r, 1, median_of) if not stats.timed_out_6_hours and stats.success: total_solved += 1 if stats.num_finisher_iters == 0: total_solved_breadth_only += 1 s = r.replace('#', '1').split('__') s[0] += "_fonly" fonly_name = '__'.join(s) if use_old_names: maps = { "mm_nonacc__leader-election__auto__seed#_t8": "mm_nonacc_fonly__leader-election__auto_full__seed1_t8", "mm_nonacc__learning-switch-ternary__auto_e0__seed#_t8": "mm_nonacc_fonly__learning-switch-ternary__auto_e0_full__seed1_t8", "mm_nonacc__lock-server-sync__auto__seed#_t8": "mm_nonacc_fonly__lock-server-sync__auto_full__seed1_t8", "mm_nonacc__2PC__auto__seed#_t8": "mm_nonacc_fonly__2PC__auto_full__seed1_t8", } if r in maps: fonly_name = maps[r] fonly_stats = get_basic_stats(input_directory, fonly_name) if r == 'mm_nonacc__sharded_kv_no_lost_keys_pyv__auto_e2__seed#_t8': total_solved_finisher_only += 1 continue if fonly_stats == None: pass #print(r) else: if not fonly_stats.timed_out_6_hours and fonly_stats.success: total_solved_finisher_only += 1 p("totalSolved", total_solved) p("totalSolvedBreadthOnly", total_solved_breadth_only) p("totalSolvedFinisherOnly", total_solved_finisher_only) #def percent_of_time_hard_smt(r): # return 100.0 * float(r.total_long_smtAllQueries_ms) / (float(r.total_cpu_time_sec) * 1000) #for r in MAIN_TABLE_ROWS: # if r == '||': continue # m = median_or_fail(input_directory, r, 1, median_of) # if hasattr(m, 'total_cpu_time_sec'): # print(m.filename) # print(percent_of_time_hard_smt(m)) # else: # #print(r) # pass def templates_table(input_directory): rows = [ "mm_nonacc_whole__paxos_epr_missing1__basic__seed1_t8", "mm_nonacc_whole__paxos_epr_missing1__basic2__seed1_t8", "||", "mm_nonacc__paxos_epr_missing1__wrong1__seed1_t8", "mm_nonacc__paxos_epr_missing1__wrong2__seed1_t8", "mm_nonacc__paxos_epr_missing1__wrong3__seed1_t8", "mm_nonacc__paxos_epr_missing1__wrong5__seed1_t8", "mm_nonacc__paxos_epr_missing1__wrong4__seed1_t8", ] unwhole_map = { "mm_nonacc_whole__paxos_epr_missing1__basic__seed1_t8": "mm_nonacc__paxos_epr_missing1__basic__seed1_t8", "mm_nonacc_whole__paxos_epr_missing1__basic2__seed1_t8": "mm_nonacce__paxos_epr_missing1__basic2__seed1_t8", } cols = [ ('l', '\\#'), ('l', 'Template'), ('c', 'Inv?'), ('r', 'Size'), ('r', 'Time'), ] suite = templates.read_suite("benchmarks/paxos_epr_missing1.ivy") def q_string(q): s = q.split() sorts = s[1:] assert s[0] in ('forall', 'exists') res = "\\" + s[0] + " " seen = set() a = 0 while a < len(sorts): assert sorts[a] not in seen seen.add(sorts[a]) b = a+1 while b < len(sorts) and sorts[b] == sorts[a]: b += 1 n_occur = b-a l = sorts[a][0] if a > 0: res += ", " res += ",".join(l+"_{"+str(i)+"}" for i in range(1,n_occur+1)) res += ":\\sort{" + sorts[a] + "}" a = b return res+".~" def templ_string(r): config_name = r.split('__')[2] bench = suite.get(config_name) t = bench.finisher_space.spaces[0].templ qs = t.split('.') return "$" + " ".join(q_string(q) for q in qs) + "*" + "$" def read_counts(): d = [] with open("scripts/paxos-spaces-sorted.txt") as f: for l in f: s = l.split() k = int(s[2]) count = int(s[6]) vs = [int(s[8]), int(s[12]), int(s[16]), int(s[20])] d.append((k, count, vs)) return d counts = read_counts() def sum_counts(counts, max_k, max_vs): total = 0 for (k, count, vs) in counts: if (k <= max_k and vs[0] <= max_vs[0] and vs[1] <= max_vs[1] and vs[2] <= max_vs[2] and vs[3] <= max_vs[3]): total += count return total sizes = { #"basic": 16862630188 #"basic2": 16862630188 #"wrong1": 16862630188 "basic": sum_counts(counts, 6, [2,2,1,1]), "basic2": sum_counts(counts, 6, [2,2,1,1]), "wrong1": sum_counts(counts, 6, [2,2,1,1]), "wrong2": sum_counts(counts, 6, [1,3,0,1]), "wrong3": sum_counts(counts, 6, [1,1,0,4]), "wrong4": sum_counts(counts, 6, [2,2,0,2]), "wrong5": sum_counts(counts, 6, [2,1,2,1]), } def calc(r, c): if c == 'Template': return templ_string(r) elif c == 'Inv?': if 'wrong' in r: return '' else: return '$\\checkmark$' elif c == 'Size': return commaify(sizes[r.split('__')[2]]) elif c == '\\#': only_rows = [r for r in rows if r != '||'] return only_rows.index(r) + 1 elif c == 'Time': stats = get_basic_stats(input_directory, r) if stats.timed_out_6_hours: #return '$>21600$' assert r == "mm_nonacc__paxos_epr_missing1__wrong4__seed1_t8" return "47231" else: return int(stats.total_time_sec) #elif c == 'Solve time': # if r in unwhole_map: # r2 = unwhole_map[r] # stats = get_basic_stats(input_directory, r2) # return int(stats.total_time_sec) # else: # return '' t = Table(cols, rows, calc) t.dump() def stuff(): directory = sys.argv[1] input_directory = os.path.join("paperlogs", directory) output_directory = os.path.join("graphs", directory) Path(output_directory).mkdir(parents=True, exist_ok=True) fig, ax = plt.subplots(nrows=3, ncols=5, figsize=[6, 8]) #make_parallel_graph(ax.flat[0], input_directory, "paxos_breadth", False) #make_parallel_graph(ax.flat[1], input_directory, "paxos_implshape_finisher", False) #make_seed_graph(ax.flat[2], input_directory, "learning_switch", False) #make_seed_graph(ax.flat[3], input_directory, "paxos_breadth", False) #make_parallel_graph(ax.flat[5], input_directory, "paxos_breadth", False) #make_parallel_graph(ax.flat[6], input_directory, "paxos_implshape_finisher", True) #make_seed_graph(ax.flat[7], input_directory, "learning_switch", True) #make_seed_graph(ax.flat[8], input_directory, "paxos_breadth", True) make_opt_comparison_graph(ax.flat[10], input_directory) make_opt_comparison_graph(ax.flat[11], input_directory) #make_nonacc_cmp_graph(ax.flat[12], input_directory) #make_seed_graph(ax.flat[2], input_directory, "paxos_breadth", True) #make_parallel_graph(ax.flat[7], input_directory, "paxos_breadth", True) #make_parallel_graph(ax.flat[12], input_directory, "nonacc_paxos_breadth", True) #make_parallel_graph(ax.flat[8], input_directory, "paxos_breadth", True, graph_cex_count=True) #make_parallel_graph(ax.flat[13], input_directory, "nonacc_paxos_breadth", False, graph_cex_count=True) #make_parallel_graph(ax.flat[9], input_directory, "paxos_breadth", True, graph_inv_count=True) #make_parallel_graph(ax.flat[14], input_directory, "nonacc_paxos_breadth", False, graph_inv_count=True) #plt.savefig(os.path.join(output_directory, 'graphs.png')) plt.show() def main(): input_directory = sys.argv[1] if "camera-ready-2020august-serenity" in input_directory: global use_old_names use_old_names = True #stuff() #make_parallel_graphs(input_directory) #make_seed_graphs_main(input_directory) #make_smt_stats_table(input_directory) #make_opt_graphs_main(input_directory, both=True) #make_optimization_step_table(input_directory) make_comparison_table(input_directory, 1, median_of=1) #misc_stats(input_directory) #templates_table(input_directory) if __name__ == '__main__': main() <file_sep>/src/alt_synth_enumerator.cpp #include "alt_synth_enumerator.h" #include <algorithm> #include "enumerator.h" #include "var_lex_graph.h" #include "auto_redundancy_filters.h" using namespace std; AltDisjunctCandidateSolver::AltDisjunctCandidateSolver( shared_ptr<Module> module, TemplateSpace const& tspace) : progress(0) , module(module) , disj_arity(tspace.k) , tspace(tspace) , taqd(v_template_hole()) , start_from(-1) , done_cutoff(0) , finish_at_cutoff(false) { cout << "Using AltDisjunctCandidateSolver" << endl; cout << "disj_arity: " << disj_arity << endl; assert (tspace.depth == 1); value templ = tspace.make_templ(module); taqd = TopAlternatingQuantifierDesc(templ); EnumInfo ei(module, templ); pieces = ei.clauses; //cout << "Using " << pieces.size() << " terms" << endl; //for (value p : pieces) { // cout << "piece: " << p->to_string() << endl; //} //assert(false); init_piece_to_index(); cur_indices = {}; done = false; var_index_states.resize(disj_arity + 2); ts = build_transition_system( get_var_index_init_state(module, templ), ei.var_index_transitions, -1); existing_invariant_trie = SubsequenceTrie(pieces.size()); cout << "ello" << endl; for (vector<int> const& indices : get_auto_redundancy_filters(pieces)) { // These are things we want to filter out. They aren't necessarily invariant, // though! Only call existing_invariants_append, not addExistingInvariant. existing_invariants_append(indices); } } void AltDisjunctCandidateSolver::addCounterexample(Counterexample cex) { cout << "add counterexample" << endl; assert (!cex.none); assert (cex.is_true || cex.is_false || (cex.hypothesis && cex.conclusion)); cexes.push_back(cex); int i = cexes.size() - 1; AlternationBitsetEvaluator abe1; AlternationBitsetEvaluator abe2; if (cex.is_true) { abe2 = AlternationBitsetEvaluator::make_evaluator( cex.is_true, pieces[0]); } else if (cex.is_false) { abe1 = AlternationBitsetEvaluator::make_evaluator( cex.is_false, pieces[0]); } else { assert(cex.hypothesis); assert(cex.conclusion); abe1 = AlternationBitsetEvaluator::make_evaluator( cex.hypothesis, pieces[0]); abe2 = AlternationBitsetEvaluator::make_evaluator( cex.conclusion, pieces[0]); } abes.push_back(make_pair(move(abe1), move(abe2))); cex_results.push_back({}); cex_results[i].resize(pieces.size()); for (int j = 0; j < (int)pieces.size(); j++) { if (cex.is_true) { cex_results[i][j].second = BitsetEvalResult::eval_over_alternating_quantifiers(cex.is_true, pieces[j]); } else if (cex.is_false) { cex_results[i][j].first = BitsetEvalResult::eval_over_alternating_quantifiers(cex.is_false, pieces[j]); } else { cex_results[i][j].first = BitsetEvalResult::eval_over_alternating_quantifiers(cex.hypothesis, pieces[j]); cex_results[i][j].second = BitsetEvalResult::eval_over_alternating_quantifiers(cex.conclusion, pieces[j]); } } } void AltDisjunctCandidateSolver::existing_invariants_append(std::vector<int> const& indices) { existing_invariant_indices.push_back(indices); existing_invariant_trie.insert(indices); } void AltDisjunctCandidateSolver::addExistingInvariant(value inv0) { for (value inv : taqd.rename_into_all_possibilities(inv0)) { vector<int> indices = get_indices_of_value(inv); sort(indices.begin(), indices.end()); existing_invariants_append(indices); value norm = inv->totally_normalize(); existing_invariant_set.insert(ComparableValue(norm)); } } inline bool is_indices_subset(vector<int> const& a, vector<int> const& b, int& upTo) { if (a.size() == 0) { upTo = 0; return true; } if (b.size() == 0) return false; int i = 0; int j = 0; while (true) { if (a[i] < b[j]) { return false; } else if (a[i] == b[j]) { i++; j++; if (i >= (int)a.size()) { upTo = j; return true; } if (j >= (int)b.size()) return false; } else { j++; if (j >= (int)b.size()) return false; } } } void AltDisjunctCandidateSolver::init_piece_to_index() { for (int i = 0; i < (int)pieces.size(); i++) { value v = pieces[i]; while (true) { if (Forall* f = dynamic_cast<Forall*>(v.get())) { v = f->body; } else if (Exists* f = dynamic_cast<Exists*>(v.get())) { v = f->body; } else { break; } } piece_to_index.insert(make_pair(ComparableValue(v), i)); } } int AltDisjunctCandidateSolver::get_index_of_piece(value p) { auto it = piece_to_index.find(ComparableValue(p)); assert (it != piece_to_index.end()); return it->second; } vector<int> AltDisjunctCandidateSolver::get_indices_of_value(value inv) { while (true) { if (Forall* f = dynamic_cast<Forall*>(inv.get())) { inv = f->body; } else if (Exists* f = dynamic_cast<Exists*>(inv.get())) { inv = f->body; } else { break; } } Or* o = dynamic_cast<Or*>(inv.get()); if (o != NULL) { vector<int> t; t.resize(o->args.size()); for (int i = 0; i < (int)t.size(); i++) { t[i] = get_index_of_piece(o->args[i]); } return t; } else { vector<int> t; t.resize(1); t[0] = get_index_of_piece(inv); return t; } } value AltDisjunctCandidateSolver::disjunction_fuse(vector<value> values) { for (int i = 0; i < (int)values.size(); i++) { while (true) { if (Forall* f = dynamic_cast<Forall*>(values[i].get())) { values[i] = f->body; } else if (Exists* f = dynamic_cast<Exists*>(values[i].get())) { values[i] = f->body; } else { break; } } } return taqd.with_body(v_or(values)); } value AltDisjunctCandidateSolver::getNext() { while (true) { while (true) { //cout << "start increment" << endl; increment(); //cout << "hi" << endl; if (done) { //cout << "return nullptr" << endl; return nullptr; } //cout << var_index_states[cur_indices.size()] << " " // << target_state << endl; if (sub_ts.next( var_index_states[cur_indices_sub.size()-1], cur_indices_sub[cur_indices_sub.size()-1]) == target_state) { break; } //cout << "bro" << endl; } progress++; //cout << "attempting" << endl; for (int i = 0; i < (int)cur_indices.size(); i++) { cur_indices[i] = slice_index_map[cur_indices_sub[i]]; } // TODO comment this /*value sanity_v; { vector<value> disjs; for (int i = 0; i < (int)cur_indices.size(); i++) { disjs.push_back(pieces[cur_indices[i]]); } sanity_v = disjunction_fuse(disjs); cout << "getNext: " << sanity_v->to_string() << endl; }*/ bool failed = false; //// Check if it contains an existing invariant int upTo; if (existing_invariant_trie.query(cur_indices, upTo /* output */)) { numEnumeratedFilteredRedundantInvariants++; this->skipAhead(upTo); failed = true; } if (failed) continue; //// Check if it violates a countereample for (int i = 0; i < (int)cexes.size(); i++) { if (cexes[i].is_true) { abes[i].second.reset_for_disj(); for (int j = 0; j < (int)cur_indices.size(); j++) { abes[i].second.add_disj(cex_results[i][cur_indices[j]].second); } bool res = abes[i].second.evaluate(); //assert (res == cexes[i].is_true->eval_predicate(sanity_v)); if (!res) { failed = true; break; } } else if (cexes[i].is_false) { abes[i].first.reset_for_disj(); for (int j = 0; j < (int)cur_indices.size(); j++) { abes[i].first.add_disj(cex_results[i][cur_indices[j]].first); } bool res = abes[i].first.evaluate(); //assert (res == cexes[i].is_false->eval_predicate(sanity_v)); if (res) { failed = true; break; } } else { abes[i].first.reset_for_disj(); for (int j = 0; j < (int)cur_indices.size(); j++) { abes[i].first.add_disj(cex_results[i][cur_indices[j]].first); } bool res = abes[i].first.evaluate(); //assert (res == cexes[i].hypothesis->eval_predicate(sanity_v)); if (res) { abes[i].second.reset_for_disj(); for (int j = 0; j < (int)cur_indices.size(); j++) { abes[i].second.add_disj(cex_results[i][cur_indices[j]].second); } bool res2 = abes[i].second.evaluate(); //assert (res2 == cexes[i].conclusion->eval_predicate(sanity_v)); if (!res2) { failed = true; break; } } } } if (failed) continue; //// Check if it's equivalent to an existing invariant //// by some normalization. vector<value> disjs; for (int i = 0; i < (int)cur_indices.size(); i++) { disjs.push_back(pieces[cur_indices[i]]); } value v = disjunction_fuse(disjs); if (existing_invariant_set.count(ComparableValue(v->totally_normalize())) > 0) { existing_invariants_append(cur_indices); continue; } dump_cur_indices(); return v; } } void AltDisjunctCandidateSolver::dump_cur_indices() { cout << "cur_indices_sub:"; for (int i : cur_indices_sub) { cout << " " << i; } cout << " / " << slice_index_map.size() << endl; } // Skip all remaining index-sequences that match // the first `upTo` numbers of the current index-sequence void AltDisjunctCandidateSolver::skipAhead(int upTo) { for (int i = upTo; i < (int)cur_indices_sub.size(); i++) { cur_indices_sub[i] = (int)pieces.size() + i - (int)cur_indices_sub.size(); } } void AltDisjunctCandidateSolver::increment() { int n = slice_index_map.size(); int t = cur_indices_sub.size(); if (start_from != -1) { t = start_from; start_from = -1; goto body_start; } goto body_end; level_size_top: cur_indices_sub.push_back(0); if ((int)cur_indices_sub.size() > disj_arity) { this->done = true; return; } t = 0; goto body_start; body_start: if (t == (int)cur_indices_sub.size()) { return; } if (t > 0) { //assert (t-1 >= 0); //assert (t <= (int)var_index_states.size()); //assert (0 <= t); //assert (t-1 <= (int)cur_indices_sub.size()); var_index_states[t] = sub_ts.next( var_index_states[t-1], cur_indices_sub[t-1]); } cur_indices_sub[t] = (t == 0 ? 0 : cur_indices_sub[t-1] + 1); goto loop_start_before_check; loop_start: //assert (t >= 0); //assert (t <= (int)var_index_states.size()); //assert (0 <= t); //assert (t <= (int)cur_indices_sub.size()); //cout << cur_indices_sub[t] << endl; //cout << sub_ts.nTransitions() << endl; //cout << slice_index_map.size() << endl; if (sub_ts.next(var_index_states[t], cur_indices_sub[t]) != -1) { t++; goto body_start; } call_end: cur_indices_sub[t]++; loop_start_before_check: if (cur_indices_sub[t] >= n) { goto body_end; } goto loop_start; body_end: if (t == done_cutoff) { if (finish_at_cutoff) { done = true; return; } goto level_size_top; } else { t--; goto call_end; } } void AltDisjunctCandidateSolver::setSubSlice(TemplateSubSlice const& tss) { this->tss = tss; auto p = get_subslice_index_map(ts, tss.ts); slice_index_map = p.first.first; //cout << "slice_index_map" << endl; //for (int i : slice_index_map) { // cout << "slice_index_map " << i << endl; //} sub_ts = p.first.second; target_state = p.second; assert (target_state != -1); //cout << "chunk: " << sc.nums.size() << " / " << sc.size << endl; assert (tss.ts.k > 0); cur_indices_sub.resize(tss.ts.k); cur_indices.resize(tss.ts.k); assert ((int)tss.prefix.size() <= tss.ts.k); for (int i = 0; i < (int)tss.prefix.size(); i++) { cur_indices_sub[i] = tss.prefix[i]; } for (int i = 1; i <= (int)tss.prefix.size(); i++) { var_index_states[i] = sub_ts.next( var_index_states[i-1], cur_indices_sub[i-1]); } start_from = tss.prefix.size(); done_cutoff = tss.prefix.size(); done = false; finish_at_cutoff = true; } long long AltDisjunctCandidateSolver::getPreSymmCount() { long long ans = 1; for (int i = 0; i < disj_arity; i++) ans *= (long long)pieces.size(); return ans; } <file_sep>/src/enumerator.h #ifndef ENUMERATOR_H #define ENUMERATOR_H //#include "expr_gen_smt.h" #include "logic.h" std::vector<value> get_clauses_for_template( std::shared_ptr<Module> module, value templ); #endif <file_sep>/src/bitset_eval_result.h #ifndef BITSET_EVAL_RESULT_H #define BITSET_EVAL_RESULT_H #include <iostream> #include <cstring> #include <cassert> struct BitsetEvalResult { std::vector<uint64_t> v; uint64_t last_bits; static BitsetEvalResult eval_over_foralls(std::shared_ptr<Model>, value v); static BitsetEvalResult eval_over_alternating_quantifiers(std::shared_ptr<Model>, value v); static bool disj_is_true(std::vector<BitsetEvalResult*> const& results) { int n = results[0]->v.size(); for (int i = 0; i < n - 1; i++) { uint64_t x = 0; for (int j = 0; j < (int)results.size(); j++) { x |= results[j]->v[i]; } if (x != ~(uint64_t)0) { return false; } } uint64_t x = 0; for (int j = 0; j < (int)results.size(); j++) { x |= results[j]->v[n-1]; } if (x != results[0]->last_bits) { return false; } return true; } void apply_disj(BitsetEvalResult const& ber) { for (int i = 0; i < (int)v.size(); i++) { v[i] |= ber.v[i]; } } void apply_conj(BitsetEvalResult const& ber) { for (int i = 0; i < (int)v.size(); i++) { v[i] &= ber.v[i]; } } void dump() { for (int i = 0; i < (int)v.size(); i++) { for (int j = 0; j < 64; j++) { if (i < (int)v.size() - 1 || (((uint64_t)1 << j) & last_bits)) { std::cout << (v[i] & ((uint64_t)1 << j) ? 1 : 0); } } } std::cout << std::endl; } }; struct BitsetLevel { int block_size; int num_blocks; bool conj; }; struct AlternationBitsetEvaluator { std::vector<BitsetLevel> levels; std::vector<uint64_t> scratch; bool final_conj; int final_num_full_words_64; uint64_t final_last_bits; uint64_t last_bits; static AlternationBitsetEvaluator make_evaluator( std::shared_ptr<Model> model, value v); void dump(int k) { for (int i = 0; i < k; i++) { int b = (int)((scratch[i / 64] >> (i % 64)) & 1); std::cout << b; } std::cout << std::endl; } void reset_for_conj() { for (int i = 0; i < (int)scratch.size(); i++) { scratch[i] = ~(uint64_t)0; } scratch[scratch.size() - 1] = last_bits; } void reset_for_disj() { for (int i = 0; i < (int)scratch.size(); i++) { scratch[i] = 0; } } void add_conj(BitsetEvalResult const& ber) { for (int i = 0; i < (int)ber.v.size(); i++) { scratch[i] &= ber.v[i]; } } void add_disj(BitsetEvalResult const& ber) { for (int i = 0; i < (int)ber.v.size(); i++) { scratch[i] |= ber.v[i]; } } void add_conj(int sz, std::vector<uint64_t> const& v) { for (int i = 0; i < sz; i++) { scratch[i] &= v[i]; } } void add_disj(int sz, std::vector<uint64_t> const& v) { for (int i = 0; i < sz; i++) { scratch[i] |= v[i]; } } static_assert(__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__, "this requires little endian"); // scratch[0 .. len] := scratch[0 .. len] & scratch[start .. start + len] void block_conj(int start, int len) { // word of 4 bytes at a time int t; for (t = 0; 32*t <= len - 32; t++) { int bit_idx = 32*t + start; int w32_idx = bit_idx / 32; uint64_t w64; memcpy(&w64, ((uint32_t*)&scratch[0]) + w32_idx, 8); uint32_t block = (uint32_t)(w64 >> ((start % 32))); uint32_t tmp; memcpy(&tmp, ((uint32_t*)&scratch[0]) + t, 4); tmp &= block; memcpy(((uint32_t*)&scratch[0]) + t, &tmp, 4); } if (32*t < len) { int bit_idx = 32*t + start; int w32_idx = bit_idx / 32; uint64_t w64; memcpy(&w64, ((uint32_t*)&scratch[0]) + w32_idx, 8); uint32_t block = (uint32_t)(w64 >> ((start % 32))); uint32_t tmp; memcpy(&tmp, ((uint32_t*)&scratch[0]) + t, 4); tmp &= block | ((uint32_t)(-1) << (len - 32*t)); memcpy(((uint32_t*)&scratch[0]) + t, &tmp, 4); } } // scratch[0 .. len] := scratch[0 .. len] | scratch[start .. start + len] void block_disj(int start, int len) { int t; for (t = 0; 32*t <= len - 32; t++) { int bit_idx = 32*t + start; int w32_idx = bit_idx / 32; uint64_t w64; memcpy(&w64, ((uint32_t*)&scratch[0]) + w32_idx, 8); uint32_t block = (uint32_t)(w64 >> ((start % 32))); uint32_t tmp; memcpy(&tmp, ((uint32_t*)&scratch[0]) + t, 4); tmp |= block; memcpy(((uint32_t*)&scratch[0]) + t, &tmp, 4); } if (32*t < len) { int bit_idx = 32*t + start; int w32_idx = bit_idx / 32; uint64_t w64; memcpy(&w64, ((uint32_t*)&scratch[0]) + w32_idx, 8); uint32_t block = (uint32_t)(w64 >> ((start % 32))); uint32_t tmp; memcpy(&tmp, ((uint32_t*)&scratch[0]) + t, 4); tmp |= block & (((uint32_t)(1) << (len - 32*t)) - 1); memcpy(((uint32_t*)&scratch[0]) + t, &tmp, 4); } } bool final_answer() { if (final_conj) { for (int j = 0; j < final_num_full_words_64; j++) { if (scratch[j] != ~(uint64_t)0) { return false; } } return (scratch[final_num_full_words_64] & final_last_bits) == final_last_bits; } else { for (int j = 0; j < final_num_full_words_64; j++) { if (scratch[j] != 0) { return true; } } return (scratch[final_num_full_words_64] & final_last_bits) != 0; } } bool evaluate() { //std::cout << "yooo" << std::endl; //dump(128); for (int i = 0; i < (int)levels.size(); i++) { BitsetLevel& level = levels[i]; if (level.conj) { for (int j = 1; j < level.num_blocks; j++) { block_conj(j * level.block_size, level.block_size); } } else { for (int j = 1; j < level.num_blocks; j++) { block_disj(j * level.block_size, level.block_size); } } //dump(level.num_blocks * level.block_size); } //std::cout << "mooo" << std::endl; bool res = final_answer(); //std::cout << "res = " << res << std::endl; return res; } }; inline void vec_copy_ber(std::vector<uint64_t>& v, BitsetEvalResult const& ber) { for (int i = 0; i < (int)ber.v.size(); i++) { v[i] = ber.v[i]; } } inline void vec_apply_disj(std::vector<uint64_t>& v, BitsetEvalResult const& ber) { for (int i = 0; i < (int)ber.v.size(); i++) { v[i] |= ber.v[i]; } } inline void vec_apply_conj(std::vector<uint64_t>& v, BitsetEvalResult const& ber) { for (int i = 0; i < (int)ber.v.size(); i++) { v[i] &= ber.v[i]; } } #endif <file_sep>/src/solve.h #ifndef SOLVE_H #define SOLVE_H #include "model.h" #include "smt.h" #include <functional> struct ContextSolverResult { smt::SolverResult res; std::vector<std::shared_ptr<Model>> models; }; enum class ModelType { Any, Min }; enum class Strictness { Strict, Indef, Quick, TryHard }; ContextSolverResult context_solve( std::string const& log_info, std::shared_ptr<Module> module, ModelType mt, Strictness, value hint, std::function< std::vector<std::shared_ptr<ModelEmbedding>>(std::shared_ptr<BackgroundContext>) > f); void context_reset(); #endif <file_sep>/get-deps.sh git clone <EMAIL>:secure-foundations/CVC4-fork.git cvc4 cd cvc4 # swiss-fork branch git checkout 2f3d441727d87db35bce38a99c79c0b19c4fd1ef cd .. git clone <EMAIL>:secure-foundations/mypyvy-fork.git mypyvy cd mypyvy # swiss-fork branch git checkout a3a386245eaea442fdcba866a38a89e96fc7e2e6 cd .. git clone <EMAIL>:secure-foundations/ivy-fork.git ivy cd ivy # swiss-fork branch git checkout 74e6ee922c965a15a0f4f5d5ae60dc85acc64850 cd .. <file_sep>/src/quantifier_permutations.cpp #include "quantifier_permutations.h" #include <set> #include <algorithm> #include <cassert> #include <iostream> using namespace std; void get_quantifier_permutations_( vector<unsigned int> const& ovs, vector<QSRange> const& qranges, int idx, vector<unsigned int> const& partial, vector<vector<unsigned int>>& res) { if (idx == (int)qranges.size()) { res.push_back(partial); return; } vector<unsigned int> my_ovs; for (int i = qranges[idx].start; i < qranges[idx].end; i++) { my_ovs.push_back(ovs[i]); } sort(my_ovs.begin(), my_ovs.end()); do { vector<unsigned int> new_partial = partial; for (unsigned int j : my_ovs) { new_partial.push_back(j); } get_quantifier_permutations_(ovs, qranges, idx+1, new_partial, res); } while (next_permutation(my_ovs.begin(), my_ovs.end())); } vector<vector<unsigned int>> get_quantifier_permutations( TopQuantifierDesc const& tqd, vector<unsigned int> const& ovs) { vector<QSRange> qranges = tqd.grouped_by_sort(); assert(tqd.decls().size() == ovs.size()); vector<vector<unsigned int>> res; get_quantifier_permutations_(ovs, qranges, 0, {}, res); return res; } vector<vector<vector<unsigned int>>> get_multiqi_quantifier_permutations( TopQuantifierDesc const& tqd, vector<vector<unsigned int>> const& ovs) { int n = ovs.size(); assert(n > 0); int m = ovs[0].size(); vector<vector<unsigned int>> i_to_t; map<vector<unsigned int>, unsigned int> t_to_i; vector<unsigned int> packed_ovs; for (int i = 0; i < m; i++) { vector<unsigned int> tuple; for (int j = 0; j < n; j++) { tuple.push_back(ovs[j][i]); } auto iter = t_to_i.find(tuple); if (iter != t_to_i.end()) { packed_ovs.push_back(iter->second); } else { packed_ovs.push_back(i_to_t.size()); t_to_i.insert(make_pair(tuple, i_to_t.size())); i_to_t.push_back(tuple); } } vector<vector<unsigned int>> packed_res = get_quantifier_permutations(tqd, packed_ovs); vector<vector<vector<unsigned int>>> res; for (vector<unsigned int> const& packed_qis : packed_res) { vector<vector<unsigned int>> qis; for (int i = 0; i < n; i++) { qis.push_back(vector<unsigned int>{}); } assert((int)packed_qis.size() == m); for (int i = 0; i < m; i++) { vector<unsigned int> tuple = i_to_t[packed_qis[i]]; for (int j = 0; j < n; j++) { qis[j].push_back(tuple[j]); } } res.push_back(qis); } return res; } <file_sep>/scripts/stats.py import json import os # from https://stackoverflow.com/questions/2301789/read-a-file-in-reverse-order-using-python def reverse_readline(filename, buf_size=8192): """A generator that returns the lines of a file in reverse order""" with open(filename) as fh: segment = None offset = 0 fh.seek(0, os.SEEK_END) file_size = remaining_size = fh.tell() while remaining_size > 0: offset = min(file_size, offset + buf_size) fh.seek(file_size - offset) buffer = fh.read(min(remaining_size, buf_size)) remaining_size -= buf_size lines = buffer.split('\n') # The first line of the buffer is probably not a complete line so # we'll save it and append it to the last line of the next buffer # we read if segment is not None: # If the previous chunk starts right from the beginning of line # do not concat the segment to the last line of new chunk. # Instead, yield the segment first if buffer[-1] != '\n': lines[-1] += segment else: yield segment segment = lines[0] for index in range(len(lines) - 1, 0, -1): if lines[index]: yield lines[index] # Don't yield None if the file was empty if segment is not None: yield segment def parse_stats(filename, cid, failure): lines = [] resulting_inv_info = [] started = False for line in reverse_readline(filename): line = line.strip() if line == "=========================================": started = True elif line == "================= Stats =================": break elif started: lines.append(line) elif line.startswith('Resulting invariant'): resulting_inv_info.append(line) lines = lines[::-1] d = {} for l in lines: if (l.startswith("z3 [") or l.startswith("cvc4 [") or l.startswith("z3 TOTAL") or l.startswith("cvc4 TOTAL") or l.startswith("long smtAllQueries")): stuff = l.split() key = ' '.join(stuff[:-10]) assert stuff[-10] == "total" ms_time = stuff[-9] + " ms" assert stuff[-8] == "ms" assert stuff[-7] == "over" ops = stuff[-6] assert stuff[-5] == "ops," d[key + " time"] = ms_time d[key + " ops"] = ops elif ":" in l: t = l.split(':') key = t[0].strip() value = t[1].strip() d[key] = value else: assert False d["column_id"] = str(cid) d["full_process_failure"] = str(1 if failure else 0) return (d, resulting_inv_info[::-1]) def pad(k, n): while len(k) < 50: k += " " return k def log_stats(f, stats, name): log(f, "") log(f, name) log(f, "-------------------------------------------------") for key in sorted(stats.keys()): if key != "progress": log(f, pad(key, 50) + " ---> " + stats[key]) log(f, "-------------------------------------------------") def add_stats(s1, s2): t1 = s1.split() t2 = s2.split() if len(t1) == 1: assert len(t2) == 1 return str(int(t1[0]) + int(t2[0])) else: assert len(t1) == 2 assert len(t2) == 2 assert t1[1] == t2[1] return str(int(t1[0]) + int(t2[0])) + " " + t1[1] def aggregate_stats(stats_list): d = {} for stats in stats_list: for key in stats: value = stats[key] if key in d: d[key] = add_stats(stats[key], d[key]) else: d[key] = stats[key] return d def log(f, *args): print(*args, file=f) def compute_average(nums): if len(nums) == 0: return "undefined" else: return str(sum(nums) / float(len(nums))) def compute_percentiles(nums): if len(nums) == 0: return "undefined" else: x = [] for i in range(0, 101): idx = (i * (len(nums) - 1)) // 100 x.append(str(nums[idx])) return " ".join(x) def process_global_stats(files): d = {} results = {} for filename in files: if os.path.exists(filename): key = None with open(filename) as f: for l in f: l = l.strip() i = None try: i = int(l) except ValueError: pass if i is None: if l != "": key = l if key not in d: d[key] = [] else: assert key != None d[key].append(i) for key in d: nums = d[key] nums.sort() results[key + " avg"] = compute_average(nums) results[key + " percentiles"] = compute_percentiles(nums) return results class Stats(object): def __init__(self, num_threads, all_args, ivy_filename, json_filename, logfile): self.num_threads = num_threads self.all_args = all_args self.inc_logs = [] self.finisher_logs = [] self.inc_result_filenames = [] self.finisher_result_filename = None self.ivy_filename = ivy_filename self.json_filename = json_filename self.all_logs = [] self.inc_individual_times = [] self.inc_times = [] self.finisher_individual_times = [] self.finisher_time = 0 self.inc_results = [] self.finisher_result = None self.logfile_base = logfile self.resulting_inv_info = [] def add_global_stat_files(self, files): self.global_stats = process_global_stats(files) def add_inc_log(self, iternum, log, seconds, cid, failure, stopped): while len(self.inc_logs) <= iternum: self.inc_logs.append([]) self.inc_individual_times.append([]) self.inc_logs[-1].append(log) self.inc_individual_times[-1].append(seconds) self.all_logs.append((log, seconds, cid, failure, stopped)) def add_inc_result(self, iternum, log, seconds): #print("inc_result_filenames", self.inc_result_filenames) #print("iternum", iternum) assert len(self.inc_result_filenames) == iternum self.inc_result_filenames.append(log) self.inc_times.append(seconds) def add_finisher_log(self, filename, seconds, cid, failure, stopped): self.finisher_logs.append(filename) self.finisher_individual_times.append(seconds) self.all_logs.append((filename, seconds, cid, failure, stopped)) def add_finisher_result(self, filename, seconds): self.finisher_result_filename = filename self.finisher_time = seconds def num_incremental(self): return len(self.inc_results) def num_finisher(self): if self.finisher_result == None: return 0 else: return 1 def read_result_file(self, filename): with open(filename, "r") as f: return json.loads(f.read()) def read_result_files(self): for filename in self.inc_result_filenames: self.inc_results.append(self.read_result_file(filename)) if self.finisher_result_filename != None: self.finisher_result = self.read_result_file(self.finisher_result_filename) def was_success(self): for res in self.inc_results: if res["success"]: return True if self.finisher_result and self.finisher_result["success"]: return True return False def total_number_of_invariants_incremental(self): if len(self.inc_results) > 0: j = self.inc_results[-1] return len(j["new_invs"] + j["base_invs"]) else: return 0 def total_number_of_invariants_finisher(self): if self.finisher_result and self.finisher_result["success"]: return 1 else: return 0 def total_number_of_invariants(self): return (self.total_number_of_invariants_incremental() + self.total_number_of_invariants_finisher()) def get_invariants(self): if self.finisher_result: res = self.finisher_result elif len(self.inc_results) > 0: res = self.inc_results[-1] else: return [] return res["base_invs"] + res["new_invs"] def get_breadth_time(self, i): return self.inc_times[i] def get_breadth_cpu_time(self, i): return sum(self.inc_individual_times[i]) def get_breadth_individual_times_string(self, i): return " ".join(str(x) for x in self.inc_individual_times[i]) def get_finisher_time(self): return self.finisher_time def get_finisher_cpu_time(self): return sum(self.finisher_individual_times) def get_finisher_individual_times_string(self): return " ".join(str(x) for x in self.finisher_individual_times) def get_total_time(self): t = 0 for i in range(len(self.inc_results)): t += self.get_breadth_time(i) t += self.get_finisher_time() return t def get_total_cpu_time(self): t = 0 for i in range(len(self.inc_results)): t += self.get_breadth_cpu_time(i) t += self.get_finisher_cpu_time() return t def dump_individual_stats(self, f): self.log_stats = {} for (log, seconds, cid, failure, stopped) in self.all_logs: stats, resulting_inv_info = parse_stats(log, cid, failure and not stopped) self.log_stats[log] = stats log_stats(f, stats, log) self.resulting_inv_info = self.resulting_inv_info + resulting_inv_info def stats_finisher(self, f): stats_list = [] for log in self.finisher_logs: stats_list.append(self.log_stats[log]) total = aggregate_stats(stats_list) log_stats(f, total, "finisher") return total def stats_inc_one(self, f, i): stats_list = [] for log in self.inc_logs[i]: stats_list.append(self.log_stats[log]) total = aggregate_stats(stats_list) log_stats(f, total, "breadth (" + str(i) + ")") return total def stats_inc_total(self, f): stats_list = [] for i in range(len(self.inc_logs)): stats_list.append(self.stats_inc_one(f, i)) total = aggregate_stats(stats_list) log_stats(f, total, "breadth (total)") return total def stats_total(self, f): stats_list = [] stats_list.append(self.stats_inc_total(f)) stats_list.append(self.stats_finisher(f)) total = aggregate_stats(stats_list) log_stats(f, total, "total") return total def print_stats(self, filename): self.read_result_files() with open(filename, "w") as f: log(f, "logs", self.logfile_base) log(f, "") log(f, "Protocol:", self.ivy_filename) log(f, "Args:", " ".join(self.all_args)) log(f, "Number of threads:", self.num_threads) log(f, "") log(f, "Number of iterations of BREADTH:", self.num_incremental()) log(f, "Number of iterations of FINISHER:", self.num_finisher()) log(f, "Success:", self.was_success()) log(f, "Number of invariants synthesized:", self.total_number_of_invariants()) log(f, "") for i in range(len(self.inc_results)): log(f, "BREADTH iteration", i, "time:", self.get_breadth_time(i), "seconds;", "cpu time:", self.get_breadth_cpu_time(i), "seconds;", "thread times: ", self.get_breadth_individual_times_string(i)) if self.finisher_result: log(f, "FINISHER", "time:", self.get_finisher_time(), "seconds;", "cpu time:", self.get_finisher_cpu_time(), "seconds", "thread times:", self.get_finisher_individual_times_string()) log(f, "total time:", self.get_total_time(), "seconds;", "total cpu time:", self.get_total_cpu_time(), "seconds") log(f, "") for (l, seconds, cid, failure, stopped) in self.all_logs: log(f, "time for process " + l + " is " + str(seconds) + " seconds" + (" (stopped)" if stopped else (" (failure)" if failure else "")) ) log(f, "") log(f, "specifics:") self.dump_individual_stats(f) self.stats_total(f) log(f, "") for key in self.global_stats: log(f, "global_stats " + key + " " + self.global_stats[key]) log(f, "") for line in self.resulting_inv_info: log(f, line) <file_sep>/src/smt_z3.cpp #include "smt.h" #include "z3++.h" #include "benchmarking.h" #include "model.h" #include "stats.h" using namespace std; using smt::_sort; using smt::_expr; using smt::_func_decl; using smt::_solver; using smt::_context; using smt::_expr_vector; using smt::_sort_vector; namespace smt_z3 { struct sort : public _sort { z3::sort so; sort(z3::sort s) : so(s) { } }; struct expr : public _expr { z3::expr ex; expr(z3::expr e) : ex(e) { } std::shared_ptr<_expr> equals(_expr* _a) const override { expr* a = dynamic_cast<expr*>(_a); assert(a != NULL); return shared_ptr<_expr>(new expr(ex == a->ex)); } std::shared_ptr<_expr> not_equals(_expr* _a) const override { expr* a = dynamic_cast<expr*>(_a); assert(a != NULL); return shared_ptr<_expr>(new expr(ex != a->ex)); } std::shared_ptr<_expr> logic_negate() const override { return shared_ptr<_expr>(new expr(!ex)); } std::shared_ptr<_expr> logic_or(_expr* _a) const override { expr* a = dynamic_cast<expr*>(_a); assert(a != NULL); return shared_ptr<_expr>(new expr(ex || a->ex)); } std::shared_ptr<_expr> logic_and(_expr* _a) const override { expr* a = dynamic_cast<expr*>(_a); assert(a != NULL); return shared_ptr<_expr>(new expr(ex && a->ex)); } std::shared_ptr<_expr> ite(_expr* _b, _expr* _c) const override { expr* b = dynamic_cast<expr*>(_b); assert(b != NULL); expr* c = dynamic_cast<expr*>(_c); assert(c != NULL); return shared_ptr<_expr>(new expr(z3::ite(ex, b->ex, c->ex))); } std::shared_ptr<_expr> implies(_expr* _b) const override { expr* b = dynamic_cast<expr*>(_b); assert(b != NULL); return shared_ptr<_expr>(new expr(z3::implies(ex, b->ex))); } }; struct func_decl : _func_decl { z3::func_decl fd; func_decl(z3::func_decl fd) : fd(fd) { } size_t arity() override { return fd.arity(); } std::shared_ptr<_sort> domain(int i) override { return shared_ptr<_sort>(new sort(fd.domain(i))); } std::shared_ptr<_sort> range() override { return shared_ptr<_sort>(new sort(fd.range())); } std::shared_ptr<_expr> call(_expr_vector* args) override; std::shared_ptr<_expr> call() override; std::string get_name() override { return fd.name().str(); } bool eq(_func_decl* _b) override { func_decl* b = dynamic_cast<func_decl*>(_b); assert (b != NULL); return fd.name() == b->fd.name(); } }; struct context : _context { z3::context ctx; void set_timeout(int ms) override { ctx.set("timeout", ms); } std::shared_ptr<_sort> bool_sort() override { return shared_ptr<_sort>(new sort(ctx.bool_sort())); } std::shared_ptr<_expr> bool_val(bool b) override { return shared_ptr<_expr>(new expr(ctx.bool_val(b))); } std::shared_ptr<_sort> uninterpreted_sort(std::string const& name) override { return shared_ptr<_sort>(new sort(ctx.uninterpreted_sort(name.c_str()))); } std::shared_ptr<_func_decl> function( std::string const& name, _sort_vector* domain, _sort* range) override; std::shared_ptr<_func_decl> function( std::string const& name, _sort* range) override; std::shared_ptr<_expr> var( std::string const& name, _sort* range) override; std::shared_ptr<_expr> bound_var( std::string const& name, _sort* so) override; std::shared_ptr<_expr_vector> new_expr_vector() override; std::shared_ptr<_sort_vector> new_sort_vector() override; std::shared_ptr<_solver> make_solver() override; }; struct sort_vector : _sort_vector { z3::sort_vector so_vec; sort_vector(context& ctx) : so_vec(ctx.ctx) { } void push_back(_sort* _s) override { sort* s = dynamic_cast<sort*>(_s); assert (s != NULL); so_vec.push_back(s->so); } size_t size() override { return so_vec.size(); } std::shared_ptr<_sort> get_at(int i) override { return shared_ptr<_sort>(new sort(so_vec[i])); } }; struct expr_vector : _expr_vector { z3::expr_vector ex_vec; expr_vector(context& ctx) : ex_vec(ctx.ctx) { } void push_back(_expr* _s) override { expr* s = dynamic_cast<expr*>(_s); assert (s != NULL); ex_vec.push_back(s->ex); } size_t size() override { return ex_vec.size(); } std::shared_ptr<_expr> get_at(int i) override { return shared_ptr<_expr>(new expr(ex_vec[i])); } std::shared_ptr<_expr> forall(_expr* _body) override { expr* body = dynamic_cast<expr*>(_body); assert (body != NULL); return shared_ptr<_expr>(new expr(z3::forall(ex_vec, body->ex))); } std::shared_ptr<_expr> exists(_expr* _body) override { expr* body = dynamic_cast<expr*>(_body); assert (body != NULL); return shared_ptr<_expr>(new expr(z3::exists(ex_vec, body->ex))); } std::shared_ptr<_expr> mk_and() override { return shared_ptr<_expr>(new expr(z3::mk_and(ex_vec))); } std::shared_ptr<_expr> mk_or() override { return shared_ptr<_expr>(new expr(z3::mk_or(ex_vec))); } }; struct solver : _solver { z3::solver z3_solver; solver(context& ctx) : z3_solver(ctx.ctx) { } smt::SolverResult check_result() override; void push() override { z3_solver.push(); } void pop() override { z3_solver.pop(); } void add(_expr* _e) override { expr* e = dynamic_cast<expr*>(_e); assert (e != NULL); //cout << "adding " << e->ex << endl; z3_solver.add(e->ex); } void dump(ofstream&) override; }; std::shared_ptr<_expr> func_decl::call(_expr_vector* _args) { expr_vector* args = dynamic_cast<expr_vector*>(_args); assert (args != NULL); return shared_ptr<_expr>(new expr(fd(args->ex_vec))); } std::shared_ptr<_expr> func_decl::call() { return shared_ptr<_expr>(new expr(fd())); } std::shared_ptr<_func_decl> context::function( std::string const& name, _sort_vector* _domain, _sort* _range) { sort_vector* domain = dynamic_cast<sort_vector*>(_domain); assert (domain != NULL); sort* range = dynamic_cast<sort*>(_range); assert (range != NULL); return shared_ptr<_func_decl>(new func_decl( ctx.function(name.c_str(), domain->so_vec, range->so))); } std::shared_ptr<_func_decl> context::function( std::string const& name, _sort* _range) { sort* range = dynamic_cast<sort*>(_range); assert (range != NULL); return shared_ptr<_func_decl>(new func_decl( ctx.function(name.c_str(), 0, 0, range->so))); } std::shared_ptr<_expr> context::var( std::string const& name, _sort* _so) { sort* so = dynamic_cast<sort*>(_so); assert (so != NULL); return shared_ptr<_expr>(new expr( ctx.constant(name.c_str(), so->so))); } std::shared_ptr<_expr> context::bound_var( std::string const& name, _sort* _so) { sort* so = dynamic_cast<sort*>(_so); assert (so != NULL); return shared_ptr<_expr>(new expr( ctx.constant(name.c_str(), so->so))); } std::shared_ptr<_solver> context::make_solver() { return shared_ptr<_solver>(new solver(*this)); } std::shared_ptr<_expr_vector> context::new_expr_vector() { return shared_ptr<_expr_vector>(new expr_vector(*this)); } std::shared_ptr<_sort_vector> context::new_sort_vector() { return shared_ptr<_sort_vector>(new sort_vector(*this)); } } namespace smt { bool is_z3_context(smt::context& ctx) { return dynamic_cast<smt_z3::context*>(ctx.p.get()) != NULL; } std::shared_ptr<_context> make_z3_context() { return shared_ptr<_context>(new smt_z3::context()); } } //////////////////// ///// Model stuff shared_ptr<Model> Model::extract_z3( smt::context& smt_ctx, smt::solver& smt_solver, std::shared_ptr<Module> module, ModelEmbedding const& e) { smt_z3::context& ctx = *dynamic_cast<smt_z3::context*>(smt_ctx.p.get()); smt_z3::solver& solver = *dynamic_cast<smt_z3::solver*>(smt_solver.p.get()); std::unordered_map<std::string, SortInfo> sort_info; std::unordered_map<iden, FunctionInfo> function_info; z3::model z3model = solver.z3_solver.get_model(); map<string, z3::expr_vector> universes; for (auto p : e.ctx->sorts) { string name = p.first; z3::sort s = dynamic_cast<smt_z3::sort*>(p.second.p.get())->so; // The C++ api doesn't seem to have the functionality we need. // Go down to the C API. Z3_ast_vector c_univ = Z3_model_get_sort_universe(ctx.ctx, z3model, s); int len; if (c_univ) { z3::expr_vector univ(ctx.ctx, c_univ); universes.insert(make_pair(name, univ)); len = univ.size(); } else { z3::expr_vector univ(ctx.ctx); univ.push_back(ctx.ctx.constant(::name("whatever").c_str(), s)); universes.insert(make_pair(name, univ)); len = univ.size(); } SortInfo sinfo; sinfo.domain_size = len; sort_info[name] = sinfo; } auto get_value = [&z3model, &ctx, &universes]( Sort* sort, z3::expr expression1) -> object_value { z3::expr expression = z3model.eval(expression1, true); if (dynamic_cast<BooleanSort*>(sort)) { if (z3::eq(expression, ctx.ctx.bool_val(true))) { return 1; } else if (z3::eq(expression, ctx.ctx.bool_val(false))) { return 0; } else { assert(false); } } else if (UninterpretedSort* usort = dynamic_cast<UninterpretedSort*>(sort)) { auto iter = universes.find(usort->name); assert(iter != universes.end()); z3::expr_vector& vec = iter->second; for (object_value i = 0; i < vec.size(); i++) { if (z3::eq(expression, vec[i])) { return i; } } assert(false); } else { assert(false && "expected boolean sort or uninterpreted sort"); } }; auto get_expr = [&ctx, &universes]( Sort* sort, object_value v) -> z3::expr { if (dynamic_cast<BooleanSort*>(sort)) { if (v == 0) { return ctx.ctx.bool_val(false); } else if (v == 1) { return ctx.ctx.bool_val(true); } else { assert(false); } } else if (UninterpretedSort* usort = dynamic_cast<UninterpretedSort*>(sort)) { auto iter = universes.find(usort->name); assert(iter != universes.end()); z3::expr_vector& vec = iter->second; assert (0 <= v && v < vec.size()); return vec[v]; } else { assert(false && "expected boolean sort or uninterpreted sort"); } }; for (VarDecl decl : module->functions) { iden name = decl.name; z3::func_decl fdecl = dynamic_cast<smt_z3::func_decl*>(e.getFunc(name).p.get())->fd; int num_args; Sort* range_sort; vector<Sort*> domain_sorts; vector<int> domain_sort_sizes; if (FunctionSort* functionSort = dynamic_cast<FunctionSort*>(decl.sort.get())) { num_args = functionSort->domain.size(); range_sort = functionSort->range.get(); for (auto ptr : functionSort->domain) { Sort* argsort = ptr.get(); domain_sorts.push_back(argsort); size_t sz; if (dynamic_cast<BooleanSort*>(argsort)) { sz = 2; } else if (UninterpretedSort* usort = dynamic_cast<UninterpretedSort*>(argsort)) { sz = sort_info[usort->name].domain_size; } else { assert(false && "expected boolean sort or uninterpreted sort"); } domain_sort_sizes.push_back(sz); } } else { num_args = 0; range_sort = decl.sort.get(); } function_info.insert(make_pair(name, FunctionInfo())); FunctionInfo& finfo = function_info[name]; if (z3model.has_interp(fdecl)) { if (fdecl.is_const()) { z3::expr e = z3model.get_const_interp(fdecl); finfo.else_value = 0; finfo.table.reset(new FunctionTable()); finfo.table->value = get_value(range_sort, e); } else { z3::func_interp finterp = z3model.get_func_interp(fdecl); vector<object_value> args; for (int i = 0; i < num_args; i++) { args.push_back(0); } while (true) { z3::expr_vector args_exprs(ctx.ctx); unique_ptr<FunctionTable>* table = &finfo.table; for (int argnum = 0; argnum < num_args; argnum++) { object_value argvalue = args[argnum]; args_exprs.push_back(get_expr(domain_sorts[argnum], argvalue)); if (!table->get()) { table->reset(new FunctionTable()); (*table)->children.resize(domain_sort_sizes[argnum]); } assert(0 <= argvalue && (int)argvalue < domain_sort_sizes[argnum]); table = &(*table)->children[argvalue]; } object_value result_value = get_value(range_sort, finterp.else_value().substitute(args_exprs)); assert (table != NULL); if (!table->get()) { table->reset(new FunctionTable()); } (*table)->value = result_value; int i; for (i = num_args - 1; i >= 0; i--) { args[i]++; if ((int)args[i] == domain_sort_sizes[i]) { args[i] = 0; } else { break; } } if (i == -1) { break; } } for (size_t i = 0; i < finterp.num_entries(); i++) { z3::func_entry fentry = finterp.entry(i); unique_ptr<FunctionTable>* table = &finfo.table; for (int argnum = 0; argnum < num_args; argnum++) { object_value argvalue = get_value(domain_sorts[argnum], fentry.arg(argnum)); if (!table->get()) { table->reset(new FunctionTable()); (*table)->children.resize(domain_sort_sizes[argnum]); } assert(0 <= argvalue && (int)argvalue < domain_sort_sizes[argnum]); table = &(*table)->children[argvalue]; } (*table)->value = get_value(range_sort, fentry.value()); } } } else { finfo.else_value = 0; } } return shared_ptr<Model>(new Model(module, move(sort_info), move(function_info))); } extern bool enable_smt_logging; namespace smt_z3 { ////////////////////// ///// solving string res_to_string(z3::check_result res) { if (res == z3::sat) { return "sat"; } else if (res == z3::unsat) { return "unsat"; } else if (res == z3::unknown) { return "timeout/unknown"; } else { assert(false); } } smt::SolverResult solver::check_result() { auto t1 = now(); z3::check_result res; try { res = z3_solver.check(); } catch (z3::exception exc) { cout << "got z3 exception" << endl; res = z3::unknown; } auto t2 = now(); long long ms = as_ms(t2 - t1); smt::log_to_stdout(ms, false, log_info, res_to_string(res)); if (enable_smt_logging) { log_smtlib(ms, res_to_string(res)); } global_stats.add_z3(ms); if (res == z3::sat) return smt::SolverResult::Sat; else if (res == z3::unsat) return smt::SolverResult::Unsat; return smt::SolverResult::Unknown; } void solver::dump(ofstream& of) { of << z3_solver << endl; } } <file_sep>/src/bmc.cpp #include "bmc.h" using namespace std; FixedBMCContext::FixedBMCContext(smt::context& z3ctx, shared_ptr<Module> module, int k, bool from_safety) : module(module), ctx(new BackgroundContext(z3ctx, module)), from_safety(from_safety) { this->k = k; this->e1 = ModelEmbedding::makeEmbedding(ctx, module); this->e2 = this->e1; for (int i = 0; i < k; i++) { shared_ptr<Action> action = shared_ptr<Action>(new ChoiceAction(module->actions)); ActionResult res = applyAction(this->e2, action, std::unordered_map<iden, smt::expr> {}); this->e2 = res.e; // Add the relation between the two states ctx->solver.add(res.constraint); } // Add the axioms for (shared_ptr<Value> axiom : module->axioms) { ctx->solver.add(this->e1->value2expr(axiom, std::unordered_map<iden, smt::expr> {})); } // Add the inits if (!from_safety) { for (shared_ptr<Value> init : module->inits) { ctx->solver.add(this->e1->value2expr(init)); } } else { ctx->solver.add(this->e2->value2expr(v_not(v_and(module->conjectures)))); } } bool FixedBMCContext::is_exactly_k_invariant(value v) { smt::solver& solver = ctx->solver; solver.push(); if (!from_safety) { solver.add(this->e2->value2expr(v_not(v))); } else{ solver.add(this->e1->value2expr(v_not(v))); } solver.set_log_info("bmc: " + to_string(k)); bool res = !solver.check_sat(); solver.pop(); return res; } shared_ptr<Model> FixedBMCContext::get_k_invariance_violation(value v, bool get_minimal) { smt::solver& solver = ctx->solver; solver.push(); if (!from_safety) { solver.add(this->e2->value2expr(v_not(v))); } else { solver.add(this->e1->value2expr(v_not(v))); } solver.set_log_info("bmc: " + to_string(k)); bool res = solver.check_sat(); shared_ptr<Model> ans; if (res) { if (get_minimal) { ans = Model::extract_minimal_models_from_z3(ctx->ctx, solver, module, {e2}, /* hint */ v)[0]; } else { ans = Model::extract_model_from_z3(ctx->ctx, solver, module, *e2); } } solver.pop(); return ans; } shared_ptr<Model> FixedBMCContext::get_k_invariance_violation_maybe(value v, bool get_minimal) { smt::solver& solver = ctx->solver; solver.push(); if (!from_safety) { solver.add(this->e2->value2expr(v_not(v))); } else { solver.add(this->e1->value2expr(v_not(v))); } solver.set_log_info("bmc: " + to_string(k)); smt::SolverResult res = solver.check_result(); shared_ptr<Model> ans; if (res == smt::SolverResult::Sat) { if (get_minimal) { //cout << "get_k_invariance_violation_maybe " << k << endl; ans = Model::extract_minimal_models_from_z3(ctx->ctx, solver, module, {e2}, /* hint */ v)[0]; //cout << "done get_k_invariance_violation_maybe" << endl; } else { ans = Model::extract_model_from_z3(ctx->ctx, solver, module, *e2); } } solver.pop(); return ans; } bool FixedBMCContext::is_reachable(shared_ptr<Model> model) { smt::solver& solver = ctx->solver; solver.push(); if (!from_safety) { model->assert_model_is(this->e2); } else { model->assert_model_is(this->e1); } solver.set_log_info("bmc: " + to_string(k)); bool res = solver.check_sat(); solver.pop(); return res; } bool FixedBMCContext::is_reachable_returning_false_if_unknown(shared_ptr<Model> model) { smt::solver& solver = ctx->solver; solver.push(); if (!from_safety) { model->assert_model_is(this->e2); } else { model->assert_model_is(this->e1); } solver.set_log_info("bmc: " + to_string(k)); smt::SolverResult res = solver.check_result(); solver.pop(); return res == smt::SolverResult::Sat; } BMCContext::BMCContext(smt::context& ctx, shared_ptr<Module> module, int k, bool from_safety) { for (int i = 1; i <= k; i++) { bmcs.push_back(shared_ptr<FixedBMCContext>(new FixedBMCContext(ctx, module, i, from_safety))); } } bool BMCContext::is_k_invariant(value v) { for (auto bmc : bmcs) { if (!bmc->is_exactly_k_invariant(v)) { return false; } } return true; } shared_ptr<Model> BMCContext::get_k_invariance_violation(value v, bool get_minimal) { for (auto bmc : bmcs) { shared_ptr<Model> mod = bmc->get_k_invariance_violation(v, get_minimal); if (mod) { return mod; } } return nullptr; } shared_ptr<Model> BMCContext::get_k_invariance_violation_maybe(value v, bool get_minimal) { for (auto bmc : bmcs) { shared_ptr<Model> mod = bmc->get_k_invariance_violation_maybe(v, get_minimal); if (mod) { return mod; } } return nullptr; } bool BMCContext::is_reachable(std::shared_ptr<Model> model) { for (auto bmc : bmcs) { if (bmc->is_reachable(model)) { return true; } } return false; } bool BMCContext::is_reachable_returning_false_if_unknown(std::shared_ptr<Model> model) { for (auto bmc : bmcs) { if (bmc->is_reachable_returning_false_if_unknown(model)) { return true; } } return false; } bool BMCContext::is_reachable_exact_steps(std::shared_ptr<Model> model) { return bmcs[bmcs.size() - 1]->is_reachable(model); } bool BMCContext::is_reachable_exact_steps_returning_false_if_unknown(std::shared_ptr<Model> model) { return bmcs[bmcs.size() - 1]->is_reachable_returning_false_if_unknown(model); } <file_sep>/src/template_priority.cpp #include "template_priority.h" #include <queue> #include <iostream> #include <cassert> #include <algorithm> #include "template_counter.h" #include "tree_shapes.h" #include "utils.h" using namespace std; std::vector<TemplateSlice> break_into_slices( shared_ptr<Module> module, TemplateSpace const& ts) { return count_many_templates(module, ts); } vector<TemplateSlice> quantifier_combos( shared_ptr<Module> module, vector<TemplateSlice> const& forall_slices, int maxExists) { vector<TemplateSlice> res; int nsorts = module->sorts.size(); for (TemplateSlice const& ts : forall_slices) { for (int i = 0; i < (1 << nsorts); i++) { TemplateSlice ts1 = ts; bool okay = true; for (int j = 0; j < nsorts; j++) { if (ts.vars[j] == 0 && ((i>>j)&1)) { okay = false; break; } else { ts1.quantifiers[j] = ((i>>j)&1) ? Quantifier::Exists : Quantifier::Forall; } } if (okay) { if (maxExists != -1) { int sumExists = 0; for (int j = 0; j < nsorts; j++) { if (ts1.quantifiers[j] == Quantifier::Exists) { sumExists += ts1.vars[j]; } } if (sumExists > maxExists) { okay = false; } } if (okay) { res.push_back(ts1); } } } } return res; } struct Node { TemplateSlice ts; vector<Node*> succs; int pred_count; }; struct NodePtr { Node* node; NodePtr(Node* n) : node(n) { } bool operator<(NodePtr const& other) const { return node->ts.count > other.node->ts.count; } }; vector<TemplateSlice> get_preds(TemplateSlice const& ts) { vector<TemplateSlice> res; assert (ts.vars.size() == ts.quantifiers.size()); for (int i = 0; i < (int)ts.vars.size(); i++) { assert (!(ts.vars[i] == 0 && ts.quantifiers[i] == Quantifier::Exists)); if (ts.vars[i] > 0) { TemplateSlice ts1 = ts; ts1.vars[i]--; if (ts1.vars[i] == 0) ts1.quantifiers[i] = Quantifier::Forall; ts1.count = -1; res.push_back(ts1); } if (ts.quantifiers[i] == Quantifier::Exists) { TemplateSlice ts1 = ts; ts1.quantifiers[i] = Quantifier::Forall; ts1.count = -1; res.push_back(ts1); } } if (ts.k > 1) { TemplateSlice ts1 = ts; ts1.k--; ts1.count = -1; res.push_back(ts1); } return res; } int slices_get_idx(vector<TemplateSlice> const& slices, TemplateSlice const& ts) { for (int i = 0; i < (int)slices.size(); i++) { if (slices[i].vars == ts.vars && slices[i].quantifiers == ts.quantifiers && slices[i].k == ts.k && slices[i].depth == ts.depth) { return i; } } return -1; } void get_prefixes_rec( vector<vector<int>>& res, TreeShape const& ts, vector<int>& indices, int i, int vis, TransitionSystem const& trans_system) { if (i == (int)indices.size()) { res.push_back(indices); return; } SymmEdge const& symm_edge = ts.symmetry_back_edges[i]; int t = symm_edge.idx == -1 ? 0 : indices[symm_edge.idx] + symm_edge.inc; for (int j = t; j < trans_system.nTransitions(); j++) { if (trans_system.next(vis, j) != -1) { int next = trans_system.next(vis, j); indices[i] = j; get_prefixes_rec(res, ts, indices, i+1, next, trans_system); } } } vector<vector<int>> get_prefixes( TemplateSlice const& slice, TreeShape const& tree_shape, TransitionSystem const& sub_trans_system) { int MAX_SZ = 1; vector<vector<int>> res; int sz = slice.k - 2; if (sz < 0) sz = 0; if (sz > MAX_SZ) sz = MAX_SZ; vector<int> indices; indices.resize(sz); get_prefixes_rec( res, tree_shape, indices, 0, 0, sub_trans_system); return res; } vector<vector<int>> get_prefixes( TemplateSlice const& slice, TransitionSystem const& sub_trans_system) { vector<int> parts; parts.resize(slice.k); for (int i = 0; i < slice.k; i++) { parts[i] = 1; } TreeShape tree_shape = tree_shape_for(true, parts); return get_prefixes(slice, tree_shape, sub_trans_system); } TransitionSystem transition_system_for_slice_list( shared_ptr<Module> module, vector<TemplateSlice> const& slices, int maxVars) { TemplateSpace tspace = space_containing_slices_ignore_quants(module, slices); value templ = tspace.make_templ(module); EnumInfo ei(module, templ); return build_transition_system( get_var_index_init_state(module, templ), ei.var_index_transitions, maxVars); } vector<TemplateSubSlice> split_slice_into_sub_slices( TransitionSystem const& trans_system, vector<TreeShape> const& tree_shapes, TemplateSlice const& slice, map<vector<int>, TransitionSystem>& sub_ts_cache) { auto iter = sub_ts_cache.find(slice.vars); TransitionSystem sub_trans_system; if (iter == sub_ts_cache.end()) { auto p = get_subslice_index_map(trans_system, slice); sub_trans_system = p.first.second; sub_ts_cache.insert(make_pair(slice.vars, sub_trans_system)); } else { sub_trans_system = iter->second; } vector<TemplateSubSlice> sub_slices; if (slice.count != 0) { if (slice.depth == 1) { TemplateSubSlice tss; tss.ts = slice; for (vector<int> pref : get_prefixes(slice, sub_trans_system)) { tss.prefix = pref; sub_slices.push_back(tss); } } else { for (int j = 0; j < (int)tree_shapes.size(); j++) { if (tree_shapes[j].total == slice.k) { TemplateSubSlice tss; tss.ts = slice; tss.tree_idx = j; for (vector<int> pref : get_prefixes(slice, tree_shapes[j], sub_trans_system)) { tss.prefix = pref; sub_slices.push_back(tss); } } } } } return sub_slices; } template <typename T> void random_sort(vector<T>& v, int a, int b) { for (int i = a; i < b-1; i++) { int j = i + (rand() % (b - i)); T tmp = v[i]; v[i] = v[j]; v[j] = tmp; } } vector<TemplateSlice> remove_count0(vector<TemplateSlice> const& v) { vector<TemplateSlice> res; for (TemplateSlice const& slice : v) { if (slice.count != 0) { res.push_back(slice); } } return res; } unsigned long long total_count(vector<TemplateSlice> const& slices) { unsigned long long sum = 0; for (TemplateSlice const& ts : slices) { sum += ts.count; } return sum; } bool strictly_dominates(vector<int> const& a, vector<int> const& b) { for (int i = 0; i < (int)a.size(); i++) { if (a[i] < b[i]) { return false; } } return a != b; } bool unstrictly_dominates(vector<int> const& a, vector<int> const& b) { for (int i = 0; i < (int)a.size(); i++) { if (a[i] < b[i]) { return false; } } return true; } vector<vector<int>> get_pareto_vars(vector<TemplateSlice> const& ts) { vector<vector<int>> v; for (int i = 0; i < (int)ts.size(); i++) { bool is_p = true; for (int j = 0; j < (int)ts.size(); j++) { if (i != j) { if (strictly_dominates(ts[j].vars, ts[i].vars)) { is_p = false; break; } } } if (is_p) { bool is_taken = false; for (int j = 0; j < (int)v.size(); j++) { if (v[j] == ts[i].vars) { is_taken = true; break; } } if (!is_taken) { v.push_back(ts[i].vars); } } } return v; } int get_vars_that_slice_fits_in( vector<vector<int>> const& m, TemplateSlice const& ts) { for (int i = 0; i < (int)m.size(); i++) { if (unstrictly_dominates(m[i], ts.vars)) { return i; } } assert (false); } void sort_decreasing_count_order(vector<vector<TemplateSlice>>& s) { vector<pair<unsigned long long, int>> cs; cs.resize(s.size()); for (int i = 0; i < (int)s.size(); i++) { cs[i].first = -total_count(s[i]); cs[i].second = i; } sort(cs.begin(), cs.end()); vector<vector<TemplateSlice>> t = move(s); s.clear(); for (int i = 0; i < (int)t.size(); i++) { s.push_back(t[cs[i].second]); } } int get_max_k(vector<TemplateSlice> const& slices) { int max_k = 0; for (int i = 0; i < (int)slices.size(); i++) { if (slices[i].k > max_k) { max_k = slices[i].k; } } return max_k; } vector<vector<TemplateSlice>> split_by_size(vector<TemplateSlice> const& slices) { vector<vector<TemplateSlice>> res; int max_k = get_max_k(slices); res.resize(max_k); for (int i = 0; i < (int)slices.size(); i++) { int idx = slices[i].k - 1; assert (0 <= idx && idx < (int)res.size()); res[idx].push_back(slices[i]); } for (int i = 0; i < (int)res.size(); i++) { assert (res[i].size() > 0); } return res; } vector<vector<TemplateSubSlice>> split_into( vector<TemplateSlice> const& slices, int n, TransitionSystem const& trans_system, map<vector<int>, TransitionSystem>& sub_ts_cache, vector<TreeShape> const& tree_shapes) { vector<vector<TemplateSubSlice>> res; res.resize(n); assert (n > 0); for (int i = 0; i < (int)slices.size(); i++) { vector<TemplateSubSlice> new_slices = split_slice_into_sub_slices(trans_system, tree_shapes, slices[i], sub_ts_cache); random_sort(new_slices, 0, new_slices.size()); int k = rand() % n; for (int j = 0; j < (int)new_slices.size(); j++) { res[k].push_back(new_slices[j]); k++; if (k == (int)res.size()) { k = 0; } } } vector<vector<TemplateSubSlice>> res2; for (int i = 0; i < n; i++) { if (res[i].size() > 0) { res2.push_back(move(res[i])); } } return res2; } std::vector<std::vector<TemplateSubSlice>> pack_tightly_dont_exceed_hull( shared_ptr<Module> module, vector<TemplateSlice> const& slices, int nthreads, TransitionSystem const& trans_system, vector<TreeShape> const& tree_shapes, map<vector<int>, TransitionSystem>& sub_ts_cache) { vector<vector<int>> m = get_pareto_vars(slices); vector<vector<TemplateSlice>> s2; s2.resize(m.size()); for (TemplateSlice const& ts : slices) { int idx = get_vars_that_slice_fits_in(m, ts); s2[idx].push_back(ts); } sort_decreasing_count_order(s2); vector<vector<TemplateSubSlice>> res; for (int i = 0; i < (int)s2.size(); i++) { unsigned long long c = total_count(s2[i]); cout << i << " " << c << endl; //long long my_nthreads = (c + 1000 - 1) / 1000; //if (my_nthreads > nthreads) my_nthreads = nthreads; //assert (my_nthreads > 0); unsigned long long my_nthreads = (i == 0 ? 2 : 1); vector_append(res, split_into(s2[i], my_nthreads, trans_system, sub_ts_cache, tree_shapes)); } return res; } std::vector<std::vector<TemplateSubSlice>> prioritize_sub_slices_basic( shared_ptr<Module> module, vector<TemplateSlice> const& slices, int nthreads, TransitionSystem const& trans_system, vector<TreeShape> const& tree_shapes) { map<vector<int>, TransitionSystem> sub_ts_cache; return split_into(slices, nthreads, trans_system, sub_ts_cache, tree_shapes); } vector<vector<vector<TemplateSubSlice>>> prioritize_sub_slices_basic_by_size( shared_ptr<Module> module, vector<TemplateSlice> const& slices, int nthreads, TransitionSystem const& trans_system, vector<TreeShape> const& tree_shapes) { map<vector<int>, TransitionSystem> sub_ts_cache; vector<vector<TemplateSlice>> splits = split_by_size(slices); vector<vector<vector<TemplateSubSlice>>> res; for (int i = 0; i < (int)splits.size(); i++) { res.push_back(split_into(splits[i], nthreads, trans_system, sub_ts_cache, tree_shapes)); } return res; } std::vector<std::vector<TemplateSubSlice>> prioritize_sub_slices_breadth( shared_ptr<Module> module, vector<TemplateSlice> const& slices, int nthreads, TransitionSystem const& trans_system, vector<TreeShape> const& tree_shapes) { map<vector<int>, TransitionSystem> sub_ts_cache; return pack_tightly_dont_exceed_hull(module, slices, nthreads, trans_system, tree_shapes, sub_ts_cache); } vector<vector<vector<TemplateSubSlice>>> prioritize_sub_slices_breadth_by_size( shared_ptr<Module> module, vector<TemplateSlice> const& slices, int nthreads, TransitionSystem const& trans_system, vector<TreeShape> const& tree_shapes) { map<vector<int>, TransitionSystem> sub_ts_cache; vector<vector<TemplateSlice>> splits = split_by_size(slices); vector<vector<vector<TemplateSubSlice>>> res; for (int i = 0; i < (int)splits.size(); i++) { res.push_back(pack_tightly_dont_exceed_hull(module, splits[i], nthreads, trans_system, tree_shapes, sub_ts_cache)); } return res; } /*std::vector<std::vector<TemplateSubSlice>> prioritize_sub_slices_finisher( shared_ptr<Module> module, vector<TemplateSlice> const& slices, int nthreads, TransitionSystem const& trans_system, vector<TreeShape> const& tree_shapes) { for (TemplateSlice const& ts : slices) { cout << ts << endl; } const unsigned long long THRES = 1000000000; map<vector<int>, TransitionSystem> sub_ts_cache; vector<vector<TemplateSubSlice>> res; int a = 0; while (a < (int)slices.size()) { int b = a+1; unsigned long long tc = slices[a].count; while (b < (int)slices.size() && tc + slices[b].count <= THRES) { tc += slices[b].count; b++; } if (b == a+1) { while (b < (int)slices.size() && slices[b].vars == slices[a].vars) { b++; } } vector<TemplateSlice> my_slices; for (int i = a; i < b; i++) { my_slices.push_back(slices[i]); } vector_append(res, pack_tightly_dont_exceed_hull( module, my_slices, nthreads, trans_system, tree_shapes, sub_ts_cache)); a = b; } return res; }*/ std::vector<std::vector<TemplateSubSlice>> prioritize_sub_slices_finisher( shared_ptr<Module> module, vector<TemplateSlice> const& slices, int nthreads, TransitionSystem const& trans_system, vector<TreeShape> const& tree_shapes) { int nsorts = module->sorts.size(); int max_mvars = 0; for (TemplateSlice const& ts : slices) { max_mvars = max(max_mvars, total_vars(ts)); } vector<vector<TemplateSlice>> all_slices_per_thread; int idx = 0; vector<vector<int>> max_vars_per_thread; vector<unsigned long long> counts; all_slices_per_thread.resize(nthreads); max_vars_per_thread.resize(nthreads); counts.resize(nthreads); for (int i = 0; i < nthreads; i++) { max_vars_per_thread[i].resize(nsorts); } map<vector<int>, TransitionSystem> sub_ts_cache; for (int i = 0; i < (int)slices.size(); i++) { TemplateSlice const& ts = slices[i]; //vector<TemplateSubSlice> new_slices = // split_slice_into_sub_slices(trans_system, tree_shapes, slices[i], sub_ts_cache); //random_sort(new_slices, 0, new_slices.size()); bool from_start = (ts.count <= 100000); vector<int> possibilities; int jstart = from_start ? 0 : (int)all_slices_per_thread.size() - nthreads; for (int j = jstart; j < (int)all_slices_per_thread.size(); j++) { int m = 0; for (int k = 0; k < nsorts; k++) { m += max(max_vars_per_thread[j][k], ts.vars[k]); } if (m <= max_mvars) { possibilities.push_back(j); } } if (possibilities.size() == 0) { vector<int> i0 = ts.vars; all_slices_per_thread.push_back(vector<TemplateSlice>{ts}); max_vars_per_thread.push_back(i0); counts.push_back(ts.count); idx++; } else { int best = possibilities[0]; for (int j = 1; j < (int)possibilities.size(); j++) { if (counts[possibilities[j]] < counts[best]) { best = possibilities[j]; } } all_slices_per_thread[best].push_back(ts); counts[best] += ts.count; for (int k = 0; k < nsorts; k++) { max_vars_per_thread[best][k] = max(max_vars_per_thread[best][k], ts.vars[k]); } } } vector<vector<TemplateSubSlice>> res; for (int i = 0; i < (int)all_slices_per_thread.size(); i++) { bool last = (i == (int)all_slices_per_thread.size() - 1); unsigned long long my_nthreads = (last ? nthreads : 1); vector_append(res, split_into(all_slices_per_thread[i], my_nthreads, trans_system, sub_ts_cache, tree_shapes)); } return res; } vector<vector<vector<TemplateSubSlice>>> prioritize_sub_slices( std::shared_ptr<Module> module, std::vector<TemplateSlice> const& _slices, int nthreads, bool is_for_breadth, bool by_size, bool basic_split) { std::vector<TemplateSlice> slices = _slices; if (slices.size() == 0) { assert (nthreads == 1); vector<TemplateSubSlice> emp; std::vector<std::vector<TemplateSubSlice>> res; res.push_back(emp); vector<vector<vector<TemplateSubSlice>>> res2; res2.push_back(res); return res2; } int max_k = 1; for (int i = 0; i < (int)slices.size(); i++) { vector<TemplateSlice> preds = get_preds(slices[i]); for (int j = 0; j < (int)preds.size(); j++) { int idx = slices_get_idx(slices, preds[j]); if (idx == -1) { preds[j].count = 0; slices.push_back(preds[j]); } } } vector<Node> nodes; nodes.resize(slices.size()); for (int i = 0; i < (int)slices.size(); i++) { nodes[i].pred_count = 0; nodes[i].ts = slices[i]; if (slices[i].k > max_k) { max_k = slices[i].k; } } for (int i = 0; i < (int)slices.size(); i++) { vector<TemplateSlice> preds = get_preds(slices[i]); for (int j = 0; j < (int)preds.size(); j++) { int idx = slices_get_idx(slices, preds[j]); assert (idx != -1); nodes[idx].succs.push_back(&nodes[i]); nodes[i].pred_count++; } } /*priority_queue<NodePtr> q; for (int i = 0; i < (int)slices.size(); i++) { if (nodes[i].pred_count == 0) { q.push(NodePtr(&nodes[i])); } } vector<TemplateSlice> ordered_slices; while (!q.empty()) { NodePtr nptr = q.top(); q.pop(); ordered_slices.push_back(nptr.node->ts); for (Node* succ : nptr.node->succs) { succ->pred_count--; if (succ->pred_count == 0) { q.push(NodePtr(succ)); } } }*/ vector<TemplateSlice> ordered_slices = slices; sort(ordered_slices.begin(), ordered_slices.end()); assert (ordered_slices.size() == slices.size()); //cout << "----" << endl; //for (TemplateSlice const& ts : ordered_slices) { // cout << ts << endl; //} cout << "ordered_slices: " << ordered_slices.size() << endl; ordered_slices = remove_count0(ordered_slices); vector<TreeShape> tree_shapes = get_tree_shapes_up_to(max_k); //int nsorts = module->sorts.size(); int max_mvars = 0; for (TemplateSlice const& ts : ordered_slices) { max_mvars = max(max_mvars, total_vars(ts)); } TransitionSystem trans_system = transition_system_for_slice_list(module, ordered_slices, max_mvars); assert(nthreads >= 1); if (basic_split) { if (by_size) { return prioritize_sub_slices_basic_by_size( module, ordered_slices, nthreads, trans_system, tree_shapes); } else { return {prioritize_sub_slices_basic( module, ordered_slices, nthreads, trans_system, tree_shapes)}; } } else if (is_for_breadth) { if (by_size) { return prioritize_sub_slices_breadth_by_size( module, ordered_slices, nthreads, trans_system, tree_shapes); } else { return {prioritize_sub_slices_breadth( module, ordered_slices, nthreads, trans_system, tree_shapes)}; } } else { return {prioritize_sub_slices_finisher( module, ordered_slices, nthreads, trans_system, tree_shapes)}; } /*vector<vector<TemplateSubSlice>> all_sub_slices_per_thread; int idx = 0; vector<vector<int>> max_vars_per_thread; vector<int> counts; all_sub_slices_per_thread.resize(nthreads); max_vars_per_thread.resize(nthreads); counts.resize(nthreads); for (int i = 0; i < nthreads; i++) { max_vars_per_thread[i].resize(nsorts); } map<vector<int>, TransitionSystem> sub_ts_cache; for (int i = 0; i < (int)ordered_slices.size(); i++) { TemplateSlice const& ts = ordered_slices[i]; vector<TemplateSubSlice> new_slices = split_slice_into_sub_slices(trans_system, tree_shapes, ordered_slices[i], sub_ts_cache); random_sort(new_slices, 0, new_slices.size()); bool from_start = (ts.count <= 100000 || is_for_breadth); vector<int> possibilities; int jstart = from_start ? 0 : (int)all_sub_slices_per_thread.size() - nthreads; for (int j = jstart; j < (int)all_sub_slices_per_thread.size(); j++) { int m = 0; for (int k = 0; k < nsorts; k++) { m += max(max_vars_per_thread[j][k], ts.vars[k]); } if (m <= max_mvars) { possibilities.push_back(j); } } if (possibilities.size() == 0) { vector<int> i0 = ts.vars; all_sub_slices_per_thread.push_back(new_slices); max_vars_per_thread.push_back(i0); counts.push_back(ts.count); idx++; } else { int best = possibilities[0]; for (int j = 1; j < (int)possibilities.size(); j++) { if (counts[possibilities[j]] < counts[best]) { best = possibilities[j]; } } vector_append(all_sub_slices_per_thread[best], new_slices); counts[best] += ts.count; for (int k = 0; k < nsorts; k++) { max_vars_per_thread[best][k] = max(max_vars_per_thread[best][k], ts.vars[k]); } } } vector<vector<TemplateSubSlice>> res; for (int i = 0; i < (int)all_sub_slices_per_thread.size(); i++) { if (all_sub_slices_per_thread[i].size() != 0) { res.push_back(move(all_sub_slices_per_thread[i])); cout << "partition count: " << counts[i] << endl; } } return res;*/ /*int a = 0; while (a < (int)ordered_slices.size()) { int b = a; unsigned long long total_count = 0; vector<int> vars; vars.resize(module->sorts.size()); while (b < (int)ordered_slices.size()) { int var_sum = 0; for (int i = 0; i < (int)vars.size(); i++) { vars[i] = max(vars[i], ordered_slices[b].vars[i]); var_sum += vars[i]; } if (var_sum > max_mvars) { break; } total_count += ordered_slices[b].count; b++; } unsigned long long my_nthreads = (total_count + 1000 - 1) / 1000; if (my_nthreads > nthreads) my_nthreads = nthreads; assert (my_nthreads > 0); vector<vector<TemplateSubSlice>> sub_slices_per_thread; sub_slices_per_thread.resize(my_nthreads); for (int i = a; i < b; i++) { vector<TemplateSubSlice> new_slices = split_slice_into_sub_slices(trans_system, tree_shapes, ordered_slices[i]); random_sort(new_slices, 0, new_slices.size()); int k = rand() % sub_slices_per_thread.size(); for (int j = 0; j < (int)new_slices.size(); j++) { sub_slices_per_thread[k].push_back(new_slices[j]); k++; if (k == (int)sub_slices_per_thread.size()) { k = 0; } } } for (int i = 0; i < (int)sub_slices_per_thread.size(); i++) { if (sub_slices_per_thread[i].size() > 0) { all_sub_slices_per_thread.push_back( move(sub_slices_per_thread[i])); } } a = b; } return all_sub_slices_per_thread;*/ /* for (int i = 0; i < (int)ordered_slices.size(); i++) { vector<TemplateSubSlice> new_slices = split_slice_into_sub_slices(trans_system, tree_shapes, ordered_slices[i]); random_sort(new_slices, 0, new_slices.size()); int k = rand() % sub_slices_per_thread.size(); for (int j = 0; j < (int)new_slices.size(); j++) { sub_slices_per_thread[k].push_back(new_slices[j]); k++; if (k == nthreads) { k = 0; } } } return sub_slices_per_thread; */ } <file_sep>/src/auto_redundancy_filters.h #ifndef AUTO_REDUNDANCY_FILTERS_H #define AUTO_REDUNDANCY_FILTERS_H #include "logic.h" #include <vector> std::vector<std::vector<int>> get_auto_redundancy_filters( std::vector<value> const&); #endif <file_sep>/src/utils.h #ifndef UTILS_H #define UTILS_H #include "logic.h" bool is_redundant_quick(value a, value b); std::vector<int> sort_and_uniquify(std::vector<int> const& v); template <typename T> void vector_append(std::vector<T>& a, std::vector<T> const& b) { for (int i = 0; i < (int)b.size(); i++) { a.push_back(b[i]); } } #endif <file_sep>/src/synth_enumerator.cpp #include "synth_enumerator.h" #include <cassert> #include <vector> #include <map> #include "enumerator.h" #include "alt_synth_enumerator.h" #include "alt_depth2_synth_enumerator.h" using namespace std; class OverlordCandidateSolver : public CandidateSolver { public: vector<TemplateSubSlice> sub_slices; vector<TemplateSpace> spaces; vector<shared_ptr<CandidateSolver>> solvers; vector<int> cex_idx; vector<int> inv_idx; vector<Counterexample> cexes; vector<value> invs; int idx; int solver_idx; bool done; OverlordCandidateSolver( shared_ptr<Module> module, vector<TemplateSubSlice> const& sub_slices) { this->sub_slices = sub_slices; cout << "OverlordCandidateSolver" << endl; //for (TemplateSubSlice const& tss : sub_slices) { // cout << tss << endl; //} spaces = finer_spaces_containing_sub_slices(module, sub_slices); for (int i = 0; i < (int)spaces.size(); i++) { cout << endl; cout << "--- Initializing enumerator ---" << endl; cout << spaces[i] << endl; solvers.push_back(shared_ptr<CandidateSolver>( spaces[i].depth == 2 ? (CandidateSolver*)new AltDepth2CandidateSolver(module, spaces[i]) : (CandidateSolver*)new AltDisjunctCandidateSolver(module, spaces[i]) )); cex_idx.push_back(0); inv_idx.push_back(0); } idx = 0; done = false; set_solver_idx(); } void update_cexes_invs() { while (inv_idx[solver_idx] < (int)invs.size()) { solvers[solver_idx]->addExistingInvariant(invs[inv_idx[solver_idx]]); inv_idx[solver_idx]++; } while (cex_idx[solver_idx] < (int)cexes.size()) { solvers[solver_idx]->addCounterexample(cexes[cex_idx[solver_idx]]); cex_idx[solver_idx]++; } } void set_solver_idx() { if (idx < (int)sub_slices.size()) { cout << endl << "OverlordCandidateSolver: " << sub_slices[idx] << endl << "OverlordCandidateSolver: index " << idx << " / " << sub_slices.size() << endl << endl; for (int i = 0; i < (int)spaces.size(); i++) { if (is_subspace(sub_slices[idx], spaces[i])) { //cout << "setting to " << i << endl; solver_idx = i; solvers[i]->setSubSlice(sub_slices[idx]); //cout << "done set " << endl; update_cexes_invs(); return; } } assert (false); } else { cout << endl << "OverlordCandidateSolver: done" << endl << endl; done = true; } } value getNext() { //cout << "getNext()" << endl; while (!done) { //cout << "calling getNext()" << endl; value next = solvers[solver_idx]->getNext(); //cout << "done getNext()" << endl; if (next != nullptr) { //cout << "returning" << endl; return next; } else { idx++; set_solver_idx(); } } return nullptr; } void addCounterexample(Counterexample cex) { cexes.push_back(cex); solvers[solver_idx]->addCounterexample(cex); cex_idx[solver_idx]++; } void addExistingInvariant(value inv) { invs.push_back(inv); solvers[solver_idx]->addExistingInvariant(inv); inv_idx[solver_idx]++; } long long getProgress() { return -1; } long long getSpaceSize() { assert(false); } long long getPreSymmCount() { long long res = 0; for (int i = 0; i < (int)solvers.size(); i++) { res += solvers[i]->getPreSymmCount(); } return res; } void setSubSlice(TemplateSubSlice const& tss) { assert(false); } }; std::shared_ptr<CandidateSolver> make_candidate_solver( std::shared_ptr<Module> module, vector<TemplateSubSlice> const& sub_slices, bool ensure_nonredundant) { return shared_ptr<CandidateSolver>( new OverlordCandidateSolver(module, sub_slices)); } <file_sep>/src/tree_shapes.h #ifndef TREE_SHAPES_H #define TREE_SHAPES_H #include <vector> #include <string> struct SymmEdge { int idx; int inc; SymmEdge(int idx, int inc) : idx(idx), inc(inc) { } }; struct TreeShape { bool top_level_is_conj; int total; std::vector<int> parts; // For i < j, there's an edge from j to i // if any symmetry-normalized formula should have // pieces[i] + inc <= piece[j] // This is vector from j to (i, inc) (or to -1 if no such edge) // for 0 <= j < total // inc will always be 0 or 1. std::vector<SymmEdge> symmetry_back_edges; std::string to_string() const; }; std::vector<TreeShape> get_tree_shapes_up_to(int n); bool is_normalized_for_tree_shape(TreeShape const& ts, std::vector<int> const& pieces); TreeShape tree_shape_for(bool top_level_is_conj, std::vector<int> const& parts); #endif <file_sep>/run-simple.sh #!/bin/bash set -e IVY_FILE=$1 TEMP=$(mktemp) if [ ${IVY_FILE: -4} == ".pyv" ] then python3 scripts/file_mypyvy_to_json.py $IVY_FILE > $TEMP else python scripts/file_to_json.py $IVY_FILE > $TEMP fi shift ./synthesis --input-module $TEMP "$@" #python3 src/driver.py "$TEMP" "$@" <file_sep>/src/template_counter.cpp #include "template_counter.h" #include <iostream> #include <cassert> #include <algorithm> #include <unordered_map> #include <set> #include "logic.h" #include "enumerator.h" #include "var_lex_graph.h" #include "tree_shapes.h" #include "top_quantifier_desc.h" using namespace std; struct Vector { vector<unsigned long long> v; void subtract(Vector const& other) { for (int i = 0; i < (int)v.size(); i++) { v[i] -= other.v[i]; } } unsigned long long get_entry_or_sum(int idx) { if (idx == -1) { unsigned long long sum = 0; for (int i = 0; i < (int)v.size(); i++) { sum += v[i]; } return sum; } else { return v[idx]; } } }; struct Matrix { vector<vector<unsigned long long>> m; Matrix() { } Matrix(int n) { m.resize(n); for (int i = 0; i < n; i++) { m[i].resize(n-i); } } void add(Matrix const& a) { int n = m.size(); for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { m[i][j-i] += a.m[i][j-i]; } } } void add_product(Matrix const& a, Matrix const& b) { int n = m.size(); for (int i = 0; i < n; i++) { for (int k = i; k < n; k++) { for (int j = k; j < n; j++) { m[i][j-i] += a.m[i][k-i] * b.m[k][j-k]; } } } } void add_product(TransitionSystem const& ts, int trans, Matrix const& a, Matrix const& b) { int n = m.size(); for (int i = 0; i < n; i++) { int i1 = ts.next(i, trans); if (i1 != -1) { for (int k = i1; k < n; k++) { for (int j = k; j < n; j++) { m[i][j-i] += a.m[i1][k-i1] * b.m[k][j-k]; } } } } } void add_product(TransitionSystem const& ts, int trans, Matrix const& a) { int n = m.size(); for (int i = 0; i < n; i++) { int i1 = ts.next(i, trans); if (i1 != -1) { for (int j = i1; j < n; j++) { m[i][j-i] += a.m[i1][j-i1]; } } } } void set_to_identity() { int n = m.size(); for (int i = 0; i < n; i++) { for (int j = i+1; j < n; j++) { m[i][j-i] = 0; } m[i][i-i] = 1; } } unsigned long long count_from_to(int from, int to) { if (to == -1) { unsigned long long res = 0; int n = m.size(); for (int i = from; i < n; i++) { res += m[from][i-from]; } return res; } else { if (to >= from) { return m[from][to-from]; } else { return 0; } } } Vector get_row(int from) { Vector v; v.v.resize(m.size()); for (int i = from; i < (int)m.size(); i++) { v.v[i] = m[from][i-from]; } return v; } }; struct GroupSpec { int groupSize; int nGroups; int firstMin; GroupSpec( int groupSize, int nGroups, int firstMin) : groupSize(groupSize), nGroups(nGroups), firstMin(firstMin) { } }; map<pair<int, int>, vector<shared_ptr<Matrix>>> group_spec_to_matrix; Matrix* getMatrixForGroupSpec(GroupSpec gs, TransitionSystem const& ts) { auto key = make_pair(gs.groupSize, gs.nGroups); auto it = group_spec_to_matrix.find(key); if (it != group_spec_to_matrix.end()) { return it->second[gs.firstMin].get(); } int m = ts.nTransitions(); int n = ts.nStates(); vector<shared_ptr<Matrix>> res; res.resize(m + 1); if (gs.nGroups == 0) { res[m] = shared_ptr<Matrix>(new Matrix(n)); res[m]->set_to_identity(); for (int i = m-1; i >= 0; i--) { res[i] = res[m]; } } else { res[m] = shared_ptr<Matrix>(new Matrix(n)); for (int i = m - 1; i >= 0; i--) { res[i] = shared_ptr<Matrix>(new Matrix()); res[i]->m = res[i+1]->m; if (gs.groupSize >= 2) { for (int numSame = 1; numSame < gs.nGroups; numSame++) { res[i]->add_product(ts, i, *getMatrixForGroupSpec(GroupSpec(gs.groupSize - 1, numSame, i+1), ts), *getMatrixForGroupSpec(GroupSpec(gs.groupSize, gs.nGroups-numSame, i+1), ts)); } res[i]->add_product(ts, i, *getMatrixForGroupSpec(GroupSpec(gs.groupSize - 1, gs.nGroups, i+1), ts)); } else { assert (gs.groupSize == 1); res[i]->add_product(ts, i, *getMatrixForGroupSpec(GroupSpec(1, gs.nGroups - 1, i+1), ts)); } } } group_spec_to_matrix[key] = res; //cout << group_spec_to_matrix.size() << endl; return res[gs.firstMin].get(); } EnumInfo::EnumInfo(std::shared_ptr<Module> module, value templ) { clauses = get_clauses_for_template(module, templ); var_index_transitions = get_var_index_transitions(module, templ, clauses); } TransitionSystem build_transition_system( VarIndexState const& init, std::vector<VarIndexTransition> const& transitions, int maxVars) { vector<VarIndexState> idx_to_state; idx_to_state.push_back(init); vector<vector<int>> matrix; unordered_map<VarIndexState, int> state_to_idx; state_to_idx.insert(make_pair(init, 0)); int cur = 0; while (cur < (int)idx_to_state.size()) { //cout << "cur " << cur << endl; matrix.push_back(vector<int>(transitions.size())); VarIndexState cur_state = idx_to_state[cur]; //cout << "cur " << cur_state.to_string() << endl; VarIndexState next(cur_state.indices.size()); for (int i = 0; i < (int)transitions.size(); i++) { //cout << "transition " << i << endl; //cout << "pre " << transitions[i].pre.to_string() << endl; if (var_index_is_valid_transition(cur_state, transitions[i].pre)) { //cout << "cur " << cur_state.to_string() << endl; //cout << "res " << transitions[i].res.to_string() << endl; var_index_do_transition(cur_state, transitions[i].res, next); //cout << "next " << next.to_string() << endl; bool okay; if (maxVars != -1) { int sum = 0; for (int j : next.indices) { sum += j; } okay = (sum <= maxVars); } else { okay = true; } if (okay) { int next_idx; auto iter = state_to_idx.find(next); if (iter == state_to_idx.end()) { idx_to_state.push_back(next); state_to_idx.insert(make_pair(next, idx_to_state.size() - 1)); next_idx = idx_to_state.size() - 1; } else { next_idx = iter->second; } matrix[cur][i] = next_idx; } else { matrix[cur][i] = -1; } } else { matrix[cur][i] = -1; } } cur++; } vector<vector<int>> state_reps; for (int i = 0; i < (int)idx_to_state.size(); i++) { state_reps.push_back(idx_to_state[i].indices); } return TransitionSystem(matrix, state_reps); } vector<Vector> countDepth1( TransitionSystem const& ts, int d) { vector<Vector> res; res.resize(d + 1); for (int i = 1; i <= d; i++) { Matrix* m = getMatrixForGroupSpec(GroupSpec(1, i, 0), ts); res[i] = m->get_row(0); } return res; } vector<Vector> countDepth2( TransitionSystem const& ts, int d) { if (d < 2) { d = 2; } int nStates = ts.nStates(); // position, max len after position, state vector<vector<Matrix>> dp; dp.resize(d+1); for (int i = 0; i <= d; i++) { dp[i].resize(d); for (int j = 0; j < d; j++) { dp[i][j] = Matrix(nStates); } } for (int j = 0; j < d; j++) { dp[d][j].set_to_identity(); } for (int i = d-1; i >= 0; i--) { for (int j = 1; j < d; j++) { dp[i][j] = dp[i][j-1]; int groupSize = j; for (int nGroups = 1; i + groupSize * nGroups <= d; nGroups++) { Matrix *m = getMatrixForGroupSpec(GroupSpec(groupSize, nGroups, 0), ts); dp[i][j].add_product(*m, dp[i + groupSize * nGroups][groupSize - 1]); } } } vector<Vector> res; res.resize(d+1); for (int i = 1; i <= d; i++) { //cout << "yo " << dp[d-i][d][0] << endl; res[i] = dp[d-i][d-1].get_row(0); } for (int i = 2; i < d; i++) { Matrix *m = getMatrixForGroupSpec(GroupSpec(i, 1, 0), ts); res[i].subtract(m->get_row(0)); } return res; } int get_num_vars(shared_ptr<Module> module, value templ) { TopAlternatingQuantifierDesc taqd(templ); vector<Alternation> alts = taqd.alternations(); int count = 0; for (int j = 0; j < (int)alts.size(); j++) { count += alts[j].decls.size(); } return count; } unsigned long long count_template( shared_ptr<Module> module, value templ, int k, bool depth2, bool useAllVars) { EnumInfo ei(module, templ); TransitionSystem ts = build_transition_system( get_var_index_init_state(module, templ), ei.var_index_transitions, -1); ts = ts.cap_total_vars(get_num_vars(module, templ)); ts = ts.remove_unused_transitions(); ts = ts.make_upper_triangular(); cout << "clauses: " << ei.clauses.size() << endl; /*for (value v : ei.clauses) { cout << v->to_string() << endl; }*/ cout << "nStates: " << ts.nStates() << endl; int final = ts.nStates() - 1; assert (final != -1); if (!useAllVars) { final = -1; } vector<Vector> counts; if (depth2) { counts = countDepth2(ts, k); } else { counts = countDepth1(ts, k); } group_spec_to_matrix.clear(); unsigned long long total = 0; for (int i = 1; i <= k; i++) { unsigned long long v = counts[i].get_entry_or_sum(final); if (depth2 && i > 1) { v *= 2; } cout << "k = " << i << " : " << v << endl; total += v; } cout << "total = " << total << endl; return total; } vector<TemplateSlice> count_many_templates( shared_ptr<Module> module, value templ, int maxClauses, bool depth2, int maxVars) { EnumInfo ei(module, templ); TransitionSystem ts = build_transition_system( get_var_index_init_state(module, templ), ei.var_index_transitions, maxVars); if (maxVars != -1) { ts = ts.cap_total_vars(maxVars); } ts = ts.remove_unused_transitions(); ts = ts.make_upper_triangular(); cout << "states " << ts.nStates() << endl; cout << "transitions " << ts.nTransitions() << endl; vector<Vector> counts; if (depth2) { counts = countDepth2(ts, maxClauses); } else { counts = countDepth1(ts, maxClauses); } group_spec_to_matrix.clear(); vector<TemplateSlice> tds; for (int d = 1; d <= maxClauses; d++) { for (int i = 0; i < ts.nStates(); i++) { TemplateSlice td; td.vars = ts.state_reps[i]; td.quantifiers.resize(td.vars.size()); for (int j = 0; j < (int)td.quantifiers.size(); j++) { td.quantifiers[j] = Quantifier::Forall; } td.k = d; td.depth = (depth2 ? 2 : 1); td.count = (depth2 && d > 1 ? 2 : 1) * counts[d].v[i]; tds.push_back(td); } } sort(tds.begin(), tds.end()); /*for (TemplateSlice const& td : tds) { cout << td.to_string(module) << endl; }*/ return tds; } struct Partial { int capTo; int sort_idx; int sort_exact_num; int other_bound; int a_idx; int b_idx; int v; int w; Partial() : capTo(-1), sort_idx(-1), sort_exact_num(-1), a_idx(-1), b_idx(-1) { } }; value make_template_with_max_vars(shared_ptr<Module> module, int maxVars, Partial partial) { vector<VarDecl> decls; int idx = 0; int so_idx = 0; for (string so_name : module->sorts) { //int v = (so_idx == 1 ? maxVars - 2 : 2); int v; if (partial.capTo != -1) { v = partial.capTo; } else if (partial.sort_idx != -1) { v = (so_idx == partial.sort_idx ? partial.sort_exact_num : partial.other_bound); } else if (partial.a_idx != -1) { v = (so_idx == partial.a_idx || so_idx == partial.b_idx ? partial.v : partial.w); } else { assert(false); } lsort so = s_uninterp(so_name); for (int i = 0; i < v; i++) { idx++; string s = to_string(idx); while (s.size() < 4) { s = "0" + s; } s = "A" + s; decls.push_back(VarDecl(string_to_iden(s), so)); } so_idx++; } return v_forall(decls, v_template_hole()); } value make_template_with_max_vars(shared_ptr<Module> module, vector<int> const& va) { vector<VarDecl> decls; int idx = 0; int so_idx = 0; for (string so_name : module->sorts) { int v = va[so_idx]; lsort so = s_uninterp(so_name); for (int i = 0; i < v; i++) { idx++; string s = to_string(idx); while (s.size() < 4) { s = "0" + s; } s = "A" + s; decls.push_back(VarDecl(string_to_iden(s), so)); } so_idx++; } return v_forall(decls, v_template_hole()); } vector<TemplateSlice> count_many_templates( shared_ptr<Module> module, int maxClauses, bool depth2, int maxVars) { vector<TemplateSlice> res; if (maxVars % 2 == 1 && maxVars >= 5) { vector<Partial> partials; int halfCap = maxVars / 2 - 1; Partial m; m.capTo = halfCap; partials.push_back(m); /*for (int i = 0; i < (int)module->sorts.size(); i++) { for (int j = maxVars / 2; j < (int)module->sorts.size(); j++) { Partial p; p.sort_idx = i; p.sort_exact_num = j; p.other_bound = min(maxVars - j, maxVars / 2 - 1); partials.push_back(p); } }*/ /*for (int i = 0; i < (int)module->sorts.size(); i++) { for (int j = i+1; j < (int)module->sorts.size(); j++) { Partial p; p.a_idx = i; p.b_idx = j; p.v = maxVars / 2 + 1; p.w = 1; partials.push_back(p); } }*/ for (Partial partial : partials) { cout << "partial" << endl; value templ = make_template_with_max_vars(module, maxVars, partial); vector<TemplateSlice> slices = count_many_templates(module, templ, maxClauses, depth2, maxVars); if (partial.sort_idx != -1) { for (TemplateSlice const& ts : slices) { if (ts.vars[partial.sort_idx] == partial.sort_exact_num) { cout << ts << endl; res.push_back(ts); } } } else if (partial.a_idx != -1) { for (TemplateSlice const& ts : slices) { if (ts.vars[partial.a_idx] >= partial.v - 1 && ts.vars[partial.b_idx] >= partial.v - 1) { cout << ts << endl; res.push_back(ts); } } } else { for (TemplateSlice const& ts : slices) { cout << ts << endl; res.push_back(ts); } } } set<vector<int>> seen; for (TemplateSlice const& ts : res) { seen.insert(ts.vars); } vector<int> v; v.resize(module->sorts.size()); while (true) { bool okay = false; int sum = 0; for (int i = 0; i < (int)v.size(); i++) { if (v[i] >= maxVars / 2) { okay = true; } sum += v[i]; } if (okay && sum == maxVars) { cout << "doing "; for (int w : v) cout << w << " "; cout << endl; value templ = make_template_with_max_vars(module, v); vector<TemplateSlice> slices = count_many_templates(module, templ, maxClauses, depth2, maxVars); for (TemplateSlice const& ts : slices) { if (seen.find(ts.vars) == seen.end()) { cout << ts << endl; res.push_back(ts); } } for (TemplateSlice const& ts : slices) { seen.insert(ts.vars); } } int i; for (i = 0; i < (int)v.size(); i++) { v[i]++; if (v[i] == maxVars+1) { v[i] = 0; } else { break; } } if (i == (int)v.size()) { break; } } } else { vector<Partial> partials; int halfCap = maxVars / 2; Partial m; m.capTo = halfCap; partials.push_back(m); for (int i = 0; i < (int)module->sorts.size(); i++) { for (int j = halfCap + 1; j <= maxVars; j++) { Partial p; p.sort_idx = i; p.sort_exact_num = j; p.other_bound = maxVars - j; partials.push_back(p); } } for (Partial partial : partials) { cout << "partial" << endl; value templ = make_template_with_max_vars(module, maxVars, partial); vector<TemplateSlice> slices = count_many_templates(module, templ, maxClauses, depth2, maxVars); if (partial.sort_idx != -1) { for (TemplateSlice const& ts : slices) { if (ts.vars[partial.sort_idx] == partial.sort_exact_num) { cout << ts << endl; res.push_back(ts); } } } else { for (TemplateSlice const& ts : slices) { cout << ts << endl; res.push_back(ts); } } } } sort(res.begin(), res.end()); return res; } vector<TemplateSlice> count_many_templates( shared_ptr<Module> module, TemplateSpace const& ts) { value templ = ts.make_templ(module); vector<TemplateSlice> slices = count_many_templates(module, templ, ts.k, (ts.depth == 2), -1); for (int i = 0; i < (int)slices.size(); i++) { slices[i].quantifiers = ts.quantifiers; assert (slices[i].quantifiers.size() == slices[i].vars.size()); for (int j = 0; j < (int)slices[i].quantifiers.size(); j++) { if (slices[i].vars[j] == 0) { slices[i].quantifiers[j] = Quantifier::Forall; } } } return slices; } pair<std::pair<std::vector<int>, TransitionSystem>, int> get_subslice_index_map( TransitionSystem const& ts, TemplateSlice const& tslice) { vector<bool> in_slice; in_slice.resize(ts.nStates()); for (int i = 0; i < ts.nStates(); i++) { in_slice[i] = true; for (int j = 0; j < (int)tslice.vars.size(); j++) { if (tslice.vars[j] < ts.state_reps[i][j]) { in_slice[i] = false; break; } } } vector<int> res; vector<bool> trans_keep; trans_keep.resize(ts.nTransitions()); for (int i = 0; i < ts.nTransitions(); i++) { bool is_okay = false; for (int j = 0; j < ts.nStates(); j++) { if (in_slice[j] && ts.next(j, i) != -1 && in_slice[ts.next(j, i)]) { is_okay = true; break; } } trans_keep[i] = is_okay; if (is_okay) { res.push_back(i); } } int target_state = -1; for (int i = 0; i < ts.nStates(); i++) { if (ts.state_reps[i] == tslice.vars) { target_state = i; break; } } //assert(target_state != -1); return make_pair(make_pair(res, ts.remove_transitions(trans_keep)), target_state); } <file_sep>/src/template_desc.cpp #include "template_desc.h" #include <ostream> #include <istream> #include <iostream> #include <cassert> #include <algorithm> #include "utils.h" using namespace std; ostream& operator<<(ostream& os, const TemplateSpace& ts) { os << "TemplateSpace[ "; os << "k " << ts.k << " d " << ts.depth << " vars ("; assert (ts.vars.size() == ts.quantifiers.size()); for (int i = 0; i < (int)ts.vars.size(); i++) { os << " " << ts.vars[i] << " " << (ts.quantifiers[i] == Quantifier::Forall ? "forall" : "exists"); } os << " ) ]"; return os; } ostream& operator<<(ostream& os, const TemplateSlice& td) { os << "TemplateSlice[ "; os << "k " << td.k << " d " << td.depth << " count " << td.count << " size " << td.vars.size() << " vars"; assert (td.vars.size() == td.quantifiers.size()); for (int i = 0; i < (int)td.vars.size(); i++) { os << " " << td.vars[i] << " " << (td.quantifiers[i] == Quantifier::Forall ? "forall" : "exists"); } os << " ]"; return os; } istream& operator>>(istream& is, TemplateSlice& td) { string b; is >> b; assert(b == "TemplateSlice["); is >> b; assert(b == "k"); is >> td.k; is >> b; assert(b == "d"); is >> td.depth; is >> b; assert(b == "count"); is >> td.count; is >> b; assert(b == "size"); int sz; is >> sz; is >> b; assert(b == "vars"); td.vars = {}; for (int i = 0; i < sz; i++) { int x; is >> x; string quant; is >> quant; assert (quant == "forall" || quant == "exists"); td.vars.push_back(x); td.quantifiers.push_back(quant == "forall" ? Quantifier::Forall : Quantifier::Exists); } is >> b; assert(b == "]"); return is; } std::string TemplateSlice::to_string(std::shared_ptr<Module> module) const { std::string s = "(("; for (int i = 0; i < (int)module->sorts.size(); i++) { if (i > 0) { s += ", "; } s += module->sorts[i]; s += " "; s += ::to_string(vars[i]); } s += ") depth " + ::to_string(depth) + ", k " + ::to_string(k) + ") count " + ::to_string(count); return s; } ostream& operator<<(ostream& os, const TemplateSubSlice& tss) { os << "TemplateSubSlice[ "; os << tss.ts; os << " "; if (tss.ts.depth == 2) { os << "tree " << tss.tree_idx << " "; } os << "prefix"; for (int p : tss.prefix) { os << " " << p; } os << " ]"; return os; } istream& operator>>(istream& is, TemplateSubSlice& tss) { string b; is >> b; assert (b == "TemplateSubSlice["); is >> tss.ts; if (tss.ts.depth == 2) { is >> b; assert (b == "tree"); is >> tss.tree_idx; } else { tss.tree_idx = -1; } is >> b; assert (b == "prefix"); while (true) { is >> b; assert (b.size() > 0); if (b[0] == ']') { break; } tss.prefix.push_back(stoi(b)); assert ((int)tss.prefix.size() <= tss.ts.k); } return is; } value TemplateSpace::make_templ(shared_ptr<Module> module) const { vector<pair<Quantifier, VarDecl>> decls; int num = 0; for (int i = 0; i < (int)vars.size(); i++) { lsort so = s_uninterp(module->sorts[i]); for (int j = 0; j < vars[i]; j++) { string name = ::to_string(num); num++; int nsize = 3; assert((int)name.size() <= nsize); while ((int)name.size() < nsize) { name = "0" + name; } name = "A" + name; decls.push_back(make_pair(quantifiers[i], VarDecl(string_to_iden(name), so))); } } value res = v_template_hole(); int b = decls.size(); while (b > 0) { int a = b-1; while (a > 0 && decls[a-1].first == decls[b-1].first) { a--; } Quantifier q = decls[b-1].first; vector<VarDecl> d; for (int i = a; i < b; i++) { d.push_back(decls[i].second); } res = (q == Quantifier::Forall ? v_forall(d, res) : v_exists(d, res)); b = a; } return res; } std::vector<TemplateSpace> spaces_containing_sub_slices( shared_ptr<Module> module, std::vector<TemplateSubSlice> const& slices) { int nsorts = module->sorts.size(); vector<TemplateSpace> tspaces; tspaces.resize(1 << nsorts); for (int i = 0; i < (1 << nsorts); i++) { tspaces[i].vars.resize(nsorts); tspaces[i].quantifiers.resize(nsorts); for (int j = 0; j < nsorts; j++) { tspaces[i].vars[j] = -1; tspaces[i].quantifiers[j] = ( (i>>j)&1 ? Quantifier::Exists : Quantifier::Forall); } tspaces[i].depth = -1; tspaces[i].k = -1; } for (TemplateSubSlice const& tss : slices) { int bitmask = 0; for (int j = 0; j < nsorts; j++) { if (tss.ts.quantifiers[j] == Quantifier::Exists) { bitmask |= (1 << j); } } for (int j = 0; j < nsorts; j++) { tspaces[bitmask].vars[j] = max( tspaces[bitmask].vars[j], tss.ts.vars[j]); } tspaces[bitmask].depth = max( tspaces[bitmask].depth, tss.ts.depth); tspaces[bitmask].k = max( tspaces[bitmask].k, tss.ts.k); } vector<TemplateSpace> res; for (int i = 0; i < (int)tspaces.size(); i++) { if (tspaces[i].depth != -1) { res.push_back(tspaces[i]); } } return res; } int vec_sum(vector<int> const& v) { int sum = 0; for (int i : v) sum += i; return sum; } int total_vars(TemplateSlice const& ts) { return vec_sum(ts.vars); } int total_vars(TemplateSpace const& ts) { return vec_sum(ts.vars); } bool is_subspace_of_any(TemplateSlice const& slice, vector<TemplateSpace> const& spaces) { for (TemplateSpace const& space : spaces) { if (is_subspace(slice, space)) { return true; } } return false; } TemplateSpace slice_to_space(TemplateSlice const& slice) { TemplateSpace ts; ts.vars = slice.vars; ts.quantifiers = slice.quantifiers; ts.depth = slice.depth; ts.k = slice.k; return ts; } TemplateSpace merge_slice_space(TemplateSlice const& slice, TemplateSpace space) { assert (slice.depth == space.depth); if (slice.k > space.k) space.k = slice.k; for (int i = 0; i < (int)slice.vars.size(); i++) { if (slice.vars[i] > space.vars[i]) space.vars[i] = slice.vars[i]; } return space; } bool is_strictly_small(TemplateSlice const& ts, int thresh) { return total_vars(ts) < thresh; } bool is_small(TemplateSpace const& ts, int thresh) { return total_vars(ts) <= thresh; } long long vars_product(TemplateSpace const& space) { long long prod = 1; for (int v : space.vars) { prod = prod * (long long)(v + 1); } return prod; } void sort_by_product(vector<TemplateSpace>& spaces) { vector<pair<long long, int>> v; for (int i = 0; i < (int)spaces.size(); i++) { v.push_back(make_pair(vars_product(spaces[i]), i)); } sort(v.begin(), v.end()); vector<TemplateSpace> res; for (int i = (int)v.size() - 1; i >= 0; i--) { res.push_back(spaces[v[i].second]); } spaces = move(res); } int compute_thresh(std::vector<TemplateSlice> const& slices) { int m = 0; for (TemplateSlice const& ts : slices) { m = max(total_vars(ts), m); } m = min(m, 6); return m; } bool is_subspace_ignoring_k(TemplateSlice const& slice, TemplateSpace const& space); std::vector<TemplateSpace> finer_spaces_containing_slices_per_quant( std::vector<TemplateSlice> const& slices) { if (slices.size() == 0) { return {}; } int thresh = compute_thresh(slices); vector<TemplateSpace> res; vector<TemplateSlice> small_slices; for (TemplateSlice const& slice : slices) { bool did_merge = false; for (int i = 0; i < (int)res.size(); i++) { if (is_subspace_ignoring_k(slice, res[i])) { if (slice.k > res[i].k) { res[i].k = slice.k; } did_merge = true; break; } } if (!did_merge) { if (is_strictly_small(slice, thresh)) { small_slices.push_back(slice); } else { res.push_back(slice_to_space(slice)); } } } for (TemplateSlice const& slice : small_slices) { if (!is_subspace_of_any(slice, res)) { bool did_merge = false; for (int i = 0; i < (int)res.size(); i++) { if (is_subspace_ignoring_k(slice, res[i])) { if (slice.k > res[i].k) { res[i].k = slice.k; } did_merge = true; break; } } if (!did_merge) { for (int i = 0; i < (int)res.size(); i++) { TemplateSpace merged = merge_slice_space(slice, res[i]); if (is_small(merged, thresh)) { res[i] = merged; did_merge = true; break; } } } if (!did_merge) { res.push_back(slice_to_space(slice)); } } } sort_by_product(res); return res; } std::vector<TemplateSpace> finer_spaces_containing_sub_slices( shared_ptr<Module> module, std::vector<TemplateSubSlice> const& slices) { int nsorts = module->sorts.size(); vector<vector<TemplateSlice>> tslices; tslices.resize(1 << (nsorts+1)); for (TemplateSubSlice const& tss : slices) { int bitmask = 0; for (int j = 0; j < nsorts; j++) { if (tss.ts.quantifiers[j] == Quantifier::Exists) { bitmask |= (1 << j); } } if (tss.ts.depth == 2) { bitmask |= (1 << nsorts); } tslices[bitmask].push_back(tss.ts); } vector<TemplateSpace> res; for (int i = 0; i < (int)tslices.size(); i++) { vector_append(res, finer_spaces_containing_slices_per_quant(tslices[i])); } return res; } TemplateSpace space_containing_slices_ignore_quants( std::shared_ptr<Module> module, std::vector<TemplateSlice> const& slices) { int nsorts = module->sorts.size(); TemplateSpace tspace; tspace.vars.resize(nsorts); tspace.quantifiers.resize(nsorts); for (int j = 0; j < nsorts; j++) { tspace.vars[j] = 0; tspace.quantifiers[j] = Quantifier::Forall; } tspace.depth = -1; tspace.k = -1; for (TemplateSlice const& ts : slices) { for (int j = 0; j < nsorts; j++) { tspace.vars[j] = max( tspace.vars[j], ts.vars[j]); } tspace.depth = max( tspace.depth, ts.depth); tspace.k = max( tspace.k, ts.k); } assert (tspace.depth != -1); return tspace; } bool is_subspace_ignoring_k(TemplateSlice const& slice, TemplateSpace const& space) { if (slice.quantifiers != space.quantifiers) { return false; } if (slice.depth != space.depth) { return false; } assert (slice.vars.size() == space.vars.size()); for (int i = 0; i < (int)slice.vars.size(); i++) { if (slice.vars[i] > space.vars[i]) { return false; } } return true; } bool is_subspace(TemplateSlice const& slice, TemplateSpace const& space) { if (slice.k > space.k) { return false; } return is_subspace_ignoring_k(slice, space); } bool is_subspace(TemplateSubSlice const& tss, TemplateSpace const& ts) { return is_subspace(tss.ts, ts); } <file_sep>/src/synth_enumerator.h #ifndef SYNTH_ENUMERATOR_H #define SYNTH_ENUMERATOR_H #include "model.h" #include "top_quantifier_desc.h" #include "template_counter.h" #include <string> struct Options { bool get_space_size; // If true, generate X such that X & conj is invariant // otherwise, generate X such X is invariant and X ==> conj bool with_conjs; bool breadth_with_conjs; bool filter_redundant; bool whole_space; bool pre_bmc; bool post_bmc; bool minimal_models; bool non_accumulative; //int threads; std::string invariant_log_filename; }; struct Counterexample { // is_true std::shared_ptr<Model> is_true; // not (is_false) std::shared_ptr<Model> is_false; // hypothesis ==> conclusion std::shared_ptr<Model> hypothesis; std::shared_ptr<Model> conclusion; bool none; Counterexample() : none(false) { } json11::Json to_json() const; static Counterexample from_json(json11::Json, std::shared_ptr<Module>); bool is_valid() const { return none || is_true || is_false || (hypothesis && conclusion); } }; class CandidateSolver { public: virtual ~CandidateSolver() {} virtual value getNext() = 0; virtual void addCounterexample(Counterexample cex) = 0; virtual void addExistingInvariant(value inv) = 0; virtual long long getProgress() = 0; virtual long long getPreSymmCount() = 0; virtual long long getSpaceSize() = 0; virtual void setSubSlice(TemplateSubSlice const&) = 0; }; //std::shared_ptr<CandidateSolver> make_sat_candidate_solver( // std::shared_ptr<Module> module, EnumOptions const& options, // bool ensure_nonredundant); //std::shared_ptr<CandidateSolver> make_naive_candidate_solver( // std::shared_ptr<Module> module, EnumOptions const& options); /*inline std::shared_ptr<CandidateSolver> make_candidate_solver( std::shared_ptr<Module> module, EnumOptions const& options, bool ensure_nonredundant) { return make_naive_candidate_solver(module, options); }*/ std::shared_ptr<CandidateSolver> make_candidate_solver( std::shared_ptr<Module> module, std::vector<TemplateSubSlice> const& sub_slices, bool ensure_nonredundant); //std::shared_ptr<CandidateSolver> compose_candidate_solvers( //std::vector<std::shared_ptr<CandidateSolver>> const& solvers); extern int numEnumeratedFilteredRedundantInvariants; #endif <file_sep>/src/enumerator.cpp #include "enumerator.h" #include <set> #include <algorithm> #include <cassert> #include "logic.h" #include "obviously_implies.h" #include "clause_gen.h" using namespace std; struct HoleInfo { vector<VarDecl> decls; }; void getHoleInfo_(value v, vector<VarDecl> decls, vector<HoleInfo>& res) { assert(v.get() != NULL); if (Forall* va = dynamic_cast<Forall*>(v.get())) { for (VarDecl decl : va->decls) { if (dynamic_cast<UninterpretedSort*>(decl.sort.get())) { decls.push_back(VarDecl(decl.name, decl.sort)); } } getHoleInfo_(va->body, decls, res); } else if (Exists* va = dynamic_cast<Exists*>(v.get())) { for (VarDecl decl : va->decls) { if (dynamic_cast<UninterpretedSort*>(decl.sort.get())) { decls.push_back(VarDecl(decl.name, decl.sort)); } } getHoleInfo_(va->body, decls, res); } else if (dynamic_cast<Var*>(v.get())) { return; } else if (dynamic_cast<Const*>(v.get())) { return; } else if (Eq* va = dynamic_cast<Eq*>(v.get())) { getHoleInfo_(va->left, decls, res); getHoleInfo_(va->right, decls, res); } else if (Not* va = dynamic_cast<Not*>(v.get())) { getHoleInfo_(va->val, decls, res); } else if (Implies* va = dynamic_cast<Implies*>(v.get())) { getHoleInfo_(va->left, decls, res); getHoleInfo_(va->right, decls, res); } else if (Apply* va = dynamic_cast<Apply*>(v.get())) { getHoleInfo_(va->func, decls, res); for (value arg : va->args) { getHoleInfo_(arg, decls, res); } } else if (And* va = dynamic_cast<And*>(v.get())) { for (value arg : va->args) { getHoleInfo_(arg, decls, res); } } else if (Or* va = dynamic_cast<Or*>(v.get())) { for (value arg : va->args) { getHoleInfo_(arg, decls, res); } } else if (dynamic_cast<TemplateHole*>(v.get())) { HoleInfo hi; hi.decls = decls; res.push_back(hi); } else { //printf("value2expr got: %s\n", v->to_string().c_str()); assert(false && "value2expr does not support this case"); } } vector<HoleInfo> getHoleInfo(value v) { vector<HoleInfo> res; getHoleInfo_(v, {}, res); return res; } value fill_holes_in_value(value templ, vector<value> const& fills, int& idx) { assert(templ.get() != NULL); if (Forall* va = dynamic_cast<Forall*>(templ.get())) { return v_forall(va->decls, fill_holes_in_value(va->body, fills, idx)); } else if (Exists* va = dynamic_cast<Exists*>(templ.get())) { return v_exists(va->decls, fill_holes_in_value(va->body, fills, idx)); } else if (NearlyForall* va = dynamic_cast<NearlyForall*>(templ.get())) { return v_nearlyforall(va->decls, fill_holes_in_value(va->body, fills, idx)); } else if (dynamic_cast<Var*>(templ.get())) { return templ; } else if (dynamic_cast<Const*>(templ.get())) { return templ; } else if (Eq* va = dynamic_cast<Eq*>(templ.get())) { return v_eq( fill_holes_in_value(va->left, fills, idx), fill_holes_in_value(va->right, fills, idx)); } else if (Not* va = dynamic_cast<Not*>(templ.get())) { return v_not( fill_holes_in_value(va->val, fills, idx)); } else if (Implies* va = dynamic_cast<Implies*>(templ.get())) { return v_implies( fill_holes_in_value(va->left, fills, idx), fill_holes_in_value(va->right, fills, idx)); } else if (Apply* va = dynamic_cast<Apply*>(templ.get())) { value func = fill_holes_in_value(va->func, fills, idx); vector<value> args; for (value arg : va->args) { args.push_back(fill_holes_in_value(arg, fills, idx)); } return v_apply(func, args); } else if (And* va = dynamic_cast<And*>(templ.get())) { vector<value> args; for (value arg : va->args) { args.push_back(fill_holes_in_value(arg, fills, idx)); } return v_and(args); } else if (Or* va = dynamic_cast<Or*>(templ.get())) { vector<value> args; for (value arg : va->args) { args.push_back(fill_holes_in_value(arg, fills, idx)); } return v_or(args); } else if (dynamic_cast<TemplateHole*>(templ.get())) { return fills[idx++]; } else { //printf("value2expr got: %s\n", templ->to_string().c_str()); assert(false && "fill_holes_in_value does not support this case"); } } value fill_holes_in_value(value templ, vector<value> const& fills) { int idx = 0; value res = fill_holes_in_value(templ, fills, idx); assert(idx == (int)fills.size()); return res; } vector<value> fill_holes(value templ, vector<vector<value>> const& fills) { vector<value> result; vector<int> indices; for (int i = 0; i < (int)fills.size(); i++) { if (fills[i].size() == 0) { return {}; } indices.push_back(0); } while (true) { vector<value> values_to_fill; for (int i = 0; i < (int)fills.size(); i++) { assert(0 <= indices[i] && indices[i] < (int)fills[i].size()); values_to_fill.push_back(fills[i][indices[i]]); } int idx = 0; result.push_back(fill_holes_in_value(templ, values_to_fill, idx)); assert(idx == (int)fills.size()); int i; for (i = 0; i < (int)fills.size(); i++) { indices[i]++; if (indices[i] == (int)fills[i].size()) { indices[i] = 0; } else { break; } } if (i == (int)fills.size()) { break; } } return result; } bool are_negations1(value a, value b) { if (Not* n = dynamic_cast<Not*>(a.get())) { return values_equal(n->val, b); } else { return false; } } bool are_negations(value a, value b) { return are_negations1(a,b) || are_negations1(b,a); } void enum_conjuncts_( vector<value> const& pieces, int k, int idx, vector<value> acc, vector<value>& result) { if ((int)acc.size() == k) { result.push_back(v_and(acc)); return; } for (int i = idx + 1; i < (int)pieces.size(); i++) { if (i == idx+1) acc.push_back(pieces[i]); else acc[acc.size() - 1] = pieces[i]; bool skip = false; for (int j = 0; j < (int)acc.size() - 1; j++) { if (are_negations(acc[j], pieces[i])) { skip = true; break; } } if (!skip) { enum_conjuncts_(pieces, k, i, acc, result); } } } vector<value> enum_conjuncts(vector<value> const& pieces, int k) { vector<value> result; for (int i = 1; i <= k; i++) { enum_conjuncts_(pieces, i, -1, {}, result); } return result; } bool is_boring(value v, bool pos) { if (Not* va = dynamic_cast<Not*>(v.get())) { return is_boring(va->val, !pos); } else if (Eq* va = dynamic_cast<Eq*>(v.get())) { // FIXME to_string comparison is sketch return va->left->to_string() == va->right->to_string() || (pos && ( dynamic_cast<Var*>(va->left.get()) != NULL || dynamic_cast<Var*>(va->right.get()) != NULL )); /* } else if (And* va = dynamic_cast<And*>(v.get())) { for (value arg : va->args) { if (is_boring(arg)) return true; } return false; } else if (Or* va = dynamic_cast<Or*>(v.get())) { for (value arg : va->args) { if (is_boring(arg)) return true; } return false; */ } else if (Apply* ap = dynamic_cast<Apply*>(v.get())) { return (iden_to_string(dynamic_cast<Const*>(ap->func.get())->name) == "le" && ap->args[0]->to_string() == ap->args[1]->to_string()); } else { return false; } } vector<value> filter_boring(vector<value> const& values) { vector<value> results; for (value v : values) { if (!is_boring(v, true)) { results.push_back(v); } } return results; } struct NormalizeState { vector<iden> names; iden get_name(iden name) { int idx = -1; for (int i = 0; i < (int)names.size(); i++) { if (names[i] == name) { idx = i; break; } } assert (idx != -1); return idx; } }; value normalize(value v, NormalizeState& ns) { assert(v.get() != NULL); if (Forall* va = dynamic_cast<Forall*>(v.get())) { return v_forall(va->decls, normalize(va->body, ns)); } else if (Exists* va = dynamic_cast<Exists*>(v.get())) { return v_exists(va->decls, normalize(va->body, ns)); } else if (Var* va = dynamic_cast<Var*>(v.get())) { return v_var(ns.get_name(va->name), va->sort); } else if (dynamic_cast<Const*>(v.get())) { return v; } else if (Eq* va = dynamic_cast<Eq*>(v.get())) { return v_eq( normalize(va->left, ns), normalize(va->right, ns)); } else if (Not* va = dynamic_cast<Not*>(v.get())) { return v_not( normalize(va->val, ns)); } else if (Implies* va = dynamic_cast<Implies*>(v.get())) { return v_implies( normalize(va->left, ns), normalize(va->right, ns)); } else if (Apply* va = dynamic_cast<Apply*>(v.get())) { value func = normalize(va->func, ns); vector<value> args; for (value arg : va->args) { args.push_back(normalize(arg, ns)); } return v_apply(func, args); } else if (And* va = dynamic_cast<And*>(v.get())) { vector<value> args; for (value arg : va->args) { args.push_back(normalize(arg, ns)); } return v_and(args); } else if (Or* va = dynamic_cast<Or*>(v.get())) { vector<value> args; for (value arg : va->args) { args.push_back(normalize(arg, ns)); } return v_or(args); } else { //printf("value2expr got: %s\n", templ->to_string().c_str()); assert(false && "value2expr does not support this case"); } } /*vector<value> remove_equiv(value templ, vector<value> const& values) { NormalizeState ns_base; vector<value> result; set<string> seen; for (value v : values) { NormalizeState ns = ns_base; value norm = normalize(v, ns); string s = norm->to_string(); cout << v->to_string() << endl; cout << s << endl; cout << endl; if (seen.find(s) == seen.end()) { seen.insert(s); result.push_back(v); } } return result; }*/ // This one is more thorough (cuts by about 3x) but also slower, // so we still do the first one to save time. vector<value> remove_equiv2(vector<value> const& values) { vector<value> result; set<ComparableValue> seen; int i = 0; for (value v : values) { i++; //if (i % 1000 == 0) printf("i = %d\n", i); value norm = v->totally_normalize(); //string s = norm->to_string(); //cout << v->to_string() << endl; //cout << s << endl; //cout << endl; ComparableValue cv(norm); if (seen.find(cv) == seen.end()) { seen.insert(cv); result.push_back(v); } } return result; } void sort_values(vector<value>& values) { std::sort(values.begin(), values.end(), [](value a, value b) { return lt_value(a, b); }); } vector<value> enumerate_for_template( shared_ptr<Module> module, value templ, int k) { vector<HoleInfo> all_hole_info = getHoleInfo(templ); vector<vector<value>> all_hole_fills; for (HoleInfo hi : all_hole_info) { vector<value> fills = gen_clauses(module, hi.decls); /*cout << "fills" << endl; cout << "===========================================" << endl; for (value v : fills) { cout << v->to_string() << endl; } cout << "===========================================" << endl; cout << "new fills" << endl; for (value v : fills1) { cout << v->to_string() << endl; } cout << "===========================================" << endl; assert(false);*/ //cout << "fills len " << fills.size() << endl; vector<value> f1 = filter_boring(fills); vector<value> f2 = enum_conjuncts(f1, k); vector<value> f3 = f2; //remove_equiv(templ, f2); //cout << "f1 len " << f1.size() << endl; //cout << "f2 len " << f2.size() << endl; //cout << "f3 len " << f3.size() << endl; for (int i = 0; i < (int)f3.size(); i++) { f3[i] = v_not(f3[i]); } all_hole_fills.push_back(move(f3)); } assert (all_hole_fills.size() > 0); vector<value> res = fill_holes(templ, all_hole_fills); //vector<value> final = remove_equiv2(res); //cout << "res len " << res.size() << endl; //return make_pair(final, res); return res; } vector<value> get_clauses_for_template( std::shared_ptr<Module> module, value templ) { return enumerate_for_template(module, templ, 1); } <file_sep>/scripts/resulting_inv_analysis.py import protocol_parsing import os import json import subprocess import sys import tempfile import paper_benchmarks import traceback def get_protocol_filename(logdir): summary_file = os.path.join(logdir, "summary") with open(summary_file, "r") as f: for line in f: if line.startswith("Protocol: "): return line[10:].strip() if line.startswith("./save.sh "): return line.split()[1] assert False, "could not find protocol filename" def does_claim_success(i): if "# Success: True" in i: return True elif "# Success: False" in i: return False elif "# timed out and extracted" in i: return False elif "# Extracted from logfiles" in i: # legacy return False else: assert False def did_succeed(logdir): with open(os.path.join(logdir, "invariants")) as f: inv_contents = f.read() return does_claim_success(inv_contents) def validate_run_invariants(logdir): with open(os.path.join(logdir, "invariants")) as f: inv_contents = f.read() claims_success = does_claim_success(inv_contents) if not claims_success: print("invariants file does not claim invariants are correct") else: print("invariants file claims to contain correct and complete invariants") protocol_filename = get_protocol_filename(logdir) print("protocol file: " + protocol_filename) j, invs = protocol_parsing.parse_invs(protocol_filename, inv_contents) j["conjectures"] = j["conjectures"] + invs tmpjson = tempfile.mktemp() with open(tmpjson, "w") as f: f.write(json.dumps(j)) proc = subprocess.Popen(["./synthesis", "--input-module", tmpjson, "--check-inductiveness"]) ret = proc.wait() def count_terms_of_value_list(invs): def count_terms(v): if v[0] in ('forall', 'exists'): return count_terms(v[2]) elif v[0] in ('and', 'or'): return sum(count_terms(t) for t in v[1]) elif v[0] == 'not': return count_terms(v[1]) elif v[0] == 'implies': return count_terms(v[1]) + count_terms(v[2]) elif v[0] == 'apply': return 1 elif v[0] == 'const': return 1 elif v[0] == 'eq': return 1 else: print(v) assert False def get_quants(v): if v[0] in ('forall', 'exists'): sorts = [ decl[2][1] for decl in v[1] ] new_qs = [(v[0], s) for s in sorts] return new_qs + get_quants(v[2]) elif v[0] in ('and', 'or'): qs = [] for t in v[1]: q = get_quants(t) if len(q) == 0: assert len(qs) == 0 qs = q return qs elif v[0] == 'not': return get_quants(v[1]) elif v[0] == 'implies': qs = [] for t in [v[1], v[2]]: q = get_quants(t) if len(q) == 0: assert len(qs) == 0 qs = q return qs elif v[0] == 'apply': return [] elif v[0] == 'const': return [] elif v[0] == 'eq': return [] else: print(v) assert False def num_exists(v): return len([x for x in v if x[0] == 'exists']) def num_alts(v): alt = 0 for i in range(1, len(v)): if v[i][0] != v[i-1][0]: alt += 1 return alt count = sum(count_terms(i) for i in invs) #print("total terms: " + str(count)) max_terms = max(count_terms(i) for i in invs) quants = [get_quants(i) for i in invs] max_vars = max(len(q) for q in quants) max_exists = max(num_exists(q) for q in quants) max_alts = max(num_alts(q) for q in quants) return { "invs": len(invs), "terms": count, "max_terms": max_terms, "max_vars": max_vars, "max_exists": max_exists, "max_alts": max_alts, "k_terms_by_inv": [count_terms(i) for i in invs] } def do_single_impl_check(module_json_file, lhs_invs, rhs_invs): proc = subprocess.Popen(["./synthesis", "--input-module", module_json_file, "--big-impl-check", lhs_invs, rhs_invs], stderr=subprocess.PIPE) out, err = proc.communicate() ret = proc.wait() assert ret == 0 for line in err.split(b'\n'): if line.startswith(b"could prove "): l = line.split() a = int(l[2]) assert l[3] == b"/" b = int(l[4]) return (a, b) assert False, "did not find output line" def impl_check(ivyname, b, module_json_file, module_invs, gen_invs, answer_invs): def write_invs_file(c): t = tempfile.mktemp() with open(t, "w") as f: f.write(json.dumps(c)) return t module_invs_file = write_invs_file(module_invs) gen_invs_file = write_invs_file(gen_invs) answer_invs_file = write_invs_file(answer_invs) conj_got, conj_total = do_single_impl_check(module_json_file, gen_invs_file, module_invs_file) invs_got, invs_total = do_single_impl_check(module_json_file, gen_invs_file, answer_invs_file) return { "safeties_got" : conj_got, "safeties_total" : conj_total, "invs_got" : invs_got, "invs_total" : invs_total, } def do_analysis(ivyname, b): if not os.path.exists(b): print("could not find", b, " ... skipping") return try: print(b) answers_filename = ".".join(ivyname.split(".")[:-1] + ["answers"]) if not os.path.exists(answers_filename): print("file does not exist: " + answers_filename) answers_filename = None module_json_file, j, gen_invs, answer_invs = ( protocol_parsing.parse_module_and_invs_invs_myparser( ivyname, os.path.join(b, "invariants"), answers_filename ) ) module_invs = j["conjectures"] def copy_dict(a, b, prefix): for key in b: a[prefix+key] = b[key] d_syn = count_terms_of_value_list(gen_invs) d = {} copy_dict(d, d_syn, "synthesized_") if answer_invs != None: d_hand = count_terms_of_value_list(answer_invs) copy_dict(d, d_hand, "handwritten_") was_success = did_succeed(b) if (not was_success) and answer_invs != None: d1 = impl_check(ivyname, b, module_json_file, module_invs, gen_invs, answer_invs) d = {**d, **d1} res_filename = os.path.join(b, "inv_analysis") print(d) with open(res_filename, "w") as f: f.write(json.dumps(d)) except Exception: traceback.print_exc() def run_analyses(input_directory): all_main_benches = paper_benchmarks.get_all_main_benchmarks() for b in all_main_benches: name = b.get_name() do_analysis("benchmarks/" + b.ivyname, os.path.join(input_directory, name)) if __name__ == '__main__': #validate_run_invariants(sys.argv[1]) #count_terms_of_tmpfile(sys.argv[1]) run_analyses(sys.argv[1]) <file_sep>/run.sh #!/bin/bash set -e python3 scripts/driver.py "$@" <file_sep>/src/auto_redundancy_filters.cpp #include "auto_redundancy_filters.h" #include <cassert> #include <iostream> #include "top_quantifier_desc.h" using namespace std; bool has_subclause(value v, value sub) { assert(v.get() != NULL); if (values_equal(v, sub)) { return true; } if (Forall* value = dynamic_cast<Forall*>(v.get())) { return has_subclause(value->body, sub); } else if (Exists* value = dynamic_cast<Exists*>(v.get())) { return has_subclause(value->body, sub); } else if (NearlyForall* value = dynamic_cast<NearlyForall*>(v.get())) { return has_subclause(value->body, sub); } else if (dynamic_cast<Var*>(v.get())) { return false; } else if (dynamic_cast<Const*>(v.get())) { return false; } else if (Eq* value = dynamic_cast<Eq*>(v.get())) { return has_subclause(value->left, sub) || has_subclause(value->right, sub); } else if (Not* value = dynamic_cast<Not*>(v.get())) { return has_subclause(value->val, sub); } else if (Implies* value = dynamic_cast<Implies*>(v.get())) { return has_subclause(value->left, sub) || has_subclause(value->right, sub); } else if (Apply* value = dynamic_cast<Apply*>(v.get())) { if (has_subclause(value->func, sub)) { return true; } for (shared_ptr<Value> arg : value->args) { if (has_subclause(arg, sub)) { return true; } } return false; } else if (And* value = dynamic_cast<And*>(v.get())) { for (shared_ptr<Value> arg : value->args) { if (has_subclause(arg, sub)) { return true; } } return false; } else if (Or* value = dynamic_cast<Or*>(v.get())) { for (shared_ptr<Value> arg : value->args) { if (has_subclause(arg, sub)) { return true; } } return false; } else if (IfThenElse* value = dynamic_cast<IfThenElse*>(v.get())) { return has_subclause(value->cond, sub) || has_subclause(value->then_value, sub) || has_subclause(value->else_value, sub); } else { //printf("has_subclause got: %s\n", v->to_string().c_str()); assert(false && "has_subclause does not support this case"); } } value get_later_not_var(value a, value b) { assert (!dynamic_cast<Var*>(a.get())); assert (!dynamic_cast<Var*>(b.get())); return lt_value(a, b) ? b : a; } vector<int> sort2(int a, int b) { assert (a != b); if (a < b) { return {a,b}; } else { return {b,a}; } } std::vector<std::vector<int>> get_auto_redundancy_filters( std::vector<value> const& _pieces) { vector<value> pieces; for (value v : _pieces) { pieces.push_back(get_taqd_and_body(v).second); } vector<vector<int>> res; for (int i = 0; i < (int)pieces.size(); i++) { if (Not* n = dynamic_cast<Not*>(pieces[i].get())) { for (int j = 0; j < (int)pieces.size(); j++) { if (values_equal(n->val, pieces[j])) { res.push_back(sort2(i,j)); } } if (Eq* e = dynamic_cast<Eq*>(n->val.get())) { // Note: these aren't tautological, but they are redundant, // since one expression can always be replaced with the other. value dis_allowed = get_later_not_var(e->left, e->right); for (int j = 0; j < (int)pieces.size(); j++) { if (i != j) { if (has_subclause(pieces[j], dis_allowed)) { res.push_back(sort2(i,j)); } } } } } } /*cout << "get_auto_redundancy_filters" << endl; for (vector<int> vs : res) { for (int i : vs) { cout << pieces[i]->to_string() << " "; } cout << endl; } assert(false);*/ return res; } <file_sep>/src/template_desc.h #ifndef TEMPLATE_DESC_H #define TEMPLATE_DESC_H #include <vector> #include "logic.h" #include "top_quantifier_desc.h" enum class Quantifier { Forall, Exists }; struct TemplateSpace { std::vector<int> vars; // up to std::vector<Quantifier> quantifiers; int depth; int k; // up to value make_templ(std::shared_ptr<Module> module) const; }; struct TemplateSlice { std::vector<int> vars; // exact std::vector<Quantifier> quantifiers; int k; // exact int depth; long long count; inline bool operator<(TemplateSlice const& other) const { return count < other.count; } std::string to_string(std::shared_ptr<Module> module) const; }; struct TemplateSubSlice { TemplateSlice ts; int tree_idx; // depth 2 only std::vector<int> prefix; TemplateSubSlice() : tree_idx(-1) { } }; std::ostream& operator<<(std::ostream& os, const TemplateSpace& ts); //std::istream& operator>>(std::istream& is, TemplateSlice& tss); std::ostream& operator<<(std::ostream& os, const TemplateSlice& tss); std::istream& operator>>(std::istream& is, TemplateSlice& tss); std::ostream& operator<<(std::ostream& os, const TemplateSubSlice& tss); std::istream& operator>>(std::istream& is, TemplateSubSlice& tss); std::vector<int> get_subslice_index_map( TopAlternatingQuantifierDesc const& taqd, std::vector<value> const& clauses, TemplateSlice const& ts); std::vector<TemplateSpace> spaces_containing_sub_slices( std::shared_ptr<Module> module, std::vector<TemplateSubSlice> const& slices); std::vector<TemplateSpace> finer_spaces_containing_sub_slices( std::shared_ptr<Module> module, std::vector<TemplateSubSlice> const& slices); TemplateSpace space_containing_slices_ignore_quants( std::shared_ptr<Module> module, std::vector<TemplateSlice> const& slices); bool is_subspace(TemplateSlice const& slice, TemplateSpace const& ts); bool is_subspace(TemplateSubSlice const& tss, TemplateSpace const& ts); int total_vars(TemplateSlice const& ts); #endif <file_sep>/scripts/get_counts.py import subprocess import templates # paperlogs/2020august/mm__leader-election__auto__seed1_t24 class CountSet(object): def __init__(self, presymm, postsymm): self.presymm = presymm self.postsymm = postsymm def get_finisher_params_from_file(filename): protocol_file = get_protocol_from_file(filename) suite = templates.read_suite(protocol_file) config_name = get_config_from_file(filename) bench = suite.get(config_name) space = bench.finisher_space return space.get_args('--finisher') def get_protocol_from_file(filename): with open(filename) as f: for line in f: if line.startswith('Protocol:'): return line.split()[1] assert False def get_config_from_file(filename): with open(filename) as f: for line in f: if line.startswith('Args:'): params = line.split() i = params.index('--config') return params[i+1] assert False def get_breadth_params_from_file(protocol_file, filename): protocol_file = get_protocol_from_file(filename) suite = templates.read_suite(protocol_file) config_name = get_config_from_file(filename) bench = suite.get(config_name) space = bench.breadth_space return space.get_args('--breadth') def calc_counts(protocol_file, params): cmd = ["./run-simple.sh", protocol_file] + ["--counts-only"] + params #print(' '.join(cmd)) proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE) out, err = proc.communicate() ret = proc.wait() assert ret == 0 presymm = None postsymm = None for line in out.split(b'\n'): if line.startswith(b"Pre-symmetries:"): presymm = int(line.split()[1]) if line.startswith(b"Post-symmetries:"): postsymm = int(line.split()[1]) assert presymm != None assert postsymm != None #print(presymm, postsymm) return presymm, postsymm def get_counts(filename, alg): protocol_file = get_protocol_from_file(filename) if alg == 'breadth': params = get_breadth_params_from_file(protocol_file, filename) elif alg == 'finisher': params = get_finisher_params_from_file(filename) else: assert False presymm, postsymm = calc_counts(protocol_file, params) return CountSet(presymm, postsymm) def sorted_counts(protocol_file, params): cmd = ["./run-simple.sh", protocol_file] + params + ["--counts-only"] print(' '.join(cmd)) proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE) out, err = proc.communicate() ret = proc.wait() assert ret == 0 res = [] for l in out.split(b'\n'): l = l.strip() if l.startswith(b"TemplateSlice["): res.append(l.decode('utf-8')) return sort_spaces(res) def count_of_space_str(s): t = s.split() assert t[5] == 'count' return int(t[6]) def sort_spaces(spaces): t = [(count_of_space_str(space), space) for space in spaces] t.sort() return [x[1] for x in t] def print_sorted_spaces(protocol_file, params): s = sorted_counts(protocol_file, params) for l in s: print(l) if __name__ == '__main__': print_sorted_spaces("benchmarks/decentralized-lock.ivy", '--template-sorter 9 2 6 0'.split()) #get_counts("paperlogs/2020august/mm__flexible_paxos__auto__seed1_t24", "finisher") <file_sep>/scripts/validate_answers_files.py import os import protocol_parsing import tempfile import json import subprocess import sys def main(): if len(sys.argv) > 1: fname_one = sys.argv[1] else: fname_one = None for rl in sorted(list(os.listdir("benchmarks"))): if rl.endswith(".answers") and (fname_one == None or fname_one + ".answers" == rl): l = os.path.join('benchmarks', rl) pyv_name = l.replace(".answers", ".pyv") ivy_name = l.replace(".answers", ".ivy") if os.path.exists(ivy_name): name = ivy_name else: name = pyv_name print(name) mjf, j, answers = protocol_parsing.parse_module_and_invs_myparser(name, l) tfile = tempfile.mktemp() with open(tfile, "w") as f: f.write(json.dumps(answers)) proc = subprocess.Popen(["./synthesis", "--check-inductiveness-linear", tfile, "--input-module", mjf]) ret = proc.wait() assert ret == 0 if __name__ == '__main__': main() <file_sep>/src/clause_gen.h #ifndef CLAUSE_GEN_H #define CLAUSE_GEN_H #include "logic.h" std::vector<value> gen_clauses( std::shared_ptr<Module>, std::vector<VarDecl> const& decls); #endif <file_sep>/scripts/file_to_json.py import sys import json import os sys.path.insert(0, os.path.abspath(os.path.join( os.path.dirname(__file__), '../ivy'))) from ivy.ivy_init import ivy_init from ivy.ivy_compiler import ivy_load_file from ivy.ivy_logic import AST from ivy import ivy_module as im from ivy import ivy_module from ivy import logic from ivy import ivy_actions from ivy import ivy_logic_utils def get_json(): with ivy_module.Module(): with open(sys.argv[1]) as f: ivy_load_file(f) functions = [] for func in im.module.functions: functions.append(logic_to_obj(func)) # XXX hack #if sys.argv[1] == "examples/leader-election.ivy": # functions.append(["const", "<=", ["functionSort", [ # ["uninterpretedSort", "id"], # ["uninterpretedSort", "id"]], # ["booleanSort"]]]) axioms = [] for axiom in im.module.get_axioms(): #print axiom #print logic_to_obj(ivy_logic_utils.close_epr(axiom)) axioms.append(logic_to_obj(ivy_logic_utils.close_epr(axiom))) conjectures = [] for conj in im.module.conjs: for fmla in conj.fmlas: #print fmla #print logic_to_obj(ivy_logic_utils.close_epr(fmla)) conjectures.append(logic_to_obj(ivy_logic_utils.close_epr(fmla))) #conjectures.append(logic_to_obj(conj.formula)) templates = [] for template in im.module.labeled_templates: #print template #print template.formula templates.append(logic_to_obj(template.formula)) #template = ivy_logic_utils.formula_to_clauses(template) #or fmla in template.fmlas: # templates.append(logic_to_obj(fmla)) inits = [] for fmla in im.module.init_cond.fmlas: inits.append(logic_to_obj(ivy_logic_utils.close_epr(fmla))) actions = {} for name in im.module.actions: action = im.module.actions[name] actions[name] = action_to_obj(action) return json.dumps({ "sorts": im.module.sort_order, "functions": functions, "inits": inits, "axioms": axioms, "conjectures": conjectures, #[c for c in conjectures if not has_wildcard(c)], "templates": templates, #[c for c in conjectures if has_wildcard(c)], "actions": actions, }) def has_wildcard(o): if type(o) == dict: for k in o: if has_wildcard(o[k]): return True return False elif type(o) == list: if len(o) == 1: return o[0] == '__wild' else: for k in xrange(0, len(o)): if has_wildcard(o[k]): return True return False else: return False def action_to_obj(l): if isinstance(l, ivy_actions.LocalAction): return [ "localAction", [logic_to_obj(arg) for arg in l.args[0:-1]], action_to_obj(l.args[-1]), ] elif isinstance(l, ivy_actions.Sequence): return [ "sequence", [action_to_obj(arg) for arg in l.args], ] elif isinstance(l, ivy_actions.AssumeAction): return [ "assume", logic_to_obj(ivy_logic_utils.close_epr(l.args[0])), ] elif isinstance(l, ivy_actions.AssumeAction): return [ "assert", logic_to_obj(ivy_logic_utils.close_epr(l.args[0])), ] elif isinstance(l, ivy_actions.AssignAction): return [ "assign", logic_to_obj(l.args[0]), logic_to_obj(l.args[1]), ] elif isinstance(l, ivy_actions.HavocAction): return [ "havoc", logic_to_obj(l.args[0]), ] elif isinstance(l, ivy_actions.IfAction): if len(l.args) >= 3: return [ "ifelse", logic_to_obj(l.args[0]), action_to_obj(l.args[1]), action_to_obj(l.args[2]), ] else: return [ "if", logic_to_obj(l.args[0]), action_to_obj(l.args[1]), ] else: print 'action_to_obj failed', type(l) assert False def maybe_merge_nearlys(obj): if obj[0] == "nearlyforall" and obj[2][0] == "nearlyforall": vs1 = obj[1] vs2 = obj[2][1] name1 = vs1[0][1] name2 = vs2[0][1] parts1 = name1.split('_') parts2 = name2.split('_') assert len(parts1) >= 3 assert len(parts2) >= 3 assert parts1[0] == 'Nearly' assert parts2[0] == 'Nearly' if parts1[1] == parts2[1]: return ["nearlyforall", vs1 + vs2, obj[2][2]] else: return obj else: return obj def sort_vars_alphabetically(vs): # ["var", "Q", ["uninterpretedSort", "quorum"]] return sorted(vs, key = lambda v : (v[2][1], v[1])) def logic_to_obj(l): if isinstance(l, logic.ForAll): vs = [v for v in l.variables if v.name != "WILD"] if len(vs) > 0: the_vars = [logic_to_obj(var) for var in vs] is_nearly = the_vars[0][1].startswith("Nearly_") name = "nearlyforall" if is_nearly else "forall" the_vars = sort_vars_alphabetically(the_vars) return maybe_merge_nearlys([name, the_vars, logic_to_obj(l.body)]) else: return logic_to_obj(l.body) if isinstance(l, logic.Exists): vars = [logic_to_obj(var) for var in l.variables] if len(vars) > 0 and vars[0][1] != 'FakeOutHackExists': the_vars = [logic_to_obj(var) for var in l.variables] the_vars = sort_vars_alphabetically(the_vars) return ["exists", the_vars, logic_to_obj(l.body)] else: return logic_to_obj(l.body) elif isinstance(l, logic.Var): if l.name == "WILD": return ["__wild"] else: return ["var", l.name, sort_to_obj(l.sort)] elif isinstance(l, logic.Const): return ["const", l.name, sort_to_obj(l.sort)] elif isinstance(l, logic.Implies): return ["implies", logic_to_obj(l.t1), logic_to_obj(l.t2)] elif isinstance(l, logic.Iff): return ["eq", logic_to_obj(l.t1), logic_to_obj(l.t2)] elif isinstance(l, logic.Eq): return ["eq", logic_to_obj(l.t1), logic_to_obj(l.t2)] elif isinstance(l, logic.Not): return ["not", logic_to_obj(l.body)] elif isinstance(l, logic.Apply): return ["apply", logic_to_obj(l.func), [logic_to_obj(term) for term in l.terms]] elif isinstance(l, logic.And): return ["and", [logic_to_obj(o) for o in l]] elif isinstance(l, logic.Or): return ["or", [logic_to_obj(o) for o in l]] else: print l print 'logic_to_obj cant do', type(l) assert False def sort_to_obj(s): if isinstance(s, logic.BooleanSort): return ["booleanSort"] elif isinstance(s, logic.UninterpretedSort): return ["uninterpretedSort", s.name] elif isinstance(s, logic.FunctionSort): return ["functionSort", [sort_to_obj(t) for t in s.domain], sort_to_obj(s.range)] else: print 'sort_to_obj cant do', type(s) assert False def fmla_to_obj(fmla): assert isinstance(fmla, AST) return [type(fmla).__name__] + [fmla_to_obj(arg) for arg in fmla.args] def main(): print get_json() if __name__ == "__main__": main() <file_sep>/scripts/file_mypyvy_to_json.py import z3 # pip3 install z3-solver import sys import json import os import argparse from typing import cast sys.path.insert(0, os.path.abspath(os.path.join( os.path.dirname(__file__), '../mypyvy/src'))) import mypyvy import utils import parser #import typechecker import syntax """ def parse_program(input: str, force_rebuild: bool = False, filename: Optional[str] = None) -> Program: l = parser.get_lexer() p = parser.get_parser(forbid_rebuild=force_rebuild) return p.parse(input=input, lexer=l, filename=filename) def parse_args(args: List[str]) -> utils.MypyvyArgs: argparser = argparse.ArgumentParser() subparsers = argparser.add_subparsers(title='subcommands', dest='subcommand') all_subparsers = [] verify_subparser = subparsers.add_parser('verify', help='verify that the invariants are inductive') verify_subparser.set_defaults(main=verify) all_subparsers.append(verify_subparser) updr_subparser = subparsers.add_parser('updr', help='search for a strengthening that proves the invariant named by the --safety=NAME flag') updr_subparser.set_defaults(main=do_updr) all_subparsers.append(updr_subparser) bmc_subparser = subparsers.add_parser('bmc', help='bounded model check to depth given by the --depth=DEPTH flag for property given by the --safety=NAME flag') bmc_subparser.set_defaults(main=bmc) all_subparsers.append(bmc_subparser) theorem_subparser = subparsers.add_parser('theorem', help='check state-independent theorems about the background axioms of a model') theorem_subparser.set_defaults(main=theorem) all_subparsers.append(theorem_subparser) trace_subparser = subparsers.add_parser('trace', help='search for concrete executions that satisfy query described by the file\'s trace declaration') trace_subparser.set_defaults(main=trace) all_subparsers.append(trace_subparser) generate_parser_subparser = subparsers.add_parser('generate-parser', help='internal command used by benchmarking infrastructure to avoid certain race conditions') generate_parser_subparser.set_defaults(main=nop) # parser is generated implicitly by main when it parses the program all_subparsers.append(generate_parser_subparser) typecheck_subparser = subparsers.add_parser('typecheck', help='typecheck the file, report any errors, and exit') typecheck_subparser.set_defaults(main=nop) # program is always typechecked; no further action required all_subparsers.append(typecheck_subparser) relax_subparser = subparsers.add_parser('relax', help='produce a version of the file that is "relaxed", in a way that is indistinguishable for universal invariants') relax_subparser.set_defaults(main=relax) all_subparsers.append(relax_subparser) all_subparsers += pd.add_argparsers(subparsers) all_subparsers += pd_fol.add_argparsers(subparsers) for s in all_subparsers: s.add_argument('--forbid-parser-rebuild', action=utils.YesNoAction, default=False, help='force loading parser from disk (helps when running mypyvy from multiple processes)') s.add_argument('--log', default='warning', choices=['error', 'warning', 'info', 'debug'], help='logging level') s.add_argument('--log-time', action=utils.YesNoAction, default=False, help='make each log message include current time') s.add_argument('--log-xml', action=utils.YesNoAction, default=False, help='log in XML format') s.add_argument('--seed', type=int, default=0, help="value for z3's smt.random_seed") s.add_argument('--print-program-repr', action=utils.YesNoAction, default=False, help='print a machine-readable representation of the program after parsing') s.add_argument('--print-program', action=utils.YesNoAction, default=False, help='print the program after parsing') s.add_argument('--key-prefix', help='additional string to use in front of names sent to z3') s.add_argument('--minimize-models', action=utils.YesNoAction, default=True, help='search for models with minimal cardinality') s.add_argument('--timeout', type=int, default=None, help='z3 timeout (milliseconds)') s.add_argument('--exit-on-error', action=utils.YesNoAction, default=False, help='exit after reporting first error') s.add_argument('--ipython', action=utils.YesNoAction, default=False, help='run IPython with s and prog at the end') s.add_argument('--error-filename-basename', action=utils.YesNoAction, default=False, help='print only the basename of the input file in error messages') s.add_argument('--query-time', action=utils.YesNoAction, default=True, help='report how long various z3 queries take') s.add_argument('--print-counterexample', action=utils.YesNoAction, default=True, help='print counterexamples') s.add_argument('--print-cmdline', action=utils.YesNoAction, default=True, help='print the command line passed to mypyvy') s.add_argument('--clear-cache', action=utils.YesNoAction, default=False, help='do not load from cache, but dump to cache as usual (effectively clearing the cache before starting)') s.add_argument('--clear-cache-memo', action=utils.YesNoAction, default=False, help='load only discovered states from the cache, but dump to cache as usual (effectively clearing the memoization cache before starting, while keeping discovered states and transitions)') s.add_argument('--cache-only', action=utils.YesNoAction, default=False, help='assert that the caches already contain all the answers') s.add_argument('--cache-only-discovered', action=utils.YesNoAction, default=False, help='assert that the discovered states already contain all the answers') s.add_argument('--print-exit-code', action=utils.YesNoAction, default=False, help='print the exit code before exiting (good for regression testing)') s.add_argument('--cvc4', action='store_true', help='use CVC4 as the backend solver. this is not very well supported.') # for diagrams: s.add_argument('--simplify-diagram', action=utils.YesNoAction, default=(s is updr_subparser), default_description='yes for updr, else no', help='in diagram generation, substitute existentially quantified variables that are equal to constants') s.add_argument('--diagrams-subclause-complete', action=utils.YesNoAction, default=False, help='in diagram generation, "complete" the diagram so that every stronger ' 'clause is a subclause') updr_subparser.add_argument('--use-z3-unsat-cores', action=utils.YesNoAction, default=True, help='generalize diagrams using brute force instead of unsat cores') updr_subparser.add_argument('--smoke-test', action=utils.YesNoAction, default=False, help='(for debugging mypyvy itself) run bmc to confirm every conjunct added to a frame') updr_subparser.add_argument('--assert-inductive-trace', action=utils.YesNoAction, default=False, help='(for debugging mypyvy itself) check that frames are always inductive') updr_subparser.add_argument('--sketch', action=utils.YesNoAction, default=False, help='use sketched invariants as additional safety (currently only in automaton)') updr_subparser.add_argument('--automaton', action=utils.YesNoAction, default=False, help='whether to run vanilla UPDR or phase UPDR') updr_subparser.add_argument('--block-may-cexs', action=utils.YesNoAction, default=False, help="treat failures to push as additional proof obligations") updr_subparser.add_argument('--push-frame-zero', default='if_trivial', choices=['if_trivial', 'always', 'never'], help="push lemmas from the initial frame: always/never/if_trivial, the latter is when there is more than one phase") verify_subparser.add_argument('--automaton', default='yes', choices=['yes', 'no', 'only'], help="whether to use phase automata during verification. by default ('yes'), both non-automaton " "and automaton proofs are checked. 'no' means ignore automaton proofs. " "'only' means ignore non-automaton proofs.") verify_subparser.add_argument('--check-transition', default=None, nargs='+', help="when verifying inductiveness, check only these transitions") verify_subparser.add_argument('--check-invariant', default=None, nargs='+', help="when verifying inductiveness, check only these invariants") verify_subparser.add_argument('--json', action='store_true', help="output machine-parseable verification results in JSON format") verify_subparser.add_argument('--smoke-test-solver', action=utils.YesNoAction, default=False, help='(for debugging mypyvy itself) double check countermodels by evaluation') updr_subparser.add_argument('--checkpoint-in', help='start from internal state as stored in given file') updr_subparser.add_argument('--checkpoint-out', help='store internal state to given file') # TODO: say when bmc_subparser.add_argument('--safety', help='property to check') bmc_subparser.add_argument('--depth', type=int, default=3, metavar='N', help='number of steps to check') argparser.add_argument('filename') return cast(utils.MypyvyArgs, argparser.parse_args(args)) """ """ def parse_program(input, filename = None): l = parser.get_lexer() p = parser.get_parser(forbid_rebuild=False) prog = p.parse(input=input, lexer=l, filename=filename) prog.input = input return prog # copied from mypyvy/src/mypyvy.py def parse_args(args): argparser = argparse.ArgumentParser() subparsers = argparser.add_subparsers(title='subcommands', dest='subcommand') all_subparsers = [] verify_subparser = subparsers.add_parser('verify', help='verify that the invariants are inductive') #verify_subparser.set_defaults(main=verify) all_subparsers.append(verify_subparser) updr_subparser = subparsers.add_parser( 'updr', help='search for a strengthening that proves the invariant named by the --safety=NAME flag') #updr_subparser.set_defaults(main=do_updr) all_subparsers.append(updr_subparser) bmc_subparser = subparsers.add_parser( 'bmc', help='bounded model check to depth given by the --depth=DEPTH flag ' 'for property given by the --safety=NAME flag') #bmc_subparser.set_defaults(main=bmc) all_subparsers.append(bmc_subparser) theorem_subparser = subparsers.add_parser( 'theorem', help='check state-independent theorems about the background axioms of a model') #theorem_subparser.set_defaults(main=theorem) all_subparsers.append(theorem_subparser) trace_subparser = subparsers.add_parser( 'trace', help='search for concrete executions that satisfy query described by the file\'s trace declaration') #trace_subparser.set_defaults(main=trace) all_subparsers.append(trace_subparser) generate_parser_subparser = subparsers.add_parser( 'generate-parser', help='internal command used by benchmarking infrastructure to avoid certain race conditions') # parser is generated implicitly by main when it parses the program, so we can just nop here #generate_parser_subparser.set_defaults(main=nop) all_subparsers.append(generate_parser_subparser) typecheck_subparser = subparsers.add_parser('typecheck', help='typecheck the file, report any errors, and exit') #typecheck_subparser.set_defaults(main=nop) # program is always typechecked; no further action required all_subparsers.append(typecheck_subparser) relax_subparser = subparsers.add_parser( 'relax', help='produce a version of the file that is "relaxed", ' 'in a way that is indistinguishable for universal invariants') #relax_subparser.set_defaults(main=relax) all_subparsers.append(relax_subparser) check_one_bounded_width_invariant_parser = subparsers.add_parser( 'check-one-bounded-width-invariant', help='popl' ) #check_one_bounded_width_invariant_parser.set_defaults(main=check_one_bounded_width_invariant) all_subparsers.append(check_one_bounded_width_invariant_parser) #all_subparsers += pd.add_argparsers(subparsers) #all_subparsers += rethink.add_argparsers(subparsers) #all_subparsers += sep.add_argparsers(subparsers) for s in all_subparsers: s.add_argument('--forbid-parser-rebuild', action=utils.YesNoAction, default=False, help='force loading parser from disk (helps when running mypyvy from multiple processes)') s.add_argument('--log', default='warning', choices=['error', 'warning', 'info', 'debug'], help='logging level') s.add_argument('--log-time', action=utils.YesNoAction, default=False, help='make each log message include current time') s.add_argument('--log-xml', action=utils.YesNoAction, default=False, help='log in XML format') s.add_argument('--seed', type=int, default=0, help="value for z3's smt.random_seed") s.add_argument('--print-program', choices=['str', 'repr', 'faithful', 'without-invariants'], help='print program after parsing using given strategy') s.add_argument('--key-prefix', help='additional string to use in front of names sent to z3') s.add_argument('--minimize-models', action=utils.YesNoAction, default=True, help='search for models with minimal cardinality') s.add_argument('--timeout', type=int, default=None, help='z3 timeout (milliseconds)') s.add_argument('--exit-on-error', action=utils.YesNoAction, default=False, help='exit after reporting first error') s.add_argument('--ipython', action=utils.YesNoAction, default=False, help='run IPython with s and prog at the end') s.add_argument('--error-filename-basename', action=utils.YesNoAction, default=False, help='print only the basename of the input file in error messages') s.add_argument('--query-time', action=utils.YesNoAction, default=True, help='report how long various z3 queries take') s.add_argument('--print-counterexample', action=utils.YesNoAction, default=True, help='print counterexamples') s.add_argument('--print-negative-tuples', action=utils.YesNoAction, default=False, help='print negative counterexamples') s.add_argument('--print-cmdline', action=utils.YesNoAction, default=True, help='print the command line passed to mypyvy') s.add_argument('--clear-cache', action=utils.YesNoAction, default=False, help='do not load from cache, but dump to cache as usual ' '(effectively clearing the cache before starting)') s.add_argument('--clear-cache-memo', action=utils.YesNoAction, default=False, help='load only discovered states from the cache, but dump to cache as usual ' '(effectively clearing the memoization cache before starting, ' 'while keeping discovered states and transitions)') s.add_argument('--cache-only', action=utils.YesNoAction, default=False, help='assert that the caches already contain all the answers') s.add_argument('--cache-only-discovered', action=utils.YesNoAction, default=False, help='assert that the discovered states already contain all the answers') s.add_argument('--print-exit-code', action=utils.YesNoAction, default=False, help='print the exit code before exiting (good for regression testing)') s.add_argument('--exit-0', action=utils.YesNoAction, default=False, help='always exit with status 0 (good for testing)') s.add_argument('--cvc4', action='store_true', help='use CVC4 as the backend solver. this is not very well supported.') s.add_argument('--smoke-test-solver', action=utils.YesNoAction, default=False, help='(for debugging mypyvy itself) double check countermodels by evaluation') # for diagrams: s.add_argument('--simplify-diagram', action=utils.YesNoAction, default=(s is updr_subparser), default_description='yes for updr, else no', help='in diagram generation, substitute existentially quantified variables ' 'that are equal to constants') updr_subparser.add_argument('--use-z3-unsat-cores', action=utils.YesNoAction, default=True, help='generalize using unsat cores rather than brute force') updr_subparser.add_argument('--assert-inductive-trace', action=utils.YesNoAction, default=False, help='(for debugging mypyvy itself) check that frames are always inductive') verify_subparser.add_argument('--check-transition', default=None, nargs='+', help="when verifying inductiveness, check only these transitions") verify_subparser.add_argument('--check-invariant', default=None, nargs='+', help="when verifying inductiveness, check only these invariants") verify_subparser.add_argument('--json', action='store_true', help="output machine-parseable verification results in JSON format") updr_subparser.add_argument('--checkpoint-in', help='start from internal state as stored in given file') updr_subparser.add_argument('--checkpoint-out', help='store internal state to given file') # TODO: say when bmc_subparser.add_argument('--safety', help='property to check') bmc_subparser.add_argument('--depth', type=int, default=3, metavar='N', help='number of steps to check') bmc_subparser.add_argument('--relax', action=utils.YesNoAction, default=False, help='relaxed semantics (domain can decrease)') argparser.add_argument('filename') #return cast(utils.MypyvyArgs, argparser.parse_args(args)) return cast(utils.MypyvyArgs, argparser.parse_args(args)) """ def binder_to_json(binder): d = [] for v in binder.vs: d.append(["var", v.name, sort_to_json(v.sort)]) return d class Mods(object): def __init__(self, mods): self.mods = mods self.in_old = False def with_old(self): assert (self.mods != None) m = Mods(self.mods) m.in_old = True return m def expr_to_json(fs, m, vs, e): if isinstance(e, syntax.QuantifierExpr): assert e.quant in ("FORALL", "EXISTS") is_forall = e.quant == "FORALL" decls = binder_to_json(e.binder) w = dict(vs) for v in e.binder.vs: w[v.name] = sort_to_json(v.sort) body = expr_to_json(fs, m, w, e.body) return ["forall" if is_forall else "exists", decls, body] elif isinstance(e, syntax.AppExpr): so = fs[e.callee] if (not m.in_old) and m.mods != None and e.callee in m.mods: c = ["const", e.callee + "'", so] else: c = ["const", e.callee, so] return ["apply", c, [expr_to_json(fs, m, vs, arg) for arg in e.args] ] elif isinstance(e, syntax.Id): if e.name in vs: return ["var", e.name, vs[e.name]] else: assert e.name in fs if (not m.in_old) and m.mods != None and e.name in m.mods: return ["const", e.name + "'", fs[e.name]] else: return ["const", e.name, fs[e.name]] elif isinstance(e, syntax.UnaryExpr): if e.op == "NOT": return ["not", expr_to_json(fs, m, vs, e.arg)] elif e.op == "OLD": return expr_to_json(fs, m.with_old(), vs, e.arg) else: print("unary", e.op) assert False elif isinstance(e, syntax.BinaryExpr): if e.op == "IMPLIES": return ["implies", expr_to_json(fs, m, vs, e.arg1), expr_to_json(fs, m, vs, e.arg2)] elif e.op == "EQUAL": return ["eq", expr_to_json(fs, m, vs, e.arg1), expr_to_json(fs, m, vs, e.arg2)] elif e.op == "IFF": return ["eq", expr_to_json(fs, m, vs, e.arg1), expr_to_json(fs, m, vs, e.arg2)] elif e.op == "NOTEQ": return ["not", ["eq", expr_to_json(fs, m, vs, e.arg1), expr_to_json(fs, m, vs, e.arg2)]] else: print("binary", e.op) assert False elif isinstance(e, syntax.NaryExpr): if e.op == "AND": return ["and", [expr_to_json(fs, m, vs, a) for a in e.args]] if e.op == "OR": return ["or", [expr_to_json(fs, m, vs, a) for a in e.args]] else: print("nary", e.op) assert False elif isinstance(e, syntax.IfThenElse): return ["ite", expr_to_json(fs, m, vs, e.branch), expr_to_json(fs, m, vs, e.then), expr_to_json(fs, m, vs, e.els) ] else: print(type(e)) print(dir(e)) assert False def get_sorts(prog): return [sort.name for sort in prog.sorts()] def sort_to_json(r): return ["uninterpretedSort", r.name] def boolean_sort_json(): return ["booleanSort"] def get_functions(prog): funcs = [] for f in prog.relations_constants_and_functions(): if isinstance(f, syntax.RelationDecl): dom = [sort_to_json(r) for r in f.arity] rng = boolean_sort_json() funcs.append(["const", f.name, ["functionSort", dom, rng]]) elif isinstance(f, syntax.ConstantDecl): funcs.append(["const", f.name, sort_to_json(f.sort)]) elif isinstance(f, syntax.FunctionDecl): dom = [sort_to_json(r) for r in f.arity] rng = sort_to_json(f.sort) funcs.append(["const", f.name, ["functionSort", dom, rng]]) return funcs def get_fs(prog): fs = {} for f in prog.relations_constants_and_functions(): if isinstance(f, syntax.RelationDecl): dom = [sort_to_json(r) for r in f.arity] rng = boolean_sort_json() fs[f.name] = ["functionSort", dom, rng] elif isinstance(f, syntax.ConstantDecl): fs[f.name] = sort_to_json(f.sort) elif isinstance(f, syntax.FunctionDecl): dom = [sort_to_json(r) for r in f.arity] rng = sort_to_json(f.sort) fs[f.name] = ["functionSort", dom, rng] return fs def get_axioms(prog): fs = get_fs(prog) return [expr_to_json(fs, Mods(None), {}, e.expr) for e in prog.axioms()] def get_inits(prog): fs = get_fs(prog) return [expr_to_json(fs, Mods(None), {}, e.expr) for e in prog.inits()] def get_conjs(prog): fs = get_fs(prog) return [expr_to_json(fs, Mods(None), {}, e.expr) for e in prog.safeties()] def get_actions(prog): fs = get_fs(prog) a = {} for e in prog.transitions(): #assert (e.num_states == 2) decls = binder_to_json(e.binder) vs = {v.name : sort_to_json(v.sort) for v in e.binder.vs} mod_names = [m.name for m in e.mods] m = Mods(mod_names) ex = expr_to_json(fs, m, vs, e.expr) if len(vs) > 0: ex = ["exists", decls, ex] a[e.name] = ["relation", mod_names, ex] return a def main(): filename = sys.argv[1] utils.args = mypyvy.parse_args(['typecheck', filename]) with open(filename) as f: contents = f.read() prog = mypyvy.parse_program(contents, filename) prog.resolve() #typechecker.typecheck_program(prog) actions = get_actions(prog) print(json.dumps({ "sorts" : get_sorts(prog), "functions" : get_functions(prog), "axioms" : get_axioms(prog), "inits" : get_inits(prog), "conjectures" : get_conjs(prog), "templates" : [], "actions" : get_actions(prog), })) #print(prog.constants) #print(prog.decls) #print(prog.sorts) #print(prog.safeties) #print(prog.functions) #print(prog.relations) #print(prog.inits) if __name__ == "__main__": main() <file_sep>/src/model_isomorphisms.h #ifndef MODEL_ISOMORPHISMS_H #define MODEL_ISOMORPHISMS_H #include "model.h" bool are_models_isomorphic(std::shared_ptr<Model> m1, std::shared_ptr<Model> m2); #endif <file_sep>/src/template_counter.h #ifndef TEMPLATE_COUNTER_H #define TEMPLATE_COUNTER_H #include "logic.h" #include "var_lex_graph.h" #include "template_desc.h" #include <algorithm> struct TransitionSystem { std::vector<std::vector<int>> transitions; std::vector<std::vector<int>> state_reps; TransitionSystem() { } TransitionSystem( std::vector<std::vector<int>> transitions, std::vector<std::vector<int>> state_reps) : transitions(transitions), state_reps(state_reps) { } // returns -1 if no edge int next(int state, int trans) const { //assert (0 <= state); //assert (state < (int)transitions.size()); //assert (0 <= trans); //assert (trans < (int)transitions[state].size()); return transitions[state][trans]; } int nTransitions() const { return transitions[0].size(); } int nStates() const { return transitions.size(); } TransitionSystem reorder_rows(std::vector<int> const& maps_to) { std::vector<int> rev; rev.resize(transitions.size()); for (int i = 0; i < (int)rev.size(); i++) { rev[i] = -1; } for (int i = 0; i < (int)maps_to.size(); i++) { rev[maps_to[i]] = i; } std::vector<std::vector<int>> transitions1; std::vector<std::vector<int>> state_reps1; for (int i = 0; i < (int)maps_to.size(); i++) { state_reps1.push_back(state_reps[maps_to[i]]); transitions1.push_back(transitions[maps_to[i]]); for (int j = 0; j < (int)transitions1[i].size(); j++) { if (transitions1[i][j] != -1) { transitions1[i][j] = rev[transitions1[i][j]]; } } } return TransitionSystem(transitions1, state_reps1); } TransitionSystem cap_total_vars(int mvars) { std::vector<int> rows_to_keep; for (int i = 0; i < (int)transitions.size(); i++) { int sum = 0; for (int j : state_reps[i]) { sum += j; } if (sum <= mvars) { rows_to_keep.push_back(i); } } return reorder_rows(rows_to_keep); } TransitionSystem make_upper_triangular() { std::vector<std::pair<int, int>> v; for (int i = 0; i < (int)transitions.size(); i++) { int sum = 0; for (int j : state_reps[i]) { sum += j; } v.push_back(std::make_pair(sum, i)); } std::sort(v.begin(), v.end()); std::vector<int> rows; for (auto p : v) { rows.push_back(p.second); } return reorder_rows(rows); } TransitionSystem remove_transitions(std::vector<bool> const& used) const { int n = nStates(); int m = nTransitions(); std::vector<std::vector<int>> transitions1; for (int i = 0; i < n; i++) { std::vector<int> row1; for (int j = 0; j < m; j++) { if (used[j]) { row1.push_back(transitions[i][j]); } } transitions1.push_back(std::move(row1)); } return TransitionSystem(transitions1, state_reps); } TransitionSystem remove_unused_transitions() { int n = nStates(); int m = nTransitions(); std::vector<bool> used; used.resize(m); for (int i = 0; i < m; i++) { bool u = false; for (int j = 0; j < n; j++) { if (transitions[j][i] != -1) { u = true; break; } } used[i] = u; } return remove_transitions(used); } }; TransitionSystem build_transition_system( VarIndexState const& init, std::vector<VarIndexTransition> const& transitions, int maxVars); //long long count_space(std::shared_ptr<Module> module, int k, int maxVars); unsigned long long count_template( std::shared_ptr<Module> module, value templ, int k, bool depth2, bool useAllVars); struct EnumInfo { std::vector<value> clauses; std::vector<VarIndexTransition> var_index_transitions; EnumInfo(std::shared_ptr<Module>, value templ); }; std::vector<TemplateSlice> count_many_templates( std::shared_ptr<Module> module, int maxClauses, bool depth2, int maxVars); std::vector<TemplateSlice> count_many_templates( std::shared_ptr<Module> module, TemplateSpace const& ts); std::pair<std::pair<std::vector<int>, TransitionSystem>, int> get_subslice_index_map( TransitionSystem const& ts, TemplateSlice const& tslice); #endif <file_sep>/src/obviously_implies.h #ifndef OBVIOUSLY_IMPLIES_H #define OBVIOUSLY_IMPLIES_H #include "logic.h" //bool obviously_implies(std::shared_ptr<Module>, value, value); std::vector<value> all_sub_disjunctions(value); #endif <file_sep>/src/model.h #ifndef MODEL_H #define MODEL_H #include <vector> #include <unordered_map> #include <map> #include "logic.h" #include "contexts.h" #include "smt.h" #include "lib/json11/json11.hpp" class SortInfo { public: size_t domain_size; }; typedef unsigned int object_value; class FunctionTable { public: std::vector<std::unique_ptr<FunctionTable>> children; object_value value; json11::Json to_json() const; static std::unique_ptr<FunctionTable> from_json(json11::Json); }; class FunctionInfo { public: object_value else_value; std::unique_ptr<FunctionTable> table; json11::Json to_json() const; static FunctionInfo from_json(json11::Json); }; class FunctionEntry { public: std::vector<object_value> args; object_value res; FunctionEntry() { } FunctionEntry( std::vector<object_value> const& args, object_value res) : args(args), res(res) { } }; struct FTree { enum class Type { True, False, And, Or, Atom }; Type type; // For Atoms: int arg_idx; object_value arg_value; // For And/Or: std::shared_ptr<FTree> left; std::shared_ptr<FTree> right; std::string to_string() const; }; struct EvalExpr; class Model { public: bool eval_predicate(value) const; static std::vector<std::shared_ptr<Model>> extract_minimal_models_from_z3( smt::context& ctx, smt::solver& solver, std::shared_ptr<Module> module, std::vector<std::shared_ptr<ModelEmbedding>> es, std::shared_ptr<Value> hint); static std::shared_ptr<Model> extract_model_from_z3( smt::context& ctx, smt::solver& solver, std::shared_ptr<Module> module, ModelEmbedding const& e); private: static std::shared_ptr<Model> extract_z3( smt::context& ctx, smt::solver& solver, std::shared_ptr<Module> module, ModelEmbedding const& e); static std::shared_ptr<Model> extract_cvc4( smt::context& ctx, smt::solver& solver, std::shared_ptr<Module> module, ModelEmbedding const& e); public: void dump() const; void dump_sizes() const; std::string obj_to_string(Sort*, object_value) const; size_t get_domain_size(lsort) const; size_t get_domain_size(Sort*) const; size_t get_domain_size(std::string) const; std::vector<size_t> get_domain_sizes_for_function(iden) const; FunctionInfo const& get_function_info(iden) const; void assert_model_is(std::shared_ptr<ModelEmbedding> e); void assert_model_is_not(std::shared_ptr<ModelEmbedding> e); void assert_model_does_not_have_substructure(std::shared_ptr<ModelEmbedding> e); void assert_model_is_or_isnt(std::shared_ptr<ModelEmbedding> e, bool exact, bool negate); std::vector<FunctionEntry> getFunctionEntries(iden name); object_value func_eval(iden name, std::vector<object_value> const& args); // return a FTree which computes whether f(...) = res std::shared_ptr<FTree> getFunctionFTree(iden name, object_value res); json11::Json to_json() const; static std::shared_ptr<Model> from_json(json11::Json, std::shared_ptr<Module>); private: std::shared_ptr<Module> module; std::unordered_map<std::string, SortInfo> sort_info; std::unordered_map<iden, FunctionInfo> function_info; public: EvalExpr value_to_eval_expr( std::shared_ptr<Value> v, std::vector<iden> const& names) const; Model( std::shared_ptr<Module> module, std::unordered_map<std::string, SortInfo>&& sort_info, std::unordered_map<iden, FunctionInfo>&& function_info) : module(module), sort_info(std::move(sort_info)), function_info(std::move(function_info)) { } private: std::map<std::pair<iden, object_value>, std::shared_ptr<FTree>> ftree_cache; std::shared_ptr<FTree> constructFunctionFTree(iden name, object_value res); friend bool are_models_isomorphic(std::shared_ptr<Model>, std::shared_ptr<Model>); }; std::shared_ptr<Model> transition_model( smt::context& ctx, std::shared_ptr<Module> module, std::shared_ptr<Model> start_state, int which_action = -1); std::vector<std::shared_ptr<Model>> get_tree_of_models( smt::context& ctx, std::shared_ptr<Module> module, std::shared_ptr<Model> start_state, int depth); std::vector<std::shared_ptr<Model>> get_tree_of_models2( smt::context& ctx, std::shared_ptr<Module> module, int depth, int multiplicity, bool reversed = false // find bad models starting at NOT(safety condition) ); struct QuantifierInstantiation { bool non_null; value formula; std::vector<VarDecl> decls; std::vector<object_value> variable_values; std::shared_ptr<Model> model; }; struct Z3VarSet { std::vector<smt::expr> vars; }; // Give a value of the form `forall A,B,...,Z . expr`, returns // instantions of the variables A,B,...,Z such that the expression returns false // (if one exists, that is, if the entire expression evaluates to false). QuantifierInstantiation get_counterexample(std::shared_ptr<Model>, value); bool eval_qi(QuantifierInstantiation const& qi, value); bool get_multiqi_counterexample( std::shared_ptr<Model>, value, std::vector<QuantifierInstantiation>& output); /* Z3VarSet add_existential_constraint(std::shared_ptr<ModelEmbedding>, value); QuantifierInstantiation z3_var_set_2_quantifier_instantiation( Z3VarSet const&, smt::solver&, std::shared_ptr<Model>, value v); */ void ftree_tests(); #endif
255e4c737b3d47a4f6c06043cd7f1d7dacff423c
[ "Markdown", "Makefile", "Python", "C++", "Dockerfile", "Shell" ]
85
Dockerfile
mahzam/SWISS
348b9c4f9b0b2f124b50c8f420d071f4bc0789b3
a2e89082a8f05bbd3f34a04a8bd0c3d5f8899ae7
refs/heads/master
<file_sep>\name{celsiusServer} %__CUT__% \docType{class} \alias{celsiusServer} \alias{celsiusServer-class} \title{ Object to hold values pertaining to a Celsius Server } \description{ Holds values like the URL needed to reach the server or the default timings for accessing the features and samples for the server etc.}%- maybe also 'usage' for other objects documented here. \section{Creating Objects}{ \code{new('celsiusServer',}\cr \code{celsiusUrl = ...., #URL}\cr \code{platform = ...., #Platform for data retrieval }\cr \code{protocol = ...., #Normalization protocol for the data to be retrieved }\cr \code{stringency = ...., #Stringency setting for annotation retrieval }\cr \code{verbose = ...., #Verbosity preference }\cr \code{transform = ...., #Transform the annotations vector into 0's and 1's }\cr \code{retry = ...., #Number of retry attempts with web server }\cr \code{sampleTime = ...., #estimated time to retrieve a sample}\cr \code{featureTime = ...., #estimated time to retrieve a feature}\cr \code{ )}} \section{Slots}{ \describe{ \item{\code{celsiusUrl}}{ Provide an approriate URL \code{"character"} to talk to a celsius server } \item{\code{platform}}{ Provide an approriate affymetrix platform \code{"character"} for data retrieval. The preferred format is the affymetrix format, but you can also enter Bioconductor formatted platform names. Default is 'HG-U133A' } \item{\code{protocol}}{ Provide an approriate normalization protocol \code{"character"} for the data to be retrieved. Values can be: 'rma','vsn','gcrma','plier' and 'mas5'. Default value is 'rma'. } \item{\code{stringency}}{ Provide an approriate stringency setting \code{"numeric"}. This is the quality of annotation desired. A higher value results in more NA (un-annotated) values for annotation retrieval. Possible values include: 600,500,400,300,200,100. Default is 500. } \item{\code{verbose}}{ Indicate \code{"logical"} whether to print output to the screen whenever data has been retrieved from the DB. Default is FALSE. } \item{\code{transform}}{ Indicate \code{"logical"} whether or not to format all annotation mask data into a list of only 0's and 1's (ie. to list NAs and and annotation conficts as 0's) Default is FALSE. } \item{\code{retry}}{ Provide the number of retry attempts \code{"character"} for the client to attempt to get data from the web server. Default is 3. } \item{\code{sampleTime}}{ Provide an expected wait time \code{"numeric"} to retrieve a sample from this platform (can determine this by using time and the getSampleData() in this library if you REALLY hate waiting) } \item{\code{featureTime}}{ Provide an expected wait time \code{"numeric"} to retrieve a feature from this platform (can determine this by using time and the getFeatureData() in this library if you REALLY hate waiting)} } } \author{ <NAME> } \keyword{ classes } <file_sep>\name{getPhenoData} %__CUT__% \alias{getPhenoData} \title{ Retrieve a matrix of annotations from controlled vocabulary terms } \description{ The following is a function to just retrieve a list of annotation terms ON a set list of IDs, or for all IDS (if none are provided). All Annots retrieved are specific to one platform.} \usage{ getPhenoData(celsiusObject, id = NULL, cvterm = NULL); } \arguments{ \item{celsiusObject}{ Provide a celsius server object with approriate URLs } \item{id}{ Provide a vector of ids } \item{cvterm}{ Provide a list of cvterms } } \value{ Return value is a table with col labels as SN identifiers and row labels as annotation terms. } \author{ <NAME> and <NAME> } \examples{ #make a celsius instance celsius = new( "celsiusServer", celsiusUrl = "http://celsius.genomics.ctrl.ucla.edu" ); #ways you can get the data data = getPhenoData( celsius, id = c( "SN:1000019", "SN:1000170", "SN:1005039", "SN:1004962", "SN:1005722", "SN:1006573" ), cvterm = c( "MA:0000168", "MPATH:218" ) ); celsius@transform = TRUE; data = getPhenoData( celsius, id = c( "SN:1000019", "SN:1000170", "SN:1005039", "SN:1004962", "SN:1005722", "SN:1006573" ), cvterm = c( "MA:0000168", "MPATH:218" ) ); data = getPhenoData( celsius, cvterm = c( "MA:0000168", "MPATH:218" ) ); celsius@transform = FALSE; data = getPhenoData( celsius, id = c( "SN:1000019", "SN:1000170", "SN:1005039", "SN:1004962", "SN:1005722", "SN:1006573" ), cvterm = c( "MPATH:218" ) ); data = getPhenoData( celsius, id = c( "SN:1000019" ), cvterm = c( "MA:0000168", "MPATH:218" ) ); data = getPhenoData( celsius, id = c( "SN:1000019" ), cvterm = c( "MPATH:218" ) ); } \keyword{ data } <file_sep>#$Id: celsius.R,v 1.40 2007/05/04 18:12:23 mcarlson Exp $ #Copyright 2006 <NAME>, <NAME>. Released under Artistic License library("Biobase"); setClass("celsiusServer", representation( celsiusUrl = "character", platform = "character", protocol = "character", stringency = "numeric", verbose = "logical", transform = "logical", retry = "numeric", sampleTime = "numeric", featureTime = "numeric"), prototype = list( celsiusUrl = "http://celsius.genomics.ctrl.ucla.edu", platform = "HG-U133A", protocol = "rma", stringency = 500, verbose = FALSE, transform = FALSE, retry = 3, sampleTime = 1.8, featureTime = 2.6 )) # #####HOWTO: make get() and set() #setGeneric("getcelsiusUrl", function(object) { # standardGeneric("getcelsiusUrl") #}) #setMethod("getcelsiusUrl", "celsiusServer", function(object) { # object@celsiusUrl #}) #setGeneric("setcelsiusUrl", function(object, String) { # standardGeneric("setcelsiusUrl") #}) #setMethod("setcelsiusUrl", "celsiusServer", function(object, String) { # eval(eval(substitute(expression(object@celsiusUrl<<-String)))) #}) .getWebData = function( celsiusObject, urlString, useScan = FALSE ){ if(celsiusObject@retry > 0){ counter = 1;}else{counter = 0;} thing = NULL; while( (counter<=celsiusObject@retry || counter==0) && is.null(thing) ){ if(useScan == TRUE){thing = tryCatch(.getWithScan(celsiusObject,urlString), error=function(e) NULL);} else{thing = tryCatch(.getAsTable(celsiusObject,urlString), error=function(e) NULL)}; if(is.null(thing)){cat("Tried and Failed" ,counter,"times to retrieve data...\n")} if(counter!=0){counter = counter + 1;} } return(thing); } .getAsTable = function( celsiusObject, urlString ){ return(read.table(paste(celsiusObject@celsiusUrl, urlString, sep=""), sep="\t", comment.char="!")); } .getWithScan = function( celsiusObject, urlString ){ table = NULL; linescan = scan(paste(celsiusObject@celsiusUrl, urlString, sep=""),sep="\t",what="character"); for ( i in seq( 1,length( linescan ),by=2 ) ) { table = rbind(table,linescan[i:(i+1)]); } return(table); } getOntologyData = function( celsiusObject, cvterm = c() ){ cvterm = as.matrix(cvterm)[, 1]; mat = NULL; j = 1; check = rep(TRUE, length(cvterm)); sampleNames = NULL; sampleNamesDone = FALSE; for (s in cvterm) { cvData = .getWebData(celsiusObject, paste("/service/cel/annots?p=",celsiusObject@platform,";f=mask;m=",s,";l=",celsiusObject@stringency, sep="")); if (celsiusObject@verbose) { cat(j, " term ID ", s, " was retrieved for ", dim(cvData)[1], " samples", "\n"); } if(is.null(cvData)){ check[j]= FALSE; } else if (dim(cvData)[2] == 2 && dim(cvData)[1] > 1) { if(!sampleNamesDone){ sampleNames=cvData[-1, 1]; sampleNamesDone=TRUE; } cvData = as.numeric(as.matrix(cvData[-1, 2])) if(celsiusObject@transform == TRUE){ cvData[cvData=="!"]=NA; cvData[is.na(cvData)]=0; } } else { cvData = NULL; check[j] = FALSE; } mat = cbind(mat, cvData); j = j + 1; } if(any(check)){ colnames(mat) = cvterm[check]; rownames(mat) = sampleNames; } badCVTerm = sum(!check); if (badCVTerm > 0) { if(badCVTerm == length(cvterm) ){ cat("\nThere is no data retrieved from the database! Please check your list of cvterms!"); } else { cat("\n", badCVTerm, "Some CVTerms were discarded from your list as they were not in the database."); cat("\nAnd they are:\n", cvterm[!check], "\n"); } } return(t(mat)); } getFeatureData = function( celsiusObject, feature = c() ){ feature = as.matrix(feature)[, 1]; mat = NULL; j = 1; check = rep(TRUE, length(feature)); sampleNames = NULL; sampleNamesDone = FALSE; for (s in feature) { featureData = .getWebData(celsiusObject, paste("/service/element/element?p=",celsiusObject@platform,";id=",s,";p=",celsiusObject@protocol, sep = "")); if (celsiusObject@verbose) { cat(j, " feature ID ", s, " was retrieved for " , dim(featureData)[1], " samples", "\n"); } if(is.null(featureData)){ check[j]= FALSE; }else if (dim(featureData)[2] == 2 && dim(featureData)[1] > 1) { if(!sampleNamesDone){ sampleNames=featureData[-1, 1]; sampleNamesDone=TRUE; } featureData = as.numeric(as.matrix(featureData[-1, 2])) } else { featureData = NULL; check[j] = FALSE; } mat = cbind(mat, featureData); j = j + 1; } if(any(check)){ colnames(mat) = feature[check]; rownames(mat) = sampleNames; } badFeature = sum(!check); if (badFeature > 0 ){ if(badFeature == length(feature) ){ cat("There is no data retrieved from the database! Please check your list of ProbeSets!"); } else { cat("\n", badFeature, "Probe sets were discarded from your list as they were not in the database for this platform."); cat("\nAnd they are:\n", feature[!check], "\n"); } } return(t(mat)); } getSampleData = function ( celsiusObject, id = c() ){ id = as.matrix(id)[, 1]; mat = NULL; j = 1; check = rep(TRUE, length(id)); probesetNames = NULL; probesetNamesDone = FALSE; for (s in id) { egr = .getWebData(celsiusObject, paste("/service/cel/cel?id=",s, ";f=egr;p=", celsiusObject@protocol, sep = "")); if (celsiusObject@verbose) { cat(j, " sample ID ", s, " was retrieved for ", dim(egr)[1], " features", "\n") } if(is.null(egr)){ check[j]= FALSE; } else if (dim(egr)[2] == 2 && dim(egr)[1] > 1) { if (!probesetNamesDone) { probesetNames = egr[-1, 1]; probesetNames = gsub( pattern = '.+?:', replacement = "", x = probesetNames); probesetNamesDone = TRUE; } egr = as.numeric(as.matrix(egr[-1, 2])); } else { egr = NULL; check[j] = FALSE; } mat = cbind(mat, egr); j = j + 1; } if(any(check)){ colnames(mat) = id[check]; rownames(mat) = probesetNames; } badID = sum(!check); if (badID > 0) { if (badID == length(id)) { cat("\nThere is no data retrieved from the database! Please check your list of IDs!\n\n"); } else { cat("\n", badID, " IDs were discarded from your list as they were either not in the database or did not contain any probesets.", sep=""); cat("\nAnd they are:\n", id[!check], "\n\n"); } } return(mat) } getAssayData = function( celsiusObject, id = NULL, feature = NULL ){ if( is.null(feature) && !is.null(id) ){ exprMatrix = getSampleData(celsiusObject,id=id); } if( is.null(id) && !is.null(feature) ){ exprMatrix = getFeatureData(celsiusObject,feature=feature); } if( !is.null(id) && !is.null(feature)){ numCols = length(id); numRows = length(feature); if(numCols *celsiusObject@sampleTime >= numRows * celsiusObject@featureTime) { exprMatrix = getFeatureData(celsiusObject,feature=feature); matchVec = match(colnames(exprMatrix), id); exprMatrix = as.matrix(exprMatrix[,!is.na(matchVec),drop=FALSE]); } else if(numRows * celsiusObject@featureTime > numCols *celsiusObject@sampleTime){ exprMatrix = getSampleData(celsiusObject,id=id); matchVec = match(rownames(exprMatrix), feature); exprMatrix = as.matrix(exprMatrix[!is.na(matchVec),,drop=FALSE]); } rownames(exprMatrix) = feature; colnames(exprMatrix) = id; } return(exprMatrix); } getPhenoData = function( celsiusObject, id = NULL, cvterm = NULL ){ annotMat = getOntologyData(celsiusObject,cvterm=cvterm); if( !is.null(id) ){ matchVec = match(colnames(annotMat), id); annotMat = annotMat[,!is.na(matchVec),drop=FALSE]; } return(annotMat) } .getAllAnnots = function( celsiusObject, id = NULL ){ if(is.null(id)){id = as.character(listSamplesForPlatform(celsiusObject))} annotTable = read.delim(paste(celsiusObject@celsiusUrl,'/service/cel/annots?p=',celsiusObject@platform,';f=tab', sep='')); rownames(annotTable) = sub(':','.',annotTable[,1]); idSymbols = sub(':','.',id); matchVec = match(rownames(annotTable), idSymbols); annotTable = annotTable[!is.na(matchVec),]; return(annotTable); } makeExprSet = function( celsiusObject, id = NULL, cvterm = NULL, feature = NULL, annotations = FALSE, mapids = FALSE ){ annotTable = NULL; phenoData = NULL; exprData = NULL; platformName = gsub(pattern='[^0-9A-Za-z]+', replacement='', x=celsiusObject@platform, perl=TRUE); platformName = sub(pattern="(\\w+)", replacement="\\L\\1", x=platformName, perl=TRUE); if(!is.null(id)){ if(mapids == TRUE){idMap = mapIdToCelsius(celsiusObject,id);}else{idMap = cbind(id,id);} id = as.vector(idMap[,2]); idPheno = as.matrix(idMap[,1]); rownames(idPheno) = idMap[,2]; colnames(idPheno) = "original_ID"; } exprData = getAssayData(celsiusObject,id = id, feature = feature); rownames(exprData) = gsub( pattern = '.+?:', replacement = "", x = rownames(exprData)); colnames(exprData) = sub(':','.',colnames(exprData)); if(!is.null(cvterm)){ phenoData = getPhenoData(celsiusObject,id = id, cvterm = cvterm) colnames(phenoData) = sub(':','.',colnames(phenoData)); phenoData = t(phenoData); matchVec = match(rownames(phenoData), colnames(exprData)); phenoData = phenoData[!is.na(matchVec),,drop=FALSE]; } if(!is.null(id)){phenoData = cbind(phenoData,idPheno);} if(annotations == TRUE){ annotTable = .getAllAnnots(celsiusObject,id); matchVec = match(rownames(annotTable), colnames(exprData)); annotTable = annotTable[!is.na(matchVec),,drop=FALSE]; # phenoData = cbind(phenoData,annotTable); if(is.null(id) && is.null(cvterm)){phenoData = annotTable}else{phenoData = cbind(phenoData,annotTable);} } if(is.null(id) && is.null(cvterm) && annotations == FALSE){ exprSet = new('ExpressionSet', exprs = exprData, annotation = platformName); }else{ phenoData = data.frame(phenoData, row.names = colnames(exprData)); phenoData = new("AnnotatedDataFrame", data = phenoData); exprSet = new('ExpressionSet', phenoData = phenoData, exprs = exprData, annotation = platformName); } return(exprSet); } mapIdToCelsius = function( celsiusObject, id = c() ){ id = as.character(id); #checkme: maybe not needed by = 50; buf = NULL; check = rep(TRUE, length(id)); j = 1; for ( i in seq( 1,length( id ),by=by ) ) { if( i + by > length( id ) ) { t = .getWebData(celsiusObject, paste('/service/search/cel_accession?f=tab;q=',paste(id[i:length(id)],collapse='+'),sep=""),useScan=TRUE); } else { t = .getWebData(celsiusObject, paste('/service/search/cel_accession?f=tab;q=',paste(id[i:((i+by)-1)],collapse='+'),sep=""),useScan=TRUE); } if(is.null(t)){ check[j]= FALSE; }else { buf = rbind(buf,t); } j = j + 1; } badID = sum(!check); if (badID == length(id)) { cat("\nThere are no IDs in your list that map to the database!\n\n"); } uniqueIDs = as.vector(unique(id)); colnames(buf) = c('query','target'); uniqueRetIDs = as.vector(unique(buf[,1])); if(length(uniqueRetIDs) != length(uniqueIDs) ){ matchVec = match(uniqueIDs, uniqueRetIDs); cat("\nThe following IDs could not be found:", id[is.na(matchVec)],"\n\n"); } return(buf); } getCvterms = function( celsiusObject, q = NULL, db = NULL ){ z = read.table(paste(celsiusObject@celsiusUrl, '/service/search/ontology?q=',q,sep=""),sep="\t",header=FALSE,col.names=c('db','accession','name','ontology')); r = vector(length=1,mode="list"); j = 1; for ( i in 1:dim(z)[1] ) { if ( is.null(db) || db == z$db[i] ) { k = as.list(x=new.env()); k$db = as.character(z$db[i]); k$accession = as.character(sub('/',':',z$accession[i])); k$name = as.character(z$name[i]); k$ontology = as.character(z$ontology[i]); r[[j]] = k; j = j + 1; } } return(r); } getPlatformData = function( celsiusObject ){ platTable = read.delim(paste(celsiusObject@celsiusUrl, '/service/platform/platforms?f=tab', sep=''),header=FALSE,col.names=c('platform','samples','field')); platTable = platTable[,1:2]; return(platTable); } listSamplesForPlatform = function( celsiusObject ){ platTable = read.delim(paste(celsiusObject@celsiusUrl,'/service/cel/cels?p=',celsiusObject@platform,';f=tab', sep=''),header=FALSE); platTable = platTable[,1]; return(platTable); } #$Log: celsius.R,v $ #Revision 1.40 2007/05/04 18:12:23 mcarlson #killed some bugs relating to annotations and possibly the refactor of #makeExprSet(). The function is MUCH easier to maintain now. And #everything appears to work well. Need guys to do testing. Also, need #to finish cleanup of the manual pages... # #Revision 1.39 2007/05/04 06:23:14 mcarlson #FINALLY! Refactored that bloated ugly makeExprsSet(). # #Revision 1.38 2007/05/04 02:26:09 mcarlson #Critical bug fix for annotations parameter, and some minor refactoring on #the huge makeExprSet(). Which I still think needs to shrink a lot. # #Revision 1.37 2007/05/03 21:56:12 mcarlson #Bug fix for the ID mapper to accomodate STRANGE IDs that begin with "0". #Also some refactoring to reduce redundancy in the code. makeExprSet() #still needs to be refactored... # #Revision 1.36 2007/05/03 02:04:34 mcarlson #Bug Fixes. Also eliminated many lines of unecessary checking in middle tier #functions. makeExprsSet still needs a major refactoring. # #Revision 1.35 2007/05/02 23:51:31 mcarlson #Added code to retry when data is being grabbed (needs more testing). And #also refactored the settings out of the functions and into the celsius #object. THIS WILL MEAN THAT WE HAVE TO CHANGE THE ONLINE TUTORIAL. So #please exercise the necessart precautions. # #Revision 1.34 2007/04/28 02:35:52 mcarlson #Improved the error handling of the function to factor out function that #gets data from the web server. Fixed a broken example. # #Revision 1.33 2007/04/28 01:22:40 mcarlson #Added preliminary code to retry a get (if it comes back empty from the #web server...). But before I continue, I need to verify that the new func #will be documented ok in the man file. # #Revision 1.32 2007/04/28 00:15:55 jundong #test it # #Revision 1.31 2007/04/28 00:08:02 mcarlson #Finally the id mapping function will have functional error handling. A #parameter has also been added to the highest level function so that ID #mapping will be toggled off by default. This should save time for people #who are using default SNIDs. # #Revision 1.30 2007/04/26 06:54:11 allenday #id mapping paging # #Revision 1.29 2007/04/26 01:26:39 mcarlson #changed progress to verbose # #Revision 1.28 2007/04/26 01:20:18 mcarlson #Added error handling code for the other two "get" functions and added a verbose #option that now goes all the way to the top. # #Revision 1.27 2007/04/25 01:44:35 mcarlson #Added Jun code for error handling for getSampleData(). Made minor edits to #the documentation. Still needs to have documentation improved... # #Revision 1.26 2007/04/21 01:55:22 mcarlson #Added param to makeExprSet() so that it can output all annot terms if requested. # #Revision 1.25 2007/04/20 23:09:42 mcarlson #Fixed some small bugs. Changed examples to match Allens web tutorial. # #Revision 1.24 2007/04/20 01:11:34 mcarlson # #Updated man.Rd # #Revision 1.23 2007/04/19 02:22:32 allenday #getCvterms function # #Revision 1.22 2007/04/19 01:20:01 mcarlson #Added functions to get the available platforms and the IDs for a particular #platform along with relevant documentation. # #Revision 1.21 2007/04/13 01:29:48 allenday #license # #Revision 1.20 2007/04/13 00:19:21 mcarlson #Made changes to the code and the man.Rd file to try to get this thing to be #compliant with documentaion standards. # #Revision 1.19 2007/04/12 23:05:45 mcarlson #Cleaned up code, added prelim manual info for server object. Fixes in to #accomodate server URL changes and parameter name changes. # #Revision 1.18 2007/04/11 23:48:08 mcarlson #Added code to make a small R object with get and set functions to allow #access to the URL Strings contained within it. Functions now use the #contents of this object to get the data that they need. This will allow #separate instanced of the celsius DB to be instantiated and accessed later #on. Also, this object defaults to the "original" celsius DB. # #Revision 1.17 2007/03/30 00:31:26 mcarlson #Dropped extraneous fucntion. Refactored the 3 base functions for speed and #efficiency. # #Revision 1.16 2007/03/28 20:59:39 mcarlson #More name changes. # #Revision 1.15 2007/03/28 20:39:00 mcarlson #corrected naming error. # #Revision 1.14 2007/03/28 19:25:59 mcarlson #Changed names of variables for consistency and to try and increase clarity #by making names more similar to the existing BIOC names. # #Revision 1.13 2007/03/28 02:43:46 mcarlson #I think that most of the evil bugs are finally dead... #All tests pass now. But the code could still be tidied (renamed etc). # #Revision 1.12 2007/03/27 01:23:18 mcarlson #Cleaned out superfluous comments in code. # #Revision 1.11 2007/03/27 00:50:27 mcarlson #Cleaned up .Rd file to lose a lot of warnings. Removed superfluous annot.manager() # #Revision 1.10 2007/03/24 02:02:52 mcarlson #Now you can use IDs from alternate sources, and the function to make a #BIOC object will just figure out what you mean, and then place the ID mapping #into the pheno object along with the annotations for any CVTERMS that you #request... Next: this code needs to be cleaned up. And good examples #need to be made. # #Revision 1.9 2007/03/23 03:07:20 mcarlson #Many many bug fixes. Most notably, you no longer are required to have a #cvterm to make a BIOC object, and a lot of coner cases where cvterm, ID, #or feature == 1 no longer fail due to inately bad "R bahavoirs"... Lets #just say that R sucks in the assumptions department and that this code now #works. # #Revision 1.8 2007/03/23 01:10:09 allenday #id mapping code and docs # #Revision 1.7 2007/03/23 00:51:22 allenday #added RCS Log # <file_sep>\name{makeExprSet} %__CUT__% \alias{makeExprSet} \title{ Retrieve data and or phenotype annotations from Celsius and package into a BIOC expression set object } \description{ The following function retrieves a matrix of annotation data and also a matrix of expression data and then packages them into a BIOC expression object for the user. The function requires a list of annotation terms along with either a list of IDs OR a list of elements (or both). If a list of elements is also provided, then the function will return the slice of data that corresponds to the intersection of those elements on the IDs listed. } \usage{ makeExprSet( celsiusObject, id = NULL, cvterm = NULL, feature = NULL, annotations = FALSE, mapids = FALSE) } \arguments{ \item{celsiusObject}{ Provide a celsius server object with approriate URLs } \item{id}{ Provide a list of SN ID's } \item{cvterm}{ Provide a list of cvterms } \item{feature}{ Provide a vector of elements } \item{annotations}{ if TRUE, this includes supplementary annotations as terms } \item{mapids}{ if TRUE, this will map any foreign keys for the user and allow access to alternate data } } \value{ Return value is a BIOC expression set object. } \author{ <NAME> and <NAME> } \examples{ #make a celsius instance celsius = new( "celsiusServer", celsiusUrl = "http://celsius.genomics.ctrl.ucla.edu", platform = "HG-U133A" ); #get the data exprSet = makeExprSet( celsius, id = c( "SN:1005595"), cvterm = c("MPATH:458") ); #get the data exprSet = makeExprSet( celsius, id = c( "SN:1005595" ) ); #get the data exprSet = makeExprSet( celsius, id = c( "SN:1005595" ), feature = c("201820_at", "202222_s_at") ); #change the transform option to TRUE celsius@transform = TRUE; #get data (with transform now = TRUE) exprSet = makeExprSet( celsius, id = c( "SN:1005595", "SN:1000170" ), cvterm = c( "MA:0000415", "MPATH:458" ) ); #get the data (transform still = TRUE) exprSet = makeExprSet( celsius, id = c( "SN:1005595", "SN:1000170" ), cvterm = c( "MA:0000415", "MPATH:458" ), feature = c( "201820_at", "202222_s_at" ) ); #change the transform option to FALSE celsius@transform = FALSE; #get the data (now with transform = FALSE) exprSet = makeExprSet( celsius, cvterm = c( "MA:0000415", "MPATH:458" ), feature = c( "222152_at", "201820_at", "202222_s_at", "202508_s_at", "203296_s_at", "203400_s_at" ) ); #get the data exprSet = makeExprSet( celsius, feature = c( "201820_at" ) ); #get the data exprSet = makeExprSet( celsius, feature = c( "201820_at", "202222_s_at" ) ); #get the data exprSet = makeExprSet( celsius, cvterm = c( "MA:0000415", "MPATH:458" ), feature = c( "201820_at", "202222_s_at" ) ); #get the data exprSet = makeExprSet( celsius, cvterm = c( "MA:0000415" ), feature = c( "201820_at" ) ); #change the affy platform being sought celsius@platform = "Mouse430_2"; #get the data (now for Mouse 430 2.0 arrays) exprSet = makeExprSet( celsius, id = c( "GSE6210" ), cvterm = c( "MPATH:458", "MA:0000415" ), mapids = TRUE); #change the platform back to HG-U133A celsius@platform = "HG-U133A"; #now get the data #(mapids = TRUE, so now you can use foreign keys as sample ID's ) exprSet = makeExprSet( celsius, id = c( "26490", "26491", "26492" ), cvterm = c( "MPATH:458", "MA:0000415" ), feature = c( "201820_at", "202222_s_at", "202508_s_at", "203296_s_at", "203400_s_at" ), mapids = TRUE ); #get the data (annotations = TRUE, so you will get some extra data about #each sample) exprSet = makeExprSet( celsius, id = c( "SN:1005595", "SN:1000170" ), cvterm = c( "MA:0000415", "MPATH:458" ), feature = c( "201820_at", "202222_s_at" ), annotations = TRUE ); } \keyword{ data } <file_sep>\name{getPlatformData} %__CUT__% \alias{getPlatformData} \title{ lists all the platforms available on a Celsius server } \description{ Useful to know which affy platforms are available. Presents a table with 2 cols: 1) platform name, and 2) number of cel files available} \usage{ platformTable = getPlatformData( celsiusObject ); } \arguments{ \item{celsiusObject}{ Providea celsius server object with approriate URLs } } \value{ Returns a two-column table. Column 1 contains the supported platforms, Column 2 contains the number of samples representing said platform. } \author{ <NAME> } \examples{ #make a celsius instance celsius = new("celsiusServer", celsiusUrl = "http://celsius.genomics.ctrl.ucla.edu" ); #get platform availability information platformTable = getPlatformData( celsius ); } \keyword{ data } <file_sep>\name{getOntologyData} %__CUT__% \alias{getOntologyData} \title{ Retrieve Annotations into R from Celsius webserver } \description{ Retrieves annotation data for Affymetrix arrays in multi-graph (MGR) format } \usage{ getOntologyData(celsiusObject, cvterm=c()); } \arguments{ \item{celsiusObject}{ Provide a celsius server object with approriate URLs } \item{cvterm}{ character vector of ontology term accessions } } \value{ Return value is a table with rows labels as SN identifiers and column labels as probeset identifiers. } \author{ <NAME>, <NAME> and <NAME> } \examples{ #make a celsius instance celsius = new( "celsiusServer", celsiusUrl = "http://celsius.genomics.ctrl.ucla.edu", platform = "HG-U133A", stringency = 500 ); #get the data data = getOntologyData( celsius, cvterm = c( "MA:0000168","MPATH:458" ) ); } \keyword{ data } <file_sep>\name{getCvterms} %__CUT__% \alias{getCvterms} \title{ Retrieve ontology term (aka CV term) data structures (lists) by query phrase } \description{ Useful for searching ontologies by ontology term name} \usage{ lungTerms = getCvterms(celsiusObject, q="lung", db="MA"); } \arguments{ \item{celsiusObject}{ Provide a celsius server object with appropriate URLs } \item{q}{ Query phrase. Meta-character "*" may be used as a wildcard } \item{db}{ DBspace of CV to be queried, e.g. "GO" for Gene Ontology, "MA" for Mouse Adult Anatomy Ontology } } \value{ Returns a vector of lists. Each list corresponds to an ontology term, with attributes: * accession - ontology term accession, e.g. "MA:0000415" * name - ontology term name, e.g. "lung" * db - db of ontology term, e.g. "MA" * ontology - name of ontology, e.g. "Mouse\_anatomy\_by\_time\_xproduct" } \author{ <NAME> } \examples{ #make a celsius instance celsius = new( "celsiusServer", celsiusUrl="http://celsius.genomics.ctrl.ucla.edu" ); #get annotation term information lungTerms = getCvterms( celsius, q = "lung", db = "MA" ); ovuTerms = getCvterms( celsius, q = "ovu*" ); } \keyword{ data } <file_sep>\name{getFeatureData} %__CUT__% \alias{getFeatureData} \title{ Retrieve data (probeset-wise) into R from Celsius webserver } \description{ Retrieves quantified Affymetrix data in multi-graph (MGR) format by feature } \usage{ getFeatureData(celsiusObject, feature = c() ); } \arguments{ \item{celsiusObject}{ Provide a celsius server object with approriate URLs } \item{feature}{ character vector of feature IDs, database accession identifiers for probeset records used in Celsius } } \value{ Return value is a table with rows labels as SN identifiers and column labels as probeset identifiers. } \author{ <NAME>, <NAME> and <NAME> } \examples{ #make a celsius instance celsius = new( "celsiusServer", celsiusUrl = "http://celsius.genomics.ctrl.ucla.edu", platform = "HG-U133A", protocol = "rma" ); #get the data data = getFeatureData(celsius, feature = c( "204412_s_at", "1316_at") ); } \keyword{ data } <file_sep>\name{getAssayData} %__CUT__% \alias{getAssayData} \title{ Get Celsius data using IDs, probesets OR the intersection of data that corresponds to BOTH IDs and probesets.} \description{ This function is to intelligently get the data from the DB so that the data is retrieved in the fastest possible way. IF only IDs are given, then it will only return the full data on THOSE, if only an feature list is given, then it will return ALL the data for that platform on only those elements, and finally, if both a ID and an feature list are given then it will decide whether to retrieve on IDs and restrict by elements, or vice versa (just depending on what is faster). } \usage{ getAssayData( celsiusObject, id = NULL, feature = NULL ); } \arguments{ \item{celsiusObject}{ Provide a celsius server object with approriate URLs } \item{id}{ character vector of IDs, database accession identifiers for CEL records used in Celsius } \item{feature}{ character vector of feature IDs, database accession identifiers for probeset records used in Celsius } } \value{ Return value is a table with col labels as SN identifiers and row labels as probeset identifiers. } \author{ <NAME> and <NAME> } \examples{ #make a celsius instance celsius = new( "celsiusServer", celsiusUrl = "http://celsius.genomics.ctrl.ucla.edu" ); #ways you can get the data data = getAssayData( celsius, id = c( "SN:1018351" ), feature = c( "201820_at", "202222_s_at", "202508_s_at", "203296_s_at", "203400_s_at" ) ); data = getAssayData( celsius, id = c( "SN:1018351", "SN:1043233" ), feature = c( "201820_at" ) ); data = getAssayData( celsius, id = c( "SN:1018351", "SN:1043233" ) ); data = getAssayData( celsius, feature = c( "201820_at", "202222_s_at" ) ); data = getAssayData( celsius, id = c( "SN:1018351", "SN:1043233" ), feature = c( "201820_at", "202222_s_at", "202508_s_at", "203296_s_at", "203400_s_at" ) ); data = getAssayData( celsius, id = c( "SN:1018351", "SN:1043233", "SN:1018331", "SN:1041970", "SN:1008042" ), feature = c( "201820_at","202222_s_at" )); data = getAssayData( celsius, id = c( "SN:1018351" ), feature = c( "201820_at" ) ); } \keyword{ data } <file_sep>\name{getSampleData} %__CUT__% \alias{getSampleData} \title{ Retrieve data (sample-wise) into R from Celsius webserver } \description{ Retrieves quantified Affymetrix data in multi-graph (MGR) format by array } \usage{ getSampleData(celsiusObject, id = c() ); } \arguments{ \item{celsiusObject}{ Provide a celsius server object with approriate URLs } \item{id}{ character vector of IDs, database accession identifiers for CEL records used in Celsius } } \value{ Return value is a table with rows labels as SN identifiers and column labels as probeset identifiers. } \author{ <NAME>, <NAME> and <NAME> } \examples{ #make a celsius instance celsius = new( "celsiusServer", celsiusUrl = "http://celsius.genomics.ctrl.ucla.edu", verbose = TRUE ); #get the data data = getSampleData( celsius, id = c( "SN:1005595" ) ); } \keyword{ data } <file_sep>\name{listSamplesForPlatform} %__CUT__% \alias{listSamplesForPlatform} \title{ Lists all the internal IDs for a given platform } \description{ Useful for enumerating all the IDs present on a platform. } \usage{ idList = listSamplesForPlatform( celsiusObject); } \arguments{ \item{celsiusObject}{ Provide a celsius server object with approriate URLs } } \value{ Returns a list of IDs that match up with a particular platform. } \author{ <NAME> } \examples{ #make a celsius instance celsius = new( "celsiusServer", celsiusUrl = "http://celsius.genomics.ctrl.ucla.edu", platform = "HG-U133_Plus_2" ); #get ids for the platform idList = listSamplesForPlatform( celsius ); } \keyword{ data } <file_sep>all :: man check install test :: check man :: /usr/bin/perl ./man.pl check :: /home/mcarlson/arch/i686/R-patched/bin/R CMD check -l /home/mcarlson/R/i686-pc-linux-gnu-library/2.5 `pwd` install :: /home/mcarlson/arch/i686/R-patched/bin/R CMD INSTALL -l /home/mcarlson/R/i686-pc-linux-gnu-library/2.5 `pwd` dist :: rm -f ./*.gz rm -f ./*.zip rm -rf ./*.Rcheck /home/mcarlson/arch/i686/R-patched/bin/R CMD build `pwd` /home/mcarlson/arch/i686/R-patched/bin/R CMD INSTALL -l . ./*.gz find `cat DESCRIPTION | grep -E '^Pack' | awk '{print $$2}'` | zip -@ `cat DESCRIPTION | perl -e '@F=<>;chomp(@F);%F=map{/^(\S+):\s+(\S+)$$/;$$1=>$$2}@F;print "$$F{Package}_$$F{Version}.zip"'` rm -rf `cat DESCRIPTION | grep -E '^Pack' | awk '{print $$2}'` <file_sep>%$Id: man.Rd,v 1.45 2007/05/24 18:04:32 mcarlson Exp $ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \name{celsius} %__CUT__% \alias{celsius} \alias{celsius-package} \docType{package} \title{ Retrieve Affymetrix microarray measurements and metadata from Celsius } \description{ Retrieve Affymetrix microarray measurements and metadata from Celsius web services, see http://genome.ucla.edu/projects/celsius. } \details{ \tabular{ll}{ Package: \tab celsius\cr Type: \tab Package\cr Version: \tab 1.0.7\cr Date: \tab 2007-05-21\cr License: \tab Artistic License\cr } This library is intended to provide a set of accessor methods to a celsius style database. To use any of these functions, you must 1st create a Celsius Server object that points to an appropriate instance of a Celsius Database. The default parameters point to the initial instance. Once this is created, there are a host of usable functions which can be called as needed Here is a brief overview: getPlatformData(): returns all affy platforms supported by the server listSamplesForPlatform(): lists all Sample IDs for a particular platform mapIdToCelsius(): this maps foreign Sample IDs to the Celsius Server instance getSampleData(): Returns data based on Sample IDs getFeatureData(): Returns data based on features (affy probeset IDs) getAssayData(): Returns an intersection of data for a set of both features and sample IDs getCvterms(): returns information (such as ID) about available controlled vocabulary terms getOntologyData(): Returns phenotypic data based on list of controlled voculary term IDs getPhenoData(): returns an intersection of data for controlled vocabulary terms and specific Sample IDs makeExprSet(): makes an expression set object from supplied IDs, features and/or controlled vocabulary terms } \author{ <NAME> and <NAME> Maintainer: <NAME> <<EMAIL>> } \keyword{ data } \seealso{ There is also individual documentation for the major functions listed above. } %~~ simple examples of the most important functions ~~ \examples{ #first make an instance of a celsius Server object. celsius = new( "celsiusServer", celsiusUrl = "http://celsius.genomics.ctrl.ucla.edu" ); #list all of the platforms supported by the server platformTable = getPlatformData( celsius ); #list all the samples in the server that correspond to the #HG-U133_Plus_2 platform... celsius@platform = "HG-U133_Plus_2"; idList = listSamplesForPlatform( celsius ); #map some foreign IDs to the celsius servers internal sample IDs celsius@platform = 'HG-U133A'; id = c( "AEX:E-MEXP-402", "GSE6210" ); mapTable = mapIdToCelsius( celsius, id = id ); #get some samples data based on sample IDs celsius@verbose = TRUE; data = getSampleData( celsius, id = c( "SN:1005595" ) ); #get some data based on features (affymetrix probesets). data = getFeatureData( celsius, feature = c( "204412_s_at", "1316_at" ) ); #get some data that corresponds to both a set of Sample IDs AND some #features (affymetrix probesets) celsius@verbose = FALSE; data = getAssayData( celsius, id = c( "SN:1018351", "SN:1043233" ), feature = c( "201820_at", "202222_s_at", "202508_s_at", "203296_s_at" ) ); #get some information about controlled vocabulary terms #(ID is probably most important here) lungTerms = getCvterms( celsius, q = "lung", db = "MA" ); #get data on all samples (on one platform) for a particular controlled #vocabulary term data = getOntologyData( celsius, cvterm=c( "MA:0000415" ) ); #get data on all samples (on one platform) for a controlled vocabulary #term on specific samples data = getPhenoData( celsius, id = c( "SN:1000019", "SN:1000170", "SN:1005039", "SN:1004962" ), cvterm = c( "MA:0000415" ) ); #finally, we can make an expression set object straight from the #database using IDs and controlled vocabulary terms exprSet = makeExprSet( celsius, id = c( "SN:1000019", "SN:1000170", "SN:1005039" ), cvterm = c( "MA:0000415" ), feature = c( "201820_at", "202222_s_at", "202508_s_at", "203296_s_at" ) ); #Or you can also make an expression set using a foreign ID: celsius@platform = "Mouse430_2"; exprSet = makeExprSet(celsius, id = c( "GSE6210" ), cvterm = c( "MA:0000415" ), feature = c( "1415670_at", "1430537_at" ), mapids = TRUE ); #Finally, you can get raw annotations for an expression set by using the #annotations parameter celsius@platform = 'HG-U133A'; exprSet = makeExprSet( celsius, id = c( "SN:1000019", "SN:1000170", "SN:1005039" ), cvterm = c( "MA:0000415" ), feature = c( "201820_at", "202222_s_at", "202508_s_at", "203296_s_at" ), annotations = TRUE ); } %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \name{celsiusServer} %__CUT__% \docType{class} \alias{celsiusServer} \alias{celsiusServer-class} \title{ Object to hold values pertaining to a Celsius Server } \description{ Holds values like the URL needed to reach the server or the default timings for accessing the features and samples for the server etc.}%- maybe also 'usage' for other objects documented here. \section{Creating Objects}{ \code{new('celsiusServer',}\cr \code{celsiusUrl = ...., #URL}\cr \code{platform = ...., #Platform for data retrieval }\cr \code{protocol = ...., #Normalization protocol for the data to be retrieved }\cr \code{stringency = ...., #Stringency setting for annotation retrieval }\cr \code{verbose = ...., #Verbosity preference }\cr \code{transform = ...., #Transform the annotations vector into 0's and 1's }\cr \code{retry = ...., #Number of retry attempts with web server }\cr \code{sampleTime = ...., #estimated time to retrieve a sample}\cr \code{featureTime = ...., #estimated time to retrieve a feature}\cr \code{ )}} \section{Slots}{ \describe{ \item{\code{celsiusUrl}}{ Provide an approriate URL \code{"character"} to talk to a celsius server } \item{\code{platform}}{ Provide an approriate affymetrix platform \code{"character"} for data retrieval. The preferred format is the affymetrix format, but you can also enter Bioconductor formatted platform names. Default is 'HG-U133A' } \item{\code{protocol}}{ Provide an approriate normalization protocol \code{"character"} for the data to be retrieved. Values can be: 'rma','vsn','gcrma','plier' and 'mas5'. Default value is 'rma'. } \item{\code{stringency}}{ Provide an approriate stringency setting \code{"numeric"}. This is the quality of annotation desired. A higher value results in more NA (un-annotated) values for annotation retrieval. Possible values include: 600,500,400,300,200,100. Default is 500. } \item{\code{verbose}}{ Indicate \code{"logical"} whether to print output to the screen whenever data has been retrieved from the DB. Default is FALSE. } \item{\code{transform}}{ Indicate \code{"logical"} whether or not to format all annotation mask data into a list of only 0's and 1's (ie. to list NAs and and annotation conficts as 0's) Default is FALSE. } \item{\code{retry}}{ Provide the number of retry attempts \code{"character"} for the client to attempt to get data from the web server. Default is 3. } \item{\code{sampleTime}}{ Provide an expected wait time \code{"numeric"} to retrieve a sample from this platform (can determine this by using time and the getSampleData() in this library if you REALLY hate waiting) } \item{\code{featureTime}}{ Provide an expected wait time \code{"numeric"} to retrieve a feature from this platform (can determine this by using time and the getFeatureData() in this library if you REALLY hate waiting)} } } \author{ <NAME> } \keyword{ classes } %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \name{getOntologyData} %__CUT__% \alias{getOntologyData} \title{ Retrieve Annotations into R from Celsius webserver } \description{ Retrieves annotation data for Affymetrix arrays in multi-graph (MGR) format } \usage{ getOntologyData(celsiusObject, cvterm=c()); } %- maybe also 'usage' for other objects documented here. \arguments{ \item{celsiusObject}{ Provide a celsius server object with approriate URLs } \item{cvterm}{ character vector of ontology term accessions } } \value{ Return value is a table with rows labels as SN identifiers and column labels as probeset identifiers. } \author{ <NAME>, <NAME> and <NAME> } \examples{ #make a celsius instance celsius = new( "celsiusServer", celsiusUrl = "http://celsius.genomics.ctrl.ucla.edu", platform = "HG-U133A", stringency = 500 ); #get the data data = getOntologyData( celsius, cvterm = c( "MA:0000168","MPATH:458" ) ); } \keyword{ data } %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \name{getFeatureData} %__CUT__% \alias{getFeatureData} \title{ Retrieve data (probeset-wise) into R from Celsius webserver } \description{ Retrieves quantified Affymetrix data in multi-graph (MGR) format by feature } \usage{ getFeatureData(celsiusObject, feature = c() ); } %- maybe also 'usage' for other objects documented here. \arguments{ \item{celsiusObject}{ Provide a celsius server object with approriate URLs } \item{feature}{ character vector of feature IDs, database accession identifiers for probeset records used in Celsius } } \value{ Return value is a table with rows labels as SN identifiers and column labels as probeset identifiers. } \author{ <NAME>, <NAME> and <NAME> } \examples{ #make a celsius instance celsius = new( "celsiusServer", celsiusUrl = "http://celsius.genomics.ctrl.ucla.edu", platform = "HG-U133A", protocol = "rma" ); #get the data data = getFeatureData(celsius, feature = c( "204412_s_at", "1316_at") ); } \keyword{ data } %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \name{getSampleData} %__CUT__% \alias{getSampleData} \title{ Retrieve data (sample-wise) into R from Celsius webserver } \description{ Retrieves quantified Affymetrix data in multi-graph (MGR) format by array } \usage{ getSampleData(celsiusObject, id = c() ); } %- maybe also 'usage' for other objects documented here. \arguments{ \item{celsiusObject}{ Provide a celsius server object with approriate URLs } \item{id}{ character vector of IDs, database accession identifiers for CEL records used in Celsius } } \value{ Return value is a table with rows labels as SN identifiers and column labels as probeset identifiers. } \author{ <NAME>, <NAME> and <NAME> } \examples{ #make a celsius instance celsius = new( "celsiusServer", celsiusUrl = "http://celsius.genomics.ctrl.ucla.edu", verbose = TRUE ); #get the data data = getSampleData( celsius, id = c( "SN:1005595" ) ); } \keyword{ data } %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \name{getAssayData} %__CUT__% \alias{getAssayData} \title{ Get Celsius data using IDs, probesets OR the intersection of data that corresponds to BOTH IDs and probesets.} \description{ This function is to intelligently get the data from the DB so that the data is retrieved in the fastest possible way. IF only IDs are given, then it will only return the full data on THOSE, if only an feature list is given, then it will return ALL the data for that platform on only those elements, and finally, if both a ID and an feature list are given then it will decide whether to retrieve on IDs and restrict by elements, or vice versa (just depending on what is faster). } \usage{ getAssayData( celsiusObject, id = NULL, feature = NULL ); } %- maybe also 'usage' for other objects documented here. \arguments{ \item{celsiusObject}{ Provide a celsius server object with approriate URLs } \item{id}{ character vector of IDs, database accession identifiers for CEL records used in Celsius } \item{feature}{ character vector of feature IDs, database accession identifiers for probeset records used in Celsius } } \value{ Return value is a table with col labels as SN identifiers and row labels as probeset identifiers. } \author{ <NAME> and <NAME> } \examples{ #make a celsius instance celsius = new( "celsiusServer", celsiusUrl = "http://celsius.genomics.ctrl.ucla.edu" ); #ways you can get the data data = getAssayData( celsius, id = c( "SN:1018351" ), feature = c( "201820_at", "202222_s_at", "202508_s_at", "203296_s_at", "203400_s_at" ) ); data = getAssayData( celsius, id = c( "SN:1018351", "SN:1043233" ), feature = c( "201820_at" ) ); data = getAssayData( celsius, id = c( "SN:1018351", "SN:1043233" ) ); data = getAssayData( celsius, feature = c( "201820_at", "202222_s_at" ) ); data = getAssayData( celsius, id = c( "SN:1018351", "SN:1043233" ), feature = c( "201820_at", "202222_s_at", "202508_s_at", "203296_s_at", "203400_s_at" ) ); data = getAssayData( celsius, id = c( "SN:1018351", "SN:1043233", "SN:1018331", "SN:1041970", "SN:1008042" ), feature = c( "201820_at","202222_s_at" )); data = getAssayData( celsius, id = c( "SN:1018351" ), feature = c( "201820_at" ) ); } \keyword{ data } %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \name{getPhenoData} %__CUT__% \alias{getPhenoData} \title{ Retrieve a matrix of annotations from controlled vocabulary terms } \description{ The following is a function to just retrieve a list of annotation terms ON a set list of IDs, or for all IDS (if none are provided). All Annots retrieved are specific to one platform.} \usage{ getPhenoData(celsiusObject, id = NULL, cvterm = NULL); } %- maybe also 'usage' for other objects documented here. \arguments{ \item{celsiusObject}{ Provide a celsius server object with approriate URLs } \item{id}{ Provide a vector of ids } \item{cvterm}{ Provide a list of cvterms } } \value{ Return value is a table with col labels as SN identifiers and row labels as annotation terms. } \author{ <NAME> and <NAME> } \examples{ #make a celsius instance celsius = new( "celsiusServer", celsiusUrl = "http://celsius.genomics.ctrl.ucla.edu" ); #ways you can get the data data = getPhenoData( celsius, id = c( "SN:1000019", "SN:1000170", "SN:1005039", "SN:1004962", "SN:1005722", "SN:1006573" ), cvterm = c( "MA:0000168", "MPATH:218" ) ); celsius@transform = TRUE; data = getPhenoData( celsius, id = c( "SN:1000019", "SN:1000170", "SN:1005039", "SN:1004962", "SN:1005722", "SN:1006573" ), cvterm = c( "MA:0000168", "MPATH:218" ) ); data = getPhenoData( celsius, cvterm = c( "MA:0000168", "MPATH:218" ) ); celsius@transform = FALSE; data = getPhenoData( celsius, id = c( "SN:1000019", "SN:1000170", "SN:1005039", "SN:1004962", "SN:1005722", "SN:1006573" ), cvterm = c( "MPATH:218" ) ); data = getPhenoData( celsius, id = c( "SN:1000019" ), cvterm = c( "MA:0000168", "MPATH:218" ) ); data = getPhenoData( celsius, id = c( "SN:1000019" ), cvterm = c( "MPATH:218" ) ); } \keyword{ data } %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \name{makeExprSet} %__CUT__% \alias{makeExprSet} \title{ Retrieve data and or phenotype annotations from Celsius and package into a BIOC expression set object } \description{ The following function retrieves a matrix of annotation data and also a matrix of expression data and then packages them into a BIOC expression object for the user. The function requires a list of annotation terms along with either a list of IDs OR a list of elements (or both). If a list of elements is also provided, then the function will return the slice of data that corresponds to the intersection of those elements on the IDs listed. } \usage{ makeExprSet( celsiusObject, id = NULL, cvterm = NULL, feature = NULL, annotations = FALSE, mapids = FALSE) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{celsiusObject}{ Provide a celsius server object with approriate URLs } \item{id}{ Provide a list of SN ID's } \item{cvterm}{ Provide a list of cvterms } \item{feature}{ Provide a vector of elements } \item{annotations}{ if TRUE, this includes supplementary annotations as terms } \item{mapids}{ if TRUE, this will map any foreign keys for the user and allow access to alternate data } } \value{ Return value is a BIOC expression set object. } \author{ <NAME> and <NAME> } \examples{ #make a celsius instance celsius = new( "celsiusServer", celsiusUrl = "http://celsius.genomics.ctrl.ucla.edu", platform = "HG-U133A" ); #get the data exprSet = makeExprSet( celsius, id = c( "SN:1005595"), cvterm = c("MPATH:458") ); #get the data exprSet = makeExprSet( celsius, id = c( "SN:1005595" ) ); #get the data exprSet = makeExprSet( celsius, id = c( "SN:1005595" ), feature = c("201820_at", "202222_s_at") ); #change the transform option to TRUE celsius@transform = TRUE; #get data (with transform now = TRUE) exprSet = makeExprSet( celsius, id = c( "SN:1005595", "SN:1000170" ), cvterm = c( "MA:0000415", "MPATH:458" ) ); #get the data (transform still = TRUE) exprSet = makeExprSet( celsius, id = c( "SN:1005595", "SN:1000170" ), cvterm = c( "MA:0000415", "MPATH:458" ), feature = c( "201820_at", "202222_s_at" ) ); #change the transform option to FALSE celsius@transform = FALSE; #get the data (now with transform = FALSE) exprSet = makeExprSet( celsius, cvterm = c( "MA:0000415", "MPATH:458" ), feature = c( "222152_at", "201820_at", "202222_s_at", "202508_s_at", "203296_s_at", "203400_s_at" ) ); #get the data exprSet = makeExprSet( celsius, feature = c( "201820_at" ) ); #get the data exprSet = makeExprSet( celsius, feature = c( "201820_at", "202222_s_at" ) ); #get the data exprSet = makeExprSet( celsius, cvterm = c( "MA:0000415", "MPATH:458" ), feature = c( "201820_at", "202222_s_at" ) ); #get the data exprSet = makeExprSet( celsius, cvterm = c( "MA:0000415" ), feature = c( "201820_at" ) ); #change the affy platform being sought celsius@platform = "Mouse430_2"; #get the data (now for Mouse 430 2.0 arrays) exprSet = makeExprSet( celsius, id = c( "GSE6210" ), cvterm = c( "MPATH:458", "MA:0000415" ), mapids = TRUE); #change the platform back to HG-U133A celsius@platform = "HG-U133A"; #now get the data #(mapids = TRUE, so now you can use foreign keys as sample ID's ) exprSet = makeExprSet( celsius, id = c( "26490", "26491", "26492" ), cvterm = c( "MPATH:458", "MA:0000415" ), feature = c( "201820_at", "202222_s_at", "202508_s_at", "203296_s_at", "203400_s_at" ), mapids = TRUE ); #get the data (annotations = TRUE, so you will get some extra data about #each sample) exprSet = makeExprSet( celsius, id = c( "SN:1005595", "SN:1000170" ), cvterm = c( "MA:0000415", "MPATH:458" ), feature = c( "201820_at", "202222_s_at" ), annotations = TRUE ); } \keyword{ data } %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \name{mapIdToCelsius} %__CUT__% \alias{mapIdToCelsius} \title{ Expands vector of SN or external identifiers to one of SN identifiers } \description{ Useful to convert, e.g. GSM or GSE IDs to coresponding SN identifier(s). } \usage{ mapTable = mapIdToCelsius( celsiusObject, id = c()); } %- maybe also 'usage' for other objects documented here. \arguments{ \item{celsiusObject}{ Provide a celsius server object with approriate URLs } \item{id}{ Provide a list of SN or external identifiers } } \value{ Returns a two-column table. Column 1 contains the "query" identifiers passed in as argument 1, Column 2 contains the "target" identifiers that correspond to the "query" identifiers. Each row pair of identifiers is unique. } \author{ <NAME> } \examples{ #make a celsius instance celsius = new( "celsiusServer", celsiusUrl = "http://celsius.genomics.ctrl.ucla.edu" ); #define IDs you which to search on id = c( "AEX:E-MEXP-402", "GSE6210" ); #map the IDs to the celsius database mapTable = mapIdToCelsius( celsius, id = id ); } \keyword{ data } %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \name{getCvterms} %__CUT__% \alias{getCvterms} \title{ Retrieve ontology term (aka CV term) data structures (lists) by query phrase } \description{ Useful for searching ontologies by ontology term name} \usage{ lungTerms = getCvterms(celsiusObject, q="lung", db="MA"); } \arguments{ \item{celsiusObject}{ Provide a celsius server object with appropriate URLs } \item{q}{ Query phrase. Meta-character "*" may be used as a wildcard } \item{db}{ DBspace of CV to be queried, e.g. "GO" for Gene Ontology, "MA" for Mouse Adult Anatomy Ontology } } \value{ Returns a vector of lists. Each list corresponds to an ontology term, with attributes: * accession - ontology term accession, e.g. "MA:0000415" * name - ontology term name, e.g. "lung" * db - db of ontology term, e.g. "MA" * ontology - name of ontology, e.g. "Mouse\_anatomy\_by\_time\_xproduct" } \author{ <NAME> } \examples{ #make a celsius instance celsius = new( "celsiusServer", celsiusUrl="http://celsius.genomics.ctrl.ucla.edu" ); #get annotation term information lungTerms = getCvterms( celsius, q = "lung", db = "MA" ); ovuTerms = getCvterms( celsius, q = "ovu*" ); } \keyword{ data } %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \name{getPlatformData} %__CUT__% \alias{getPlatformData} \title{ lists all the platforms available on a Celsius server } \description{ Useful to know which affy platforms are available. Presents a table with 2 cols: 1) platform name, and 2) number of cel files available} \usage{ platformTable = getPlatformData( celsiusObject ); } %- maybe also 'usage' for other objects documented here. \arguments{ \item{celsiusObject}{ Providea celsius server object with approriate URLs } } \value{ Returns a two-column table. Column 1 contains the supported platforms, Column 2 contains the number of samples representing said platform. } \author{ <NAME> } \examples{ #make a celsius instance celsius = new("celsiusServer", celsiusUrl = "http://celsius.genomics.ctrl.ucla.edu" ); #get platform availability information platformTable = getPlatformData( celsius ); } \keyword{ data } %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \name{listSamplesForPlatform} %__CUT__% \alias{listSamplesForPlatform} \title{ Lists all the internal IDs for a given platform } \description{ Useful for enumerating all the IDs present on a platform. } \usage{ idList = listSamplesForPlatform( celsiusObject); } %- maybe also 'usage' for other objects documented here. \arguments{ \item{celsiusObject}{ Provide a celsius server object with approriate URLs } } \value{ Returns a list of IDs that match up with a particular platform. } \author{ <NAME> } \examples{ #make a celsius instance celsius = new( "celsiusServer", celsiusUrl = "http://celsius.genomics.ctrl.ucla.edu", platform = "HG-U133_Plus_2" ); #get ids for the platform idList = listSamplesForPlatform( celsius ); } \keyword{ data } %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %\name{.getWebData} %__CUT__% %\alias{.getWebData} %\title{ a private Function to retrieve data from the web server } %\description{ a private Function } %\usage{ % thing = .getWebData( celsiusObject, urlstring, useScan ); %} %\arguments{ % \item{celsiusObject}{ Provide a celsius server object with approriate % URLs } % \item{urlstring}{ Provide the other information to compose the rest of % the URL string } % \item{useScan}{ indicate whether scan needs to be run (only ever % planned for gathering ID data) } %} %\author{ <NAME> } %%\examples{} %\keyword{ data } %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %\name{.getAsTable} %__CUT__% %\alias{.getAsTable} %\title{ a private Function to retrieve data from the web server using % read.table() } %\description{ a private Function } %\usage{ % thing = .getWebData( celsiusObject, urlstring); %} %\arguments{ % \item{celsiusObject}{ Provide a celsius server object with approriate % URLs } % \item{urlstring}{ Provide the other information to compose the rest of % the URL string } %} %\author{ <NAME> } %%\examples{} %\keyword{ data } %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %\name{.getWithScan} %__CUT__% %\alias{.getWithScan} %\title{ a private Function to retrieve data from the web server using % scan() this helper function is specialized for mapping IDs and is % not intended for general usage at this time } %\description{ a private Function } %\usage{ % thing = .getWithScan( celsiusObject, urlstring); %} %\arguments{ % \item{celsiusObject}{ Provide a celsius server object with approriate % URLs } % \item{urlstring}{ Provide the other information to compose the rest of % the URL string } %} %\author{ <NAME> } %%\examples{} %\keyword{ data } %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %\name{.getAllAnnots} %__CUT__% %\alias{.getAllAnnots} %\title{ a private Function to retrieve all annotation data from the web % server and map this to the requested IDs } %\description{ a private Function } %\usage{ % thing = .getAllAnnots( celsiusObject, id); %} %\arguments{ % \item{celsiusObject}{ Provide a celsius server object with approriate % URLs } % \item{id}{ Provide a list of ids to get all annotation data for } %} %\author{ <NAME> } %%\examples{} %\keyword{ data } %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %$Log: man.Rd,v $ %Revision 1.45 2007/05/24 18:04:32 mcarlson %Corrected build errors in documentation. % %Revision 1.44 2007/05/23 01:48:24 mcarlson %edited out synopsis from the man.Rd file. % %Revision 1.43 2007/05/22 01:59:22 allenday %syntax error % %Revision 1.42 2007/05/04 19:48:49 mcarlson %updated the man.Rd file to format and make the help more consistent and... %helpful. % %Revision 1.41 2007/05/04 18:12:22 mcarlson %killed some bugs relating to annotations and possibly the refactor of %makeExprSet(). The function is MUCH easier to maintain now. And %everything appears to work well. Need guys to do testing. Also, need %to finish cleanup of the manual pages... % %Revision 1.40 2007/05/04 02:26:08 mcarlson %Critical bug fix for annotations parameter, and some minor refactoring on %the huge makeExprSet(). Which I still think needs to shrink a lot. % %Revision 1.39 2007/05/03 21:56:11 mcarlson %Bug fix for the ID mapper to accomodate STRANGE IDs that begin with "0". %Also some refactoring to reduce redundancy in the code. makeExprSet() %still needs to be refactored... % %Revision 1.38 2007/05/02 23:51:30 mcarlson %Added code to retry when data is being grabbed (needs more testing). And %also refactored the settings out of the functions and into the celsius %object. THIS WILL MEAN THAT WE HAVE TO CHANGE THE ONLINE TUTORIAL. So %please exercise the necessart precautions. % %Revision 1.37 2007/04/28 02:35:50 mcarlson %Improved the error handling of the function to factor out function that %gets data from the web server. Fixed a broken example. % %Revision 1.36 2007/04/28 01:22:38 mcarlson %Added preliminary code to retry a get (if it comes back empty from the %web server...). But before I continue, I need to verify that the new func %will be documented ok in the man file. % %Revision 1.35 2007/04/28 00:08:02 mcarlson %Finally the id mapping function will have functional error handling. A %parameter has also been added to the highest level function so that ID %mapping will be toggled off by default. This should save time for people %who are using default SNIDs. % %Revision 1.34 2007/04/26 01:45:29 allenday %version bump! % %Revision 1.33 2007/04/26 01:26:38 mcarlson %changed progress to verbose % %Revision 1.32 2007/04/26 01:20:17 mcarlson %Added error handling code for the other two "get" functions and added a verbose %option that now goes all the way to the top. % %Revision 1.31 2007/04/25 01:44:35 mcarlson %Added Jun code for error handling for getSampleData(). Made minor edits to %the documentation. Still needs to have documentation improved... % %Revision 1.30 2007/04/21 02:02:45 mcarlson % %Added edit to the man.Rd file to try and stamp out error. % %Revision 1.29 2007/04/21 01:55:20 mcarlson %Added param to makeExprSet() so that it can output all annot terms if requested. % %Revision 1.28 2007/04/20 23:26:05 mcarlson %Added another clever example to the top set of functions. % %Revision 1.27 2007/04/20 23:09:39 mcarlson %Fixed some small bugs. Changed examples to match Allens web tutorial. % %Revision 1.26 2007/04/20 01:26:19 allenday %1.1 check passes % %Revision 1.25 2007/04/20 01:11:34 mcarlson % %Updated man.Rd % %Revision 1.24 2007/04/19 22:42:23 allenday %docs and code work % %Revision 1.23 2007/04/19 02:22:31 allenday %getCvterms function % %Revision 1.22 2007/04/19 01:20:00 mcarlson %Added functions to get the available platforms and the IDs for a particular %platform along with relevant documentation. % %Revision 1.21 2007/04/13 01:37:31 mcarlson %Just putting more names in... % %Revision 1.20 2007/04/13 01:26:09 allenday %doc fixes, make target for distributable file % %Revision 1.19 2007/04/13 00:46:05 mcarlson %more edits to try to get the class to read in... % %Revision 1.18 2007/04/13 00:19:21 mcarlson %Made changes to the code and the man.Rd file to try to get this thing to be %compliant with documentaion standards. % %Revision 1.17 2007/04/12 23:05:45 mcarlson %Cleaned up code, added prelim manual info for server object. Fixes in to %accomodate server URL changes and parameter name changes. % %Revision 1.16 2007/04/12 18:56:29 mcarlson %Updated usage and synopsis for man.Rd to accomodate the new celsius object. % %Revision 1.15 2007/04/11 23:48:07 mcarlson %Added code to make a small R object with get and set functions to allow %access to the URL Strings contained within it. Functions now use the %contents of this object to get the data that they need. This will allow %separate instanced of the celsius DB to be instantiated and accessed later %on. Also, this object defaults to the "original" celsius DB. % %Revision 1.14 2007/03/30 00:31:25 mcarlson %Dropped extraneous fucntion. Refactored the 3 base functions for speed and %efficiency. % %Revision 1.13 2007/03/28 20:59:39 mcarlson %More name changes. % %Revision 1.12 2007/03/28 20:38:59 mcarlson %corrected naming error. % %Revision 1.11 2007/03/28 19:25:59 mcarlson %Changed names of variables for consistency and to try and increase clarity %by making names more similar to the existing BIOC names. % %Revision 1.10 2007/03/28 02:43:43 mcarlson %I think that most of the evil bugs are finally dead... %All tests pass now. But the code could still be tidied (renamed etc). % %Revision 1.9 2007/03/27 00:50:23 mcarlson %Cleaned up .Rd file to lose a lot of warnings. Removed superfluous annot.manager() % %Revision 1.8 2007/03/24 02:02:52 mcarlson %Now you can use IDs from alternate sources, and the function to make a %BIOC object will just figure out what you mean, and then place the ID mapping %into the pheno object along with the annotations for any CVTERMS that you %request... Next: this code needs to be cleaned up. And good examples %need to be made. % %Revision 1.7 2007/03/23 03:07:20 mcarlson %Many many bug fixes. Most notably, you no longer are required to have a %cvterm to make a BIOC object, and a lot of coner cases where cvterm, ID, %or feature == 1 no longer fail due to inately bad "R bahavoirs"... Lets %just say that R sucks in the assumptions department and that this code now %works. % %Revision 1.6 2007/03/23 01:10:09 allenday %id mapping code and docs % %Revision 1.5 2007/03/23 00:52:41 allenday %added RCS Id and Log % <file_sep>\name{mapIdToCelsius} %__CUT__% \alias{mapIdToCelsius} \title{ Expands vector of SN or external identifiers to one of SN identifiers } \description{ Useful to convert, e.g. GSM or GSE IDs to coresponding SN identifier(s). } \usage{ mapTable = mapIdToCelsius( celsiusObject, id = c()); } \arguments{ \item{celsiusObject}{ Provide a celsius server object with approriate URLs } \item{id}{ Provide a list of SN or external identifiers } } \value{ Returns a two-column table. Column 1 contains the "query" identifiers passed in as argument 1, Column 2 contains the "target" identifiers that correspond to the "query" identifiers. Each row pair of identifiers is unique. } \author{ <NAME> } \examples{ #make a celsius instance celsius = new( "celsiusServer", celsiusUrl = "http://celsius.genomics.ctrl.ucla.edu" ); #define IDs you which to search on id = c( "AEX:E-MEXP-402", "GSE6210" ); #map the IDs to the celsius database mapTable = mapIdToCelsius( celsius, id = id ); } \keyword{ data } <file_sep>\name{celsius} %__CUT__% \alias{celsius} \alias{celsius-package} \docType{package} \title{ Retrieve Affymetrix microarray measurements and metadata from Celsius } \description{ Retrieve Affymetrix microarray measurements and metadata from Celsius web services, see http://genome.ucla.edu/projects/celsius. } \details{ \tabular{ll}{ Package: \tab celsius\cr Type: \tab Package\cr Version: \tab 1.0.7\cr Date: \tab 2007-05-21\cr License: \tab Artistic License\cr } This library is intended to provide a set of accessor methods to a celsius style database. To use any of these functions, you must 1st create a Celsius Server object that points to an appropriate instance of a Celsius Database. The default parameters point to the initial instance. Once this is created, there are a host of usable functions which can be called as needed Here is a brief overview: getPlatformData(): returns all affy platforms supported by the server listSamplesForPlatform(): lists all Sample IDs for a particular platform mapIdToCelsius(): this maps foreign Sample IDs to the Celsius Server instance getSampleData(): Returns data based on Sample IDs getFeatureData(): Returns data based on features (affy probeset IDs) getAssayData(): Returns an intersection of data for a set of both features and sample IDs getCvterms(): returns information (such as ID) about available controlled vocabulary terms getOntologyData(): Returns phenotypic data based on list of controlled voculary term IDs getPhenoData(): returns an intersection of data for controlled vocabulary terms and specific Sample IDs makeExprSet(): makes an expression set object from supplied IDs, features and/or controlled vocabulary terms } \author{ <NAME> and <NAME> Maintainer: <NAME> <<EMAIL>> } \keyword{ data } \seealso{ There is also individual documentation for the major functions listed above. } \examples{ #first make an instance of a celsius Server object. celsius = new( "celsiusServer", celsiusUrl = "http://celsius.genomics.ctrl.ucla.edu" ); #list all of the platforms supported by the server platformTable = getPlatformData( celsius ); #list all the samples in the server that correspond to the #HG-U133_Plus_2 platform... celsius@platform = "HG-U133_Plus_2"; idList = listSamplesForPlatform( celsius ); #map some foreign IDs to the celsius servers internal sample IDs celsius@platform = 'HG-U133A'; id = c( "AEX:E-MEXP-402", "GSE6210" ); mapTable = mapIdToCelsius( celsius, id = id ); #get some samples data based on sample IDs celsius@verbose = TRUE; data = getSampleData( celsius, id = c( "SN:1005595" ) ); #get some data based on features (affymetrix probesets). data = getFeatureData( celsius, feature = c( "204412_s_at", "1316_at" ) ); #get some data that corresponds to both a set of Sample IDs AND some #features (affymetrix probesets) celsius@verbose = FALSE; data = getAssayData( celsius, id = c( "SN:1018351", "SN:1043233" ), feature = c( "201820_at", "202222_s_at", "202508_s_at", "203296_s_at" ) ); #get some information about controlled vocabulary terms #(ID is probably most important here) lungTerms = getCvterms( celsius, q = "lung", db = "MA" ); #get data on all samples (on one platform) for a particular controlled #vocabulary term data = getOntologyData( celsius, cvterm=c( "MA:0000415" ) ); #get data on all samples (on one platform) for a controlled vocabulary #term on specific samples data = getPhenoData( celsius, id = c( "SN:1000019", "SN:1000170", "SN:1005039", "SN:1004962" ), cvterm = c( "MA:0000415" ) ); #finally, we can make an expression set object straight from the #database using IDs and controlled vocabulary terms exprSet = makeExprSet( celsius, id = c( "SN:1000019", "SN:1000170", "SN:1005039" ), cvterm = c( "MA:0000415" ), feature = c( "201820_at", "202222_s_at", "202508_s_at", "203296_s_at" ) ); #Or you can also make an expression set using a foreign ID: celsius@platform = "Mouse430_2"; exprSet = makeExprSet(celsius, id = c( "GSE6210" ), cvterm = c( "MA:0000415" ), feature = c( "1415670_at", "1430537_at" ), mapids = TRUE ); #Finally, you can get raw annotations for an expression set by using the #annotations parameter celsius@platform = 'HG-U133A'; exprSet = makeExprSet( celsius, id = c( "SN:1000019", "SN:1000170", "SN:1005039" ), cvterm = c( "MA:0000415" ), feature = c( "201820_at", "202222_s_at", "202508_s_at", "203296_s_at" ), annotations = TRUE ); }
2813ad438d07f856455d815cdf8e03f469c76ed6
[ "Makefile", "R" ]
15
R
cran/celsius
8cf711f41aad02eb1dd041576318be1bd4549ffe
38b0b034cfc3334293b5e2e00b8739cd605b882d
refs/heads/main
<repo_name>gotooooo/nextjs-typescript-example<file_sep>/src/hooks/useFetchMovie.ts import { useEffect, useState } from 'react' import apiClient, { baseQuery } from '../utils/apiClient' import { MovieDetail } from '../types/Movie' const useFetchMovie = (title = 'Iron%20Man'): [MovieDetail, any] => { const initalState: MovieDetail = { Title: '', Year: '', Rated: '', Released: '', Runtime: '', Genre: '', Director: '', Writer: '', Actors: '', Plot: '', Language: '', Country: '', Awards: '', Poster: '', Ratings: [], Metascore: '', imdbRating: '', imdbVotes: '', imdbID: '', Type: '', DVD: '', BoxOffice: '', Production: '', Website: '' } const [res, setRes] = useState<MovieDetail>(initalState) const [err, setErr] = useState(null) useEffect(() => { const titleQuery = title !== '' ? `&t=${title}` : 'Iron%20Man' const fetch = async () => { await apiClient.get(`${baseQuery}${titleQuery}`) .then((res) => { setRes(res.data) }) .catch((err) => { setErr(err) }) } fetch() }, []) return [res, err] } export default useFetchMovie <file_sep>/src/hooks/useFetchMovies.ts import { useEffect, useState } from 'react' import apiClient, { baseQuery } from '../utils/apiClient' import { Movie, MovieWithId } from '../types/Movie' const useFetchMovies = (): [(input: string) => void, MovieWithId[], any] => { const [res, setRes] = useState<MovieWithId[]>([]) const [err, setErr] = useState<any>(null) const [keyword, setKeyword] = useState('man') const searchByKeyword = (input: string) => { setKeyword(input) } useEffect(() => { const keywordQuery = keyword !== '' ? `&s=${keyword}` : '&s=man' const fetch = async () => { await apiClient.get(`${baseQuery}${keywordQuery}`) .then((res) => { if (res.data.Response === 'True') { setErr(null) setRes(res.data.Search.map((movie: Movie, index: number) => { return { ...movie, id: index + 1 } })) } else { setErr('Movies Not Found') } }) .catch((err) => { setErr(err) }) } fetch() }, [keyword]) return [searchByKeyword, res, err] } export default useFetchMovies <file_sep>/src/types/Movie.ts type Movie = { Title: string Year: string imdbID: string Type: string Poster: string } type MovieWithId = Movie & { id: number } type MovieForDisplay = { Title: string Year: string Poster: string } type Rating = { Source: string Value: string } type MovieDetail = { Title: string Year: string Rated: string Released: string Runtime: string Genre: string Director: string Writer: string Actors: string Plot: string Language: string Country: string Awards: string Poster: string Ratings: Rating[] Metascore: string imdbRating: string imdbVotes: string imdbID: string Type: string DVD: string BoxOffice: string Production: string Website: string } export type { Movie, MovieWithId, MovieForDisplay, MovieDetail } <file_sep>/src/utils/apiClient.ts import axios from 'axios' // you SHOULD replace this apiKey // see http://www.omdbapi.com/apikey.aspx const apiKey = '86418ab1' const omdbBaseUrl = 'https://www.omdbapi.com/' const baseQuery = `?i=tt3896198&apikey=${apiKey}` const logging = false const apiClient = axios.create({ baseURL: omdbBaseUrl, timeout: 0, responseType: 'json' }) apiClient.interceptors.request.use((v) => { if (logging) console.log(JSON.stringify(v)) return v }) apiClient.interceptors.response.use((v) => { if (logging) console.log(JSON.stringify(v)) return v }) export default apiClient export { baseQuery } <file_sep>/README.md # nextjs typescript example
b48aa305accc2af99f361ec27497e174c09f5c15
[ "Markdown", "TypeScript" ]
5
TypeScript
gotooooo/nextjs-typescript-example
5b905c1d32bee5b73474e4e2eac95066840787c6
5f0e94c604356aae9a4a4dd02610c2d8581e0cd1
refs/heads/main
<file_sep>import contracts from './contracts' import { FarmConfig, QuoteToken } from './types' const farms: FarmConfig[] = [ { pid: 0, risk: 5, lpSymbol: 'MASH-BUSD LP', lpAddresses: { 97: '', 56: '0x87c182edb12f74d561519ab586205fe6cd75363a', }, tokenSymbol: 'MASH', tokenAddresses: { 97: '', 56: '0x<KEY>', }, quoteTokenSymbol: QuoteToken.BUSD, quoteTokenAdresses: contracts.busd, }, // { // pid: 20, // risk: 5, // lpSymbol: 'MASH-ETH LP', // lpAddresses: { // 97: '', // 56: '0x548997391C670A5179AF731A30e7C3aDA2f483e7', // }, // tokenSymbol: 'MASH', // tokenAddresses: { // 97: '', // 56: '0x<KEY>', // }, // quoteTokenSymbol: QuoteToken.ETH, // quoteTokenAdresses: contracts.eth, // }, { pid: 1, risk: 5, lpSymbol: 'MASH-BNB LP', lpAddresses: { 97: '', 56: '0x7621886ac71e985dbea4f3f563bbb5a7865876a8', }, tokenSymbol: 'MASH', tokenAddresses: { 97: '', 56: '0x<KEY>', }, quoteTokenSymbol: QuoteToken.BNB, quoteTokenAdresses: contracts.wbnb, }, { pid: 13, risk: 5, lpSymbol: 'MASH-BTCB LP', lpAddresses: { 97: '', 56: '0x0e70ff44229c6573cc020921345948ba4b5ec7cc', }, tokenSymbol: 'MASH', tokenAddresses: { 97: '', 56: '0x<KEY>', }, quoteTokenSymbol: QuoteToken.MASH, quoteTokenAdresses: contracts.cake, image: 'mash-btcb' }, { pid: 14, risk: 5, lpSymbol: 'MASH-VAULT LP', lpAddresses: { 97: '', 56: '0x9f8223b4b616aa9becb599c93b0430c6bef0443a', }, tokenSymbol: 'MASH', tokenAddresses: { 97: '', 56: '0x<KEY>', }, quoteTokenSymbol: QuoteToken.VAULT, quoteTokenAdresses: contracts.vault, }, { pid: 15, risk: 5, lpSymbol: 'MASH-CAKE LP', lpAddresses: { 97: '', 56: '0x16940bc578c30c7c10a2cf8a150b98a8b1cee152', }, tokenSymbol: 'MASH', tokenAddresses: { 97: '', 56: '0x<KEY>', }, quoteTokenSymbol: QuoteToken.MASH, quoteTokenAdresses: contracts.cake, image: 'mash-cake', }, { pid: 21, risk: 5, lpSymbol: 'MASH-PLUM LP', lpAddresses: { 97: '', 56: '0x9EC365D77dCF2b3230399a23D35aEF4318de710D', }, tokenSymbol: 'MASH', tokenAddresses: { 97: '', 56: '0<KEY>', }, quoteTokenSymbol: QuoteToken.PLUM, quoteTokenAdresses: contracts.plum, depositUrl: 'https://exchange.pancakeswap.finance/#/add/0x787732f27d18495494cea3792ed7946bbcff8db2/0xdE8eD8c9480EA12D050182AA99630B235dE30f83' }, { pid: 22, risk: 5, lpSymbol: 'MASH-SLIME LP', lpAddresses: { 97: '', 56: '0xb442780739037577920857DaD91259416b72DE7a', }, tokenSymbol: 'SLIME', tokenAddresses: { 97: '', 56: '0x23b06097F8FE2DD9D3dF094D3ee8319Daa8756c1', }, quoteTokenSymbol: QuoteToken.MASH, quoteTokenAdresses: contracts.cake, depositUrl: 'https://dex.slime.finance/#/add/0x23b06097F8FE2DD9D3dF094D3ee8319Daa8756c1/0x787732f27d18495494cea3792ed7946bbcff8db2', image: 'mash-slime' }, { pid: 23, risk: 5, lpSymbol: 'MASH-TAKO LP', lpAddresses: { 97: '', 56: '0xC6D926086b29774b10530ab9e02980e9586a061F', }, tokenSymbol: 'TAKO', tokenAddresses: { 97: '', 56: '0x2F3391AeBE27393aBa0a790aa5E1577fEA0361c2', }, quoteTokenSymbol: QuoteToken.MASH, quoteTokenAdresses: contracts.cake, depositUrl: 'https://dex.apeswap.finance/#/add/0x2F3391AeBE27393aBa0a790aa5E1577fEA0361c2/0x787732f27d18495494cea3792ed7946bbcff8db2', image: 'mash-tako' }, { pid: 2, risk: 3, lpSymbol: 'BNB-BUSD LP', lpAddresses: { 97: '', 56: '0x1b96b92314c44b159149f7e0303511fb2fc4774f', }, tokenSymbol: 'BNB', tokenAddresses: { 97: '', 56: '0<KEY>', }, quoteTokenSymbol: QuoteToken.BUSD, quoteTokenAdresses: contracts.busd, }, { pid: 3, risk: 2, lpSymbol: 'BTCB-BNB LP', lpAddresses: { 97: '', 56: '0x7561eee90e24f3b348e1087a005f78b4c8453524', }, tokenSymbol: 'BTCB', tokenAddresses: { 97: '', 56: '0<KEY>', }, quoteTokenSymbol: QuoteToken.BNB, quoteTokenAdresses: contracts.wbnb, }, { pid: 4, risk: 5, isTokenOnly: true, lpSymbol: 'MASH', lpAddresses: { 97: '', 56: '0x87c182edb12f74d561519ab586205fe6cd75363a', // VIKING-BUSD LP }, tokenSymbol: 'MASH', tokenAddresses: { 97: '', 56: '0<KEY>', }, quoteTokenSymbol: QuoteToken.BUSD, quoteTokenAdresses: contracts.busd, }, { pid: 11, risk: 1, isTokenOnly: true, lpSymbol: 'BUSD', lpAddresses: { 97: '', 56: '0x87c182edb12f74d561519ab586205fe6cd75363a', // VIKING-BUSD LP (BUSD-BUSD will ignore) }, tokenSymbol: 'BUSD', tokenAddresses: { 97: '', 56: '0xe9e7cea3dedca5984780bafc599bd69add087d56', }, quoteTokenSymbol: QuoteToken.BUSD, quoteTokenAdresses: contracts.busd, }, { pid: 10, risk: 3, isTokenOnly: true, lpSymbol: 'WBNB', lpAddresses: { 97: '', 56: '0x1b96b92314c44b159149f7e0303511fb2fc4774f', // BNB-BUSD LP }, tokenSymbol: 'WBNB', tokenAddresses: { 97: '', 56: '<KEY>', }, quoteTokenSymbol: QuoteToken.BUSD, quoteTokenAdresses: contracts.busd, }, { pid: 12, risk: 2, isTokenOnly: true, lpSymbol: 'BTCB', lpAddresses: { 97: '', 56: '0xb8875e207ee8096a929d543c9981c9586992eacb', // BTCB-BUSD LP }, tokenSymbol: 'BTCB', tokenAddresses: { 97: '', 56: '0<KEY>', }, quoteTokenSymbol: QuoteToken.BUSD, quoteTokenAdresses: contracts.busd, }, { pid: 5, risk: 4, isTokenOnly: true, lpSymbol: 'CAKE', lpAddresses: { 97: '', 56: '0x0ed8e0a2d99643e1e65cca22ed4424090b8b7458', // CAKE-BUSD LP }, tokenSymbol: 'CAKE', tokenAddresses: { 97: '', 56: '0x0e09fabb73bd3ade0a17ecc321fd13a19e81ce82', }, quoteTokenSymbol: QuoteToken.BUSD, quoteTokenAdresses: contracts.busd, }, { pid: 6, risk: 4, isTokenOnly: true, lpSymbol: 'BUNNY', lpAddresses: { 97: '', 56: '0xec7a69a3a5ee177c84855c86cc926ca0ba6275cc', // CAKE-BUSD LP }, tokenSymbol: 'BUNNY', tokenAddresses: { 97: '', 56: '0xc9849e6fdb743d08faee3e34dd2d1bc69ea11a51', }, quoteTokenSymbol: QuoteToken.BUSD, quoteTokenAdresses: contracts.busd, }, { pid: 9, risk: 10, isTokenOnly: true, lpSymbol: 'VAULT', lpAddresses: { 97: '', 56: '0xbeba8abb80bfa3c13ee4073d75a873e8a2b71dc3', // CAKE-BUSD LP }, tokenSymbol: 'VAULT', tokenAddresses: { 97: '', 56: '0xd456be0ff7007b3d8ad656136487a23e771f5762', }, quoteTokenSymbol: QuoteToken.BNB, quoteTokenAdresses: contracts.wbnb, }, { pid: 8, risk: 4, isTokenOnly: true, lpSymbol: 'XVS', lpAddresses: { 97: '', 56: '0x7d0ad8d3333814cf2ba2fb082dbc52d6b1a57c6e', // CAKE-BUSD LP }, tokenSymbol: 'XVS', tokenAddresses: { 97: '', 56: '0xcf<KEY>', }, quoteTokenSymbol: QuoteToken.BUSD, quoteTokenAdresses: contracts.busd, }, { pid: 17, risk: 5, lpSymbol: 'USDC-BUSD LP', lpAddresses: { 97: '', 56: '0x680Dd100E4b394Bda26A59dD5c119A391e747d18', }, tokenSymbol: 'USDC', tokenAddresses: { 97: '', 56: '0x8ac76a51cc950d9822d68b83fe1ad97b32cd580d', }, quoteTokenSymbol: QuoteToken.BUSD, quoteTokenAdresses: contracts.busd, }, { pid: 18, risk: 5, lpSymbol: 'USDT-BUSD LP', lpAddresses: { 97: '', 56: '0xc15fa3E22c912A276550F3E5FE3b0Deb87B55aCd', }, tokenSymbol: 'USDT', tokenAddresses: { 97: '', 56: '0x55d398326f99059ff775485246999027b3197955', }, quoteTokenSymbol: QuoteToken.BUSD, quoteTokenAdresses: contracts.busd, }, { pid: 24, risk: 5, lpSymbol: 'ETH-BUSD LP', lpAddresses: { 97: '', 56: '0xd9A0d1F5e02dE2403f68Bb71a15F8847A854b494', }, tokenSymbol: 'ETH', tokenAddresses: { 97: '', 56: '0x2170Ed0880ac9A7<KEY>', }, quoteTokenSymbol: QuoteToken.BUSD, quoteTokenAdresses: contracts.busd, }, { pid: 25, risk: 5, lpSymbol: 'DOT-WBNB LP', lpAddresses: { 97: '', 56: '0xbCD62661A6b1DEd703585d3aF7d7649Ef4dcDB5c', }, tokenSymbol: 'DOT', tokenAddresses: { 97: '', 56: '0x7083609fCE4d1d8Dc0C979AAb8c869Ea2C873402', }, quoteTokenSymbol: QuoteToken.BNB, quoteTokenAdresses: contracts.wbnb, image: 'dot-wbnb' }, { pid: 19, risk: 5, lpSymbol: 'DOGE-BUSD LP', lpAddresses: { 97: '', 56: '0x1Efcb446bFa553A2EB2fff99c9F76962be6ECAC3', }, tokenSymbol: 'DOGE', tokenAddresses: { 97: '', 56: '0<KEY>', }, quoteTokenSymbol: QuoteToken.BUSD, quoteTokenAdresses: contracts.busd, }, ] export default farms <file_sep>import { PoolConfig, QuoteToken, PoolCategory } from './types' const MASH = 'MASH'; const pools: PoolConfig[] = [ { sousId: 8, tokenName: 'Mash-SlimeV2 LP', stakingTokenName: QuoteToken[MASH], stakingTokenAddress: '0<KEY>', contractAddress: { 97: '0<KEY>', 56: '<KEY>', }, poolCategory: PoolCategory.CORE, projectLink: 'https://app.slime.finance/', harvest: true, isFinished: false, tokenPerBlock: '0.000856329483621793', sortOrder: 1, tokenDecimals: 18, startBlock: 7323438, endBlock: 7525038, withBurnFee:true, isLPStake:false, isLPReward:true, burnFee:0, slimeRounding:5, image: 'mash-slime' }, { sousId: 2, tokenName: 'MASH-BUSD LP', stakingTokenName: QuoteToken[MASH], stakingTokenAddress: '0<KEY>', contractAddress: { 97: '0x00ea75D83B3Cb954447BADc9F807631416933C48', 56: '0x00ea75D83B3Cb954447BADc9F807631416933C48', }, poolCategory: PoolCategory.CORE, projectLink: 'https://marshmallowdefi.com/', harvest: true, isFinished: false, tokenPerBlock: '0.002777777777777777', sortOrder: 1, tokenDecimals: 18, startBlock: 7386238, endBlock: 7587838, withBurnFee: true, isLPStake:false, isLPReward:true, burnFee: 3, slimeRounding: 5, image: 'mash-busd' }, { sousId: 1, tokenName: 'M<PASSWORD>', stakingTokenName: QuoteToken[MASH], stakingTokenAddress: '<KEY>', contractAddress: { 97: '0xB<KEY>', 56: '0xB<KEY>', }, poolCategory: PoolCategory.CORE, projectLink: 'https://marshmallowdefi.com/', harvest: true, isFinished: false, tokenPerBlock: '0.000124007936507936', sortOrder: 1, tokenDecimals: 18, startBlock: 7386238, endBlock: 7587838, withBurnFee: true, isLPStake:false, isLPReward:true, burnFee: 3, slimeRounding: 5, image: 'mash-bnb' }, { sousId: 3, tokenName: 'MASH-PLUM LP V2', stakingTokenName: QuoteToken[MASH], stakingTokenAddress: '0<KEY>', contractAddress: { 97: '0x99eC02568f4090A066c027d3172d317db0DD90a4', 56: '0x9<KEY>', }, poolCategory: PoolCategory.CORE, projectLink: 'https://plumcake.finance/', harvest: true, isFinished: false, tokenPerBlock: '0.002901785714285714', sortOrder: 1, tokenDecimals: 18, startBlock: 7488488, endBlock: 7690088, withBurnFee: true, isLPStake:false, isLPReward:true, burnFee: 3, slimeRounding: 5, image: 'mash-plum' }, { sousId: 4, tokenName: '<NAME>', stakingTokenName: QuoteToken[MASH], stakingTokenAddress: '0<KEY>', contractAddress: { 97: '0x56d93Aefaf766b8DA4a57b9805057BD2822fC73a', 56: '0x56d93Aefaf766b8DA4a57b9805057BD2822fC73a', }, poolCategory: PoolCategory.CORE, projectLink: 'https://apeswap.finance/', harvest: true, isFinished: false, tokenPerBlock: '0.008933531746031746', sortOrder: 1, tokenDecimals: 18, startBlock: 7516658, endBlock: 7718258, withBurnFee: true, isLPStake:false, isLPReward:true, isApe: true, burnFee: 3, slimeRounding: 5, image: 'mash-tako' }, { sousId: 9, tokenName: 'M<PASSWORD>', stakingTokenName: QuoteToken[MASH], stakingTokenAddress: '<KEY>', contractAddress: { 97: '0x99B75635683E874d8ea3e2696a25e25AeDFDC454', 56: '0x99B75635683E874d8ea3e2696a25e25AeDFDC454', }, poolCategory: PoolCategory.CORE, projectLink: 'https://app.slime.finance/', harvest: true, isFinished: false, tokenPerBlock: '0.002251984126984126', sortOrder: 1, tokenDecimals: 18, startBlock: 7544928, endBlock: 7746528, withBurnFee: true, isLPStake: false, isLPReward: true, burnFee: 0, slimeRounding: 5, image: 'mash-slime' }, { sousId: 10, tokenName: 'BTCB', stakingTokenName: QuoteToken[MASH], stakingTokenAddress: '0x<KEY>', contractAddress: { 97: '0x08fa76bAA1D731F54248d45Ab19F9E8642f49b2D', 56: '0x08fa76bAA1D731F54248d45Ab19F9E8642f49b2D', }, poolCategory: PoolCategory.CORE, projectLink: 'https://marshmallowdefi.com/', harvest: true, isFinished: false, tokenPerBlock: '0.000000258928571428', sortOrder: 1, tokenDecimals: 18, startBlock: 7605838, endBlock: 7807438, withBurnFee: true, isLPStake: false, isLPReward: false, burnFee: 3, slimeRounding: 5, image: 'mash-btcb' }, { sousId: 11, tokenName: 'CAKE', stakingTokenName: QuoteToken[MASH], stakingTokenAddress: '0x<KEY>', contractAddress: { 97: '0<KEY>', 56: '0<KEY>', }, poolCategory: PoolCategory.CORE, projectLink: 'https://pancakeswap.finance/', harvest: true, isFinished: false, tokenPerBlock: '0.000570436507936507', sortOrder: 1, tokenDecimals: 18, startBlock: 7605838, endBlock: 7807438, withBurnFee: true, isLPStake: false, isLPReward: false, burnFee: 3, slimeRounding: 5, image: 'mash-wcake' }, // { // sousId: 1, // tokenName: 'TWT', // stakingTokenName: QuoteToken.SYRUP, // stakingTokenAddress: '0x009cF7bC57584b7998236eff51b98A168DceA9B0', // contractAddress: { // 97: '0xAfd61Dc94f11A70Ae110dC0E0F2061Af5633061A', // 56: '0xAfd61Dc94f11A70Ae110dC0E0F2061Af5633061A', // }, // poolCategory: PoolCategory.CORE, // projectLink: 'https://trustwallet.com/', // harvest: true, // tokenPerBlock: '20', // sortOrder: 999, // isFinished: true, // tokenDecimals: 18, // }, ] export default pools <file_sep>import { MenuEntry } from '@pancakeswap-libs/uikit' const config: MenuEntry[] = [ { label: 'Home', icon: 'HomeIcon', href: '/', }, { label: 'Trade', icon: 'TradeIcon', items: [ { label: 'Exchange', href: 'http://exchange.marshmallowdefi.com/', }, { label: 'Liquidity', href: 'http://exchange.marshmallowdefi.com/#/pool', }, ], }, { label: 'Farms', icon: 'FarmIcon', href: '/farms', }, { label: 'Pools', icon: 'PoolIcon', href: '/pools', }, { label: 'SafeFarms', icon: 'FarmIcon', href: 'http://safefarms.marshmallowdefi.com/info', }, { label: 'Launch Pools', icon: 'PoolIcon', href: '/launch', }, // { // label: 'Audit', // icon: 'AuditIcon', // href: 'https://marshmallowdefi.com/Audit.pdf', // }, { label: 'Audit', icon: 'AuditIcon', items: [ { label: 'Techrate', href: '/Audit.pdf', }, { label: 'CERTIK', href: 'https://certik.org/projects/marshmallow', }, ], }, { label: 'Partnership', icon: 'AuditIcon', href: 'https://forms.gle/UdsH5aEU3JxroM5G9', }, { label: 'Token Info', icon: 'InfoIcon', items: [ { label: 'MASH BSC Scan', href: 'https://bscscan.com/token/<KEY>', }, { label: 'MASH Price Graph', href: 'https://dex.guru/token/<KEY>7D18495494cea3792ed7946BbCFF8db2-bsc', }, { label: 'TOFY BSC Scan', href: 'https://bscscan.com/token/0xe1f2d89a6c79b4242f300f880e490a70083e9a1c', }, { label: 'TOFY Price Graph', href: 'https://charts.bogged.finance/?token=0xe1f2d89a6c79b4242f300f880e490a70083e9a1c', } ], }, { label: 'More', icon: 'MoreIcon', items: [ { label: "Github", href: "https://github.com/MarshmallowSwap", }, { label: "Docs", href: "https://marshmallowswap.gitbook.io/marshmallowswap/", }, { label: "Blog", href: "https://medium.com/@marshmallowdefi", }, { label: "Telegram", href: "https://t.me/MarshmallowDeFi" }, ], }, ] export default config <file_sep>import { usePriceMashBusd } from 'state/hooks' import { getBalanceNumber } from 'utils/formatBalance' import { useTotalRewards } from './useTickets' const useLotteryTotalPrizesUsd = () => { const totalRewards = useTotalRewards() const totalMash = getBalanceNumber(totalRewards) const mashPriceBusd = usePriceMashBusd() return totalMash * mashPriceBusd.toNumber() } export default useLotteryTotalPrizesUsd <file_sep>export default { cake: { 56: '0x787732f27d18495494cea3792ed7946bbcff8db2', 97: '', }, masterChef: { 56: '0x8932a6265b01d1d4e1650feb8ac38f9d79d3957b', 97: '', }, wbnb: { 56: '0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c', 97: '', }, lottery: { 56: '', 97: '', }, lotteryNFT: { 56: '', 97: '', }, mulltiCall: { 56: '0x1ee38d535d541c55c9dae27b12edf090c608e6fb', 97: '0x67ADCB4dF3931b0C5Da724058ADC2174a9844412', }, busd: { 56: '0xe9e7cea3dedca5984780bafc599bd69add087d56', 97: '', }, wcake: { 56: '0x0e09fabb73bd3ade0a17ecc321fd13a19e81ce82', 97: '', }, btcb: { 56: '0x7130d2a12b9bcbfae4f2634d864a1ee1ce3ead9c', 97: '', }, vault: { 56: '0xd456be0ff7007b3d8ad656136487a23e771f5762', 97: '', }, plum: { 56: '0xdE8eD8c9480EA12D050182AA99630B235dE30f83', 97: '', }, slime: { 56: '0x23b06097F8FE2DD9D3dF094D3ee8319Daa8756c1', 97: '', }, tako: { 56: '0x2F3391AeBE27393aBa0a790aa5E1577fEA0361c2', 97: '' } }
62f103bf8cd77470ea259916a7e529f41ba331af
[ "TypeScript" ]
5
TypeScript
hnovellaapps/swapaliencat
fca3cb27c0a1435134bfa1f4a21ac4ff9a115b3d
4a786f5c4cc1e939ac077d825daec9e4bc4e0559
refs/heads/master
<file_sep>module.exports = { 'greetings': [ '¡Hola $user!', '¡Buenas $user!', '¡Hola $user! ¿Qué tal todo?', '¡Hola $user! Te echaba de menos...', '¡Buenas $user! Espero que no seas mi bot archienemigo disfrazado', '¡Hola $user! ¿Has traído comida?', '¡Hola $user! No te olvides de darme un abrazo, que no puedo vivir sin ellos', '¡Buenas $user! Recuerda mostrar tus respetos a los moderadores, seres supremos de este stream', '¡Hola $user! ¡Por ser el view 999.999 has ganado un trozo de pizza sin piña para compartir con quien tu quieras!', '¿Qué tal todo, $user?', '$owner y toda su comunidad quiere que sepas que te apreciamos y nos encanta verte por aquí, $user' ], 'sillazo': [ 'Sillazo $target' ], 'sillazo-generic': [ 'Sillazo genérico' ], 'bad-target': [ 'Necesitas poner el @' ], 'no-subscriber': [ 'Este comando es exclusivo para subs' ], 'preduel': [ '$user quiere tener un duelo contigo $target, escribe !aceptar o !denegar', '$target , has sido batido a un duelo por $user , ¿aceptas o tienes miedo? (!aceptar o !denegar)', '¡Atención $target! $user quiere solucionar vuestros problemas enfrentándoos en un intenso duelo , puedes !aceptar o !denegar el duelo ¿Qué harás?', '$target, parece ser que $user te reta a un duelo, en el cual , de una vez por todas, se sabrá cual de vosotros es realmente el más sabio , apuesto y fuerte , demuestra tu poder escribiendo !aceptar, o deja ver tu debilidad escribiendo !denegar' ], 'induel': [ 'Empieza el duelo entre $user y $target... $user empieza a arrepentirse de haber retado a $target pero ya no hay vuelta atrás', 'Comienza el duelo , $user se peina su cabello con aires de superioridad y $target lo mira con menosprecio ... ¿Quién será el ganador?', '$target se sitúa en frente de $user. Ambos cogen sus espadas y en sus ojos se puede ver que están impacientes por comenzar. ¿Quién será el espadachín más hábil?', '$user saca de su pantalón un arma que parece sacada de una peli de ciencia ficción, ni siquiera parece de este mundo , y para demostrar su poder, le dispara a una paloma y la convierte en cenizas, $target no se esperaba esa jugada, pero la esperanza es lo último que se pierde...', '$target se prepara para el combate haciendo abdominales mientras $user , confiado , se toma un café y un par de bollos ... ¿Tendrá $user la agilidad suficiente como para luchar y vencer después de comer?', '$user va de compras, necesita la ropa perfecta para dislumbrar a $target con su belleza y así ganar. ¿Será efectiva su técnica?', '$target ha tenido un problema de digestión y está pasando demasiado tiempo en el baño... ¿Llegará a tiempo para luchar contra $target?', '$user está nervioso, en realidad ve cierto atractivo en $target que no se atreve a decirle, pero ... ¿los que se peleán se desean ,no?... o eso cree $user', '$target y $user han decidido que su duelo será de comida. Quien antes termine los 2 kilos de alubias será el vencedor... 3..2..1 ...' ], 'postduel': [ 'Ha sido una intensa batalla, con lágrimas de alegría y de tristeza. Y el ganador es...$target', 'El duelo ha sido tan intenso que una densa niebla se ha levantado... Pero a lo lejos solo un cuerpo está en pie, al cabo de unos segundos confirmamos que el gran gandor es $target', 'Pasan las horas y no se sabe nada de los participantes... ¡Esperen! !Alguien ha aparecido victorioso! ... Y el gran vencedor de este duelo ha sido $target', 'Los dos participantes han aparecido tirados en el suelo... parece que esta vez no habrá ningún ganador. Aunque... ¡Alguien se está levantando! , a pesar de la dureza de la batalla hay un ganador , ¡Enorabuena $target!', 'Al cabo de un tiempo parece que nada cambia, los dos duelistas siguen en pie, aunque $target empieza a reirse fuertemente ¿Será que es el ganador?, ¡Y efectivamente, al cabo de unos segundos su rival no aguanta más y $target es la única persona en pie! ¡Enhorabuena!', 'En esta batalla tenemos un claro vencedor, de hecho no ha estado para nada reñida, podría considerarse abuso... ¡ $target, enorabuena, ha sido increíble como lo has derrotado en un abrir y cerrar de ojos!' ], }
ca4f14eac297ad67c5f4f96422d1db1cf87e353f
[ "JavaScript" ]
1
JavaScript
suraei/Chappie
1ef31b5b18185f063ea56c756337a641c0b38eab
60d8dadaa28dd566ba62deccd328a12394320231
refs/heads/master
<file_sep><?php namespace Admin\Controller; use Think\Controller; class ApiController extends Controller { public function index(){ $this->display(); } // 返回号码配置信息 private function getNumberInfo($year_number){ $_DBObj = M("lottery"); if (empty($year_number)){ $year_number = date('Y'); } $sql = 'select * from hp_year_number WHERE year = 2017'; $numberInfo = M()->query($sql); // 数组前加入一个空数组,数组下标对应,开奖数字 array_unshift($numberInfo,array()); return $numberInfo; } public function open_lottery(){ /** * 判断值是否为整数 * 是否为空 * 号码不能相等 * 跟新是否成功 * */ if ($_REQUEST){ if ( intval($_REQUEST['lottery_id']) ){ $lottery_id = intval($_REQUEST['lottery_id']); } if ( intval($_REQUEST['year_number']) ){ $year_number = intval($_REQUEST['year_number']); } if ( intval($_REQUEST['number_01']) ){ $data['number_01'] = intval($_REQUEST['number_01']); } if ( intval($_REQUEST['number_02']) ){ $data['number_02'] = intval($_REQUEST['number_02']); } if ( intval($_REQUEST['number_03']) ){ $data['number_03'] = intval($_REQUEST['number_03']); } if ( intval($_REQUEST['number_04']) ){ $data['number_04'] = intval($_REQUEST['number_04']); } if ( intval($_REQUEST['number_05']) ){ $data['number_05'] = intval($_REQUEST['number_05']); } if ( intval($_REQUEST['number_06']) ){ $data['number_06'] = intval($_REQUEST['number_06']); } if ( intval($_REQUEST['number_lottery']) ){ $data['number_lottery'] = intval($_REQUEST['number_lottery']); } // 检测是否有重复 if ( count($data) != count(array_unique($data)) ) { $response = array('errMsg' => 'number repeat;', 'payload' => ''); }else{ $numberInfo = $this->getNumberInfo($year_number); $data['lottery_data'] = json_encode(array( 'number_01' => $numberInfo[$data['number_01']], 'number_02' => $numberInfo[$data['number_02']], 'number_03' => $numberInfo[$data['number_03']], 'number_04' => $numberInfo[$data['number_04']], 'number_05' => $numberInfo[$data['number_05']], 'number_06' => $numberInfo[$data['number_06']], 'number_lottery' => $numberInfo[$data['number_lottery']], )); if($data['number_01'] && $data['number_02'] && $data['number_03'] && $data['number_04'] && $data['number_05'] && $data['number_06'] && $data['number_lottery']){ $data['status'] = 0; } else { $data['status'] = 1; } $_DBObj = M('lottery'); $row = $_DBObj->where('lottery_id =' .$lottery_id)->save($data); if($row){ $res = $_DBObj->where('lottery_id =' .$lottery_id)->find(); $response = array('errMsg' => 'ok', 'payload' => $res); }else{ $response = array('errMsg' => 'update fail', 'payload' => ''); } } } else { $response = array('errMsg' => 'no data', 'payload' => ''); } echo json_encode($response); } }<file_sep><?php namespace Admin\Controller; use Think\Controller; class IndexController extends Controller { public function index(){ if (session('uid') && session('username')){ $this->display(); } else { $this->display('User/login'); } } }<file_sep><?php namespace Admin\Controller; use Think\Controller; class UserController extends Controller { public function index(){ $this->display(); } // 用户登录 public function login(){ if ($_POST){ $data['username'] = $_POST['username']; $data['passwd'] = md5( $_POST['passwd'] ); $_DBObj = M('administration'); $res = $_DBObj->field('uid, admin')->where($data)->find(); if ($res){ session('uid', $res['uid']); session('username', md5($res['admin']) ); $this->success('登录成功'); }else{ echo "帐号密码错误!"; } } else { echo "访问错误"; } } }<file_sep><?php namespace Admin\Controller; use Think\Controller; class LotteryController extends Controller { public function index(){ $_DBObj = M('lottery'); if (!empty($_GET['lottery_id'])){ $row = $_DBObj->field('lottery_id, year_number, lottery_time, open_time, number_01, number_02, number_03, number_04, number_05, number_06, number_lottery')->where('lottery_id='.$_GET['lottery_id'])->find(); }else{ $row = $_DBObj->field('lottery_id, year_number, lottery_time, open_time, number_01, number_02, number_03, number_04, number_05, number_06, number_lottery')->where('status = 2')->order('lottery_id desc')->find(); } $this->assign('lottery', $row); $this->display(); } // 添加开奖 public function addLottery(){ if ($_POST){ $_DBObj = M('lottery'); $data['lottery_time'] = $_POST['lottery_time']; $data['year_number'] = $_POST['year_number']; $data['open_time'] = $_POST['open_time']; $data['status'] = 2; $data['lottery_id'] = date("Y",strtotime($_POST['open_time'])).$data['lottery_time']; $row = $_DBObj->data($data)->add(); if ($row){ $response = array('errMsg' => 'add: ok', 'payload' => ''); }else{ $response = array('errMsg' => 'add: error', 'payload' => ''); } echo json_encode($response); }else{ $this->display(); } } // 开奖历史 public function history(){ $_DBObj = M('lottery'); $rowList = $_DBObj->select(); $lotteryData = $rowList; foreach($rowList as $key => $val){ $lotteryData[$key]['lottery_data'] = json_decode($val['lottery_data'], true); $lotteryData[$key]['number_01'] = $lotteryData[$key]['lottery_data']['number_01']; $lotteryData[$key]['number_02'] = $lotteryData[$key]['lottery_data']['number_02']; $lotteryData[$key]['number_03'] = $lotteryData[$key]['lottery_data']['number_03']; $lotteryData[$key]['number_04'] = $lotteryData[$key]['lottery_data']['number_04']; $lotteryData[$key]['number_05'] = $lotteryData[$key]['lottery_data']['number_05']; $lotteryData[$key]['number_06'] = $lotteryData[$key]['lottery_data']['number_06']; $lotteryData[$key]['number_lottery'] = $lotteryData[$key]['lottery_data']['number_lottery']; } $this->assign('lotteryList', $lotteryData); // dump($lotteryData); $this->display(); } // 返回号码配置信息 private function getNumberInfo($number_year = 0){ if ($number_year = 0){ $number_year = data('Y'); } $_DBObj = M("lottery"); $sql = 'select * from hp_year_number WHERE year = '.$number_year; $numberInfo = M()->query($sql); // 数组前加入一个空数组,数组下标对应,开奖数字 array_unshift($numberInfo,array()); return $numberInfo; } }<file_sep><?php namespace Home\Controller; use Think\Controller; class ApiController extends Controller { public function index() { /** * 先查询状态为 1 正在开奖的 * 如果没有查询最后一个完成开奖的状态 0 */ $_DBObj = M("lottery"); // 查询开奖中 status = 1 $row = $_DBObj->where('status = 1')->order('lottery_id desc')->find(); if($row){ $lottery = $this->getNumberInfo($row); $res = array('errMsg' => 'success', 'data' => $lottery); } else { // 查询最后一期完成开奖 $row = $_DBObj->where('status = 0')->order('lottery_id desc')->find(); if($row){ $lottery = $this->getNumberInfo($row); $res = array('errMsg' => 'success', 'data' => $lottery); } else { $res = array('errMsg' => 'fail', 'data' => '没有记录'); } } echo json_encode($res); } // 传入开奖一维数组数组,返回数组信息 public function getNumberInfo($arr){ $sql = 'select * from hp_year_number WHERE year = '.$arr['year_number']; $numberInfo = M()->query($sql); // 数组前加入一个空数组,数组下标对应,开奖数字 array_unshift($numberInfo,array()); if ($arr['number_01']){ $arr['number_01'] = $numberInfo[$arr['number_01']]; } if ($arr['number_02']){ $arr['number_02'] = $numberInfo[$arr['number_02']]; } if ($arr['number_03']){ $arr['number_03'] = $numberInfo[$arr['number_03']]; } if ($arr['number_04']){ $arr['number_04'] = $numberInfo[$arr['number_04']]; } if ($arr['number_05']){ $arr['number_05'] = $numberInfo[$arr['number_05']]; } if ($arr['number_06']){ $arr['number_06'] = $numberInfo[$arr['number_06']]; } if ($arr['number_lottery']){ $arr['number_lottery'] = $numberInfo[$arr['number_lottery']]; } return $arr; } }<file_sep><?php namespace Home\Controller; use Think\Controller; class IndexController extends Controller { public function index(){ $this->display(); } // 开奖历史 public function history(){ $_DBObj = M('lottery'); $rowList = $_DBObj->select(); $lotteryData = $rowList; foreach($rowList as $key => $val){ $lotteryData[$key]['lottery_data'] = json_decode($val['lottery_data'], true); $lotteryData[$key]['number_01'] = $lotteryData[$key]['lottery_data']['number_01']; $lotteryData[$key]['number_02'] = $lotteryData[$key]['lottery_data']['number_02']; $lotteryData[$key]['number_03'] = $lotteryData[$key]['lottery_data']['number_03']; $lotteryData[$key]['number_04'] = $lotteryData[$key]['lottery_data']['number_04']; $lotteryData[$key]['number_05'] = $lotteryData[$key]['lottery_data']['number_05']; $lotteryData[$key]['number_06'] = $lotteryData[$key]['lottery_data']['number_06']; $lotteryData[$key]['number_lottery'] = $lotteryData[$key]['lottery_data']['number_lottery']; } $this->assign('lotteryList', $lotteryData); // print_r($lotteryData); $this->display(); } }
87af61c6b654adaa6ba3c1366108ec5b7b464ac3
[ "PHP" ]
6
PHP
CengMing/lottery
7cb8ae5d4e6b9cd44e4da37a7976568bb908becb
8cc69fcadb5b2b5121f541ac046f43a33b2b657d
refs/heads/master
<repo_name>SeekingPlumBlossoms/observer<file_sep>/src/main/java/com/gy/yb/example/Observer.java package com.gy.yb.example; import com.gy.yb.example.WeatherSubject; public interface Observer { public void update(WeatherSubject weatherSubject); public void setObservserName(); public String getObserverName(); } <file_sep>/src/main/java/com/gy/yb/Client.java package com.gy.yb; public class Client { public static void main(String[] args ){ //1.创建目标 ConcreteWeatherSubject concreteWeatherSubject=new ConcreteWeatherSubject(); //2.创建观察者 ConcreteObserver observerGirl=new ConcreteObserver(); observerGirl.setObserverName("女友"); observerGirl.setRemindThing("约会"); ConcreteObserver observerMum=new ConcreteObserver(); observerMum.setObserverName("妈妈"); observerMum.setRemindThing("购物"); //3.注册观察者 concreteWeatherSubject.attach(observerGirl); concreteWeatherSubject.attach(observerMum); //4.发布目标 concreteWeatherSubject.setWeatherContent("明天天气晴,气温很好"); } } <file_sep>/src/main/java/com/gy/yb/WeatherSubject.java package com.gy.yb; import java.util.ArrayList; import java.util.List; public class WeatherSubject { private List<Observer> observers=new ArrayList<>(); public void attach(Observer observer){ observers.add(observer); } public void detach(Observer observer){ observers.remove(observer); } protected void notifyObservers(){ observers.forEach((observer -> observer.update(this))); } }
9f3ef32725b29ce770af806f0c8312af0fa51b27
[ "Java" ]
3
Java
SeekingPlumBlossoms/observer
b5827cb49e575cc65489a8860029367f058d040c
8457a86d2b0f2ba776c9f55db4226783fb0032d1
refs/heads/master
<repo_name>Meanche/meanche.github.io<file_sep>/ShopProject/app.js let productsCount = document.getElementById("products-count") let addToCartButtons = document.querySelectorAll(".add-to-cart") for(var i = 0; i < addToCartButtons.length; i++) { addToCartButtons[i].addEventListener("click", function(){ var prevProductsCount = +productsCount.textContent productsCount.textContent = prevProductsCount + 1 }) }
34a5fba8ac6ca2ee341484dc5869a01498b1fa57
[ "JavaScript" ]
1
JavaScript
Meanche/meanche.github.io
a33d5d07a5223c591cad10ef1f7cc1a8ffc6b055
df0a6f3d0e5b4c75c2fd969819b9b2325df3c312
refs/heads/master
<file_sep>import winreg class Registry(): def __init__(self,path,user=winreg.HKEY_CURRENT_USER): self.User = user self.Path = path self.Valid = self.Load() def Load(self): try: return winreg.OpenKey(self.User,self.Path,access=winreg.KEY_ALL_ACCESS) except FileNotFoundError as e: return None def Create(self): winreg.CreateKey(self.User,self.Path) def __setitem__(self,item,value): winreg.SetValueEx(self.Valid,item,0,winreg.REG_SZ,value) def __getitem__(self,item=''): try: return winreg.QueryValueEx(self.Valid,item)[0] except FileNotFoundError as e: return None <file_sep>#!/bin/bash command="" statement="while true; do CMDS; done" screen -S "Program" bash -c "${statement/CMDS/$command}"<file_sep>import os import sys import time from pathlib import Path from tkinter import * from tkinter.filedialog import askopenfilenames files = askopenfilenames(initialdir=os.getcwd()) if files: for filename in files: file = Path(filename) # Apply Rule Here rule = filename.lower() file.rename( rule ) <file_sep>#!/bin/bash screen -d -r "Program" -X quit<file_sep>Mods = [] WorkshopItems = [] def Add(name,id): Mods.append(name) WorkshopItems.append(id) if __name__ == "__main__": Add("Skateboard","2728300240") Add("SurvivorRadioV3.4","2224576262") print( 'Mods=' +";".join(Mods) ) print( 'WorkshopItems=' +";".join(WorkshopItems) ) <file_sep>import datetime def calculate_sales_goal(): goal = int(input("Enter the sales goal: ")) current_sales = int(input("Enter the current sales: ")) current_date = datetime.datetime.now() last_day = (current_date.replace(day=28) + datetime.timedelta(days=4)).replace(day=1) - datetime.timedelta(days=1) remaining_days = 0 days_worked = 0 for day in range(current_date.day, last_day.day + 1): if current_date.replace(day=day).weekday() != 6: remaining_days += 1 days_worked += 1 gap = abs((current_sales - goal) / days_worked) boxes = int(gap) if gap >= 1 else 0 print(f"Remaining days (excluding Sundays and off days): {remaining_days}") print(f"Gap: {gap:.2f}") print(f"Boxes: {boxes:.1f}") if __name__ == "__main__": print("Sales Goal Calculator") calculate_sales_goal() <file_sep>local sounds = { innocent = { "innocent1.mp3", "innocent2.mp3", "innocent3.mp3", "innocent4.mp3", "innocent5.mp3" }, traitor = { "traitor1.mp3", "traitor2.mp3", "traitor3.mp3", "traitor4.mp3", "traitor5.mp3" }, timeout = { "time.mp3" } } if SERVER then util.AddNetworkString("EndMusic") url = ( "http://" .. string.Split(game.GetIPAddress(),":")[1] .. ":80" .. "/audio/" ) hook.Add("TTTEndRound", "endroundurl", function(result) if result == WIN_TRAITOR then file, _ = table.Random(sounds.traitor) elseif result == WIN_INNOCENT then file, _ = table.Random(sounds.innocent) else file, _ = table.Random(sounds.timeout) end net.Start("EndMusic") net.WriteString( url .. file) net.Broadcast() end) else CreateClientConVar( "music_vol", "1", true, false ) hook.Add("TTTSettingsTabs", "setting", function(dtabs) dsettings = dtabs:GetItems()[2].Panel dform = vgui.Create("DForm") dform:SetName("EndRound Music") dform:NumSlider("Volume", "music_vol", 0, 1, 2 ) dsettings:AddItem(dform) end) net.Receive( "EndMusic", function() url = net.ReadString() music_vol = GetConVar("music_vol"):GetFloat() if music_vol != 0 then sound.PlayURL(url, "", function(station) if ( IsValid( station ) ) then station:Play() station:SetVolume(music_vol) end end) end end) end <file_sep>import os import sys from crontab import CronTab class CronJob: """ id - A unique string identifier. cmd - The console command. time - A string slice or special variable. state - The state of the cron job. * None = Remove if it exists. * True = Enable. * False = Disable. user - Specify user to run on (default: root) """ def __init__(self, id, cmd, time, state=True, user="root" ): self.Cron = CronTab(user) self.Validate(id,cmd) self.SetTime(time) self.SetEnabled(state) self.Save(state) def Validate(self,id,cmd): self.Job = next( self.Cron.find_comment(id), None) if self.Job is None: self.Job = self.Cron.new(comment=id,command=cmd) self.Job.every_reboot() self.SetCommand(cmd) def SetCommand(self,cmd): self.Job.set_command(cmd) def SetTime(self,time): self.Job.slices.setall(time) def SetEnabled(self,state): self.Job.enable(state) def Save(self,state): if state is None: self.Cron.remove(self.Job) self.Cron.write() return # Example Of Usage CronJob( "Test", "touch test", "@reboot", state = True ) <file_sep>import math import sys import os def format_trunc(number): truncated_number = int(number * 100) / 100 formatted_number = "{:.3f}".format(truncated_number) return formatted_number N = int( input( "Opps for AA: ") or "0" ) SMB = int( input("SMB to Deduct: ") or "0" ) N = ( N - SMB ) PTR = float( input("PTR(%): ") ) / 100 PTR_Numb = ( N * PTR ) for X in range(1,50): PTR = (PTR_Numb+X) / (N+X) print( X, str( format_trunc(PTR) ) ) if( PTR >= 0.70 ): sys.exit() <file_sep>import os import sys import json from pathlib import Path class JsonDictConfig: def __init__(self, dir='config.json'): self.Path = Path(dir) self.Read() def Read(self): self.Table = json.loads(self.Path.read_text()) def Encode(self): return json.dumps(self.Table, indent=4) def __getitem__(self, item): return self.Table.get(item, None) def __setitem__(self, item, value): self.Table[item] = value def __delitem__(self, item): if item in self.Table: del self.Table[item] def Write(self): self.Path.write_text(self.Encode()) def __repr__(self): return repr(self.Table) <file_sep>AddCSLuaFile() ENT.Type = "anim" ENT.Base = "base_gmodentity" ENT.PrintName = "Merky_Nade" ENT.Category = "Other" ENT.Editable = true ENT.Spawnable = true ENT.AdminOnly = false ENT.Delay = 5 function ENT:SpawnFunction( ply, tr, ClassName ) if ( !tr.Hit ) then return end local size = math.random( 16, 48 ) local ent = ents.Create( ClassName ) ent:SetPos( tr.HitPos + tr.HitNormal * size ) ent:Spawn() ent:Activate() return ent end function ENT:Initialize() self:SetModel( "models/Combine_Helicopter/helicopter_bomb01.mdl" ) self:PhysicsInit(SOLID_VPHYSICS) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid(SOLID_VPHYSICS) local phys = self:GetPhysicsObject() if (phys:IsValid()) then phys:Wake() end if !SERVER then return end self.Nade = ents.Create("env_explosion") self.Nade:SetPos( self:GetPos() ) self.Nade:SetParent( self ) self.Nade:SetKeyValue( "iMagnitude", "100" ) self.Nade:Spawn() timer.Simple( self.Delay, function() self:Explode() end) end function ENT:Explode() if !SERVER then return end SafeRemoveEntityDelayed(self,0.1) self.Nade:Fire("Explode", 0, 0 ) end <file_sep>using System; using System.Linq; using System.Collections.Generic; using System.Timers; using Sandbox.Common.ObjectBuilders; using Sandbox.Definitions; using Sandbox.Game; using Sandbox.Game.WorldEnvironment; using Sandbox.Game.SessionComponents; using Sandbox.Game.Gui; using Sandbox.ModAPI; using VRage.ObjectBuilders; using VRage.Collections; using VRage.Game; using VRage.Game.Components; using VRage.Game.ModAPI; using VRage.ModAPI; using VRageMath; public class Merky : MySessionComponentBase { public Merky() { var timer = new System.Timers.Timer(); timer.Elapsed += new ElapsedEventHandler(this.Think); timer.Interval = 1000; // 1 second timer.Enabled = true; } public void Think(object sender, ElapsedEventArgs args) { var SpawnPlanet = MyAPIGateway.Session.GetWorld().Planets[0]; var pos = SpawnPlanet.PositionAndOrientation.Value.Position; var players = new List<IMyPlayer>(); MyAPIGateway.Players.GetPlayers(players); foreach (var ply in players) { var identify = ply.Identity; var character = ply.Character; if (!character.IsDead) { var max = (SpawnPlanet.Radius + SpawnPlanet.AtmosphereRadius); var dist = Vector3D.Distance(pos, ply.GetPosition()); if (dist >= max) { character.Kill(); } } } } } <file_sep>#!/bin/bash cd "$(dirname "$0")" # This makes it semi-portable tar -zcvf backup/$(date +%s).tar world
966e4e62432a38322bc05987ef3b0f39348ba3f7
[ "C#", "Python", "Shell", "Lua" ]
13
Python
TheMerkyShadow/Random
4b13357ea4ed3d85b75a4b0d6e0c52fc75d54e6c
e39eeacb093a067e1eaeb42150cbdfb7949ca5ea
refs/heads/master
<repo_name>dtorresxp/odoo-nginx-le<file_sep>/odoo-nginx-le.sh #! /bin/bash ################################################################################################### # # Author: <NAME> # Company: Calyx Servicios S.A. # License: AGPL-3 # Description: Script aims to transform a non-proxied Odoo into a SSL protected one (NGINX + LE). # ################################################################################################### # Run some stuff to fix broken packages, still wondering why... sudo dpkg --configure -a && sudo apt-get -f install # Now add the repositories Certbot. echo "Adding Certbot repositories..." sudo add-apt-repository ppa:certbot/certbot -y # Let’s begin by updating the package lists and installing software-properties-common and NGINX. # Commands separated by && will run in succession. echo "Updating and installing software-properties-common and NGINX..." sudo apt-get update && sudo apt-get install software-properties-common nginx certbot python-certbot-nginx -y # Go to NGINX sites-* path and delete all. After that, create a dummy server for ACME challenge. echo "Removing default NGINX servers and creating server for ACME challenge..." cd /etc/nginx/sites-enabled/ && sudo rm default cd /etc/nginx/sites-available/ && sudo rm default sudo wget -O odoo https://raw.githubusercontent.com/sotolucas/odoo-nginx-le/master/etc/nginx/sites-available/no-ssl && sudo ln -s /etc/nginx/sites-available/odoo /etc/nginx/sites-enabled/odoo # Ask user to input domains. read -p "Ingrese el dominio principal: " PRI_DOM read -p "Ingrese los dominios secundarios separados por coma SIN espacios: " SEC_DOM # Build strings with all domains to use on Certbot request and NGINX server_name block. ALL_DOM="$PRI_DOM,$SEC_DOM" # Replace example domain with domains provided by user. echo "Replacing example domain with domains provided by user..." sudo sed -i "s/foo-bar.calyx-cloud.com.ar/$ALL_DOM/g" odoo # As NGINX doesn't accepts comma separated values, we remove them. sudo sed -i "s/,/ /g" odoo # Restart NGINX server. echo "Restarting NGINX..." sudo service nginx restart # Issue SSL Let's Encrypt! certificate. echo "Issuing SSL Let's Encrypt! certificate..." sudo certbot --nginx --non-interactive --domains $ALL_DOM --agree-tos -m <EMAIL> # Go to NGINX sites-* path and delete all. After that, create definitive server. echo "Removing ACME challenge NGINX servers and creating server for Odoo..." cd /etc/nginx/sites-enabled/ && sudo rm odoo cd /etc/nginx/sites-available/ && sudo rm odoo sudo wget -O odoo https://raw.githubusercontent.com/sotolucas/odoo-nginx-le/master/etc/nginx/sites-available/wh-ssl && sudo ln -s /etc/nginx/sites-available/odoo /etc/nginx/sites-enabled/odoo # Make this in to parts as replacing all foo-bar with ALL_DOM would add it to LE certs path, so... # First replace example server name for all domains that we need to listen to. # Then, replace example server name for main domain which is also certificate's main domain. sudo sed -i "s/server_name foo-bar.calyx-cloud.com.ar/server_name $ALL_DOM/g" odoo sudo sed -i "s/foo-bar.calyx-cloud.com.ar/$PRI_DOM/g" odoo # As NGINX doesn't accepts comma separated values, we remove them. sudo sed -i "s/,/ /g" odoo # Restart NGINX server. echo "Restarting NGINX..." sudo service nginx restart
bfb3191ee2563591b92823dd989c94882fab6972
[ "Shell" ]
1
Shell
dtorresxp/odoo-nginx-le
3b738c074e8e619c657f43401758e6dbeae2faf7
cec124a5d6f9d2e361087013219174e9b01a38c7
refs/heads/master
<repo_name>neoexa/VilledeMontpellier<file_sep>/app/src/main/java/neoexa/com/VilledeMontpellier/ProfileActivity.java package neoexa.com.VilledeMontpellier; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import neoexa.com.VilledeMontpellier.Model.Shop; import neoexa.com.VilledeMontpellier.Model.User; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.*; import java.util.ArrayList; public class ProfileActivity extends AppCompatActivity implements View.OnClickListener { private TextView usernameTextView; private TextView telephoneTextView; private TextView addressTextView; private DatabaseReference mDatabase; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile); //Input usernameTextView = (TextView) findViewById(R.id.usernameTV); telephoneTextView = (TextView) findViewById(R.id.telephoneTV); addressTextView = (TextView) findViewById(R.id.addressTV); //Button findViewById(R.id.profileBtn).setOnClickListener(this); //Database reference mDatabase = FirebaseDatabase.getInstance().getReference(); } //validation du formulaire private boolean validateInput() { boolean valid = true; String username = usernameTextView.getText().toString(); if (TextUtils.isEmpty(username)) { usernameTextView.setError("Requis."); valid = false; } else { usernameTextView.setError(null); } String telephone = telephoneTextView.getText().toString(); if (TextUtils.isEmpty(telephone)) { telephoneTextView.setError("Requis."); valid = false; } else { telephoneTextView.setError(null); } String address = addressTextView.getText().toString(); if (TextUtils.isEmpty(address)) { addressTextView.setError("Requis."); valid = false; } else { addressTextView.setError(null); } return valid; } private void registerUser(DatabaseReference mDatabase, String username, String telephone, String address){ if (!validateInput()) { return; } FirebaseUser authUser = FirebaseAuth.getInstance().getCurrentUser(); if (authUser != null) { String email = authUser.getEmail(); String uid = authUser.getUid(); User user = new User(username, email, telephone, address); mDatabase.child("users").child(uid).setValue(user); Intent toProfileIntent = new Intent (ProfileActivity.this, HomeActivity.class); ProfileActivity.this.startActivity(toProfileIntent); } else { Toast.makeText(ProfileActivity.this, "Erreur utilisateur non connecté !", Toast.LENGTH_SHORT).show(); } } @Override public void onClick(View v) { int i = v.getId(); if (i == R.id.profileBtn) { registerUser(mDatabase, usernameTextView.getText().toString(), telephoneTextView.getText().toString(), addressTextView.getText().toString()); } } } <file_sep>/app/src/main/java/neoexa/com/VilledeMontpellier/fragment/AdminShopsFragment.java package neoexa.com.VilledeMontpellier.fragment; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; 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; import java.util.ArrayList; import neoexa.com.VilledeMontpellier.AddShopActivity; import neoexa.com.VilledeMontpellier.Model.Shop; import neoexa.com.VilledeMontpellier.Model.ShopAdapter; import neoexa.com.VilledeMontpellier.R; import neoexa.com.VilledeMontpellier.ShopsActivity; public class AdminShopsFragment extends Fragment implements View.OnClickListener { FloatingActionButton addShop; private String uid; private DatabaseReference mDatabase; private ListView shopsListView; private ArrayList<Shop> myShops = new ArrayList<>(); private ShopAdapter adapter; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_admin_shops, container, false); //Current user FirebaseUser authUser = FirebaseAuth.getInstance().getCurrentUser(); if (authUser != null) { uid = authUser.getUid(); } else { Toast.makeText(getActivity(), "Erreur utilisateur non connecté !", Toast.LENGTH_SHORT).show(); } //Database mDatabase = FirebaseDatabase.getInstance().getReference("shops"); //Views rootView.findViewById(R.id.fab_add_shop).setOnClickListener(this); shopsListView = (ListView) rootView.findViewById(R.id.adminshoplv); //Events //Listener on DB mDatabase.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { myShops.clear(); for (DataSnapshot shopsSnapshot : dataSnapshot.getChildren()) { Shop retrievedShop = shopsSnapshot.getValue(Shop.class); if (retrievedShop.userId == uid){ myShops.add(retrievedShop);} } //Adapteur adapter = new ShopAdapter(getActivity(), myShops, myShops); shopsListView.setAdapter(adapter); } @Override public void onCancelled(DatabaseError databaseError) { } }); return rootView; } @Override public void onClick(View v) { int i = v.getId(); if (i == R.id.fab_add_shop) { Intent toProfileIntent = new Intent (getActivity(), AddShopActivity.class); AdminShopsFragment.this.startActivity(toProfileIntent); } } } <file_sep>/app/src/main/java/neoexa/com/VilledeMontpellier/Model/User.java package neoexa.com.VilledeMontpellier.Model; import java.util.ArrayList; public class User { public String username ; public String email; public String telephone ; public String address; public User() { // Default constructor required for calls to DataSnapshot.getValue(User.class) } public User(String username, String email, String telephone, String address) { this.username = username; this.email = email; this.telephone = telephone; this.address = address; } public String getUsername() { return username; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public void setUsername(String username) { this.username = username; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } } <file_sep>/app/src/main/java/neoexa/com/VilledeMontpellier/AddShopActivity.java package neoexa.com.VilledeMontpellier; import android.app.ProgressDialog; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.TextView; import android.widget.Toast; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import java.util.ArrayList; import java.util.List; import fr.ganfra.materialspinner.MaterialSpinner; import neoexa.com.VilledeMontpellier.Model.Shop; public class AddShopActivity extends AppCompatActivity implements View.OnClickListener { private MaterialSpinner categorySpinner; private TextView nameTextView; private TextView addressTextView; private String selectedCategory; private ProgressDialog pd; private String uid; private DatabaseReference mDatabase; List<String> categories = new ArrayList<String>(); ArrayAdapter<String> adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_shop); initCategoriesArray(); //Spinner&Adapter categorySpinner = (MaterialSpinner) findViewById(R.id.catSpinner); adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,categories); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); categorySpinner.setAdapter(adapter); //TextViews nameTextView = (TextView) findViewById(R.id.newName); addressTextView =(TextView) findViewById(R.id.newAddress); //Button findViewById(R.id.addShopBtn).setOnClickListener(this); //Database reference mDatabase = FirebaseDatabase.getInstance().getReference(); //Current User FirebaseUser authUser = FirebaseAuth.getInstance().getCurrentUser(); if (authUser != null) { uid = authUser.getUid();} else { Toast.makeText(AddShopActivity.this, "Erreur utilisateur non connecté !", Toast.LENGTH_SHORT).show(); } //Events categorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if(position != -1){ selectedCategory = categorySpinner.getItemAtPosition(position).toString(); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } private boolean validateInput(){ boolean valid = true; if (TextUtils.isEmpty(selectedCategory)) { valid = false; } String name = nameTextView.getText().toString(); if (TextUtils.isEmpty(name)) { nameTextView.setError("Requis."); valid = false; } else { nameTextView.setError(null); } String adress = addressTextView.getText().toString(); if (TextUtils.isEmpty(adress)) { addressTextView.setError("Requis."); valid = false; } else { addressTextView.setError(null); } return valid; } private void initCategoriesArray() { categories.add("finance"); categories.add("hotel"); categories.add("market"); categories.add("food"); } private void postShop(DatabaseReference mDatabase, String name, String address, String category){ String key = mDatabase.child("shops").push().getKey(); Log.e("Key", key); Shop newShop = new Shop(uid, name, address, category); mDatabase.child("shops").child(key).setValue(newShop); Intent toProfileIntent = new Intent (AddShopActivity.this, AdminActivity.class); AddShopActivity.this.startActivity(toProfileIntent); } @Override public void onClick(View v) { int i = v.getId(); if (i == R.id.addShopBtn) { postShop(mDatabase, nameTextView.getText().toString(), addressTextView.getText().toString(), selectedCategory); } } } <file_sep>/app/src/main/java/neoexa/com/VilledeMontpellier/CalendarActivity.java package neoexa.com.VilledeMontpellier; import android.content.Intent; import android.provider.CalendarContract; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.firebase.ui.database.FirebaseRecyclerAdapter; import com.firebase.ui.database.FirebaseRecyclerOptions; import com.google.firebase.auth.FirebaseAuth; 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.MutableData; import com.google.firebase.database.Query; import com.google.firebase.database.Transaction; import neoexa.com.VilledeMontpellier.Model.Event; import neoexa.com.VilledeMontpellier.viewholder.EventViewHolder; public class CalendarActivity extends AppCompatActivity { private static final String TAG = "CalendarActivity"; private DatabaseReference mDatabase; private FirebaseRecyclerAdapter<Event, EventViewHolder> mAdapter; private RecyclerView mRecycler; private LinearLayoutManager mManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_calendar); mDatabase = FirebaseDatabase.getInstance().getReference(); mRecycler = (RecyclerView) findViewById(R.id.events_list); mRecycler.setHasFixedSize(true); mManager = new LinearLayoutManager(this); mManager.setReverseLayout(true); mManager.setStackFromEnd(true); mRecycler.setLayoutManager(mManager); // Set up FirebaseRecyclerAdapter with the Query Query postsQuery = getQuery(mDatabase); FirebaseRecyclerOptions options = new FirebaseRecyclerOptions.Builder<Event>() .setQuery(postsQuery, Event.class) .build(); mAdapter = new FirebaseRecyclerAdapter<Event, EventViewHolder>(options) { @Override public EventViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) { LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext()); return new EventViewHolder(inflater.inflate(R.layout.item_event, viewGroup, false)); } @Override protected void onBindViewHolder(EventViewHolder viewHolder, int position, final Event model) { final DatabaseReference eventRef = getRef(position); // Set click listener for the whole event view final String postKey = eventRef.getKey(); viewHolder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Launch CALENDARaCTIVITY addEvent(v); } }); // Bind Event to ViewHolder, setting OnClickListener viewHolder.bindToEvent(model, new View.OnClickListener() { @Override public void onClick(View cardViewBtn) { DatabaseReference globalEventRef = mDatabase.child("events").child(eventRef.getKey()); DatabaseReference userEventRef = mDatabase.child("user-events").child(model.uid).child(eventRef.getKey()); // Run two transactions onAddCalendarClicked(globalEventRef); onAddCalendarClicked(userEventRef); } }); } }; mRecycler.setAdapter(mAdapter); } @Override public void onStart() { super.onStart(); if (mAdapter != null) { mAdapter.startListening(); } } @Override public void onStop() { super.onStop(); if (mAdapter != null) { mAdapter.stopListening(); } } public void addEvent(View v){ Intent intent = new Intent(Intent.ACTION_INSERT) .setData(CalendarContract.Events.CONTENT_URI); if (intent.resolveActivity(getPackageManager()) != null) { startActivity(intent); } } public String getUid() { return FirebaseAuth.getInstance().getCurrentUser().getUid(); } public Query getQuery (DatabaseReference databaseReference){ Query q = databaseReference.child("events").limitToFirst(10); return q; } private void onAddCalendarClicked(DatabaseReference eventRef) { eventRef.runTransaction(new Transaction.Handler() { @Override public Transaction.Result doTransaction(MutableData mutableData) { Event e = mutableData.getValue(Event.class); if (e == null) { return Transaction.success(mutableData); } if (e.people.containsKey(getUid())) { // Uncheck the event and remove self from people e.people.remove(getUid()); } else { // Check the post and add self to people e.peopleCount = e.peopleCount + 1; e.people.put(getUid(), true); } // Set value and report transaction success mutableData.setValue(e); return Transaction.success(mutableData); } @Override public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) { // Transaction completed Log.d(TAG, "eventTransaction:onComplete:" + databaseError); } }); } } <file_sep>/app/src/main/java/neoexa/com/VilledeMontpellier/AddEventActivity.java package neoexa.com.VilledeMontpellier; import android.app.DatePickerDialog; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import java.util.Calendar; import java.util.Date; import neoexa.com.VilledeMontpellier.Model.Event; public class AddEventActivity extends AppCompatActivity implements View.OnClickListener { private TextView event_title; private TextView event_desc; private TextView event_address; private TextView event_begin; private TextView event_end; private Date eBegin; private Date eEnd; private DatePickerDialog.OnDateSetListener beginDateSetListener; private DatePickerDialog.OnDateSetListener endDateSetListener; private DatabaseReference mDatabase; private FirebaseUser authUser; private String uid; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_event); //TextViews event_title = (TextView) findViewById(R.id.event_title); event_desc = (TextView) findViewById(R.id.event_desc); event_address = (TextView) findViewById(R.id.event_address); event_begin = (TextView) findViewById(R.id.event_begin); event_end = (TextView) findViewById(R.id.event_end); //DatePicker event_begin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Calendar cal = Calendar.getInstance(); int day = cal.get(Calendar.DAY_OF_MONTH); int month = cal.get(Calendar.MONTH); int year = cal.get(Calendar.YEAR); DatePickerDialog dialog = new DatePickerDialog(AddEventActivity.this, R.style.NeoTheme, beginDateSetListener, year, month, day); dialog.show(); } }); beginDateSetListener = new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) { int mMonth = month + 1; eBegin = new Date(year , mMonth, dayOfMonth); String bd = dayOfMonth + "/" + mMonth + "/" + year; event_begin.setText(bd); } }; event_end.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Calendar cal = Calendar.getInstance(); int day = cal.get(Calendar.DAY_OF_MONTH); int month = cal.get(Calendar.MONTH); int year = cal.get(Calendar.YEAR); DatePickerDialog dialog = new DatePickerDialog(AddEventActivity.this, R.style.NeoTheme, endDateSetListener, year, month, day); dialog.show(); } }); endDateSetListener = new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) { int mMonth = month + 1; eEnd = new Date(year, mMonth, dayOfMonth); String bd = dayOfMonth + "/" + mMonth + "/" + year; event_end.setText(bd); } }; //Button findViewById(R.id.addEventBtn).setOnClickListener(this); //Database reference mDatabase = FirebaseDatabase.getInstance().getReference(); //Current User authUser = FirebaseAuth.getInstance().getCurrentUser(); if (authUser != null) { uid = authUser.getUid();} else { Toast.makeText(AddEventActivity.this, "Erreur utilisateur non connecté !", Toast.LENGTH_SHORT).show(); } } private boolean validateInput(){ boolean valid = true; String title = event_title.getText().toString(); if (TextUtils.isEmpty(title)) { event_title.setError("Requis."); valid = false; } else { event_title.setError(null); } String address = event_address.getText().toString(); if (TextUtils.isEmpty(address)) { event_address.setError("Requis."); valid = false; } else { event_address.setError(null); } if (eBegin.toString() == null) { event_begin.setError("Requis."); valid = false; } else { event_begin.setError(null); } return valid; } private void postEvent(){ if (!validateInput()) { return; } String title = event_title.getText().toString(); String desc = event_desc.getText().toString(); String address = event_address.getText().toString(); String key = mDatabase.child("events").push().getKey(); Event newEvent = new Event(uid, title, desc, address, eBegin, eEnd); mDatabase.child("events").child(key).setValue(newEvent); Intent toProfileIntent = new Intent (AddEventActivity.this, AdminActivity.class); AddEventActivity.this.startActivity(toProfileIntent); } @Override public void onClick(View v) { int i = v.getId(); if (i == R.id.addEventBtn){ postEvent(); } } } <file_sep>/app/src/main/java/neoexa/com/VilledeMontpellier/ShopsActivity.java package neoexa.com.VilledeMontpellier; import android.annotation.SuppressLint; import android.content.Intent; import android.content.pm.PackageManager; import android.location.Location; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.AppCompatImageButton; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Filter; import android.widget.ImageButton; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SearchView; import android.widget.Toast; import com.google.android.gms.location.FusedLocationProviderClient; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; 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; import java.util.ArrayList; import neoexa.com.VilledeMontpellier.Model.Shop; import neoexa.com.VilledeMontpellier.Model.ShopAdapter; import neoexa.com.VilledeMontpellier.Model.User; public class ShopsActivity extends AppCompatActivity { private SearchView searchView; private ImageButton noFilterBtn; private ImageButton foodFilterBtn; private ImageButton marketFilterBtn; private ImageButton hotelFilterBtn; private ImageButton financeFilterBtn; private ImageButton favoriteFilterBtn; private ImageButton nearbyFilterBtn; private ListView shopsListView; private ArrayList<Shop> shops = new ArrayList<>(); private ArrayList<Shop> favoriteShops = new ArrayList<>(); private ShopAdapter adapter; private DatabaseReference mDatabase; private DatabaseReference mDatabaseFav; private String uid; public static final int LOCATION_REQUEST = 1; private FusedLocationProviderClient mFusedLocationClient; private Location currentLoc; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_shops); //Current User FirebaseUser authUser = FirebaseAuth.getInstance().getCurrentUser(); if (authUser != null) { uid = authUser.getUid(); } else { Toast.makeText(ShopsActivity.this, "Erreur utilisateur non connecté !", Toast.LENGTH_SHORT).show(); } //Location mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this); //References searchView = (SearchView) findViewById(R.id.search_bar); noFilterBtn = (ImageButton) findViewById(R.id.noFilter_btn); foodFilterBtn = (ImageButton) findViewById(R.id.food_filter_btn); marketFilterBtn = (ImageButton) findViewById(R.id.market_filter_btn); hotelFilterBtn = (ImageButton) findViewById(R.id.hotel_filter_btn); financeFilterBtn = (ImageButton) findViewById(R.id.finance_filter_btn); favoriteFilterBtn = (ImageButton) findViewById(R.id.favorite_filter_btn); nearbyFilterBtn = (ImageButton) findViewById(R.id.nearby_filter_btn); shopsListView = (ListView) findViewById(R.id.shopsListView); //Database mDatabase = FirebaseDatabase.getInstance().getReference("shops"); mDatabaseFav = FirebaseDatabase.getInstance().getReference("favorites/" + uid); //Listener on DB mDatabase.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { shops.clear(); for (DataSnapshot shopsSnapshot : dataSnapshot.getChildren()) { Shop retrievedShop = shopsSnapshot.getValue(Shop.class); shops.add(retrievedShop); } //Adapteur adapter = new ShopAdapter(ShopsActivity.this, shops, favoriteShops); shopsListView.setAdapter(adapter); } @Override public void onCancelled(DatabaseError databaseError) { } }); mDatabaseFav.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { favoriteShops.clear(); for (DataSnapshot shopsSnapshot : dataSnapshot.getChildren()) { Shop favShop = shopsSnapshot.getValue(Shop.class); favoriteShops.add(favShop); } //Adapteur adapter = new ShopAdapter(ShopsActivity.this, shops, favoriteShops); shopsListView.setAdapter(adapter); } @Override public void onCancelled(DatabaseError databaseError) { } }); //Get last known location if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION}, LOCATION_REQUEST); return; } mFusedLocationClient.getLastLocation() .addOnSuccessListener(this, new OnSuccessListener<Location>() { @Override public void onSuccess(Location location) { // Got last known location. In some rare situations this can be null. if (location != null) { currentLoc = new Location(""); currentLoc.setLongitude(location.getLongitude()); currentLoc.setLatitude(location.getLatitude()); } } }); // Events shopsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Toast.makeText(ShopsActivity.this, "Fragement", Toast.LENGTH_SHORT).show(); } }); shopsListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { Shop clickedShop = (Shop) parent.getAdapter().getItem(position); String key = mDatabaseFav.push().getKey(); mDatabaseFav.child(key).setValue(clickedShop); Toast.makeText(ShopsActivity.this, "Added to favorites", Toast.LENGTH_SHORT).show(); return true; } }); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { return false; } @Override public boolean onQueryTextChange(String newText) { adapter.getFilter().filter(newText); return false; } }); noFilterBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { adapter.noFilter(); } }); foodFilterBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { adapter.filterRestaurant(); } }); marketFilterBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { adapter.filterMarket(); } }); hotelFilterBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { adapter.filterHotel(); } }); financeFilterBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { adapter.filterFinance(); } }); favoriteFilterBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { adapter.filterFavorite(); } }); nearbyFilterBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { adapter.filterNearby(currentLoc); } }); } }
887cfa87d8a5de99bac740a36c617d43f040801b
[ "Java" ]
7
Java
neoexa/VilledeMontpellier
e7ba0d1fc065d4577a8fd939cbd210490ea9e1ed
2c2f2bd1db893f48f29c0323a723a374e4087539
refs/heads/main
<file_sep>window.Seed = (function () { const entries = [ { id: 1, title: '<NAME>', description: 'The lake is a long way from here.', url: '#', votes: 12, avatar: 'assets/images/avatars/jack.jpg', image: 'assets/images/entries/image-yellow.png', }, { id: 2, title: '<NAME>', description: 'The sun had set and so had his dreams.', url: '#', votes: 7, avatar: 'assets/images/avatars/jane.jpg', image: 'assets/images/entries/image-red.png', }, { id: 3, title: '<NAME>', description: 'Red is greener than purple, for sure.', url: '#', votes: 9, avatar: 'assets/images/avatars/donna.png', image: 'assets/images/entries/image-grey.png', }, { id: 4, title: '<NAME>', description: 'In that instant, everything changed.', url: '#', votes: 10, avatar: 'assets/images/avatars/maria.png', image: 'assets/images/entries/image-blue.png', }, ]; return {entries: entries}; }());<file_sep># UpVote app build with Vue.js and Bulma * Vue.js - https://vuejs.org/ * Bulma - https://bulma.io/ * Font Awesome - https://fontawesome.com/ ## Running the code Open `index.html` in your favourite browser.
09f2363d4178a6ff6c9333678cd0bd393f99abba
[ "JavaScript", "Markdown" ]
2
JavaScript
PIPONCHOV/upvote-vuejs
f3aa1613bba5c20f00c2c1609bcc926cbb348ef8
d69a1261ad0d73fbfb8c59e31d54266f2df7db9c
refs/heads/master
<file_sep>import os, time, sys import log_run as lr import subprocess import json path = "/home/git/RPI-timelapse-api/" def execCmd(inCmd): proc = subprocess.Popen([inCmd], stdout=subprocess.PIPE, shell=True) (out, err) = proc.communicate() return out def start(): print "Starting" os.system("python "+path+"test.py &") r = execCmd("ps ax | grep test.py") g = open(path+'logs.txt', 'w') g.write(r) g.close() f = open(path+'log_run.py', 'w') f.write('running=True\n') f.write('pid=\'\'\n') f.write('params=[]\n') f.close() def stop(): print "Stopping" f = open(path+'log_run.py', 'w') f.write('running=False\n') f.write('pid=\'\'\n') f.write('params=[]\n') f.close() def status(): data = { 'running':str(lr.running), 'pid':'32' } print json.dumps(data) if __name__ == '__main__': if len(sys.argv) <= 1 or len(sys.argv) >= 3: print "Error, need exactly one argument: START | STOP | STATUS." else: if sys.argv[1] == 'START': if not lr.running: start() else: print "Already running, prick" elif sys.argv[1] == 'STOP': if lr.running: stop() else: print "Not running, why would you want to stop it asshole ?" elif sys.argv[1] == 'STATUS': status() <file_sep>import time i=0 while True and i<6: print "hola que tal #" + str(i) time.sleep(3) i+=1 <file_sep>var dataJSON; $(function(){ }); function start() { $('#switch-start').attr('disabled', true); $.ajax({ type: 'GET' , url: "api/start.php", contentType: "application/x-www-form-urlencoded;charset=utf-8", data:{}, datatype: "json", async: true, success : function(data) { dataJSON = JSON.parse(data); console.log(dataJSON); $('#results').text(""); var res = ""; $.each(dataJSON, function(i, item){ res += "<strong>" +i+ "</strong>: " + item + " <br/>"; }); $('#switch-start').attr('disabled', false); $(res).appendTo('#results'); }, fail : function() { alert( "error" ); }, always : function() { alert( "finished" ); } }); } function stop() { $('#switch-stop').attr('disabled', true); $.ajax({ type: 'GET' , url: "api/stop.php", contentType: "application/x-www-form-urlencoded;charset=utf-8", data:{}, datatype: "json", async: true, success : function(data) { dataJSON = JSON.parse(data); console.log(dataJSON); $('#results').text(""); var res = ""; $.each(dataJSON, function(i, item){ res += "<strong>" +i+ "</strong>: " + item + " <br/>"; }); $('#switch-stop').attr('disabled', false); $(res).appendTo('#results'); }, fail : function() { alert( "error" ); }, always : function() { alert( "finished" ); } }); } <file_sep># RPI-timelapse-api Web services to make timelapses via the RPI <file_sep><?php /*$command = escapeshellcmd('date'); $output = shell_exec($command); echo $output; echo "<br />";*/ $path = '/home/git/RPI-timelapse-api/'; $command = escapeshellcmd('python ' . $path . 'run.py STOP'); $descriptorspec = array( 0 => array("pipe", "r"), // stdin is a pipe that the child will read from 1 => array("pipe", "w"), // stdout is a pipe that the child will write to 2 => array("file", "/tmp/error-output.txt", "a") // stderr is a file to write to ); $process = proc_open($command, $descriptorspec, $pipes, null, null); sleep(1); $output = shell_exec('python ' . $path . 'run.py STATUS'); echo ($output); ?> <file_sep>running=False pid='' params=[]
3ce0e2eabc651f29d754040b9a6377b0208b8f6b
[ "JavaScript", "PHP", "Python", "Markdown" ]
6
Python
Lysuo/RPI-timelapse-api
663dc079fbed618451384764895dc3b5b726c272
ee2f5074a11b541cb2e6728603a18a41a660313d
refs/heads/master
<file_sep> function helloWorld(name: string, age: number) { console.log(`hello world! your name: ${name}, your age: ${age}`); } console.log(helloWorld('levin', 1));
f33e7d2d71ff0a391d366fb382a493861d96874f
[ "TypeScript" ]
1
TypeScript
szlevinli/studyTypeScript
2fb7ef78609d30470784448d87eca194508c581d
0eac1e28bc0b54097e3a3e74d61895d283141bd8