text:
package me.ialistannen.bukkitutil.commandsystem.implementation;

import me.ialistannen.bukkitutil.commandsystem.base.AbstractCommandNode;
import me.ialistannen.bukkitutil.commandsystem.base.CommandResultType;
import me.ialistannen.bukkitutil.commandsystem.base.CommandTree;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;

import java.util.Collections;
import java.util.List;

/**
 * The default TabCompleter
 */
@SuppressWarnings("WeakerAccess") // It said the class can be package-private. I disagree.
public class DefaultTabCompleter implements TabCompleter {

	private final CommandTree tree;

	private boolean assumeCommandIsPartOfTree;

	/**
	 *
	 * @param tree The {@link CommandTree}
	 *
	 * @see #DefaultTabCompleter(CommandTree, boolean) with true as the boolean
	 */
	@SuppressWarnings("unused")
	public DefaultTabCompleter(CommandTree tree) {
		this(tree, true);
	}

	/**
	 * @param tree                      The {@link CommandTree}
	 * @param assumeCommandIsPartOfTree If true, the command's name will be treated as the first argument.
	 */
	@SuppressWarnings("unused")
	public DefaultTabCompleter(CommandTree tree, boolean assumeCommandIsPartOfTree) {
		this.tree = tree;
		this.assumeCommandIsPartOfTree = assumeCommandIsPartOfTree;
	}

	@Override
	public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
		String[] arguments = args;
		if (assumeCommandIsPartOfTree) {
			arguments = new String[args.length + 1];
			System.arraycopy(args, 0, arguments, 1, args.length);
			arguments[0] = command.getName();
		}

		AbstractCommandNode.FindTabCompleteResult result = tree.doTabComplete(sender, alias, arguments);
		if (result.getResult() == CommandResultType.SUCCESSFUL) {
			return result.getResultList();
		}
		return Collections.emptyList();
	}
}


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

class Mr extends CI_Controller {
  function __construct() {
        parent::__construct();

        if ($this->session->userdata('is_logged_in') != TRUE && $this->uri->segment(1) != 'Auth' && $this->session->userdata('id_level_user') == '13' ){
        $this -> session -> set_flashdata('info_login', 'Anda tidak mempunyai otentifikasi ke halaman ini. Silahkan login ulang untuk mengakses sesuai dengan hak otentifikasi anda!');
        redirect('Auth');
    }
    date_default_timezone_set("Asia/Jakarta");

    }

  public function index()
  {
    //page info
    $data['dashboardtitle']= 'Manajer Rayon';
    $data['mr_active']= 'active';
    $data['mr_open']= 'open';
    $data['mr_sub']= 'active';
    $data['page']= '';
    $data['sub_page']= '';
    $data['activated_bread']= 'active';
    $data['dashboardtitle']= 'Manajer Rayon';
    $this->load->view('Mr_admin/data',$data);
  }

}

redpajama_set_name: RedPajamaGithub


text:
/*
 * NodeSearchPanel.java
 *
 * Created on February 18, 2004, 12:00 PM
 */

package org.tolweb.treegrow.main;

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import layout.TableLayout;
import org.jdom.*;

import org.tolweb.treegrow.tree.*;

/**
 *
 * @author  dmandel
 */
public class NodeSearchPanel extends JPanel {
    /**
	 *
	 */
	private static final long serialVersionUID = -4257874007109328110L;
	private DefaultListModel resultsListModel;
    private JList listBox;
    private JTextField nodeNameField;
    private JButton findNodeButton;

    /** Creates a new instance of NodeSearchPanel */
    public NodeSearchPanel(String label) {
        double[][] size = {{10, .33, .33, .33, 10}, {10, 25, 10, 175, 10}};
        setLayout(new TableLayout(size));
        JPanel findPanel = new JPanel(new BorderLayout());
        JLabel attachLabel = new JLabel(label);
        findPanel.add(attachLabel, BorderLayout.WEST);
        nodeNameField = new JTextField();
        nodeNameField.addKeyListener(new KeyAdapter() {
            public void keyPressed(KeyEvent evt) {
                if(evt.getKeyCode() == KeyEvent.VK_ENTER) {
                    findNodeButton.doClick();
                }
            }
        });
        findPanel.add(nodeNameField, BorderLayout.CENTER);

        findNodeButton = new JButton("Find node");
        findNodeButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Thread thread = new Thread() {
                    public void run() {
                        setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
                        findNodeButton.setEnabled(false);
                        doNodeSearch();
                        setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
                        findNodeButton.setEnabled(true);
                    }
                };
                thread.start();
            }
        });

        findPanel.add(findNodeButton, BorderLayout.EAST);
        add(findPanel, "1,1,3,1");
        resultsListModel = new DefaultListModel();
        listBox = new JList(resultsListModel);
        listBox.setCellRenderer(new NodeOrSearchResultCellRenderer());

        add(new JScrollPane(listBox), "1,3,3,3");

    }

    public Object getSelectedValue() {
        return listBox.getSelectedValue();
    }

    public void addListSelectionListener(ListSelectionListener listener) {
        listBox.addListSelectionListener(listener);
    }

    private void doNodeSearch() {
        Controller controller = Controller.getController();
        CheckNetConnection netConnection = new CheckNetConnection();
        resultsListModel.clear();
        if (netConnection.isConnected() < 0) {
            String NO_CONNECTION_LOCAL_NODES_ONLY = controller.getMsgString("NO_CONNECTION_LOCAL_NODES_ONLY");
            JOptionPane.showMessageDialog(this, NO_CONNECTION_LOCAL_NODES_ONLY, "No connection", JOptionPane.INFORMATION_MESSAGE);
        }
        Iterator it = TreePanel.getTreePanel().getTree().getCheckedOutNodes().iterator();
        while (it.hasNext()) {
            Node node = (Node) it.next();
            if (node.getName().toLowerCase().indexOf(nodeNameField.getText().toLowerCase()) != -1) {
                resultsListModel.addElement(node);
            }
        }
        if (netConnection.isConnected() > 0) {
            // Search the database for nodes with this name
            NodeNameSearcher searcher = new NodeNameSearcher();
            Object results;
            try {
                results = searcher.searchDatabase(nodeNameField.getText(), 0);
                Object[] currentResults = resultsListModel.toArray();
                if (results == null) {
                    throw new RuntimeException();
                } else if (results instanceof Element) {
                    String errorString = searcher.getSearchErrorString((Element) results);
                    if (!(resultsListModel.getSize() > 0 && errorString.equals(controller.getMsgString("NO_RECORD_FOUND")))) {
                        JOptionPane.showMessageDialog(this, errorString, "Error", JOptionPane.ERROR_MESSAGE);
                    }
                } else if (results instanceof Stack) {
                    boolean doAdd;
                    Stack stack = (Stack) results;
                    while (!stack.isEmpty()) {
                        doAdd = true;
                        NodeDetails details = (NodeDetails) stack.pop();
                        for (int i = 0; i < currentResults.length; i++) {
                            if (((Node) currentResults[i]).getName().equals(details.getNodeName())) {
                                doAdd = false;
                            }
                        }
                        if (doAdd) {
                            resultsListModel.addElement(details);
                        }
                    }
                    listBox.setSelectionInterval(0, 0);
                }
            } catch (Exception e) {
                String PROBLEM_SEARCHING = controller.getMsgString("PROBLEM_SEARCHING");
                JOptionPane.showMessageDialog(this, PROBLEM_SEARCHING, "Error", JOptionPane.ERROR_MESSAGE);
            }

        }
    }

    private class NodeOrSearchResultCellRenderer extends DefaultListCellRenderer {
        /**
		 *
		 */
		private static final long serialVersionUID = 895345196038082566L;

		public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            Component result = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            if (value instanceof Node) {
                ((JLabel) result).setText(((Node) value).getName());
            } else {
                ((JLabel) result).setText(((NodeDetails) value).getNodeName());
            }
            return result;
        }
    }
}


text:
import tensorflow as tf

class BaseModel(object):
    """"""

    def create_model(self, **unused_params):
        raise NotImplementedError()

    def run_model(self, unused_model_input, **unused_params):
        raise NotImplementedError()

    def get_variables(self):
        raise NotImplementedError()

class SampleModel(BaseModel):
    def __init__(self):
        pass

    def create_model(self, output_size, **unused_params):
        pass

    def run_model(self, model_input, **unused_params):
        pass

    def get_variables(self):
        pass


text:
namespace ui {
namespace test {

class TestWebDialogDelegate : public WebDialogDelegate {
 public:
  explicit TestWebDialogDelegate(const GURL& url);
  virtual ~TestWebDialogDelegate();

  void set_size(int width, int height) {
    size_.SetSize(width, height);
  }

  // WebDialogDelegate implementation:
  virtual ModalType GetDialogModalType() const OVERRIDE;
  virtual string16 GetDialogTitle() const OVERRIDE;
  virtual GURL GetDialogContentURL() const OVERRIDE;
  virtual void GetWebUIMessageHandlers(
      std::vector<content::WebUIMessageHandler*>* handlers) const OVERRIDE;
  virtual void GetDialogSize(gfx::Size* size) const OVERRIDE;
  virtual std::string GetDialogArgs() const OVERRIDE;
  virtual void OnDialogClosed(const std::string& json_retval) OVERRIDE;
  virtual void OnCloseContents(content::WebContents* source,
                               bool* out_close_dialog) OVERRIDE;
  virtual bool ShouldShowDialogTitle() const OVERRIDE;

 protected:
  const GURL url_;
  gfx::Size size_;

  DISALLOW_COPY_AND_ASSIGN(TestWebDialogDelegate);
};

}  // namespace test
}  // namespace ui

#endif  // UI_WEB_DIALOGS_TEST_TEST_WEB_DIALOG_DELEGATE_H_


text:
ROS package for Weiss Robotics WSG 32 Gripper

(also distributed as Schunk WSG 32)

Forked from: https://code.google.com/p/wsg50-ros-pkg

Modifications of this repository:
Reading back state with high rates, open-loop control via topics, catkinized, modifications for hydro.
Existing features are not discussed here - see original Wiki: https://code.google.com/p/wsg50-ros-pkg/wiki/wsg_32

Todo: Restructure code

Node wsg_32_ip (was: wsg_32_tcp)

Parameters

ip: IP address of gripper

port: Port of gripper

local_port: Local port for UDP

protocol: udp or tcp (default)

com_mode: polling (default), script or auto_update. See communication modes below.

rate: Polling rate in Hz.

grasping_force: Set grasping force limit on startup

Services

See https://code.google.com/p/wsg50-ros-pkg/wiki/wsg_32. Services currently block the reception of state updates.

Topics

~/goal_position [IN, wsg_32_common/Cmd], in modes script, auto_update:

Position goal; send target position in mm and speed

~/goal_speed [IN, std_msgs/Float32], in mode script:

Velocity goal (in mm/s); positive values open the gripper

~/moving [OUT, std_msgs/Bool], in modes script, auto_update:

Signals a change in the motion state for position control. Can be used to wait for the end of a gripper movement. Does not work correctly yet for velocity control, since the gripper state register does not directly provide this information.

~/state [OUT, std_msgs/State]:

State information (opening width, speed, forces). Note: Not all fields are available with all communication modes.

/joint_states [OUT, sensor_msgs/JointState]:

Standard joint state message

Communication modes (closed-loop control)

Select by com_mode parameter.

Polling

