text:
package org.alljoyn.ioe.controlpanelservice.communication;

import java.util.Map;

/**
 * Used to notify observers about the connection manager events
 */
public interface ConnManagerEventsListener {

	/**
	 * The method is launched when the event happened in ConnectionManager
	 * @param eventType The type of the event
	 * @param args
	 */
	public void connMgrEventOccured(ConnManagerEventType eventType, Map<String, Object> args);
}

redpajama_set_name: RedPajamaGithub


text:
package com.m7md.models;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

import java.math.BigInteger;
import java.util.List;

/**
 * Created by m7md on 4/25/16.
 */
public class HibernateImpl {
    private static final SessionFactory ourSessionFactory;
    private static final ServiceRegistry serviceRegistry;

    static {
        try {
            Configuration configuration = new Configuration();
            configuration.configure();

            serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
            ourSessionFactory = configuration.buildSessionFactory(serviceRegistry);
        } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static Session getSession() throws HibernateException {
        return ourSessionFactory.openSession();
    }

    /**
     * @param session supply it with the current session
     * @return The Last Inserted Row Id.
     */
    public static BigInteger getLastId(Session session) {
        return (BigInteger) session.createSQLQuery("SELECT LAST_INSERT_ID()")
                .uniqueResult();
    }

    /**
     * @param entity The table type
     * @param <T>
     * @return The Last Inserted Row Id
     */
    public static <T> BigInteger insert(T entity) {

        Session session = getSession();
        Transaction transaction = session.beginTransaction();
        session.save(entity);
        transaction.commit();

        BigInteger lastId = getLastId(session);
        session.close();
        return lastId;

    }

    /**
     * @param <T> to specify the return type
     * @param entity The table type
     * @return The List of Rows In The Parameter Entity
     */
    public static <T> List<T> fetchRows(String entity) {

        Session session = getSession();
        Transaction transaction = session.beginTransaction();
        List<T> data = session.createQuery("from " + entity).list();
        transaction.commit();
        session.close();
        return data;

    }

}


text:
//
// CallTests.cs
//
// Author(s):
//       Alessio Parma <alessio.parma@gmail.com>
//
// Copyright (c) 2012-2016 Alessio Parma <alessio.parma@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

namespace DIBRIS.Dessert.Tests.Events
{
    using NUnit.Framework;
    using SimEvents = System.Collections.Generic.IEnumerable<SimEvent>;

    sealed class CallTests : TestBase
    {
        SimEvents Caller_NoExitValue()
        {
            var w = new IntWrapper();
            w.X += 5;
            yield return Env.Timeout(5);
            var call = Env.Call(Called_NoExitValue(Env.ActiveProcess, w));
            yield return call;
            Assert.AreEqual(35, w.X);
            Assert.AreEqual(null, call.Value);
        }

        SimEvents Caller_NoReturnValue_Nested()
        {
            var call = Env.Call(Caller_NoExitValue());
            yield return call;
        }

        SimEvents Called_NoExitValue(SimProcess caller, IntWrapper w)
        {
            Assert.AreSame(caller, Env.ActiveProcess);
            w.X += 10;
            yield return Env.Timeout(10);
            Assert.AreSame(caller, Env.ActiveProcess);
            w.X += 20;
            yield return Env.Timeout(20);
            Assert.AreSame(caller, Env.ActiveProcess);
        }

        SimEvents Caller_WithExitValue()
        {
            var w = new IntWrapper();
            w.X += 5;
            yield return Env.Timeout(5);
            var call = Env.Call(Called_WithExitValue(Env.ActiveProcess, w));
            yield return call;
            Assert.AreEqual(35, w.X);
            Assert.AreEqual(w, call.Value);
        }

        SimEvents Called_WithExitValue(SimProcess caller, IntWrapper w)
        {
            Assert.AreSame(caller, Env.ActiveProcess);
            w.X += 10;
            yield return Env.Timeout(10);
            Assert.AreSame(caller, Env.ActiveProcess);
            w.X += 20;
            yield return Env.Timeout(20);
            Assert.AreSame(caller, Env.ActiveProcess);
            yield return Env.Exit(w);
            Assert.Fail();
        }

        SimEvents Caller_WithExitValue_Nested()
        {
            var call = Env.Call(Caller_WithExitValue());
            yield return call;
        }

        SimEvents FibonacciFunc(int n)
        {
            if (n <= 0) {
                yield return Env.Exit(0);
            } else if (n == 1) {
                yield return Env.Exit(1);
            } else {
                var call = Env.Call<int>(FibonacciFunc(n - 1));
                yield return call;
                var n1 = call.Value;
                call = Env.Call<int>(FibonacciFunc(n - 2));
                yield return call;
                var n2 = call.Value;
                yield return Env.Exit(n1 + n2);
            }
        }

        [TestCase(0, 0), TestCase(1, 1), TestCase(2, 1), TestCase(3, 2), TestCase(4, 3), TestCase(5, 5), TestCase(6, 8)]
        public void Fibonacci(int n, int result)
        {
            var fib = Env.Process(FibonacciFunc(n));
            Env.Run();
            Assert.AreEqual(result, fib.Value);
        }

        sealed class IntWrapper
        {
            public int X;
        }

        [Test]
        public void NoReturnValue()
        {
            Env.Process(Caller_NoExitValue());
            Env.Run();
        }

        [Test]
        public void NoReturnValue_Nested()
        {
            Env.Process(Caller_NoReturnValue_Nested());
            Env.Run();
        }

        [Test]
        public void WithReturnValue()
        {
            Env.Process(Caller_WithExitValue());
            Env.Run();
        }

        [Test]
        public void WithReturnValue_Nested()
        {
            Env.Process(Caller_WithExitValue_Nested());
            Env.Run();
        }
    }
}


text:
<?php

namespace ECM\Bundle\ModuleBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Gedmo\Mapping\Annotation as Gedmo;

/**
 * Sponsor
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="ECM\Bundle\ModuleBundle\Entity\SponsorRepository")
 * @ORM\Entity(repositoryClass="Gedmo\Sortable\Entity\Repository\SortableRepository")
 * @ORM\HasLifecycleCallbacks
 */
class Sponsor {

    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="titre", type="string", length=255)
     */
    private $titre;

    /**
     * @var string
     *
     * @ORM\Column(name="urlImage", type="text", nullable=true)
     */
    private $urlImage;

    /**
     * @var string
     *
     * @ORM\Column(name="lien", type="text")
     */
    private $lien;

    /**
     * @var integer
     *
     *@Gedmo\SortablePosition
     * @ORM\Column(name="position", type="integer")
     */
    private $position;

    /**
     * @var date
     *
     * @ORM\Column(name="updated", type="date", nullable=true)
     */
    private $updated;

    /**
     * @var file
     *
     */

    private $image;

    public function getImage() {
        return $this->image;
    }

    public function setImage(UploadedFile $image = null) {
        $this->image = $image;
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId() {
        return $this->id;
    }

    /**
     * Get titre
     *
     * @return string
     */
    public function getTitre()
    {
        return $this->titre;
    }

    /**
     * Set titre
     *
     * @param string $titre
     * @return Sponsor
     */
    public function setTitre($titre) {
        $this->titre = $titre;

        return $this;
    }

    /**
     * Get urlImage
     *
     * @return string
     */
    public function getUrlImage()
    {
        return $this->urlImage;
    }

    /**
     * Set urlImage
     *
     * @param string $urlImage
     * @return Sponsor
     */
    public function setUrlImage($urlImage) {
        $this->urlImage = $urlImage;

        return $this;
    }

    /**
     * Get lien
     *
     * @return string
     */
    public function getLien()
    {
        return $this->lien;
    }

    /**
     * Set lien
     *
     * @param string $lien
     * @return Sponsor
     */
    public function setLien($lien) {
        $this->lien = $lien;

        return $this;
    }

    public function getAbsolutePath() {
        return null === $this->urlImage ? null : $this->getUploadRootDir() . '/' . $this->urlImage;
    }

    protected function getUploadRootDir() {
        // le chemin absolu du répertoire où les documents uploadés doivent être sauvegardés
        return __DIR__ . '/../../../../../web/' . $this->getUploadDir();
    }

    protected function getUploadDir() {
        // on se débarrasse de « __DIR__ » afin de ne pas avoir de problème lorsqu'on affiche
        // le document/image dans la vue.
        return 'images/sponsors';
    }

    public function getWebPath()
    {
        return null === $this->urlImage ? null : $this->getUploadDir() . '/' . $this->urlImage;
    }

    /**
     * @ORM\PrePersist()
     * @ORM\PreUpdate()
     */
    public function upload()
    {
        if (null === $this->image) {
            return;
        }
        $this->urlImage = $this->image->getClientOriginalName();
        // s'il y a une erreur lors du déplacement du fichier, une exception
        // va automatiquement être lancée par la méthode move(). Cela va empêcher
        // proprement l'entité d'être persistée dans la base de données si
        // erreur il y a
        $this->image->move($this->getUploadRootDir(), $this->image->getClientOriginalName());
        $this->image = null;
    }

//    /**
//     * @ORM\PostRemove()
//     */
//    public function removeUpload()
//    {
//        if ($image = $this->getAbsolutePath()) {
//            unlink($image);
//        }
//    }

    /**
     * @ORM\PrePersist()
     * @ORM\PreUpdate()
     */
    public function refreshUpdated() {
        $this->setUpdated(new \DateTime("now"));
//        $this->urlImage = $this->image->getClientOriginalName();
    }

    /**
     * Get updated
     *
     * @return \DateTime
     */
    public function getUpdated()
    {
        return $this->updated;
    }

    /**
     * Set updated
     *
     * @param \DateTime $updated
     * @return Sponsor
     */
    public function setUpdated($updated)
    {
        $this->updated = $updated;

        return $this;
    }

    /**
     * Get position
     *
     * @return integer
     */
    public function getPosition()
    {
        return $this->position;
    }

    /**
     * Set position
     *
     * @param integer $position
     * @return Sponsor
     */
    public function setPosition($position)
    {
        $this->position = $position;

        return $this;
    }
}


text:
package com.nerdapplabs;

import java.io.IOException;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import com.nerdapplabs.registerEvent.OnRegistrationCompleteEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.nerdapplabs.model.Asset;
import com.nerdapplabs.model.AssetRequest;
import com.nerdapplabs.dao.AssetDao;
import com.nerdapplabs.dao.VerificationTokenRepository;
import com.nerdapplabs.model.*;
import com.nerdapplabs.service.*;

@Controller
@SessionAttributes("email")
public class UserController {

	@Autowired
	private UserServiceImplement userService;

	@Autowired
	UserService service;

	@Autowired
	AssetDao assetDao;

