text:
    Логирование

    Yii предоставляет гибкий и масштабируемый компонент для логирования, который способен обрабатывать сообщения в соответствии с уровнем сложности или по типу. Вы можете фильтровать сообщения по нескольким критериям и направлять их в файлы, электронную почту, отладчик и т.д.

    Основы логирования

    Основы логирования так же просты, как вызов одного метода:

    <?php
    highlight_string("<?php
\\Yii::info('Hello, I am a test log message');
?>");
    ?>

    Категории сообщения для логирования

    Кроме того, что само сообщение категории сообщения может быть указано в целях обеспечения фильтрации таких сообщений и управлять ими по-разному. Категория сообщения передается в качестве второго аргумента в метод логирования и приложения по умолчанию.

    Уровни важности

    Есть несколько уровней важности и доступны соответствующие методы:

[[Yii::trace]] используется в основном в процессе разработки, чтобы указать рабочий процесс некоторого кода. Обратите внимание, что он работает только в режиме разработки, когда YII_DEBUG установлен в true.

[[Yii::error]] используется, когда есть неустранимая ошибка.

[[Yii::warning]] используется когда произошла ошибка, но выполнение может быть продолжено.

[[Yii::info]] используется для учета важных событий, таких как логины администратора.

    Цели логирования

    Когда один из методов ведения журнала вызывается, сообщение передается в [[yii\log\Logger]] компонент также доступный, как Yii::$app->log. Logger накапливает сообщения в память, а затем, когда есть достаточно сообщений или когда текущий запрос завершен, то отправляет их в различных цели журнала, таких как файл или по электронной почте.

    Вы можете настроить цели в конфигурации приложения, вроде следующего:

    <?php
    highlight_string("<?php
[
    'components' => [
        'log' => [
            'targets' => [
                'file' => [
                    'class' => 'yii\\log\\FileTarget',
                    'levels' => ['trace', 'info'],
                    'categories' => ['yii\\*'],
                ],
                'email' => [
                    'class' => 'yii\\log\\EmailTarget',
                    'levels' => ['error', 'warning'],
                    'message' => [
                        'to' => ['admin@example.com', 'developer@example.com'],
                        'subject' => 'New example.com log message',
                    ],
                ],
            ],
        ],
    ],
]
?>");
    ?>

    В конфигурации выше мы определяем две цели журнала: [[yii\log\FileTarget|file]] и [[yii\log\EmailTarget|email]]. В обоих случаях мы имеем фильтрации сообщений в зависимости от целей по степени тяжести. В случае, если цель - файл, то мы дополнительно фильтруем по категориям. yii\* означает все категории, начиная с yii\.

    Каждая цель логирования может иметь имя и можно ссылаться через [[yii\log\Logger::targets|targets]] объект следующим образом:

    <?php
    highlight_string("<?php
Yii::\$app->log->targets['file']->enabled = false;
?>");
    ?>

    Когда приложение заканчивается или [[yii\log\Logger::flushInterval|flushInterval]] достигается, Logger будет вызывать [[yii\log\Logger::flush()|flush()]] для отправки сообщений журнала для различных целей журналов, такие как файл, электронную почту, веб-сайтов.

    Профилирование

    Профилирование производительности - это специальный тип сообщений, которые могут быть использованы для измерения времени, необходимого для исполнения некоторого блока кода, чтобы выявить узкие места в производительности.

    Для его использования нужно определить, какие блоки кода надо профилировать. Тогда мы отмечаем начало и конец каждого блока кода, вставив следующие методы:

    <?php
    highlight_string("<?php
\\Yii::beginProfile('myBenchmark');
...code block being profiled...
\\Yii::endProfile('myBenchmark');
?>");
    ?>

    где 'myBenchmark' однозначно идентифицирует блок кода.

    Примечание, блоки кода должны быть вложены должным образом, например,

    <?php
    highlight_string("<?php
\\Yii::beginProfile('block1');
    // some code to be profiled
    \\Yii::beginProfile('block2');
        // some other code to be profiled
    \\Yii::endProfile('block2');
\\Yii::endProfile('block1');
?>");
    ?>

    Результаты профилирования могут быть отображены в отладчике.


text:
package com.epam.catgenome.manager.blast;

import com.epam.catgenome.controller.vo.TaskVO;
import com.epam.catgenome.manager.blast.dto.CreateDatabaseRequest;
import com.epam.catgenome.entity.blast.BlastTask;
import com.epam.catgenome.entity.blast.result.BlastSequence;
import com.epam.catgenome.manager.blast.dto.BlastRequestResult;
import com.epam.catgenome.manager.blast.dto.CreateDatabaseResponse;
import com.epam.catgenome.manager.blast.dto.TaskPage;
import com.epam.catgenome.exception.BlastRequestException;
import com.epam.catgenome.util.db.Filter;
import com.epam.catgenome.util.db.QueryParameters;
import com.epam.catgenome.security.acl.aspect.AclMask;
import com.epam.catgenome.security.acl.aspect.AclTree;
import okhttp3.ResponseBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Collection;
import java.util.List;

import static com.epam.catgenome.security.acl.SecurityExpressions.ROLE_USER;

@Service
public class BlastTaskSecurityService {

    @Autowired
    private BlastTaskManager blastTaskManager;

    @AclTree
    @AclMask
    @PreAuthorize(ROLE_USER)
    public BlastTask load(final Long taskId) {
        return blastTaskManager.loadTask(taskId);
    }

    @PreAuthorize(ROLE_USER)
    public BlastTask create(final TaskVO taskVO) throws BlastRequestException {
        return blastTaskManager.create(taskVO);
    }

    @PreAuthorize(ROLE_USER)
    public void deleteTask(final long taskId) throws IOException {
        blastTaskManager.deleteTask(taskId);
    }

    @PreAuthorize(ROLE_USER)
    public TaskPage loadAllTasks(final QueryParameters queryParameters) {
        return blastTaskManager.loadCurrentUserTasks(queryParameters);
    }

    @PreAuthorize(ROLE_USER)
    public long getTasksCount(final List<Filter> filters) {
        return blastTaskManager.getTasksCount(filters);
    }

    @PreAuthorize(ROLE_USER)
    public void cancel(final long taskId) throws BlastRequestException {
        blastTaskManager.cancelTask(taskId);
    }

    @PreAuthorize(ROLE_USER)
    public BlastRequestResult getResult(final long taskId) throws BlastRequestException {
        return blastTaskManager.getResult(taskId);
    }

    @PreAuthorize(ROLE_USER)
    public Collection<BlastSequence> getGroupedResult(final long taskId) throws BlastRequestException {
        return blastTaskManager.getGroupedResult(taskId);
    }

    @PreAuthorize(ROLE_USER)
    public ResponseBody getRawResult(final long taskId) throws BlastRequestException {
        return blastTaskManager.getRawResult(taskId);
    }

    @PreAuthorize(ROLE_USER)
    public void deleteTasks() {
        blastTaskManager.deleteTasks();
    }

    @PreAuthorize(ROLE_USER)
    public CreateDatabaseResponse createDatabase(final CreateDatabaseRequest request) throws BlastRequestException {
        return blastTaskManager.createDatabase(request);
    }
}

redpajama_set_name: RedPajamaGithub


text:
const { Ledger } = require('../')
const { expect } = require('chai')
const { journal, chart } = require('../__mocks__')

describe('LedgerFactory', () => {
  const factory = new Ledger.Factory()

  describe('createFromJournal', () => {
    it('creates a ledger from the journal', () => {
      const ledger = factory.createFromJournalAndChart(journal, chart)

      expect(ledger).to.be.instanceof(Ledger)
    })
  })
})


text:
"""
Setup of Python virtualenv sandboxes.

.. versionadded:: 0.17.0
"""

import logging
import os

import salt.utils.functools
import salt.utils.platform
import salt.utils.versions
import salt.version
from salt.exceptions import CommandExecutionError, CommandNotFoundError

log = logging.getLogger(__name__)

# Define the module's virtual name
__virtualname__ = "virtualenv"

def __virtual__():
    if "virtualenv.create" in __salt__:
        return __virtualname__
    return (False, "virtualenv module could not be loaded")

def managed(
    name,
    venv_bin=None,
    requirements=None,
    system_site_packages=False,
    distribute=False,
    use_wheel=False,
    clear=False,
    python=None,
    extra_search_dir=None,
    never_download=None,
    prompt=None,
    user=None,
    cwd=None,
    index_url=None,
    extra_index_url=None,
    pre_releases=False,
    no_deps=False,
    pip_download=None,
    pip_download_cache=None,
    pip_exists_action=None,
    pip_ignore_installed=False,
    proxy=None,
    use_vt=False,
    env_vars=None,
    no_use_wheel=False,
    pip_upgrade=False,
    pip_pkgs=None,
    pip_no_cache_dir=False,
    pip_cache_dir=None,
    process_dependency_links=False,
    no_binary=None,
    **kwargs
):
    """
    Create a virtualenv and optionally manage it with pip

    name
        Path to the virtualenv.

    venv_bin: virtualenv
        The name (and optionally path) of the virtualenv command. This can also
        be set globally in the minion config file as ``virtualenv.venv_bin``.

    requirements: None
        Path to a pip requirements file. If the path begins with ``salt://``
        the file will be transferred from the master file server.

    use_wheel: False
        Prefer wheel archives (requires pip >= 1.4).

    python: None
        Python executable used to build the virtualenv

    user: None
        The user under which to run virtualenv and pip.

    cwd: None
        Path to the working directory where `pip install` is executed.

    no_deps: False
        Pass `--no-deps` to `pip install`.

    pip_exists_action: None
        Default action of pip when a path already exists: (s)witch, (i)gnore,
        (w)ipe, (b)ackup.

    proxy: None
        Proxy address which is passed to `pip install`.

    env_vars: None
        Set environment variables that some builds will depend on. For example,
        a Python C-module may have a Makefile that needs INCLUDE_PATH set to
        pick up a header file while compiling.

    no_use_wheel: False
        Force to not use wheel archives (requires pip>=1.4)

    no_binary
        Force to not use binary packages (requires pip >= 7.0.0)
        Accepts either :all: to disable all binary packages, :none: to empty the set,
        or a list of one or more packages

    pip_upgrade: False
        Pass `--upgrade` to `pip install`.

    pip_pkgs: None
        As an alternative to `requirements`, pass a list of pip packages that
        should be installed.

    process_dependency_links: False
        Run pip install with the --process_dependency_links flag.

        .. versionadded:: 2017.7.0

    Also accepts any kwargs that the virtualenv module will. However, some
    kwargs, such as the ``pip`` option, require ``- distribute: True``.

    .. code-block:: yaml

        /var/www/myvirtualenv.com:
          virtualenv.managed:
            - system_site_packages: False
            - requirements: salt://REQUIREMENTS.txt
            - env_vars:
                PATH_VAR: '/usr/local/bin/'
    """
    ret = {"name": name, "result": True, "comment": "", "changes": {}}

    if "virtualenv.create" not in __salt__:
        ret["result"] = False
        ret["comment"] = "Virtualenv was not detected on this system"
        return ret

    if salt.utils.platform.is_windows():
        venv_py = os.path.join(name, "Scripts", "python.exe")
    else:
        venv_py = os.path.join(name, "bin", "python")
    venv_exists = os.path.exists(venv_py)

    # Bail out early if the specified requirements file can't be found
    if requirements and requirements.startswith("salt://"):
        cached_requirements = __salt__["cp.is_cached"](requirements, __env__)
        if not cached_requirements:
            # It's not cached, let's cache it.
            cached_requirements = __salt__["cp.cache_file"](requirements, __env__)
        # Check if the master version has changed.
        if cached_requirements and __salt__["cp.hash_file"](
            requirements, __env__
        ) != __salt__["cp.hash_file"](cached_requirements, __env__):
            cached_requirements = __salt__["cp.cache_file"](requirements, __env__)
        if not cached_requirements:
            ret.update(
                {
                    "result": False,
                    "comment": "pip requirements file '{}' not found".format(
                        requirements
                    ),
                }
            )
            return ret
        requirements = cached_requirements

    # If it already exists, grab the version for posterity
    if venv_exists and clear:
        ret["changes"]["cleared_packages"] = __salt__["pip.freeze"](bin_env=name)
        ret["changes"]["old"] = __salt__["cmd.run_stderr"](
            "{} -V".format(venv_py)
        ).strip("\n")

    # Create (or clear) the virtualenv
    if __opts__["test"]:
        if venv_exists and clear:
            ret["result"] = None
            ret["comment"] = "Virtualenv {} is set to be cleared".format(name)
            return ret
        if venv_exists and not clear:
            ret["comment"] = "Virtualenv {} is already created".format(name)
            return ret
        ret["result"] = None
        ret["comment"] = "Virtualenv {} is set to be created".format(name)
        return ret

    if not venv_exists or (venv_exists and clear):
        try:
            venv_ret = __salt__["virtualenv.create"](
                name,
                venv_bin=venv_bin,
                system_site_packages=system_site_packages,
                distribute=distribute,
                clear=clear,
                python=python,
                extra_search_dir=extra_search_dir,
                never_download=never_download,
                prompt=prompt,
                user=user,
                use_vt=use_vt,
                **kwargs
            )
        except CommandNotFoundError as err:
            ret["result"] = False
            ret["comment"] = "Failed to create virtualenv: {}".format(err)
            return ret

        if venv_ret["retcode"] != 0:
            ret["result"] = False
            ret["comment"] = venv_ret["stdout"] + venv_ret["stderr"]
            return ret

        ret["result"] = True
        ret["changes"]["new"] = __salt__["cmd.run_stderr"](
            "{} -V".format(venv_py)
        ).strip("\n")

        if clear:
            ret["comment"] = "Cleared existing virtualenv"
        else:
            ret["comment"] = "Created new virtualenv"

    elif venv_exists:
        ret["comment"] = "virtualenv exists"

    # Check that the pip binary supports the 'use_wheel' option
    if use_wheel:
        min_version = "1.4"
        max_version = "9.0.3"
        cur_version = __salt__["pip.version"](bin_env=name)
        too_low = salt.utils.versions.compare(
            ver1=cur_version, oper="<", ver2=min_version
        )
        too_high = salt.utils.versions.compare(
            ver1=cur_version, oper=">", ver2=max_version
        )
        if too_low or too_high:
            ret["result"] = False
            ret["comment"] = (
                "The 'use_wheel' option is only supported in "
                "pip between {} and {}. The version of pip detected "
                "was {}.".format(min_version, max_version, cur_version)
            )
            return ret

    # Check that the pip binary supports the 'no_use_wheel' option
    if no_use_wheel:
        min_version = "1.4"
        max_version = "9.0.3"
        cur_version = __salt__["pip.version"](bin_env=name)
        too_low = salt.utils.versions.compare(
            ver1=cur_version, oper="<", ver2=min_version
        )
        too_high = salt.utils.versions.compare(
            ver1=cur_version, oper=">", ver2=max_version
        )
        if too_low or too_high:
            ret["result"] = False
            ret["comment"] = (
                "The 'no_use_wheel' option is only supported in "
                "pip between {} and {}. The version of pip detected "
                "was {}.".format(min_version, max_version, cur_version)
            )
            return ret

    # Check that the pip binary supports the 'no_binary' option
    if no_binary:
        min_version = "7.0.0"
        cur_version = __salt__["pip.version"](bin_env=name)
        too_low = salt.utils.versions.compare(
            ver1=cur_version, oper="<", ver2=min_version
        )
        if too_low:
            ret["result"] = False
            ret["comment"] = (
                "The 'no_binary' option is only supported in "
                "pip {} and newer. The version of pip detected "
                "was {}.".format(min_version, cur_version)
            )
            return ret

    # Populate the venv via a requirements file
    if requirements or pip_pkgs:
        try:
            before = set(__salt__["pip.freeze"](bin_env=name, user=user, use_vt=use_vt))
        except CommandExecutionError as exc:
            ret["result"] = False
            ret["comment"] = exc.strerror
            return ret

        if requirements:

            if isinstance(requirements, str):
                req_canary = requirements.split(",")[0]
            elif isinstance(requirements, list):
                req_canary = requirements[0]
            else:
                raise TypeError("pip requirements must be either a string or a list")

            if req_canary != os.path.abspath(req_canary):
                cwd = os.path.dirname(os.path.abspath(req_canary))

        pip_ret = __salt__["pip.install"](
            pkgs=pip_pkgs,
            requirements=requirements,
            process_dependency_links=process_dependency_links,
            bin_env=name,
            use_wheel=use_wheel,
            no_use_wheel=no_use_wheel,
            no_binary=no_binary,
            user=user,
            cwd=cwd,
            index_url=index_url,
            extra_index_url=extra_index_url,
            download=pip_download,
            download_cache=pip_download_cache,
            pre_releases=pre_releases,
            exists_action=pip_exists_action,
            ignore_installed=pip_ignore_installed,
            upgrade=pip_upgrade,
            no_deps=no_deps,
            proxy=proxy,
            use_vt=use_vt,
            env_vars=env_vars,
            no_cache_dir=pip_no_cache_dir,
            cache_dir=pip_cache_dir,
            **kwargs
        )
        ret["result"] &= pip_ret["retcode"] == 0
        if pip_ret["retcode"] > 0:
            ret["comment"] = "{}\n{}\n{}".format(
                ret["comment"], pip_ret["stdout"], pip_ret["stderr"]
            )

        after = set(__salt__["pip.freeze"](bin_env=name))

        new = list(after - before)
        old = list(before - after)

        if new or old:
            ret["changes"]["packages"] = {
                "new": new if new else "",
                "old": old if old else "",
            }
    return ret

manage = salt.utils.functools.alias_function(managed, "manage")


text:
Meteor.publish('livechat:externalMessages', function(roomId) {
	return RocketChat.models.LivechatExternalMessage.findByRoomId(roomId);
});


text:
Northplate
==========

Boilerplate code for sites being built with [Sass](http://sass-lang.com)/[Compass](http://compass-style.org). The architecture is layed out in [SMACSS](http://smacss.com) style, with each section being built into seperate modules.

Stucture
--------

+ index.html
+ config.rb
+ assets/
    + fonts/
    + images/
    + library/
    + scripts/
    + style.css
    + style/
        + base/
            + _variables.scss
            + _base.scss
            + _layout.scss
            + _state.scss
        + modules/


text:
'use babel'

class View {
    constructor(serializedState) {
        console.warn('pppppppppp');
        let htmlContent = '';
        for(let i = 0; i < 50; i++){
            htmlContent += '
列表项' + i + '
';
        }
        this.element = document.createElement('div');
        this.element.classList.add('lego-editor');

        let message = document.createElement('ul');
        // message.textContent = "The Legoeditor package is Alive! It's ALIVE!";
        message.innerHTML = htmlContent;
        message.classList.add('message');
        this.element.appendChild(message);
    }
    serialize() {

    }
    destroy() {
        this.element.remove();
    }
    getElement() {
        return this.element;
    }
}
export default View;


text:
SplashScreen::SplashScreen(const QPixmap &pixmap, Qt::WindowFlags f) :
    QSplashScreen(pixmap, f)
{
    // set reference point, paddings
    int paddingRight            = 50;
    int paddingTop              = 50;
    int titleVersionVSpace      = 17;
    int titleCopyrightVSpace    = 40;

    float fontFactor            = 1.0;

    // define text to place
    QString titleText       = QString(QApplication::applicationName()).replace(QString("-testnet"), QString(""), Qt::CaseSensitive); // cut of testnet, place it as single object further down
    QString versionText     = QString("Version %1").arg(QString::fromStdString(FormatFullVersion()));
    QString copyrightText   = QChar(0xA9)+QString(" 2009-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Bitcoin developers"));
    QString testnetAddText  = QString(tr("[testnet]")); // define text to place as single text object

    QString font            = "Arial";

    // load the bitmap for writing some text over it
    QPixmap newPixmap;
    if(GetBoolArg("-testnet")) {
        newPixmap     = QPixmap(":/images/splash_testnet");
    }
    else {
        newPixmap     = QPixmap(":/images/splash");
    }

    QPainter pixPaint(&newPixmap);
    pixPaint.setPen(QColor(100,100,100));

    // check font size and drawing with
    pixPaint.setFont(QFont(font, 33*fontFactor));
    QFontMetrics fm = pixPaint.fontMetrics();
    int titleTextWidth  = fm.width(titleText);
    if(titleTextWidth > 160) {
        // strange font rendering, Arial probably not found
        fontFactor = 0.75;
    }

    pixPaint.setFont(QFont(font, 33*fontFactor));
    fm = pixPaint.fontMetrics();
    titleTextWidth  = fm.width(titleText);
    pixPaint.drawText(newPixmap.width()-titleTextWidth-paddingRight,paddingTop,titleText);

    pixPaint.setFont(QFont(font, 15*fontFactor));

    // if the version string is to long, reduce size
    fm = pixPaint.fontMetrics();
    int versionTextWidth  = fm.width(versionText);
    if(versionTextWidth > titleTextWidth+paddingRight-10) {
        pixPaint.setFont(QFont(font, 10*fontFactor));
        titleVersionVSpace -= 5;
    }
    pixPaint.drawText(newPixmap.width()-titleTextWidth-paddingRight+2,paddingTop+titleVersionVSpace,versionText);

    // draw copyright stuff
    pixPaint.setFont(QFont(font, 10*fontFactor));
    pixPaint.drawText(newPixmap.width()-titleTextWidth-paddingRight,paddingTop+titleCopyrightVSpace,copyrightText);

    // draw testnet string if -testnet is on
    if(QApplication::applicationName().contains(QString("-testnet"))) {
        // draw copyright stuff
        QFont boldFont = QFont(font, 10*fontFactor);
        boldFont.setWeight(QFont::Bold);
        pixPaint.setFont(boldFont);
        fm = pixPaint.fontMetrics();
        int testnetAddTextWidth  = fm.width(testnetAddText);
        pixPaint.drawText(newPixmap.width()-testnetAddTextWidth-10,15,testnetAddText);
    }

    pixPaint.end();

    this->setPixmap(newPixmap);
}


text:
package jelectrum;

import java.util.LinkedHashMap;
import java.util.Map;

public class LRUCache<K,V> extends LinkedHashMap<K,V>
{

	private static final long serialVersionUID=9L;
	private int MAX_CAP;

	public LRUCache(int cap)
	{
		super(cap+1, 2.000f, true);
		MAX_CAP=cap;

	}

	protected boolean removeEldestEntry(Map.Entry<K,V> eldest)
	{
		return (size() > MAX_CAP);

	}

}


text:
// ChunkDataSerializer.cpp

// Implements the cChunkDataSerializer class representing the object that can:
//  - serialize chunk data to different protocol versions
//  - cache such serialized data for multiple clients

#include "Globals.h"
#include "ChunkDataSerializer.h"
#include "zlib/zlib.h"
#include "Protocol_1_8.h"
#include "Protocol_1_9.h"
#include "../ByteBuffer.h"

/** Calls the given function with every present chunk section. */
template <class Func>
void ForEachSection(const cChunkData & a_Data, Func a_Func)
{
	for (size_t SectionIdx = 0; SectionIdx < cChunkData::NumSections; ++SectionIdx)
	{
		auto Section = a_Data.GetSection(SectionIdx);
		if (Section != nullptr)
		{
			a_Func(*Section);
		}
	}
}

////////////////////////////////////////////////////////////////////////////////
// cChunkDataSerializer:

cChunkDataSerializer::cChunkDataSerializer(
	const cChunkData &    a_Data,
	const unsigned char * a_BiomeData,
	const eDimension      a_Dimension
):
	m_Data(a_Data),
	m_BiomeData(a_BiomeData),
	m_Dimension(a_Dimension)
{
}

const AString & cChunkDataSerializer::Serialize(int a_Version, int a_ChunkX, int a_ChunkZ)
{
	Serializations::const_iterator itr = m_Serializations.find(a_Version);
	if (itr != m_Serializations.end())
	{
		return itr->second;
	}

	AString data;
	switch (a_Version)
	{
		case RELEASE_1_8_0: Serialize47(data, a_ChunkX, a_ChunkZ); break;
		case RELEASE_1_9_0: Serialize107(data, a_ChunkX, a_ChunkZ); break;
		case RELEASE_1_9_4: Serialize110(data, a_ChunkX, a_ChunkZ); break;
		// TODO: Other protocol versions may serialize the data differently; implement here

		default:
		{
			LOGERROR("cChunkDataSerializer::Serialize(): Unknown version: %d", a_Version);
			ASSERT(!"Unknown chunk data serialization version");
			break;
		}
	}
	if (!data.empty())
	{
		m_Serializations[a_Version] = data;
	}
	return m_Serializations[a_Version];
}

void cChunkDataSerializer::Serialize47(AString & a_Data, int a_ChunkX, int a_ChunkZ)
{
	// This function returns the fully compressed packet (including packet size), not the raw packet!

	// Create the packet:
	cByteBuffer Packet(512 KiB);
	Packet.WriteVarInt32(0x21);  // Packet id (Chunk Data packet)
	Packet.WriteBEInt32(a_ChunkX);
	Packet.WriteBEInt32(a_ChunkZ);
	Packet.WriteBool(true);      // "Ground-up continuous", or rather, "biome data present" flag
	Packet.WriteBEUInt16(m_Data.GetSectionBitmask());

	// Write the chunk size:
	const int BiomeDataSize = cChunkDef::Width * cChunkDef::Width;
	UInt32 ChunkSize = (
		m_Data.NumPresentSections() * cChunkData::SectionBlockCount * 3 +  // Blocks and lighting
		BiomeDataSize    // Biome data
	);
	Packet.WriteVarInt32(ChunkSize);

	// Chunk written as seperate arrays of (blocktype + meta), blocklight and skylight
	// each array stores all present sections of the same kind packed together

	// Write the block types to the packet:
	ForEachSection(m_Data, [&](const cChunkData::sChunkSection & a_Section)
		{
			for (size_t BlockIdx = 0; BlockIdx != cChunkData::SectionBlockCount; ++BlockIdx)
			{
				BLOCKTYPE BlockType = a_Section.m_BlockTypes[BlockIdx] & 0xFF;
				NIBBLETYPE BlockMeta = a_Section.m_BlockMetas[BlockIdx / 2] >> ((BlockIdx & 1) * 4) & 0x0f;
				Packet.WriteBEUInt8(static_cast<unsigned char>(BlockType << 4) | BlockMeta);
				Packet.WriteBEUInt8(static_cast<unsigned char>(BlockType >> 4));
			}
		}
	);

	// Write the block lights:
	ForEachSection(m_Data, [&](const cChunkData::sChunkSection & a_Section)
		{
			Packet.WriteBuf(a_Section.m_BlockLight, sizeof(a_Section.m_BlockLight));
		}
	);

	// Write the sky lights:
	ForEachSection(m_Data, [&](const cChunkData::sChunkSection & a_Section)
		{
			Packet.WriteBuf(a_Section.m_BlockSkyLight, sizeof(a_Section.m_BlockSkyLight));
		}
	);

	// Write the biome data:
	Packet.WriteBuf(m_BiomeData, BiomeDataSize);

	AString PacketData;
	Packet.ReadAll(PacketData);
	Packet.CommitRead();

	cByteBuffer Buffer(20);
	if (PacketData.size() >= 256)
	{
		if (!cProtocol_1_8_0::CompressPacket(PacketData, a_Data))
		{
			ASSERT(!"Packet compression failed.");
			a_Data.clear();
			return;
		}
	}
	else
	{
		AString PostData;
		Buffer.WriteVarInt32(static_cast<UInt32>(Packet.GetUsedSpace() + 1));
		Buffer.WriteVarInt32(0);
		Buffer.ReadAll(PostData);
		Buffer.CommitRead();

		a_Data.clear();
		a_Data.reserve(PostData.size() + PacketData.size());
		a_Data.append(PostData.data(), PostData.size());
		a_Data.append(PacketData.data(), PacketData.size());
	}
}

void cChunkDataSerializer::Serialize107(AString & a_Data, int a_ChunkX, int a_ChunkZ)
{
	// This function returns the fully compressed packet (including packet size), not the raw packet!

	// Create the packet:
	cByteBuffer Packet(512 KiB);
	Packet.WriteVarInt32(0x20);  // Packet id (Chunk Data packet)
	Packet.WriteBEInt32(a_ChunkX);
	Packet.WriteBEInt32(a_ChunkZ);
	Packet.WriteBool(true);        // "Ground-up continuous", or rather, "biome data present" flag
	Packet.WriteVarInt32(m_Data.GetSectionBitmask());
	// Write the chunk size:
	const size_t BitsPerEntry = 13;
	const size_t Mask = (1 << BitsPerEntry) - 1;  // Creates a mask that is 13 bits long, ie 0b1111111111111
	const size_t ChunkSectionDataArraySize = (cChunkData::SectionBlockCount * BitsPerEntry) / 8 / 8;  // Convert from bit count to long count
	size_t ChunkSectionSize = (
		1 +                                // Bits per block - set to 13, so the global palette is used and the palette has a length of 0
		1 +                                // Palette length
		2 +                                // Data array length VarInt - 2 bytes for the current value
		ChunkSectionDataArraySize * 8 +    // Actual block data - multiplied by 8 because first number is longs
		cChunkData::SectionBlockCount / 2  // Block light
	);

	if (m_Dimension == dimOverworld)
	{
		// Sky light is only sent in the overworld.
		ChunkSectionSize += cChunkData::SectionBlockCount / 2;
	}

	const size_t BiomeDataSize = cChunkDef::Width * cChunkDef::Width;
	size_t ChunkSize = (
		ChunkSectionSize * m_Data.NumPresentSections() +
		BiomeDataSize
	);
	Packet.WriteVarInt32(static_cast<UInt32>(ChunkSize));

	// Write each chunk section...
	ForEachSection(m_Data, [&](const cChunkData::sChunkSection & a_Section)
		{
			Packet.WriteBEUInt8(BitsPerEntry);
			Packet.WriteVarInt32(0);  // Palette length is 0
			Packet.WriteVarInt32(static_cast<UInt32>(ChunkSectionDataArraySize));

			UInt64 TempLong = 0;  // Temporary value that will be stored into
			UInt64 CurrentlyWrittenIndex = 0;  // "Index" of the long that would be written to

			for (size_t Index = 0; Index < cChunkData::SectionBlockCount; Index++)
			{
				UInt64 Value = static_cast<UInt64>(a_Section.m_BlockTypes[Index] << 4);
				if (Index % 2 == 0)
				{
					Value |= a_Section.m_BlockMetas[Index / 2] & 0x0f;
				}
				else
				{
					Value |= a_Section.m_BlockMetas[Index / 2] >> 4;
				}
				Value &= Mask;  // It shouldn't go out of bounds, but it's still worth being careful

				// Painful part where we write data into the long array.  Based off of the normal code.
				size_t BitPosition = Index * BitsPerEntry;
				size_t FirstIndex = BitPosition / 64;
				size_t SecondIndex = ((Index + 1) * BitsPerEntry - 1) / 64;
				size_t BitOffset = BitPosition % 64;

				if (FirstIndex != CurrentlyWrittenIndex)
				{
					// Write the current data before modifiying it.
					Packet.WriteBEUInt64(TempLong);
					TempLong = 0;
					CurrentlyWrittenIndex = FirstIndex;
				}

				TempLong |= (Value << BitOffset);

				if (FirstIndex != SecondIndex)
				{
					// Part of the data is now in the second long; write the first one first
					Packet.WriteBEUInt64(TempLong);
					CurrentlyWrittenIndex = SecondIndex;

					TempLong = (Value >> (64 - BitOffset));
				}
			}
			// The last long will generally not be written
			Packet.WriteBEUInt64(TempLong);

			// Write lighting:
			Packet.WriteBuf(a_Section.m_BlockLight, sizeof(a_Section.m_BlockLight));
			if (m_Dimension == dimOverworld)
			{
				// Skylight is only sent in the overworld; the nether and end do not use it
				Packet.WriteBuf(a_Section.m_BlockSkyLight, sizeof(a_Section.m_BlockSkyLight));
			}
		}
	);

	// Write the biome data
	Packet.WriteBuf(m_BiomeData, BiomeDataSize);

	AString PacketData;
	Packet.ReadAll(PacketData);
	Packet.CommitRead();

	cByteBuffer Buffer(20);
	if (PacketData.size() >= 256)
	{
		if (!cProtocol_1_9_0::CompressPacket(PacketData, a_Data))
		{
			ASSERT(!"Packet compression failed.");
			a_Data.clear();
			return;
		}
	}
	else
	{
		AString PostData;
		Buffer.WriteVarInt32(static_cast<UInt32>(Packet.GetUsedSpace() + 1));
		Buffer.WriteVarInt32(0);
		Buffer.ReadAll(PostData);
		Buffer.CommitRead();

		a_Data.clear();
		a_Data.reserve(PostData.size() + PacketData.size());
		a_Data.append(PostData.data(), PostData.size());
		a_Data.append(PacketData.data(), PacketData.size());
	}
}

void cChunkDataSerializer::Serialize110(AString & a_Data, int a_ChunkX, int a_ChunkZ)
{
	// This function returns the fully compressed packet (including packet size), not the raw packet!

	// Create the packet:
	cByteBuffer Packet(512 KiB);
	Packet.WriteVarInt32(0x20);  // Packet id (Chunk Data packet)
	Packet.WriteBEInt32(a_ChunkX);
	Packet.WriteBEInt32(a_ChunkZ);
	Packet.WriteBool(true);        // "Ground-up continuous", or rather, "biome data present" flag
	Packet.WriteVarInt32(m_Data.GetSectionBitmask());
	// Write the chunk size:
	const size_t BitsPerEntry = 13;
	const size_t Mask = (1 << BitsPerEntry) - 1;  // Creates a mask that is 13 bits long, ie 0b1111111111111
	const size_t ChunkSectionDataArraySize = (cChunkData::SectionBlockCount * BitsPerEntry) / 8 / 8;  // Convert from bit count to long count
	size_t ChunkSectionSize = (
		1 +                                // Bits per block - set to 13, so the global palette is used and the palette has a length of 0
		1 +                                // Palette length
		2 +                                // Data array length VarInt - 2 bytes for the current value
		ChunkSectionDataArraySize * 8 +    // Actual block data - multiplied by 8 because first number is longs
		cChunkData::SectionBlockCount / 2  // Block light
	);

	if (m_Dimension == dimOverworld)
	{
		// Sky light is only sent in the overworld.
		ChunkSectionSize += cChunkData::SectionBlockCount / 2;
	}

	const size_t BiomeDataSize = cChunkDef::Width * cChunkDef::Width;
	size_t ChunkSize = (
		ChunkSectionSize * m_Data.NumPresentSections() +
		BiomeDataSize
	);
	Packet.WriteVarInt32(static_cast<UInt32>(ChunkSize));

	// Write each chunk section...
	ForEachSection(m_Data, [&](const cChunkData::sChunkSection & a_Section)
		{
			Packet.WriteBEUInt8(BitsPerEntry);
			Packet.WriteVarInt32(0);  // Palette length is 0
			Packet.WriteVarInt32(static_cast<UInt32>(ChunkSectionDataArraySize));

			UInt64 TempLong = 0;  // Temporary value that will be stored into
			UInt64 CurrentlyWrittenIndex = 0;  // "Index" of the long that would be written to

			for (size_t Index = 0; Index < cChunkData::SectionBlockCount; Index++)
			{
				UInt64 Value = static_cast<UInt64>(a_Section.m_BlockTypes[Index] << 4);
				if (Index % 2 == 0)
				{
					Value |= a_Section.m_BlockMetas[Index / 2] & 0x0f;
				}
				else
				{
					Value |= a_Section.m_BlockMetas[Index / 2] >> 4;
				}
				Value &= Mask;  // It shouldn't go out of bounds, but it's still worth being careful

				// Painful part where we write data into the long array.  Based off of the normal code.
				size_t BitPosition = Index * BitsPerEntry;
				size_t FirstIndex = BitPosition / 64;
				size_t SecondIndex = ((Index + 1) * BitsPerEntry - 1) / 64;
				size_t BitOffset = BitPosition % 64;

				if (FirstIndex != CurrentlyWrittenIndex)
				{
					// Write the current data before modifiying it.
					Packet.WriteBEUInt64(TempLong);
					TempLong = 0;
					CurrentlyWrittenIndex = FirstIndex;
				}

				TempLong |= (Value << BitOffset);

				if (FirstIndex != SecondIndex)
				{
					// Part of the data is now in the second long; write the first one first
					Packet.WriteBEUInt64(TempLong);
					CurrentlyWrittenIndex = SecondIndex;

					TempLong = (Value >> (64 - BitOffset));
				}
			}
			// The last long will generally not be written
			Packet.WriteBEUInt64(TempLong);

			// Write lighting:
			Packet.WriteBuf(a_Section.m_BlockLight, sizeof(a_Section.m_BlockLight));
			if (m_Dimension == dimOverworld)
			{
				// Skylight is only sent in the overworld; the nether and end do not use it
				Packet.WriteBuf(a_Section.m_BlockSkyLight, sizeof(a_Section.m_BlockSkyLight));
			}
		}
	);

	// Write the biome data
	Packet.WriteBuf(m_BiomeData, BiomeDataSize);

	// Identify 1.9.4's tile entity list as empty
	Packet.WriteBEUInt8(0);

	AString PacketData;
	Packet.ReadAll(PacketData);
	Packet.CommitRead();

	cByteBuffer Buffer(20);
	if (PacketData.size() >= 256)
	{
		if (!cProtocol_1_9_0::CompressPacket(PacketData, a_Data))
		{
			ASSERT(!"Packet compression failed.");
			a_Data.clear();
			return;
		}
	}
	else
	{
		AString PostData;
		Buffer.WriteVarInt32(static_cast<UInt32>(Packet.GetUsedSpace() + 1));
		Buffer.WriteVarInt32(0);
		Buffer.ReadAll(PostData);
		Buffer.CommitRead();

		a_Data.clear();
		a_Data.reserve(PostData.size() + PacketData.size());
		a_Data.append(PostData.data(), PostData.size());
		a_Data.append(PacketData.data(), PacketData.size());
	}
}


text:
package rs.lukaj.upisstats.scraper.download;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import rs.lukaj.upisstats.scraper.obrada2017.LetterUtils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by luka on 2.7.17.
 */
public class Smer2017 extends Smer {
    protected String skola;
    protected String smer;
    protected String jezik;
    protected String opstina;
    protected String okrug;
    protected String podrucje;
    protected String trajanje;
    protected String kvotaUmanjenje;
    protected String upisano1K, upisano2K;
    protected String minBodova1K, minBodova2K, kvota2K;

    protected String json;

    public String getSkola() {
        return skola;
    }

    public String getJezik() {
        return jezik;
    }

    public String getOpstina() {
        return opstina;
    }

    public String getOkrug() {
        return okrug;
    }

    public String getTrajanje() {
        return trajanje;
    }

    public String getSmer() {
        return smer;
    }

    //let's pretend this isn't godawful
    public String getPodrucje2017() {
        return podrucje;
    }

    public String getJson() {
        return json;
    }

    public Smer2017(String sifra, String kvota) {
        super(sifra, null, kvota);
    }

    public Smer2017(String compactString) {
        super(compactString);
        smer = super.getPodrucje();
        String[] tokens = compactString.split("\\\\");
        skola = LetterUtils.toLatin(tokens[3]);
        trajanje = tokens[4];
        kvotaUmanjenje = tokens[5];
        jezik = tokens[6];
        opstina = tokens[7];
        okrug = tokens[8];
        podrucje = tokens[9];
        upisano1K = tokens[10];
        minBodova1K = tokens[11];
        kvota2K = tokens[12];
        upisano2K = tokens[13];
        minBodova2K = tokens[14];
    }

    public String toCompactString() {
        StringBuilder str = new StringBuilder(128);
        if(skola != null && skola.endsWith(",")) skola = skola.substring(0, skola.length()-1);
        str.append(getSifra()).append("\\").append(smer).append("\\").append(getKvota()).append("\\").append(skola).append("\\")
                .append(trajanje).append("\\").append(kvotaUmanjenje).append("\\").append(jezik).append("\\")
                .append(opstina).append("\\").append(okrug).append("\\").append(podrucje).append("\\")
        .append(upisano1K).append("\\").append(minBodova1K).append("\\").append(kvota2K).append("\\").append(upisano2K).append("\\").append(minBodova2K).append("\n");
        return str.toString();
    }

    private ExecutorService executor = Executors.newSingleThreadExecutor();
    public void saveJson(String json) {
        executor.execute(() -> {
            try {
                BufferedWriter bw = new BufferedWriter(new FileWriter(new File(Smerovi.SMEROVI_FOLDER, getSifra() + ".json")));
                bw.write(json);
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            Smerovi2017.getInstance().save(); //not the finest solution
        });
    }

    public void exetendFromJson() {
        try {
            JsonParser parser = new JsonParser();
            trajanje = (parser.parse(Files.readAllLines(new File(Smerovi.SMEROVI_FOLDER, getSifra() + ".json").toPath()).stream().reduce("", (a, b)->a+b)).getAsJsonArray().get(0).getAsJsonObject().get("Trajanje").getAsString()); //I'm not it the mood, mkay?
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void loadFromJson() {
        try {
            JsonParser parse = new JsonParser();
            SmerMappingTools.Mapper mapper = SmerMappingTools.getMapper(2018);
            JsonObject json = parse.parse(Files.readAllLines(new File(Smerovi.SMEROVI_FOLDER, getSifra() + ".json").toPath()).get(0)).getAsJsonArray().get(0).getAsJsonObject();
            loadFromJson(mapper, json);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void loadFromJson(SmerMappingTools.Mapper mapper, JsonObject json) {
        skola = json.get("NazivSkole2").getAsString();
        smer = json.get("Profil2").getAsString();
        jezik = mapper.getJezik(Integer.parseInt(json.get("IDJezik").getAsString()));
        opstina = mapper.getOpstina(Integer.parseInt(json.get("IDOpstina").getAsString()));
        okrug = mapper.getOkrug(Integer.parseInt(json.get("IDOkrug").getAsString()));
        kvotaUmanjenje = json.get("KvotaUmanjenje").getAsString();
        podrucje = json.get("Naziv2").getAsString();
        trajanje = json.get("Trajanje").getAsString();

        upisano1K = json.get("Upisano1K").getAsString();
        upisano2K = json.get("Upisano2K").getAsString();
        minBodova1K = json.get("MinBodova1K").getAsString();
        minBodova2K = json.get("MinBodova2K").getAsString();
        kvota2K  = json.get("Kvota2K").getAsString().trim();
    }

    public String getKvotaUmanjenje() {
        return kvotaUmanjenje;
    }

    public String getUpisano1K() {
        return upisano1K;
    }

    public String getUpisano2K() {
        return upisano2K;
    }

    public String getMinBodova1K() {
        return minBodova1K;
    }

    public String getMinBodova2K() {
        return minBodova2K;
    }

    public String getKvota2K() {
        return kvota2K;
    }
}


text:
package by.hut.flat.calendar.internal;

import java.util.List;

import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;

public class SamplePagerAdapter extends PagerAdapter{

    List<View> pages = null;

    public SamplePagerAdapter(List<View> pages){
        this.pages = pages;
    }

    @Override
    public Object instantiateItem(ViewGroup collection, int position){
        View v = pages.get(position);
        collection.addView(v, 0);
        return v;
    }

    @Override
    public void destroyItem(ViewGroup collection, int position, Object view){
        collection.removeView((View) view);
    }
    @Override
    public int getCount(){
        return pages.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object){
        return view.equals(object);
    }

    @Override
    public void finishUpdate(View arg0){
    }

    @Override
    public void restoreState(Parcelable arg0, ClassLoader arg1){
    }

    @Override
    public Parcelable saveState(){
        return null;
    }

    @Override
    public void startUpdate(View arg0){
    }
    public static int Int(String str){
		return Integer.parseInt(str);
	}
}


text: a TCP test tool for MacOSX


text:
<!DOCTYPE HTML>

		<meta http-equiv="Content-Type" content="html/html; charset=utf-8" />
		<title>NSString(SFPascalString) Category Reference</title>
		<meta id="xcode-display" name="xcode-display" content="render"/>
		<link rel="stylesheet" type="text/css" href="../css/styles.css" media="all" />
		<link rel="stylesheet" type="text/css" media="print" href="../css/stylesPrint.css" />
		<meta name="generator" content="appledoc 2.1 (build 840)" />

SFPSDWriter

				Shiny Frog

NSString(SFPascalString) Category Reference

					<button aria-label="Show Table of Contents" role="checkbox" class="open" id="table_of_contents">Table of Contents</button>

					<select id="jumpTo">
	<option value="top">Jump To…</option>

	<option value="tasks">Tasks</option>

	<option value="instance_methods">Instance Methods</option>

	<option value="//api/name/sfPascalStringLengthPaddedTo:">    - sfPascalStringLengthPaddedTo:</option>

	<option value="//api/name/sfPascalStringPaddedTo:">    - sfPascalStringPaddedTo:</option>

	<option value="//api/name/sfPascalStringPaddedTo:withPaddingString:">    - sfPascalStringPaddedTo:withPaddingString:</option>

</select>

Tasks

Instance Methods

sfPascalStringLengthPaddedTo:

sfPascalStringPaddedTo:

sfPascalStringPaddedTo:withPaddingString:

Index

Hierarchy

NSString(SFPascalString) Category Reference

	Declared in
	NSString+SFPascalString.h
NSString+SFPascalString.m

Tasks

		– sfPascalStringPaddedTo:withPaddingString:

Pascal string padded to multiples of the paddind interval.

		– sfPascalStringPaddedTo:

Pascal string padded to multiples of the paddind interval using as padding the unicode char 0x00.

		– sfPascalStringLengthPaddedTo:

The length of the string padded to the multiples of the padding interval.

Instance Methods

sfPascalStringLengthPaddedTo:

The length of the string padded to the multiples of the padding interval.

- (int)sfPascalStringLengthPaddedTo:(int)paddingInterval

Discussion

The length of the string padded to the multiples of the padding interval.

Declared In

		NSString+SFPascalString.h

sfPascalStringPaddedTo:

Pascal string padded to multiples of the paddind interval using as padding the unicode char 0x00.

- (const char *)sfPascalStringPaddedTo:(int)paddingInterval

Discussion

Pascal string padded to multiples of the paddind interval using as padding the unicode char 0x00.

Declared In

		NSString+SFPascalString.h

sfPascalStringPaddedTo:withPaddingString:

Pascal string padded to multiples of the paddind interval.

- (const char *)sfPascalStringPaddedTo:(int)paddingInterval withPaddingString:(NSString *)paddingString

Discussion

Pascal string padded to multiples of the paddind interval.

Declared In

		NSString+SFPascalString.h

Index

Hierarchy

© 2014 Shiny Frog. All rights reserved. (Last updated: 2014-06-16)

						Generated by appledoc 2.1 (build 840).


text:
package net.minidev.ovh.api.cloud;

/**
 * Load balancing IP imported into your OpenStack project
 */
public class OvhIPLoadbalancing {
	/**
	 * validation url
	 *
	 * canBeNull && readOnly
	 */
	public String validationUrl;

	/**
	 * ID of your load balancing ip import
	 *
	 * canBeNull && readOnly
	 */
	public String id;

	/**
	 * IPLB service name
	 *
	 * canBeNull && readOnly
	 */
	public String iplb;

	/**
	 * Status of your import
	 *
	 * canBeNull && readOnly
	 */
	public String status;
}


text:
<?php

namespace Arrilot\BitrixModels\Exceptions;

use Exception;

class ExceptionFromBitrix extends Exception
{

}


text:
///// Package Declaration /////

package ly.kite.util;

///// Import(s) /////

import android.content.BroadcastReceiver;
import android.graphics.Bitmap;

import java.util.HashMap;
import java.util.LinkedList;

///// Class Declaration /////

/*****************************************************
 *
 * This class implements a MRU-LRU image cache.
 *
 *****************************************************/
public class ImageCache implements IImageConsumer
  {
  ////////// Static Constant(s) //////////

  @SuppressWarnings( "unused" )
  private static final String  LOG_TAG = "ImageCache";

  ////////// Static Variable(s) //////////

  ////////// Member Variable(s) //////////

  private int                           mCapacityInBytes;

  private HashMap<Object,Holder>        mHolderTable;
  private LinkedList<Holder>            mHolderList;
  private int                           mSizeInBytes;

  private HashMap<Object,PendingImage>  mPendingTable;

  ////////// Static Initialiser(s) //////////

  ////////// Static Method(s) //////////

  ////////// Constructor(s) //////////

  public ImageCache( int capacityInBytes )
    {
    mCapacityInBytes = capacityInBytes;

    mHolderTable     = new HashMap<>();
    mHolderList      = new LinkedList<>();
    mSizeInBytes     = 0;

    mPendingTable    = new HashMap<>();
    }

  ////////// IImageConsumer Method(s) //////////

  /*****************************************************
   *
   * Called when the image is being downloaded.
   *
   *****************************************************/
  @Override
  public void onImageDownloading( Object key )
    {
    // Find the corresponding pending image

    PendingImage pendingImage = mPendingTable.remove( key );

    if ( pendingImage == null ) return;

    // Notify the end consumer
    pendingImage.consumer.onImageDownloading( key );
    }

  /*****************************************************
   *
   * Called when the image is available. Override this
   * in a child class if we want to do anything with
   * the image before caching it, but remember that it
   * is on the UI thread.
   *
   *****************************************************/
  @Override
  public void onImageAvailable( Object key, Bitmap bitmap )
    {
    // Find the corresponding pending image

    PendingImage pendingImage = mPendingTable.remove( key );

    if ( pendingImage == null ) return;

    // Store the image
    addImage( key, bitmap );

    // Pass the image to the end consumer
    pendingImage.consumer.onImageAvailable( key, bitmap );
    }

  ////////// Method(s) //////////

  /*****************************************************
   *
   * Returns an image, if it is in the cache, null otherwise.
   *
   *****************************************************/
  public Bitmap getImage( Object key )
    {
    // Try and find the image

    Holder holder = mHolderTable.get( key );

    if ( holder == null ) return ( null );

    // Move the image to the front of the MRU-LRU list before
    // we return the bitmap.

    mHolderList.remove( holder );
    mHolderList.addFirst( holder );

    return ( holder.bitmap );
    }

  /*****************************************************
   *
   * Stores a pending request.
   *
   *****************************************************/
  public void addPendingImage( Object key, IImageConsumer consumer )
    {
    mPendingTable.put( key, new PendingImage( key, consumer ) );
    }

  /*****************************************************
   *
   * Adds an image to the cache.
   *
   *****************************************************/
  public void addImage( Object key, Bitmap bitmap )
    {
    // Create a new holder for the image
    Holder newHolder = new Holder( key, bitmap );

    // Store the holder in the table and at the front of the list
    mHolderTable.put( key, newHolder );
    mHolderList.addFirst( newHolder );

    // Calculate the new size after the image has been added. If the size
    // exceeds the capacity, then remove images from the end until we get
    // back down within the capacity.

    mSizeInBytes += newHolder.approximateSizeInBytes;

    while ( mSizeInBytes > mCapacityInBytes )
      {
      // Get the least recently used image and remove it

      Holder lruHolder = mHolderList.removeLast();

      if ( lruHolder == null ) break;

      mHolderTable.remove( lruHolder.key );

      mSizeInBytes -= lruHolder.approximateSizeInBytes;
      }
    }

  ////////// Inner Class(es) //////////

  /*****************************************************
   *
   * Holds an image.
   *
   *****************************************************/
  private class Holder
    {
    Object  key;
    Bitmap  bitmap;
    int     approximateSizeInBytes;

    Holder( Object key, Bitmap bitmap )
      {
      this.key                    = key;
      this.bitmap                 = bitmap;

      // Calculate the approximate size in bytes. This only works if
      // the bitmap is not reconfigured.
      this.approximateSizeInBytes = bitmap.getByteCount();
      }
    }

  /*****************************************************
   *
   * A pending image request.
   *
   *****************************************************/
  private class PendingImage
    {
    Object          key;
    IImageConsumer  consumer;

    PendingImage( Object key, IImageConsumer consumer )
      {
      this.key      = key;
      this.consumer = consumer;
      }

    }

  }


text:
extern "Java"
{
  namespace javax
  {
    namespace swing
    {
      namespace event
      {
          class UndoableEditEvent;
      }
      namespace undo
      {
          class UndoManager;
          class UndoableEdit;
      }
    }
  }
}

class javax::swing::undo::UndoManager : public ::javax::swing::undo::CompoundEdit
{

public:
  UndoManager();
  virtual ::java::lang::String * toString();
  virtual void end();
  virtual jint getLimit();
  virtual void setLimit(jint);
  virtual void discardAllEdits();
public: // actually protected
  virtual void trimForLimit();
  virtual void trimEdits(jint, jint);
  virtual ::javax::swing::undo::UndoableEdit * editToBeUndone();
  virtual ::javax::swing::undo::UndoableEdit * editToBeRedone();
  virtual void undoTo(::javax::swing::undo::UndoableEdit *);
  virtual void redoTo(::javax::swing::undo::UndoableEdit *);
public:
  virtual void undoOrRedo();
  virtual jboolean canUndoOrRedo();
  virtual void undo();
  virtual jboolean canUndo();
  virtual void redo();
  virtual jboolean canRedo();
  virtual jboolean addEdit(::javax::swing::undo::UndoableEdit *);
  virtual ::java::lang::String * getUndoOrRedoPresentationName();
  virtual ::java::lang::String * getUndoPresentationName();
  virtual ::java::lang::String * getRedoPresentationName();
  virtual void undoableEditHappened(::javax::swing::event::UndoableEditEvent *);
public: // actually package-private
  static const jlong serialVersionUID = -2077529998244066750LL;
  jint __attribute__((aligned(__alignof__( ::javax::swing::undo::CompoundEdit)))) indexOfNextAdd;
  jint limit;
public:
  static ::java::lang::Class class$;
};

#endif // __javax_swing_undo_UndoManager__


text:
package org.OpenColorIO;
import org.OpenColorIO.*;
import java.nio.FloatBuffer;

public class PlanarImageDesc extends ImageDesc
{
    public PlanarImageDesc(FloatBuffer rData, FloatBuffer gData, FloatBuffer bData,
                           FloatBuffer aData, long width, long height)
    {
        super();
        create(rData, gData, bData, aData, width, height);
    }
    public PlanarImageDesc(FloatBuffer rData, FloatBuffer gData, FloatBuffer bData,
                           FloatBuffer aData, long width, long height,
                           long yStrideBytes)
    {
        super();
        create(rData, gData, bData, aData, width, height, yStrideBytes);
    }
    protected PlanarImageDesc(long impl) { super(impl); }
    public native void dispose();
    protected void finalize() { dispose(); }
    protected native void create(FloatBuffer rData, FloatBuffer gData, FloatBuffer bData,
                                 FloatBuffer aData, long width, long height);
    protected native void create(FloatBuffer rData, FloatBuffer gData, FloatBuffer bData,
                                 FloatBuffer aData, long width, long height,
                                 long yStrideBytes);
    public native FloatBuffer getRData();
    public native FloatBuffer getGData();
    public native FloatBuffer getBData();
    public native FloatBuffer getAData();
    public native long getWidth();
    public native long getHeight();
    public native long getYStrideBytes();
};


text:
  <TITLE>Forward protocol (Appendix 9)</TITLE>

  FBB forward protocol.

(Appendix 9)

 FBB software includes two forward protocols. The first one is standard with
MBL/RLI  protocol.  The  second  one  was  developed  to  allow
efficiency, particularly on long links where propagation time of data are
long. The exchange of commands is reduced to a minimum, and not acknowledged
to get time. The data transfer direction is changed every block of data, a
block of data holding up to five messages. This uses the "pipeline" effect of
long links (Nodes and digipeaters), and gain some time over short links
(HF...).

 FBB protocol is very simple in its principle. It is based on MID/BID usage.
The identification is made by the F letter in the SID (system type identifier
contained in square brackets). All command lines must start in first column
with the 'F' character. All command lines are ended by a return (CR)
character.

 Suppose I call another BBS to forward some mail. When I connect another BBS
using FBB protocol, I will receive the SID followed by a text and the prompt
(">"). If the SID contains the F flag, I will send immediately my SID and the
first proposal.

 Proposals looks like :

 FB P F6FBB FC1GHV FC1MVP 24657_F6FBB 1345
 F> HH

 FB : Identifies the type of the command (proposal)
 P : Type of message (P = Private, B = Bulletin).
 F6FBB : Sender (from field).
 FC1GHV : BBS of recipient (@field).
 FC1MVP : Recipient (to field).
 24657_F6FBB : BID ou MID.
 1345 : Size of message in bytes.
 F> : End of proposal.
 HH is optional. It is the checksum of the whole proposal in hexadecimal.

 ALL the fields are necessary. This kind of command must hold seven fields.
If a field is missing upon receiving, an error message will be send
immediately followed by a disconnection.

 A proposal can handle up to five FB command lines. If the total size of
messages seems to be too important, the proposal can handle less lines. In
FBB software, a parameter is defined in INIT.SRV file to tell the maximum
size of the message block. It is set by default to 10KB.

 Example of proposal :

 FB P F6FBB FC1GHV.FFPC.FRA.EU FC1MVP 24657_F6FBB 1345
 FB P FC1CDC F6ABJ F6AXV 24643_F6FBB 5346
 FB B F6FBB FRA FBB 22_456_F6FBB 8548
 F> HH

 This proposal is limited to three FB lines, as the amount of messages
overran the 10KB limit.

 When receiving the proposal, the other BBS will reject, accept or defer the
message. This command is made by a FS line :

 FS -+=

 This means :

 - I don't want the first message (-).
 - I need the second message (+).
 - I defer the third message, as I'm still receiving it.

 In the new version 1 of FBB protocol there are 3 more responses:
 R, E or H:

 "FS +R++" means that the second message is rejected. Only works with new
 version of the protocol.
 The information is also written in the LOG like :
 MJ B:Message_Bid V:Callsign_Rejecting
 A warning message may be sent to the sending sysop when his message is
 rejected (see INIT.SRV for more info on warning messages).
 The message is not marked as 'F', and still can be forwarded to another BBS

 "FS +H++" means that the second message is held. Only works with new
 version of the protocol.
 The information is also written in the LOG like :
 MH B:Message_Bid V:Callsign_Rejecting
 A warning message may be sent to the sending sysop when his message is
 held (see INIT.SRV for more info on warning messages).

 "FS +E++" means that the second message has a format error. Only works
 with new version of the protocol.
 A warning message may be sent to the sending sysop when his message
 proposal is wrong (see INIT.SRV for more info on warning messages).

 It should interesting to defer a message if you are still receiving it on a
other channel, or if you think that the size is to big, or for another
reason. The message should be proposed again at the next connection.

 FS line MUST have as many +,-,=, R, E, H signs as lines in the proposal.

 When receiving the FS lines, I can send the block of messages. Each message
is made with the title on the first line, the text, and a Ctrl Z in the last
line. The is no blank line between the messages.

 Title of 2nd message
 Text of 2nd message
 .....
 ^Z

 When the other BBS has received all the asked messages, it acknowledges by
sending its proposal, and the system is reversed.

 If it has no message to send, it only sends a line :

 FF

 This line must not to be followed by a F>.

 If the other hand has no message, it sends a line :

 FQ

 and asks for the disconnection.

 Example :
 ---------

 F6FBB                          FC1GHV
 ----------------------------------------------------------------

 Connects FC1GHV

                                Connected

                                [FBB-5.11-FHM$]
                                Bienvenue a Poitiers, Jean-Paul.
                                >

 [FBB-5.11-FHM$]     (F6FBB has the F flag in the SID)
 FB P F6FBB FC1GHV.FFPC.FRA.EU FC1MVP 24657_F6FBB 1345
 FB P FC1CDC F6ABJ F6AXV 24643_F6FBB 5346
 FB B F6FBB FRA FBB 22_456_F6FBB 8548
 F> HH

                                FS +-+ (accepts the 1st and the 3rd).

 Title 1st message
 Text 1st message
 ......
 ^Z
 Title 3rd message
 Text 3rd message
 ......
 ^Z

                                 FB P FC1GHV F6FBB F6FBB 2734_FC1GHV 234
                                 FB B FC1GHV F6FBB FC1CDC 2745_FC1GHV 3524
                                 F> HH

 FS -- (Don't need them, and send immediately the proposal).
 FB P FC1CDC F6ABJ F6AXV 24754_F6FBB 345
 F> HH

                                 FS + (Accepts the message)

 Title message
 Text message
 ......
 ^Z

                                 FF (no more message)

 FB B F6FBB TEST FRA 24654_F6FBB 145
 F> HH

                                 FS + (Accepts the message)

 Title message
 Text message
 ......
 ^Z

                                 FF (still no message)

 FQ (No more message)

 Disconnection of the link.

 In this example, FBB protocol is used as the two BBS were identified by the
F flag in the SID. If F6FBB had sent the SID [FBB-5.11-MH$] when answering
FC1GHV, the protocol should be the standard MBL/RLI.

 All callsigns are only examples !

This page was last updated


text:
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Pin to Board

 <?php echo validation_errors(); ?>

    <?php echo form_open_multipart("feed/pin_to_board", 'id=board_form'); ?>

        Select Board

          <?php
            $array = array();
            foreach($boards as $row)
            {
                $array[$row['name']] = $row['name'];
            }
            echo form_dropdown('board_record',  $array)
          ?>

        <input type="hidden" id="pid" name="pid" value="<?php $pid ?>;" />

  <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
  <a href="<?php echo base_url('index.php/profile/board'); ?>" role="button" class="btn btn-danger">Create Board
  <?php echo form_submit('submit', 'Pin to Board', 'class="btn btn-primary"'); ?>
  <?php echo form_close(); ?>


text:
using Money.Models.Loading;
using Neptuo;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Money.Components
{
    public class PagingContext
    {
        private readonly LoadingContext loading;

        public int CurrentPageIndex { get; private set; }
        public bool HasNextPage { get; private set; } = true;

        public Func<Task<PagingLoadStatus>> LoadPageAsync { get; }

        public PagingContext(Func<Task<PagingLoadStatus>> loadPageAsync, LoadingContext loading)
        {
            Ensure.NotNull(loadPageAsync, "loadPageAsync");
            Ensure.NotNull(loading, "loading");
            LoadPageAsync = loadPageAsync;
            this.loading = loading;
        }

        private void ProcessStatus(PagingLoadStatus status)
        {
            switch (status)
            {
                case PagingLoadStatus.HasNextPage:
                    HasNextPage = true;
                    break;

                case PagingLoadStatus.LastPage:
                    HasNextPage = false;
                    break;

                case PagingLoadStatus.EmptyPage:
                    HasNextPage = false;
                    if (CurrentPageIndex > 0)
                        CurrentPageIndex--;
                    break;

                default:
                    throw Ensure.Exception.NotSupported(status.ToString());
            }
        }

        public async Task NextAsync()
        {
            using (loading.Start())
            {
                if (!HasNextPage)
                    return;

                CurrentPageIndex++;
                var status = await LoadPageAsync();
                ProcessStatus(status);
            }
        }

        public async Task PrevAsync()
        {
            using (loading.Start())
            {
                if (CurrentPageIndex == 0)
                    return;

                CurrentPageIndex--;
                var status = await LoadPageAsync();
                ProcessStatus(status);
            }
        }

        public async Task LoadAsync(int index)
        {
            using (loading.Start())
            {
                CurrentPageIndex = index;
                var status = await LoadPageAsync();
                ProcessStatus(status);
            }
        }
    }
}


text:
package cpup.poke4j.plugin.files;

import cpup.poke4j.plugin.CommandRun;
import cpup.poke4j.plugin.ICommand;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

public class SaveCommand implements ICommand {
	@Override
	public void invoke(CommandRun run) throws Exception {
		String path = run.getArgs().get(0, String.class);
		BufferedWriter writer = new BufferedWriter(new FileWriter(new File(path)));
		run.getBuffer().save(writer);
		writer.close();
	}

	private static SaveCommand instance;

	public static SaveCommand get() {
		if(instance == null) {
			instance = new SaveCommand();
		}
		return instance;
	}
}


text:
{% extends "base.html" %}

{% block content %}

About SmashStats

The application recognizes and sorts players by tag, and associates them with the sets and tournaments they have played in. Once players have been recorded in the database, the program attempts to match all references to them to their tag. Currently, Smashstats only accepts bracket data from Challonge, meaning that no match information can be automatically generated. Additionally, player information about regions, main, and secondary characters requires input from the larger community.

In its current state, SmashStats does not claim to represent a fully comprehensive record of all players' set and tournament histories, but rather is a proof of concept for widespread stats tracking.

If you are interested in this project and would like to contribute, contact the developers at smashstats@gmail.com, or connect with us through our social media accounts.

Features planned for future releases

 Support for more regions

 Tournament data from Liquipedia, as well as match data

Support us! Donations help keep our server running.

    <form class="text-center" action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">
      <input type="hidden" name="cmd" value="_s-xclick">
      <input type="hidden" name="hosted_button_id" value="7SZNGHVFNVF7W">
      <input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">

    </form>

Frequently Asked Questions

Where are you getting this information?

          The app scrapes Challonge and Smashgg brackets and stores information in a database, altogether a completely automated process.

What types of tournament bracket programs do you support?

              Currently, just Challonge and Smashgg, but progress is being made on parsing Liquipedia for detailed match info.

Is tournament bracket data accurate?

              We can only work with whatever is provided on the bracket. If a tournament only has a final bracket, we'd rather process what data we have than exclude it because it lacks completion.

How are ratings calculated?

          Trueskill, which estimates your skill based on who you've won and lost to. Tournament attendance is a slight factor, though a much bigger one for players with very low set counts. Read more about it here

Do tournament placements matter?

            No, they do not. Rating is solely based on who you've won and lost to, and your relative ratings at the time of the set.

Are DQ (disqualification) sets taken into account? How about the margin of victory?

            DQ scores, if reported properly in Challonge (commonly a score of -1 or 0-0), are not taken into account. We do record the set match score, but only the outcome of a set, win or loss, is factored into rankings.

What are the difference between Global and Regional Rankings?

            AS OF 8/12: If you play someone from a different region than you, only your Global trueskill updates, but if you play someone from the same region, only your Region trueskill updates. This holds true regardless of the type or size of the tournament.

How many sets per player are taken into rating?

            Currently, all sets a player has ever played. This is subject to change in the future, to the last (most recent) x number of sets.

Why do some tournaments have placements that suddenly jump into the thousandths?

            Unless it's EVO, those are pool placements. For example, 7th in your pool grants you a 1007th placing. Players are not assigned a pool placement if they advanced to the final bracket, and instead only have a final bracket placement, as only one placement per tournament is permitted.

How do you account for players who may use alternate tags in different tournaments?

          The application automatically can detect different spellings and different team/sponsor information for players, provided a player registers his/her tag. If a player uses completely different tags between tournaments, the application can remember alternate names, but that number will be limited to prevent abuse of the system. Players can also be merged after a tournament is processed.

Seems that I'm listed under multiple tags - I thought the program would automatically do this?

              If you haven't explicitly registered a tag with the program, it won't automatically match tags to it. It will attempt, however, to match players with differences in tag capitalization and team/sponsor information. If you've already told me your main/alternate tags, let me know and I'll fix it and merge the player instances.

Why don't you display sponsor or team tags?

              It helps for the program to consistently recognize and identify players whose tags in bracket may differ from tournament to tournament. It also reduces the need for maintenance whenever a player changes team or sponsor.

How do you deal with people from different regions having the same tag?

              In these instances, their tag will be suffixed by their region's name, i.e. FalcoMaster3000 [NorCal]. As for players in the same region having the same tag, that is probably an issue that should be addressed outside of this app.

There seems to be some missing information on the page. Can I help?

          Yes! Only so much can be done through automation, so info like player's alternate tags, characters, sometimes tournament's dates, and more need to be provided by the community. We can only automatically offer what we scrape from tournament brackets. Please tweet at us or contact us using our media links at the bottom of the page if you can offer any info!

Why do some tournaments take place in 20XX?

            Because they year is... Actually though, those dates are automatically entered if the program can't locate a date for a bracket automatically, so that the community can easily spot them and fix them with the correct info.

Why is my rating so low?

          git gud kid. (But players with a very low amount of played sets tend to ranked very low, and have skill ratings that tend to fluctuate more.)

I think some of my results are not being represented.

             Your region may not be supported, or we lack data for that particular tournament. If not, check the profile page for your tag. If there are tournaments that you've entered that are listed in the database but not on your page, chances are your tag wasn't recognized. You can also try searching for your alternate tags or tournaments you've entered. Let us know if you think there's an issue.

I play in different regions frequently. Which region should I be listed under?

            You should consider yourself as part of the region you currently enter the most tournaments in.

How can I get my region on here?

          If you are a prominent TO in your area, get in contact with us through our email or social media at the bottom of the page

Who are the creators of SmashStats?

          Tonic, a Marth main based in New England, and Wyne, a Falco player studying in SoCal.

{% endblock %}


text:
const assert = require('assert');
const DummyRequest = require('../../utils/DummyRequest');
const MD5Sum = require('../../../lib/s3middleware/MD5Sum').default;
const constants = require('../../../lib/constants');

function consume(stream) {
    stream.on('data', () => { });
}

function testMD5(payload, expectedMD5, done) {
    const dummy = new DummyRequest({}, payload);
    const md5summer = new MD5Sum();
    md5summer.on('hashed', () => {
        assert.strictEqual(md5summer.completedHash, expectedMD5);
        done();
    });
    dummy.pipe(md5summer);
    consume(md5summer);
}

describe('utilities.MD5Sum', () => {
    it('should work on empty request', done => {
        testMD5('', constants.emptyFileMd5, done);
    });

    it('should work on SAY GRRRR!!! request', done => {
        testMD5('SAY GRRRR!!!', '986eb4a201192e8b1723a42c1468fb4e', done);
    });

    it('should work on multiple MiB data stream', done => {
        /*
         * relies on a zero filled buffer and
         * split content in order to get multiple calls of _transform()
         * md5sum computed by hand with:
         * $ dd if=/dev/zero of=/dev/stdout bs=1M count=16 2>/dev/null | md5sum
         */
        const buffer = Buffer.alloc(4 * 1024 * 1024);
        testMD5([buffer, buffer, buffer, buffer],
            '2c7ab85a893283e98c931e9511add182', done);
    });
});


text:
package mkchx.pomelo.sampleapp;

public class ConstKey {

    public static final String KEY_CONNECTION = "connection";
    public static final String KEY_GPS = "permission.gps";

    public static final String KEY_SELECTED = "key.selected";
    public static final String KEY_VENUE = "key.venue";
    public static final String KEY_PHOTO = "key.photo";

    public static final String KEY_MARK_ID = "key.marker.id";
}


text:
require 'open-uri'
require "csv"

def gen_word
  config = CSV.read('game/settings.conf')
  # username = config[0][0]
  difficulty = config[0][1].to_i
  mode = config[0][2]

  if difficulty == 0
      words = open("http://linkedin-reach.hagbpyjegb.us-west-2.elasticbeanstalk.com/words")
  else
      words = open("http://linkedin-reach.hagbpyjegb.us-west-2.elasticbeanstalk.com/words?difficulty=#{difficulty}")
  end

  res_bod = words.read
  words_arr = res_bod.split(' ')
  len = words_arr.length - 1

  if mode == 'word'
      words_arr[rand(0..len)]
  else
      phrase = []
      difficulty = 2 if difficulty == 0 || difficulty == 1
      difficulty.times do
        phrase << words_arr[rand(0..len)]
      end
      phrase.join(' ')
  end
end