Gripper state is polled regularly using built-in commands (original implementaion). Service calls (e.g. move) block polling as long as the gripper moves. The topic interface is not available. Up to 15 Hz could be reached with the WSG-50 hardware revision 2.

Script

Allows for closed-loop control with a custom script (see below) that supports up to 2 FMF finger. Gripper state is read synchronously with the specified rate. Up to 30 Hz could be reached with the WSG-50 hardware revision 2. The gripper can be controlled asynchronously by sending position or velocity goals to the topics listed above. Commands will be sent with the next read command in the timer callback timer_cb().

The service interface can still be used - yet, they are blocking the gripper communication. There are no state updates while the gripper is moved by a service.

Auto_update

Requests periodic updates of the gripper state (position, speed, force; less data than with the script). Up to 140 Hz could be reached with the WSG-50 hardware revision 2. All responses of the gripper must be received by a reading thread which also publishes the ROS messages. Therefore, most commands in functions.cpp cannot be used. Position targets are sent asynchronously to the gripper using the built-in commands.

The services are disabled.

Gripper script

The script cmd_measure.lua must be running on the gripper for the script mode. It allows for non-blocking position and velocity control and responds with the current position, speed, motor force and up to two FMF finger forces. The custom commands 0xB0 (read only), 0xB1 (read, goal position and speed), 0xB2 (read, goal speed) are used. Tested with firmware version 2.6.4. There have been minor API changes since 1.x.

Node wsg_32_can

Remains unchanged; new features not implemented here.


text:
require File.expand_path('../../../spec_helper', __FILE__)

ruby_version_is ""..."1.9.1" do
  describe "Precision#prec_f" do
    it "converts a Integer to Float when called on an Integer" do
      1.prec_f.should==1.0
    end

    it "returns the same Float when called on a Float" do
      1.9.prec_f.should==1.9
    end
  end
end


text:
<?php

namespace PHPExiftool\Driver\Tag\DICOM;

use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;

/**
 * @ExclusionPolicy("all")
 */
class CertifiedTimestamp extends AbstractTag
{

    protected $Id = '0400,0310';

    protected $Name = 'CertifiedTimestamp';

    protected $FullName = 'DICOM::Main';

    protected $GroupName = 'DICOM';

    protected $g0 = 'DICOM';

    protected $g1 = 'DICOM';

    protected $g2 = 'Image';

    protected $Type = '?';

    protected $Writable = false;

    protected $Description = 'Certified Timestamp';
}


text:
#include "pch.h"
#include "Tile.h"
#include "GameManager.h"
#include "DataManager.h"
#include "ComponentManager.h"
#include "SpriteComponent.h"

bool Tile::init()
{
	if (!BaseComponent::init())
	{
		return false;
	}

	m_SpriteType = ST_END;
	return true;
}

void Tile::initPhysicsBody(cocos2d::Rect physicalRect, PhysicsCategory categoryBitmask)
{
	cocos2d::Rect physicsRect = cocos2d::Rect::ZERO;

	physicsRect.origin.x = physicalRect.size.width / 2;
	physicsRect.origin.y = physicalRect.size.height / 2;
	physicsRect.size = physicalRect.size;

	auto meterial = cocos2d::PhysicsMaterial(1, 1, 0);
	m_Body = cocos2d::PhysicsBody::createBox(physicsRect.size, meterial, physicsRect.origin);
	m_Body->setContactTestBitmask(PHYC_ALL);
	m_Body->setCategoryBitmask(categoryBitmask);
	m_Body->setCollisionBitmask(PHYC_ALL);
	m_Body->setTag(static_cast<int>(getType()));
	m_Body->setDynamic(false);
	m_Body->setMass(10);
	m_Body->setRotationEnable(false);
	m_Body->setPositionOffset(physicalRect.origin);
	m_Body->retain();

	setPhysicsBody(m_Body);
}

void Tile::initSprite(cocos2d::Size spriteSize)
{
	for(int yIdx = 0; yIdx < spriteSize.height; yIdx += GET_DATA_MANAGER()->getTileSize().height)
	{
		for(int xIdx = 0; xIdx < spriteSize.width; xIdx += GET_DATA_MANAGER()->getTileSize().width)
		{
			auto spriteComp = GET_COMPONENT_MANAGER()->createComponent<SpriteComponent>();
			spriteComp->initSprite(m_SpriteType, this, cocos2d::Point(xIdx, yIdx), cocos2d::Point(0,0));
			addComponent(spriteComp);
			spriteComp->enter();
		}
	}
}

void Tile::setEnabled(bool enable)
{
	if (enable == true)
	{
		setPhysicsBody(m_Body);
	}
	else
	{
		setPhysicsBody(nullptr);
		if (m_Body != nullptr)
		{
			m_Body->removeFromWorld();
		}
	}
}

Tile::Tile()
{

}

Tile::~Tile()
{
	SAFE_RELEASE(m_Body);
}


text:
@interface ViewController : UIViewController

@property(nonatomic,readonly,assign) NSInteger age;

@end


text:
package magefortress.creatures;

import magefortress.creatures.behavior.holdable.MFMockHoldable;
import magefortress.creatures.behavior.movable.MFMockMovable;
import magefortress.creatures.behavior.holdable.MFIHoldable;
import magefortress.creatures.behavior.movable.MFIMovable;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;

public class MFRaceTest
{
  private MFRace race;
  private final static Class<? extends MFIMovable> MOVE_CLASS = MFMockMovable.class;
  private final static Class<? extends MFIHoldable> HOLD_CLASS = MFMockHoldable.class;
  private final static int ID = 42;
  private final static String NAME = "Test Race";

  @Before
  public void setUp()
  {
    race = new MFRace(ID, NAME, MOVE_CLASS, HOLD_CLASS);
  }

  @Test(expected=IllegalArgumentException.class)
  public void shouldNotCreateRaceWithoutName()
  {
    race = new MFRace(ID, null, MFMockMovable.class, MFMockHoldable.class);
  }

  @Test(expected=IllegalArgumentException.class)
  public void shouldNotCreateRaceWithoutMovingBehaviour()
  {
    race = new MFRace(ID, NAME, null, HOLD_CLASS);
  }

  @Test(expected=IllegalArgumentException.class)
  public void shouldNotCreateRaceWithoutHoldingBehavior()
  {
    race = new MFRace(ID, NAME, MOVE_CLASS, null);
  }

  @Test(expected=ClassNotFoundException.class)
  public void shouldNotCreateRaceWithNonExistingMovingBehavior()
          throws ClassNotFoundException
  {
    final String movingBehaviorClassName = "MFMockMovable";
    final String holdingBehaviorClassName = "magefortress.creatures.behavior.holdable.MFMockHoldable";
    race = new MFRace(ID, NAME, movingBehaviorClassName, holdingBehaviorClassName);
  }

  @Test(expected=ClassNotFoundException.class)
  public void shouldNotCreateRaceWithNonExistingHoldingBehavior()
          throws ClassNotFoundException
  {
    final String movingBehaviorClassName = "magefortress.creatures.behavior.movable.MFMockMovable";
    final String holdingBehaviorClassName = "MFMockHoldable";
    race = new MFRace(ID, NAME, movingBehaviorClassName, holdingBehaviorClassName);
  }

  @Test(expected=IllegalArgumentException.class)
  public void shouldNotCreateRaceWithWrongMovingClassName()
          throws ClassNotFoundException
  {
    final String wrongMovingBehaviorClassName = "magefortress.creatures.behavior.holdable.MFMockHoldable";
    final String holdingBehaviorClassName = "magefortress.creatures.behavior.holdable.MFMockHoldable";

    race = new MFRace(ID, NAME, wrongMovingBehaviorClassName, holdingBehaviorClassName);
  }

  @Test(expected=IllegalArgumentException.class)
  public void shouldNotCreateRaceWithWrongHoldingClassName()
          throws ClassNotFoundException
  {
    final String movingBehaviorClassName = "magefortress.creatures.behavior.movable.MFMockMovable";
    final String wrongHoldingBehaviorClassName = "magefortress.creatures.behavior.movable.MFMockMovable";

    race = new MFRace(ID, NAME, movingBehaviorClassName, wrongHoldingBehaviorClassName);
  }

  @Test
  public void shouldCreateRaceWithBehaviorsByName()
          throws ClassNotFoundException
  {
    final String movingBehaviorClassName = "magefortress.creatures.behavior.movable.MFMockMovable";
    final String holdingBehaviorClassName = "magefortress.creatures.behavior.holdable.MFMockHoldable";
    race = new MFRace(ID, NAME, movingBehaviorClassName, holdingBehaviorClassName);

    assertEquals(movingBehaviorClassName, race.getMovingBehaviorClass().getName());
    assertEquals(holdingBehaviorClassName, race.getHoldingBehaviorClass().getName());
  }

  @Test
  public void shouldGetId()
  {
    assertEquals(ID, race.getId());
  }

  @Test
  public void shouldGetName()
  {
    assertEquals(NAME, race.getName());
  }

  @Test
  public void shouldGetMovingBehaviorClass()
  {
    Class<? extends MFIMovable> expMovingBehavior = MOVE_CLASS;
    Class<? extends MFIMovable> gotMovingBehavior = race.getMovingBehaviorClass();

    assertEquals(expMovingBehavior, gotMovingBehavior);
  }

  @Test
  public void shouldGetHoldingBehaviorClass()
  {
    Class<? extends MFIHoldable> expHoldingBehavior = HOLD_CLASS;
    Class<? extends MFIHoldable> gotHoldingBehavior = race.getHoldingBehaviorClass();

    assertEquals(expHoldingBehavior, gotHoldingBehavior);
  }

  @Test
  public void shouldCreateCreature()
  {
    Class<? extends MFIMovable> movingBehaviorClass = MFMockMovable.class;
    Class<? extends MFIHoldable> holdingBehaviorClass = MFMockHoldable.class;

    MFRace testrace = new MFRace(ID, NAME, movingBehaviorClass, holdingBehaviorClass);

    MFCreature gotCreature = testrace.createCreature();

    assertEquals(NAME, gotCreature.getName());
    assertEquals(movingBehaviorClass, gotCreature.getMovingBehavior().getClass());
    assertEquals(holdingBehaviorClass, gotCreature.getHoldingBehavior().getClass());
  }

}


text:
package productionBehaviours;

import common.AgentDataStore;
import interactors.DecisionBehaviour;
import interactors.ResponderBehaviour;

public class ProductionDecisionBehaviour extends DecisionBehaviour {

	private static final long serialVersionUID = -5138036682748995317L;

	public ProductionDecisionBehaviour(ResponderBehaviour interactionBehaviour, AgentDataStore dataStore) {
		super(interactionBehaviour, new ProductionDecision(interactionBehaviour, dataStore));
	}
}


text:
Basix XML syntax highlighter in C++/Qt (subclass of QSyntaxHighlighter). Uses simple regexes to highlight not very complicated XML content.

The primary limitations are:
* No specific handling for nested quotes within attributes
* No handling for multi-line comments

Also, at the moment there's no highlight for text content