	@Autowired
	VerificationTokenRepository tokenDao;

	@Autowired
	ApplicationEventPublisher eventPublisher;

	@Autowired
	private MessageSource messageSource;

	@Autowired
	private MessageSource messages;

	int count = 0;
	private static final String EMAIL_PATTERN = ".+@+nerdapplabs+.com";
	private String temp;
	private Long tempid;

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login() {
		return "login";
	}

	@RequestMapping(value = "/asset", method = RequestMethod.GET)
	public ModelAndView asset(@ModelAttribute("asset") Asset asset) {

		ModelAndView model = new ModelAndView();
		List<NewModel> listmodelname = service.listModel();
		model.addObject("listmodelname", listmodelname);
		List<ModelAccessory> listmodelaccessory = service.listModelAccessory();
		model.addObject("listmodelaccessory", listmodelaccessory);
		List<ModelConsumable> listmodelconsumable = service.listModelConsumable();
		model.addObject("listmodelconsumable", listmodelconsumable);
		List<Company> listcompany = service.listCompany();
		model.addObject("listcompany", listcompany);
		List<Supplier> listsupplier = service.listSupplier();
		model.addObject("listsupplier", listsupplier);
		List<Status> liststatus = service.listStatus();
		model.addObject("liststatus", liststatus);
		model.setViewName("asset");
		return model;

	}

	@RequestMapping(value = "/newmodel", method = RequestMethod.GET)
	public String newModelAccessory() {
		return "addmodel";
	}

	@RequestMapping(value = "/changePassword{email}", method = RequestMethod.GET)
	public String changePasssword(@ModelAttribute("changepassword") User user) {
		return "changepassword";
	}

	@RequestMapping(value = "/newcompany", method = RequestMethod.GET)
	public String newCompany() {
		return "addcompany";
	}

	@RequestMapping(value = "/confirmationLink", method = RequestMethod.GET)
	public String confirmationLink() {
		return "confirmationlink";
	}

	@RequestMapping(value = "/newmodelaccessory", method = RequestMethod.GET)
	public String newModelConsumable() {
		return "addmodelaccessory";
	}

	@RequestMapping(value = "/newmodelconsumable", method = RequestMethod.GET)
	public String newModel() {
		return "addmodelconsumable";
	}

	@RequestMapping(value = "/newsupplier", method = RequestMethod.GET)
	public String newSupplier() {
		return "addsupplier";
	}

