text:
/**
 * Created by JetBrains PhpStorm.
 * User: xliu
 * Date: 24/02/14
 * Time: 14:03
 * To change this template use File | Settings | File Templates.
 */

goog.provide("dotasim.features.maingame.v.components.HeroUnit");
goog.require("dotasim.features.maingame.v.components.Unit");

dotasim.HeroUnit = function(party)
{
    dotasim.Unit.call(this, party);

    //hero unit is slightly bigger
    this.scaleX = this.scaleY = 1.3;
};
BOK.inherits(dotasim.HeroUnit, dotasim.Unit);

redpajama_set_name: RedPajamaGithub


text:
package com.riversoft.weixin.qy;

import com.fasterxml.jackson.annotation.JsonRootName;
import com.riversoft.weixin.common.menu.Menu;
import com.riversoft.weixin.common.util.JsonMapper;
import com.riversoft.weixin.qy.agent.Agents;
import com.riversoft.weixin.qy.agent.bean.Agent;
import com.riversoft.weixin.qy.media.Medias;
import com.riversoft.weixin.common.media.MediaType;
import com.riversoft.weixin.qy.menu.Menus;
import org.apache.commons.io.IOUtils;
import org.junit.Test;

import java.io.IOException;

/**
 * Created by exizhai on 10/6/2015.
 */
public class Starter {

    @Test
    public void testStart() throws IOException {
        String json = IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream("agent.json"));
        ExampleAgent exampleAgent = JsonMapper.nonEmptyMapper().fromJson(json, ExampleAgent.class);

        String logo = Medias.defaultMedias().upload(MediaType.image, this.getClass().getClassLoader().getResourceAsStream("media/image.png"), "image.png");
        exampleAgent.getAgent().setLogoMediaId(logo);

        Agents.defaultAgents().update(exampleAgent.getAgent());
        Menus.defaultMenus().delete(45);
        Menus.defaultMenus().create(45, exampleAgent.getMenu());
    }

    @JsonRootName("example-agent")
    public static class ExampleAgent {

        private Agent agent;

        private Menu menu;

        public Agent getAgent() {
            return agent;
        }

        public void setAgent(Agent agent) {
            this.agent = agent;
        }

        public Menu getMenu() {
            return menu;
        }

        public void setMenu(Menu menu) {
            this.menu = menu;
        }
    }
}


text:
package org.onosproject.drivers.fujitsu;

import com.google.common.collect.ImmutableList;
import org.apache.commons.configuration.HierarchicalConfiguration;
import org.onosproject.drivers.utilities.XmlConfigParser;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;
import org.apache.commons.configuration.tree.ConfigurationNode;
import org.onlab.packet.IpAddress;
import org.onosproject.mastership.MastershipService;
import org.onosproject.net.Annotations;
import org.onosproject.net.DefaultAnnotations;
import org.onosproject.net.DeviceId;
import org.onosproject.net.behaviour.ControllerConfig;
import org.onosproject.net.behaviour.ControllerInfo;
import org.onosproject.net.driver.AbstractHandlerBehaviour;
import org.onosproject.net.driver.DriverHandler;
import org.onosproject.netconf.NetconfController;
import org.onosproject.netconf.NetconfDevice;
import org.onosproject.netconf.NetconfException;
import org.slf4j.Logger;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import static com.google.common.base.Preconditions.checkNotNull;
import static org.slf4j.LoggerFactory.getLogger;

/**
 * Implementation to get and set parameters available in VOLT NE
 * through the Netconf protocol.
 */
public class FujitsuVoltControllerConfig extends AbstractHandlerBehaviour
        implements ControllerConfig {

    private final Logger log = getLogger(FujitsuVoltControllerConfig.class);
    private static final String RESOURCE_XML = "voltcontrollers.xml";

    private static final String DOT = ".";
    private static final String L_ANGLE_BR = "<";
    private static final String R_ANGLE_BR = "/>";
    private static final String VOLT_NE_NAMESPACE =
            "xmlns=\"http://fujitsu.com/ns/volt/1.1\"";
    private static final String DATA = "data";
    private static final String VOLT_NE = "volt-ne";
    private static final String VOLT_OFCONFIG = "volt-ofconfig";
    private static final String OF_CONTROLLERS = "of-controllers";
    private static final String OF_CONTROLLER = "of-controller";
    private static final String CONTROLLER_INFO = "controller-info";
    private static final String REPORT_ALL = "report-all";
    private static final String IP_ADDRESS = "ip-address";
    private static final String PORT = "port";
    private static final String PROTOCOL = "protocol";
    private static final String CONFIG = "config";
    private static final String OFCONFIG_ID = "ofconfig-id";
    private static final String EDIT_CONFIG = "edit-config";
    private static final String TARGET = "target";
    private static final String RUNNING = "running";
    private static final String MERGE = "merge";
    private static final String DEFAULT_OPERATION = "default-operation";

    private static final String VOLT_NE_OPEN = "<" + VOLT_NE + " ";
    private static final String VOLT_NE_CLOSE = "</" + VOLT_NE + ">";
    private static final String VOLT_OFCONFIG_EL = "<" + VOLT_OFCONFIG + "/>\n";
    private static final String TARGET_OPEN = "<" + TARGET + ">";
    private static final String TARGET_CLOSE = "</" + TARGET + ">";
    private static final String END_LICENSE_HEADER = "-->";

    private static final String VOLT_DATACONFIG = DATA + DOT + VOLT_NE + DOT +
            VOLT_OFCONFIG + DOT + OF_CONTROLLERS + DOT + OF_CONTROLLER;

    private static final String EDIT_CONFIG_TG = EDIT_CONFIG + DOT + TARGET;
    private static final String EDIT_CONFIG_DO = EDIT_CONFIG + DOT + DEFAULT_OPERATION;
    private static final String CONTROLLER_INFO_ID = CONTROLLER_INFO + DOT + "id";
    private static final String CONTROLLER_INFO_IP = CONTROLLER_INFO + DOT + IP_ADDRESS;
    private static final String CONTROLLER_INFO_PORT = CONTROLLER_INFO + DOT + PORT;
    private static final String CONTROLLER_INFO_PROTOCOL = CONTROLLER_INFO + DOT + PROTOCOL;

    private static final String VOLT_EDITCONFIG = EDIT_CONFIG + DOT +
            CONFIG + DOT + VOLT_NE + DOT + VOLT_OFCONFIG + DOT + OF_CONTROLLERS;

    @Override
    public List<ControllerInfo> getControllers() {
        DriverHandler handler = handler();
        NetconfController controller = handler.get(NetconfController.class);
        MastershipService mastershipService = handler.get(MastershipService.class);
        DeviceId ncDeviceId = handler.data().deviceId();
        checkNotNull(controller, "Netconf controller is null");
        List<ControllerInfo> controllers = new ArrayList<>();
        if (mastershipService.isLocalMaster(ncDeviceId)) {
            try {
                StringBuilder request = new StringBuilder();
                request.append(VOLT_NE_OPEN).append(VOLT_NE_NAMESPACE).append(">\n");
                request.append(VOLT_OFCONFIG_EL);
                request.append(VOLT_NE_CLOSE);

                String reply;
                reply = controller.
                        getDevicesMap().get(ncDeviceId).getSession().
                        get(request.toString(), REPORT_ALL);
                log.debug("Reply XML {}", reply);
                controllers.addAll(parseStreamVoltControllers(XmlConfigParser.
                        loadXml(new ByteArrayInputStream(reply.getBytes(StandardCharsets.UTF_8)))));
            } catch (IOException e) {
                log.error("Cannot communicate to device {} ", ncDeviceId);
            }
        } else {
            log.warn("I'm not master for {} please use master, {} to execute command",
                     ncDeviceId,
                     mastershipService.getMasterFor(ncDeviceId));
        }
        return ImmutableList.copyOf(controllers);
    }

    @Override
    public void setControllers(List<ControllerInfo> controllers) {
        DriverHandler handler = handler();
        NetconfController controller = handler.get(NetconfController.class);
        MastershipService mastershipService = handler.get(MastershipService.class);
        DeviceId ncdeviceId = handler.data().deviceId();
        checkNotNull(controller, "Netconf controller is null");
        if (mastershipService.isLocalMaster(ncdeviceId)) {
            try {
                NetconfDevice device = controller.getNetconfDevice(ncdeviceId);
                String config = createVoltControllersConfig(
                        XmlConfigParser.loadXml(getClass().
                                getResourceAsStream(RESOURCE_XML)),
                        RUNNING, MERGE, controllers);
                device.getSession().editConfig(config.substring(
                        config.indexOf(END_LICENSE_HEADER) + END_LICENSE_HEADER.length()));
            } catch (NetconfException e) {
                log.error("Cannot communicate to device {} , exception ", ncdeviceId, e);
            }
        } else {
            log.warn("I'm not master for {} please use master, {} to execute command",
                     ncdeviceId,
                     mastershipService.getMasterFor(ncdeviceId));
        }
    }

    /**
     * Parses XML string to get controller information.
     *
     * @param cfg a hierarchical configuration
     * @return a list of controllers
     */
    private List<ControllerInfo> parseStreamVoltControllers(HierarchicalConfiguration cfg) {
        List<ControllerInfo> controllers = new ArrayList<>();
        List<HierarchicalConfiguration> fields =
                cfg.configurationsAt(VOLT_DATACONFIG);

        for (HierarchicalConfiguration sub : fields) {
            List<HierarchicalConfiguration> childFields =
                    sub.configurationsAt(CONTROLLER_INFO);

            for (HierarchicalConfiguration child : childFields) {
                Annotations annotations = DefaultAnnotations.builder()
                        .set(OFCONFIG_ID, sub.getString(OFCONFIG_ID)).build();
                ControllerInfo controller = new ControllerInfo(
                        IpAddress.valueOf(child.getString(IP_ADDRESS)),
                        Integer.parseInt(child.getString(PORT)),
                        child.getString(PROTOCOL), annotations);

                log.debug("VOLT: OFCONTROLLER: PROTOCOL={}, IP={}, PORT={}, ID={} ",
                          controller.type(), controller.ip(),
                          controller.port(), controller.annotations().value(OFCONFIG_ID));
                controllers.add(controller);
            }
        }
        return controllers;
    }

    /**
     * Forms XML string to change controller information.
     *
     * @param cfg a hierarchical configuration
     * @param target the type of configuration
     * @param netconfOperation operation type
     * @param controllers list of controllers
     * @return XML string
     */
    public static String createVoltControllersConfig(HierarchicalConfiguration cfg,
                                                     String target, String netconfOperation,
                                                     List<ControllerInfo> controllers) {
        XMLConfiguration editcfg = null;

        cfg.setProperty(EDIT_CONFIG_TG, target);
        cfg.setProperty(EDIT_CONFIG_DO, netconfOperation);

        List<ConfigurationNode> newControllers = new ArrayList<>();
        for (ControllerInfo ci : controllers) {
            XMLConfiguration controller = new XMLConfiguration();
            controller.setRoot(new HierarchicalConfiguration.Node(OF_CONTROLLER));
            controller.setProperty(OFCONFIG_ID, ci.annotations().value(OFCONFIG_ID));
            controller.setProperty(CONTROLLER_INFO_ID, ci.annotations().value(OFCONFIG_ID));
            controller.setProperty(CONTROLLER_INFO_IP, ci.ip());
            controller.setProperty(CONTROLLER_INFO_PORT, ci.port());
            controller.setProperty(CONTROLLER_INFO_PROTOCOL, ci.type());
            newControllers.add(controller.getRootNode());
        }
        cfg.addNodes(VOLT_EDITCONFIG, newControllers);

        try {
             editcfg = (XMLConfiguration) cfg;
        } catch (ClassCastException e) {
            e.printStackTrace();
        }
        StringWriter stringWriter = new StringWriter();
        try {
            editcfg.save(stringWriter);
        } catch (ConfigurationException e) {
            e.printStackTrace();
        }
        String s = stringWriter.toString();
        s = s.replace(TARGET_OPEN + target + TARGET_CLOSE,
                      TARGET_OPEN + L_ANGLE_BR + target + R_ANGLE_BR + TARGET_CLOSE);
        return s;
    }

}


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	errorHandler = require('./errors.server.controller'),
	Application = mongoose.model('Application'),
	_ = require('lodash');