The repository includes the highlighter class implemented as a static library and the example app. Here's the screenshot of the example app in action:
![](https://github.com/d1vanov/basic-xml-syntax-highlighter/blob/master/example/example.png)

License: MIT


text:
package rangolib

import "os/exec"

func RunHugo() ([]byte, error) {
	hugo := exec.Command("hugo")

	output, err := hugo.Output()
	if err != nil {
		return nil, err
	}

	return output, nil
}


text:
@interface ATSwipeTypePage : UIView <UITextViewDelegate>
@end


text:
<title>gcloud sql ssl-certs create</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="project_path" value="/sdk/_project.yaml">
<meta name="book_path" value="/sdk/_book.yaml">

NAME

gcloud sql ssl-certs create - creates an SSL certificate for a Cloud SQL instance

SYNOPSIS

gcloud sql ssl-certs create COMMON_NAME CERT_FILE [--instance INSTANCE, -i INSTANCE] [GLOBAL-FLAG …]

DESCRIPTION

Creates an SSL certificate for a Cloud SQL instance.

POSITIONAL ARGUMENTS

<var>COMMON_NAME</var>

User supplied name. Constrained to [a-zA-Z.-_ ]+.

<var>CERT_FILE</var>

Location of file which the private key of the created ssl-cert will be written to.

GROUP FLAGS

--instance <var>INSTANCE</var>, -i <var>INSTANCE</var>

Cloud SQL instance ID.

GLOBAL FLAGS

Run $ gcloud help for a description of flags available to
all commands.

NOTES

This command is in the Google Cloud SDK sql component. See
installing components
if it is not installed.


text:
<?php

class SettingsController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	//public $layout='//layouts/column2';
	public $defaultAction = 'index';

	/**
	 * Initialize admin page theme
	 */
	public function init()
	{
		if(!Yii::app()->user->isGuest) {
			if(Yii::app()->user->level == 1) {
				$arrThemes = Utility::getCurrentTemplate('admin');
				Yii::app()->theme = $arrThemes['folder'];
				$this->layout = $arrThemes['layout'];
			} else {
				throw new CHttpException(404, Yii::t('phrase', 'The requested page does not exist.'));
			}
		} else {
			$this->redirect(Yii::app()->createUrl('site/login'));
		}
	}

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			//'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array(),
				'users'=>array('@'),
				'expression'=>'isset(Yii::app()->user->level)',
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('general','banned','signup','analytic'),
				'users'=>array('@'),
				'expression'=>'isset(Yii::app()->user->level) && (Yii::app()->user->level == 1)',
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array(),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$this->redirect(array('general'));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionGeneral()
	{
		$model=$this->loadModel(1);

		// Uncomment the following line if AJAX validation is needed
		$this->performAjaxValidation($model);

		if(isset($_POST['OmmuSettings'])) {
			$model->attributes=$_POST['OmmuSettings'];
			$model->scenario = 'general';

			$jsonError = CActiveForm::validate($model);
			if(strlen($jsonError) > 2) {
				$errors = $model->getErrors();
				$summary['msg'] = "
".Yii::t('phrase', 'Please fix the following input errors:')."";
				$summary['msg'] .= "
";
				foreach($errors as $key => $value) {
					$summary['msg'] .= "
{$value[0]}
";
				}
				$summary['msg'] .= "

";

				$message = json_decode($jsonError, true);
				$merge = array_merge_recursive($summary, $message);
				$encode = json_encode($merge);
				echo $encode;

			} else {
				if(isset($_GET['enablesave']) && $_GET['enablesave'] == 1) {
					if($model->save()) {
						echo CJSON::encode(array(
							'type' => 0,
							'msg' => '
'.Yii::t('phrase', 'General settings success updated.').'
',
						));
					} else {
						print_r($model->getErrors());
					}
				}
			}
			Yii::app()->end();

		} else {
			$this->pageTitle = Yii::t('phrase', 'General Settings');
			$this->pageDescription = Yii::t('phrase', 'This page contains general settings that affect your entire social network.');
			$this->pageMeta = '';
			$this->render('admin_general',array(
				'model'=>$model,
			));
		}
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionBanned()
	{
		$model=$this->loadModel(1);

		// Uncomment the following line if AJAX validation is needed
		$this->performAjaxValidation($model);

		if(isset($_POST['OmmuSettings'])) {
			$model->attributes=$_POST['OmmuSettings'];
			$model->scenario = 'banned';

			$jsonError = CActiveForm::validate($model);
			if(strlen($jsonError) > 2) {
				$errors = $model->getErrors();
				$summary['msg'] = "
".Yii::t('phrase', 'Please fix the following input errors:')."";
				$summary['msg'] .= "
";
				foreach($errors as $key => $value) {
					$summary['msg'] .= "
{$value[0]}
";
				}
				$summary['msg'] .= "

";

				$message = json_decode($jsonError, true);
				$merge = array_merge_recursive($summary, $message);
				$encode = json_encode($merge);
				echo $encode;

			} else {
				if(isset($_GET['enablesave']) && $_GET['enablesave'] == 1) {
					if($model->save()) {
						echo CJSON::encode(array(
							'type' => 0,
							'msg' => '
'.Yii::t('phrase', 'Spam and banning tools success updated.').'
',
						));
					} else {
						print_r($model->getErrors());
					}
				}
			}
			Yii::app()->end();

		} else {
			$this->pageTitle = Yii::t('phrase', 'Spam & Banning Tools');
			$this->pageDescription = Yii::t('phrase', 'Social networks are often the target of aggressive spam tactics. This most often comes in the form of fake user accounts and spam in comments. On this page, you can manage various anti-spam and censorship features. Note: To turn on the signup image verification feature (a popular anti-spam tool), see the {setting} page.', array(
				'{setting}' => CHtml::link(Yii::t('phrase', 'Signup Settings'), Yii::app()->createUrl('settings/signup')),
			));
			$this->pageMeta = '';
			$this->render('admin_banned',array(
				'model'=>$model,
			));
		}
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionSignup()
	{
		$model=$this->loadModel(1);

		// Uncomment the following line if AJAX validation is needed
		$this->performAjaxValidation($model);

		if(isset($_POST['OmmuSettings'])) {
			$model->attributes=$_POST['OmmuSettings'];
			$model->scenario = 'signup';

			$jsonError = CActiveForm::validate($model);
			if(strlen($jsonError) > 2) {
				$errors = $model->getErrors();
				$summary['msg'] = "
".Yii::t('phrase', 'Please fix the following input errors:')."";
				$summary['msg'] .= "
";
				foreach($errors as $key => $value) {
					$summary['msg'] .= "
{$value[0]}
";
				}
				$summary['msg'] .= "

";

				$message = json_decode($jsonError, true);
				$merge = array_merge_recursive($summary, $message);
				$encode = json_encode($merge);
				echo $encode;

			} else {
				if(isset($_GET['enablesave']) && $_GET['enablesave'] == 1) {
					if($model->save()) {
						echo CJSON::encode(array(
							'type' => 0,
							'msg' => '
'.Yii::t('phrase', 'Signup setting success updated.').'
',
						));
					} else {
						print_r($model->getErrors());
					}
				}
			}
			Yii::app()->end();

		} else {
			$this->pageTitle = Yii::t('phrase', 'Signup Settings');
			$this->pageDescription = Yii::t('phrase', 'The user signup process is a crucial element of your social network. You need to design a signup process that is user friendly but also gets the initial information you need from new users. On this page, you can configure your signup process.');
			$this->pageMeta = '';
			$this->render('admin_signup',array(
				'model'=>$model,
			));
		}
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionAnalytic()
	{
		$model=$this->loadModel(1);

		// Uncomment the following line if AJAX validation is needed
		$this->performAjaxValidation($model);

		if(isset($_POST['OmmuSettings'])) {
			$model->attributes=$_POST['OmmuSettings'];

			$jsonError = CActiveForm::validate($model);
			if(strlen($jsonError) > 2) {
				$errors = $model->getErrors();
				$summary['msg'] = "
".Yii::t('phrase', 'Please fix the following input errors:')."";
				$summary['msg'] .= "
";
				foreach($errors as $key => $value) {
					$summary['msg'] .= "
{$value[0]}
";
				}
				$summary['msg'] .= "

";

				$message = json_decode($jsonError, true);
				$merge = array_merge_recursive($summary, $message);
				$encode = json_encode($merge);
				echo $encode;

			} else {
				if(isset($_GET['enablesave']) && $_GET['enablesave'] == 1) {
					if($model->save()) {
						echo CJSON::encode(array(
							'type' => 0,
							'msg' => '
'.Yii::t('phrase', 'Google analytics setting success updated.').'
',
						));
					} else {
						print_r($model->getErrors());
					}
				}
			}
			Yii::app()->end();

		} else {
			$this->pageTitle = Yii::t('phrase', 'Google Analytics Settings');
			$this->pageDescription = Yii::t('phrase', 'Want to use Google Analytics to keep track of your site\'s traffic data? Setup is super easy. Just enter your Google Analytics Tracking ID and *bam*... you\'re tracking your site\'s traffic stats! If you need help finding your ID, check here.');
			$this->pageMeta = '';
			$this->render('admin_analytic',array(
				'model'=>$model,
			));
		}
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model = OmmuSettings::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404, Yii::t('phrase', 'The requested page does not exist.'));
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='ommu-settings-form') {
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}


text:
class BackboneRailsRoutes::Routes

  def self.backbone
    routes = rails.each_with_object({}) do |route, result|
      result[route[:name]] = route[:path].gsub("(.:format)", "")
    end
  end

  def self.rails
    begin
      require 'rails/application/route_inspector'
      inspector = Rails::Application::RouteInspector.new
    rescue LoadError
      require 'action_dispatch/routing/inspector'
      inspector = ActionDispatch::Routing::RoutesInspector.new([])
    end

    Rails.application.reload_routes!
    routes = Rails.application.routes.routes

    return inspector.send(:collect_routes, routes)
  end

end


text:
package org.bluez;

import java.util.Map;

import org.bluez.datatypes.TwoTuple;
import org.bluez.exceptions.BluezFailedException;
import org.bluez.exceptions.BluezInProgressException;
import org.bluez.exceptions.BluezInvalidOffsetException;
import org.bluez.exceptions.BluezInvalidValueLengthException;
import org.bluez.exceptions.BluezNotAuthorizedException;
import org.bluez.exceptions.BluezNotPermittedException;
import org.bluez.exceptions.BluezNotSupportedException;
import org.freedesktop.dbus.FileDescriptor;
import org.freedesktop.dbus.interfaces.DBusInterface;
import org.freedesktop.dbus.types.UInt16;
import org.freedesktop.dbus.types.Variant;

/**
 * File generated - 2020-06-18.

 * Based on bluez Documentation: gatt-api.txt.

 *

 * Service: org.bluez

 * Interface: org.bluez.GattCharacteristic1

 *

 * Object path:

 *             [variable prefix]/{hci0,hci1,...}/dev_XX_XX_XX_XX_XX_XX/serviceXX/charYYYY

 *

 * Supported properties:

 *

 * 		string UUID [read-only]

 *

 * 			128-bit characteristic UUID.

 *

 * 		object Service [read-only]

 *

 * 			Object path of the GATT service the characteristic

 * 			belongs to.

 *

 * 		array{byte} Value [read-only, optional]

 *

 * 			The cached value of the characteristic. This property

 * 			gets updated only after a successful read request and

 * 			when a notification or indication is received, upon

 * 			which a PropertiesChanged signal will be emitted.

 *

 * 		boolean WriteAcquired [read-only, optional]

 *

 * 			True, if this characteristic has been acquired by any

 * 			client using AcquireWrite.

 *

 * 			For client properties is ommited in case

 * 			'write-without-response' flag is not set.

 *

 * 			For server the presence of this property indicates

 * 			that AcquireWrite is supported.

 *

 * 		boolean NotifyAcquired [read-only, optional]

 *

 * 			True, if this characteristic has been acquired by any

 * 			client using AcquireNotify.

 *

 * 			For client this properties is ommited in case 'notify'

 * 			flag is not set.

 *

 * 			For server the presence of this property indicates

 * 			that AcquireNotify is supported.

 *

 * 		boolean Notifying [read-only, optional]

 *

 * 			True, if notifications or indications on this

 * 			characteristic are currently enabled.

 *

 * 		array{string} Flags [read-only]

 *

 * 			Defines how the characteristic value can be used. See

 * 			Core spec "Table 3.5: Characteristic Properties bit

 * 			field", and "Table 3.8: Characteristic Extended

 * 			Properties bit field". Allowed values:

 *

 * 				"broadcast"

 * 				"read"

 * 				"write-without-response"

 * 				"write"

 * 				"notify"

 * 				"indicate"

 * 				"authenticated-signed-writes"

 * 				"extended-properties"

 * 				"reliable-write"

 * 				"writable-auxiliaries"

 * 				"encrypt-read"

 * 				"encrypt-write"

 * 				"encrypt-authenticated-read"

 * 				"encrypt-authenticated-write"

 * 				"secure-read" (Server only)

 * 				"secure-write" (Server only)

 * 				"authorize"

 *

 * 		uint16 Handle [read-write, optional] (Server Only)

 *

 * 			Characteristic handle. When available in the server it

 * 			would attempt to use to allocate into the database

 * 			which may fail, to auto allocate the value 0x0000

 * 			shall be used which will cause the allocated handle to

 * 			be set once registered.

 *

 *

 */
public interface GattCharacteristic1 extends DBusInterface {

    /**
     * From bluez documentation:

     *

     * Issues a request to read the value of the

     * characteristic and returns the value if the

     * operation was successful.

     *

     * Possible options: "offset": uint16 offset

     * 		  "mtu": Exchanged MTU (Server only)

     * 		  "device": Object Device (Server only)

     *

     *
     * @param _options options
     *
     * @return byte[] - maybe null
     *
     * @throws BluezFailedException on failure
     * @throws BluezInProgressException when operation already in progress
     * @throws BluezNotPermittedException on BluezNotPermittedException
     * @throws BluezNotAuthorizedException when not authorized
     * @throws BluezInvalidOffsetException on BluezInvalidOffsetException
     * @throws BluezNotSupportedException when operation not supported
     */
    byte[] ReadValue(Map<String, Variant<?>> _options) throws BluezFailedException, BluezInProgressException, BluezNotPermittedException, BluezNotAuthorizedException, BluezInvalidOffsetException, BluezNotSupportedException;

    /**
     * From bluez documentation:

     *

     * Issues a request to write the value of the

     * characteristic.

     *

     * Possible options: "offset": Start offset

     * 		  "type": string

     * Possible values:

     * "command": Write without

     * response

     * "request": Write with response

     * "reliable": Reliable Write

     * 		  "mtu": Exchanged MTU (Server only)

     * 		  "device": Device path (Server only)

     * 		  "link": Link type (Server only)

     * 		  "prepare-authorize": True if prepare

     * 	       authorization

     * 	       request

     *

     *
     * @param _value value
     * @param _options options
     *
     * @throws BluezFailedException on failure
     * @throws BluezInProgressException when operation already in progress
     * @throws BluezNotPermittedException on BluezNotPermittedException
     * @throws BluezInvalidValueLengthException on BluezInvalidValueLengthException
     * @throws BluezNotAuthorizedException when not authorized
     * @throws BluezNotSupportedException when operation not supported
     */
    void WriteValue(byte[] _value, Map<String, Variant<?>> _options) throws BluezFailedException, BluezInProgressException, BluezNotPermittedException, BluezInvalidValueLengthException, BluezNotAuthorizedException, BluezNotSupportedException;

    /**
     * From bluez documentation:

     *

     * Acquire file descriptor and MTU for writing. Only

     * sockets are supported. Usage of WriteValue will be

     * locked causing it to return NotPermitted error.

     *

     * For server the MTU returned shall be equal or smaller

     * than the negotiated MTU.

     *

     * For client it only works with characteristic that has

     * WriteAcquired property which relies on

     * write-without-response Flag.

     *

     * To release the lock the client shall close the file

     * descriptor, a HUP is generated in case the device

     * is disconnected.

     *

     * Note: the MTU can only be negotiated once and is

     * symmetric therefore this method may be delayed in

     * order to have the exchange MTU completed, because of

     * that the file descriptor is closed during

     * reconnections as the MTU has to be renegotiated.

     *

     * Possible options: "device": Object Device (Server only)

     * 		  "mtu": Exchanged MTU (Server only)

     * 		  "link": Link type (Server only)

     *

     *
     * @param _options options
     *
     * @return TwoTuple<FileDescriptor, UInt16> - maybe null
     *
     * @throws BluezFailedException on failure
     * @throws BluezNotSupportedException when operation not supported
     */
    TwoTuple<FileDescriptor, UInt16> AcquireWrite(Map<String, Variant<?>> _options) throws BluezFailedException, BluezNotSupportedException;

    /**
     * From bluez documentation:

     *

     * Acquire file descriptor and MTU for notify. Only

     * sockets are support. Usage of StartNotify will be locked

     * causing it to return NotPermitted error.

     *

     * For server the MTU returned shall be equal or smaller

     * than the negotiated MTU.

     *

     * Only works with characteristic that has NotifyAcquired

     * which relies on notify Flag and no other client have

     * called StartNotify.

     *

     * Notification are enabled during this procedure so

     * StartNotify shall not be called, any notification

     * will be dispatched via file descriptor therefore the

     * Value property is not affected during the time where

     * notify has been acquired.

     *

     * To release the lock the client shall close the file

     * descriptor, a HUP is generated in case the device

     * is disconnected.

     *

     * Note: the MTU can only be negotiated once and is

     * symmetric therefore this method may be delayed in

     * order to have the exchange MTU completed, because of

     * that the file descriptor is closed during

     * reconnections as the MTU has to be renegotiated.

     *

     * Possible options: "device": Object Device (Server only)

     * 		  "mtu": Exchanged MTU (Server only)

     * 		  "link": Link type (Server only)

     *

     *
     * @param _options options
     *
     * @return TwoTuple<FileDescriptor, UInt16> - maybe null
     *
     * @throws BluezFailedException on failure
     * @throws BluezNotSupportedException when operation not supported
     */
    TwoTuple<FileDescriptor, UInt16> AcquireNotify(Map<String, Variant<?>> _options) throws BluezFailedException, BluezNotSupportedException;

    /**
     * From bluez documentation:

     *

     * Starts a notification session from this characteristic

     * if it supports value notifications or indications.

     *

     *
     * @throws BluezFailedException on failure
     * @throws BluezNotPermittedException on BluezNotPermittedException
     * @throws BluezInProgressException when operation already in progress
     * @throws BluezNotSupportedException when operation not supported
     */
    void StartNotify() throws BluezFailedException, BluezNotPermittedException, BluezInProgressException, BluezNotSupportedException;

    /**
     * From bluez documentation:

     *

     * This method will cancel any previous StartNotify

     * transaction. Note that notifications from a

     * characteristic are shared between sessions thus

     * calling StopNotify will release a single session.

     *

     *
     * @throws BluezFailedException on failure
     */
    void StopNotify() throws BluezFailedException;

    /**
     * From bluez documentation:

     *

     * This method doesn't expect a reply so it is just a

     * confirmation that value was received.

     *

     *
     * @throws BluezFailedException on failure
     */
    void Confirm() throws BluezFailedException;

}


text:
Imageboard Mei
==============

Mei is a Futaba-styled imageboard, allowing people to discuss and upload pictures. My aim is to improve the user interface to my liking, instead of mimicking the traditional Futaba's look & feel.

**Visit the [wiki](https://github.com/lulalala/mei/wiki) to see more information! I try to minimize number of commits so documentations are all over there!**

### Highlights

* Multi-image upload
* Image upload using url
* Better user interface
* Multi-board support
* Extensible


text:
/*!
@file
@author Verox (verox.averre@gmail.com)
@author Nou (korewananda@gmail.com)
@author Glowbal (thomasskooi@live.nl)

@brief Curator functionality, aka Zeus

These are functions for working with the Zeus game master system.

https://github.com/NouberNou/intercept
*/
#pragma once
#include "shared.hpp"
#include "client\client.hpp"
#include "shared\client_types.hpp"

using namespace intercept::types;

namespace intercept {
    namespace sqf {

    }
}


text:
export PATH=/opt/oracle/instantclient_12_1:$PATH
export OCI_LIB_DIR=/opt/oracle/instantclient_12_1
export OCI_INC_DIR=/opt/oracle/instantclient_12_1/sdk/include
export ORACLE_HOME=/opt/oracle/instantclient_12_1
export LD_LIBRARY_PATH=/opt/oracle/instantclient_12_1:$LD_LIBRARY_PATH
export TNS_ADMIN=./
node server.js


text:
class CreateActiveadminCmsPosts < ActiveRecord::Migration
  def change
    create_table :activeadmin_cms_posts do |t|
      t.string  :title
      t.text    :content
      t.boolean :published, default: false
      t.timestamps
    end
  end
end


text:
package org.olat.core.gui.components;

import org.olat.core.gui.render.RenderResult;
import org.olat.core.gui.render.Renderer;
import org.olat.core.gui.render.RenderingState;
import org.olat.core.gui.render.StringOutput;
import org.olat.core.gui.render.URLBuilder;
import org.olat.core.gui.translator.Translator;

/**
 *
 * Empty implementation of the ComponentRenderer
 *
 * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com
 *
 */
public class DefaultComponentRenderer implements ComponentRenderer {

	@Override
	public void render(Renderer renderer, StringOutput sb, Component source,
			URLBuilder ubu, Translator translator, RenderResult renderResult,
			String[] args) {
		//
	}

	@Override
	public void renderHeaderIncludes(Renderer renderer, StringOutput sb,
			Component source, URLBuilder ubu, Translator translator,
			RenderingState rstate) {
		//
	}

	@Override
	public void renderBodyOnLoadJSFunctionCall(Renderer renderer,
			StringOutput sb, Component source, RenderingState rstate) {
		//
	}
}


text:
	<input class="goalID" type="hidden" data-value="goalURI"></input>
	<input class="goalStatusCode" type="hidden"  data-value="statusCode"></input>

		<button class="ui-button ui-button-small deleteGoal" data-template-bind='[{"attribute": "data-target-goal-uri", "value": "goalURI"}, {"attribute": "creator-uri", "value": "creatorURI"}]' data-localize="Act_Delete">Delete</button>

	<button class="ui-button ui-button-small editGoal" data-template-bind='[{"attribute": "data-target-goal-uri", "value": "goalURI"}]' data-localize="Act_Edit">Edit</button>
	<button class="ui-button ui-button-small openGoalEdit addSubgoal" data-localize="Act_AddSubgoal" data-template-bind='[{"attribute": "data-target-goal-uri", "value": "goalURI"},{"attribute": "data-target-goal-title", "value": "title"},{"attribute": "data-target-goal-location-uri", "value": "locationURI"},{"attribute": "data-target-goal-wisher-uri", "value": "wisherURI"},{"attribute": "data-target-goal-wisher-name", "value": "wisherName"} ]'>Add subgoal</button>


text:
using namespace OVR;
namespace OvrMangaroll {

	struct ProviderState {
	public:
		MangaProvider *Provider;
		int Offset;

		ProviderState() : Provider(NULL), Offset(0) {}
		ProviderState(MangaProvider *provider, int offset = 0) : Provider(provider), Offset(offset) {}
	};

	// Forward declaration
	class Mangaroll;
	class Manga;
	class MangaSelectorComponent;

	class CategoryComponent : public ClickableComponent {
	public:
		CategoryComponent();
		virtual ~CategoryComponent() { }
		bool Selected;
		Vector4f ColNormal;
		Vector4f ColFocused;
		Vector4f ColHighlight;
	protected:
		virtual eMsgStatus _OnEvent(OvrGuiSys & guiSys, VrFrame const & vrFrame,
			VRMenuObject * self, VRMenuEvent const & event);
	private:
		bool _Focused;
	};

	class MangaPanel : public UIObject {
	public:
		MangaPanel(OvrGuiSys &guiSys);
		virtual ~MangaPanel();
		void SetSelector(MangaSelectorComponent *selector);

		void AddToMenu(UIMenu *menu, UIObject *parent = NULL);
		void SetManga(MangaWrapper *manga);
		MangaWrapper *GetManga();
		void Update();
		bool IsTitleVisible() { return _Title->GetVisible(); }
		void UpdateProgress();

	public:
		float Position;
		int Index;
		int Width;
		int Height;
		int Border;
	private:
		void Init(void);
		void UpdateCoverAspectRatio();
	private:
		MangaSelectorComponent *_Selector;
		MangaWrapper *_Manga;
		UIImage *_Background;
		UILabel *_Title;
		UIImage *_Cover;
		UIImage *_Preloader;
		UIScrubBar *_Progressbar;

		UITexture *_CoverTexture;
		ClickableComponent *_Component;
		OvrGuiSys *_Gui;

		static void OnClick(void *);
	};

	class MangaSelectorComponent : public VRMenuComponent {
	public:
		MangaSelectorComponent(OvrGuiSys &guiSys);
		virtual ~MangaSelectorComponent() { }

		void SetProvider(MangaProvider &provider, bool stack=false);
		void AddToMenu(UIMenu *menu, UIObject *parent);

		void SetOnSelectManga(void(*cb)(Manga*, void*), void* obj) {
			this->_Callback = cb;
			this->_CallbackObject = obj;
		}

		void SelectManga(Manga *manga);
		bool CanSeek();
		bool CanSeekBack();
		bool CanGoBack() {
			return _Providers.GetSizeI() > 1;
		}
		void GoBack() {
			//if (IsOperatable()) {
				_Providers.Pop(); // TODO: Garbage
				_NoResultMessage->SetVisible(false);
				Seek(0);
				_FadeDir = -1;
			//}
		}

		bool IsOperatable() {
			return _Transition.GetFadeState() == Fader::FADE_NONE;
		}

		void UpdateGUI();

		// Constants because I'm lazy
		static int const COLS = 8;
		static int const ROWS = 2;
		static int const ANGLE = 100; // Degrees
		static int const MARGIN = 20;

		// Number of visible panels on either side
		static int const NUM_VISIBLE_PANELS = 2;
	private:
		virtual eMsgStatus OnEvent_Impl(OvrGuiSys & guiSys, VrFrame const & vrFrame,
			VRMenuObject * self, VRMenuEvent const & event);

		void Update(VRMenuEvent const & evt);
		void CleanPanels();
		void Seek(int dir);
		void UpdatePanels();

		ProviderState &CurrentState() {
			return _Providers.Back();
		}
		MangaProvider *CurrentProvider() {
			return CurrentState().Provider;
		}

		MangaPanel *CreatePanel(int x, int y, UIObject *container);
		static void OnGoBackward(UIButton *, void *);
		static void OnGoForward(UIButton *, void *);
		bool ProviderCaughtUp();

		UIMenu *_Menu;
		UIObject *_Parent;
		OvrGuiSys &_Gui;
		void(*_Callback)(Manga*, void*);
		void *_CallbackObject;
		UIContainer *_Containers[2];
		Array<MangaPanel *> _PanelSets[2];
		int _Front;
		int _Back;
		SineFader _Transition;
		int _FadeDir;
		int _FillCount;
		float _Speed;
		float _Gravity;
		Vector2f _LastTouch;
		float _TouchStartTime;
		bool _IsTouching;
		float _PanelHeight;
		Array<ProviderState> _Providers;
		int _PanelCount;
		UITexture _Arrow;
		UITexture _ArrowLeftTexture;
		UITexture _Fill;
		UILabel *_NoResultMessage;

		UILabel *_Title;
		UIButton *_ArrowRight;
		UIButton *_ArrowLeft;

		VRMenuObject *_ActivePanel;
		double _FocusLostTime;
	};

	class MangaSelectionView : public View {
	public:
		MangaSelectionView(Mangaroll &app);
		virtual ~MangaSelectionView();

		virtual void 		OneTimeInit(const char * launchIntent);
		virtual void		OneTimeShutdown();

		virtual void 		OnOpen();
		virtual void 		OnClose();
		virtual bool 		OnKeyEvent(const int keyCode, const int repeatCount, const KeyEventType eventType);
		virtual Matrix4f 	Frame(const VrFrame & vrFrame);
		virtual Matrix4f	GetEyeViewMatrix(const int eye) const;
		virtual Matrix4f	GetEyeProjectionMatrix(const int eye, const float fovDegreesX, const float fovDegreesY) const;
		virtual Matrix4f 	DrawEyeView(const int eye, const float fovDegreesX, const float fovDegreesY, ovrFrameParms & frameParms);

		void OnSelectManga(Manga *);

	private:

		void UpdateGUI();
		Mangaroll &_Mangaroll;
		UIMenu *_Menu;

		UIContainer *_OrientationContainer;
		UIContainer *_MainContainer;
		UIContainer *_LabelContainer;
		UILabel *_LocalSrcLabel;
		UILabel *_RemoteSrcLabel;

		MangaSelectorComponent *_Selector;
		UIContainer *_SelectorContainer;
		UITexture _FillTexture;

		LocalMangaProvider _LocalMangaProvider;
		MangaServiceProvider _NProvider;

		CategoryComponent _LocalCategoryComponent;
		CategoryComponent _RemoteCategoryComponent;

		SineFader _Fader;
		bool _CloseRequested;
		float _AngleOnOpen;
		static void OnLocalCategory(void *p);
		static void OnRemoteCategory(void *p);
	};

}


text:
class Base {
  public String foo() {
    return "Base.foo()";
  }
}


text:
var a = require('async');
var e = require('./Exceptions');
var u = require('./Utils');
var NewDownload = require('./NewDownloadSetup');
var ReDownload = require('./ReDownloadSetup');

var isReDownload = function() {
	this.cParams.downloadType = 'new';
	if (this.cParams.file.match(/.*\.mtd$/g)) {
		this.cParams.downloadType = 're';
		return true;
	}
	return false;
};

var TaskExecuter = function(file, url, cParams) {
	this.cParams = cParams || {};

	this.cParams.file = file;

	if (isReDownload.call(this) === false) {
		this.cParams.url = url;
	}
};

var _start = function() {
	var self = this;
	var callback = function(tasks) {
		a.auto(tasks, self.cParams.onEnd);
	};

	if (self.cParams.downloadType == 'new') {
		if (self.cParams.url === undefined) self.cParams.onEnd(e(1005));
		else u.executor(NewDownload, self.cParams)(callback);
	} else {
		u.executor(ReDownload, self.cParams)(callback);
	}
};

TaskExecuter.prototype.start = _start;

module.exports = TaskExecuter;


text:
<?php
require_once 'PHPUnit2/Framework/TestCase.php';

class _model_Node_OpenEndedText extends PHPUnit2_Framework_TestCase {
	function testCompileAnswerExpression() {
		$question = SyndNodeLib::factory('open_ended_text');

		$question->data['INFO_CORRECT_ANSWER'] = "You are always interrupting me! <It is/It's> really very rude.";
		$this->assertTrue($question->isCorrect("You are always interrupting me! It is really very rude."));
		$this->assertTrue($question->isCorrect("You are always interrupting me! It's really very rude."));

		$question->data['INFO_CORRECT_ANSWER'] = "You are always interrupting me! <It is/ It's > really very rude.";
		$this->assertTrue($question->isCorrect("You are always interrupting me! It's really very rude."));

		$question->data['INFO_CORRECT_ANSWER'] = "You are always interrupting me! < It is / It's >really very rude.";
		$this->assertTrue($question->isCorrect("You are always interrupting me! It's really very rude."));

		$question->data['INFO_CORRECT_ANSWER'] = "You are <always/often/mostly> interrupting me! <It is/It's> really very rude.";
		$this->assertTrue($question->isCorrect("You are always interrupting me! It's really very rude."));
		$this->assertTrue($question->isCorrect("You are often interrupting me! It's really very rude."));
		$this->assertTrue($question->isCorrect("You are mostly interrupting me! It's really very rude."));
	}
}


text:
/* global window */
/* global define */

(function (factory) {
    "use strict";

    var hookup      = typeof window !== "undefined" ? window : this;
    hookup.Legalize = factory();

    if (typeof define === "function" && define.amd) {
        define("Legalize", [], hookup.Legalize);
    }
}(function (undefined) {
    "use strict";

    function isFunc(f) {
        return typeof f === 'function';
    }

    // es5 shims
    if (!Array.isArray) {
        Array.isArray = function (arg) {
            return Object.prototype.toString.call(arg) === '[object Array]';
        };
    }

    var ES5Object = {

        freeze: isFunc(Object.freeze) ? Object.freeze : function (x) {
            // Object.freeze is used to freeze the publicly exposed API.
            // This will work on all modern browsers, so "attacking"
            // (= shooting yourself in the foot) the API will work only in legacy browsers.
            // Therefore: The shim just returns the thing and that's all it does.
            // This is the same behaviour as in github.com/es-shims/es5-shim .
            return x;
        },

        keys: isFunc(Object.keys) ? Object.keys : (function() {
            // Object.keys() is not available in some legacy browsers.
            // This shim is taken (and slightly modified to make jshint happy) from
            // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

            var hasOwnProperty = Object.prototype.hasOwnProperty;
            var hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString');
            var dontEnums = [
                  'toString',
                  'toLocaleString',
                  'valueOf',
                  'hasOwnProperty',
                  'isPrototypeOf',
                  'propertyIsEnumerable',
                  'constructor'
                ];
            var dontEnumsLength = dontEnums.length;

            return function(obj) {
                var result = [], prop, i;

                for (prop in obj) {
                    if (hasOwnProperty.call(obj, prop)) {
                        result.push(prop);
                    }
                }

                if (hasDontEnumBug) {
                    for (i = 0; i < dontEnumsLength; i += 1) {
                        if (hasOwnProperty.call(obj, dontEnums[i])) {
                            result.push(dontEnums[i]);
                        }
                    }
                }
                return result;
            };
        }()),

        create: isFunc(Object.create) ? Object.create : function (object) {
            // Object.create() is not available in some legacy browsers.
            // This is not a proper shim (for example it does not support a second argument).
            // The implementation here is however all that is needed for legalize.
            function F() {}
            F.prototype = object;

            return new F();
        }
    };

    return (function (Object) {

        // the `Object` argument overloads the actual `Object` in legacy
        // browser engines. legalize uses exactly the functions defined
        // above. Node will not care as this file is only wrapped around
        // the library for the browser.

        /* jshint unused: false */

        // @include legalize.js
        /* global publiclyExposedInterface */

        return publiclyExposedInterface;
    }(ES5Object));
}));


text:
namespace peloton {
namespace concurrency {

//===--------------------------------------------------------------------===//
// Transaction
//===--------------------------------------------------------------------===//

class Transaction : public Printable {
  Transaction(Transaction const &) = delete;

 public:
  Transaction(const size_t thread_id,
              const IsolationLevelType isolation,
              const cid_t &read_id) {
    Init(thread_id, isolation, read_id);
  }

  Transaction(const size_t thread_id,
              const IsolationLevelType isolation,
              const cid_t &read_id,
              const cid_t &commit_id) {
    Init(thread_id, isolation, read_id, commit_id);
  }

  ~Transaction() {}

 private:

  void Init(const size_t thread_id,
            const IsolationLevelType isolation,
            const cid_t &read_id) {
    Init(thread_id, isolation, read_id, read_id);
  }

  void Init(const size_t thread_id,
            const IsolationLevelType isolation,
            const cid_t &read_id,
            const cid_t &commit_id) {
    read_id_ = read_id;

    // commit id can be set at a transaction's commit phase.
    commit_id_ = commit_id;

    // set txn_id to commit_id.
    txn_id_ = commit_id_;

    epoch_id_ = read_id_ >> 32;

    thread_id_ = thread_id;

    isolation_level_ = isolation;

    is_written_ = false;

    insert_count_ = 0;

    gc_set_.reset(new GCSet());
  }

 public:
  //===--------------------------------------------------------------------===//
  // Mutators and Accessors
  //===--------------------------------------------------------------------===//

  inline size_t GetThreadId() const { return thread_id_; }

  inline txn_id_t GetTransactionId() const { return txn_id_; }

  inline cid_t GetReadId() const { return read_id_; }

  inline cid_t GetCommitId() const { return commit_id_; }

  inline eid_t GetEpochId() const { return epoch_id_; }

  inline void SetCommitId(const cid_t commit_id) { commit_id_ = commit_id; }

  void RecordRead(const ItemPointer &);

  void RecordReadOwn(const ItemPointer &);

  void RecordUpdate(const ItemPointer &);

  void RecordInsert(const ItemPointer &);

  // Return true if we detect INS_DEL
  bool RecordDelete(const ItemPointer &);

  void RecordDropedTable(storage::DataTable *table) {
    dropped_tables.push_back(table);
  }

  std::vector<storage::DataTable *> &GetDroppedTables() {
    return dropped_tables;
  }

  RWType GetRWType(const ItemPointer &);

  bool IsInRWSet(const ItemPointer &location) {

    oid_t tile_group_id = location.block;
    oid_t tuple_id = location.offset;

    if (rw_set_.find(tile_group_id) != rw_set_.end() &&
        rw_set_.at(tile_group_id).find(tuple_id) !=
            rw_set_.at(tile_group_id).end()) {
      return true;
    } else {
      return false;
    }
  }

  inline const ReadWriteSet &GetReadWriteSet() { return rw_set_; }

  inline std::shared_ptr<GCSet> GetGCSetPtr() { return gc_set_; }

  inline bool IsGCSetEmpty() { return gc_set_->size() == 0; }

  // Get a string representation for debugging
  const std::string GetInfo() const;

  // Set result and status
  inline void SetResult(ResultType result) { result_ = result; }

  // Get result and status
  inline ResultType GetResult() const { return result_; }

  inline bool IsReadOnly() const {
    return is_written_ == false && insert_count_ == 0;
  }

  inline IsolationLevelType GetIsolationLevel() const {
    return isolation_level_;
  }
 private:
  //===--------------------------------------------------------------------===//
  // Data members
  //===--------------------------------------------------------------------===//

  // transaction id
  txn_id_t txn_id_;

  // thread id
  size_t thread_id_;

  // read id
  // this id determines which tuple versions the transaction can access.
  cid_t read_id_;

  // commit id
  // this id determines the id attached to the tuple version written by the transaction.
  cid_t commit_id_;

  // epoch id can be extracted from read id.
  // GC manager uses this id to check whether a version is still visible.
  eid_t epoch_id_;

  ReadWriteSet rw_set_;

  // this set contains data location that needs to be gc'd in the transaction.
  std::shared_ptr<GCSet> gc_set_;

  // result of the transaction
  ResultType result_ = ResultType::SUCCESS;

  std::vector<storage::DataTable *> dropped_tables;

  bool is_written_;
  size_t insert_count_;

  IsolationLevelType isolation_level_;

};

}  // End concurrency namespace
}  // End peloton namespace


text:
static FILE* LogFile = NULL;
static const char * LogPath = "patrician_log.dat";

void initialize_log_lock(void);
void lock_log_lock(void);
void unlock_log_lock(void);
void release_log_lock(void);

void initialize_log(void)
{
	assert(LogFile == NULL);

	LogFile = fopen(LogPath, "w");
	initialize_log_lock();
}

void log_entry(const char* tag, const char* data)
{
	lock_log_lock();
	fprintf(LogFile, "{\"log_type\":\"%s\", \"data\":\"%s\"}\n", tag, data);
	fflush(LogFile);
	unlock_log_lock();
}

void release_log(void)
{
	release_log_lock();

	fclose(LogFile);
	LogFile = NULL;
}

void initialize_log_lock(void)
{

}

void lock_log_lock(void)
{

}

void unlock_log_lock(void)
{

}

void release_log_lock(void)
{

}


text:
package org.apache.solr.core;

import org.apache.solr.cloud.CurrentCoreDescriptorProvider;
import org.apache.solr.cloud.SolrZkServer;
import org.apache.solr.cloud.ZkController;
import org.apache.solr.cloud.ZkSolrResourceLoader;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.cloud.ZkStateReader;
import org.apache.solr.common.cloud.ZooKeeperException;
import org.apache.solr.common.util.ExecutorUtil;
import org.apache.solr.schema.IndexSchema;
import org.apache.solr.schema.IndexSchemaFactory;
import org.apache.solr.util.DefaultSolrThreadFactory;
import org.apache.solr.util.SystemIdResolver;
import org.apache.zookeeper.KeeperException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.InputSource;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeoutException;

public class ZkContainer {
  protected static Logger log = LoggerFactory.getLogger(ZkContainer.class);

  protected ZkController zkController;
  private SolrZkServer zkServer;

  private ExecutorService coreZkRegister = Executors.newFixedThreadPool(Integer.MAX_VALUE,
      new DefaultSolrThreadFactory("coreZkRegister") );

  public ZkContainer() {

  }

  public void initZooKeeper(final CoreContainer cc, String solrHome, ConfigSolr config) {

    if (config.getCoreLoadThreadCount() <= 1) {
      throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
          "SolrCloud requires a value of at least 2 in solr.xml for coreLoadThreads");
    }

    initZooKeeper(cc, solrHome,
        config.getZkHost(), config.getZkClientTimeout(), config.getZkHostPort(), config.getZkHostContext(),
        config.getHost(), config.getLeaderVoteWait(), config.getGenericCoreNodeNames());
  }

  public void initZooKeeper(final CoreContainer cc, String solrHome, String zkHost, int zkClientTimeout, String hostPort,
                            String hostContext, String host, int leaderVoteWait, boolean genericCoreNodeNames) {
    ZkController zkController = null;

    // if zkHost sys property is not set, we are not using ZooKeeper
    String zookeeperHost;
    if(zkHost == null) {
      zookeeperHost = System.getProperty("zkHost");
    } else {
      zookeeperHost = zkHost;
    }

    String zkRun = System.getProperty("zkRun");

    if (zkRun == null && zookeeperHost == null)
        return;  // not in zk mode

    if (null == hostPort) {
      throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR,
                   "'hostPort' must be configured to run SolrCloud");
    }
    if (null == hostContext) {
      throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR,
                   "'hostContext' must be configured to run SolrCloud");
    }

    // zookeeper in quorum mode currently causes a failure when trying to
    // register log4j mbeans.  See SOLR-2369
    // TODO: remove after updating to an slf4j based zookeeper
    System.setProperty("zookeeper.jmx.log4j.disable", "true");

    if (zkRun != null) {
      String zkDataHome = System.getProperty("zkServerDataDir", solrHome + "zoo_data");
      String zkConfHome = System.getProperty("zkServerConfDir", solrHome);
      zkServer = new SolrZkServer(zkRun, zookeeperHost, zkDataHome, zkConfHome, hostPort);
      zkServer.parseConfig();
      zkServer.start();

      // set client from server config if not already set
      if (zookeeperHost == null) {
        zookeeperHost = zkServer.getClientString();
      }
    }

    int zkClientConnectTimeout = 30000;

    if (zookeeperHost != null) {

      // we are ZooKeeper enabled
      try {
        // If this is an ensemble, allow for a long connect time for other servers to come up
        if (zkRun != null && zkServer.getServers().size() > 1) {
          zkClientConnectTimeout = 24 * 60 * 60 * 1000;  // 1 day for embedded ensemble
          log.info("Zookeeper client=" + zookeeperHost + "  Waiting for a quorum.");
        } else {
          log.info("Zookeeper client=" + zookeeperHost);
        }
        String confDir = System.getProperty("bootstrap_confdir");
        boolean boostrapConf = Boolean.getBoolean("bootstrap_conf");

        if(!ZkController.checkChrootPath(zookeeperHost, (confDir!=null) || boostrapConf)) {
          throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR,
              "A chroot was specified in ZkHost but the znode doesn't exist. ");
        }
        zkController = new ZkController(cc, zookeeperHost, zkClientTimeout,
            zkClientConnectTimeout, host, hostPort, hostContext,
            leaderVoteWait, genericCoreNodeNames,
            new CurrentCoreDescriptorProvider() {

              @Override
              public List<CoreDescriptor> getCurrentDescriptors() {
                List<CoreDescriptor> descriptors = new ArrayList<CoreDescriptor>(
                    cc.getCoreNames().size());
                Collection<SolrCore> cores = cc.getCores();
                for (SolrCore core : cores) {
                  descriptors.add(core.getCoreDescriptor());
                }
                return descriptors;
              }
            });

        if (zkRun != null && zkServer.getServers().size() > 1 && confDir == null && boostrapConf == false) {
          // we are part of an ensemble and we are not uploading the config - pause to give the config time
          // to get up
          Thread.sleep(10000);
        }

        if(confDir != null) {
          File dir = new File(confDir);
          if(!dir.isDirectory()) {
            throw new IllegalArgumentException("bootstrap_confdir must be a directory of configuration files");
          }
          String confName = System.getProperty(ZkController.COLLECTION_PARAM_PREFIX+ZkController.CONFIGNAME_PROP, "configuration1");
          zkController.uploadConfigDir(dir, confName);
        }

        if(boostrapConf) {
          ZkController.bootstrapConf(zkController.getZkClient(), cc, solrHome);
        }

      } catch (InterruptedException e) {
        // Restore the interrupted status
        Thread.currentThread().interrupt();
        log.error("", e);
        throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR,
            "", e);
      } catch (TimeoutException e) {
        log.error("Could not connect to ZooKeeper", e);
        throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR,
            "", e);
      } catch (IOException e) {
        log.error("", e);
        throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR,
            "", e);
      } catch (KeeperException e) {
        log.error("", e);
        throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR,
            "", e);
      }

    }
    this.zkController = zkController;
  }

  // Helper method to separate out creating a core from ZK as opposed to the
  // "usual" way. See create()
  SolrCore createFromZk(String instanceDir, CoreDescriptor dcore, SolrResourceLoader loader) {
    try {
      SolrResourceLoader solrLoader = null;
      SolrConfig config = null;
      String zkConfigName = null;
      IndexSchema schema;
      String collection = dcore.getCloudDescriptor().getCollectionName();
      zkController.createCollectionZkNode(dcore.getCloudDescriptor());

      zkConfigName = zkController.getZkStateReader().readConfigName(collection);
      if (zkConfigName == null) {
        log.error("Could not find config name for collection:" + collection);
        throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR,
            "Could not find config name for collection:" + collection);
      }
      solrLoader = new ZkSolrResourceLoader(instanceDir, zkConfigName,
          loader.getClassLoader(), dcore.getSubstitutableProperties(), zkController);
      config = getSolrConfigFromZk(zkConfigName, dcore.getConfigName(),
          solrLoader);
      schema = IndexSchemaFactory.buildIndexSchema(dcore.getSchemaName(),
          config);
      return new SolrCore(dcore.getName(), null, config, schema, dcore);

    } catch (KeeperException e) {
      log.error("", e);
      throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e);
    } catch (InterruptedException e) {
      // Restore the interrupted status
      Thread.currentThread().interrupt();
      log.error("", e);
      throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e);
    }
  }

  public void registerInZk(final SolrCore core, boolean background) {
    Thread thread = new Thread() {
      @Override
      public void run() {
          try {
            zkController.register(core.getName(), core.getCoreDescriptor());
          } catch (InterruptedException e) {
            // Restore the interrupted status
            Thread.currentThread().interrupt();
            SolrException.log(log, "", e);
          } catch (Exception e) {
            try {
              zkController.publish(core.getCoreDescriptor(), ZkStateReader.DOWN);
            } catch (InterruptedException e1) {
              Thread.currentThread().interrupt();
              log.error("", e1);
            } catch (Exception e1) {
              log.error("", e1);
            }
            SolrException.log(log, "", e);
          }
        }

    };

    if (zkController != null) {
      if (background) {
        coreZkRegister.execute(thread);
      } else {
        thread.run();
      }
    }
  }

  public SolrConfig getSolrConfigFromZk(String zkConfigName, String solrConfigFileName,
      SolrResourceLoader resourceLoader) {
    SolrConfig cfg = null;
    try {
      byte[] config = zkController.getConfigFileData(zkConfigName,
          solrConfigFileName);
      InputSource is = new InputSource(new ByteArrayInputStream(config));
      is.setSystemId(SystemIdResolver
          .createSystemIdFromResourceName(solrConfigFileName));
      cfg = solrConfigFileName == null ? new SolrConfig(resourceLoader,
          SolrConfig.DEFAULT_CONF_FILE, is) : new SolrConfig(resourceLoader,
          solrConfigFileName, is);
    } catch (Exception e) {
      throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
          "getSolrConfigFromZK failed for " + zkConfigName + " "
              + solrConfigFileName, e);
    }
    return cfg;
  }

  public ZkController getZkController() {
    return zkController;
  }

  public void publishCoresAsDown(List<SolrCore> cores) {

    for (SolrCore core : cores) {
      try {
        zkController.publish(core.getCoreDescriptor(), ZkStateReader.DOWN);
      } catch (KeeperException e) {
        CoreContainer.log.error("", e);
      } catch (InterruptedException e) {
        CoreContainer.log.error("", e);
      }
    }
  }

  public void close() {

    try {
      if (zkController != null) {
        zkController.close();
      }
    } finally {
      try {
        if (zkServer != null) {
          zkServer.stop();
        }
      } finally {
        ExecutorUtil.shutdownNowAndAwaitTermination(coreZkRegister);
      }
    }

  }
}


