text:
FROM gewo/interactive
MAINTAINER Gebhard Wöstemeyer <g.woestemeyer@gmail.com>

ENV PATH /usr/local/rvm/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

RUN apt-get update && apt-get -y install curl git && apt-get clean
# RUN echo 'source /usr/local/rvm/scripts/rvm' >> /etc/bash.bashrc
RUN \
  echo 'source /etc/profile.d/rvm.sh' >> /etc/shell_env &&\
  echo "gem: --no-ri --no-rdoc" > ~/.gemrc &&\
  echo "export rvm_trust_rvmrcs_flag=1" >> ~/.rvmrc &&\
  echo "export rvm_autoupdate_flag=2" >> ~/.rvmrc

RUN \
  gpg --keyserver hkp://keys.gnupg.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3 &&\
  curl -L https://get.rvm.io | bash -s stable && rvm requirements

RUN echo 'bundler' >> /usr/local/rvm/gemsets/global.gems

CMD ["/bin/bash"]


text:
package ui.newrecord;

import ui.CheckUtils;
import ui.tablemodel.ClientTableModel;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class NewDBClientRecord extends NewDBRecordFrame {

    public NewDBClientRecord(int amount, final ClientTableModel tableModel) {
        super(amount);
        setLabelTextFieldName(0, "Название компании");
        setLabelTextFieldName(1, "ОКПО");
        setLabelTextFieldName(2, "Адрес");
        setLabelTextFieldName(3, "Телефон");
        yesButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (checkNewDBRecord()) {
                    tableModel.addRow(getTextFieldValue(0), Integer.parseInt(getTextFieldValue(1)), getTextFieldValue(2), getTextFieldValue(3));
                    dispose();
                }
            }
        });
    }

    @Override
    public boolean checkNewDBRecord() {
        Boolean flag = true;
        if (!CheckUtils.checkLength(getTextFieldValue(1), 8)) {
            JOptionPane.showMessageDialog(this, "ОКПО должен быть равен 8 символам");
            flag = false;
        }
        if (!CheckUtils.isInteger(getTextFieldValue(1))) {
            JOptionPane.showMessageDialog(this, "ОКПО не является числом");
            flag = false;
        }
        return flag;
    }
}

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) 2017 Ubisoft Entertainment
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using Sharpmake.Generators.FastBuild;
using Sharpmake.Generators.VisualStudio;

namespace Sharpmake
{
    public abstract class BaseMicrosoftPlatform
        : BasePlatform
        , Project.Configuration.IConfigurationTasks
        , IMicrosoftPlatformBff
        , IPlatformVcxproj
    {
        #region IPlatformDescriptor implementation
        public override bool IsMicrosoftPlatform => true;
        public override bool IsUsingClang => false;
        public override bool HasDotNetSupport => true;
        public override bool HasSharedLibrarySupport => true;
        #endregion

        #region Project.Configuration.IConfigurationTasks implementation
        public void SetupLibraryPaths(Project.Configuration configuration, DependencySetting dependencySetting, Project.Configuration dependency)
        {
            DefaultPlatform.SetupLibraryPaths(configuration, dependencySetting, dependency);
        }

        public string GetDefaultOutputExtension(Project.Configuration.OutputType outputType)
        {
            switch (outputType)
            {
                case Project.Configuration.OutputType.Exe:
                case Project.Configuration.OutputType.DotNetConsoleApp:
                case Project.Configuration.OutputType.DotNetWindowsApp:
                    return "exe";
                case Project.Configuration.OutputType.Lib:
                    return "lib";
                case Project.Configuration.OutputType.Dll:
                case Project.Configuration.OutputType.DotNetClassLibrary:
                    return "dll";
                case Project.Configuration.OutputType.None:
                    return string.Empty;
                default:
                    return outputType.ToString().ToLower();
            }
        }
        #endregion

        #region IMicrosoftPlatformBff implementation
        public virtual bool SupportsResourceFiles => false;
        #endregion

        #region IPlatformVcxproj implementation
        public override string ExecutableFileExtension => "exe";
        public override string SharedLibraryFileExtension => "dll";
        public override string ProgramDatabaseFileExtension => "pdb";
        public override string StaticLibraryFileExtension => "lib";
        #endregion
    }
}


text:
import os
import socket
import shutil

from logger import logger
from client import JudgeClient
from language import languages
from compiler import compile_
from result import result
from settings import judger_workspace

class JudgeInstanceRunner(object):

    def run(self, token, submission_id, language_code, code, time_limit, memory_limit, test_case_id,
            spj, spj_language, spj_code, spj_version):
        language = languages[language_code]
        host_name = socket.gethostname()
        judge_base_path = os.path.join(judger_workspace, "run", submission_id)

        if not token or token != os.environ.get("rpc_token"):
            if token:
                logger.info("Invalid token: " + token)
            return {"code": 2, "data": {"error": "Invalid token", "server": host_name}}

        try:
            os.mkdir(judge_base_path)
            os.chmod(judge_base_path, 0777)

            # 将代码写入文件
            src_path = os.path.join(judge_base_path, language["src_name"])
            f = open(src_path, "w")
            f.write(code.encode("utf8"))
            f.close()
        except Exception as e:
            shutil.rmtree(judge_base_path, ignore_errors=True)
            return {"code": 2, "data": {"error": str(e), "server": host_name}}

        # 编译
        try:
            exe_path = compile_(language_item=language, src_path=src_path,
                                exe_path=judge_base_path, judge_base_path=judge_base_path, compile_spj=False)
        except Exception as e:
            shutil.rmtree(judge_base_path, ignore_errors=True)
            return {"code": 1, "data": {"error": str(e), "server": host_name}}

        test_case_dir = os.path.join(judger_workspace, "test_case", test_case_id)

        # SPJ相关
        if spj:
            spj_path = os.path.join(test_case_dir, "spj-" + spj_version)
            if "spj-" + spj_version not in os.listdir(test_case_dir):
                spj_language_item = languages[spj_language]
                spj_code_path = os.path.join(test_case_dir, "spj-" + spj_language_item["src_name"])

                f = open(spj_code_path, "w")
                f.write(spj_code.encode("utf8"))
                f.close()

                try:
                    compile_(language_item=languages[spj_language], src_path=spj_code_path,
                             exe_path=spj_path,
                             judge_base_path=judge_base_path, compile_spj=True)
                except Exception as e:
                    return {"code": 2, "data": {"error": "SPJ Compile error: " + str(e), "server": host_name}}
        else:
            spj_path = None

        # 运行
        try:
            client = JudgeClient(language_code=language_code,
                                 exe_path=exe_path,
                                 max_cpu_time=int(time_limit),
                                 max_memory=int(memory_limit) * 1024 * 1024,
                                 test_case_dir=test_case_dir,
                                 judge_base_path=judge_base_path, spj_path=spj_path)
            judge_result = {"result": result["accepted"], "info": client.run(),
                            "accepted_answer_time": None, "server": host_name}

            for item in judge_result["info"]:
                if item["result"] != 0:
                    judge_result["result"] = item["result"]
                    break
            else:
                l = sorted(judge_result["info"], key=lambda k: k["cpu_time"])
                judge_result["accepted_answer_time"] = l[-1]["cpu_time"]
            return {"code": 0, "data": judge_result}
        except Exception as e:
            return {"code": 2, "data": {"error": str(e), "server": host_name}}
        finally:
            shutil.rmtree(judge_base_path, ignore_errors=True)


text:
#ifndef AQUATUX_H
#define AQUATUX_H

/*
* AquaTux reads a settings file and determines how to implement the following interfaces:
*   AttitudeInput:  Where to get readings for yaw, pitch, roll and depth (ie submarine IMU+depth sensor, simulator)
*   ImageInput:     Where to get a stream of input images (ie video, webcam, simulator)
*   Operation:      What algorithm (manual or autonomous) to control the output, given the inputs
*   ActuatorOutput: Where to output movement commands (ie change the simulator or give motor commands to the submarine)
*/

#include "AttitudeInput.h"
#include "ImageInput.h"
#include "Operation.h"
#include "ActuatorOutput.h"

class AquaTux {
  public:
    AquaTux(const char *);
    void work();
    ~AquaTux();
  private:
    AttitudeInput *m_attitude_input;
    ImageInput *m_image_input;
    Operation *m_operation;
    ActuatorOutput *m_actuator_output;
};

#endif


text:
# BunnyJS v 0.14.42 (Beta)