/**
 * Create a Application
 */
exports.create = function(req, res) {
	var application = new Application(req.body);
	application.user = req.user;

	application.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(application);
		}
	});
};

/**
 * Show the current Application
 */
exports.read = function(req, res) {
	res.jsonp(req.application);
};

/**
 * Update a Application
 */
exports.update = function(req, res) {
	var application = req.application ;

	application = _.extend(application , req.body);

	application.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(application);
		}
	});
};

/**
 * Delete an Application
 */
exports.delete = function(req, res) {
	var application = req.application ;

	application.remove(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(application);
		}
	});
};

/**
 * List of Applications
 */
exports.list = function(req, res) {
	Application.find().sort('-created').populate('user', 'displayName').exec(function(err, applications) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(applications);
		}
	});
};

/**
 * Application middleware
 */
exports.applicationByID = function(req, res, next, id) {
	Application.findById(id).populate('user', 'displayName').exec(function(err, application) {
		if (err) return next(err);
		if (! application) return next(new Error('Failed to load Application ' + id));
		req.application = application ;
		next();
	});
};

/**
 * Application authorization middleware
 */
exports.hasAuthorization = function(req, res, next) {
	if (req.application.user.id !== req.user.id) {
		return res.status(403).send('User is not authorized');
	}
	next();
};


text:
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace EntityFrameworkCodeFirst.Models.StudentSystem
{
    public class Course
    {
        private ICollection<Student> students;
        private ICollection<Homework> homeoworks;
        private ICollection<CourseMaterial> courseMaterials;

        public Course()
        {
            this.students = new HashSet<Student>();
            this.homeoworks = new HashSet<Homework>();
            this.courseMaterials = new HashSet<CourseMaterial>();
        }

        public int Id { get; set; }

        [Required]
        [StringLength(120, MinimumLength = 3)]
        public string Name { get; set; }

        [Column(TypeName = "ntext")]
        [MaxLength]
        public string Description { get; set; }

        public virtual ICollection<Student> Students
        {
            get { return this.students; }
            set { this.students = value; }
        }

        public virtual ICollection<Homework> Homeworks
        {
            get { return this.homeoworks; }
            set { this.homeoworks = value; }
        }

        public virtual ICollection<CourseMaterial> CourseMaterials
        {
            get { return this.courseMaterials; }
            set { this.courseMaterials = value; }
        }
    }
}


text:
package com.jajinba.android.utils;

public class EqualUtils {

  public static boolean isEqual(Object o, Object o1) {
    if ((o == null || o.toString().equals("")) && (o1 == null || o1.toString().equals(""))) {
      return true;
    } else if (o == null && o1 != null) {
      return false;
    } else if (o != null && o1 == null) {
      return false;
    } else {
      return o.equals(o1);
    }
  }
}


text:
//
//    Copyright (c) 2006-2018 Erik Ylvisaker
//
//    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.
//

using Microsoft.Xna.Framework;

namespace AgateLib.UserInterface
{
    public class ImageSource
    {
        public static bool Equals(ImageSource a, ImageSource b)
        {
            if (a == null && b == null)
            {
                return true;
            }

            if (a == null || b == null)
            {
                return false;
            }

            if (a.File != b.File)
            {
                return false;
            }

            if (a.SourceRect != b.SourceRect)
            {
                return false;
            }

            return true;
        }

        public ImageSource() { }

        public ImageSource(string file)
        {
            File = file;
        }

        public string File { get; set; }