text:
package de.m3y.prometheus.exporter.fsimage;

import de.m3y.hadoop.hdfs.hfsa.core.FsImageData;
import de.m3y.hadoop.hdfs.hfsa.core.FsVisitor;
import de.m3y.hadoop.hdfs.hfsa.util.FsUtil;
import io.prometheus.client.Histogram;
import io.prometheus.client.SimpleCollector;
import io.prometheus.client.Summary;
import org.apache.hadoop.fs.permission.PermissionStatus;
import org.apache.hadoop.hdfs.server.namenode.FsImageProto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.LongAdder;
import java.util.function.Function;
import java.util.regex.Pattern;

import static de.m3y.prometheus.exporter.fsimage.FsImageCollector.METRIC_PREFIX;
import static de.m3y.prometheus.exporter.fsimage.FsImageCollector.MetricFamilySamples;
import static de.m3y.prometheus.exporter.fsimage.FsImageUpdateHandler.FSIZE;
import static de.m3y.prometheus.exporter.fsimage.FsImageUpdateHandler.REPLICATION;

/**
 * Generates a report for a loaded FSImage.
 */
public class FsImageReporter {
    private static final Logger LOG = LoggerFactory.getLogger(FsImageReporter.class);

    interface MetricAdapter {
        void observe(long metricValue);