[Website](https://bunnyjs.com) * [![NPM downloads/month](https://img.shields.io/npm/dm/bunnyjs.svg?style=flat-square)](https://www.npmjs.org/package/bunnyjs) [![NPM version](https://img.shields.io/npm/v/bunnyjs.svg?style=flat-square)](https://www.npmjs.org/package/bunnyjs) * [Gitter chat](https://gitter.im/bunny-js/Lobby) * [Contribute to Docs](https://github.com/bunnyjs/docs) * [Assets Builder](https://github.com/Mevrael/assets-builder)

## ES6 browser framework

### "Powerful like React, simple like jQuery"

**BunnyJS** is a modern **Vanilla JS** and ES6 library and next-generation front-end framework, package of small stand-alone components without dependencies.

* No dependencies - can be used in any project anywhere anytime
* 0 learning curve - you can start right now, just plain JavaScript with simple architecture easy to maintain and extend
* Designed in mind to build modern, complicated, real world business apps
* Faster, simpler, enjoyable than any frontend framework
* Large set of ready components, custom UI elements and utils
* LTS

For help & ideas - [DM me on Twitter](https://twitter.com/Mevrael)

## Browser support

IE9+, last 2 versions of Chrome, Firefox, Safari, Android 4.4+, iOS 9+

## Installation

1. Install via `npm install bunnyjs --save`
2. [Rollup.js](http://rollupjs.org) with babel and npm plugins is recommended for transpiling and bundling.
3. Or you can just use [Assets Builder](https://github.com/Mevrael/assets-builder) which will automatically build your future JS and CSS with 1 command.
4. Or just include into HTML already transpiled and minified JS from `dists` folder or any [CDN](https://unpkg.com/bunnyjs/dist).
5. Probably some polyfills for IE might be required depending on Component.

```html
<script src="https://unpkg.com/bunnyjs/dist/..."></script>
```

## Extending BunnyJS and Vanilla JS objects

Recommended way to use any of BunnyJS component is - *"do not change the code you do not own"*. That means do not modify native prototypes or any 3rd party code.

1. Create some `base` or `core` folder in your app,
2. Extend BunnyJS objects with `Object.assign()` or `Object.create`
3. Now everywhere in your project import custom file and not directly BunnyJS's file.

```javascript

import { Component as BunnyComponent } from 'bunnyjs/src/...';

export const Component = Object.assign({}, BunnyComponent, {

    init(arg) {
        // do whatever you want
        console.log(arg);

        // call default (parent)
        return BunnyComponent.init(arg);
    }

});

```

## Components

1. Form processing with native API, AJAX submit, file upload, image preview, data binding and more
1. Native HTML5 form validation ([View example](https://bunnyjs.com/examples/form-validation/))
1. Facebook-like Messenger
1. Custom selects, spinners,
1. DOM utils, ready(), events
1. Libraries for Date, URL, File, Image
1. Ajax, APIs
1. Routing
1. Template engine
1. DataTable and Pagination ([View example](https://bunnyjs.com/examples/datatable/))
1. Calendar and DatePicker
1. Autocomplete, Dropdown
1. Element, positions, coordinates, smooth scrolling
1. Dependency Injection, Inversion of control

## Architecture

1. Separation of concerns, loose coupling, modularity
1. Functional programming
1. ES6 import/exports, Promises
1. Native Browser API, polyfills were needed
1. Object literal notation, no prototypes, "classes" , "new"
1. Object composition over inheritance
1. Dependency injection

## Contributors wanted

* Become a contributor of a fast growing open source project
* Share your ideas to the world
* Help yourself and millions of developers around the world solving JavaScript fatigue and modern overendineered problem
* Help building a tool which will provide a best user experience, performance, security, durability and load time for billions of the Internet users with smart usage of Computer's and Mobile device's resources

## Local development, examples and dists generation

* Make sure to install `npm install assets-builder` first.
* Examples are located in the `examples` folder. File `index.html` can be opened in the browser to view examples. Examples are generated with `npm build`
* To generate dists - `npm build dist -p`

## Experimental components based on DOMObserver (Mutation Observer)

Learn how to build [Vanilla JavaScript components on Medium.](https://medium.com/bunnyllc/vanilla-js-components-8d20c58b69f4#.qpwcm9mbn)

`src/DOMObserver` may be used to listen for DOM events like when new tag (component) was inserted into DOM or removed. It is based on latest Mutation Observer API (IE11+) and allows to automatically init components inserted into DOM later.

BunnyJS provides an experimental base abstract `src/Component` which may be used to create custom components:

```html
<script src="https://unpkg.com/bunnyjs/dist/component.min.js"></script>
```

Below is [Clock](https://jsfiddle.net/o01mvsyn/) example from [Inferno](https://infernojs.org/). As you can see you can do everything in Vanilla JS with less code, size and it works natively.

```javascript

const MyClock = Object.assign({}, Component, {

  tagName: 'clock',

  attributes: {
    date: new Date,
  },

  addEvents(clock) {
    clock._timer = setInterval(() => {
      clock.date = new Date;
    }, 1000);
  },

  uninit(clock) {
    clearInterval(clock._timer);
  },

  __date(clock, newVal) {
    clock.textContent = newVal.toLocaleTimeString();
  }

});

MyClock.register();
```

Now just `document.body.appendChild(document.createElement('clock'))` and it works.

To update the whole "state" of the component you may just use Vanilla JS `Object.assign(component, {stateObject})`.

For example, you have a simple <btn> clicker. By clicking on it btn.counter is increased. You can update counter with `btn.counter = 1` or `Object.assign(document.getElementsByTagName('btn')[0], {counter: 1})`;

You may also set default counter value with `<btn counter="6">`

For more examples look in `examples/component` folder.

---

© [Mev-Rael](https://twitter.com/Mevrael)

[MIT License](https://github.com/mevrael/bunny/blob/master/LICENSE)


text:
package com.xiaogua.better.bean;

import java.util.Date;

import org.springframework.format.annotation.DateTimeFormat;

import com.xiaogua.better.datetime.DateTimeCode;

public class Parent_Normal_Bean {
	private String parentName;
	private int parentAge;
	@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
	private Date parentDate;

	public Parent_Normal_Bean() {
		super();
	}

	public Parent_Normal_Bean(String parentName, int parentAge, Date parentDate) {
		super();
		this.parentName = parentName;
		this.parentAge = parentAge;
		this.parentDate = parentDate;
	}

	public String getParentName() {
		return parentName;
	}

	public void setParentName(String parentName) {
		this.parentName = parentName;
	}

	public int getParentAge() {
		return parentAge;
	}

	public void setParentAge(int parentAge) {
		this.parentAge = parentAge;
	}

	public Date getParentDate() {
		return parentDate;
	}

	public void setParentDate(Date parentDate) {
		this.parentDate = parentDate;
	}

	public String toString() {
		String infoStr = "Parent_Normal_Bean [parentName=" + parentName + ", parentAge=" + parentAge + ", parentDate=";
		if (parentDate == null) {
			infoStr += "null]";
		} else {
			try {
				infoStr += DateTimeCode.getStrFromDate(parentDate, DateTimeCode.FULL_DATETIME) + "]";
			} catch (Exception e) {
				infoStr += parentDate + "]";
			}
		}
		return infoStr;
	}

}


text: docker build -t katsupplybot .


text:
<?php
namespace ApplicationTest\EventBus\Queue;

use ApplicationTest\EventBus\DummyEvent;
use Application\Domain\EventBus\Queue\AmqpQueue;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PHPUnit_Framework_TestCase;

class AmqpQueueTest extends PHPUnit_Framework_TestCase
{

    /** @var AMQPStreamConnection */
    protected $producerConnection;

    /** @var AMQPStreamConnection */
    protected $consumerConnection;

    /** @var AmqpQueue */
    protected $consumer;

    /** @var AmqpQueue */
    protected $producer;

    private $host = 'zebra.rmq.cloudamqp.com';

    private $post = 5672;

    private $user = 'roblgcxy';

    private $pass = 'dfnRxpAByZYpmxCTA-g_r_u1zqkXoViP';

    private $vhost = 'roblgcxy';

    public function setUp()
    {
        $this->consumerConnection = new AMQPStreamConnection($this->host, $this->post, $this->user, $this->pass, $this->vhost);
        $this->producerConnection = new AMQPStreamConnection($this->host, $this->post, $this->user, $this->pass, $this->vhost);

        $this->producer = new AmqpQueue($this->producerConnection, 'testAdapterQueueNMT');
        $this->consumer = new AmqpQueue($this->consumerConnection, 'testAdapterQueueNMT');
    }

    public function testAdapterQueue()
    {
        for ($i = 1; $i <= 10; ++ $i) {
            $event = new DummyEvent();
            $this->producer->push($event);
        }
        // $this->assertEquals($event, $this->consumer->pop());
    }

    public function testName()
    {
        $this->assertEquals('testAdapterQueueNMT', $this->consumer->name());
    }
}


text:
<?php
	if(isset($_SESSION[USER_RETURN_MSG])) {
		$msg = $_SESSION[USER_RETURN_MSG]['Msg'];
	}
?>

<?php echo @$msg; ?>

<?php
if(isset($_SESSION['ModalBox']))
{
?>

	<?php echo $_SESSION['ModalBox']; ?>

<?php
}
?>

<?php if( isset($_SESSION['remember_me']) ){ ?>

<?php unset($_SESSION['remember_me']); } ?>


text:
<?php

/* WebProfilerBundle:Profiler:toolbar_js.html.twig */
class __TwigTemplate_4060873fc3784b76f36635ceacc0e8ed extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = false;

        $this->blocks = array(
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        // line 1
        echo "
env, $this->getContext($context, "token"), "html", null, true);
        echo "\" class=\"sf-toolbar\" style=\"display: none\">

";
        // line 2
        $this->env->loadTemplate("WebProfilerBundle:Profiler:base_js.html.twig")->display($context);
        // line 3
        echo "
";
    }

    public function getTemplateName()
    {
        return "WebProfilerBundle:Profiler:toolbar_js.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  42 => 13,  33 => 7,  29 => 6,  24 => 3,  22 => 2,  17 => 1,);
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<databaseChangeLog
        xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-2.0.xsd">

    <preConditions>
        <or>
            <runningAs username="liquibase" />
            <runningAs username="sa" />
        </or>
    </preConditions>

    <changeSet id="1" author="nvoxland">
        <createTable tableName="relpathinclude1">
            <column name="id" type="int"/>
        </createTable>
    </changeSet>

    <includeAll path="changelogs/common/includerelative/includeAll"/>
</databaseChangeLog>


text:
package xyz.openmodloader.test.mods;

import net.minecraft.entity.monster.EntityCreeper;
import net.minecraft.entity.passive.EntityHorse;
import net.minecraft.entity.passive.EntityPig;
import net.minecraft.entity.player.EntityPlayer;
import xyz.openmodloader.OpenModLoader;
import xyz.openmodloader.event.impl.EntityEvent;
import xyz.openmodloader.test.TestMod;

public class TestEntityEvent implements TestMod {

    @Override
    public void onInitialize() {

        OpenModLoader.getEventBus().register(EntityEvent.Constructing.class, this::onEntityConstruct);
        OpenModLoader.getEventBus().register(EntityEvent.Join.class, this::onEntityJoinWorld);
        OpenModLoader.getEventBus().register(EntityEvent.ChangeDimension.class, this::onChangeDimension);
        OpenModLoader.getEventBus().register(EntityEvent.Mount.class, this::onMount);
        OpenModLoader.getEventBus().register(EntityEvent.Dismount.class, this::onDismount);
        OpenModLoader.getEventBus().register(EntityEvent.LightningStruck.class, this::onLightningStrike);
    }

    private void onLightningStrike(EntityEvent.LightningStruck event) {
        if (event.getEntity() instanceof EntityCreeper) {
            event.setCanceled(true);
        }
    }

    private void onEntityConstruct(EntityEvent.Constructing event) {
        if (event.getEntity() instanceof EntityPlayer) {
            OpenModLoader.getLogger().info("A player was constructed.");
        }
    }

    private void onEntityJoinWorld(EntityEvent.Join event) {
        if (event.getEntity() instanceof EntityPlayer) {
            OpenModLoader.getLogger().info(String.format("A player joined the world on side %s.", event.getWorld().isRemote ? "client" : "server"));
        }
        if (event.getEntity() instanceof EntityPig) {
            event.setCanceled(true);
        }
    }

    private void onChangeDimension(EntityEvent.ChangeDimension event) {
        OpenModLoader.getLogger().info("Entity: %s is travelling from dimension %d to %d", event.getEntity(), event.getPreviousDimension(), event.getNewDimension());
        if (event.getNewDimension() == -1) {
            event.setNewDimension(1);
        }
    }

    private void onMount(EntityEvent.Mount event) {
        if (event.getRiding() instanceof EntityPig) {
            event.setCanceled(true);
        }
    }

    private void onDismount(EntityEvent.Dismount event) {
        if (event.getRiding() instanceof EntityHorse) {
            event.setCanceled(true);
        }
    }
}


text:
package org.jivesoftware.openfire.session;

import java.net.UnknownHostException;
import java.security.cert.Certificate;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.net.ssl.SSLSession;

import org.dom4j.Element;
import org.jivesoftware.openfire.Connection;
import org.jivesoftware.openfire.SessionManager;
import org.jivesoftware.openfire.StreamID;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.auth.UnauthorizedException;
import org.jivesoftware.openfire.interceptor.InterceptorManager;
import org.jivesoftware.openfire.interceptor.PacketRejectedException;
import org.jivesoftware.openfire.net.SocketConnection;
import org.jivesoftware.openfire.net.TLSStreamHandler;
import org.jivesoftware.openfire.streammanagement.StreamManager;
import org.jivesoftware.util.LocaleUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xmpp.packet.*;

/**
 * The session represents a connection between the server and a client (c2s) or
 * another server (s2s) as well as a connection with a component. Authentication and
 * user accounts are associated with c2s connections while s2s has an optional authentication
 * association but no single user user.

 *
 * Obtain object managers from the session in order to access server resources.
 *
 * @author Gaston Dombiak
 */
public abstract class LocalSession implements Session {

	private static final Logger Log = LoggerFactory.getLogger(LocalSession.class);

    /**
     * The utf-8 charset for decoding and encoding Jabber packet streams.
     */
    protected static String CHARSET = "UTF-8";

    /**
     * The Address this session is authenticated as.
     */
    private JID address;

    /**
     * The stream id for this session (random and unique).
     */
    private StreamID streamID;

    /**
     * The current session status.
     */
    protected int status = STATUS_CONNECTED;

    /**
     * The connection that this session represents.
     */
    protected final Connection conn;

    protected SessionManager sessionManager;

    private String serverName;

    private long startDate = System.currentTimeMillis();

    private long lastActiveDate;
    private long clientPacketCount = 0;
    private long serverPacketCount = 0;

    /**
	 * Session temporary data. All data stored in this Map disapear when session
	 * finishes.
	 */
	private final Map<String, Object> sessionData = new HashMap<>();

    /**
     * XEP-0198 Stream Manager
     */
    protected final StreamManager streamManager;

    private final Locale language;

    /**
     * Creates a session with an underlying connection and permission protection.
     *
     * @param serverName domain of the XMPP server where the new session belongs.
     * @param connection The connection we are proxying.
     * @param streamID unique identifier for this session.
     * @param language The language to use for this session.
     */
    public LocalSession(String serverName, Connection connection, StreamID streamID, Locale language) {
        if (connection == null) {
            throw new IllegalArgumentException("connection must not be null");
        }
        conn = connection;
        this.streamID = streamID;
        this.serverName = serverName;
        String id = streamID.getID();
        this.address = new JID(null, serverName, id, true);
        this.sessionManager = SessionManager.getInstance();
        this.streamManager = new StreamManager(conn);
        this.language = language;
    }

    /**
      * Obtain the address of the user. The address is used by services like the core
      * server packet router to determine if a packet should be sent to the handler.
      * Handlers that are working on behalf of the server should use the generic server
      * hostname address (e.g. server.com).
      *
      * @return the address of the packet handler.
      */
    @Override
    public JID getAddress() {
        return address;
    }

    /**
     * Sets the new address of this session. The address is used by services like the core
     * server packet router to determine if a packet should be sent to the handler.
     * Handlers that are working on behalf of the server should use the generic server
     * hostname address (e.g. server.com).
     *
     * @param address the new address of this session.
     */
    public void setAddress(JID address){
        this.address = address;
    }

    /**
     * Returns the connection associated with this Session.
     *
     * @return The connection for this session
     */
    public Connection getConnection() {
        return conn;
    }

    /**
     * Obtain the current status of this session.
     *
     * @return The status code for this session
     */
    @Override
    public int getStatus() {
        return status;
    }

    /**
     * Set the new status of this session. Setting a status may trigger
     * certain events to occur (setting a closed status will close this
     * session).
     *
     * @param status The new status code for this session
     */
    public void setStatus(int status) {
        this.status = status;
    }

    /**
     * Obtain the stream ID associated with this sesison. Stream ID's are generated by the server
     * and should be unique and random.
     *
     * @return This session's assigned stream ID
     */
    @Override
    public StreamID getStreamID() {
        return streamID;
    }

    /**
     * Obtain the name of the server this session belongs to.
     *
     * @return the server name.
     */
    @Override
    public String getServerName() {
        return serverName;
    }

    /**
     * Obtain the date the session was created.
     *
     * @return the session's creation date.
     */
    @Override
    public Date getCreationDate() {
        return new Date(startDate);
    }

    /**
     * Obtain the time the session last had activity.
     *
     * @return The last time the session received activity.
     */
    @Override
    public Date getLastActiveDate() {
        return new Date(lastActiveDate);
    }

    /**
     * Increments the number of packets sent from the client to the server.
     */
    public void incrementClientPacketCount() {
        clientPacketCount++;
        lastActiveDate = System.currentTimeMillis();
        streamManager.incrementServerProcessedStanzas();
    }

    /**
     * Increments the number of packets sent from the server to the client.
     */
    public void incrementServerPacketCount() {
        serverPacketCount++;
        lastActiveDate = System.currentTimeMillis();
    }

    /**
     * Obtain the number of packets sent from the client to the server.
     *
     * @return The number of packets sent from the client to the server.
     */
    @Override
    public long getNumClientPackets() {
        return clientPacketCount;
    }

    /**
     * Obtain the number of packets sent from the server to the client.
     *
     * @return The number of packets sent from the server to the client.
     */
    @Override
    public long getNumServerPackets() {
        return serverPacketCount;
    }

    /**
	 * Saves given session data. Data are saved to temporary storage only and are accessible during
	 * this session life only and only from this session instance.
	 *
	 * @param key a String value of stored data key ID.
	 * @param value a Object value of data stored in session.
	 * @see #getSessionData(String)
	 */
	public void setSessionData(String key, Object value) {
        synchronized (sessionData) {
            sessionData.put(key, value);
        }
    }

	/**
	 * Retrieves session data. This method gives access to temporary session data only. You can
	 * retrieve earlier saved data giving key ID to receive needed value. Please see
	 * {@link #setSessionData(String, Object)}  description for more details.
	 *
	 * @param key a String value of stored data ID.
	 * @return a Object value of data for given key.
	 * @see #setSessionData(String, Object)
	 */
	public Object getSessionData(String key) {
        synchronized (sessionData) {
    		return sessionData.get(key);
        }
    }

    /**
     * Removes session data. Please see {@link #setSessionData(String, Object)} description
     * for more details.
     *
     * @param key a String value of stored data ID.
     * @see #setSessionData(String, Object)
     */
    public void removeSessionData(String key) {
        synchronized (sessionData) {
            sessionData.remove(key);
        }
    }

    /**
     * Get XEP-0198 Stream manager for session
     * @return The StreamManager for the session.
     */
    public StreamManager getStreamManager() {
    	return streamManager;
    }

    @Override
    public void process(Packet packet) {
        // Check that the requested packet can be processed
        if (canProcess(packet)) {
            // Perform the actual processing of the packet. This usually implies sending
            // the packet to the entity
            try {
                // Invoke the interceptors before we send the packet
                InterceptorManager.getInstance().invokeInterceptors(packet, this, false, false);
                deliver(packet);
                // Invoke the interceptors after we have sent the packet
                InterceptorManager.getInstance().invokeInterceptors(packet, this, false, true);
            }
            catch (PacketRejectedException e) {
                // An interceptor rejected the packet so do nothing
            }
            catch (Exception e) {
                Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
            }
        } else {
            // http://xmpp.org/extensions/xep-0016.html#protocol-error
            if (packet instanceof Message) {
                // For message stanzas, the server SHOULD return an error, which SHOULD be <service-unavailable/>.
                Message message = (Message) packet;
                Message result = message.createCopy();
                result.setTo(message.getFrom());
                result.setError(PacketError.Condition.service_unavailable);
                XMPPServer.getInstance().getRoutingTable().routePacket(message.getFrom(), result, true);
            } else if (packet instanceof IQ) {
                // For IQ stanzas of type "get" or "set", the server MUST return an error, which SHOULD be <service-unavailable/>.
                // IQ stanzas of other types MUST be silently dropped by the server.
                IQ iq = (IQ) packet;
                if (iq.getType() == IQ.Type.get || iq.getType() == IQ.Type.set) {
                    IQ result = IQ.createResultIQ(iq);
                    result.setError(PacketError.Condition.service_unavailable);
                    XMPPServer.getInstance().getRoutingTable().routePacket(iq.getFrom(), result, true);
                }
            }
        }
    }

    /**
     * Returns true if the specified packet can be delivered to the entity. Subclasses will use different
     * criterias to determine of processing is allowed or not. For instance, client sessions will use
     * privacy lists while outgoing server sessions will always allow this action.
     *
     * @param packet the packet to analyze if it must be blocked.
     * @return true if the specified packet must be blocked.
     */
    abstract boolean canProcess(Packet packet);

    abstract void deliver(Packet packet) throws UnauthorizedException;

    @Override
    public void deliverRawText(String text) {
        conn.deliverRawText(text);
    }

    /**
     * Returns a text with the available stream features. Each subclass may return different
     * values depending whether the session has been authenticated or not.
     *
     * @return a text with the available stream features or <tt>null</tt> to add nothing.
     */
    public abstract String getAvailableStreamFeatures();

    @Override
    public void close() {
        conn.close();
    }

    @Override
    public boolean validate() {
        return conn.validate();
    }

    @Override
    public boolean isSecure() {
        return conn.isSecure();
    }

    @Override
    public Certificate[] getPeerCertificates() {
        return conn.getPeerCertificates();
    }

    @Override
    public boolean isClosed() {
        return conn.isClosed();
    }

    @Override
    public String getHostAddress() throws UnknownHostException {
        return conn.getHostAddress();
    }

    @Override
    public String getHostName() throws UnknownHostException {
        return conn.getHostName();
    }

    @Override
	public String toString() {
        return super.toString() + " status: " + status + " address: " + address + " id: " + streamID;
    }

    protected static int[] decodeVersion(String version) {
        int[] answer = new int[] {0 , 0};
        String [] versionString = version.split("\\.");
        answer[0] = Integer.parseInt(versionString[0]);
        answer[1] = Integer.parseInt(versionString[1]);
        return answer;
    }

    /**
     * Returns true if the other peer of this session presented a self-signed certificate. When
     * using self-signed certificate for server-2-server sessions then SASL EXTERNAL will not be
     * used and instead server-dialback will be preferred for vcerifying the identify of the remote
     * server.
     *
     * @return true if the other peer of this session presented a self-signed certificate.
     */
    public boolean isUsingSelfSignedCertificate() {
        return conn.isUsingSelfSignedCertificate();
    }

    /**
     * Returns a String representing the Cipher Suite Name, or "NONE".
     * @return String
     */
    @Override
    public String getCipherSuiteName() {
        SocketConnection s = (SocketConnection)getConnection();
        if (s != null) {
            TLSStreamHandler t = s.getTLSStreamHandler();
            if (t != null) {
                SSLSession ssl = t.getSSLSession();
                if (ssl != null) {
                    return ssl.getCipherSuite();
                }
            }
        }
        return "NONE";
    }

    @Override
    public final Locale getLanguage() {
        return language;
    }
}


text:
namespace google {
namespace cloud {
namespace dataproc_internal {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN

std::shared_ptr<WorkflowTemplateServiceStub>
CreateDefaultWorkflowTemplateServiceStub(google::cloud::CompletionQueue cq,
                                         Options const& options);

GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
}  // namespace dataproc_internal
}  // namespace cloud
}  // namespace google

#endif  // GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_DATAPROC_INTERNAL_WORKFLOW_TEMPLATE_STUB_FACTORY_H


text:
<?php defined('BX_DOL') or die('hack attempt');

bx_import('BxDolModuleDb');

class BxQuoteOfDayDb extends BxBaseModGeneralDb
{
    function __construct(&$oConfig)
    {
        parent::__construct($oConfig);
    }

    public function getHiddenItemsCount()
    {
        $CNF = &$this->_oConfig->CNF;
        $sSql = $this->prepare("SELECT COUNT(*) FROM " . $CNF['TABLE_ENTRIES'] . " WHERE " . $CNF['FIELD_STATUS'] . "!='active'");

        return $this->getOne($sSql);
    }

    public function getData()
    {
        $CNF = &$this->_oConfig->CNF;
        return  $this->getColumn("SELECT `" . $CNF['FIELD_TEXT'] . "` FROM " . $CNF['TABLE_ENTRIES'] . " WHERE " . $CNF['FIELD_STATUS'] . "='active'");
    }

}

/** @} */


text:
'use strict';

var CptSite;

$(PreInitializePage);

function PreInitializePage() {
  $("#tabs").tabs();
  displayQueryStringParameters();
  CptSite = CPT.SharePoint.Web.DataAccess;
  CptSite.getSiteProperties().then(onSitePropertiesReceived, onError);
}

function InitializePage() {
  CptSite.getContextInfo().then(onContextInfoReceived, onError);
  CptSite.getLists().then(onListsReceived, onError);
  CptSite.getLibraries().then(onLibrariesReceived, onError);
  CptSite.getFileHierarchy().then(onFileHierarchyReceived, onError);
  CptSite.getSiteUsers().then(onSiteUsersReceived, onError);
  CptSite.getSiteGroups().then(onSiteGroupsReceived, onError);
}

function displayQueryStringParameters() {
  var querystring = document.URL.split("?")[1];
  if (querystring) {

    var table = $("<table>", { "class": "table_inside_tab" });

    table.append($("<thead>")
                    .append($("<tr>")
                      .append($("<td>").text("Parameter"))
                      .append($("<td>").text("Value"))));

    var params = querystring.split("&");
    for (var index = 0; (index < params.length) ; index++) {

      var current = params[index].split("=");

      table.append($("<tr>")
                     .append($("<td>").text(current[0]))
                     .append($("<td>").text(decodeURIComponent(current[1]))));

    }

    $("#startPageContainer")
      .empty()
      .append(table)
  }
}

function onSitePropertiesReceived(data) {
  var siteProperties = data.d;

  var table = $("<table>", { "class": "table_inside_tab" });

  table.append($("<thead>")
                  .append($("<tr>")
                    .append($("<td>").text("Property"))
                    .append($("<td>").text("Value"))));

  table.append($("<tr>")
                 .append($("<td>").text("Id"))
                 .append($("<td>").text(siteProperties.Id)));

  table.append($("<tr>")
              .append($("<td>").text("Title"))
              .append($("<td>").text(siteProperties.Title)));

  if (siteProperties.Description) {
    table.append($("<tr>")
                  .append($("<td>").text("Description"))
                  .append($("<td>").text(siteProperties.Description)));
  }

  table.append($("<tr>")
                  .append($("<td>").text("Language"))
                  .append($("<td>").text(siteProperties.Language)));

  table.append($("<tr>")
                  .append($("<td>").text("Created"))
                  .append($("<td>").text(siteProperties.Created)));

  table.append($("<tr>")
                  .append($("<td>").text("LastItemModifiedDate"))
                  .append($("<td>").text(siteProperties.LastItemModifiedDate)));

  table.append($("<tr>")
                  .append($("<td>").text("Url"))
                  .append($("<td>").text(siteProperties.Url)));

  table.append($("<tr>")
                  .append($("<td>").text("ServerRelativeUrl"))
                  .append($("<td>").text(siteProperties.ServerRelativeUrl)));

  table.append($("<tr>")
                  .append($("<td>").text("WebTemplate"))
                  .append($("<td>").text(siteProperties.WebTemplate)));

  table.append($("<tr>")
                  .append($("<td>").text("Configuration"))
                  .append($("<td>").text(siteProperties.Configuration)));

  table.append($("<tr>")
                  .append($("<td>").text("MasterUrl"))
                  .append($("<td>").text(siteProperties.MasterUrl)));

  table.append($("<tr>")
                  .append($("<td>").text("CustomMasterUrl"))
                  .append($("<td>").text(siteProperties.CustomMasterUrl)));

  table.append($("<tr>")
                  .append($("<td>").text("EnableMinimalDownload"))
                  .append($("<td>").text(siteProperties.EnableMinimalDownload)));

  table.append($("<tr>")
                  .append($("<td>").text("TreeViewEnabled"))
                  .append($("<td>").text(siteProperties.TreeViewEnabled)));

  table.append($("<tr>")
                  .append($("<td>").text("QuickLaunchEnabled"))
                  .append($("<td>").text(siteProperties.QuickLaunchEnabled)));

  table.append($("<tr>")
                  .append($("<td>").text("RecycleBinEnabled"))
                  .append($("<td>").text(siteProperties.RecycleBinEnabled)));

  table.append($("<tr>")
                  .append($("<td>").text("SyndicationEnabled"))
                  .append($("<td>").text(siteProperties.SyndicationEnabled)));

  table.append($("<tr>")
                  .append($("<td>").text("AllowRssFeeds"))
                  .append($("<td>").text(siteProperties.AllowRssFeeds)));

  table.append($("<tr>")
                  .append($("<td>").text("UIVersion"))
                  .append($("<td>").text(siteProperties.UIVersion)));

  table.append($("<tr>")
                  .append($("<td>").text("UIVersionConfigurationEnabled"))
                  .append($("<td>").text(siteProperties.UIVersionConfigurationEnabled)));

  $("#sitePropertiesContainer")
    .empty()
    .append(table);

  InitializePage();

}

function onContextInfoReceived(data) {
  var contextInfo = data.d.GetContextWebInformation;

  var table = $("<table>", { "class": "table_inside_tab" });

  table.append($("<thead>")
                  .append($("<tr>")
                    .append($("<td>").text("Property"))
                    .append($("<td>").text("Value"))));

  table.append($("<tr>")
                 .append($("<td>").text("WebFullUrl"))
                 .append($("<td>").text(contextInfo.WebFullUrl)));

  table.append($("<tr>")
                 .append($("<td>").text("SiteFullUrl"))
                 .append($("<td>").text(contextInfo.SiteFullUrl)));

  table.append($("<tr>")
                 .append($("<td>").text("FormDigestValue"))
                 .append($("<td>").text(contextInfo.FormDigestValue)));

  table.append($("<tr>")
                 .append($("<td>").text("FormDigestTimeoutSeconds"))
                 .append($("<td>").text(contextInfo.FormDigestTimeoutSeconds)));

  table.append($("<tr>")
                 .append($("<td>").text("SupportedSchemaVersions"))
                 .append($("<td>").text(contextInfo.SupportedSchemaVersions.results)));

  $("#contextInfoContainer")
    .empty()
    .append(table);

}

function onListsReceived(data) {

  var lists = data.d.results;
  var listsAccordian = $("<div>");
  for (var index = 0; index < lists.length; index++) {

    listsAccordian.append($("<h3>").text(lists[index].Title));

    var tableContainer = $("<div>");
    var table = $("<table>", { "class": "table_inside_accordian" });

    table.append($("<tr>")
      .append($("<td>").text("Created"))
      .append($("<td>").text(lists[index].Created)));

    table.append($("<tr>")
            .append($("<td>").text("Id"))
            .append($("<td>").text(lists[index].Id)));

    table.append($("<tr>")
                .append($("<td>").text("Title"))
                .append($("<td>").text(lists[index].Title)));

    table.append($("<tr>")
        .append($("<td>").text("BaseTemplate"))
        .append($("<td>").text(lists[index].BaseTemplate)));

    table.append($("<tr>")
        .append($("<td>").text("EnableAttachments"))
        .append($("<td>").text(lists[index].EnableAttachments)));

    table.append($("<tr>")
        .append($("<td>").text("EnableVersioning"))
        .append($("<td>").text(lists[index].EnableVersioning)));

    table.append($("<tr>")
        .append($("<td>").text("ItemCount"))
        .append($("<td>").text(lists[index].ItemCount)));

    tableContainer.append(table);
    listsAccordian.append(tableContainer);
  }

  listsAccordian.accordion({ collapsible: true, active: false, autoHeight: true });

  $("#listsContainer")
    .empty()
    .append(listsAccordian);

};

function onLibrariesReceived(data) {
  var libraries = data.d.results;
  var librariesAccordian = $("<div>");
  for (var index = 0; index < libraries.length; index++) {

    librariesAccordian.append($("<h4>").text(libraries[index].Title));

    var tableContainer = $("<div>");

    var table = $("<table>", { "class": "table_inside_accordian" });

    table.append($("<tr>")
                .append($("<td>").text("Title"))
                .append($("<td>").text(libraries[index].Title)));

    table.append($("<tr>")
            .append($("<td>").text("Id"))
            .append($("<td>").text(libraries[index].Id)));

    table.append($("<tr>")
        .append($("<td>").text("BaseTemplate"))
        .append($("<td>").text(libraries[index].BaseTemplate)));

    table.append($("<tr>")
        .append($("<td>").text("BaseType"))
        .append($("<td>").text(libraries[index].BaseType)));

    table.append($("<tr>")
        .append($("<td>").text("Created"))
        .append($("<td>").text(libraries[index].Created)));

    if (libraries[index].DocumentTemplateUrl) {
      table.append($("<tr>")
          .append($("<td>").text("EnableAttachments"))
          .append($("<td>").text(libraries[index].EnableAttachments)));
    }

    table.append($("<tr>")
        .append($("<td>").text("EnableVersioning"))
        .append($("<td>").text(libraries[index].EnableVersioning)));

    table.append($("<tr>")
        .append($("<td>").text("ItemCount"))
        .append($("<td>").text(libraries[index].ItemCount)));

    tableContainer.append(table);
    librariesAccordian.append($("<div>").append(tableContainer));
  }

  librariesAccordian.accordion({ collapsible: true, active: false, autoHeight: false });

  $("#librariesContainer")
    .empty()
    .append(librariesAccordian);

}

function onFileHierarchyReceived(data) {
  var rootFolder = data.d;
  var serverRelativeUrl = rootFolder.ServerRelativeUrl;

  var fileHierarchyContainer = $("#fileHierarchyContainer");
  var fileHierarchyList = $("<ul>", { "class": "filetree" });

  var folders = rootFolder.Folders.results;
  if (folders) { folders.sort(SortByName); }
  for (var index = 0; index < folders.length; index++) {
    var folder = folders[index];
    var listItem = $("<li>", { "class": "closed" });
    listItem.append($("<span>", { "class": "folder" }).text(folder.Name));
    fileHierarchyList.append(listItem);
    var childFolders = folder.Folders.results;
    var childFiles = folder.Files.results;
    LoadChildFolders(listItem, childFolders, childFiles);
  }

  var files = rootFolder.Files.results;
  if (files) { files.sort(SortByName); }
  for (var index = 0; index < files.length; index++) {
    var listItem = $("<li>");
    listItem.append($("<span>", { "class": "file" }).text(files[index].Name));
    fileHierarchyList.append(listItem);
  }

  fileHierarchyList.treeview();
  fileHierarchyContainer.append(fileHierarchyList);

}

function LoadChildFolders(parentListItem, folders, files) {

  var foldersExist = ((typeof folders != 'undefined') && (typeof folders.length != 'undefined'));
  var filesExist = ((typeof files != 'undefined') && (typeof files.length != 'undefined'));

  if (foldersExist || filesExist) {

    var list = $("<ul>");

    if (foldersExist) {
      folders.sort(SortByName);
      for (var index = 0; index < folders.length; index++) {
        var folder = folders[index];
        var listItem = $("<li>", { "class": "closed" });
        listItem.append($("<span>", { "class": "folder" }).text(folder.Name));
        list.append(listItem);
        var childFolders = folder.Folders.results;
        var childFiles = folder.Files.results;
        LoadChildFolders(listItem, childFolders, childFiles);
      }
    }

    if (filesExist) {
      files.sort(SortByName);
      for (var index = 0; index < files.length; index++) {
        var file = files[index];
        var listItem = $("<li>", {"Title": file.Name });
        listItem.append($("<span>", { "class": "file" }).text(file.Name));
        list.append(listItem);
      }
    }

    parentListItem.append(list);
  }
}

function onSiteUsersReceived(data) {

  var siteUsers = data.d.results;
  siteUsers.sort(SortById);

  var panel = $("#siteUsers");
  panel.append($("<h2>").text("Site Users"));

  var table = $("<table>", { "class": "table_inside_tab" });
  table.append($("<thead>")
                  .append($("<tr>")
                    .append($("<td>").text("ID"))
                    .append($("<td>").text("Title"))
                    .append($("<td>").text("LoginName"))
                    .append($("<td>").text("PrincipalType"))
                    .append($("<td>").text("IsSiteAdmin"))));

  for (var index = 0; index < siteUsers.length; index++) {
    var siteUser = siteUsers[index];
    table.append($("<tr>")
                .append($("<td>").text(siteUser.Id))
                .append($("<td>").text(siteUser.Title))
                .append($("<td>").text(siteUser.LoginName))
                .append($("<td>").text(siteUser.PrincipalType))
                .append($("<td>").text(siteUser.IsSiteAdmin)));
  }
  panel.append(table);
}

function onSiteGroupsReceived(data) {

  var siteGroups = data.d.results;
  siteGroups.sort(SortById);

  var panel = $("#siteGroups");
  panel.append($("<h2>").text("Site Groups"));

  var table = $("<table>", { "class": "table_inside_tab" });
  table.append($("<thead>")
                  .append($("<tr>")
                    .append($("<td>").text("ID"))
                    .append($("<td>").text("Title"))
                    .append($("<td>").text("Users"))));

  for (var index = 0; index < siteGroups.length; index++) {

    var siteGroup = siteGroups[index];

    var siteGroupUsers = siteGroup.Users.results;
    var siteGroupUserNames = "(empty)";

    var usersExist = ((typeof siteGroupUsers != 'undefined') && (typeof siteGroupUsers.length != 'undefined') && (siteGroupUsers.length > 0));
    if (usersExist) {
      siteGroupUserNames = "";
      for (var innerIndex = 0; innerIndex < siteGroupUsers.length; innerIndex++) {
        var siteGroupUser = siteGroupUsers[innerIndex];
        siteGroupUserNames += siteGroupUser.Title + ": ";
      }
    }

    table.append($("<tr>")
                .append($("<td>").text(siteGroup.Id))
                .append($("<td>").text(siteGroup.Title))
                .append($("<td>").text(siteGroupUserNames)));

  }
  panel.append(table);
}

function SortByName(a, b) {
  var aName = a.Name.toLowerCase();
  var bName = b.Name.toLowerCase();
  return ((aName < bName) ? -1 : ((aName > bName) ? 1 : 0));
}

function SortById(a, b) {
  return ((a.Id < b.Id) ? -1 : ((a.Id > b.Id) ? 1 : 0));
}

function onError(error) {
  alert(JSON.stringify(error));
}


text:
package org.apereo.cas.config;

import com.hazelcast.config.Config;
import com.hazelcast.config.MapConfig;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import org.apereo.cas.configuration.CasConfigurationProperties;
import org.apereo.cas.configuration.model.support.hazelcast.HazelcastTicketRegistryProperties;
import org.apereo.cas.configuration.support.Beans;
import org.apereo.cas.hz.HazelcastConfigurationFactory;
import org.apereo.cas.ticket.TicketCatalog;
import org.apereo.cas.ticket.TicketDefinition;
import org.apereo.cas.ticket.registry.HazelcastTicketRegistry;
import org.apereo.cas.ticket.registry.NoOpTicketRegistryCleaner;
import org.apereo.cas.ticket.registry.TicketRegistry;
import org.apereo.cas.ticket.registry.TicketRegistryCleaner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * Spring's Java configuration component for {@code HazelcastInstance} that is consumed and used by
 * {@link HazelcastTicketRegistry}.
 * <p>
 * This configuration class has the smarts to choose the configuration source for the {@link HazelcastInstance}
 * that it produces by either loading the native hazelcast XML config file from a resource location
 * or it creates the {@link HazelcastInstance} programmatically
 * with a handful properties and their defaults (if not set) that it exposes to CAS deployers.
 *
 * @author Misagh Moayyed
 * @author Dmitriy Kopylenko
 * @since 4.2.0
 */
@Configuration("hazelcastTicketRegistryConfiguration")
@EnableConfigurationProperties(CasConfigurationProperties.class)
public class HazelcastTicketRegistryConfiguration {
    private static final Logger LOGGER = LoggerFactory.getLogger(HazelcastTicketRegistryConfiguration.class);

    @Autowired
    private CasConfigurationProperties casProperties;

    @Autowired
    @Bean
    public TicketRegistry ticketRegistry(@Qualifier("ticketCatalog") final TicketCatalog ticketCatalog) {
        final HazelcastTicketRegistryProperties hz = casProperties.getTicket().getRegistry().getHazelcast();
        final HazelcastTicketRegistry r = new HazelcastTicketRegistry(hazelcast(ticketCatalog),
                ticketCatalog,
                hz.getPageSize());
        r.setCipherExecutor(Beans.newTicketRegistryCipherExecutor(hz.getCrypto(), "hazelcast"));
        return r;
    }

    @Bean
    public TicketRegistryCleaner ticketRegistryCleaner() {
        return NoOpTicketRegistryCleaner.getInstance();
    }

    @Autowired
    @Bean
    public HazelcastInstance hazelcast(@Qualifier("ticketCatalog") final TicketCatalog ticketCatalog) {
        return Hazelcast.newHazelcastInstance(getConfig(ticketCatalog));
    }

    private Config getConfig(final TicketCatalog ticketCatalog) {
        final HazelcastTicketRegistryProperties hz = casProperties.getTicket().getRegistry().getHazelcast();
        final Map<String, MapConfig> configs = buildHazelcastMapConfigurations(ticketCatalog);
        final HazelcastConfigurationFactory factory = new HazelcastConfigurationFactory();
        return factory.build(hz, configs);
    }

    private Map<String, MapConfig> buildHazelcastMapConfigurations(final TicketCatalog ticketCatalog) {
        final Map<String, MapConfig> mapConfigs = new HashMap<>();

        final HazelcastTicketRegistryProperties hz = casProperties.getTicket().getRegistry().getHazelcast();
        final HazelcastConfigurationFactory factory = new HazelcastConfigurationFactory();

        final Collection<TicketDefinition> definitions = ticketCatalog.findAll();
        definitions.forEach(t -> {
            final MapConfig mapConfig = factory.buildMapConfig(hz, t.getProperties().getStorageName(), t.getProperties().getStorageTimeout());
            LOGGER.debug("Created Hazelcast map configuration for [{}]", t);
            mapConfigs.put(t.getProperties().getStorageName(), mapConfig);
        });
        return mapConfigs;
    }
}


text:
package com.wtfrak.nixon.parser.expressions;

public enum ExpressionType {
	TASK, LIST, STRING, NAME, NUMBER, COMMAND
}


text:
package com.intellij.java.codeInspection;

import com.intellij.JavaTestUtil;
import com.intellij.codeInspection.varScopeCanBeNarrowed.ParameterCanBeLocalInspection;
import com.intellij.testFramework.InspectionTestCase;

public class ParameterCanBeLocalTest extends InspectionTestCase {
  @Override
  protected String getTestDataPath() {
    return JavaTestUtil.getJavaTestDataPath() + "/inspection";
  }

  private void doTest() {
    doTest("parameterCanBeLocal/" + getTestName(true), new ParameterCanBeLocalInspection());
  }

  public void testSimple () { doTest(); }
  public void testIf () { doTest(); }
  public void testFor () { doTest(); }
  public void testReadOnly () { doTest(); }
}


text:
using ElasticPS.Util;
using System.Net.Http;
using System;
using System.Management.Automation;

namespace ElasticPS
{
    [Cmdlet(VerbsCommon.Get, "EsIndex")]
    public class GetIndexCmdlet : PSCmdlet
    {
        [Parameter(Mandatory = false, Position = 0)]
        public string Name { get; set; } = string.Empty;

        [Parameter(Mandatory = true, Position = 1)]
        public string Uri { get; set; }

        protected override void BeginProcessing()
        {
            if (!Uri.EndsWith("/"))
                Uri += "/";

            var request = new EsRequest(HttpMethod.Get, Uri, Name);

            var response = request.Send();
            WriteObject(response);
        }
    }
}


text:
layout: post
title: Static Factory Methods in Kotlin
date: 2021-07-15 17:10:00 +0800
categories: Kotlin
tags: design-pattern
published: false
---

* content
{:toc}

## sequence vs list

```kotlin
fun main() {
    val list = listOf<Int>(1, 2, 3, 4)
    list.filter {
        println("filter1 list $it")
        true
    }.filter {
        println("filter2 list $it")
        true
    }.take(2).filter {
        println("filter3 list $it")
        true
    }.forEach(::println)

    list.asSequence().filter {
        println("filter1 sequence $it")
        true
    }.filter {
        println("filter2 sequence $it")
        true
    }.take(2).filter {
        println("filter3 sequence $it")
        true
    }.forEach(::println)
}
```

### 惰性计算

Lazy Evaluation

### 计算顺序

### 中间操作、终端操作

If the sequence operation returns another sequence, which is produced lazily, it's called intermediate, and otherwise the operation is terminal.

* sorted、sortedBy、sortedWith
* take

### constrainOnce

### sequence 的四种构造方法

1; From elements

sequenceOf

2; From an Iterable

listOf().asSequence()

3; From a function

generateSequence()

4; From chunks

sequence()
yield()
yieldAll()

## yield

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.sequences/-sequence-scope/yield.html

```kotlin
fun main() {
    val fibonacci = sequence {
        var a = 1
        var b = 1
        // this sequence is infinite
        while (true) {
            b += a.apply { a = b }
            // this is a suspend function call
            yield(a)
        }
    }
    fibonacci.take(10).forEach(::println)
}
```

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.sequences/
https://kotlinlang.org/docs/sequences.html#from-chunks
<!-- https://zhuanlan.zhihu.com/p/52248891 -->
<!-- https://juejin.cn/post/6844903667947012110 -->
<!-- https://juejin.cn/post/6844903616072040455 -->
<!-- https://juejin.cn/post/6844903622409453576 -->
<!-- https://stackoverflow.com/a/55130592/7368406 -->
https://www.jianshu.com/p/c5cda7314fe1


text:
layout: post
title: 测试
description: "测试用"
category:
tags: ["测试"]
---

<button onclick="ins()" id="install-button">Add to Chrome</button>


text:
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="daniel.stadtgeschichten.activity.LogActivity">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1" >
        <TableLayout
            android:id="@+id/table"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:stretchColumns="*">
            <TableRow
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
                <TextView
                    android:text="@string/latitude"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="@dimen/log_table_padding" />
                <TextView
                    android:text="@string/longitude"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="@dimen/log_table_padding" />
                <TextView
                    android:text="@string/accuracy"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="@dimen/log_table_padding" />
            </TableRow>
        </TableLayout>
    </ScrollView>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:id="@+id/toggleLogging"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/start"
            android:onClick="toggleLogging"/>
        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/reset"
            android:onClick="reset" />
        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/export"
            android:onClick="exportData" />
    </LinearLayout>

</LinearLayout>


text:
package com.jd.living.database;

import android.util.Log;

import com.jd.living.model.Listing;
import com.jd.living.model.ormlite.SearchHistory;

import org.androidannotations.annotations.AfterInject;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.EBean;

import java.util.ArrayList;
import java.util.List;

@EBean(scope = EBean.Scope.Singleton)
public class DatabaseHelper implements SearchDatabase.SearchListener, FavoriteDatabase.FavoriteListener {

    public enum DatabaseState {
        FAVORITE,
        SEARCH
    }

    @Bean
    protected SearchDatabase searchDatabase;
    @Bean
    protected FavoriteDatabase favoriteDatabase;

    public interface DatabaseListener {
        void onUpdate(List<Listing> result);
    }

    public interface FavoriteDatabaseListener extends DatabaseListener {
    }

    public interface SearchDatabaseListener extends DatabaseListener {
        void onFavoriteUpdated();

        void onSearchStarted();
    }

    private List<FavoriteDatabaseListener> favoriteDatabaseListeners = new ArrayList<>();
    private List<SearchDatabaseListener> searchDatabaseListeners = new ArrayList<>();

    private List<Listing> searchResult = new ArrayList<>();
    private List<Listing> favoriteResult = new ArrayList<>();

    @AfterInject
    public void init() {
        searchDatabase.setListingsListeners(this);
        favoriteDatabase.setFavoriteListener(this);
    }

    public void addDatabaseListener(DatabaseListener listener) {
        if (listener instanceof FavoriteDatabaseListener) {
            favoriteDatabaseListeners.add((FavoriteDatabaseListener) listener);
            listener.onUpdate(favoriteResult);
        }
        if (listener instanceof SearchDatabaseListener) {
            searchDatabaseListeners.add((SearchDatabaseListener) listener);
            if (searchResult.isEmpty()) {
                searchDatabase.launchListingsSearch();
            } else {
                listener.onUpdate(searchResult);
            }
        }
    }

    public void removeDatabaseListener(DatabaseListener listener) {
        if (listener instanceof FavoriteDatabaseListener) {
            favoriteDatabaseListeners.remove(listener);
        }
        if (listener instanceof SearchDatabaseListener) {
            searchDatabaseListeners.remove(listener);
        }
    }

    public void setCurrentListIndex(int i, DatabaseState state) {
        switch (state) {
            case SEARCH:
                searchDatabase.setCurrentListIndex(i);
                break;
            case FAVORITE:
                favoriteDatabase.setCurrentListIndex(i);
                break;
        }
    }

    public void setCurrentId(int i, DatabaseState state) {
        switch (state) {
            case SEARCH:
                searchDatabase.setCurrentId(i);
                break;
            case FAVORITE:
                favoriteDatabase.setCurrentId(i);
                break;
        }
    }

    public Listing getCurrentListing(DatabaseState state) {
        switch (state) {
            case SEARCH:
                return searchDatabase.getCurrentListing();
            case FAVORITE:
                return favoriteDatabase.getCurrentListing();
        }
        return null;
    }

    public Listing getListingBasedOnLocation(int objectIndex, DatabaseState state) {
        switch (state) {
            case SEARCH:
                return searchDatabase.getListingBasedOnLocation(objectIndex);
            case FAVORITE:
                return favoriteDatabase.getListingBasedOnLocation(objectIndex);
        }
        return new Listing();
    }

    public int getListIndex(int booliId, DatabaseState state) {
        switch (state) {
            case SEARCH:
                return searchDatabase.getListIndex(booliId);
            case FAVORITE:
                return favoriteDatabase.getListIndex(booliId);
        }
        return -1;
    }

    public Listing getListing(int booliId, DatabaseState state) {
        switch (state) {
            case SEARCH:
                return searchDatabase.getListing(booliId);
            case FAVORITE:
                return favoriteDatabase.getListing(booliId);
        }
        return null;
    }

    public List<Listing> getResult(DatabaseState state) {
        switch (state) {
            case SEARCH:
                return searchResult;
            case FAVORITE:
                return favoriteResult;
        }
        return new ArrayList<>();
    }

    public void launchSearch() {
        searchDatabase.launchListingsSearch();
    }

    public void launchSearch(SearchHistory searchHistory) {
        searchDatabase.launchListingsSearch(searchHistory);
    }

    @Override
    public void onUpdateFavorites() {
        favoriteResult = favoriteDatabase.getResult();
        onUpdate(DatabaseState.FAVORITE);
    }

    @Override
    public void onUpdateSearch() {
        searchResult = searchDatabase.getResult();
        onUpdate(DatabaseState.SEARCH);
    }

    @Override
    public void onSearchStarted() {
        for (SearchDatabaseListener listener : searchDatabaseListeners) {
            listener.onSearchStarted();
        }
    }

    public FavoriteDatabase getFavoriteDatabase() {
        return favoriteDatabase;
    }

    public SearchDatabase getSearchDatabase() {
        return searchDatabase;
    }

    synchronized private void onUpdate(DatabaseState state) {

        switch (state) {
            case FAVORITE:
                for (FavoriteDatabaseListener listener : favoriteDatabaseListeners) {
                    listener.onUpdate(favoriteResult);
                }

                for (SearchDatabaseListener listener : searchDatabaseListeners) {
                    listener.onFavoriteUpdated();
                }

                break;
            case SEARCH:
                List<SearchDatabaseListener> b = new ArrayList<>(searchDatabaseListeners);
                for (DatabaseListener listener : b) {
                    listener.onUpdate(searchResult);
                }

                break;
            default:
                break;
        }
    }
}


text:
@implementation UITextView (AllowMultiTouches)

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return YES;
}

- (BOOL)canBecomeFirstResponder {
    if (self.editable) {
        return self.editable;
    } else {
        return YES;
    }
}

@end

@implementation ItemViewController

@synthesize jotTextView = _jotTextView;
@synthesize item = _item;

#pragma mark -
#pragma mark View Lifecycle Management

- (void)loadView {
    CGRect frame = [[UIScreen mainScreen] bounds];
    self.view = [[UIView alloc] initWithFrame:frame];
    self.view.backgroundColor = [UIColor whiteColor];

    self.jotTextView = [[UITextView alloc] initWithFrame:frame];
    self.jotTextView.delegate = self;
    self.jotTextView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    self.jotTextView.font = [UIFont fontWithName:@"Palatino" size:20.0];
    self.jotTextView.contentInset = UIEdgeInsetsMake(0, 0, 20, 0);

    [self.view addSubview:self.jotTextView];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.centered = YES;
    [self.jotTextView addKeyboardPanningWithActionHandler:^(CGRect keyboardFrameInView) {
        if (_jotTextView.editable) {
            CGRect newFrame = _jotTextView.frame;
            newFrame.size.height = keyboardFrameInView.origin.y - _jotTextView.contentOffset.y;
            _jotTextView.frame = newFrame;
        }
    }];

    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(changeGesture:)];
    [self.jotTextView addGestureRecognizer:panGesture];

    JotItemStore *defaultStore = [JotItemStore defaultStore];
    [self setItem:[defaultStore getCurrentItem]];

    [defaultStore addObserver:self forKeyPath:@"currentIndex" options:0 context:nil];

    // Immediately show keyboard
    [self.jotTextView becomeFirstResponder];
}

- (void)viewDidUnload {
    [super viewDidUnload];
    self.jotTextView = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context
{

    if ([keyPath isEqualToString:@"currentIndex"]) {
        JotItemStore *defaultStore = (JotItemStore *)object;
        [self setItem:[defaultStore getCurrentItem]];

    }
}

#pragma mark -
#pragma mark Modify Item

- (void)setItem:(JotItem *)item {
    _item = item;
    self.jotTextView.text = self.item.text;
}

- (void)textViewDidChange:(UITextView *)textView {
    if (!self.item) {
        JotItem *newItem = [[JotItemStore defaultStore] createItemWithText:textView.text];
        [[JotItemStore defaultStore] setCurrentIndex:0];
        self.item = newItem;
    }
    self.item.text = textView.text;

    if (self.item.shared.count > 0) {
        [self.item.shared removeAllObjects];
    }
}

- (void)setCentered:(BOOL)centered {
//    NSLog(@"setCentered: %i", centered);
    _jotTextView.scrollEnabled = centered;
    _jotTextView.editable = centered;
    _centered = centered;
}

#pragma mark -
#pragma mark GestureRecognizer

- (void)changeGesture:(UIPanGestureRecognizer *)gesture {
    CGPoint point = [gesture translationInView:self.view];
//    CGPoint velocity = [gesture velocityInView:self.view];
//    if (self.centered) {
//        NSLog(@"Centered: true");
//    } else {
//        NSLog(@"Centered: false");
//    }
//    NSLog(@"point: %@", NSStringFromCGPoint(point));
//    NSLog(@"velocity: %@", NSStringFromCGPoint(velocity));

    if (!self.centered) {
//        NSLog(@"AAA");
        [self.viewDeckController performSelector:@selector(panned:) withObject:gesture];
        [self.jotTextView hideKeyboard];
    }
    else if (point.y != 0) {
//        NSLog(@"BBB");
    }
    else if (point.x >= 0 || point.x <= 0) {
//        NSLog(@"CCC");
        [self.viewDeckController performSelector:@selector(panned:) withObject:gesture];
        [self.jotTextView hideKeyboard];
    }

}

@end


text:
window.onload = function() {
  chrome.extension.getViews({type:"tab"}).forEach(function(view) {
    if (view.relativePageLoaded) {
      view.relativePageLoaded();
    }
  });
}


text:
"""This implements the entry point for the `cros` CLI toolset.

This script is invoked by chromite/bin/cros, which sets up the
proper execution environment and calls this module's main() function.

In turn, this script looks for a subcommand based on how it was invoked. For
example, `cros lint` will use the cli/cros/cros_lint.py subcommand.

See cli/ for actual command implementations.
"""

from __future__ import print_function

import sys

from chromite.cli import command
from chromite.lib import commandline
from chromite.lib import cros_logging as logging

assert sys.version_info >= (3, 6), 'This module requires Python 3.6+'

def GetOptions(cmd_name=None):
  """Returns the parser to use for commandline parsing.

  Args:
    cmd_name: The subcommand to import & add.

  Returns:
    A commandline.ArgumentParser object.
  """
  parser = commandline.ArgumentParser(caching=True, default_log_level='notice')

  subparsers = parser.add_subparsers(title='Subcommands', dest='subcommand')
  subparsers.required = True

  # We add all the commands so `cros --help ...` looks reasonable.
  # We add them in order also so the --help output is stable for users.
  for subcommand in sorted(command.ListCommands()):
    if subcommand == cmd_name:
      class_def = command.ImportCommand(cmd_name)
      epilog = getattr(class_def, 'EPILOG', None)
      sub_parser = subparsers.add_parser(
          cmd_name, description=class_def.__doc__, epilog=epilog,
          caching=class_def.use_caching_options,
          formatter_class=commandline.argparse.RawDescriptionHelpFormatter)
      class_def.AddParser(sub_parser)
    else:
      subparsers.add_parser(subcommand, add_help=False)

  return parser

def _RunSubCommand(subcommand):
  """Helper function for testing purposes."""
  return subcommand.Run()

def main(argv):
  try:
    # The first time we parse the commandline is only to figure out what
    # subcommand the user wants to run.  This allows us to avoid importing
    # all subcommands which can be quite slow.  This works because there is
    # no way in Python to list all subcommands and their help output in a
    # single run.
    parser = GetOptions()
    if not argv:
      parser.print_help()
      return 1

    namespace, _ = parser.parse_known_args(argv)
    # The user has selected a subcommand now, so get the full parser after we
    # import the single subcommand.
    parser = GetOptions(namespace.subcommand)
    namespace = parser.parse_args(argv)
    subcommand = namespace.command_class(namespace)
    try:
      code = _RunSubCommand(subcommand)
    except (commandline.ChrootRequiredError, commandline.ExecRequiredError):
      # The higher levels want these passed back, so oblige.
      raise
    except Exception as e:
      code = 1
      logging.error('cros %s failed before completing.', namespace.subcommand)
      if namespace.debug:
        raise
      else:
        logging.error(e)
        logging.error('(Re-run with --debug for more details.)')

    if code is not None:
      return code

    return 0
  except KeyboardInterrupt:
    logging.debug('Aborted due to keyboard interrupt.')
    return 1


text:
#include "catch.hpp"

#include "server/server.hpp"
#include "server/server_message_conveyor.hpp"

#include "client/local_player_roster.hpp"

#include "resources/resource_store.hpp"
#include "resources/car_store.hpp"
#include "resources/settings.hpp"

#include "cup/cup_settings.hpp"
#include "cup/cup.hpp"
#include "cup/cup_synchronizer.hpp"

#include "stage/stage.hpp"
#include "stage/stage_messages.hpp"

#include <thread>

using namespace ts;

/*
namespace test
{
  struct SceneLoader
    : client::SceneLoaderInterface
  {
    client::LocalMessageDispatcher* message_dispatcher = nullptr;
    const stage::Stage* stage_ptr = nullptr;

    virtual void handle_message(const stage::messages::StageLoaded& stage_loaded) override
    {
      (*message_dispatcher)(cup::messages::Ready());

      stage_ptr = stage_loaded.stage_ptr;
    }
  };
}

TEST_CASE("Cup infrastructure.")
{
  resources::ResourceStore resource_store;
  auto& cup_settings = resource_store.settings().cup_settings();
  auto& car_store = resource_store.car_store();

  cup_settings.tracks.emplace_back();
  cup_settings.tracks.back().path = "assets/tracks/banaring.trk";
  cup_settings.tracks.back().name = "banaring";

  car_store.load_car_directory("assets/cars");
  auto car_it = car_store.car_definitions().find("slider");
  REQUIRE(car_it != car_store.car_definitions().end());
  cup_settings.selected_cars.push_back(*car_it);

  cup::Cup client_cup;
  cup::CupSynchronizer cup_synchronizer(&client_cup);

  cup::PlayerDefinition local_players[2];
  local_players[0].control_slot = 0;
  local_players[0].name = "Steve";
  local_players[0].id = 0xF00;
  local_players[1].control_slot = 2;
  local_players[1].name = "Johnny";
  local_players[1].id = 0xBAA;

  server::Server server_obj(&resource_store);
  client::LocalMessageDispatcher client_message_dispatcher(&server_obj.message_conveyor());

  client::LocalPlayerRoster local_player_controller(local_players, 2);
  test::SceneLoader scene_loader;
  scene_loader.message_dispatcher = &client_message_dispatcher;
  client::MessageContext<client::LocalMessageDispatcher> message_context{};
  /*
  message_context.cup_synchronizer = &cup_synchronizer;
  message_context.local_player_controller = &local_player_controller;
  message_context.scene_loader = &scene_loader;

  client::MessageConveyor<client::LocalMessageDispatcher> message_conveyor(message_context);

  server_obj.initiate_local_connection(&message_conveyor, local_players, 2);
  REQUIRE(client_cup.cup_state() == cup::CupState::Registration);

  client_message_dispatcher(cup::messages::Advance());
  REQUIRE(client_cup.cup_state() == cup::CupState::Intermission);

  client_message_dispatcher(cup::messages::Advance());
  // Wait for the server to load the track

  for (std::size_t n = 0; n != 5000 && client_cup.cup_state() != cup::CupState::Action; n += 20)
  {
    server_obj.update(20);
    std::this_thread::sleep_for(std::chrono::milliseconds(20));
  }

  REQUIRE(scene_loader.stage_ptr != nullptr);

  const auto& stage_desc = scene_loader.stage_ptr->stage_description();
  REQUIRE(stage_desc.car_instances.size() == 2);

  REQUIRE(client_cup.cup_state() == cup::CupState::Action);
  client_message_dispatcher(cup::messages::Advance());
  REQUIRE(client_cup.cup_state() == cup::CupState::End);
  client_message_dispatcher(cup::messages::Advance());
  REQUIRE(client_cup.cup_state() == cup::CupState::Registration);
}
*/


text:
package com.terradue.dsi;

import static java.lang.System.exit;

import java.util.LinkedList;
import java.util.List;

import javax.inject.Inject;

import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;

@Parameters( commandDescription = "Reboot the specified Deployment(s)." )
public final class RebootDeployments
    extends BaseTool
{

    public static void main( String[] args )
    {
        exit( new RebootDeployments().execute( args ) );
    }

    @Parameter( description = "The image identificator(s) as returned by the upload command" )
    protected List<String> ids = new LinkedList<String>();

    @Inject
    private StopDeployments stopInstances;

    @Inject
    private StartDeployments startInstances;

    public void setStopInstances( StopDeployments stopInstances )
    {
        this.stopInstances = stopInstances;
    }

    public void setStartInstances( StartDeployments startInstances )
    {
        this.startInstances = startInstances;
    }

    @Override
    public void execute()
        throws Exception
    {
        for ( String id : ids )
        {
            if ( stopInstances.stopInstance( id ) )
            {
                startInstances.startInstance( id );
            }
        }
    }

}


text:
package org.jasig.portal.url;

import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;

import java.io.UnsupportedEncodingException;

import static org.junit.Assert.assertEquals;

/**
 * @Author James Wennmacher, jwennmacher@unicon.net
 */
public class CasLoginRefUrlEncoderTest {

    CasLoginRefUrlEncoder encoder;
    MockHttpServletRequest request;

    @Before
    public void setUp() throws UnsupportedEncodingException {
        encoder = new CasLoginRefUrlEncoder();
        encoder.setCasLoginUrl("https://cas:80/cas/login?service=myhost:8080/uPortal/Login");
        request = new MockHttpServletRequest("GET", "http://myhost:8080/uPortal/p/fname");
        request.setCharacterEncoding("UTF-8");
    }

    @Test
    public void testSimpleDestination() throws Exception {
        assertEquals("https://cas:80/cas/login?service=myhost:8080/uPortal/Login%3FrefUrl%3Dhttp%3A%2F%2Fmyhost%3A8080%2FuPortal%2Fp%2Ffname",
                encoder.encodeLoginAndRefUrl(request));
    }

    @Test
    public void testWithParam() throws Exception {
        request = new MockHttpServletRequest("GET", "http://myhost:8080/uPortal/p/fname");
        request.setQueryString("pP_announcementId=1834");
        request.setCharacterEncoding("UTF-8");
        assertEquals("https://cas:80/cas/login?service=myhost:8080/uPortal/Login%3FrefUrl%3Dhttp%3A%2F%2Fmyhost%3A8080%2FuPortal%2Fp%2Ffname%253FpP_announcementId%253D1834",
                encoder.encodeLoginAndRefUrl(request));
    }

    @Test
    public void testWithTwoParams() throws Exception {
        request = new MockHttpServletRequest("GET", "http://myhost:8080/uPortal/p/fname");
        request.setQueryString("pP_action=displayFullAnnouncement&pP_announcementId=1834");
        request.setCharacterEncoding("UTF-8");
        assertEquals("https://cas:80/cas/login?service=myhost:8080/uPortal/Login%3FrefUrl%3Dhttp%3A%2F%2Fmyhost%3A8080%2FuPortal%2Fp%2Ffname%253FpP_action%253DdisplayFullAnnouncement%2526pP_announcementId%253D1834",
                encoder.encodeLoginAndRefUrl(request));
    }
}


text:
export ZMS_JDBC_PASSWORD=${ZMS_JDBC_PASSWORD:-mariadb}
export ZTS_CERT_JDBC_PASSWORD=${ZTS_CERT_JDBC_PASSWORD:-mariadb}
### SSL private key password
# export ZMS_PK_PASS=${ZMS_PK_PASS:-athenz}
# export ZTS_PK_PASS=${ZTS_PK_PASS:-athenz}
# export UI_PK_PASS=${UI_PK_PASS:-athenz}
### keystore password
export ZMS_SSL_KEYSTORE_PASS=${ZMS_SSL_KEYSTORE_PASS:-athenz}
export ZTS_SSL_KEYSTORE_PASS=${ZTS_SSL_KEYSTORE_PASS:-athenz}
export ZTS_ZTS_SSL_KEYSTORE_PASS=${ZTS_SSL_KEYSTORE_PASS}
### truststore password
export ZMS_SSL_TRUSTSTORE_PASS=${ZMS_SSL_TRUSTSTORE_PASS:-athenz}
export ZTS_SSL_TRUSTSTORE_PASS=${ZTS_SSL_TRUSTSTORE_PASS:-athenz}
export ZTS_ZTS_SSL_TRUSTSTORE_PASS=${ZTS_SSL_TRUSTSTORE_PASS}

echo "All required passwords are set in ENV."


text:
'''
Created on Mar 20, 2015

@author: yury
'''
import os, sys, time
from optparse import OptionParser
from converters import Converter_7z2zip

script_usage = "Usage: %prog [-jN] <input_filepath> <output_filepath>"
#option_0 = {'name': ('-o', '--outfile'), 'dest': 'outfile', 'help': 'resulted file name', 'type': 'string', 'nargs' : 1}
option_1 = {'name' : ('-j', '--threads'), 'dest': 'threads', 'help' : 'number of threads', 'type': 'int', 'default' : 1, 'nargs' : 1}
options = [option_1]

def main(options, arguments):
    input_file = arguments[0]
    output_file = arguments[1]

    converter = Converter_7z2zip(input_file, output_file, options.threads)

    start_time = time.time()
    try:
        converter.convert()
    finally:
        elapsed = time.time() - start_time
        print "\n\n It took %d seconds to convert" % (elapsed)

if __name__ == '__main__':
    parser = OptionParser(usage=script_usage)
    for option in options:
        param = option['name']
        del option['name']
        parser.add_option(*param, **option)
    options, arguments = parser.parse_args()
    sys.argv[:] = arguments

    if (len(arguments) < 2):
        parser.error("Not enough arguments provided!")

    if not (arguments[0] and os.path.isfile(arguments[0])):
        parser.error("Provided path does not point to a valid file!")

    if arguments[1] == None:
        parser.error("Output filepath is not specified!")

    if os.path.exists(arguments[1]):
        while True:
            user_input = raw_input('The output file already exists. Overwrite (y/n)?: ')
            if user_input.capitalize() == 'YES' or user_input.capitalize() == 'Y':
                break
            elif user_input.capitalize() == 'NO' or user_input.capitalize() == 'N':
                print "Please provide another output path. Exiting!!!"
                exit(1)

    main(options, arguments)


text:
package edu.internet2.middleware.shibboleth.common.attribute.resolver.provider.attributeDefinition;

import java.util.List;
import java.util.Locale;
import java.util.Map;

import edu.internet2.middleware.shibboleth.common.attribute.BaseAttribute;
import edu.internet2.middleware.shibboleth.common.attribute.encoding.AttributeEncoder;
import edu.internet2.middleware.shibboleth.common.attribute.resolver.provider.ResolutionPlugIn;
import edu.internet2.middleware.shibboleth.common.attribute.resolver.provider.dataConnector.DataConnector;

/**
 * A plugin used to create attributes or refine attributes provided from {@link DataConnector}s.
 *
 * Attribute definitions must be stateless and thread-safe as a single instance may be used to service every request.
 */
public interface AttributeDefinition extends ResolutionPlugIn<BaseAttribute> {

    /**
     * Gets the localized human readable description of attribute.
     *
     * @return human readable description of attribute
     */
    public Map<Locale, String> getDisplayDescriptions();

    /**
     * Gets the localized human readable name of the attribute.
     *
     * @return human readable name of the attribute
     */
    public Map<Locale, String> getDisplayNames();

    /**
     * Gets the map of encoders to be added to attributes produced by this definition, keyed on encoder category.
     *
     * @return encoders to be added to attributes produced by this definition
     */
    public List<AttributeEncoder> getAttributeEncoders();

    /**
     * Gets whether this attribute definition is only a dependency and thus its values should never be released outside
     * the resolver.
     *
     * @return whether this attribute definition is only a dependency
     */
    public boolean isDependencyOnly();
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sitecore.SecurityModel;
using Sitecore.Globalization;
using Sitecore.Extranet.Core.Extensions;
using Sitecore.Data.Items;
using Sitecore.Data;
using System.IO;
using System.Web;
using Sitecore.Extranet.Core.Utility;
using System.Text.RegularExpressions;
using Sitecore.Data.Fields;
using Sitecore.Security.AccessControl;
using Sitecore.Security.Domains;
using Sitecore.Security.Accounts;
using Sitecore.Web.UI.HtmlControls;
using Sitecore.Jobs;
using Sitecore.Data.Managers;
using Sitecore.Publishing;
using Sitecore;

namespace Sitecore.Extranet.Core.Wizards {
	public abstract class BaseLongRunningJob {

		protected List<object> CleanupList;
		protected Database MasterDB;
		protected Database WebDB;
		protected Job BuildJob;
		protected Dictionary<string, object> InputData;

		public BaseLongRunningJob(Job job) {
			CleanupList = new List<object>();
			BuildJob = job;
			MasterDB = Sitecore.Configuration.Factory.GetDatabase("master");
			WebDB = Sitecore.Configuration.Factory.GetDatabase("web");
		}

		#region Messaging

		protected int LangCur;
		protected int LangTotal;
		protected int ItemCur;
		protected int ItemTotal;

		protected void SetStatus(int processed) {
			SetStatus(processed, string.Empty);
		}
		protected void SetStatus(string message) {
			SetStatus(-1, message);
		}
		protected void SetStatus(int processed, string message) {
			if(processed > -1)
				BuildJob.Status.Processed = processed;
			if(!string.IsNullOrEmpty(message))
				BuildJob.Status.Messages.Add(message);
		}

		#endregion Messaging

		#region Execute

		/// <summary>
		/// Builds a country site in the Sitecore Master database. Performs clean up if the creation fails.
		/// </summary>
		/// <param name="data">Contains parameters to configure the construction. See Lookup.Parameters for detailed information.</param>
		/// <returns>A message indicating the status of the action</returns>
		public void Execute(Dictionary<string, object> data) {

			BuildJob = Sitecore.Context.Job;
			SetStatus(0, "Starting Build.");
			InputData = data;
			CleanupList.Clear();

			try {
				using (new SecurityDisabler()) {
					CoreExecute();
				}
				BuildJob.Status.Messages.Add("Finished Successfully");
			} catch (Exception ex) {
				StringBuilder sb = new StringBuilder(ex.ToString());
				CleanupOnFail(ref sb);
				BuildJob.Status.Failed = true;
				BuildJob.Status.Messages.Add(string.Format("The wizard was unable to complete because of the following error(s): <br/>{0}", sb.ToString()));
			}
		}

		public abstract void CoreExecute();

		#endregion

		#region Security Helper Methods

		/// <summary>
		/// Any settings added to the branches using the "BranchTemplate" roles will be replaced with ones created for this site
		/// </summary>
		/// <param name="i"></param>
		/// <param name="sitename"></param>
		protected void ReplaceSecurity(Item i, string oldRoleName, string newRoleName) {
			string s = i[FieldIDs.Security];
			if (!string.IsNullOrEmpty(s)) {
				using (new EditContext(i)) {
					i[FieldIDs.Security] = s.Replace(oldRoleName, newRoleName);
				}
			}
		}

		/// <summary>
		/// This will create a role from the string name provided
		/// </summary>
		/// <param name="resources">the resource set that keeps track of items to remove</param>
		/// <param name="fullyQualifiedRoleName">name of the role</param>
		/// <returns>The role created or null if it isn't created</returns>
		protected Role CreateRole(string fullyQualifiedRoleName) {
			if (!Role.Exists(fullyQualifiedRoleName)) {
				System.Web.Security.Roles.CreateRole(fullyQualifiedRoleName);
			}
			Role role = Role.FromName(fullyQualifiedRoleName);
			if (role != null) {
				//add to resources for removal on fail
				CleanupList.Add(role);
			}
			return role;
		}

		#endregion Security Helper Methods

		#region Helper Methods

		protected void CleanupOnFail(ref StringBuilder message) {
			using (new SecurityDisabler()) {
				foreach (var val in CleanupList) {
					try {
						if (val is Item) {
							(val as Item).Delete();
						} else if (val is DirectoryInfo) {
							(val as DirectoryInfo).Delete(true);
						} else if (val is Role) {
							System.Web.Security.Roles.DeleteRole((val as Role).Name);
						}
					} catch (System.Exception ex) {
						message.AppendLine();
						message.AppendFormat("Failed to cleanup [{0}] because of --> {1}", val.ToString(), ex.Message);
					}
				}
			}
		}

		#endregion Helper Methods
	}
}