	@RequestMapping(value = "/newstatus", method = RequestMethod.GET)
	public String newStatus() {
		return "addstatus";
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(User user, @RequestParam String email, @RequestParam String password, HttpSession session,
			Model model, HttpServletRequest request) {

		user = userService.loginUser(email, password);
		try {
			if (user == null) {
				model.addAttribute("loginError", "Error Loggin in , please try again");
				return "login";
			}
			if (user.getRole().contains("ROLE_SUPER")) {
				session.setAttribute("email", email);
				session.setMaxInactiveInterval(600);
				return "redirect:/users?email=" + email;
			} else if (user.getRole().contains("ROLE_ADMIN")) {
				session.setAttribute("email", email);
				session.setMaxInactiveInterval(600);
				return "redirect:/requestedassets?email=" + email;
			} else if (user.getRole().contains("ROLE_USER")) {
				session.setAttribute("email", email);
				session.setMaxInactiveInterval(600);
				return "redirect:/assetrequest";
			} else {
				return "login";

			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

	}

	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logout(HttpSession session) {

		session.removeAttribute("loggedInUser");
		session.removeAttribute("email");
		session.setMaxInactiveInterval(10);
		return "login";
	}

	@RequestMapping(value = "/register", method = RequestMethod.GET)
	public ModelAndView getRegistration() {

		ModelAndView modelandview = new ModelAndView("register");
		return modelandview;
	}

	@RequestMapping(value = "/updateuser", method = RequestMethod.POST)
	public String updateUser(@Valid @ModelAttribute("user") User user, HttpSession session, BindingResult result) {

		if (result.hasErrors()) {
			return "updateuser";
		} else {
			userService.update(user);
			return "redirect:/users";
		}

	}

	@RequestMapping(value = "/users")
	public ModelAndView listUsers(ModelAndView model, HttpSession session) throws IOException {

		session.getAttribute("email");
		List<User> listUsers = service.list();
		model.addObject("listUsers", listUsers);
		model.setViewName("userslist");

		return model;
	}

	@RequestMapping(value = "/getUser{email}")
	public String view(@RequestParam String email, Model model) {

		model.addAttribute("user", userService.getUser(email));
		return "updateuser";
	}

	@RequestMapping(value = "/getAsset{id}")
	public ModelAndView editAsset(Model model, HttpServletRequest request) {

		Long id = (long) Integer.parseInt(request.getParameter("id"));
		model.addAttribute("asset", userService.getAsset(id));
		ModelAndView modelview = new ModelAndView();
        List<NewModel> listmodelname = service.listModel();
		modelview.addObject("listmodelname", listmodelname);
		List<ModelAccessory> listmodelaccessory = service.listModelAccessory();
		modelview.addObject("listmodelaccessory", listmodelaccessory);
		List<ModelConsumable> listmodelconsumable = service.listModelConsumable();
		modelview.addObject("listmodelconsumable", listmodelconsumable);
		List<Company> listcompany = service.listCompany();
		modelview.addObject("listcompany", listcompany);
		List<Supplier> listsupplier = service.listSupplier();
		modelview.addObject("listsupplier", listsupplier);
		List<Status> liststatus = service.listStatus();
		modelview.addObject("liststatus", liststatus);
		modelview.setViewName("asset");
		return modelview;
	}

	@RequestMapping(value = "/asset", method = RequestMethod.POST)
	public ModelAndView asset(@Valid @ModelAttribute("asset") Asset asset, HttpServletRequest request, Model model,
			@RequestParam Long id) {

		List<Asset> assetAttributesList = userService.uniqueAttribute();
		List<Asset> registeredAttributesList = userService.registeredAttribute(id);
		for (int i = 0; i < assetAttributesList.size(); i++) {
			if (assetAttributesList.get(i).getId() == id)
				tempid = id;
		}
          if (temp == null) {
			for (int i = 0; i < assetAttributesList.size(); i++) {
				if (assetAttributesList.get(i).getSerialnumber().equals(asset.getSerialnumber())) {
					model.addAttribute("serialError", "Serial number already exist");
					return new ModelAndView("redirect:/asset");
				} else if (assetAttributesList.get(i).getTag().equals(asset.getTag())) {
					model.addAttribute("tagError", "Asset Tag already exist");
					return new ModelAndView("redirect:/asset");
				} else if (assetAttributesList.get(i).getOrdernumber().equals(asset.getOrdernumber())) {
					model.addAttribute("orderError", "Order Number already esist");
					return new ModelAndView("redirect:/asset");
				}
			}
			userService.addAsset(asset);
			ModelAndView modelview = new ModelAndView("redirect:/requestedassets");
			return modelview;
		} else {
			for (int i = 0; i < registeredAttributesList.size(); i++) {
				if (registeredAttributesList.get(i).getSerialnumber().equals(asset.getSerialnumber())) {
					model.addAttribute("serialError", "Serial number already exist");
					return new ModelAndView("redirect:/getAsset?id=" + asset.getId());
				} else if (registeredAttributesList.get(i).getOrdernumber().equals(asset.getOrdernumber())) {
					model.addAttribute("orderError", "Order number already exist");
					return new ModelAndView("redirect:/getAsset?id=" + asset.getId());
				} else if (registeredAttributesList.get(i).getTag().equals(asset.getTag())) {
					model.addAttribute("tagError", "Asset Tag already exist");
					return new ModelAndView("redirect:/getAsset?id=" + asset.getId());
				}
			}
			userService.updateAsset(asset, id);
			return new ModelAndView("redirect:/assetslist");
		}
	}

	@RequestMapping(value = "/requestNotAssign{id}{email}")
	public ModelAndView requestNotAssign(@ModelAttribute("reasonassign") AssetRequest assetrequest) {

		ModelAndView modelview = new ModelAndView();
		modelview.setViewName("requestnotassigned");
		return modelview;
	}

	@RequestMapping(value = "/requestNotAssigned", method = RequestMethod.POST)
	public ModelAndView requestNotAssigned(@RequestParam Long id, @RequestParam String reason, ModelAndView modelview) {

		userService.updateNotAssignedRequest(reason, id);
		List<User> listEmail = service.listEmail();
		modelview.addObject("listEmail", listEmail);
		modelview.setViewName("requestedassets");
		return modelview;
	}

	@RequestMapping(value = "/deleteUser", method = RequestMethod.GET)
	public ModelAndView deleteUser(HttpServletRequest request,@RequestParam(value = "email") String email) {

		//String email = request.getParameter("email");
		userService.softDelete(email);
		return new ModelAndView("redirect:/users");
	}

	@RequestMapping(value = "/deleteCompany", method = RequestMethod.GET)
	public ModelAndView deleteCompany(@RequestParam(value = "id") Long id, @RequestParam(value = "company") String company, Model model) {

		List<Asset> listExistedAttributes = userService.existedAttributes();
		for (int i = 0; i < listExistedAttributes.size(); i++) {
			if (listExistedAttributes.get(i).getCompany().equals(company)) {
				model.addAttribute("companyError", "This record cannot be deleted as it exists in asset record");
				return new ModelAndView("listofcompanies");
			}
		}
		userService.deleteCompany(id);
		return new ModelAndView("listofcompanies");
	}

	@RequestMapping(value = "/deleteSupplier", method = RequestMethod.GET)
	public ModelAndView deleteSupplier(@RequestParam(value = "id") Long id, @RequestParam(value = "supplier") String supplier, Model model) {

		List<Asset> listExistedAttributes = userService.existedAttributes();
		for (int i = 0; i < listExistedAttributes.size(); i++) {
			if (listExistedAttributes.get(i).getSupplier().equals(supplier)) {
				model.addAttribute("supplierError", "This record cannot be deleted as it exists in asset record");
				return new ModelAndView("listofsuppliers");
			}
		}
		userService.deleteSupplier(id);
		return new ModelAndView("listofsuppliers");
	}

	@RequestMapping(value = "/deleteAssetModel", method = RequestMethod.GET)
	public ModelAndView deleteAssetModel(@ModelAttribute("assetmodel") NewModel newmodel,@RequestParam(value = "id") Long id, @RequestParam(value = "model") String model, Model modelname) {

		List<Asset> listExistedAttributes = userService.existedAttributes();
		for (int i = 0; i < listExistedAttributes.size(); i++) {
			if (listExistedAttributes.get(i).getModel().equals(model)) {
				modelname.addAttribute("modelError","This record cannot be deleted as it exists in asset record");
				return new ModelAndView("listofassetmodels");
			}
		}
		userService.deleteAssetModel(id);
		return new ModelAndView("listofassetmodels");
	}

	@RequestMapping(value = "/deleteAccessoryModel", method = RequestMethod.GET)
	public ModelAndView deleteAccessoryModel(@RequestParam(value = "id") Long id, @RequestParam(value = "model") String model, Model modelname) {

		List<Asset> listExistedAttributes = userService.existedAttributes();
		for (int i = 0; i < listExistedAttributes.size(); i++) {
			if (listExistedAttributes.get(i).getModel().equals(model)) {
				modelname.addAttribute("modelError", "This record cannot be deleted as it exists in asset record");
				return new ModelAndView("listofaccessorymodels");
			}
		}
		userService.deleteAccessoryModel(id);
		return new ModelAndView("listofaccessorymodels");
	}

	@RequestMapping(value = "/deleteConsumableModel", method = RequestMethod.GET)
	public ModelAndView deleteConsumableModel(@RequestParam(value = "id") Long id, @RequestParam(value = "model") String model, Model modelname) {

		List<Asset> listExistedAttributes = userService.existedAttributes();
		for (int i = 0; i < listExistedAttributes.size(); i++) {
			if (listExistedAttributes.get(i).getModel().equals(model)) {
				modelname.addAttribute("modelError", "This record cannot be deleted as it exists in asset record");
				return new ModelAndView("listofconsumablemodels");
			}
		}
		userService.deleteConsumableModel(id);
		return new ModelAndView("listofconsumablemodels");
	}

	@RequestMapping(value = "/deleterequestedassets", method = RequestMethod.GET)
	public ModelAndView deleteRequestedAssets(HttpServletRequest request) {

		Long id = (long) Integer.parseInt(request.getParameter("id"));
		userService.deleteAssetRequest(id);
		return new ModelAndView("redirect:/assetrequest");
	}

	@RequestMapping(value = "/deleteAsset", method = RequestMethod.GET)
	public ModelAndView deleteAsset(HttpServletRequest request,@RequestParam(value = "id") Long id) {

		//Long id = (long) Integer.parseInt(request.getParameter("id"));
		userService.deleteAsset(id);
		return new ModelAndView("redirect:/assetslist");
	}

	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public ModelAndView getAdd() {

		ModelAndView modelandview = new ModelAndView("add");
		return modelandview;
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public ModelAndView addUser(@Valid @ModelAttribute("adduser") User user, BindingResult result,
			Map<String, Object> model, Errors errors) {

		ModelAndView modelandview = new ModelAndView("add");
		if (result.hasErrors()) {
			return modelandview;
		}
		User tempUser = userService.findByEmail(user.getEmail());
		if (tempUser != null) {
			((Model) model).addAttribute("emailError", "Email already registered");
			return modelandview;
		}

		if (!(user.getEmail().isEmpty())) {
			Pattern pattern = Pattern.compile(EMAIL_PATTERN);
			Matcher matcher = pattern.matcher(user.getEmail());
			if (!matcher.matches()) {
				errors.rejectValue("email", "domainmatch.email", "Domain name must be @nerdapplabs.com");
				return modelandview;
			}
			//user.setStatus(1);
			//userService.save(user);
			//((Model) model).addAttribute("saveUser","User added successfully");
			//return new ModelAndView("add");
		}

		user.setStatus(1);
		userService.save(user);
		((Model) model).addAttribute("saveUser","User added successfully");
		ModelAndView modelview = new ModelAndView("add");
		return modelview;

	}

	@RequestMapping(value = "/register", method = RequestMethod.POST)
	public ModelAndView registration(@Valid @ModelAttribute("userform") User user, BindingResult result,
			Model model, Errors errors, WebRequest request) {

		ModelAndView modelandview = new ModelAndView("register");
		if (!(user.getEmail().isEmpty())) {
			Pattern pattern = Pattern.compile(EMAIL_PATTERN);
			Matcher matcher = pattern.matcher(user.getEmail());
			if (!matcher.matches()) {
				errors.rejectValue("email", "domainmatch.email", "Domain name must be @nerdapplabs.com");
				return modelandview;
			}
		}
		User tempUser = userService.findByEmail(user.getEmail());
		if (tempUser != null) {
			 model.addAttribute("emailError", "Email already registered");
			return modelandview;
		}
		user.setStatus(0);
		user.setIs_approved(false);
		userService.save(user);

		try {
			String appUrl = request.getContextPath();
			model.addAttribute("confirmationlink","Confirmation link send to your email");
			eventPublisher.publishEvent(new OnRegistrationCompleteEvent(user, appUrl));
		} catch (Exception e) {
			 model.addAttribute("emailError", "Error in sending email");
			return modelandview;
		}
		ModelAndView modelview = new ModelAndView("register");
		return modelview;
	}

	@RequestMapping(value = "/changePassword{email}{newpassword}{oldpassword}", method = RequestMethod.POST)
	public ModelAndView changePassword(@ModelAttribute("changepassword") User user, @RequestParam String newpassword,
			@RequestParam String email, @RequestParam String oldpassword, Model model, Errors errors) {

		user = userService.getUser(email);
		if (user.getPassword().contains(oldpassword)) {
			userService.updatePassword(email, newpassword);
			if (user.getRole().contains("ROLE_ADMIN")) {
				return new ModelAndView("redirect:/requestedassets?email=" + email);
			} else if (user.getRole().contains("ROLE_USER")) {
				return new ModelAndView("redirect:/assetrequest");
			} else if(user.getRole().contains("ROlE_SUPER")) {
			return new ModelAndView("redirect:/users?email=" + email);
			} else {
				return new ModelAndView("redirect:/changePassword");
			}
		} else {
			model.addAttribute("passwordError", "Password not registered");
			return new ModelAndView("redirect:/changePassword");
		}

	}

	@RequestMapping(value = "/modelaccessory", method = RequestMethod.POST)
	public ModelAndView addModelAccessory(@ModelAttribute("newmodelaccessory") ModelAccessory modelaccessory,
			Model modelObject) {

		List<ModelAccessory> listmodelaccessory = service.listModelAccessory();
		for (int i = 0; i < listmodelaccessory.size(); i++) {
			if (listmodelaccessory.get(i).getModel().equals(modelaccessory.getModel())) {
				modelObject.addAttribute("modelError", "Model name already exsist");
				return new ModelAndView("redirect:/modelaccessory");
			}
		}
		userService.addModelAccessory(modelaccessory);
		ModelAndView modelview = new ModelAndView("redirect:/listmodelaccessory");
		return modelview;
	}

	@RequestMapping(value = "/modelconsumable", method = RequestMethod.POST)
	public ModelAndView addModelConsumable(@ModelAttribute("newmodelconsumable") ModelConsumable modelconsumable,
			Model modelObject) {

		List<ModelConsumable> listmodelconsumable = service.listModelConsumable();
		for (int i = 0; i < listmodelconsumable.size(); i++) {
			if (listmodelconsumable.get(i).getModel().equals(modelconsumable.getModel())) {
				modelObject.addAttribute("modelError", "Model name already exsist");
				return new ModelAndView("redirect:/modelconsumable");
			}
		}
		userService.addModelConsumable(modelconsumable);
		ModelAndView modelview = new ModelAndView("redirect:/listmodelconsumable");
		return modelview;
	}

	@RequestMapping(value = "/newmodel", method = RequestMethod.POST)
	public ModelAndView addModel(@ModelAttribute("newmodel") NewModel newmodel, Model modelObject) {

		List<NewModel> listmodel = service.listModel();
		for (int i = 0; i < listmodel.size(); i++) {
			if (listmodel.get(i).getModel().equals(newmodel.getModel())) {
				modelObject.addAttribute("modelError", "Model name already exsist");
				return new ModelAndView("redirect:/newmodel");
			}
		}
		userService.addModel(newmodel);
		ModelAndView modelview = new ModelAndView("redirect:/listmodel");
		return modelview;
	}

	@RequestMapping(value = "/listmodel")
	public ModelAndView listModel(ModelAndView model) throws IOException {

		List<NewModel> listmodel = service.listModel();
		model.addObject("listmodel", listmodel);
		ModelAndView modelview = new ModelAndView("redirect:/asset");
		return modelview;
	}

	@RequestMapping(value = "/listmodelaccessory")
	public ModelAndView listModelAccessory(ModelAndView model) throws IOException {

		List<ModelAccessory> listmodelaccessory = service.listModelAccessory();
		model.addObject("listmodelaccessory", listmodelaccessory);
		ModelAndView modelview = new ModelAndView("redirect:/asset");
		return modelview;
	}

	@RequestMapping(value = "/listmodelconsumable")
	public ModelAndView listModelConsumable(ModelAndView model) throws IOException {

		List<ModelConsumable> listmodelconsumable = service.listModelConsumable();
		model.addObject("listmodelconsumable", listmodelconsumable);
		ModelAndView modelview = new ModelAndView("redirect:/asset");
		return modelview;
	}

	@RequestMapping(value = "/newsupplier", method = RequestMethod.POST)
	public ModelAndView addSupplier(@ModelAttribute("supplier") Supplier supplier, Model model) {

		List<Supplier> listsupplier = service.listSupplier();
		for (int i = 0; i < listsupplier.size(); i++) {
			if (listsupplier.get(i).getSupplier().equals(supplier.getSupplier())) {
				model.addAttribute("supplierError", "Supplier already exsist");
				return new ModelAndView("redirect:/newsupplier");
			}
		}
		userService.addSupplier(supplier);
		ModelAndView modelview = new ModelAndView("redirect:/listsupplier");
		return modelview;
	}

	@RequestMapping(value = "/listsupplier")
	public ModelAndView listSupplier(ModelAndView model) throws IOException {

		List<Supplier> listsupplier = service.listSupplier();
		model.addObject("listsupplier", listsupplier);
		ModelAndView modelview = new ModelAndView("redirect:/asset");
		return modelview;
	}

	@RequestMapping(value = "/newstatus", method = RequestMethod.POST)
	public ModelAndView addStatus(@ModelAttribute("status") Status status, Model model) {

		List<Status> liststatus = service.listStatus();
		for (int i = 0; i < liststatus.size(); i++) {
			if (liststatus.get(i).getStatus().equals(status.getStatus())) {
				model.addAttribute("statusError", "Status already exsist");
				return new ModelAndView("redirect:/newstatus");
			}
		}
		userService.addStatus(status);
		ModelAndView modelview = new ModelAndView("redirect:/liststatus");
		return modelview;
	}

	@RequestMapping(value = "/liststatus")
	public ModelAndView listStatus(ModelAndView model) throws IOException {

		List<Status> liststatus = service.listStatus();
		model.addObject("liststatus", liststatus);
		ModelAndView modelview = new ModelAndView("redirect:/asset");
		return modelview;
	}

	@RequestMapping(value = "/newcompany", method = RequestMethod.POST)
	public ModelAndView addCompany(@ModelAttribute("newcompany") Company company, Model model) {

		List<Company> listcompany = service.listCompany();
		for (int i = 0; i < listcompany.size(); i++) {
			if (listcompany.get(i).getCompany().equals(company.getCompany())) {
				model.addAttribute("companyError", "Company name already exsist");
				return new ModelAndView("redirect:/newcompany");
			}
		}
		userService.addCompany(company);
		ModelAndView modelview = new ModelAndView("redirect:/listcompany");
		return modelview;
	}

	@RequestMapping(value = "/listcompany")
	public ModelAndView listCompany(ModelAndView model) throws IOException {

		List<Company> listcompany = service.listCompany();
		model.addObject("listcompany", listcompany);
		ModelAndView modelview = new ModelAndView("redirect:/asset");
		return modelview;
	}

	@RequestMapping(value = "/listOfCompanies")
	public ModelAndView listOfCompanies(ModelAndView model) throws IOException {

		List<Company> listcompany = service.listCompany();
		model.addObject("listcompany", listcompany);
		model.setViewName("listofcompanies");
		return model;
	}

	@RequestMapping(value = "/listOfSuppliers")
	public ModelAndView listOfSuppliers(ModelAndView model) throws IOException {

		List<Supplier> listsupplier = service.listSupplier();
		model.addObject("listsupplier", listsupplier);
		model.setViewName("listofsuppliers");
		return model;
	}

	@RequestMapping(value = "/listOfAssetModels")
	public ModelAndView listOfAssetModels(ModelAndView model) throws IOException {

		List<NewModel> listmodel = service.listModel();
		model.addObject("listmodel", listmodel);
		model.setViewName("listofassetmodels");
		return model;
	}

	@RequestMapping(value = "/listOfAccessoryModels")
	public ModelAndView listOfAccessoryModels(ModelAndView model) throws IOException {

		List<ModelAccessory> listmodelaccessory = service.listModelAccessory();
		model.addObject("listmodelaccessory", listmodelaccessory);
		model.setViewName("listofaccessorymodels");
		return model;
	}

	@RequestMapping(value = "/listOfConsumableModels")
	public ModelAndView listOfConsumableModels(ModelAndView model) throws IOException {

		List<ModelConsumable> listmodelconsumable = service.listModelConsumable();
		model.addObject("listmodelconsumable", listmodelconsumable);
		model.setViewName("listofconsumablemodels");
		return model;
	}

	@RequestMapping(value = "/assetrequest", method = RequestMethod.GET)
	public ModelAndView listAssetsRequest(@ModelAttribute("assetrequest") AssetRequest assetrequest, ModelAndView model,
			HttpSession session, Model modelview) throws IOException {

		session.getAttribute("email");
		List<NewModel> listmodelname = service.listModel();
		model.addObject("listmodelname", listmodelname);
		List<ModelAccessory> listmodelaccessory = service.listModelAccessory();
		model.addObject("listmodelaccessory", listmodelaccessory);
		List<ModelConsumable> listmodelconsumable = service.listModelConsumable();
		model.addObject("listmodelconsumable", listmodelconsumable);
		List<AssetRequest> listAssetsRequest = service.listAssetsRequest(session);
		model.addObject("listAssetsRequest", listAssetsRequest);
		model.setViewName("assetrequest");
		return model;
	}

	@RequestMapping(value = "/assetrequest", method = RequestMethod.POST)
	public ModelAndView requestAsset(@RequestParam String email,
			@Valid @ModelAttribute("assetrequest") AssetRequest assetrequest, BindingResult result,
			Map<String, Object> model, Errors errors, HttpSession session, User user, @RequestParam String assettype,
			@RequestParam String assetname, @RequestParam String windows, Model modelview) {

		session.getAttribute("email");
		List<AssetRequest> listAssets = service.listAsset(user);
		List<AssetRequest> listAssetsRequest = service.listAssetsRequest(session);
		ModelAndView view = new ModelAndView("assetrequest");
		List<NewModel> listmodelname = service.listModel();
		view.addObject("listmodelname", listmodelname);
		List<ModelAccessory> listmodelaccessory = service.listModelAccessory();
		view.addObject("listmodelaccessory", listmodelaccessory);
		List<ModelConsumable> listmodelconsumable = service.listModelConsumable();
		view.addObject("listmodelconsumable", listmodelconsumable);
		for (int i = 0; i < listAssets.size(); i++) {
			if (listAssets.get(i).getAssettype().equals(assettype) && listAssets.get(i).getAssetname().equals(assetname)
					&& listAssets.get(i).getWindows().equals(windows)) {
				modelview.addAttribute("typeRegistered", "assettype,assetname and windows already registered");
				view.addObject("listAssetsRequest", listAssetsRequest);
				view.setViewName("assetrequest");
				return view;
			}
		}

		if (result.hasErrors()) {
			listAssetsRequest = service.listAssetsRequest(session);
			view.addObject("listAssetsRequest", listAssetsRequest);
			view.setViewName("assetrequest");
			return view;
		}
		userService.saveAsset(assetrequest, user);
		listAssetsRequest = service.listAssetsRequest(session);
		view.addObject("listAssetsRequest", listAssetsRequest);
		view.setViewName("assetrequest");
		return view;
	}

	@RequestMapping(value = "/statusassetslist{email}", method = RequestMethod.GET)
	public ModelAndView statusAsset(@ModelAttribute("user") User user, ModelAndView modelview, HttpSession session,
			AssetRequest assetrequest) throws IOException {

		user = userService.getUser(user.getEmail());
		List<AssetRequest> listAssets = service.listAsset(user);
		modelview.addObject("listAssets", listAssets);
		modelview.setViewName("statusassetslist");
		return modelview;
	}

	@RequestMapping(value = "/statusCheckRequest{email}{id}", method = RequestMethod.GET)
	public ModelAndView CheckRequest(@ModelAttribute("asset") Asset asset, @RequestParam Long id,
			@RequestParam String email, ModelAndView model, AssetRequest assetrequest, User user) throws IOException {

		List<Asset> listAssets = service.listAssets();
		model.addObject("listAssets", listAssets);
		model.setViewName("assetslist");
		return model;
	}

	@RequestMapping(value = "/statusCheckRequest{email}{id}", method = RequestMethod.POST)
	public ModelAndView statusCheckRequest(@ModelAttribute("asset") Asset asset, @RequestParam Long id,
			@RequestParam String email, ModelAndView model, AssetRequest assetrequest, User user) throws IOException {

		List<Asset> listAssets = service.listAssets();
		model.addObject("listAssets", listAssets);
		model.setViewName("assetslist");
		return model;
	}

	ModelAndView modelview;

	@RequestMapping(value = "/statusAssignRequest", method = RequestMethod.GET)
	public @ResponseBody ModelAndView statusAssignRequest(@ModelAttribute("asset") Asset asset,
			@RequestParam("id") Long id, @RequestParam("quantity") String quantity, @RequestParam("email") String email,
			@RequestParam("serialnumber") String serialnumber) throws IOException {

		User user;
		user = userService.getUser(email);
		asset = userService.getAsset(id);
		List<AssetRequest> listAsset = service.listAsset(user);
		List<Asset> listAssets = service.listAssets();
		for (int i = 0; i < listAsset.size(); i++) {
			if (listAsset.get(i).getId() == id)
				tempid = id;
		}
		for (int i = 0; i < listAssets.size(); i++) {
			if (listAssets.get(i).getSerialnumber().contentEquals(serialnumber)	)
				temp = serialnumber;
		}
		if (temp != null) {
			userService.updateAssetQuantity(quantity, serialnumber);
			if (tempid != null) {
				userService.updateAssetRequestQuantity(quantity, id);
			}
			listAssets = service.listAssets();
			modelview.addObject("listAssets", listAssets);
			modelview.setViewName("assetslist");
			return modelview;
		}
		listAssets = service.listAssets();
		modelview.addObject("listAssets", listAssets);
		modelview.setViewName("assetslist");
		return modelview;
	}

	@RequestMapping(value = "/statusRecieveRequest{id}{email}", method = RequestMethod.GET)
	public ModelAndView statusRecieveRequest(@ModelAttribute("user") User user, ModelAndView modelview,
			AssetRequest assetrequest, @RequestParam Long id, @RequestParam String email) throws IOException {
		user = userService.getUser(email);
        List<AssetRequest> listAssets = service.listAsset(user);
		for (int i = 0; i < listAssets.size(); i++) {
			if (listAssets.get(i).getId() == id)
				tempid = id;
		}
		if (tempid != null) {
			userService.updateRecieveRequest(assetrequest, id);
			listAssets = service.listAsset(user);
			modelview.addObject("listAssets", listAssets);
			modelview.setViewName("statusassetslist");
			return modelview;
		}
		modelview.addObject("listAssets", listAssets);
		modelview.setViewName("statusassetslist");
		return modelview;
	}

	@RequestMapping(value = "/requestedassetslist{email}")
	public ModelAndView listAssets(@ModelAttribute("user") User user, ModelAndView modelview, HttpSession session)
			throws IOException {
		session.getAttribute("email");
		user = userService.getUser(user.getEmail());
		List<AssetRequest> listAssets = service.listAsset(user);
		modelview.addObject("listAssets", listAssets);
		modelview.setViewName("requestedassetslist");
		return modelview;
	}

	@RequestMapping(value = "/registrationconfirm", method = RequestMethod.GET)
	public String confirmRegistration(WebRequest request, Model model, @RequestParam("token") String token) {

		VerificationToken verificationToken = userService.getVerificationToken(token);
		if (verificationToken == null) {
			String message = messages.getMessage("auth.message.invalidToken", null, null);
			model.addAttribute("message", message);
			return "redirect:/baduser";
		}
		User user = verificationToken.getUser();
		Calendar cal = Calendar.getInstance();
		if ((verificationToken.getExpiryDate().getTime() - cal.getTime().getTime()) <= 0) {
			String messageValue = messages.getMessage("auth.message.expired", null, null);
			model.addAttribute("message", messageValue);
			return "redirect:/baduser";
		}
		user.setIs_approved(true);
		userService.save(user);
		return "redirect:/confirmationLink";
	}

	@RequestMapping(value = "/requestedassets{email}")
	public ModelAndView listEmail(ModelAndView model, HttpSession session) throws IOException {

		session.getAttribute("email");
		List<User> listEmail = service.listEmail();
		model.addObject("listEmail", listEmail);
		model.setViewName("requestedassets");
		return model;

	}

	@RequestMapping(value = "/listOfApprovalUsers")
	public ModelAndView listOfRegisteredUsers(@ModelAttribute("user") User user,ModelAndView model) throws IOException {

		List<User> listApprovalUsers = service.listApprovalUsers();
		model.addObject("listApprovalUsers", listApprovalUsers);
		model.setViewName("approvaluserslist");
		return model;

	}

	@RequestMapping(value = "/assetslist")
	public ModelAndView listAssets(@ModelAttribute("asset") Asset asset, ModelAndView model, AssetRequest assetrequest,
			User user) throws IOException {
		List<NewModel> listmodelname = service.listModel();
		model.addObject("listmodelname", listmodelname);
		List<ModelAccessory> listmodelaccessory = service.listModelAccessory();
		model.addObject("listmodelaccessory", listmodelaccessory);
		List<ModelConsumable> listmodelconsumable = service.listModelConsumable();
		model.addObject("listmodelconsumable", listmodelconsumable);
		List<Asset> listAssets = service.listAssets();
		model.addObject("listAssets", listAssets);
		model.setViewName("assetslist");
		return model;
    }

	@RequestMapping(value = "/approveUser{email}", method = RequestMethod.GET)
	public ModelAndView approveUser(@RequestParam String email, Model model) throws MessagingException {
		userService.sendApprovalEmail(email);
		model.addAttribute("approveUser","Approval is sent to User's mail");
		userService.updateRegisteredStatus(email);
		return new ModelAndView("approvaluserslist");

	}

	@RequestMapping(value = "/rejectUser", method = RequestMethod.GET)
	public ModelAndView rejectUser(@RequestParam(value = "email") String email,Model model){

		int result = userService.deleteToken(email);
		if(result == 0) {
			model.addAttribute("tokenError","User cannot be deleted as token still exists");
			return new ModelAndView("approvaluserslist");
		}
		userService.deleteFakeUser(email);
		return new ModelAndView("approvaluserslist");

	}

	@RequestMapping(value = "/forgotpassword")
	public String forgotPassword() {
		return "forgotpassword";
	}

	@RequestMapping(value = "/recoverypassword", method = RequestMethod.POST)
	public String recoverPassword(@ModelAttribute("passwordform") User user, Model model) {
		User tempuser = userService.findByEmail(user.getEmail());
		if (tempuser != null && tempuser.getStatus() == 1) {
			userService.sendEmail(user.getEmail());
			model.addAttribute("emailError", "Password send successfully to your email");
			return "forgotpassword";
		} else if (tempuser == null) {
			model.addAttribute("emailError", "Valid email required");
			return "forgotpassword";
		} else if (tempuser.getStatus() == 0) {
			System.out.println("email not registered");
			model.addAttribute("emailError", "Email not registered");
			return "forgotpassword";
		} else {
			return "forgotpassword";
		}
	}
}


text:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  Adapter file for Quintus Prolog 3.3~3.5
%  Last updated on November 1, 2022
%
%  This file is part of Logtalk <https://logtalk.org/>
%  Copyright 1998-2022 Paulo Moura <pmoura@logtalk.org>
%  SPDX-License-Identifier: Apache-2.0
%
%  Licensed under the Apache License, Version 2.0 (the "License");
%  you may not use this file except in compliance with the License.
%  You may obtain a copy of the License at
%
%      http://www.apache.org/licenses/LICENSE-2.0
%
%  Unless required by applicable law or agreed to in writing, software
%  distributed under the License is distributed on an "AS IS" BASIS,
%  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%  See the License for the specific language governing permissions and
%  limitations under the License.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

:- [library(between)].
:- [library(foreach)].
:- [library(files)].
:- [library(directory)].
:- [library(strings)].
:- [library(environ)].
:- [library(subsumes)].
:- [library(unify)].
:- [library(math)].

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  ISO Prolog Standard predicates that we must define because they are
%  not built-in
%
%  add a clause for '$lgt_iso_predicate'/1 declaring each ISO predicate that
%  you must define; there must be at least one clause for this predicate
%  whose call should fail if you don't define any ISO predicates
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

:- prolog_flag(character_escapes, _, on).

:- op(700, xfx, \=).
:- op(200, xfx, **).

% '$lgt_iso_predicate'(?callable).

'$lgt_iso_predicate'(_ \= _).
'$lgt_iso_predicate'(acyclic_term(_)).
'$lgt_iso_predicate'(at_end_of_stream).
'$lgt_iso_predicate'(at_end_of_stream(_)).
'$lgt_iso_predicate'(atom_codes(_, _)).
'$lgt_iso_predicate'(atom_concat(_, _, _)).
'$lgt_iso_predicate'(atom_length(_, _)).
'$lgt_iso_predicate'(catch(_, _, _)).
'$lgt_iso_predicate'(char_code(_, _)).
'$lgt_iso_predicate'(current_predicate(_)).
'$lgt_iso_predicate'(current_prolog_flag(_, _)).
'$lgt_iso_predicate'(flush_output).
'$lgt_iso_predicate'(get_byte(_)).
'$lgt_iso_predicate'(get_byte(_, _)).
'$lgt_iso_predicate'(get_char(_)).
'$lgt_iso_predicate'(get_char(_, _)).
'$lgt_iso_predicate'(get_code(_)).
'$lgt_iso_predicate'(get_code(_, _)).
'$lgt_iso_predicate'(number_codes(_, _)).
'$lgt_iso_predicate'(once(_)).
'$lgt_iso_predicate'(peek_byte(_)).
'$lgt_iso_predicate'(peek_byte(_, _)).
'$lgt_iso_predicate'(peek_code(_)).
'$lgt_iso_predicate'(peek_code(_, _)).
'$lgt_iso_predicate'(put_byte(_)).
'$lgt_iso_predicate'(put_byte(_, _)).
'$lgt_iso_predicate'(put_char(_)).
'$lgt_iso_predicate'(put_char(_, _)).
'$lgt_iso_predicate'(put_code(_)).
'$lgt_iso_predicate'(put_code(_, _)).
'$lgt_iso_predicate'(set_prolog_flag(_, _)).
'$lgt_iso_predicate'(stream_property(_, _)).
'$lgt_iso_predicate'(sub_atom(_, _, _, _, _)).
'$lgt_iso_predicate'(subsumes_term(_, _)).
'$lgt_iso_predicate'(term_variables(_, _)).
'$lgt_iso_predicate'(throw(_)).
'$lgt_iso_predicate'(unify_with_occurs_check(_, _)).

Term1 \= Term2 :-
	\+ (Term1 = Term2).

acyclic_term(_).

at_end_of_stream :-
	at_end_of_file.

at_end_of_stream(Stream) :-
	at_end_of_file(Stream).

atom_codes(Atom, Codes) :-
	atom_chars(Atom, Codes).

atom_concat(Atom1, Atom2, Atom3) :-
	nonvar(Atom1), nonvar(Atom2),
	!,
	atom_chars(Atom1, Codes1),
	atom_chars(Atom2, Codes2),
	append(Codes1, Codes2, Codes3),
	atom_chars(Atom3, Codes3).

atom_concat(Atom1, Atom2, Atom3) :-
	nonvar(Atom3),
	!,
	atom_chars(Atom3, Codes3),
	append(Codes1, Codes2, Codes3),
	atom_chars(Atom1, Codes1),
	atom_chars(Atom2, Codes2).

atom_length(Atom, Length) :-
	atom_chars(Atom, Codes),
	length(Codes, Length).

catch(Goal, Catcher, Recovery) :-
	on_exception(Catcher, Goal, Recovery).

char_code(Char, Code) :-
	atom_chars(Char, [Code]).

current_predicate(Functor/Arity) :-
	current_predicate(_, Callable),
	functor(Callable, Functor, Arity).
current_predicate(Module:Functor/Arity) :-
	current_predicate(_, Module:Callable),
	functor(Callable, Functor, Arity).

current_prolog_flag(Flag, Value) :-
	prolog_flag(Flag, Value).

flush_output :-
	current_output(Stream),
	flush_output(Stream).

get_byte(Stream, Byte) :-
	get0(Stream, Byte).

get_byte(Byte) :-
	get0(Byte).

get_char(Stream, Char) :-
	get0(Stream, Code),
	atom_chars(Char, [Code]).

get_char(Char) :-
	get0(Code),
	atom_chars(Char, [Code]).

get_code(Stream, Code) :-
	get0(Stream, Code).

get_code(Code) :-
	get0(Code).

number_codes(Number, Codes) :-
	number_chars(Number, Codes).

once(Goal) :-
	call(Goal),
	!.

peek_byte(Stream, Byte) :-
	peek_char(Stream, Byte).

peek_byte(Byte) :-
	peek_char(Byte).

peek_code(Stream, Code) :-
	peek_char(Stream, Code).

peek_code(Code) :-
	peek_char(Code).

put_byte(Stream, Byte) :-
	put(Stream, Byte).

put_byte(Byte) :-
	put(Byte).

put_char(Stream, Char) :-
	atom_chars(Char, [Code]),
	put(Stream, Code).

put_char(Char) :-
	atom_chars(Char, [Code]),
	put(Code).

put_code(Stream, Code) :-
	put(Stream, Code).

put_code(Code) :-
	put(Code).

stream_property(Stream, alias(Alias)) :-
	(	var(Stream) ->
		'$lgt_quintus_stream_alias'(Stream, Alias)
	;	'$lgt_quintus_stream_alias'(Stream, Alias),
		!
	).

set_prolog_flag(Flag, Value) :-
	prolog_flag(Flag, _, Value).

sub_atom(Atom, Before, Length, After, SubAtom) :-
	substring(Atom, SubAtom, Before, Length, After).

subsumes_term(General, Specific) :-
	subsumes(General, Specific).

term_variables(Term, Variables) :-
	'$lgt_quintus_term_variables'(Term, [], List),
	'$lgt_quintus_reverse'(List, [], Variables).

'$lgt_quintus_term_variables'(Term, Acc, Variables) :-
	(	var(Term) ->
		(	'$lgt_quintus_var_member_chk'(Term, Acc) ->
			Variables = Acc
		;	Variables = [Term| Acc]
		)
	;	Term =.. [_| Args],
		'$lgt_quintus_term_variables_list'(Args, Acc, Variables)
	).

'$lgt_quintus_term_variables_list'([], Variables, Variables).
'$lgt_quintus_term_variables_list'([Term| Terms], Acc, Variables) :-
	'$lgt_quintus_term_variables'(Term, Acc, Acc2),
	'$lgt_quintus_term_variables_list'(Terms, Acc2, Variables).

'$lgt_quintus_var_member_chk'(Variable, [Head| Tail]) :-
	(	Variable == Head ->
		true
	;	'$lgt_quintus_var_member_chk'(Variable, Tail)
	).

'$lgt_quintus_reverse'([], Reversed, Reversed).
'$lgt_quintus_reverse'([Head| Tail], List, Reversed) :-
	'$lgt_quintus_reverse'(Tail, [Head| List], Reversed).

throw(Ball) :-
	raise_exception(Ball).

unify_with_occurs_check(Term1, Term2) :-
	unify(Term1, Term2).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  de facto standard Prolog predicates that might be missing
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% between(+integer, +integer, ?integer) -- library predicate

% findall(?term, +callable, ?list, +list)

findall(Term, Goal, List, Tail) :-
	findall(Term, Goal, List0),
	append(List0, Tail, List).

% forall(+callable, +callable) -- library predicate

% format(+stream_or_alias, +character_code_list_or_atom, +list) -- built-in

'$lgt_format'(Stream, Format, Arguments) :-
	format(Stream, Format, Arguments).

'$lgt_format'(Format, Arguments) :-
	format(Format, Arguments).

% format(+character_code_list_or_atom, +list) -- built-in

% numbervars(?term, +integer, ?integer) -- built-in

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  predicate properties
%
%  this predicate must return at least static, dynamic, and built_in
%  properties for an existing predicate (and ideally meta_predicate/1
%  properties for built-in predicates and library predicates)
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% '$lgt_predicate_property'(+callable, ?predicate_property)

'$lgt_predicate_property'(Pred, static) :-
	predicate_property(Pred, compiled).
'$lgt_predicate_property'(Pred, Prop) :-
	predicate_property(Pred, Prop).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  meta-predicates
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% setup_call_cleanup(+callable, +callable, +callable) -- not supported

% call/2-7

call(F, A) :-
	Call =.. [F, A],
	call(Call).

call(F, A1, A2) :-
	Call =.. [F, A1, A2],
	call(Call).

call(F, A1, A2, A3) :-
	Call =.. [F, A1, A2, A3],
	call(Call).

call(F, A1, A2, A3, A4) :-
	Call =.. [F, A1, A2, A3, A4],
	call(Call).

call(F, A1, A2, A3, A4, A5) :-
	Call =.. [F, A1, A2, A3, A4, A5],
	call(Call).

call(F, A1, A2, A3, A4, A5, A6) :-
	Call =.. [F, A1, A2, A3, A4, A5, A6],
	call(Call).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  Prolog non-standard built-in meta-predicates and meta-directives
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% '$lgt_prolog_meta_predicate'(@callable, ?callable, ?atom)

'$lgt_prolog_meta_predicate'(not(_), not(0), predicate).
'$lgt_prolog_meta_predicate'(on_exception(_, _, _), on_exception(*, 0, 0), predicate).

% '$lgt_prolog_meta_directive'(@callable, -callable)

'$lgt_prolog_meta_directive'(_, _) :-
	fail.

% '$lgt_prolog_to_logtalk_meta_argument_specifier_hook'(@nonvar, -atom)

'$lgt_prolog_to_logtalk_meta_argument_specifier_hook'(_, _) :-
	fail.

% '$lgt_candidate_tautology_or_falsehood_goal_hook'(@callable)
%
% valid candidates are proprietary built-in predicates with
% no side-effects when called with ground arguments

'$lgt_candidate_tautology_or_falsehood_goal_hook'(name(_, _)).

% '$lgt_prolog_database_predicate'(@callable)
%
% table of non-standard database built-in predicates

'$lgt_prolog_database_predicate'(assert(_)).
'$lgt_prolog_database_predicate'(assert(_, _)).
'$lgt_prolog_database_predicate'(asserta(_, _)).
'$lgt_prolog_database_predicate'(assertz(_, _)).
'$lgt_prolog_database_predicate'(clause(_, _, _)).
'$lgt_prolog_database_predicate'(listing(_)).

% '$lgt_prolog_predicate_property'(?callable)
%
% table of proprietary predicate properties; used by the
% compiler when checking if a predicate property is valid

'$lgt_prolog_predicate_property'(_) :-
	fail.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  file name extension predicates
%
%  these extensions are used by Logtalk load/compile predicates
%
%  you may want to change the extension for the intermediate files
%  generated by the Logtalk compiler ("object" files) to match the
%  extension expected by default by your Prolog compiler
%
%  there should only a single extension defined for object files but
%  but multiple extensions can be defined for Logtalk and Prolog source
%  files and for backend specific temporary files
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% '$lgt_file_extension'(?atom, ?atom)

'$lgt_file_extension'(logtalk, '.lgt').
'$lgt_file_extension'(logtalk, '.logtalk').
'$lgt_file_extension'(object, '.pl').
'$lgt_file_extension'(prolog, '.pl').
'$lgt_file_extension'(prolog, '.prolog').
'$lgt_file_extension'(prolog, '.pro').

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  backend Prolog compiler features
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% '$lgt_prolog_feature'(?atom, ?atom)
%
% backend Prolog compiler supported features (that are compatible with Logtalk)

'$lgt_prolog_feature'(prolog_dialect, quintus).
'$lgt_prolog_feature'(prolog_version, v(Major,Minor,0)) :-
	prolog_flag(version, Version),
	substring(Version, MajorAtom, 0, 1, 2),
	atom_chars(MajorAtom, MajorCodes),
	number_chars(Major, MajorCodes),
	substring(Version, MinorAtom, 2, 1, 0),
	atom_chars(MinorAtom, MinorCodes),
	number_chars(Minor, MinorCodes).
'$lgt_prolog_feature'(prolog_compatible_version, @>=(v(3,3,0))).

'$lgt_prolog_feature'(encoding_directive, unsupported).
'$lgt_prolog_feature'(tabling, unsupported).
'$lgt_prolog_feature'(engines, unsupported).
'$lgt_prolog_feature'(threads, unsupported).
'$lgt_prolog_feature'(modules, supported).
'$lgt_prolog_feature'(coinduction, unsupported).
'$lgt_prolog_feature'(unicode, unsupported).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  default flag values
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% '$lgt_default_flag'(?atom, ?atom)
%
% default values for all flags

% startup flags:
'$lgt_default_flag'(settings_file, allow).
% lint compilation flags:
'$lgt_default_flag'(unknown_entities, warning).
'$lgt_default_flag'(unknown_predicates, warning).
'$lgt_default_flag'(undefined_predicates, warning).
'$lgt_default_flag'(singleton_variables, warning).
'$lgt_default_flag'(steadfastness, silent).
'$lgt_default_flag'(naming, silent).
'$lgt_default_flag'(duplicated_clauses, silent).
'$lgt_default_flag'(tail_recursive, silent).
'$lgt_default_flag'(disjunctions, warning).
'$lgt_default_flag'(conditionals, warning).
'$lgt_default_flag'(catchall_catch, silent).
'$lgt_default_flag'(portability, silent).
'$lgt_default_flag'(redefined_built_ins, silent).
'$lgt_default_flag'(redefined_operators, warning).
'$lgt_default_flag'(deprecated, warning).
'$lgt_default_flag'(missing_directives, warning).
'$lgt_default_flag'(duplicated_directives, warning).
'$lgt_default_flag'(trivial_goal_fails, warning).
'$lgt_default_flag'(always_true_or_false_goals, warning).
'$lgt_default_flag'(lambda_variables, warning).
'$lgt_default_flag'(suspicious_calls, warning).
'$lgt_default_flag'(underscore_variables, singletons).
% optional features compilation flags:
'$lgt_default_flag'(complements, deny).
'$lgt_default_flag'(dynamic_declarations, deny).
'$lgt_default_flag'(events, deny).
'$lgt_default_flag'(context_switching_calls, allow).
% other compilation flags:
'$lgt_default_flag'(scratch_directory, './').
'$lgt_default_flag'(report, on).
'$lgt_default_flag'(clean, on).
'$lgt_default_flag'(code_prefix, '$').
'$lgt_default_flag'(optimize, off).
'$lgt_default_flag'(source_data, on).
'$lgt_default_flag'(reload, changed).
'$lgt_default_flag'(debug, off).
% Prolog compiler and loader flags:
'$lgt_default_flag'(prolog_compiler, []).
'$lgt_default_flag'(prolog_loader, []).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  operating-system access predicates
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% '$lgt_prolog_os_file_name'(+atom, -atom)
% '$lgt_prolog_os_file_name'(-atom, +atom)
%
% converts between Prolog internal file paths and operating-system paths

'$lgt_prolog_os_file_name'(Path, Path).

% '$lgt_expand_path'(+atom, -atom)
%
% expands a file path to a full path

'$lgt_expand_path'(Path, ExpandedPath) :-
	% first expand any environment variable in the path
	expanded_file_name(Path, ExpandedPath0),
	'$lgt_quintus_convert_file_path'(ExpandedPath0, ExpandedPath1),
	(	absolute_file_name(ExpandedPath1, [file_errors(fail)], ExpandedPath) ->
		true
	;	absolute_file_name(ExpandedPath1, [file_type(directory), file_errors(fail)], ExpandedPath)
	).

'$lgt_quintus_convert_file_path'(File, Converted) :-
	atom_codes(File, FileCodes),
	'$lgt_quintus_reverse_slashes'(FileCodes, ConvertedCodes),
	atom_codes(Converted, ConvertedCodes).

'$lgt_quintus_reverse_slashes'([], []).
'$lgt_quintus_reverse_slashes'([Code| Codes], [ConvertedCode| ConvertedCodes]) :-
	(	char_code('\\', Code) ->
		char_code('/', ConvertedCode)
	;	ConvertedCode = Code
	),
	'$lgt_quintus_reverse_slashes'(Codes, ConvertedCodes).

% '$lgt_file_exists'(+atom)
%
% checks if a file exists

'$lgt_file_exists'(File) :-
	file_exists(File).

% '$lgt_delete_file'(+atom)
%
% deletes a file

'$lgt_delete_file'(File) :-
	delete_file(File).

% '$lgt_directory_exists'(+atom)
%
% checks if a directory exists

'$lgt_directory_exists'(Directory) :-
	'$lgt_expand_path'(Directory, ExpandedPath),
	absolute_file_name(ExpandedPath, [access(exist), file_type(directory), file_errors(fail)], _).

% '$lgt_current_directory'(-atom)
%
% gets current working directory

'$lgt_current_directory'(Directory) :-
	absolute_file_name('.', Directory).

% '$lgt_change_directory'(+atom)
%
% changes current working directory

'$lgt_change_directory'(Directory) :-
	unix(cd(Directory)).

% '$lgt_make_directory'(+atom)
%
% makes a new directory; succeeds if the directory already exists

'$lgt_make_directory'(Directory) :-
	'$lgt_expand_path'(Directory, Path),
	(	absolute_file_name(Path, [access(exist), file_type(directory), file_errors(fail)], _) ->
		true
	;	atom_concat('mkdir ', Path, Command),
		unix(system(Command))
	).

% '$lgt_directory_hash_dialect_as_atom'(+atom, -atom)
%
% returns the directory hash and dialect as an atom with the format _hash_dialect

'$lgt_directory_hash_dialect_as_atom'(Directory, Hash) :-
	hash_term(Directory, Hash0),
	'$lgt_prolog_feature'(prolog_dialect, Dialect),
	number_chars(Hash0, Hash0Codes),
	atom_chars(Dialect, DialectCodes),
	append([0'_| Hash0Codes], [0'_| DialectCodes], HashCodes),
	atom_chars(Hash, HashCodes).

% '$lgt_directory_hash_pid_as_atom'(+atom, -atom)
%
% returns the directory hash and PID as an atom with the format _hash_pid

'$lgt_directory_hash_pid_as_atom'(Directory, Hash) :-
	hash_term(Directory, Hash0),
	number_chars(Hash0, Codes),
	atom_chars(Hash, [0'_| Codes]).

% '$lgt_compile_prolog_code'(+atom, +atom, +list)
%
% compile to disk a Prolog file, resulting from a
% Logtalk source file, given a list of flags

'$lgt_compile_prolog_code'(_, _, _).

% '$lgt_load_prolog_code'(+atom, +atom, +list)
%
% compile and load a Prolog file, resulting from a
% Logtalk source file, given a list of flags

'$lgt_load_prolog_code'(File, _, _) :-
	compile(File).

% '$lgt_load_prolog_file'(+atom)
%
% compile and (re)load a Prolog file (used in standards compliance tests)

'$lgt_load_prolog_file'(File) :-
	compile(File).

% '$lgt_file_modification_time'(+atom, -nonvar)
%
% gets a file modification time, assumed to be an opaque term but comparable

'$lgt_file_modification_time'(File, Time) :-
	file_property(File, modify_time, Time).

% '$lgt_environment_variable'(?atom, ?atom)
%
% access to operating-system environment variables

'$lgt_environment_variable'(Variable, Value) :-
	environ(Variable, Value).

% '$lgt_decompose_file_name'(+atom, ?atom, ?atom, ?atom)
%
% decomposes a file path in its components; the directory must always end
% with a slash; the extension must start with a "." when defined and must
% be the empty atom when it does not exist

'$lgt_decompose_file_name'(File, Directory, Name, Extension) :-
	atom_codes(File, FileCodes),
	(	'$lgt_strrch'(FileCodes, 0'/, [_Slash| BasenameCodes]) ->
		atom_codes(Basename, BasenameCodes),
		atom_concat(Directory, Basename, File)
	;	Directory = './',
		atom_codes(Basename, FileCodes),
		BasenameCodes = FileCodes
	),
	(	'$lgt_strrch'(BasenameCodes, 0'., ExtensionCodes) ->
		atom_codes(Extension, ExtensionCodes),
		atom_concat(Name, Extension, Basename)
	;	Name = Basename,
		Extension = ''
	).

% the following auxiliary predicate is simplified version of code
% written by Per Mildner and is used here with permission
'$lgt_strrch'(Xs, G, Ys) :-
	Xs = [X| Xs1],
	(	X == G ->
		'$lgt_strrch1'(Xs1, G, Xs, Ys)
	;	'$lgt_strrch'(Xs1, G, Ys)
	).

'$lgt_strrch1'([], _G, Ys, Ys).
'$lgt_strrch1'([X| Xs1], G, Prev, Ys) :-
	(	X == G ->
		'$lgt_strrch1'(Xs1, G, [X| Xs1], Ys)
	;	'$lgt_strrch1'(Xs1, G, Prev, Ys)
	).

% '$lgt_directory_files'(+atom, -list(atom))
%
% returns a list of files in the given directory

'$lgt_directory_files'(Directory, Files) :-
	findall(File1, file_member_of_directory(Directory, File1, _), Files1),
	findall(Directory1, directory_member_of_directory(Directory, Directory1, _), Directories1),
	append(['.', '..'| Directories1], Files1, Files).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  getting stream current line number
%  (needed for improved compiler error messages)
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% '$lgt_stream_current_line_number'(@stream, -integer)

'$lgt_stream_current_line_number'(Stream, Line) :-
	line_count(Stream, Line).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  abstraction of the standard open/4 and close/1 predicates for dealing
%  with required proprietary actions when opening and closing streams
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% '$lgt_open'(+atom, +atom, -stream, @list)

'$lgt_open'(File, Mode, Stream, Options) :-
	(	Options = [alias(Alias)| OtherOptions] ->
		open(File, Mode, OtherOptions, Stream),
		'$lgt_quintus_save_stream_alias'(Stream, Alias)
	;	open(File, Mode, Options, Stream)
	).

% '$lgt_close'(@stream)

'$lgt_close'(Stream) :-
	retractall('$lgt_quintus_stream_alias'(Stream, _)),
	close(Stream).

:- dynamic('$lgt_quintus_stream_alias'/2).

'$lgt_quintus_save_stream_alias'(Stream, Alias) :-
	retractall('$lgt_quintus_stream_alias'(Stream, _)),
	asserta('$lgt_quintus_stream_alias'(Stream, Alias)).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  customized version of the read_term/3 predicate for returning the term
%  position (start and end lines; needed for improved error messages) and
%  the variable names (ideally using the standard variable_names/1 option)
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% '$lgt_read_term'(@stream, -term, +list, -pair(integer,integer))

'$lgt_read_term'(Stream, Term, Options, LineBegin-LineEnd) :-
	line_count(Stream, LineBegin),
	read_term(Stream, [syntax_errors(error)| Options], Term),
	line_count(Stream, LineEnd).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  Prolog dialect specific term and goal expansion
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% '$lgt_prolog_term_expansion'(@callable, -callable)

'$lgt_prolog_term_expansion'(_, _) :-
	fail.

% '$lgt_prolog_goal_expansion'(@callable, -callable)

% some built-in predicate use a argument order different from the one that become the standard
'$lgt_prolog_goal_expansion'(read_term(Term, Options), {read_term(Options, Term)}).
'$lgt_prolog_goal_expansion'(read_term(Stream, Term, Options), {read_term(Stream, Options, Term)}).
'$lgt_prolog_goal_expansion'(open(File, Mode, Stream, Options), {open(File, Mode, Options, Stream)}).
% most arithmetic functions are implemented as predicates
'$lgt_prolog_goal_expansion'(Result is Expression, {Head}) :-
	'$lgt_quintus_arithmetic_expression_to_head'(Result is Expression, Head),
	'$lgt_quintus_arithmetic_expression_to_goal'(Expression, Result, Goal),
	'$lgt_compile_aux_clauses'([({Head} :- {Goal})]).
'$lgt_prolog_goal_expansion'(X =:= Y, {Head}) :-
	'$lgt_quintus_arithmetic_expression_to_head'(X =:= Y, Head),
	'$lgt_quintus_arithmetic_expression_to_goal'(X, ResultX, GoalX),
	'$lgt_quintus_arithmetic_expression_to_goal'(Y, ResultY, GoalY),
	'$lgt_compile_aux_clauses'([({Head} :- {GoalX, GoalY, ResultX =:= ResultY})]).
'$lgt_prolog_goal_expansion'(X =\= Y, {Head}) :-
	'$lgt_quintus_arithmetic_expression_to_head'(X =\= Y, Head),
	'$lgt_quintus_arithmetic_expression_to_goal'(X, ResultX, GoalX),
	'$lgt_quintus_arithmetic_expression_to_goal'(Y, ResultY, GoalY),
	'$lgt_compile_aux_clauses'([({Head} :- {GoalX, GoalY, ResultX =\= ResultY})]).
'$lgt_prolog_goal_expansion'(X < Y, {Head}) :-
	'$lgt_quintus_arithmetic_expression_to_head'(X < Y, Head),
	'$lgt_quintus_arithmetic_expression_to_goal'(X, ResultX, GoalX),
	'$lgt_quintus_arithmetic_expression_to_goal'(Y, ResultY, GoalY),
	'$lgt_compile_aux_clauses'([({Head} :- {GoalX, GoalY, ResultX < ResultY})]).
'$lgt_prolog_goal_expansion'(X =< Y, {Head}) :-
	'$lgt_quintus_arithmetic_expression_to_head'(X =< Y, Head),
	'$lgt_quintus_arithmetic_expression_to_goal'(X, ResultX, GoalX),
	'$lgt_quintus_arithmetic_expression_to_goal'(Y, ResultY, GoalY),
	'$lgt_compile_aux_clauses'([({Head} :- {GoalX, GoalY, ResultX =< ResultY})]).
'$lgt_prolog_goal_expansion'(X > Y, {Head}) :-
	'$lgt_quintus_arithmetic_expression_to_head'(X > Y, Head),
	'$lgt_quintus_arithmetic_expression_to_goal'(X, ResultX, GoalX),
	'$lgt_quintus_arithmetic_expression_to_goal'(Y, ResultY, GoalY),
	'$lgt_compile_aux_clauses'([({Head} :- {GoalX, GoalY, ResultX > ResultY})]).
'$lgt_prolog_goal_expansion'(X >= Y, {Head}) :-
	'$lgt_quintus_arithmetic_expression_to_head'(X >= Y, Head),
	'$lgt_quintus_arithmetic_expression_to_goal'(X, ResultX, GoalX),
	'$lgt_quintus_arithmetic_expression_to_goal'(Y, ResultY, GoalY),
	'$lgt_compile_aux_clauses'([({Head} :- {GoalX, GoalY, ResultX >= ResultY})]).

'$lgt_quintus_arithmetic_expression_to_head'(Expression, Head) :-
	term_variables(Expression, Variables),
	gensym('$lgt_quintus_ae_', Functor),
	Head =.. [Functor| Variables].

'$lgt_quintus_arithmetic_expression_to_goal'(Expression, Result, ExpressionGoal) :-
	(	var(Expression) ->
		ExpressionGoal = (Result is Expression)
	;	number(Expression) ->
		ExpressionGoal = (Result is Expression)
	;	'$lgt_quintus_arithmetic_function_1'(Expression, Result, X, ResultX, Goal) ->
		'$lgt_quintus_arithmetic_expression_to_goal'(X, ResultX, GoalX),
		ExpressionGoal = (GoalX, Goal)
	;	'$lgt_quintus_arithmetic_function_2'(Expression, Result, X, ResultX, Y, ResultY, Goal) ->
		'$lgt_quintus_arithmetic_expression_to_goal'(X, ResultX, GoalX),
		'$lgt_quintus_arithmetic_expression_to_goal'(Y, ResultY, GoalY),
		ExpressionGoal = (GoalX, GoalY, Goal)
	).

'$lgt_quintus_arithmetic_function_1'(abs(X), Result, X, ResultX, abs(ResultX, Result)).
'$lgt_quintus_arithmetic_function_1'(atan(X), Result, X, ResultX, atan(ResultX, Result)).
'$lgt_quintus_arithmetic_function_1'(ceiling(X), Result, X, ResultX, ceiling(ResultX, Result)).
'$lgt_quintus_arithmetic_function_1'(cos(X), Result, X, ResultX, cos(ResultX, Result)).
'$lgt_quintus_arithmetic_function_1'(exp(X), Result, X, ResultX, exp(ResultX, Result)).
'$lgt_quintus_arithmetic_function_1'(float(X), Result, X, ResultX, Result is float(ResultX)).
'$lgt_quintus_arithmetic_function_1'(floor(X), Result, X, ResultX, floor(ResultX, Result)).
'$lgt_quintus_arithmetic_function_1'(log(X), Result, X, ResultX, log(ResultX, Result)).
'$lgt_quintus_arithmetic_function_1'(round(X), Result, X, ResultX, round(ResultX, Result)).
'$lgt_quintus_arithmetic_function_1'(sign(X), Result, X, ResultX, sign(ResultX, Result)).
'$lgt_quintus_arithmetic_function_1'(sin(X), Result, X, ResultX, sin(ResultX, Result)).
'$lgt_quintus_arithmetic_function_1'(sqrt(X), Result, X, ResultX, sqrt(ResultX, Result)).
'$lgt_quintus_arithmetic_function_1'(truncate(X), Result, X, ResultX, truncate(ResultX, Result)).

'$lgt_quintus_arithmetic_function_2'(X + Y, Result, X, ResultX, Y, ResultY, Result is ResultX + ResultY).
'$lgt_quintus_arithmetic_function_2'(X - Y, Result, X, ResultX, Y, ResultY, Result is ResultX - ResultY).
'$lgt_quintus_arithmetic_function_2'(X * Y, Result, X, ResultX, Y, ResultY, Result is ResultX * ResultY).
'$lgt_quintus_arithmetic_function_2'(X / Y, Result, X, ResultX, Y, ResultY, Result is ResultX / ResultY).
'$lgt_quintus_arithmetic_function_2'(X // Y, Result, X, ResultX, Y, ResultY, Result is ResultX // ResultY).
'$lgt_quintus_arithmetic_function_2'(X ** Y, Result, X, ResultX, Y, ResultY, pow(ResultX, ResultY, Result)).
'$lgt_quintus_arithmetic_function_2'(X mod Y, Result, X, ResultX, Y, ResultY, Result is ResultX mod ResultY).
'$lgt_quintus_arithmetic_function_2'(min(X, Y), Result, X, ResultX, Y, ResultY, min(ResultX, ResultY, Result)).
'$lgt_quintus_arithmetic_function_2'(max(X, Y), Result, X, ResultX, Y, ResultY, max(ResultX, ResultY, Result)).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  converts between Prolog stream encoding names and XML encoding names
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% '$lgt_logtalk_prolog_encoding'(?atom, ?atom, +stream)

'$lgt_logtalk_prolog_encoding'(_, _, _) :-
	fail.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  lambda expressions support predicates
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% '$lgt_copy_term_without_constraints'(@term, ?term)

'$lgt_copy_term_without_constraints'(Term, Copy) :-
	copy_term(Term, Copy).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  hooks predicates for writing and asserting compiled entity terms
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% '$lgt_write_compiled_term'(@stream, @callable, +atom, +atom, +integer)
%
% the third argument is the term type: runtime (internal runtime clause),
% user (compiled user-defined term), or aux (auxiliary clause resulting
% e.g. from term-expansion)

'$lgt_write_compiled_term'(Stream, Term, _Kind, _Path, _Line) :-
	write_canonical(Stream, Term),
	write(Stream, '.\n').

% '$lgt_assertz_entity_clause'(@clause, +atom)

'$lgt_assertz_entity_clause'(Clause, _Kind) :-
	assertz(Clause).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  error term normalization (when exception terms don't follow the ISO
%  Prolog standard)
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% '$lgt_normalize_error_term'(@callable, -callable)

'$lgt_normalize_error_term'(
	error(existence_error(_, _, procedure, ':'(user, Functor/Arity), _), _),
	error(existence_error(procedure, Functor/Arity), _)
).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  message token printing
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%:- multifile('$logtalk#0.print_message_token#4'/5).
%:- dynamic('$logtalk#0.print_message_token#4'/5).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  term hashing (not currently used in the compiler/runtime)
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% term_hash(@callable, +integer, +integer, -integer)

term_hash(_, _, _, _) :-
	fail.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  atomics concat (not currently used in the compiler/runtime)
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% atomic_concat(+atomic, +atomic, ?atom)

atomic_concat(Atomic1, Atomic2, Atom) :-
	(	var(Atomic1) ->
		throw(error(instantiation_error, atomic_concat/3))
	;	var(Atomic2) ->
		throw(error(instantiation_error, atomic_concat/3))
	;	\+ atomic(Atomic1) ->
		throw(error(type_error(atomic, Atomic1), atomic_concat/3))
	;	\+ atomic(Atomic2) ->
		throw(error(type_error(atomic, Atomic2), atomic_concat/3))
	;	'$lgt_quintus_atomic_atom'(Atomic1, Atom1),
		'$lgt_quintus_atomic_atom'(Atomic2, Atom2),
		atom_concat(Atom1, Atom2, Atom)
	).

'$lgt_quintus_atomic_atom'(Atomic, Atom) :-
	(	atom(Atomic) ->
		Atom = Atomic
	;	number_chars(Atomic, Codes),
		atom_chars(Atom, Codes)
	).

% atomic_list_concat(@list(atomic), ?atom)

atomic_list_concat([Atomic| Atomics], Atom) :-
	!,
	(	var(Atomic) ->
		throw(error(instantiation_error, atomic_list_concat/2))
	;	\+ atomic(Atomic) ->
		throw(error(type_error(atomic, Atomic), atomic_list_concat/2))
	;	'$lgt_quintus_atomic_atom'(Atomic, Atom0),
		'$lgt_quintus_atomic_list_concat'(Atomics, Atom0, Atom)
	).
atomic_list_concat([], '').

'$lgt_quintus_atomic_list_concat'([Next| Atomics], Atom0, Atom) :-
	!,
	atomic_list_concat([Next| Atomics], Atom1),
	atom_concat(Atom0, Atom1, Atom).
'$lgt_quintus_atomic_list_concat'([], Atom, Atom).

% atomic_list_concat(@list(atomic), +atom, ?atom)

atomic_list_concat([Atomic| Atomics], Separator, Atom) :-
	!,
	(	var(Atomic) ->
		throw(error(instantiation_error, atomic_list_concat/3))
	;	var(Separator) ->
		throw(error(instantiation_error, atomic_list_concat/3))
	;	\+ atomic(Atomic) ->
		throw(error(type_error(atomic, Atomic), atomic_list_concat/3))
	;	\+ atomic(Separator) ->
		throw(error(type_error(atomic, Separator), atomic_list_concat/3))
	;	'$lgt_quintus_atomic_atom'(Atomic, Atom0),
		'$lgt_quintus_atomic_atom'(Separator, SeparatorAtom),
		'$lgt_quintus_atomic_list_concat'(Atomics, Atom0, SeparatorAtom, Atom)
	).
atomic_list_concat([], _, '').

'$lgt_quintus_atomic_list_concat'([Next| Atomics], Atom0, SeparatorAtom, Atom) :-
	!,
	atomic_list_concat([Next| Atomics], SeparatorAtom, Atom2),
	atom_concat(SeparatorAtom, Atom2, Atom1),
	atom_concat(Atom0, Atom1, Atom).
'$lgt_quintus_atomic_list_concat'([], Atom, _, Atom).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  string built-in type
%
%  define these predicates to trivially fail if no string type is available
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% '$lgt_string'(@term)

'$lgt_string'(_) :-
	fail.

% '$lgt_string_codes'(+string, -list(codes))
% '$lgt_string_codes'(-string, +list(codes))

'$lgt_string_codes'(_, _) :-
	fail.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  module qualification to be used when calling Prolog meta-predicates
%  with meta-arguments that are calls to object or category predicates
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% '$lgt_user_module_qualification'(@callable, -callable)

'$lgt_user_module_qualification'(Goal, user:Goal).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  auxiliary predicates for compiling modules as objects
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% '$lgt_find_module_predicate'(+atom, -atom, @callable)
%
% succeeds when Module:Predicate is visible in module Current

'$lgt_find_visible_module_predicate'(_Current, _Module, _Predicate) :-
	fail.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  shortcuts to the Logtalk built-in predicates logtalk_load/1 and
%  logtalk_make/1
%
%  defined in the adapter files to make it easier to comment them out in case
%  of conflict with some Prolog native feature; they require conformance with
%  the ISO Prolog standard regarding the definition of the {}/1 syntax
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

{X} :-
	var(X),
	throw(error(instantiation_error, logtalk({X}, _))).
{*} :-
	!,
	logtalk_make(all).
{!} :-
	!,
	logtalk_make(clean).
{?} :-
	!,
	logtalk_make(check).
{@} :-
	!,
	logtalk_make(circular).
{#} :-
	!,
	logtalk_make(documentation).
{+d} :-
	!,
	logtalk_make(debug).
{+n} :-
	!,
	logtalk_make(normal).
{+o} :-
	!,
	logtalk_make(optimal).
{$} :-
	!,
	logtalk_make(caches).

{Files} :-
	'$lgt_conjunction_to_list'(Files, List),
	logtalk_load(List).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  end!
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


text:
module("luci.controller.vnstat", package.seeall)

function index()
	entry({"admin", "status", "vnstat"}, alias("admin", "status", "vnstat", "graphs"), _("VnStat Traffic Monitor"), 90).i18n = "vnstat"
	entry({"admin", "status", "vnstat", "graphs"}, template("vnstat"), _("Graphs"), 1)
	entry({"admin", "status", "vnstat", "config"}, cbi("vnstat"), _("Configuration"), 2)

	entry({"mini", "network", "vnstat"}, alias("mini", "network", "vnstat", "graphs"), _("VnStat Traffic Monitor"), 90).i18n = "vnstat"
	entry({"mini", "network", "vnstat", "graphs"}, template("vnstat"), _("Graphs"), 1)
	entry({"mini", "network", "vnstat", "config"}, cbi("vnstat"), _("Configuration"), 2)
end