        long count();
    }

    static class HistogramMetricAdapter implements MetricAdapter {
        final Histogram.Child child;

        HistogramMetricAdapter(Histogram.Child child) {
            this.child = child;
        }

        @Override
        public void observe(long metricValue) {
            child.observe(metricValue);
        }

        @Override
        public long count() {
            return (long) sum(child.get().buckets);
        }

        private static double sum(double[] doubles) {
            double s = 0;
            for (double d : doubles) {
                s += d;
            }
            return s;
        }
    }

    static class SummaryMetricAdapter implements MetricAdapter {
        final Summary.Child child;

        SummaryMetricAdapter(Summary.Child child) {
            this.child = child;
        }

        @Override
        public void observe(long metricValue) {
            child.observe(metricValue);
        }

        @Override
        public long count() {
            return (long) child.get().count;
        }
    }

    abstract static class AbstractFileSystemStats {
        final LongAdder sumDirectories = new LongAdder();
        final LongAdder sumBlocks = new LongAdder();
        final LongAdder sumSymLinks = new LongAdder();
        final MetricAdapter fileSize;

        protected AbstractFileSystemStats(MetricAdapter fileSize) {
            this.fileSize = fileSize;
        }
    }

    static class OverallStats extends AbstractFileSystemStats {
        final Summary replication;