        public Rectangle? SourceRect { get; set; }
    }
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Tipopeticion_model extends CI_Model{
    var $table = 'tipopeticion';
    var $column_order = array('sPeticion_lista', null);
    var $column_search = array('sPeticion_lista');
    var $order = array('iId' => 'desc');

    public function __construct() {
      parent::__construct();
      $this->load->database();
    }

    /* Función privada que obtiene los datos de la BBDD necesarios para construir la vista.
    */
    private function _get_datatables_query() {
      $this->db->from($this->table);
      $i = 0;

      foreach ($this->column_search as $item) {
        if($_POST['search']['value']) {
          if($i===0) {
            $this->db->group_start();
            $this->db->like($item, $_POST['search']['value']);
          }
          else {
            $this->db->or_like($item, $_POST['search']['value']);
          }

          if(count($this->column_search) - 1 == $i)
            $this->db->group_end();
        }
        $i++;
      }

      if(isset($_POST['order'])) {
        $this->db->order_by($this->column_order[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);
      }
      else if(isset($this->order)) {
        $order = $this->order;
        $this->db->order_by(key($order), $order[key($order)]);
      }
    }

    /* Función que se utilizará para devolver a la vista los datos que ésta mostrará. Utiliza la función _get_datatables_query()
      como soporte
    */
    function get_datatables() {
      $this->_get_datatables_query();
      if ($_POST['length'] != -1)
        $this->db->limit($_POST['length'], $_POST['start']);
      $query = $this->db->get();
      return $query->result();
    }

    /* Función que devuelve el número de resultados de una consulta filtrada. */
    function count_filtered() {
      $this->_get_datatables_query();
      $query = $this->db->get();
      return $query->num_rows();
    }

    /* Función que devuelve el número total de registros de una consulta */
    public function count_all() {
      $this->db->from($this->table);
      return $this->db->count_all_results();
    }

    /*
      Función que obtiene un registro de la tabla de 'titulacion' según un $iId que obtiene como entrada.
      ENTRADA: $iId (Identificador único del registro que queremos obtener de la base de datos)
      SALIDA:  Registro [titulacion].
    */
    public function get_by_id($iId) {
      $this->db->from($this->table);
      $this->db->where('iId',$iId);
      $query = $this->db->get();
      return $query->row();
    }

    /*
      Función que guarda un nuevo registro en la base de datos, que toma como parámetro de entrada.
      ENTRADA: $data (Array con el registro a insertar.)
      SALIDA:  Último ID insertado.
    */
    public function save($data) {
      $this->db->insert($this->table, $data);
      return $this->db->insert_id();
    }

    /*
      Función que actualiza un registro de la base de datos según una condición.
      ENTRADA:
        $where: Condición que cumplirá el registro que se quiere modificar.
        $data:  Array con los nuevos datos.
      SALIDA: Número de filas afectadas por la modificación.
    */
    public function update($where, $data)
    {
      $this->db->update($this->table, $data, $where);
      return $this->db->affected_rows();
    }

    /*
      Función que elimina un registro cuyo $iId se toma como entrada
      ENTRADA: $iId (Identificador del registro que se quiere eliminar).
      SALIDA: -
    */
    public function delete_by_id($iId) {
      // Primero eliminamos las peticiones de la tabla de peticiones
      $this->db->where('iId_Peticion', $iId);
      $this->db->delete('peticion');
      // Ahora borramos el tipo de petición.
      $this->db->where('iId', $iId);
      $this->db->delete($this->table);
    }
}
?>


text:
var User = S.newClass();
module.exports = User;

var generateCard = function(id) {
    var cssClass = 'sprite-deck-' + (id || 'backside');
    return '

';
};

User.extendPrototype({
    construct(name) {
        this.name = name;
        this.connected = true;
        this.$eltList = $('
').text(name);
        this.$eltGame = $('

');
        User.usersList.append(this.$eltList);
        User.cardsContainer.append(this.$eltGame);
        this.$eltGame.find('.name').text(name);
    },
    isConnected() {
        return this.connected;
    },
    reconnect() {
        this.connected = true;
        this.$eltList.css('text-decoration', 'none');

    },
    disconnect() {
        this.$eltList.css('text-decoration', 'line-through');
    },
    delete() {
        this.$eltList.fadeOut(1000, function() { $(this).remove(); });
        this.$eltGame.remove();

        delete this.$eltList;
        delete this.$eltGame;
        delete this.$ready;
    },
    reset() {
        this.ready = false;
        if (this.$ready) {
            this.$ready.remove();
            delete this.$ready;
        }
    },
    markAsReady() {
        this.ready = true;
        this.$ready = $(' ✔').appendTo(this.$eltList).fadeIn().fadeOut().fadeIn();
    },
    setCard(cardId) {
        var $oldCard = this.$card || false;
        var $card = $(generateCard(cardId));
        this.$card = $card;
        $card.css('top', '1000px');
        this.$eltGame.find('.card-container').append($card);
        $card.animate({'top': '0'}, 1000, () => {
            this.removeCard($oldCard);
        });
    },
    removeCard($card) {
        var $cardToRemove = $card !== undefined ? $card : this.$card;
        if ($cardToRemove) {
            $cardToRemove.fadeOut(function() {$(this).remove(); });
            if (!$card) {
                delete this.$card;
            }
        }
    }
});


text:
williamyeh.mongodb_exporter for Ansible Galaxy
============

[![Circle CI](https://circleci.com/gh/William-Yeh/ansible-mongodb-exporter.svg?style=shield)](https://circleci.com/gh/William-Yeh/ansible-mongodb-exporter) [![Build Status](https://travis-ci.org/William-Yeh/ansible-mongodb-exporter.svg?branch=master)](https://travis-ci.org/William-Yeh/ansible-mongodb-exporter)

## Summary

Role name in Ansible Galaxy: **[williamyeh.mongodb_exporter](https://galaxy.ansible.com/williamyeh/mongodb_exporter/)**

This Ansible role has the following features for [mongodb_exporter](https://github.com/dcu/mongodb_exporter) (a MongoDB metrics exporter for [Prometheus](http://prometheus.io/)):

 - Install mongodb_exporter by compiling its Golang source code (I hope the maintainer of mongodb_exporter will provide official binary releases).
 - Handlers for restart/reload/stop events.

NOTE: If you want to install Prometheus itself or other exporters, see **[williamyeh.prometheus](https://github.com/William-Yeh/ansible-prometheus)** for more info.

## Role Variables

### Mandatory variables

None.

### Optional variables

**Mongodb_exporter specific** user-configurable defaults:

```yaml
# MongoDB Connection String URI
# @see http://docs.mongodb.org/manual/reference/connection-string/
mongodb_exporter_mongodb_uri:  "mongodb://localhost:27017"
```

If the Linux distributions are equipped with systemd, this role will use this mechanism accordingly. You can disable this (i.e., use traditional SysV-style init script) by defining the variable to false: `mongodb_exporter_use_systemd: false`.

```yaml
mongodb_exporter_use_systemd
```

**Prometheus** user-configurable defaults (of course, a subset of optional variables in [williamyeh.prometheus](https://github.com/William-Yeh/ansible-prometheus)):

```yaml
# user and group
prometheus_user:   prometheus
prometheus_group:  prometheus

# directory for executable files
prometheus_install_path:   /opt/prometheus

# directory for logs
prometheus_log_path:       /var/log/prometheus

# directory for PID files
prometheus_pid_path:       /var/run/prometheus

# version of helper utility "gosu"
gosu_version:  1.9
```

## Handlers

- `restart mongodb_exporter`

- `reload mongodb_exporter`

- `stop mongodb_exporter`

## Usage

### Step 1: add role

Add role name `williamyeh.mongodb_exporter` to your playbook file.

### Step 2: add variables

Set vars in your playbook file, if necessary.

Simple example:

```yaml
---
# file: simple-playbook.yml

- hosts: all
  become: True
  roles:
    - williamyeh.mongodb_exporter

  vars:

    mongodb_exporter_mongodb_uri:  "mongodb://adm:password@localhost:27017"

```

## Dependencies

None.

## License

MIT License. See the [LICENSE file](LICENSE) for details.


text: export const FIELD_ON_CHANGE: string = 'FIELD_ON_CHANGE';


text:
/**
 * Annotations for bookkeeper stats api.
 */
package org.apache.bookkeeper.stats.annotations;


text:
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4])
plt.ylabel('some numbers')
plt.savefig('myfig.png')
#plt.show()

'''
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
plt.plot([1,2,3])
plt.savefig('myfig.pdf')
'''


text:
// This file tests the behavior of all concrete font systems available on the
// current platform, i.e. FreeTypeFont (with or without ICU), CoreTextFont on
// Mac / iOS, and not the mock fonts.

#include "base/integral_types.h"
#include "ion/base/invalid.h"
#include "ion/base/logchecker.h"
#include "ion/math/rangeutils.h"
#include "ion/math/vector.h"
#include "ion/port/environment.h"
#include "ion/port/fileutils.h"
#include "ion/text/font.h"
#include "ion/text/tests/testfont.h"
#include "third_party/googletest/googletest/include/gtest/gtest.h"

namespace ion {
namespace text {

using math::Point2f;
using math::Point3f;
using math::Range2f;
using math::Vector2f;
using math::Vector2ui;

const std::string GetIonDirectory() {

  std::string cwd = port::GetCurrentWorkingDirectory();
  size_t ion = cwd.rfind("ion/");
  if (ion != std::string::npos) {
    return cwd.substr(0, ion + 3);
  }
  return "";
}

// This returns the available font classes with a simple Latin font.
std::vector<FontPtr> SimpleTestFonts(size_t sdf_padding) {
  std::vector<FontPtr> fonts;
  fonts.push_back(testing::BuildTestFreeTypeFont("Test", 32U, sdf_padding));
#if defined(ION_PLATFORM_MAC) || defined(ION_PLATFORM_IOS)
  fonts.push_back(testing::BuildTestCoreTextFont("Test", 32U, sdf_padding));
#endif
  return fonts;
}

// This returns the available font classes with a more complex font (Hindi).
std::vector<FontPtr> ComplexTestFonts() {
  std::vector<FontPtr> fonts;
#if defined(ION_USE_ICU)
  auto test = testing::BuildTestFreeTypeFont("Test", 32U, 4U);
  auto devangari =
      testing::BuildTestFreeTypeFont("NotoSansDevanagari-Regular", 32U, 4U);
  // With a proper fallback set even a simple FreeType font should work.
  test->AddFallbackFont(devangari);
  fonts.push_back(test);
  fonts.push_back(devangari);
#endif
#if defined(ION_PLATFORM_MAC) || defined(ION_PLATFORM_IOS)
  fonts.push_back(
      testing::BuildTestCoreTextFont("NotoSansDevanagari-Regular", 32U, 4U));
  // As CoreText fonts perform font fallback, even the basic test font should
  // be capable of complex layout.
  fonts.push_back(testing::BuildTestCoreTextFont("Test", 32U, 4U));
#endif
  return fonts;
}

// Returns whether two points are within a certain range of each other in X and
// Y, and the third axis is near the XY plane.
static bool PointXYNear(const Point3f& a, const Point2f& b) {
  // Quite a large error, as this is comparing two different font
  // implementations.
  static const float kError = 0.03f;
  if (fabsf(a[0] - b[0]) < kError &&
      fabsf(a[1] - b[1]) < kError &&
      fabsf(a[2]) < kError) {
    return true;
  }
  return false;
}

// Returns whether a glyph's quad is close to a certain shape.
static bool GlyphQuadNear(const Layout::Glyph& glyph,
                          float xmin, float xmax, float ymin, float ymax) {
  return PointXYNear(glyph.quad.points[0], Point2f(xmin, ymin)) &&
         PointXYNear(glyph.quad.points[1], Point2f(xmax, ymin)) &&
         PointXYNear(glyph.quad.points[2], Point2f(xmax, ymax)) &&
         PointXYNear(glyph.quad.points[3], Point2f(xmin, ymax));
}

// Checks that the layout's Position and Size are close to expectations.
static void CheckPositionAndSize(const Layout& layout, const Point2f& position,
                                 const Vector2f& size) {
  // Quite a large error, as this is comparing two different font
  // implementations.
  static const float kError = 0.03f;
  EXPECT_NEAR(position[0], layout.GetPosition()[0], kError);
  EXPECT_NEAR(position[1], layout.GetPosition()[1], kError);
  EXPECT_NEAR(size[0], layout.GetSize()[0], kError);
  EXPECT_NEAR(size[1], layout.GetSize()[1], kError);
}

TEST(PlatformFontTest, ValidFont) {
  base::LogChecker logchecker;
  std::vector<FontPtr> fonts = SimpleTestFonts(4);
  for (const FontPtr& font : fonts) {
    EXPECT_EQ("Test", font->GetName());
    EXPECT_EQ(32U, font->GetSizeInPixels());
    EXPECT_EQ(4U, font->GetSdfPadding());

    // FontMetrics.
    const Font::FontMetrics& fmet = font->GetFontMetrics();
    EXPECT_EQ(38.f, fmet.line_advance_height);
    EXPECT_NEAR(25.4f, fmet.ascender, 0.2f);
  }
}

TEST(PlatformFontTest, GlyphGrid) {
  // Tests basic properties of the GlyphGrid for a few characters.
  base::LogChecker logchecker;
  std::vector<FontPtr> fonts = SimpleTestFonts(4);
  for (const FontPtr& font : fonts) {
    {
      // Valid glyph for the letter 'A'.
      const Font::GlyphGrid& grid =
          font->GetGlyphGrid(font->GetDefaultGlyphForChar('A'));
      EXPECT_EQ(19U, grid.pixels.GetWidth());
      EXPECT_EQ(23U, grid.pixels.GetHeight());
    }

    {
      // Valid glyph for the letter 'g'.
      const Font::GlyphGrid& grid =
          font->GetGlyphGrid(font->GetDefaultGlyphForChar('g'));
      EXPECT_EQ(14U, grid.pixels.GetWidth());
      // The grid is slightly different size between FreeType and CoreText.
      EXPECT_NEAR(25.0, static_cast<double>(grid.pixels.GetHeight()), 1.0);
    }

    // Invalid glyph for character with index 1.
    EXPECT_TRUE(base::IsInvalidReference(
        font->GetGlyphGrid(font->GetDefaultGlyphForChar(1))));
  }
}

TEST(PlatformFontTest, SimpleLayout) {
  // Lays out a simple line of text and checks all fields in the layout contain
  // sane values. The allowed error bounds reflect the differences between
  // CoreText and FreeType font rendering.
  std::vector<FontPtr> fonts = SimpleTestFonts(4);
  for (const FontPtr& font : fonts) {
    LayoutOptions options;
    Layout l = font->BuildLayout("Abcd", options);

    EXPECT_EQ(l.GetGlyphCount(), 4U);

    EXPECT_TRUE(GlyphQuadNear(l.GetGlyph(0), -0.09f, 0.75f, -0.12f, 0.84f));
    EXPECT_TRUE(GlyphQuadNear(l.GetGlyph(1), 0.56f, 1.25f, -0.16f, 0.84f));
    EXPECT_TRUE(GlyphQuadNear(l.GetGlyph(2), 1.03f, 1.69f, -0.16f,  0.68f));
    EXPECT_TRUE(GlyphQuadNear(l.GetGlyph(3), 1.48f, 2.16f, -0.15f, 0.84f));

    CheckPositionAndSize(l, Point2f(0.f, -0.03f), Vector2f(2.03f, 0.75f));

    EXPECT_EQ(1.1875f, l.GetLineAdvanceHeight());
  }
}

TEST(PlatformFontTest, MetricsBasedAlignment) {
  // Lays out a simple line of text and checks position and size after using
  // metrics_based_alignment. The allowed error bounds reflect the differences
  // between CoreText and FreeType font rendering.
  std::vector<FontPtr> fonts = SimpleTestFonts(4);
  for (const FontPtr& font : fonts) {
    LayoutOptions options;
    options.metrics_based_alignment = true;
    Layout l = font->BuildLayout("Abcd", options);

    EXPECT_EQ(l.GetGlyphCount(), 4U);

    // Glyphs didnt change size.
    EXPECT_TRUE(GlyphQuadNear(l.GetGlyph(0), -0.09f, 0.75f, -0.12f, 0.84f));
    EXPECT_TRUE(GlyphQuadNear(l.GetGlyph(1), 0.56f, 1.25f, -0.16f, 0.84f));
    EXPECT_TRUE(GlyphQuadNear(l.GetGlyph(2), 1.03f, 1.69f, -0.16f,  0.68f));
    EXPECT_TRUE(GlyphQuadNear(l.GetGlyph(3), 1.48f, 2.16f, -0.15f, 0.84f));

    // Width uses advance instead of bitmap_offset + size;
    // Height uses full ascender and descender that add up to font size.
    CheckPositionAndSize(l, Point2f(0.f, -0.20f), Vector2f(2.08f, 1.00f));

    EXPECT_EQ(1.1875f, l.GetLineAdvanceHeight());
  }
}

TEST(PlatformFontTest, TargetSize) {
  // This builds a Layout that uses the full height and width of each glyph and
  // checks the bounds of the resulting text rectangle to verify the scale.
  std::vector<FontPtr> fonts = SimpleTestFonts(4);
  for (const FontPtr& font : fonts) {
    LayoutOptions options;
    options.horizontal_alignment = kAlignLeft;
    options.vertical_alignment = kAlignBaseline;

    // Any negative size should fail to layout.
    LayoutOptions invalid_options = options;
    invalid_options.target_size.Set(-200.f, 0.0f);
    EXPECT_EQ(font->BuildLayout("####", invalid_options).GetGlyphCount(), 0u);
    invalid_options.target_size.Set(0.f, -200.0f);
    EXPECT_EQ(font->BuildLayout("####", invalid_options).GetGlyphCount(), 0u);

    // Scale specified as width only.
    options.target_size.Set(200.f, 0.0f);
    Layout first_layout = font->BuildLayout("####", options);

    // Scale 2x in both dimensions.
    options.target_size[0] *= 2.0f;
    EXPECT_NEAR(
        font->BuildLayout("####", options).GetGlyph(0).quad.points[2][0],
        first_layout.GetGlyph(0).quad.points[2][0] * 2,
        0.001);

    // Scale specified as height only.
    options.target_size.Set(0.0f, 1000.0f);
    Layout layout_1000 = font->BuildLayout("####", options);
    EXPECT_NEAR(layout_1000.GetGlyph(0).quad.points[2][0],
                first_layout.GetGlyph(0).quad.points[2][0] * 15.625,
                40);

    // Non-uniform scale, should match the width-only and height-only layouts in
    // the appropriate axes.
    options.target_size.Set(200.f, 1000.f);
    Layout layout_non_uniform = font->BuildLayout("####", options);
    EXPECT_NEAR(layout_non_uniform.GetGlyph(0).quad.points[2][0],
                first_layout.GetGlyph(0).quad.points[2][0],
                0.001);
    EXPECT_NEAR(layout_non_uniform.GetGlyph(0).quad.points[2][1],
                layout_1000.GetGlyph(0).quad.points[2][1],
                0.001);
  }
}

TEST(PlatformFontTest, TargetPoint) {
  // Verify the behavior of LayoutOptions::target_point.
  std::vector<FontPtr> fonts = SimpleTestFonts(4);
  for (const FontPtr& font : fonts) {
    LayoutOptions options;
    options.horizontal_alignment = kAlignLeft;
    options.vertical_alignment = kAlignBaseline;
    // Set a scale to verify that target_point is applied after target_size.
    options.target_size.Set(200.f, 1000.f);

    Layout first_layout = font->BuildLayout("####", options);
    options.target_point = Point2f(70.f, 300.f);
    Layout offset_layout = font->BuildLayout("####", options);

    EXPECT_NEAR(offset_layout.GetGlyph(0).quad.points[2][0],
                first_layout.GetGlyph(0).quad.points[2][0] + 70.f,
                0.001);
    EXPECT_NEAR(offset_layout.GetGlyph(0).quad.points[2][1],
                first_layout.GetGlyph(0).quad.points[2][1] + 300.f,
                0.001);
  }
}

TEST(PlatformFontTest, LineSpacing) {
  // Verify the behavior of LayoutOptions::line_spacing.
  std::vector<FontPtr> fonts = SimpleTestFonts(4);
  for (const FontPtr& font : fonts) {
    LayoutOptions options;

    // Create two multiline layouts, one with vanilla line_spacing (1) and the
    // other with line_spacing 3.
    Layout layout1 = font->BuildLayout("####\n####", options);
    options.line_spacing = 3.f;
    Layout layout3 = font->BuildLayout("####\n####", options);

    // Back-calculate line spacing by dividing line height by glyph height.
    float glyph_height1 = layout1.GetGlyph(6).quad.points[0][1] -
        layout1.GetGlyph(6).quad.points[3][1];

    float glyph_height3 = layout3.GetGlyph(6).quad.points[0][1] -
        layout3.GetGlyph(6).quad.points[3][1];

    float line_height1 = layout1.GetGlyph(6).quad.points[0][1] -
        layout1.GetGlyph(0).quad.points[0][1];

    float line_height3 = layout3.GetGlyph(6).quad.points[0][1] -
        layout3.GetGlyph(0).quad.points[0][1];

    float line_spacing1 = line_height1 / glyph_height1;
    float line_spacing3 = line_height3 / glyph_height3;

    // Expect the correct ratio of line spacing.
    EXPECT_NEAR(line_spacing3 / line_spacing1, 3, 0.01);
  }
}

TEST(PlatformFontTest, Space) {
  // Test that the horizontal advance for a space is reasonable.
  std::vector<FontPtr> fonts = SimpleTestFonts(4);
  for (const FontPtr& font : fonts) {
    LayoutOptions options;
    options.horizontal_alignment = kAlignLeft;
    options.vertical_alignment = kAlignBaseline;
    options.target_size.Set(0.0f, 100.0f);

    Layout space_layout = font->BuildLayout("# #", options);
    Layout::Glyph last_glyph =
        space_layout.GetGlyph(space_layout.GetGlyphCount() - 1);
    EXPECT_NEAR(194, last_glyph.quad.points[1][0], 3);
  }
}

TEST(PlatformFontTest, MultiLine) {
  std::vector<FontPtr> fonts = SimpleTestFonts(0);
  for (const FontPtr& font : fonts) {
    LayoutOptions options;
    options.target_size = Vector2f(0, 100);

    // Two-line text with left and baseline alignment. Verify that second line
    // is below the first, the left edges of the two lines are close
    // horizontally.
    {
      options.horizontal_alignment = kAlignLeft;
      options.vertical_alignment = kAlignBaseline;
      Layout layout = font->BuildLayout("Abc\ng", options);
      EXPECT_GT(layout.GetGlyph(0).quad.points[0][1],
                layout.GetGlyph(layout.GetGlyphCount() - 1).quad.points[3][1]);
      EXPECT_NEAR(layout.GetGlyph(0).quad.points[0][1], 0, 1);
      EXPECT_NEAR(layout.GetGlyph(0).quad.points[0][0],
                  layout.GetGlyph(layout.GetGlyphCount() - 1)
                      .quad.points[0][0], 1);
    }

    {
      // Centered two-line text. Verify that the shorter line's horizontal
      // bounds are within that of the longer.
      options.horizontal_alignment = kAlignHCenter;
      Layout layout = font->BuildLayout("Abcedf\nabc", options);
      EXPECT_GT(layout.GetGlyph(5).quad.points[3][0] - 10.f,
                layout.GetGlyph(layout.GetGlyphCount() - 1).quad.points[3][0]);
      EXPECT_LT(layout.GetGlyph(0).quad.points[0][0] + 10.f,
                layout.GetGlyph(layout.GetGlyphCount() - 3).quad.points[0][0]);
    }

    {
      // Right-aligned two-line text. Verify that the second line starts
      // significantly to the right of the first, and both lines end near to the
      // origin horizontally.
      options.horizontal_alignment = kAlignRight;
      Layout layout = font->BuildLayout("Abcedf\nabc", options);
      EXPECT_LT(layout.GetGlyph(0).quad.points[0][0] + 50,
                layout.GetGlyph(layout.GetGlyphCount() - 3).quad.points[0][0]);
      EXPECT_NEAR(layout.GetGlyph(5).quad.points[2][0], 0, 1);
      EXPECT_NEAR(layout.GetGlyph(layout.GetGlyphCount() - 1)
                      .quad.points[2][0], 0, 2);
    }

    // Top alignment. Verify that the top of the first line's glyphs are close
    // to the origin vertically.
    {
      options.vertical_alignment = kAlignTop;
      Layout layout = font->BuildLayout("Abg.\ng", options);
      EXPECT_NEAR(layout.GetGlyph(0).quad.points[3][1], 0, 1);
    }

    // Bottom alignment. Verify that the bottom of the last line's glyphs are
    // close to the origin vertically.
    {
      options.vertical_alignment = kAlignBottom;
      Layout layout = font->BuildLayout("Abg.\ng", options);
      EXPECT_NEAR(layout.GetGlyph(layout.GetGlyphCount() - 1)
                      .quad.points[0][1], 0, 1);
    }
  }
}

TEST(PlatformFontTest, FontAdvancedLayout) {
  static const char kDataDir[] = "/third_party/icu/icu4c/source/stubdata/";
  port::SetEnvironmentVariableValue("ION_ICU_DIR",
                                    GetIonDirectory() + kDataDir);

  // Assert that glyph combining works correctly by observing that the width of
  // the test string shrinks when the <reph> is added (since that turns the 'र'
  // into a super-script on the 'ग' instead of being its own character).
  std::string no_reph_str = "मारग";
  std::string with_reph_str = "मार्ग";
  std::vector<FontPtr> fonts = ComplexTestFonts();
  for (const FontPtr& font : fonts) {
    LayoutOptions options;
    Layout no_reph = font->BuildLayout(no_reph_str, options);
    Layout with_reph = font->BuildLayout(with_reph_str, options);
    GlyphSet no_reph_glyphs(base::AllocatorPtr(nullptr));
    GlyphSet with_reph_glyphs(base::AllocatorPtr(nullptr));
    no_reph.GetGlyphSet(&no_reph_glyphs);
    with_reph.GetGlyphSet(&with_reph_glyphs);
    // Both layouts end up with 4 glyphs, but they are not the same glyphs!
    ASSERT_EQ(4U, no_reph.GetGlyphCount());
    ASSERT_EQ(4U, with_reph.GetGlyphCount());
    ASSERT_NE(no_reph_glyphs, with_reph_glyphs);

    // Expect that |with_reph| is no more than this times |no_reph|'s width.
    // Note that this constant has been chosen to be just large enough to pass
    // for all the available platform fonts.
    static const double kMaximumAllowedRatio = 0.82;
    EXPECT_LT(
        with_reph.GetGlyph(with_reph.GetGlyphCount() - 1).quad.points[1][0],
        no_reph.GetGlyph(no_reph.GetGlyphCount() - 1).quad.points[1][0] *
            kMaximumAllowedRatio);
  }
}

}  // namespace text
}  // namespace ion


text:
module ConfidentialInfoRedactorLite
  class Hyperlink

    # Rubular: http://rubular.com/r/fXa4lp0gfS
    HYPERLINK_REGEX = /(http|https|www)(\.|:)/

    def replace(text)
      text.split(/\s+/).map { |token| text = text.gsub(/#{Regexp.escape(token.gsub(/\.\z/, ''))}/, ' <redacted hyperlink> ') if !(token !~ HYPERLINK_REGEX) }
      text
    end
  end
end


text:
<?php

define('BASEPATH', 'Staff');
require_once('../applications/wrapper.php');

if (!$IKO->perm->check('access_administration')) {
    redirect(SITE_URL);
}//Checks if user has permission to create a thread.
//require_once('template/top.php');
echo $ADMIN->template('top');
$notice = '';

$versions = @file_get_contents('http://api.codetana.com/iko/version_list.php'); //@jtPox insert the real IP here

if ($versions != '') {
    $versionList = explode("|", $versions);
    foreach ($versionList as $version) {
        if (version_compare(IKOBB_VERSION, $version, '<')) {
            //echo '
New version found: ' . $version . '
» Download Now?
';

            // do update
            // Step 1 downloading the file
            if (isset($_GET['doUpdate']) && $_GET['doUpdate'] == true && isset($_GET['step']) && $_GET['step'] == 1) {
                $ADMIN->download('http://api.codetana.com/iko/update_packages/Iko_update_package_' . $version . '.zip', true);
                echo '

                                33%

';
                echo '
» Install Now?
';
            } // Step 2 Extract zip
            elseif (isset($_GET['doUpdate']) && $_GET['doUpdate'] == true && isset($_GET['step']) && $_GET['step'] == 2) {
                if (is_file('updates/Iko_update_package_' . $version . '.zip')) {
                    $output = $ADMIN->zip_extract('updates/Iko_update_package_' . $version . '.zip', true, true);
                } else {
                    $output = '
Downloaded file not found!
';
                }
                echo '

                                66%

';
                echo $output;

                echo '
» Last step
';
            } // Step 3 Execute upgrade.php
            elseif (isset($_GET['doUpdate']) && $_GET['doUpdate'] == true && isset($_GET['step']) && $_GET['step'] == 3) {
                if (is_file('updates/upgrade.php')) include('updates/upgrade.php');
                echo '

                                100%

';

            }

        }
    }
}

//require_once('template/bot.php');
echo $ADMIN->template('bot');

?>


text:
package org.smartdeveloperhub.harvesters.it.frontend.testing;

import org.smartdeveloperhub.harvesters.it.frontend.testing.collector.TestingCollector;
import org.smartdeveloperhub.harvesters.it.notification.CollectorConfiguration;

public interface TestingCollectorProvider {

	TestingCollector provide(CollectorConfiguration configuration);

}


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Diagnostics;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.CSharp.Formatting
{
    /// <summary>
    /// trivia factory.
    ///
    /// it will cache some commonly used trivia to reduce memory footprint and heap allocation
    /// </summary>
    internal partial class TriviaDataFactory : AbstractTriviaDataFactory
    {
        public TriviaDataFactory(TreeData treeInfo, OptionSet optionSet) :
            base(treeInfo, optionSet)
        {
        }

        private static bool IsCSharpWhitespace(char c)
        {
            return SyntaxFacts.IsWhitespace(c) || SyntaxFacts.IsNewLine(c);
        }

        public override TriviaData CreateLeadingTrivia(SyntaxToken token)
        {
            // no trivia
            if (!token.HasLeadingTrivia)
            {
                Debug.Assert(this.TreeInfo.GetTextBetween(default(SyntaxToken), token).All(IsCSharpWhitespace));
                return GetSpaceTriviaData(space: 0);
            }

            var result = Analyzer.Leading(token);
            var info = GetWhitespaceOnlyTriviaInfo(default(SyntaxToken), token, result);
            if (info != null)
            {
                Debug.Assert(this.TreeInfo.GetTextBetween(default(SyntaxToken), token).All(IsCSharpWhitespace));
                return info;
            }

            return new ComplexTrivia(this.OptionSet, this.TreeInfo, default(SyntaxToken), token);
        }

        public override TriviaData CreateTrailingTrivia(SyntaxToken token)
        {
            // no trivia
            if (!token.HasTrailingTrivia)
            {
                Debug.Assert(this.TreeInfo.GetTextBetween(token, default(SyntaxToken)).All(IsCSharpWhitespace));
                return GetSpaceTriviaData(space: 0);
            }

            var result = Analyzer.Trailing(token);
            var info = GetWhitespaceOnlyTriviaInfo(token, default(SyntaxToken), result);
            if (info != null)
            {
                Debug.Assert(this.TreeInfo.GetTextBetween(token, default(SyntaxToken)).All(IsCSharpWhitespace));
                return info;
            }

            return new ComplexTrivia(this.OptionSet, this.TreeInfo, token, default(SyntaxToken));
        }

        public override TriviaData Create(SyntaxToken token1, SyntaxToken token2)
        {
            // no trivia in between
            if (!token1.HasTrailingTrivia && !token2.HasLeadingTrivia)
            {
                Debug.Assert(string.IsNullOrWhiteSpace(this.TreeInfo.GetTextBetween(token1, token2)));
                return GetSpaceTriviaData(space: 0);
            }

            var result = Analyzer.Between(token1, token2);
            var info = GetWhitespaceOnlyTriviaInfo(token1, token2, result);
            if (info != null)
            {
                Debug.Assert(string.IsNullOrWhiteSpace(this.TreeInfo.GetTextBetween(token1, token2)));
                return info;
            }

            return new ComplexTrivia(this.OptionSet, this.TreeInfo, token1, token2);
        }

        private bool ContainsOnlyWhitespace(Analyzer.AnalysisResult result)
        {
            if (result.HasComments || result.HasPreprocessor || result.HasSkippedTokens || result.HasSkippedOrDisabledText)
            {
                return false;
            }

            return true;
        }

        private TriviaData GetWhitespaceOnlyTriviaInfo(SyntaxToken token1, SyntaxToken token2, Analyzer.AnalysisResult result)
        {
            if (!ContainsOnlyWhitespace(result))
            {
                return null;
            }

            // only whitespace in between
            int space = GetSpaceOnSingleLine(result);
            Contract.ThrowIfFalse(space >= -1);

            if (space >= 0)
            {
                // check whether we can use cache
                return GetSpaceTriviaData(space, result.TreatAsElastic);
            }

            // tab is used in a place where it is not an indentation
            if (result.LineBreaks == 0 && result.Tab > 0)
            {
                // calculate actual space size from tab
                var spaces = CalculateSpaces(token1, token2);
                return new ModifiedWhitespace(this.OptionSet, result.LineBreaks, indentation: spaces, elastic: result.TreatAsElastic, language: LanguageNames.CSharp);
            }

            // check whether we can cache trivia info for current indentation
            var lineCountAndIndentation = GetLineBreaksAndIndentation(result);

            var canUseTriviaAsItIs = lineCountAndIndentation.Item1;
            return GetWhitespaceTriviaData(lineCountAndIndentation.Item2, lineCountAndIndentation.Item3, canUseTriviaAsItIs, result.TreatAsElastic);
        }

        private int CalculateSpaces(SyntaxToken token1, SyntaxToken token2)
        {
            var initialColumn = (token1.RawKind == 0) ? 0 : this.TreeInfo.GetOriginalColumn(this.OptionSet.GetOption(FormattingOptions.TabSize, LanguageNames.CSharp), token1) + token1.Span.Length;
            var textSnippet = this.TreeInfo.GetTextBetween(token1, token2);

            return textSnippet.ConvertTabToSpace(this.OptionSet.GetOption(FormattingOptions.TabSize, LanguageNames.CSharp), initialColumn, textSnippet.Length);
        }

        private ValueTuple<bool, int, int> GetLineBreaksAndIndentation(Analyzer.AnalysisResult result)
        {
            Debug.Assert(result.Tab >= 0);
            Debug.Assert(result.LineBreaks >= 0);

            var indentation = result.Tab * this.OptionSet.GetOption(FormattingOptions.TabSize, LanguageNames.CSharp) + result.Space;
            if (result.HasTrailingSpace || result.HasUnknownWhitespace)
            {
                return ValueTuple.Create(false, result.LineBreaks, indentation);
            }

            if (!this.OptionSet.GetOption(FormattingOptions.UseTabs, LanguageNames.CSharp))
            {
                if (result.Tab > 0)
                {
                    return ValueTuple.Create(false, result.LineBreaks, indentation);
                }

                return ValueTuple.Create(true, result.LineBreaks, indentation);
            }

            Debug.Assert(this.OptionSet.GetOption(FormattingOptions.UseTabs, LanguageNames.CSharp));

            // tab can only appear before space to be a valid tab for indentation
            if (result.HasTabAfterSpace)
            {
                return ValueTuple.Create(false, result.LineBreaks, indentation);
            }

            if (result.Space >= this.OptionSet.GetOption(FormattingOptions.TabSize, LanguageNames.CSharp))
            {
                return ValueTuple.Create(false, result.LineBreaks, indentation);
            }

            Debug.Assert((indentation / this.OptionSet.GetOption(FormattingOptions.TabSize, LanguageNames.CSharp)) == result.Tab);
            Debug.Assert((indentation % this.OptionSet.GetOption(FormattingOptions.TabSize, LanguageNames.CSharp)) == result.Space);

            return ValueTuple.Create(true, result.LineBreaks, indentation);
        }

        private int GetSpaceOnSingleLine(Analyzer.AnalysisResult result)
        {
            if (result.HasTrailingSpace || result.HasUnknownWhitespace || result.LineBreaks > 0 || result.Tab > 0)
            {
                return -1;
            }

            return result.Space;
        }
    }
}


text:
package org.jboss.resteasy.reactive.server.vertx.test.simple;

import java.time.Duration;
import java.time.Instant;

import javax.ws.rs.GET;
import javax.ws.rs.Path;

import org.hamcrest.Matchers;
import org.jboss.resteasy.reactive.RestQuery;
import org.jboss.resteasy.reactive.server.vertx.test.framework.ResteasyReactiveUnitTest;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

import io.restassured.RestAssured;

public class InstantParamTest {

    @RegisterExtension
    static ResteasyReactiveUnitTest test = new ResteasyReactiveUnitTest()
            .setArchiveProducer(() -> ShrinkWrap.create(JavaArchive.class)
                    .addClasses(HelloResource.class));

    @Test
    public void test() {
        RestAssured.get("/hello?instant=1984-08-08T01:02:03Z")
                .then().statusCode(200).body(Matchers.equalTo("hello#1984-08-09T01:02:03Z"));
    }

    @Path("hello")
    public static class HelloResource {

        @GET
        public String helloQuery(@RestQuery Instant instant) {
            return "hello#" + instant.plus(Duration.ofDays(1)).toString();
        }
    }

}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Util extends CI_Controller {

	public function __construct(){
		parent::__construct();
		$this->load->model(Response_model);
		$this->load->database();
	}

	public function index($current_page=1)
	{

		echo 'util.index';
	}

	public function getPage($offset=0,$page_size=PER_PAGE){
		$this->load->database();
		$this->db->from('tb_discussion')->select('comment');
		$query = $this->db->get();

// 		$query = $this->db->query('select * from tb_discussion');
		var_dump($query->result());

	}

	/**
	 * 获取 IP  地理位置
	 * 淘宝IP接口
	 * @Return: array
	 */
	function IPgetCity($ip = '',$isJson=TRUE)
	{
		if($ip == ''){
			$url = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json";
			$ip=json_decode(file_get_contents($url),true);
			$data = $ip;
		}else{
			$url="http://ip.taobao.com/service/getIpInfo.php?ip=".$ip;
			$ip=json_decode(file_get_contents($url));
			if((string)$ip->code=='1'){
				return false;
			}
			$data = $ip->data;
		}
		if($isJson==TRUE){
			return $this->Response_model->success($data);
		}else{
			return $data;
		}

	}

	function get_http_user_agent($isJson=true){
		if($isJson==true){
			return $this->Response_model->success($_SERVER['HTTP_USER_AGENT']);
		}else{
			return $_SERVER['HTTP_USER_AGENT'];
		}
	}

	function test(){
		$this->db->select('user_id,login_ip,login_time,user_login,login_city,http_user_agent')
		->from('tb_user_login_record')
		->order_by('login_time','DESC')
		->limit(1,1);
		$query=$this->db->get();
		return $this->Response_model->success($query->result_array());
	}
}


text:
package server

import (
	"github.com/stretchr/testify/assert"
	"net/http"
	"net/http/httptest"
	"os"
	"strings"
	"sync"
	"testing"
)

func init() {
	os.Setenv("NO_HTTP_AUTH", "true")
}

var (
	handler        = new(CombinerServer)
	invalidJSON    = "{"
	incompleteJSON = "{}"
	validJSON      = `{"bucket_name":"asd","doc_list":[{"key":"100001.pdf"}], "callback":"http://localhost:9090","combined_key":"out.pdf"}`
)

func TestPing(t *testing.T) {
	recorder := httptest.NewRecorder()
	req, _ := http.NewRequest("GET", "http://example.com/health_check.html", nil)
	handler.Ping(recorder, req)
	assert.Equal(t, 200, recorder.Code)
	assert.Equal(t, "", recorder.Body.String())
}

func TestRejectsInvalidRequest(t *testing.T) {
	recorder := httptest.NewRecorder()
	postBody := strings.NewReader(invalidJSON)
	req, _ := http.NewRequest("POST", "http://example.com/", postBody)
	handler.ProcessJob(recorder, req)
	assert.Equal(t, 400, recorder.Code)
	assert.Equal(t, recorder.Body.String(), string(invalidMessage))
}

func TestRejectsIncompleteRequest(t *testing.T) {
	recorder := httptest.NewRecorder()
	postBody := strings.NewReader(incompleteJSON)
	req, _ := http.NewRequest("POST", "http://example.com/", postBody)
	handler.ProcessJob(recorder, req)
	assert.Equal(t, 400, recorder.Code)
	assert.Equal(t, recorder.Body.String(), string(invalidMessage))
}

func TestAcceptsValidRequest(t *testing.T) {
	handler.pending = new(sync.WaitGroup)
	recorder := httptest.NewRecorder()
	postBody := strings.NewReader(validJSON)
	req, _ := http.NewRequest("POST", "http://example.com/", postBody)
	handler.ProcessJob(recorder, req)
	assert.Equal(t, 200, recorder.Code)
	assert.Equal(t, recorder.Body.String(), string(okMessage))
}


text:
(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('vue')) :
  typeof define === 'function' && define.amd ? define(['exports', 'vue'], factory) :
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.FeatureToggleComponent = {}, global.vue));
})(this, (function (exports, vue) { 'use strict';

  function _interopNamespace(e) {
    if (e && e.__esModule) return e;
    var n = Object.create(null);
    if (e) {
      Object.keys(e).forEach(function (k) {
        if (k !== 'default') {
          var d = Object.getOwnPropertyDescriptor(e, k);
          Object.defineProperty(n, k, d.get ? d : {
            enumerable: true,
            get: function () { return e[k]; }
          });
        }
      });
    }
    n["default"] = e;
    return Object.freeze(n);
  }

  var vue__namespace = /*#__PURE__*/_interopNamespace(vue);

  function _typeof(obj) {
    "@babel/helpers - typeof";

    if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
      _typeof = function _typeof(obj) {
        return typeof obj;
      };
    } else {
      _typeof = function _typeof(obj) {
        return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
      };
    }

    return _typeof(obj);
  }

  var parseToFn = function parseToFn(fnOrBool) {
    if (typeof fnOrBool == 'boolean') return function () {
      return fnOrBool;
    };
    return fnOrBool;
  };

  var getKey = function getKey(name, variant) {
    var _name = name.toLowerCase();

    if (typeof variant == 'string') {
      _name += "#" + variant.toLowerCase();
    }

    return _name;
  };

  function initVisibilities() {
    var visibilities = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    var returnVisibilities = {};
    Object.keys(visibilities).forEach(function (key) {
      if (key.startsWith('_')) return;
      returnVisibilities[getKey(key)] = parseToFn(visibilities[key]);
    });
    return returnVisibilities;
  }

  function featuretoggleapi() {
    var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    var globals = {
      datas: {},
      listeners: {},
      visibilities: initVisibilities(config),
      showLogs: false,
      usedPlugins: []
    };

    function init(api) {
      if (config._plugins) {
        if (!Array.isArray(config._plugins)) throw new Error('featuretoggleapi()-constructor: config.plugins must be an array.');

        config._plugins.forEach(function (plugin) {
          if (typeof plugin !== 'function') throw new Error('featuretoggleapi()-constructor: config.plugins needs functions as entries, not ' + _typeof(plugin) + '.');

          _addPlugin(plugin, api);
        });
      }

      triggerEvent('init');
    }

    function _addPlugin(plugin, api) {
      plugin(api);
    }

    function triggerEvent(eventtype, param) {
      (globals.listeners[eventtype] || []).forEach(function (listener) {
        listener(param);
      });
    }

    var log = function log(message) {
      if (!globals.showLogs) return; //Nur Browser können Syntaxhighlighting die anderen geben die Nachricht einfach aus und schneiden
      //die styletags raus

      if (typeof window === 'undefined') {
        var loggedMessage = message.replace(/<b>/g, "");
        console.log(loggedMessage);
        return;
      }

      var hasBoldTag = message.indexOf('<b>') != -1;
      var hasVisibleKeyword = message.indexOf('visible') != -1;
      var hasHiddenKeyword = message.indexOf('hidden') != -1;

      var _message = message.replace('visible', '%cvisible');

      _message = _message.replace('hidden', '%chidden');
      if (hasVisibleKeyword) console.log(_message, "color:green;font-weight:bold;");else if (hasHiddenKeyword) console.log(_message, "color:red;font-weight:bold;");else if (hasBoldTag) {
        _message = _message.replace('<b>', '%c');
        var parts = [_message, 'font-weight:bold;'];
        console.log.apply(null, parts);
      } else console.log(message);
    };

    var logAndReturn = function logAndReturn(returnValue, message) {
      log(message);
      log('');
      return returnValue;
    };

    var getVisibility = function getVisibility(visibilityFn, functionname, name, variant, data) {
      if (visibilityFn == null) return undefined;
      var calculatedVisibility = visibilityFn({
        name: name,
        variant: variant,
        data: data
      });

      if (typeof calculatedVisibility == 'boolean') {
        return calculatedVisibility;
      }

      return logAndReturn(false, "The ".concat(functionname, " returns ").concat(calculatedVisibility, ". => Please return true or false. This result (and all non-boolean results) will return false."));
    };

    function parseKey(key) {
      var parts = key.split('#');
      return {
        name: parts[0],
        variant: parts.length > 1 ? parts[1] : undefined,
        data: globals.datas[key]
      };
    }
    /*
        the following calls are possible:
        visibility(name,result);
        visibility(name,variant,result);
        visibility(name,variant,data,result);

        =>
        param1: name
        param2: result || variant
        param3: result || data
        param4: result
    */

    function visibilityFnParams(param1, param2, param3, param4) {
      //name must always be set
      if (param1 == undefined) throw new Error('feature.visibility(): 1st parameter name must be defined');
      if (arguments.length == 1) throw new Error('feature.visibility(): 2nd parameter name must be a boolean or function, but is empty');
      var name = param1,
          variant = null,
          data = null,
          result = null;

      if (param3 == undefined && param4 == undefined) {
        result = param2;
      } else if (param4 == undefined) {
        variant = param2;
        result = param3;
      } else {
        variant = param2;
        data = param3;
        result = param4;
      }

      return {
        name: name,
        variant: variant,
        data: data,
        result: result
      };
    }

    function getEvent(name, variant, data, result) {
      var event;
      event = {
        name: name,
        variant: variant,
        data: data
      };
      event.key = getKey(event.name, event.variant);
      if (result == null) return event;
      event.visibilityFunction = parseToFn(result);
      event.result = event.visibilityFunction({
        name: event.name,
        variant: event.variant,
        data: event.data || {},
        _internalCall: true,
        description: 'When attaching a function, the result must be calculated internally. You can filter this out with the _internalCall:true -Flag.'
      });
      return event;
    }

    function isVisible(name, variant, data) {
      var visibilities = globals.visibilities;
      log("\nCheck Visibility of <b>Feature \"".concat(name, "\", variant \"").concat(variant == undefined ? '' : variant, "\"").concat(data ? " with data " + JSON.stringify(data) : "", "."));
      if (name == undefined) throw new Error('The attribute "name" is required for tag <feature></feature>. Example: <feature name="aname"></feature>');
      var requiredFn = visibilities['_required'];
      var requiredFnExists = visibilities['_required'] != null;
      var requiredFnResult = getVisibility(requiredFn, 'requiredVisibility', name, variant, data);
      var visibilityFnKey = getKey(name, variant);
      var visibilityFn = visibilities[visibilityFnKey];
      var visibilityFnExists = visibilities[visibilityFnKey] != null;
      var visibilityFnResult = getVisibility(visibilityFn, 'visibility function', name, variant, data);
      var variantExists = variant != null;
      var visibilityOnlyNameFnKey = getKey(name, null);
      var visibilityOnlyNameFn = visibilities[visibilityOnlyNameFnKey];
      visibilities[visibilityOnlyNameFnKey] != null;
      var visibilityOnlyNameFnResult = getVisibility(visibilityOnlyNameFn, 'visibility function (only name)', name, variant, data);
      var defaultFn = visibilities['_default'];
      var defaultFnExists = visibilities['_default'] != null;
      var defaultFnResult = getVisibility(defaultFn, 'defaultVisibility', name, variant, data);
      if (!requiredFnExists) log("No requiredVisibility rule specified for this feature.");else if (requiredFnExists && requiredFnResult === true) log("The requiredVisibility rule returns true. This feature will be shown when no other rule rejects it.");else if (requiredFnExists && requiredFnResult === false) return logAndReturn(false, "The requiredVisibility rule returns false. This feature will be hidden.");
      if (visibilityFnExists) return logAndReturn(visibilityFnResult, "The visibility rule returns ".concat(visibilityFnResult, ". This feature will be ").concat(visibilityFnResult ? 'visible' : 'hidden', "."));
      log('No visibility rule found matching name and variant.');
      if (variantExists && typeof visibilityOnlyNameFnResult == 'boolean') return logAndReturn(visibilityOnlyNameFnResult, "Found a visibility rule for name ".concat(name, " without variants. The rule returns ").concat(visibilityOnlyNameFnResult, ". => This feature will be ").concat(visibilityOnlyNameFnResult ? 'visible' : 'hidden', "."));else if (variantExists) log("No rules found for name ".concat(name, " without variants."));
      if (defaultFnExists) return logAndReturn(defaultFnResult, "Found a defaultVisibility rule. The rule returns ".concat(defaultFnResult, ". => This feature will be ").concat(defaultFnResult ? 'visible' : 'hidden', "."));
      log("No default rule found.");
      if (requiredFnExists) return logAndReturn(true, "Only the requiredVisibility rule was found. This returned true. => This feature will be visible.");
      return logAndReturn(false, 'No rules were found. This feature will be hidden.');
    }

    var api = {
      name: 'feature-toggle-api',
      setData: function setData(nameParam, variantOrDataParam, dataParam) {
        if (nameParam == undefined) throw new Error('setData(): The name must of the feature must be defined, but ist undefined');
        var variant = dataParam != undefined ? variantOrDataParam : undefined;
        var data = dataParam || variantOrDataParam;
        var event = getEvent(nameParam, variant, data);
        globals.datas[event.key] = event.data;
        triggerEvent('visibilityrule', event);
      },
      on: function on(eventtype, fn, config) {
        globals.listeners[eventtype] = globals.listeners[eventtype] || [];
        globals.listeners[eventtype].push(fn);
        triggerEvent('registerEvent', {
          type: eventtype
        });
        if (config != undefined && config.ignorePreviousRules) return;
        Object.keys(globals.visibilities).forEach(function (key) {
          var event = parseKey(key);
          var rule = globals.visibilities[key];
          event.result = rule(event);
          fn(event);
        });
      },
      trigger: triggerEvent,
      showLogs: function showLogs(_showLogs) {
        globals.showLogs = _showLogs == undefined ? true : _showLogs;
      },
      isVisible: isVisible,

      /*
          the following function calls are possible:
          visibility(name,result);
          visibility(name,variant,result);
          visibility(name,variant,data,result);
      */
      visibility: function visibility(param1, param2, param3, param4) {
        var params = visibilityFnParams(param1, param2, param3, param4);
        var event = getEvent(params.name, params.variant, params.data, params.result);
        globals.visibilities[event.key] = event.visibilityFunction;
        globals.datas[event.key] = event.data;
        triggerEvent('visibilityrule', event);
      },
      requiredVisibility: function requiredVisibility(fn) {
        if (typeof fn != "function") throw new Error('feature.requiredVisibility(): 1st parameter must be a function, but is ' + _typeof(fn));
        globals.visibilities['_required'] = parseToFn(fn);
      },
      defaultVisibility: function defaultVisibility(fn) {
        if (typeof fn != "function") throw new Error('feature.defaultVisibility(): 1st parameter must be a function, but is ' + _typeof(fn));
        globals.visibilities['_default'] = parseToFn(fn);
      },
      addPlugin: function addPlugin(plugin) {
        if (globals.usedPlugins.includes(plugin)) return;

        _addPlugin(plugin, api);

        globals.usedPlugins.push(plugin);
      }
    };
    init(api);
    return api;
  }

  var featureToggleApi_module = featuretoggleapi;

  var FeatureToggleComponent = new featureToggleApi_module();

  function getDefaultSlot(slot) {
    // in vue3, slot is a function
    if (typeof slot == 'function') return slot(); //in vue <= 2 slot can be directly accessed.

    return slot;
  }

  function vuePlugin(api) {
    Object.assign(api, {
      props: {
        name: {
          type: String
        },
        variant: {
          type: String
        },
        data: {
          type: [Object, String]
        },
        tag: {
          type: String,
          "default": ''
        }
      },
      name: 'feature',
      data: function data() {
        return {
          isVisible: api.isVisible(this.name, this.variant, this.data)
        };
      },
      render: function render(createElement) {
        if (!this.isVisible) return; // fix for vue3: h is imported instead of passed by the render function

        if (!!this.tag) {
          var create = vue__namespace[function () {
            return 'h';
          }()] || createElement;

          return create(this.tag, {
            'feature-name': this.name,
            'feature-variant': this.variant
          }, getDefaultSlot(this.$slots["default"]));
        }

        return getDefaultSlot(this.$slots["default"]);
      },
      methods: {
        _isVisible: function _isVisible(name, variant, data) {
          return api.isVisible(name, variant, data);
        }
      }
    });
  }

  FeatureToggleComponent.addPlugin(vuePlugin);

  exports.FeatureToggleComponent = FeatureToggleComponent;

  Object.defineProperty(exports, '__esModule', { value: true });

}));


text:
package com.eeeya.fantuan.config;

import com.eeeya.fantuan.BaseTest;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;

@Component
public class AppConfigTest extends BaseTest {

    @Autowired
    AppConfig appConfig;

    @Test
    public void testGetAppProfileName() throws Exception {
        assertTrue(appConfig.getAppProfileName() != null);
    }

    @Test
    public void testGetAppName() throws Exception {
        assertTrue(appConfig.getAppName().equals("Fantuan"));
    }

    @Test
    public void testGetAppDescription() throws Exception {
        assertThat(appConfig.getAppDescription(), containsString(appConfig.getAppName()));
    }
}


text:
package org.apache.jackrabbit.oak.plugins.index.property.strategy;

import static org.apache.jackrabbit.oak.plugins.index.IndexConstants.ENTRY_COUNT_PROPERTY_NAME;
import static org.apache.jackrabbit.oak.plugins.index.IndexConstants.INDEX_CONTENT_NODE_NAME;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Set;

import javax.annotation.Nullable;

import org.apache.jackrabbit.oak.api.PropertyState;
import org.apache.jackrabbit.oak.api.Type;
import org.apache.jackrabbit.oak.plugins.memory.MultiStringPropertyState;
import org.apache.jackrabbit.oak.spi.query.Filter;
import org.apache.jackrabbit.oak.spi.state.ChildNodeEntry;
import org.apache.jackrabbit.oak.spi.state.NodeBuilder;
import org.apache.jackrabbit.oak.spi.state.NodeState;
import org.apache.jackrabbit.oak.util.ApproximateCounter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * An IndexStoreStrategy implementation that saves the unique node in a single property.

 * This should reduce the number of nodes in the repository, and speed up access.

 *

 * For example for a node that is under {@code /test/node}, the index
 * structure will be {@code /oak:index/index/@key}:
 */
public class UniqueEntryStoreStrategy implements IndexStoreStrategy {

    static final Logger LOG = LoggerFactory.getLogger(UniqueEntryStoreStrategy.class);

    private final String indexName;

    public UniqueEntryStoreStrategy() {
        this(INDEX_CONTENT_NODE_NAME);
    }

    public UniqueEntryStoreStrategy(String indexName) {
        this.indexName = indexName;
    }

    @Override
    public void update(
            NodeBuilder index, String path,
            @Nullable final String indexName,
            @Nullable final NodeBuilder indexMeta,
            Set<String> beforeKeys, Set<String> afterKeys) {
        for (String key : beforeKeys) {
            remove(index, key, path);
        }
        for (String key : afterKeys) {
            insert(index, key, path);
        }
    }

    private static void remove(NodeBuilder index, String key, String value) {
        ApproximateCounter.adjustCountSync(index, -1);
        NodeBuilder builder = index.getChildNode(key);
        if (builder.exists()) {
            // there could be (temporarily) multiple entries
            // we need to remove the right one
            PropertyState s = builder.getProperty("entry");
            if (s.count() == 1) {
                builder.remove();
            } else {
                ArrayList<String> list = new ArrayList<String>();
                for (int i = 0; i < s.count(); i++) {
                    String r = s.getValue(Type.STRING, i);
                    if (!r.equals(value)) {
                        list.add(r);
                    }
                }
                PropertyState s2 = MultiStringPropertyState.stringProperty("entry", list);
                builder.setProperty(s2);
            }
        }
    }

    private static void insert(NodeBuilder index, String key, String value) {
        ApproximateCounter.adjustCountSync(index, 1);
        NodeBuilder k = index.child(key);
        ArrayList<String> list = new ArrayList<String>();
        list.add(value);
        if (k.hasProperty("entry")) {
            // duplicate key (to detect duplicate entries)
            // this is just set temporarily,
            // while trying to add a duplicate entry
            PropertyState s = k.getProperty("entry");
            for (int i = 0; i < s.count(); i++) {
                String r = s.getValue(Type.STRING, i);
                if (!list.contains(r)) {
                    list.add(r);
                }
            }
        }
        PropertyState s2 = MultiStringPropertyState.stringProperty("entry", list);
        k.setProperty(s2);
    }

    @Override
    public Iterable<String> query(final Filter filter, final String indexName,
            final NodeState indexMeta, final Iterable<String> values) {
        final NodeState index = indexMeta.getChildNode(getIndexNodeName());
        return new Iterable<String>() {
            @Override
            public Iterator<String> iterator() {
                if (values == null) {
                    return new Iterator<String>() {

                        Iterator<? extends ChildNodeEntry> it = index.getChildNodeEntries().iterator();

                        @Override
                        public boolean hasNext() {
                            return it.hasNext();
                        }

                        @Override
                        public String next() {
                            PropertyState s = it.next().getNodeState().getProperty("entry");
                            return s.getValue(Type.STRING, 0);
                        }

                        @Override
                        public void remove() {
                            it.remove();
                        }

                    };
                }
                ArrayList<String> list = new ArrayList<String>();
                for (String p : values) {
                    NodeState key = index.getChildNode(p);
                    if (key.exists()) {
                        // we have an entry for this value, so use it
                        PropertyState s = key.getProperty("entry");
                        String v = s.getValue(Type.STRING, 0);
                        list.add(v);
                    }
                }
                return list.iterator();
            }
        };
    }

    @Override
    public boolean exists(NodeBuilder index, String key) {
        return index.hasChildNode(key);
    }

    @Override
    public long count(NodeState root, NodeState indexMeta, Set<String> values, int max) {
        NodeState index = indexMeta.getChildNode(getIndexNodeName());
        long count = 0;
        if (values == null) {
            PropertyState ec = indexMeta.getProperty(ENTRY_COUNT_PROPERTY_NAME);
            if (ec != null) {
                count = ec.getValue(Type.LONG);
                if (count >= 0) {
                    return count;
                }
            }
            if (count == 0) {
                long approxCount = ApproximateCounter.getCountSync(index);
                if (approxCount != -1) {
                    return approxCount;
                }
            }
            count = 1 + index.getChildNodeCount(max);
            // "is not null" queries typically read more data
            count *= 10;
        } else if (values.size() == 1) {
            NodeState k = index.getChildNode(values.iterator().next());
            if (k.exists()) {
                count = k.getProperty("entry").count();
            } else {
                count = 0;
            }
        } else {
            count = values.size();
        }
        return count;
    }

    @Override
    public long count(final Filter filter, NodeState root, NodeState indexMeta, Set<String> values, int max) {
        return count(root, indexMeta, values, max);
    }

    @Override
    public String getIndexNodeName() {
        return indexName;
    }
}