        OverallStats(MetricAdapter fileSize, Summary replication) {
            super(fileSize);
            this.replication = replication;
        }
        // No additional attributes, for now.
    }

    static class UserStats extends AbstractFileSystemStats {
        final String userName;
        final MetricAdapter replication;

        UserStats(String userName, MetricAdapter fileSize, MetricAdapter replication) {
            super(fileSize);
            this.userName = userName;
            this.replication = replication;
        }
    }

    static class GroupStats extends AbstractFileSystemStats {
        final String groupName;

        GroupStats(String groupName, MetricAdapter fileSize) {
            super(fileSize);
            this.groupName = groupName;
        }
    }

    static class PathStats extends AbstractFileSystemStats {
        final String path;

        PathStats(String path, MetricAdapter fileSize) {
            super(fileSize);
            this.path = path;
        }
    }

    /**
     * Contains collected statistics for an FSImage.
     */
    static class Report {
        volatile boolean error = false;

        // Overall stats
        final OverallStats overallStats;
        final SimpleCollector<?> overallFleSizeDistribution;
        final Summary overallReplication;
        // Group stats
        final Map<String, GroupStats> groupStats;
        final SimpleCollector<?> groupFileSizeDistribution;
        final Function<String, GroupStats> createGroupStats;
        // User stats
        final Map<String, UserStats> userStats;
        final SimpleCollector<?> userFileSizeDistribution;
        final Function<String, UserStats> createUserStat;
        final Summary userReplication;
        // Path stats
        final Map<String, PathStats> pathStats;
        final SimpleCollector<?> pathFileSizeDistribution;
        final Function<String, PathStats> createPathStat;
        // Path sets
        final Map<String, PathStats> pathSetStats;
        final SimpleCollector<?> pathSetFileSizeDistribution;
        final Function<String, PathStats> createPathSetStat;

        Report(Config config) {
            groupStats = new ConcurrentHashMap<>();
            userStats = new ConcurrentHashMap<>();
            pathStats = new ConcurrentHashMap<>();
            pathSetStats = new ConcurrentHashMap<>();

            double[] configuredBuckets = config.getFileSizeDistributionBucketsAsDoubles();

            // Overall
            Histogram overallHistogram = Histogram.build()
                    .name(METRIC_PREFIX + FSIZE)
                    .buckets(configuredBuckets)
                    .help("Overall file size distribution")
                    .create();
            overallFleSizeDistribution = overallHistogram;
            overallReplication = Summary.build()
                    .name(FsImageCollector.METRIC_PREFIX + REPLICATION)
                    .help("Overall file replication").create();
            overallStats = new OverallStats(new HistogramMetricAdapter(overallHistogram.labels()), overallReplication);

            // Group
            if (config.isSkipFileDistributionForGroupStats()) {
                Summary summary = Summary.build()
                        .name(FsImageUpdateHandler.METRIC_PREFIX_GROUP + FSIZE)
                        .labelNames(FsImageUpdateHandler.LABEL_GROUP_NAME)
                        .help("Per group file size and file count").create();
                createGroupStats = groupName -> new GroupStats(groupName,
                        new SummaryMetricAdapter(summary.labels(groupName)));
                groupFileSizeDistribution = summary;
            } else {
                Histogram histogram = Histogram.build()
                        .name(FsImageUpdateHandler.METRIC_PREFIX_GROUP + FSIZE)
                        .labelNames(FsImageUpdateHandler.LABEL_GROUP_NAME)
                        .buckets(configuredBuckets)
                        .help("Per group file size distribution.").create();
                createGroupStats = groupName -> new GroupStats(groupName,
                        new HistogramMetricAdapter(histogram.labels(groupName)));
                groupFileSizeDistribution = histogram;
            }

            // User
            userReplication = Summary.build()
                    .name(FsImageUpdateHandler.METRIC_PREFIX_USER + REPLICATION)
                    .labelNames(FsImageUpdateHandler.LABEL_USER_NAME)
                    .help("Per user file replication").create();
            if (config.isSkipFileDistributionForUserStats()) {
                Summary summary = Summary.build()
                        .name(FsImageUpdateHandler.METRIC_PREFIX_USER + FSIZE)
                        .labelNames(FsImageUpdateHandler.LABEL_USER_NAME)
                        .help("Per user file size and file count").create();
                createUserStat = userName -> new UserStats(userName,
                        new SummaryMetricAdapter(summary.labels(userName)),
                        new SummaryMetricAdapter(userReplication.labels(userName)));
                userFileSizeDistribution = summary;
            } else {
                Histogram histogram = Histogram.build()
                        .name(FsImageUpdateHandler.METRIC_PREFIX_USER + FSIZE)
                        .labelNames(FsImageUpdateHandler.LABEL_USER_NAME)
                        .buckets(configuredBuckets)
                        .help("Per user file size distribution").create();
                createUserStat = userName -> new UserStats(userName,
                        new HistogramMetricAdapter(histogram.labels(userName)),
                        new SummaryMetricAdapter(userReplication.labels(userName)));
                userFileSizeDistribution = histogram;
            }

            // Paths
            if (config.isSkipFileDistributionForPathStats()) {
                Summary summary = Summary.build()
                        .name(FsImageUpdateHandler.METRIC_PREFIX_PATH + FSIZE)
                        .labelNames(FsImageUpdateHandler.LABEL_PATH)
                        .help("Path specific file size and file count").create();
                createPathStat = path -> new PathStats(path, new SummaryMetricAdapter(summary.labels(path)));
                pathFileSizeDistribution = summary;
            } else {
                Histogram histogram = Histogram.build()
                        .name(FsImageUpdateHandler.METRIC_PREFIX_PATH + FSIZE)
                        .buckets(configuredBuckets)
                        .labelNames(FsImageUpdateHandler.LABEL_PATH)
                        .help("Path specific file size distribution").create();
                createPathStat = path -> new PathStats(path, new HistogramMetricAdapter(histogram.labels(path)));
                pathFileSizeDistribution = histogram;
            }

            // Path sets
            if (config.isSkipFileDistributionForPathSetStats()) {
                Summary summary = Summary.build()
                        .name(FsImageUpdateHandler.METRIC_PREFIX_PATH_SET + FSIZE)
                        .labelNames(FsImageUpdateHandler.LABEL_PATH_SET)
                        .help("Path set specific file size and file count").create();
                createPathSetStat = path -> new PathStats(path, new SummaryMetricAdapter(summary.labels(path)));
                pathSetFileSizeDistribution = summary;
            } else {
                Histogram histogram = Histogram.build()
                        .name(FsImageUpdateHandler.METRIC_PREFIX_PATH_SET + FSIZE)
                        .buckets(configuredBuckets)
                        .labelNames(FsImageUpdateHandler.LABEL_PATH_SET)
                        .help("Path set specific file size distribution").create();
                createPathSetStat = path -> new PathStats(path, new HistogramMetricAdapter(histogram.labels(path)));
                pathSetFileSizeDistribution = histogram;
            }
        }

        public void collect(List<MetricFamilySamples> mfs) {
            mfs.addAll(overallFleSizeDistribution.collect());
            mfs.addAll(overallReplication.collect());

            mfs.addAll(groupFileSizeDistribution.collect());

            mfs.addAll(userFileSizeDistribution.collect());
            mfs.addAll(userReplication.collect());

            if (hasPathStats()) {
                mfs.addAll(pathFileSizeDistribution.collect());
            }
            if (hasPathSetStats()) {
                mfs.addAll(pathSetFileSizeDistribution.collect());
            }
        }

        boolean hasPathStats() {
            return null != pathStats && !pathStats.isEmpty();
        }

        boolean hasPathSetStats() {
            return null != pathSetStats && !pathSetStats.isEmpty();
        }

    }

    private FsImageReporter() {
        // Nothing
    }

    static Report computeStatsReport(final FsImageData fsImageData, Config config) throws IOException {
        Report report = new Report(config);
        final OverallStats overallStats = report.overallStats;

        long t = System.currentTimeMillis();
        new FsVisitor.Builder().parallel().visit(fsImageData, new FsVisitor() {
            @Override
            public void onFile(FsImageProto.INodeSection.INode inode, String path) {
                FsImageProto.INodeSection.INodeFile f = inode.getFile();
                PermissionStatus p = fsImageData.getPermissionStatus(f.getPermission());

                final long fileSize = FsUtil.getFileSize(f);
                final long fileBlocks = f.getBlocksCount();
                overallStats.sumBlocks.add(fileBlocks);
                overallStats.fileSize.observe(fileSize);
                overallStats.replication.observe(f.getReplication());

                // Group stats
                final String groupName = p.getGroupName();
                final GroupStats groupStat = report.groupStats.computeIfAbsent(groupName, report.createGroupStats);
                groupStat.sumBlocks.add(fileBlocks);
                groupStat.fileSize.observe(fileSize);

                // User stats
                final String userName = p.getUserName();
                UserStats userStat = report.userStats.computeIfAbsent(userName, report.createUserStat);
                userStat.sumBlocks.add(fileBlocks);
                userStat.fileSize.observe(fileSize);
                userStat.replication.observe(f.getReplication());
            }

            @Override
            public void onDirectory(FsImageProto.INodeSection.INode inode, String path) {
                FsImageProto.INodeSection.INodeDirectory d = inode.getDirectory();
                PermissionStatus p = fsImageData.getPermissionStatus(d.getPermission());
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Visiting directory {}",
                            path + ("/".equals(path) ? "" : "/") + inode.getName().toStringUtf8());
                }

                // Group stats
                final String groupName = p.getGroupName();
                final GroupStats groupStat = report.groupStats.computeIfAbsent(groupName, report.createGroupStats);
                groupStat.sumDirectories.increment();

                // User stats
                final String userName = p.getUserName();
                final UserStats userStat = report.userStats.computeIfAbsent(userName, report.createUserStat);
                userStat.sumDirectories.increment();

                overallStats.sumDirectories.increment();
            }

            @Override
            public void onSymLink(FsImageProto.INodeSection.INode inode, String path) {
                FsImageProto.INodeSection.INodeSymlink d = inode.getSymlink();
                PermissionStatus p = fsImageData.getPermissionStatus(d.getPermission());

                // Group stats
                final String groupName = p.getGroupName();
                final GroupStats groupStat = report.groupStats.computeIfAbsent(groupName, report.createGroupStats);
                groupStat.sumSymLinks.increment();

                // User stats
                final String userName = p.getUserName();
                final UserStats userStat = report.userStats.computeIfAbsent(userName, report.createUserStat);
                userStat.sumSymLinks.increment();

                overallStats.sumSymLinks.increment();
            }
        });
        LOG.info("Finished computing overall/group/user stats in {}ms", System.currentTimeMillis() - t);
        if (config.hasPaths()) {
            computePathStats(fsImageData, config, report);
        }
        if (config.hasPathSets()) {
            computePathSetStatsParallel(fsImageData, config, report);
        }

        return report;
    }

    private static void computePathStats(FsImageData fsImageData, Config config, Report report) throws IOException {
        Set<String> expandedPaths = expandPaths(fsImageData, config.getPaths());
        LOG.info("Expanded paths {} for path stats {}", expandedPaths, config.getPaths());
        long s = System.currentTimeMillis();
        expandedPaths.parallelStream().forEach(p -> {
            try {
                long t = System.currentTimeMillis();
                final PathStats pathStats = report.pathStats.computeIfAbsent(p, report.createPathStat);
                new FsVisitor.Builder().visit(fsImageData, new PathStatVisitor(pathStats), p);
                // Subtract start dir, as only child dirs count
                pathStats.sumDirectories.decrement();
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Finished path stat for {} with {} total number of files in {}ms",
                            p, pathStats.fileSize.count(), System.currentTimeMillis() - t);
                }
            } catch (IOException e) {
                LOG.error("Can not traverse " + p, e);
                report.error = true;
            }
        });
        LOG.info("Finished {} path stats in {}ms", report.pathStats.size(), System.currentTimeMillis() - s);
    }

    private static void computePathSetStatsParallel(FsImageData fsImageData, Config config, Report report) {
        long s = System.currentTimeMillis();
        config.getPathSets().entrySet().parallelStream().forEach(entry ->
                computePathSetStats(fsImageData, entry, report)
        );
        LOG.info("Finished {} path set stats in {}ms", report.pathSetStats.size(), System.currentTimeMillis() - s);
    }

    private static void computePathSetStats(FsImageData fsImageData, Map.Entry<String, List<String>> entry, Report report) {
        final FsVisitor.Builder builder = new FsVisitor.Builder();
        try {
            Set<String> expandedPaths = expandPaths(fsImageData, entry.getValue());
            LOG.info("Expanded paths {} for path set stats {}", expandedPaths, entry.getKey());
            long t = System.currentTimeMillis();
            final PathStats pathStats = report.pathSetStats.computeIfAbsent(entry.getKey(), report.createPathSetStat);
            final PathStatVisitor visitor = new PathStatVisitor(pathStats);
            for (String path : expandedPaths) {
                builder.visit(fsImageData, visitor, path);
            }
            // Subtract number of start dirs, as only child dirs count
            pathStats.sumDirectories.add(-expandedPaths.size());
            if (LOG.isDebugEnabled()) {
                LOG.debug("Finished path set stat for {} with {} total number of files in {}ms",
                        entry.getKey(), pathStats.fileSize.count(), System.currentTimeMillis() - t);
            }
        } catch (IOException e) {
            LOG.error("Can not traverse path set " + entry.getKey() + " using paths " + entry.getValue(), e);
            report.error = true;
        }
    }

    static Set<String> expandPaths(FsImageData fsImageData, Collection<String> paths) throws IOException {
        Set<String> expandedPaths = new HashSet<>();
        for (String path : paths) {
            // If path does not exist, match child directories
            if (!hasDirectory(fsImageData, path)) {
                addMatchingPaths(fsImageData, expandedPaths, path);
            } else { // Existing directory
                expandedPaths.add(path);
            }
        }

        return expandedPaths;
    }

    private static void addMatchingPaths(FsImageData fsImageData, Set<String> expandedPaths, String path)
            throws IOException {
        // 1. Find base path
        //    Example: path= "/foo/bar/.*" -> "/foo/bar/"
        final String[] parts = path.split("/");
        String basePath = "/";
        int i = 1;
        while (i < parts.length) {
            String part = parts[i];
            if (hasDirectory(fsImageData, basePath + part)) {
                i++;
                basePath += part + '/';
            } else break;
        }
        LOG.info("Base path for {} is {}", path, basePath);

        // 2. Expand paths below base path
        Set<String> paths = Collections.singleton(basePath);
        for (int j=i; j < parts.length; j++) {
            String part = parts[j];
            Pattern pattern = Pattern.compile(part);
            Set<String> matchedPaths = new HashSet<>();
            for (String currentPath : paths) {
                try {
                    List<String> childPaths = fsImageData.getChildDirectories(currentPath,
                            iNode -> pattern.matcher(iNode.getName().toStringUtf8()).matches());
                    matchedPaths.addAll(childPaths);
                } catch (FileNotFoundException | NoSuchElementException ex) {
                    LOG.warn("Skipping configured, non-existing path {} for metric computations." +
                            " Check your configuration path/pathSet entries!", currentPath);
                }
            }
            paths = matchedPaths;
        }
        expandedPaths.addAll(paths);
    }

    /**
     * TODO: Replace once FSImageLoader contains this functionality
     */
    private static boolean hasDirectory(FsImageData fsImageData, String path) throws IOException {
        if ("/".equals(path)) { // Root always exists
            return true;
        }
        try {
            return null != fsImageData.getINodeFromPath(path);
        } catch (FileNotFoundException | IllegalArgumentException ex) {
            return false;
        }
    }

    static class PathStatVisitor implements FsVisitor {
        private final PathStats pathStats;

        PathStatVisitor(PathStats pathStats) {
            this.pathStats = pathStats;
        }

        @Override
        public void onFile(FsImageProto.INodeSection.INode inode, String path) {
            FsImageProto.INodeSection.INodeFile f = inode.getFile();
            pathStats.sumBlocks.add(f.getBlocksCount());
            final long fileSize = FsUtil.getFileSize(f);
            pathStats.fileSize.observe(fileSize);
        }

        @Override
        public void onDirectory(FsImageProto.INodeSection.INode inode, String path) {
            pathStats.sumDirectories.increment();
        }

        @Override
        public void onSymLink(FsImageProto.INodeSection.INode inode, String path) {
            pathStats.sumSymLinks.increment();
        }
    }

}