text:
HOST_NAME="${1}"
NETMASK="${2}"
NETWORK="${3}"
BROADCAST="${4}"
GATEWAY="${5}"
NAMESERVER="${6}"
PUBLIC_KEY_PATH="${7}"

if [ "${HOST_NAME}" = "" ] || [ "${NETMASK}" = "" ] || [ "${NETWORK}" = "" ] || [ "${BROADCAST}" = "" ] || [ "${GATEWAY}" = "" ] || [ "${NAMESERVER}" = "" ] || [ "${PUBLIC_KEY_PATH}" = "" ]; then
    echo "Usage: ${0} HOST_NAME DOMAIN NETMASK NETWORK BROADCAST GATEWAY NAMESERVER SEARCH_DOMAIN PUBLIC_KEY_PATH"

    exit 1
fi

STATE=$(vbt host show --name cm1 | grep --perl-regexp --only-matching "(?<=state: )[a-z]+")

if [ "${STATE}" = poweroff ]; then
    vbt host start --name "${HOST_NAME}"
    sleep 60
    # TODO: Find a way to check if machine has finished booting with guest additions?
fi

# TODO: USER_NAME is only required to run bootstrap-wrapper-salt.sh.
#USER_NAME=$(sqlite3 "${HOME}/.virtual-box-tools/user.sqlite" "SELECT user_name FROM user WHERE host_name = '${HOST_NAME}' AND user_name != 'root'")
DOMAIN=$(sqlite3 "${HOME}/.virtual-box-tools/user.sqlite" "SELECT domain_name FROM user WHERE host_name = '${HOST_NAME}' AND user_name = 'root'")
# TODO: USER_PASSWORD is only required to run bootstrap-wrapper-salt.sh.
#USER_PASSWORD=$(sqlite3 "${HOME}/.virtual-box-tools/user.sqlite" "SELECT password FROM user WHERE host_name = '${HOST_NAME}' AND user_name = '${USER_NAME}'")
ROOT_PASSWORD=$(sqlite3 "${HOME}/.virtual-box-tools/user.sqlite" "SELECT password FROM user WHERE host_name = '${HOST_NAME}' AND user_name = 'root'")
ADDRESS=$(dig +noall +answer "${HOST_NAME}.${DOMAIN}" | grep "${HOST_NAME}.${DOMAIN}" | awk '{ print $5 }')
bin/configure-network.sh "${HOST_NAME}" "${ROOT_PASSWORD}" "${ADDRESS}" "${NETMASK}" "${NETWORK}" "${BROADCAST}" "${GATEWAY}" "${NAMESERVER}" "${DOMAIN}"
vbt host stop --name "${HOST_NAME}" --wait
# TODO: Something prevents the network from shutting down orderly, taking 90 seconds extra. Disable DHCP if possible.
vbt host start --name "${HOST_NAME}" --wait
# TODO: If host existed before, this will likely fail because of the known_hosts entry being different.
bin/bootstrap-wrapper.sh "${HOST_NAME}" "${PUBLIC_KEY_PATH}"
#PROXY=""
#SALT_MASTER=""
#MINION_IDENTIFIER=""
#bin/bootstrap-wrapper-salt.sh "${USER_NAME}@${HOST_NAME}.${DOMAIN}" "${USER_PASSWORD}" "${ROOT_PASSWORD}" "${SALT_MASTER}" "${MINION_IDENTIFIER}" "${PROXY}"


text:
package io.reactivex.netty.protocol.http.websocket;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.reactivex.netty.client.ClientMetricsEvent;
import io.reactivex.netty.metrics.MetricEventsSubject;

/**
 * @author Tomasz Bak
 */
public interface WebSocketClientMetricsHandlers {

    class ClientReadMetricsHandler extends ChannelInboundHandlerAdapter {

        private final MetricEventsSubject<ClientMetricsEvent<?>> eventsSubject;

        public ClientReadMetricsHandler(MetricEventsSubject<ClientMetricsEvent<?>> eventsSubject) {
            this.eventsSubject = eventsSubject;
        }

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            eventsSubject.onEvent(WebSocketClientMetricsEvent.WEB_SOCKET_FRAME_READS);
            super.channelRead(ctx, msg);
        }
    }

    class ClientWriteMetricsHandler extends ChannelOutboundHandlerAdapter {

        private final MetricEventsSubject<ClientMetricsEvent<?>> eventsSubject;

        public ClientWriteMetricsHandler(MetricEventsSubject<ClientMetricsEvent<?>> eventsSubject) {
            this.eventsSubject = eventsSubject;
        }

        @Override
        public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
            eventsSubject.onEvent(WebSocketClientMetricsEvent.WEB_SOCKET_FRAME_WRITES);
            super.write(ctx, msg, promise);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package project.jyland.category.dao;

import java.util.List;

import project.jyland.board.model.JYCat;

public interface CategoryDao {

	List<JYCat> getCatList();
	void createCategory(JYCat cat);
	List<JYCat> getPopCatList();

}


text:
<?php
namespace Mongolid\Model;

use Exception;
use Illuminate\Support\Str;
use Mongolid\Container\Container;
use stdClass;

/**
 * This trait adds attribute getter, setters and also a useful
 * `fill` method that can be used with $fillable and $guarded
 * properties to make sure that only the correct attributes
 * will be set.
 *
 * It is supposed to be used on model classes in general
 *
 * @mixin HasAttributesInterface
 */
trait HasAttributesTrait
{
    /**
     * Once you put at least one string in this array, only
     * the attributes specified here will be changed
     * with the setDocumentAttribute method.
     *
     * @var array
     */
    protected $fillable = [];

    /**
     * The attributes that are not mass assignable. The opposite
     * to the fillable array;.
     *
     * @var array
     */
    protected $guarded = [];

    /**
     * Check if model should mutate attributes checking
     * the existence of a specific method on model
     * class. Default is false.
     *
     * @var bool
     */
    protected $mutable = false;

    /**
     * Store mutable attribute values to work with `&__get()`.
     *
     * @var array
     */
    protected $mutableCache = [];

    /**
     * The model's attributes.
     *
     * @var array
     */
    private $attributes = [];

    /**
     * The model attribute's original state.
     *
     * @var array
     */
    private $originalAttributes = [];

    /**
     * {@inheritdoc}
     */
    public static function fill(
        array $input,
        HasAttributesInterface $object = null,
        bool $force = false
    ): HasAttributesInterface {
        if (!$object) {
            $object = Container::make(static::class);
        }

        if ($object instanceof PolymorphableModelInterface) {
            $class = $object->polymorph(array_merge($object->getDocumentAttributes(), $input));

            if ($class !== get_class($object)) {
                $originalAttributes = $object->getDocumentAttributes();
                $object = new $class();

                foreach ($originalAttributes as $key => $value) {
                    $object->setDocumentAttribute($key, $value);
                }
            }
        }

        foreach ($input as $key => $value) {
            if ($force
                || ((!$object->fillable || in_array($key, $object->fillable)) && !in_array($key, $object->guarded))) {
                if ($value instanceof stdClass) {
                    $value = json_decode(json_encode($value), true); // cast to array
                }

                $object->setDocumentAttribute($key, $value);
            }
        }

        return $object;
    }

    /**
     * {@inheritdoc}
     */
    public function hasDocumentAttribute(string $key): bool
    {
        return !is_null($this->getDocumentAttribute($key));
    }

    /**
     * {@inheritdoc}
     */
    public function &getDocumentAttribute(string $key)
    {
        if ($this->mutable && $this->hasMutatorMethod($key, 'get')) {
            $this->mutableCache[$key] = $this->{$this->buildMutatorMethod($key, 'get')}();

            return $this->mutableCache[$key];
        }

        if (array_key_exists($key, $this->attributes)) {
            return $this->attributes[$key];
        }

        if (!method_exists(self::class, $key) && method_exists($this, $key)) {
            return $this->getRelationResults($key);
        }

        $this->attributes[$key] = null;

        return $this->attributes[$key];
    }

    /**
     * {@inheritdoc}
     */
    public function getDocumentAttributes(): array
    {
        foreach ($this->attributes as $field => $value) {
            if (null === $value) {
                $this->cleanDocumentAttribute($field);
            }
        }

        return $this->attributes ?? [];
    }

    /**
     * {@inheritdoc}
     */
    public function cleanDocumentAttribute(string $key)
    {
        unset($this->attributes[$key]);

        if ($this->hasFieldRelation($key)) {
            $this->unsetRelation($this->getFieldRelation($key));
        }
    }

    /**
     * {@inheritdoc}
     */
    public function setDocumentAttribute(string $key, $value)
    {
        if ($this->mutable && $this->hasMutatorMethod($key, 'set')) {
            $value = $this->{$this->buildMutatorMethod($key, 'set')}($value);
        }

        if (null === $value) {
            $this->cleanDocumentAttribute($key);

            return;
        }

        $this->attributes[$key] = $value;

        if ($this->hasFieldRelation($key)) {
            $this->unsetRelation($this->getFieldRelation($key));
        }
    }

    /**
     * {@inheritdoc}
     */
    public function syncOriginalDocumentAttributes()
    {
        try {
            $this->originalAttributes = unserialize(serialize($this->getDocumentAttributes()));
        } catch (Exception $e) {
            $this->originalAttributes = $this->getDocumentAttributes();
        }
    }

    /**
     * {@inheritdoc}
     */
    public function getOriginalDocumentAttributes(): array
    {
        return $this->originalAttributes;
    }

    /**
     * {@inheritdoc}
     */
    public function toArray(): array
    {
        return $this->getDocumentAttributes();
    }

    /**
     * Verify if model has a mutator method defined.
     *
     * @param string $key    attribute name
     * @param string $prefix method prefix to be used (get, set)
     */
    protected function hasMutatorMethod(string $key, $prefix): bool
    {
        $method = $this->buildMutatorMethod($key, $prefix);

        return method_exists($this, $method);
    }

    /**
     * Create mutator method pattern.
     *
     * @param string $key    attribute name
     * @param string $prefix method prefix to be used (get, set)
     */
    protected function buildMutatorMethod(string $key, string $prefix): string
    {
        return $prefix.Str::studly($key).'DocumentAttribute';
    }
}


text:
#import "NSObject.h"

@class NSMutableArray, NSSet, NSString;

@interface IBCustomClassSuggestionsProvider : NSObject
{
    NSString *currentAutoCompletingComboBoxDataSourceBaseClassName;
    unsigned int dataSourceQueryGeneration;
    NSMutableArray *pendingHandlers;
    NSSet *validResults;
    BOOL queriesAreInFlight;
    id <IBCustomClassSuggestionsProviderDelegate> _delegate;
}

@property __weak id <IBCustomClassSuggestionsProviderDelegate> delegate; // @synthesize delegate=_delegate;
- (void).cxx_destruct;
- (void)suggestCompletionsForBaseclass:(id)arg1 fromDocument:(id)arg2 completionHandler:(id)arg3;
- (void)setQueriesAreInFlight:(BOOL)arg1;
- (void)notifyHandlersOfResults:(id)arg1;
- (id)init;

@end


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

{% block script1 %}

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="Power Smart Energy Management Platform">
    <meta name="author" content="Jiayu Chen">

    <title>Power Smart Energy Management Platform</title>

    <link href="/assets/css/bootstrap.min.css" rel="stylesheet">

    <link href="/assets/css/plugins/metisMenu/metisMenu.min.css" rel="stylesheet">

    <link href="/assets/css/plugins/timeline.css" rel="stylesheet">

    <link href="/assets/css/sb-admin-2.css" rel="stylesheet">
    <link href="/assets/css/customize.css" rel="stylesheet">
    <link href="/assets/css/mail.css" rel="stylesheet">

    <link href="/assets/css/plugins/morris.css" rel="stylesheet">

    <link href="/assets/font-awesome-4.1.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">

{% endblock %}

{% block content %}

Inbox

Outbox

                <form role="form" method="post" action="/accounts/internalmail/compose/submit">
                    {% csrf_token %}

New Message

From:  {{ profiles.user.username}}  ({{ profiles.user.email}})

To:

                    <input class="form-control" id="id_toname" name="toname" type="text" placehoder="To other user of PSEP" style="width: 60%;">

Title

                    <input class="form-control" id="id_Title" name="Title" type="text" placehoder="Message Title" style="width: 60%;">

Message
<textarea class="form-control" id="id_Content" name="Content" placehoder="Add your message"></textarea>

                    <button type="submit" class="btn btn-success pull-left" value="submit" >submit</button>

                </form>

        {% if request.session.message %}
            {% if request.session.message == "New message has been sent !" %}

                   <button type="button" class="close" data-dismiss="alert" aria-hidden="true">
                        ×
                   </button>
                   {{ request.session.message }}

            {% elif request.session.message == "The message is failed, please check if the user is exiting !" %}

                   <button type="button" class="close" data-dismiss="alert" aria-hidden="true">
                        ×
                   </button>
                   {{ request.session.message }}

            {% else %}
            {% endif %}
        {% endif %}

{% endblock %}

{% block script2 %}
{% endblock %}


text:
import { APP_CLIENT_IDS } from '../constants';
import { HTTP_ERROR_CODES } from '../errors';
import { AuthenticationCredentialsPayload } from '../webauthn/interface';

export const PASSWORD_WRONG_ERROR = 8002;

export const auth = (data: any) => ({
    method: 'post',
    url: 'auth',
    data,
    ignoreHandler: [HTTP_ERROR_CODES.TOO_MANY_REQUESTS],
});

export const auth2FA = (data: { TwoFactorCode: string } | { FIDO2: AuthenticationCredentialsPayload }) => ({
    method: 'post',
    url: 'auth/2fa',
    data: data,
});

export const authJwt = (data: { Token: String; ClientSecret?: String }) => ({
    method: 'post',
    url: 'auth/jwt',
    data,
});

export const revoke = () => ({
    method: 'delete',
    url: 'auth',
});

interface RefreshArgs {
    RefreshToken: string;
    RedirectURI?: string;
}

export const setRefreshCookies = (data?: RefreshArgs) => {
    const config = {
        method: 'post',
        url: 'auth/refresh',
    };
    if (!data) {
        return config;
    }
    return {
        ...config,
        data: {
            ResponseType: 'token',
            GrantType: 'refresh_token',
            RefreshToken: data.RefreshToken,
            RedirectURI: data.RedirectURI || 'https://protonmail.com',
        },
    };
};

interface CookiesArgs {
    UID: string;
    RefreshToken: string;
    State: string;
    RedirectURI?: string;
    Persistent?: boolean;
}

export const setCookies = ({
    UID,
    RefreshToken,
    State,
    RedirectURI = 'https://protonmail.com',
    Persistent = false,
}: CookiesArgs) => ({
    method: 'post',
    url: 'auth/cookies',
    data: {
        UID,
        ResponseType: 'token',
        GrantType: 'refresh_token',
        RefreshToken,
        RedirectURI,
        Persistent: Number(Persistent),
        State,
    },
});

export const getLocalKey = () => ({
    method: 'get',
    url: 'auth/sessions/local/key',
});
export const setLocalKey = (Key: string) => ({
    method: 'put',
    url: 'auth/sessions/local/key',
    data: {
        Key,
    },
});
export const pushForkSession = (data: {
    Payload?: string;
    ChildClientID: APP_CLIENT_IDS;
    Independent: 0 | 1;
    Selector?: string;
    UserCode?: string;
}) => ({
    method: 'post',
    url: 'auth/sessions/forks',
    data,
});

export const pullForkSession = (selector: string) => ({
    method: 'get',
    url: `auth/sessions/forks/${selector}`,
});

export const getLocalSessions = () => ({
    method: 'get',
    url: `auth/sessions/local`,
});

export const getInfo = (Username?: string) => ({
    method: 'post',
    url: 'auth/info',
    data: Username ? { Username } : undefined,
});

export const getModulus = () => ({
    method: 'get',
    url: 'auth/modulus',
});

export const querySessions = () => ({
    method: 'get',
    url: 'auth/sessions',
});

export const revokeOtherSessions = () => ({
    method: 'delete',
    url: 'auth/sessions',
});

export const revokeSession = (UID: string | number) => ({
    method: 'delete',
    url: `auth/sessions/${UID}`,
});

export const queryScopes = () => ({
    method: 'get',
    url: 'auth/scopes',
});

export const getMnemonicAuthInfo = (Username?: string) => ({
    method: 'post',
    url: 'auth/v4/mnemonic/info',
    data: Username ? { Username } : undefined,
});

export const authMnemonic = (Username?: string) => ({
    method: 'post',
    url: 'auth/v4/mnemonic',
    data: { Username },
    ignoreHandler: [HTTP_ERROR_CODES.TOO_MANY_REQUESTS],
});


text:
We really like contributions and bug reports, in fact the project wouldn't have got to this stage without them.
We do have a few guidelines to bear in mind.

## Community

We have two Slack channels for the Prototype kit. You'll need a government email address to join them.

* [Slack channel for users of the prototype kit](https://ukgovernmentdigital.slack.com/messages/prototype-kit/)
* [Slack channel for developers of the prototype kit](https://ukgovernmentdigital.slack.com/messages/prototype-kit-dev/)

## Raising bugs

When raising bugs please explain the issue in good detail and provide a guide to how to replicate it.
When describing the bug it's useful to follow the format:

- what you did
- what you expected to happen
- what happened

## Suggesting features

Please raise feature requests as issues before contributing any code.

This ensures they are discussed properly before any time is spent on them.

## GOV.UK Elements

The project contains code taken from the [GOV.UK Elements](https://github.com/alphagov/govuk_elements/) project.
Please check that any issues related to that code are raised with that project, not this one.

## Contributing code

### Indentation and whitespace

Your JavaScript code should pass [linting](docs/linting.md).

For anything else, maintain 2-space, soft-tabs only indentation. No trailing whitespace.

### Versioning

Follow the guidelines on [semver.org](http://semver.org/) for assigning version
numbers.

Versions should only be changed in a commit of their own, in a pull request of
their own. This alerts team members to the new version and allows for
last-minute scrutiny before the new version is released. Also, by raising a
separate pull request, we avoid version number conflicts between feature
branches.

### Commit hygiene

Please see our [git style guide](https://github.com/alphagov/styleguides/blob/master/git.md)
which describes how we prefer git history and commit messages to read.


text:
import warnings

from django import forms
from django.utils.translation import ugettext_lazy as _

from django.contrib.auth import authenticate

UNMASKED_DIGITS_TO_SHOW = 6

mask_password = lambda p: "%s%s" % (p[:UNMASKED_DIGITS_TO_SHOW], "*" * max(len(p) - UNMASKED_DIGITS_TO_SHOW, 0))

# Originally from django.contrib.auth.forms
class AuthenticationForm(forms.Form):
    """
    Base class for authenticating users. Extend this to get a form that accepts
    username/password logins.
    """
    username = forms.CharField(max_length=30)
    password = forms.CharField(label=_("Password"), widget=forms.PasswordInput)

    error_messages = {
        'invalid_login': _("Please enter a correct username and password. "
                           "Note that both fields are case-sensitive."),
        'inactive': _("This account is inactive."),
    }

    def __init__(self, request=None, *args, **kwargs):
        """
        If request is passed in, the form will validate that cookies are
        enabled. Note that the request (a HttpRequest object) must have set a
        cookie with the key TEST_COOKIE_NAME and value TEST_COOKIE_VALUE before
        running this validation.
        """
        self.request = request
        self.user_cache = None
        super(AuthenticationForm, self).__init__(*args, **kwargs)

        self.fields['username'].label = 'User Name'

    def clean(self):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')

        if username and password:
            #  Now -- instead we use authDrupal
            self.user_cache = authenticate(username=username,
                                           password=password)
            if self.user_cache is None:
                raise forms.ValidationError(
                    self.error_messages['invalid_login'],
                    code='invalid_login',
                    params={'username': self.username_field.verbose_name},
                )
            elif not self.user_cache.is_active:
                raise forms.ValidationError(
                    self.error_messages['inactive'],
                    code='inactive',
                )

        return self.cleaned_data

    def check_for_test_cookie(self):
        warnings.warn("check_for_test_cookie is deprecated; ensure your login "
                "view is CSRF-protected.", DeprecationWarning)

    def get_user_id(self):
        if self.user_cache:
            return self.user_cache.id
        return None

    def get_user(self):
        return self.user_cache


text:
'use strict';

const mongoose = require('mongoose'),
    BlueBird = require('bluebird'),
    Promise = BlueBird,
    getConfig = require('../config/get_config');

mongoose.connectAsync = Promise.promisify(mongoose.connect);

let initialized = false,
    mongoosePromise;

function initialize(env, options) {
    options = options || {};
    if(!initialized) {
        console.log('dbInit');
        const config = getConfig(env);
        initialized = true;
        mongoosePromise = mongoose.connectAsync(config.connectionString, options);
        mongoose.Promise = BlueBird;
    }
    return mongoosePromise;
}

module.exports = initialize;


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ChangeListManager">
    <list default="true" id="e33ab985-8991-41c3-86cd-49073656f473" name="Default" comment="" />
    <ignored path="DLTutorial.iws" />
    <ignored path=".idea/workspace.xml" />
    <option name="EXCLUDED_CONVERTED_TO_IGNORED" value="true" />
    <option name="TRACKING_ENABLED" value="true" />
    <option name="SHOW_DIALOG" value="false" />
    <option name="HIGHLIGHT_CONFLICTS" value="true" />
    <option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
    <option name="LAST_RESOLUTION" value="IGNORE" />
  </component>
  <component name="ChangesViewManager" flattened_view="true" show_ignored="false" />
  <component name="CreatePatchCommitExecutor">
    <option name="PATCH_PATH" value="" />
  </component>
  <component name="ExecutionTargetManager" SELECTED_TARGET="default_target" />
  <component name="FavoritesManager">
    <favorites_list name="DLTutorial" />
  </component>
  <component name="Git.Settings">
    <option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
  </component>
  <component name="ProjectFrameBounds">
    <option name="y" value="23" />
    <option name="width" value="1412" />
    <option name="height" value="772" />
  </component>
  <component name="ProjectLevelVcsManager" settingsEditedManually="false">
    <OptionsSetting value="true" id="Add" />
    <OptionsSetting value="true" id="Remove" />
    <OptionsSetting value="true" id="Checkout" />
    <OptionsSetting value="true" id="Update" />
    <OptionsSetting value="true" id="Status" />
    <OptionsSetting value="true" id="Edit" />
    <ConfirmationsSetting value="0" id="Add" />
    <ConfirmationsSetting value="0" id="Remove" />
  </component>
  <component name="ProjectView">
    <navigator currentView="ProjectPane" proportions="" version="1">
      <flattenPackages />
      <showMembers />
      <showModules />
      <showLibraryContents />
      <hideEmptyPackages />
      <abbreviatePackageNames />
      <autoscrollToSource />
      <autoscrollFromSource />
      <sortByType />
      <manualOrder />
      <foldersAlwaysOnTop value="true" />
    </navigator>
    <panes>
      <pane id="Scratches" />
      <pane id="ProjectPane">
        <subPane>
          <PATH>
            <PATH_ELEMENT>
              <option name="myItemId" value="DLTutorial" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
            </PATH_ELEMENT>
          </PATH>
          <PATH>
            <PATH_ELEMENT>
              <option name="myItemId" value="DLTutorial" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="DLTutorial" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
            </PATH_ELEMENT>
          </PATH>
        </subPane>
      </pane>
      <pane id="Scope" />
    </panes>
  </component>
  <component name="PropertiesComponent">
    <property name="settings.editor.selected.configurable" value="com.jetbrains.python.configuration.PyActiveSdkModuleConfigurable" />
    <property name="settings.editor.splitter.proportion" value="0.2" />
    <property name="last_opened_file_path" value="/opt/local/bin/python" />
  </component>
  <component name="RunManager">
    <configuration default="true" type="CompoundRunConfigurationType" factoryName="Compound Run Configuration">
      <method />
    </configuration>
    <configuration default="true" type="PythonConfigurationType" factoryName="Python">
      <option name="INTERPRETER_OPTIONS" value="" />
      <option name="PARENT_ENVS" value="true" />
      <envs>
        <env name="PYTHONUNBUFFERED" value="1" />
      </envs>
      <option name="SDK_HOME" value="" />
      <option name="WORKING_DIRECTORY" value="" />
      <option name="IS_MODULE_SDK" value="false" />
      <option name="ADD_CONTENT_ROOTS" value="true" />
      <option name="ADD_SOURCE_ROOTS" value="true" />
      <module name="" />
      <option name="SCRIPT_NAME" value="" />
      <option name="PARAMETERS" value="" />
      <option name="SHOW_COMMAND_LINE" value="false" />
      <method />
    </configuration>
    <configuration default="true" type="docs" factoryName="Docutils task">
      <option name="INTERPRETER_OPTIONS" value="" />
      <option name="PARENT_ENVS" value="true" />
      <envs />
      <option name="SDK_HOME" value="" />
      <option name="WORKING_DIRECTORY" value="" />
      <option name="IS_MODULE_SDK" value="false" />
      <option name="ADD_CONTENT_ROOTS" value="true" />
      <option name="ADD_SOURCE_ROOTS" value="true" />
      <module name="" />
      <option name="docutils_input_file" value="" />
      <option name="docutils_output_file" value="" />
      <option name="docutils_params" value="" />
      <option name="docutils_task" value="" />
      <option name="docutils_open_in_browser" value="false" />
      <method />
    </configuration>
    <configuration default="true" type="tests" factoryName="Unittests">
      <option name="INTERPRETER_OPTIONS" value="" />
      <option name="PARENT_ENVS" value="true" />
      <envs />
      <option name="SDK_HOME" value="" />
      <option name="WORKING_DIRECTORY" value="" />
      <option name="IS_MODULE_SDK" value="false" />
      <option name="ADD_CONTENT_ROOTS" value="true" />
      <option name="ADD_SOURCE_ROOTS" value="true" />
      <module name="" />
      <option name="SCRIPT_NAME" value="" />
      <option name="CLASS_NAME" value="" />
      <option name="METHOD_NAME" value="" />
      <option name="FOLDER_NAME" value="" />
      <option name="TEST_TYPE" value="TEST_SCRIPT" />
      <option name="PATTERN" value="" />
      <option name="USE_PATTERN" value="false" />
      <option name="PUREUNITTEST" value="true" />
      <option name="PARAMS" value="" />
      <option name="USE_PARAM" value="false" />
      <method />
    </configuration>
  </component>
  <component name="ShelveChangesManager" show_recycled="false" />
  <component name="TaskManager">
    <task active="true" id="Default" summary="Default task">
      <changelist id="e33ab985-8991-41c3-86cd-49073656f473" name="Default" comment="" />
      <created>1499434455408</created>
      <option name="number" value="Default" />
      <updated>1499434455408</updated>
    </task>
    <servers />
  </component>
  <component name="ToolWindowManager">
    <frame x="0" y="23" width="1412" height="772" extended-state="0" />
    <editor active="false" />
    <layout>
      <window_info id="Project" active="true" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="0" side_tool="false" content_ui="combo" />
      <window_info id="TODO" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="6" side_tool="false" content_ui="tabs" />
      <window_info id="Event Log" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="7" side_tool="true" content_ui="tabs" />
      <window_info id="Python Console" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" />
      <window_info id="Version Control" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" />
      <window_info id="Structure" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
      <window_info id="Terminal" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" />
      <window_info id="Favorites" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="2" side_tool="true" content_ui="tabs" />
      <window_info id="Cvs" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="4" side_tool="false" content_ui="tabs" />
      <window_info id="Message" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
      <window_info id="Commander" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.4" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
      <window_info id="Inspection" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.4" sideWeight="0.5" order="5" side_tool="false" content_ui="tabs" />
      <window_info id="Run" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="2" side_tool="false" content_ui="tabs" />
      <window_info id="Hierarchy" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="2" side_tool="false" content_ui="combo" />
      <window_info id="Find" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
      <window_info id="Ant Build" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
      <window_info id="Debug" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.4" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" />
    </layout>
  </component>
  <component name="VcsContentAnnotationSettings">
    <option name="myLimit" value="2678400000" />
  </component>
  <component name="XDebuggerManager">
    <breakpoint-manager />
    <watches-manager />
  </component>
</project>


text:
import Ember from 'ember';
import { initialize } from '../../../initializers/raygun-setup';
import { module, test } from 'qunit';

var container, application;

module('RaygunSetupInitializer', {
  beforeEach: function() {
    Ember.run(function() {
      application = Ember.Application.create();
      container = application.__container__;
      application.deferReadiness();
    });
  }
});

test('should print a message and return if no raygun config', function(assert) {

  var oldLog = window.console.log;
  window.console = {
    log: function(message) {
      this.loggedMessage = message;
    }
  };

  var result = initialize(container, application);

  assert.ok(!result);
  assert.equal("Please set your Raygun config in environment.js", window.console.loggedMessage);
});

test('should set Raygun up if config provided', function(assert) {
  console.log(window.Raygun.apiKey);
  assert.ok(window.Raygun);
  // application.config = {
  //   raygun: {
  //     apiKey: "LOL"
  //   },
  //   environment: "production"
  // };

  // var result = initialize(container, application);
  // assert.ok(result);
  // assert.equal("LOL", window.Raygun.apiKey);
});


text:
package softuniGallery.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import softuniGallery.entity.ImageAlbum;

public interface ImageRepository extends JpaRepository<ImageAlbum, Integer> {

}


text:
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
                android:oneshot="false">
    <item
        android:drawable="@drawable/record_animate_01"
        android:duration="200" />

    <item
        android:drawable="@drawable/record_animate_02"
        android:duration="200" />
    <item
        android:drawable="@drawable/record_animate_03"
        android:duration="200" />
    <item
        android:drawable="@drawable/record_animate_04"
        android:duration="200" />
    <item
        android:drawable="@drawable/record_animate_05"
        android:duration="200" />
    <item
        android:drawable="@drawable/record_animate_06"
        android:duration="200" />
    <item
        android:drawable="@drawable/record_animate_07"
        android:duration="200" />
    <item
        android:drawable="@drawable/record_animate_08"
        android:duration="200" />

    <item
        android:drawable="@drawable/record_animate_09"
        android:duration="200" />
    <item
        android:drawable="@drawable/record_animate_10"
        android:duration="200" />
    <item
        android:drawable="@drawable/record_animate_11"
        android:duration="200" />
    <item
        android:drawable="@drawable/record_animate_12"
        android:duration="200" />
    <item
        android:drawable="@drawable/record_animate_13"
        android:duration="200" />
    <item
        android:drawable="@drawable/record_animate_14"
        android:duration="200" />

</animation-list>


text:
package cgeo.geocaching.filters.core;

import cgeo.geocaching.log.LogType;
import cgeo.geocaching.models.Geocache;
import cgeo.geocaching.storage.SqlBuilder;
import cgeo.geocaching.utils.CollectionStream;
import cgeo.geocaching.utils.expressions.ExpressionConfig;

import java.util.Arrays;

import org.apache.commons.lang3.BooleanUtils;

public  class FavoritesGeocacheFilter extends NumberRangeGeocacheFilter<Float> {

    private static final String CONFIG_KEY_PERCENTAGE = "percentage";

    private boolean percentage = false;

    public FavoritesGeocacheFilter() {
        super(Float::valueOf);
    }

    public boolean isPercentage() {
        return percentage;
    }

    public void setPercentage(final boolean percentage) {
        this.percentage = percentage;
    }

    @Override
    public Float getValue(final Geocache cache) {
        if (!percentage || cache.getFavoritePoints() == 0) {
            return (float) cache.getFavoritePoints();
        }
        final int rawFindsCount = cache.getFindsCount();

        return rawFindsCount == 0 ? null : ((float) cache.getFavoritePoints()) / rawFindsCount;
    }

    @Override
    protected String getSqlColumnName() {
        return "favourite_cnt";
    }

    @Override
    public void addToSql(final SqlBuilder sqlBuilder) {
        if (!percentage) {
            super.addToSql(sqlBuilder);
        } else {
            final String newTableId = sqlBuilder.getNewTableId();
            sqlBuilder.addJoin("LEFT JOIN (" + getGroupClause(sqlBuilder.getNewTableId()) + ") " + newTableId + " ON " + sqlBuilder.getMainTableId() + ".geocode = " + newTableId + ".geocode");
            addRangeToSqlBuilder(sqlBuilder, getFavoritePercentageStatement(sqlBuilder.getMainTableId() + ".favourite_cnt", newTableId + ".find_count"));
        }
    }

    private static String getGroupClause(final String tid) {
        final String logIds = CollectionStream.of(Arrays.asList(LogType.getFoundLogIds())).toJoinedString(",");
        return "select " + tid + ".geocode, sum(count) as find_count from cg_logCount " + tid + " where " + tid + ".type in (" + logIds + ") group by " + tid + ".geocode";
    }

    private static String getFavoritePercentageStatement(final String favCountColumn, final String findCountColumn) {
        return "(CAST(" + favCountColumn + " AS REAL) / CASE WHEN " + findCountColumn + " IS NULL THEN 1 WHEN " + findCountColumn + " = 0 THEN 1 ELSE " + findCountColumn + " END)";
    }

    @Override
    public void setConfig(final ExpressionConfig config) {
        super.setConfig(config);
        percentage = config.getFirstValue(CONFIG_KEY_PERCENTAGE, false, BooleanUtils::toBoolean);
    }

    @Override
    public ExpressionConfig getConfig() {
        final ExpressionConfig config = super.getConfig();
        config.putList(CONFIG_KEY_PERCENTAGE, Boolean.toString(percentage));
        return config;
    }

    @Override
    protected String getUserDisplayableConfig() {
        if (percentage) {
            return (getMinRangeValue() == null ? "*" : (Math.round(getMinRangeValue() * 100)) + "%") + "-" + (getMaxRangeValue() == null ? "*" : (Math.round(getMaxRangeValue() * 100)) + "%");
        }
        return super.getUserDisplayableConfig();
    }

}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_wchar_t_snprintf_84_goodG2B.cpp
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805.string.label.xml
Template File: sources-sink-84_goodG2B.tmpl.cpp
*/
/*
 * @description
 * CWE: 122 Heap Based Buffer Overflow
 * BadSource:  Allocate using new[] and set data pointer to a small buffer
 * GoodSource: Allocate using new[] and set data pointer to a large buffer
 * Sinks: swprintf
 *    BadSink : Copy string to data using swprintf
 * Flow Variant: 84 Data flow: data passed to class constructor and destructor by declaring the class object on the heap and deleting it after use
 *
 * */
#ifndef OMITGOOD

#include "std_testcase.h"
#include "CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_wchar_t_snprintf_84.h"

#ifdef _WIN32
#define SNPRINTF _snwprintf
#else
#define SNPRINTF swprintf
#endif

namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_wchar_t_snprintf_84
{
CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_wchar_t_snprintf_84_goodG2B::CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_wchar_t_snprintf_84_goodG2B(wchar_t * dataCopy)
{
    data = dataCopy;
    /* FIX: Allocate using new[] and point data to a large buffer that is at least as large as the large buffer used in the sink */
    data = new wchar_t[100];
    data[0] = L'\0'; /* null terminate */
}

CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_wchar_t_snprintf_84_goodG2B::~CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_wchar_t_snprintf_84_goodG2B()
{
    {
        wchar_t source[100];
        wmemset(source, L'C', 100-1); /* fill with L'C's */
        source[100-1] = L'\0'; /* null terminate */
        /* POTENTIAL FLAW: Possible buffer overflow if source is larger than data */
        SNPRINTF(data, 100, L"%s", source);
        printWLine(data);
        delete [] data;
    }
}
}
#endif /* OMITGOOD */


text:
package com.boldradius.astrolabe.client.components

import com.boldradius.astrolabe.client.components.graph.Graph
import com.boldradius.astrolabe.client.modules.{ Mode, RxObserver }
import com.boldradius.astrolabe.client.services.{ ClusterService, ClusterService$ }
import com.boldradius.astrolabe.http.DiscoveredCluster
import japgolly.scalajs.react.extra.OnUnmount
import japgolly.scalajs.react._
import japgolly.scalajs.react.vdom.all._
object ClusterNodeGraphComponent {

  case class Props(store: ClusterService, mode: Mode)

  case class State(cluster: Option[DiscoveredCluster])

  class Backend(t: BackendScope[Props, State]) extends RxObserver(t) {
    def mounted(): Unit = {
      react(t.props.store.getSelectedCluster, updateCluster)
    }

    def updateCluster(maybeCluster: Option[DiscoveredCluster]) = {

      val current = t.state.cluster

      current match {
        case None => maybeCluster.fold[Unit]({})(c => t.modState(_.copy(cluster = maybeCluster)))
        case Some(c) => maybeCluster.fold[Unit](t.modState(_.copy(cluster = None)))(newC =>
          if (c.system != newC.system) {
            t.modState(_.copy(cluster = maybeCluster))
          })
      }

    }

  }

  def component = ReactComponentB[Props]("ClusterNodeGraph")
    .initialStateP(P => {
      State(P.store.getSelectedCluster())
    }).backend(new Backend(_))
    .render((P, S, B) => {
      S.cluster.fold(span(""))(cluster => {
        div(
          Graph(cluster.system, P.mode, 1400, 900, P.store, false)
        )
      })
    }).componentDidMount(_.backend.mounted())
    .configure(OnUnmount.install)
    .build

  def apply(store: ClusterService, mode: Mode) = component(Props(store, mode))

}


text:
package com.badlydrawngames.veryangryrobots;

public interface ISubmitScores {
	void submitScore (final int score);
}


text:
@interface BUImage : NSObject <NSCoding>

// image address URL
@property (nonatomic, copy) NSString *imageURL;

// image width
@property (nonatomic, assign) float width;

// image height
@property (nonatomic, assign) float height;

- (instancetype)initWithDictionary:(NSDictionary *)dic;

@end


text:
My [GitHub Pages Blog](https://huashengwang1989.github.io "カセイちゃんの動物園") built on [Hexo](https://hexo.io).

As GitHub pages requrie `master` branch for deploy, please proceed to `develop` branch for sources.

## Kasei Theme
Kasei theme is built based on [Bootstrap](http://getbootstrap.com).
Please see the blog folder for the theme.

### Updated 2017.7.18
Optimized for mobile.


text:
FROM enmarche-common

CMD ["supervisord", "-c", "/etc/supervisor/conf.d/supervisord.conf"]


text:
package com.eatlappscontest.kks.model;

import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.eatlappscontest.kks.spec.StaticObject;

public interface IStaticObject {

	StaticObject getType();

	Rectangle getBounds();

	Vector2 getPosition();

	long getSpawnTime();

	Texture getTexture();

	long getLifeTime();

	boolean isBlur();

	void draw(SpriteBatch batch, float ppuX, float ppuY, float delta);
}


text:
<!doctype html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>CMsgGCRoutingInfo_RoutingMethod | demofile</title>
	<meta name="description" content="Documentation for demofile">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="../assets/css/main.css">

						Search
						<input id="tsd-search-field" type="text" />

Preparing search index...

The search index is not available

					demofile

						Options

								All

Public

Public/Protected

All

							<input type="checkbox" id="tsd-filter-inherited" checked />
							Inherited
							<input type="checkbox" id="tsd-filter-externals" checked />
							Externals
							<input type="checkbox" id="tsd-filter-only-exported" />
							Only exported

					Menu

					Globals

					"protobufs/steammessages"

					CMsgGCRoutingInfo_RoutingMethod

Enumeration CMsgGCRoutingInfo_RoutingMethod

Index

Enumeration members

CLIENT_<wbr>STEAMID

DISCARD

PROTOBUF_<wbr>FIELD_<wbr>UINT64

RANDOM

WEBAPI_<wbr>PARAM_<wbr>UINT64

Enumeration members

CLIENT_<wbr>STEAMID

CLIENT_<wbr>STEAMID:  = 2

Defined in src/protobufs/steammessages.ts:442

DISCARD

DISCARD:  = 1

Defined in src/protobufs/steammessages.ts:441

PROTOBUF_<wbr>FIELD_<wbr>UINT64

PROTOBUF_<wbr>FIELD_<wbr>UINT64:  = 3

Defined in src/protobufs/steammessages.ts:443

RANDOM

RANDOM:  = 0

Defined in src/protobufs/steammessages.ts:440

WEBAPI_<wbr>PARAM_<wbr>UINT64

WEBAPI_<wbr>PARAM_<wbr>UINT64:  = 4

Defined in src/protobufs/steammessages.ts:444

						Globals

						"protobufs/steammessages"

						CMsgGCRouting<wbr>Info_<wbr><wbr>Routing<wbr>Method

								CLIENT_<wbr>STEAMID

								DISCARD

								PROTOBUF_<wbr>FIELD_<wbr>UINT64

								RANDOM

								WEBAPI_<wbr>PARAM_<wbr>UINT64

Legend

Object literal

Variable

Function

Function with type parameter

Type alias

Type alias with type parameter

Interface

Interface with type parameter

Class

Class with type parameter

Enumeration

Generated using TypeDoc


text:
package org.pepstock.charba.client.dom.elements;

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

import org.pepstock.charba.client.commons.ArrayInteger;
import org.pepstock.charba.client.commons.JsHelper;
import org.pepstock.charba.client.commons.Key;
import org.pepstock.charba.client.commons.NativeName;
import org.pepstock.charba.client.commons.NativeObject;
import org.pepstock.charba.client.items.Undefined;

import jsinterop.annotations.JsMethod;
import jsinterop.annotations.JsOverlay;
import jsinterop.annotations.JsPackage;
import jsinterop.annotations.JsType;

/**
 * Represents an array of 8-bit unsigned integers clamped to 0-255; if you specified a value that is out of the range of [0,255], 0 or 255 will be set instead; if you specify a
 * non-integer, the nearest integer will be set.

 * The contents are initialized to 0.
 *
 * @author Andrea "Stock" Stocchero
 *
 */
@JsType(isNative = true, name = NativeName.UINT8_CLAMPED_ARRAY, namespace = JsPackage.GLOBAL)
final class Uint8ClampedArray {

	// property key of iterator which contains the value
	@JsOverlay
	private static final Key VALUE = Key.create("value");
	// property key of iterator which provides if the iterator has been iterated
	@JsOverlay
	private static final Key DONE = Key.create("done");

	/**
	 * To avoid any instantiation
	 */
	private Uint8ClampedArray() {
		// do nothing
	}

	/**
	 * Returns a new array iterator object that contains the values for each index in the array.
	 *
	 * @return a new array iterator object that contains the values for each index in the array
	 */
	@JsMethod
	private native JsIterator values();

	/**
	 * Iterator is an object which defines a sequence and potentially a return value upon its termination.

	 * Specifically, an iterator is any object which implements the Iterator protocol by having a next() method that returns an object with two properties:

	 *

	 *
value: The next value in the iteration sequence.
	 *
done: This is true if the last value in the sequence has already been consumed. If value is present alongside done, it is the iterator's return value.
	 *

	 *

	 * Once created, an iterator object can be iterated explicitly by repeatedly calling next().

	 * Iterating over an iterator is said to consume the iterator, because it is generally only possible to do once. After a terminating value has been yielded additional calls to
	 * next() should continue to return {done: true}.
	 *
	 * @author Andrea "Stock" Stocchero
	 *
	 */
	@JsType(isNative = true, name = NativeName.ITERATOR, namespace = JsPackage.GLOBAL)
	private interface JsIterator {

		/**
		 * Returns an object with two properties done and value.
		 *
		 * @return an object with two properties done and value
		 */
		NativeObject next();
	}

	/**
	 * Transforms a {@link Uint8ClampedArray} to an {@link ArrayInteger} instance in order to be managed.
	 *
	 * @return an {@link ArrayInteger} instance in order to be managed.
	 */
	@JsOverlay
	ArrayInteger toArray() {
		// lists of integers to create the result array
		final List<Integer> result = new LinkedList<>();
		// gets iterator
		final JsIterator iterator = values();
		// flag to close the cycle
		boolean done = false;
		// scans iterator
		do {
			// gets object
			NativeObject element = iterator.next();
			// reads done and value property
			done = JsHelper.get().getBooleanProperty(DONE, element);
			int value = JsHelper.get().getIntegerProperty(VALUE, element);
			// checks if the properties are consistent to add new element
			// to result array
			if (!done && Undefined.isNot(value)) {
				result.add(value);
			}
		} while (!done);
		// returns the array
		return ArrayInteger.fromOrEmpty(result);
	}

}


text:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.Serialization;
using System.Xml;
using System.Linq;
using System.Xml.Serialization;

namespace XeroApi.Model
{
    /// <summary>
    /// Navigates across a model tree and serialised to an <c ref="XmlWriter"/>.
    /// </summary>
    /// <remarks>
    /// This class doesn't serialise properties marked as [Obsolete] or [ReadOnly].
    /// </remarks>
    public class ModelTreeNavigator : IDisposable
    {
        private static readonly ICollection<Type> KnownPropertyTypes = new Collection<Type>
        {
            typeof(Int16),
            typeof(Int32),
            typeof(Int64),
            typeof(Guid),
            typeof(Enum),
            typeof(String),
            typeof(DateTime),
            typeof(Decimal)
        };

        private XmlWriter _writer;

        /// <summary>
        /// Initializes a new instance of the <see cref="ModelTreeNavigator"/> class.
        /// </summary>
        /// <param name="writer">The writer.</param>
        public ModelTreeNavigator(XmlWriter writer)
        {
            _writer = writer;
        }

        /// <summary>
        /// Navigates across the specified model and outputs to the current XmlWriter.
        /// </summary>
        /// <typeparam name="TModel">The type of the model.</typeparam>
        /// <param name="model">The model.</param>
        public void Navigate<TModel>(TModel model)
            where TModel : ModelBase
        {
            WriteClass(model);
        }

        /// <summary>
        /// Writes the class.
        /// </summary>
        /// <param name="model">The class to be written.</param>
        /// <param name="elementName">Name of the element.</param>
        public void WriteClass(object model, string elementName = "")
        {
            if (model == null)
            {
                return;
            }

            Type modelType = GetNonNullableType(model.GetType());

            if (string.IsNullOrEmpty(elementName))
            {
                elementName = modelType.Name;
            }

            Debug.WriteLine(string.Format("Class name:{0} type:{1}", "?", modelType));

            _writer.WriteStartElement(elementName);

            IEnumerable<PropertyInfo> propertiesToSerialise = modelType.GetProperties()
                .Where(prop => FindAttributeOnProperty<XmlIgnoreAttribute>(prop) == null)
                .Where(prop => FindAttributeOnProperty<ReadOnlyAttribute>(prop) == null)
                .ToArray();

            // Write attributes on the parent element BEFORE writing child elements (simple types only)
            foreach (PropertyInfo property in propertiesToSerialise.Where(prop => FindAttributeOnProperty<XmlAttributeAttribute>(prop) != null))
            {
                WritePropertyAsAttribute(model, property);
            }

            // Write child elements (simple and complex types)
            foreach (PropertyInfo property in propertiesToSerialise.Where(prop => FindAttributeOnProperty<XmlAttributeAttribute>(prop) == null))
            {
                WritePropertyAsElement(model, property);
            }

            _writer.WriteEndElement();
        }

        public void WriteList(IModelList modelList, PropertyInfo property)
        {
            if (modelList == null)
            {
                return;
            }

            _writer.WriteStartElement(property.Name);

            XmlArrayItemAttribute xmlArrayItem = FindAttributeOnProperty<XmlArrayItemAttribute>(property);
            string overrideElementName = (xmlArrayItem == null) ? string.Empty : xmlArrayItem.ElementName;

            foreach (var modelListItem in modelList)
            {
                WriteClass(modelListItem, overrideElementName);
            }

            _writer.WriteEndElement();
        }

        public void WritePropertyAsAttribute(object model, PropertyInfo property)
        {
            XmlAttributeAttribute xmlAttribute = FindAttributeOnProperty<XmlAttributeAttribute>(property);

            Type propType = GetNonNullableType(property.PropertyType);
            string propName = xmlAttribute.AttributeName ?? property.Name;
            object propValue = property.GetValue(model, new object[0]);

            if (propType.IsEnum)
            {
                _writer.WriteAttributeString(propName, string.Empty, ConvertValueToString(propValue));
                return;
            }

            if (KnownPropertyTypes.Any(propType.IsAssignableFrom))
            {
                _writer.WriteAttributeString(propName, string.Empty, ConvertValueToString(propValue));
                return;
            }

            throw new SerializationException(string.Format("The property type {0} cannot be serialised as an attribute", propType.Name));
        }

        /// <summary>
        /// Writes the property.
        /// </summary>
        /// <typeparam name="TInput">The type of the input.</typeparam>
        /// <param name="model">The model.</param>
        /// <param name="property">The property.</param>
        public void WritePropertyAsElement<TInput>(TInput model, PropertyInfo property)
        {
            var propType = GetNonNullableType(property.PropertyType);
            object propValue = property.GetValue(model, null);

            Debug.WriteLine(string.Format("Prop name:{0} type:{1}", property.Name, propType));

            if (propValue == null)
            {
                return;
            }

            // Write enum value as simple element
            if (typeof(Enum).IsAssignableFrom(propType))
            {
                _writer.WriteElementString(property.Name, string.Empty, ConvertValueToString(propValue));
            }

            // Write value as simple xml element...
            else if (KnownPropertyTypes.Any(propType.IsAssignableFrom))
            {
                _writer.WriteElementString(property.Name, string.Empty, ConvertValueToString(propValue));
            }

            // Write List as complex type
            else if (typeof(IModelList).IsAssignableFrom(propType))
            {
                WriteList((IModelList)propValue, property);
            }

            // Write nested classes
            else
            {
                WriteClass(propValue);
            }
        }

        private static string ConvertValueToString(object input)
        {
            if (input == null)
            {
                return null;
            }

            if (input is DateTime)
            {
                return ((DateTime) input).ToString("s");
            }

            return input.ToString();
        }

        public void Dispose()
        {
            _writer = null;
        }

        #region Helper Methods (TODO: move to ModelTypeHelper)

        public static Type GetNonNullableType(Type type)
        {
            return typeof(Nullable<>).IsAssignableFrom(type) ? type.GetGenericArguments()[0] : type;
        }

        /// <summary>
        /// Finds the attribute on property.
        /// </summary>
        /// <typeparam name="TAttribute">The type of the attribute.</typeparam>
        /// <param name="property">The property.</param>
        /// <returns></returns>
        public static  TAttribute FindAttributeOnProperty<TAttribute>(PropertyInfo property)
            where TAttribute : Attribute
        {
            if (property == null)
            {
                return null;
            }

            return property.GetCustomAttributes(typeof(TAttribute), true).FirstOrDefault() as TAttribute;
        }

        /// <summary>
        /// Finds the attribute on class.
        /// </summary>
        /// <typeparam name="TAttribute">The type of the attribute.</typeparam>
        /// <typeparam name="TInput">The type of the model.</typeparam>
        /// <param name="input">The input.</param>
        /// <returns></returns>
        public static TAttribute FindAttributeOnClass<TAttribute, TInput>(TInput input)
            where TAttribute : Attribute
            where TInput : ModelBase
        {
            if (input == null)
            {
                return null;
            }

            return input.GetType().GetCustomAttributes(typeof(TAttribute), true).FirstOrDefault() as TAttribute;
        }

        #endregion
    }
}


text:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Templating
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public ObservableCollection<Plane> allPlanes { get; set; }

        public MainWindow()
        {
            allPlanes = new ObservableCollection<Plane>();
            // Required to initialize variables
            InitializeComponent();
            this.DataContext = this;

            allPlanes.Add(new Plane("Tango1", 20, 200));
            allPlanes.Add(new Plane("Bravo2", 100, 200));
            allPlanes.Add(new Plane("Alpha0", 25, 50));
            allPlanes.Add(new Plane("AirForceOne", 125, 100));
        }
    }
}


text:
<!doctype html>
<html>

<head>
    <title>SVG Example</title>
    <script src="http://d3js.org/d3.v4.min.js"></script>
</head>

<body>

    <svg width="1400" height="200"></svg>
    These planets placed in scable distance to sun and drew in scalable diameter to eachother but the distances (million km) and the diameter measurement (km) are in different scale.

    <script>

        d3.csv("solar-system.csv", function (data) {
            var width = 1400;
            var height = 200;

            var distanceScale = d3.scaleLinear()
                .domain([0, 6000])
                .range([0, width-50]);

            var diameterScale = d3.scaleLinear()
                .domain([0, 140000])
                .range([0, 50]);

            var canvas = d3.select("svg")
                .append("g");

            canvas.append("rect")
                .attr("width", "100%")
                .attr("height", "100%")
                .attr("fill", "#ddd");

            canvas.selectAll("circle")
                .data(data)
                .enter()
                    .append("circle")
                    .attr("cx", function(d) { return distanceScale(d.distance); } )
                    .attr("cy", 100)
                    .attr("r", function(d) { return diameterScale(d.diameter); })
                    .attr("fill", "black");

            canvas.selectAll("text")
                .data(data)
                .enter()
                    .append("text")
                    .attr("fill", "red")
                    .attr("x", function(d) { return distanceScale(d.distance) - 4; })
                    .attr("y", 93)
                    .text(function(d) { return d.label; });

            var axis = d3.axisBottom(distanceScale);

            canvas.append("g")
                .call(axis);

        });

    </script>

</body>

</html>


text:
@interface STViewController : UIViewController

@property (nonatomic, strong) STAlertView *stAlertView;

- (IBAction)showNormalUIAlertView:(id)sender;
- (IBAction)showTextFieldUIAlertView:(id)sender;

@end


text:
/* Japanese translation by Yoshiki Kato @burnworks - v1.0.0 - 2016-03-01 */

var HTMLCS_WCAG2AAA_Sniffs_Principle1_Guideline1_4_1_4_4 = {
    /**
     * Determines the elements to register for processing.
     *
     * Each element of the returned array can either be an element name, or "_top"
     * which is the top element of the tested code.
     *
     * @returns {Array} The list of elements.
     */
    register: function()
    {
        return ['_top'];

    },

    /**
     * Process the registered element.
     *
     * @param {DOMNode} element The element registered.
     * @param {DOMNode} top     The top element of the tested code.
     */
    process: function(element, top)
    {
        HTMLCS.addMessage(HTMLCS.NOTICE, top, 'テキストはコンテンツ、または機能を損なうことなく、支援技術なしで 200% までサイズを変更できることを確認してください。 Check that text can be resized without assistive technology up to 200 percent without loss of content or functionality.', 'G142');

    }
};


text:
std::vector<std::string> convertPythia6Command(Command command);

#endif


text:
'use strict';

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

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _Grid = require('./Grid');

var _Grid2 = _interopRequireDefault(_Grid);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var Half = function Half(props) {
  return _react2.default.createElement(_Grid2.default, _extends({}, props, { width: [1, 1 / 2] }));
};

exports.default = Half;


text:
package org.apache.flink.table.api.stream.sql

import org.apache.flink.api.scala._
import org.apache.flink.table.api.scala._
import org.apache.flink.table.utils.TableTestUtil._
import org.apache.flink.table.utils.{StreamTableTestUtil, TableTestBase}
import org.junit.Test

class SortTest extends TableTestBase {

  private val streamUtil: StreamTableTestUtil = streamTestUtil()
  private val table = streamUtil.addTable[(Int, String, Long)]("MyTable", 'a, 'b, 'c,
      'proctime.proctime, 'rowtime.rowtime)

  @Test
  def testSortProcessingTime(): Unit = {

    val sqlQuery = "SELECT a FROM MyTable ORDER BY proctime, c"

    val expected =
      unaryNode(
        "DataStreamCalc",
        unaryNode("DataStreamSort",
          streamTableNode(table),
          term("orderBy", "proctime ASC", "c ASC")),
        term("select", "a", "PROCTIME(proctime) AS proctime", "c"))

    streamUtil.verifySql(sqlQuery, expected)
  }

  @Test
  def testSortRowTime(): Unit = {

    val sqlQuery = "SELECT a FROM MyTable ORDER BY rowtime, c"

    val expected =
      unaryNode(
        "DataStreamCalc",
        unaryNode("DataStreamSort",
          streamTableNode(table),
          term("orderBy", "rowtime ASC, c ASC")),
        term("select", "a", "rowtime", "c"))

    streamUtil.verifySql(sqlQuery, expected)
  }
}


text:
use std::cell::Cell;
use std::cell::RefCell;
use std::convert::TryInto;
use std::fmt;
use std::fs::File;
use std::ops::Deref;
use std::ops::DerefMut;
use std::panic::catch_unwind;
use std::panic::resume_unwind;
use std::panic::AssertUnwindSafe;

use serde::de;
use serde::de::Error;
use serde::de::Visitor;
use serde::ser;
use serde::Deserialize;
use serde::Deserializer;
use serde::Serialize;
use serde::Serializer;

use super::RawDescriptor;
use crate::descriptor::SafeDescriptor;

thread_local! {
    static DESCRIPTOR_DST: RefCell<Option<Vec<RawDescriptor>>> = Default::default();
}

/// Initializes the thread local storage for descriptor serialization. Fails if it was already
/// initialized without an intervening `take_descriptor_dst` on this thread.
fn init_descriptor_dst() -> Result<(), &'static str> {
    DESCRIPTOR_DST.with(|d| {
        let mut descriptors = d.borrow_mut();
        if descriptors.is_some() {
            return Err(
                "attempt to initialize descriptor destination that was already initialized",
            );
        }
        *descriptors = Some(Default::default());
        Ok(())
    })
}

/// Takes the thread local storage for descriptor serialization. Fails if there wasn't a prior call
/// to `init_descriptor_dst` on this thread.
fn take_descriptor_dst() -> Result<Vec<RawDescriptor>, &'static str> {
    match DESCRIPTOR_DST.with(|d| d.replace(None)) {
        Some(d) => Ok(d),
        None => Err("attempt to take descriptor destination before it was initialized"),
    }
}

/// Pushes a descriptor on the thread local destination of descriptors, returning the index in which
/// the descriptor was pushed.
//
/// Returns Err if the thread local destination was not already initialized.
fn push_descriptor(rd: RawDescriptor) -> Result<usize, &'static str> {
    DESCRIPTOR_DST.with(|d| {
        d.borrow_mut()
            .as_mut()
            .ok_or("attempt to serialize descriptor without descriptor destination")
            .map(|descriptors| {
                let index = descriptors.len();
                descriptors.push(rd);
                index
            })
    })
}

/// Serializes a descriptor for later retrieval in a parent `SerializeDescriptors` struct.
///
/// If there is no parent `SerializeDescriptors` being serialized, this will return an error.
///
/// For convenience, it is recommended to use the `with_raw_descriptor` module in a `#[serde(with =
/// "...")]` attribute which will make use of this function.
pub fn serialize_descriptor<S: Serializer>(
    rd: &RawDescriptor,
    se: S,
) -> std::result::Result<S::Ok, S::Error> {
    let index = push_descriptor(*rd).map_err(ser::Error::custom)?;
    se.serialize_u32(
        index
            .try_into()
            .map_err(|_| ser::Error::custom("attempt to serialize too many descriptors at once"))?,
    )
}

/// Wrapper for a `Serialize` value which will capture any descriptors exported by the value when
/// given to an ordinary `Serializer`.
///
/// This is the corresponding type to use for serialization before using
/// `deserialize_with_descriptors`.
///
/// # Examples
///
/// ```
/// use serde_json::to_string;
/// use base::platform::{FileSerdeWrapper, SerializeDescriptors};
/// use tempfile::tempfile;
///
/// let tmp_f = tempfile().unwrap();
/// let data = FileSerdeWrapper(tmp_f);
/// let data_wrapper = SerializeDescriptors::new(&data);
///
/// // Serializes `v` as normal...
/// let out_json = serde_json::to_string(&data_wrapper).expect("failed to serialize");
/// // If `serialize_descriptor` was called, we can capture the descriptors from here.
/// let out_descriptors = data_wrapper.into_descriptors();
/// ```
pub struct SerializeDescriptors<'a, T: Serialize>(&'a T, Cell<Vec<RawDescriptor>>);

impl<'a, T: Serialize> SerializeDescriptors<'a, T> {
    pub fn new(inner: &'a T) -> Self {
        Self(inner, Default::default())
    }

    pub fn into_descriptors(self) -> Vec<RawDescriptor> {
        self.1.into_inner()
    }
}

impl<'a, T: Serialize> Serialize for SerializeDescriptors<'a, T> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        init_descriptor_dst().map_err(ser::Error::custom)?;

        // catch_unwind is used to ensure that init_descriptor_dst is always balanced with a call to
        // take_descriptor_dst afterwards.
        let res = catch_unwind(AssertUnwindSafe(|| self.0.serialize(serializer)));
        self.1.set(take_descriptor_dst().unwrap());
        match res {
            Ok(r) => r,
            Err(e) => resume_unwind(e),
        }
    }
}

thread_local! {
    static DESCRIPTOR_SRC: RefCell<Option<Vec<Option<SafeDescriptor>>>> = Default::default();
}

/// Sets the thread local storage of descriptors for deserialization. Fails if this was already
/// called without a call to `take_descriptor_src` on this thread.
///
/// This is given as a collection of `Option` so that unused descriptors can be returned.
fn set_descriptor_src(descriptors: Vec<Option<SafeDescriptor>>) -> Result<(), &'static str> {
    DESCRIPTOR_SRC.with(|d| {
        let mut src = d.borrow_mut();
        if src.is_some() {
            return Err("attempt to set descriptor source that was already set");
        }
        *src = Some(descriptors);
        Ok(())
    })
}

/// Takes the thread local storage of descriptors for deserialization. Fails if the storage was
/// already taken or never set with `set_descriptor_src`.
///
/// If deserialization was done, the descriptors will mostly come back as `None` unless some of them
/// were unused.
fn take_descriptor_src() -> Result<Vec<Option<SafeDescriptor>>, &'static str> {
    DESCRIPTOR_SRC.with(|d| {
        d.replace(None)
            .ok_or("attempt to take descriptor source which was never set")
    })
}

/// Takes a descriptor at the given index from the thread local source of descriptors.
//
/// Returns None if the thread local source was not already initialized.
fn take_descriptor(index: usize) -> Result<SafeDescriptor, &'static str> {
    DESCRIPTOR_SRC.with(|d| {
        d.borrow_mut()
            .as_mut()
            .ok_or("attempt to deserialize descriptor without descriptor source")?
            .get_mut(index)
            .ok_or("attempt to deserialize out of bounds descriptor")?
            .take()
            .ok_or("attempt to deserialize descriptor that was already taken")
    })
}

/// Deserializes a descriptor provided via `deserialize_with_descriptors`.
///
/// If `deserialize_with_descriptors` is not in the call chain, this will return an error.
///
/// For convenience, it is recommended to use the `with_raw_descriptor` module in a `#[serde(with =
/// "...")]` attribute which will make use of this function.
pub fn deserialize_descriptor<'de, D>(de: D) -> std::result::Result<SafeDescriptor, D::Error>
where
    D: Deserializer<'de>,
{
    struct DescriptorVisitor;

    impl<'de> Visitor<'de> for DescriptorVisitor {
        type Value = u32;

        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
            formatter.write_str("an integer which fits into a u32")
        }

        fn visit_u8<E: de::Error>(self, value: u8) -> Result<Self::Value, E> {
            Ok(value as _)
        }

        fn visit_u16<E: de::Error>(self, value: u16) -> Result<Self::Value, E> {
            Ok(value as _)
        }

        fn visit_u32<E: de::Error>(self, value: u32) -> Result<Self::Value, E> {
            Ok(value)
        }

        fn visit_u64<E: de::Error>(self, value: u64) -> Result<Self::Value, E> {
            value.try_into().map_err(E::custom)
        }

        fn visit_u128<E: de::Error>(self, value: u128) -> Result<Self::Value, E> {
            value.try_into().map_err(E::custom)
        }

        fn visit_i8<E: de::Error>(self, value: i8) -> Result<Self::Value, E> {
            value.try_into().map_err(E::custom)
        }

        fn visit_i16<E: de::Error>(self, value: i16) -> Result<Self::Value, E> {
            value.try_into().map_err(E::custom)
        }

        fn visit_i32<E: de::Error>(self, value: i32) -> Result<Self::Value, E> {
            value.try_into().map_err(E::custom)
        }

        fn visit_i64<E: de::Error>(self, value: i64) -> Result<Self::Value, E> {
            value.try_into().map_err(E::custom)
        }

        fn visit_i128<E: de::Error>(self, value: i128) -> Result<Self::Value, E> {
            value.try_into().map_err(E::custom)
        }
    }

    let index = de.deserialize_u32(DescriptorVisitor)? as usize;
    take_descriptor(index).map_err(D::Error::custom)
}

/// Allows the use of any serde deserializer within a closure while providing access to the a set of
/// descriptors for use in `deserialize_descriptor`.
///
/// This is the corresponding call to use deserialize after using `SerializeDescriptors`.
///
/// If `deserialize_with_descriptors` is called anywhere within the given closure, it return an
/// error.
pub fn deserialize_with_descriptors<F, T, E>(
    f: F,
    descriptors: &mut Vec<Option<SafeDescriptor>>,
) -> Result<T, E>
where
    F: FnOnce() -> Result<T, E>,
    E: de::Error,
{
    let swap_descriptors = std::mem::take(descriptors);
    set_descriptor_src(swap_descriptors).map_err(E::custom)?;

    // catch_unwind is used to ensure that set_descriptor_src is always balanced with a call to
    // take_descriptor_src afterwards.
    let res = catch_unwind(AssertUnwindSafe(f));

    // unwrap is used because set_descriptor_src is always called before this, so it should never
    // panic.
    *descriptors = take_descriptor_src().unwrap();

    match res {
        Ok(r) => r,
        Err(e) => resume_unwind(e),
    }
}

/// Module that exports `serialize`/`deserialize` functions for use with `#[serde(with = "...")]`
/// attribute. It only works with fields with `RawDescriptor` type.
///
/// # Examples
///
/// ```
/// use serde::{Deserialize, Serialize};
/// use base::platform::RawDescriptor;
///
/// #[derive(Serialize, Deserialize)]
/// struct RawContainer {
///     #[serde(with = "base::platform::with_raw_descriptor")]
///     rd: RawDescriptor,
/// }
/// ```
pub mod with_raw_descriptor {
    use serde::Deserializer;

    use super::super::RawDescriptor;
    pub use super::serialize_descriptor as serialize;
    use crate::descriptor::IntoRawDescriptor;

    pub fn deserialize<'de, D>(de: D) -> std::result::Result<RawDescriptor, D::Error>
    where
        D: Deserializer<'de>,
    {
        super::deserialize_descriptor(de).map(IntoRawDescriptor::into_raw_descriptor)
    }
}

/// Module that exports `serialize`/`deserialize` functions for use with `#[serde(with = "...")]`
/// attribute.
///
/// # Examples
///
/// ```
/// use std::fs::File;
/// use serde::{Deserialize, Serialize};
/// use base::platform::RawDescriptor;
///
/// #[derive(Serialize, Deserialize)]
/// struct FileContainer {
///     #[serde(with = "base::platform::with_as_descriptor")]
///     file: File,
/// }
/// ```
pub mod with_as_descriptor {
    use serde::Deserializer;
    use serde::Serializer;

    use crate::descriptor::AsRawDescriptor;
    use crate::descriptor::FromRawDescriptor;
    use crate::descriptor::IntoRawDescriptor;

    pub fn serialize<S: Serializer>(
        rd: &dyn AsRawDescriptor,
        se: S,
    ) -> std::result::Result<S::Ok, S::Error> {
        super::serialize_descriptor(&rd.as_raw_descriptor(), se)
    }

    pub fn deserialize<'de, D, T>(de: D) -> std::result::Result<T, D::Error>
    where
        D: Deserializer<'de>,
        T: FromRawDescriptor,
    {
        super::deserialize_descriptor(de)
            .map(IntoRawDescriptor::into_raw_descriptor)
            .map(|rd| unsafe { T::from_raw_descriptor(rd) })
    }
}

/// A simple wrapper around `File` that implements `Serialize`/`Deserialize`, which is useful when
/// the `#[serde(with = "with_as_descriptor")]` trait is infeasible, such as for a field with type
/// `Option<File>`.
#[derive(Serialize, Deserialize)]
#[serde(transparent)]
pub struct FileSerdeWrapper(#[serde(with = "with_as_descriptor")] pub File);

impl fmt::Debug for FileSerdeWrapper {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl From<File> for FileSerdeWrapper {
    fn from(file: File) -> Self {
        FileSerdeWrapper(file)
    }
}

impl From<FileSerdeWrapper> for File {
    fn from(f: FileSerdeWrapper) -> File {
        f.0
    }
}

impl Deref for FileSerdeWrapper {
    type Target = File;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl DerefMut for FileSerdeWrapper {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

#[cfg(test)]
mod tests {
    use std::collections::HashMap;
    use std::fs::File;
    use std::mem::ManuallyDrop;

    use serde::de::DeserializeOwned;
    use serde::Deserialize;
    use serde::Serialize;
    use tempfile::tempfile;

    use super::super::deserialize_with_descriptors;
    use super::super::with_as_descriptor;
    use super::super::with_raw_descriptor;
    use super::super::AsRawDescriptor;
    use super::super::FileSerdeWrapper;
    use super::super::FromRawDescriptor;
    use super::super::RawDescriptor;
    use super::super::SafeDescriptor;
    use super::super::SerializeDescriptors;

    fn deserialize<T: DeserializeOwned>(json: &str, descriptors: &[RawDescriptor]) -> T {
        let mut safe_descriptors = descriptors
            .iter()
            .map(|&v| Some(unsafe { SafeDescriptor::from_raw_descriptor(v) }))
            .collect();

        let res =
            deserialize_with_descriptors(|| serde_json::from_str(json), &mut safe_descriptors)
                .unwrap();

        assert!(safe_descriptors.iter().all(|v| v.is_none()));

        res
    }

    #[test]
    fn raw() {
        #[derive(Serialize, Deserialize, PartialEq, Debug)]
        struct RawContainer {
            #[serde(with = "with_raw_descriptor")]
            rd: RawDescriptor,
        }
        // Specifically chosen to not overlap a real descriptor to avoid having to allocate any
        // descriptors for this test.
        let fake_rd = 5_123_457_i32;
        let v = RawContainer {
            rd: fake_rd as RawDescriptor,
        };
        let v_serialize = SerializeDescriptors::new(&v);
        let json = serde_json::to_string(&v_serialize).unwrap();
        let descriptors = v_serialize.into_descriptors();
        let res = deserialize(&json, &descriptors);
        assert_eq!(v, res);
    }

    #[test]
    fn file() {
        #[derive(Serialize, Deserialize)]
        struct FileContainer {
            #[serde(with = "with_as_descriptor")]
            file: File,
        }

        let v = FileContainer {
            file: tempfile().unwrap(),
        };
        let v_serialize = SerializeDescriptors::new(&v);
        let json = serde_json::to_string(&v_serialize).unwrap();
        let descriptors = v_serialize.into_descriptors();
        let v = ManuallyDrop::new(v);
        let res: FileContainer = deserialize(&json, &descriptors);
        assert_eq!(v.file.as_raw_descriptor(), res.file.as_raw_descriptor());
    }

    #[test]
    fn option() {
        #[derive(Serialize, Deserialize)]
        struct TestOption {
            a: Option<FileSerdeWrapper>,
            b: Option<FileSerdeWrapper>,
        }

        let v = TestOption {
            a: None,
            b: Some(tempfile().unwrap().into()),
        };
        let v_serialize = SerializeDescriptors::new(&v);
        let json = serde_json::to_string(&v_serialize).unwrap();
        let descriptors = v_serialize.into_descriptors();
        let v = ManuallyDrop::new(v);
        let res: TestOption = deserialize(&json, &descriptors);
        assert!(res.a.is_none());
        assert!(res.b.is_some());
        assert_eq!(
            v.b.as_ref().unwrap().as_raw_descriptor(),
            res.b.unwrap().as_raw_descriptor()
        );
    }

    #[test]
    fn map() {
        let mut v: HashMap<String, FileSerdeWrapper> = HashMap::new();
        v.insert("a".into(), tempfile().unwrap().into());
        v.insert("b".into(), tempfile().unwrap().into());
        v.insert("c".into(), tempfile().unwrap().into());
        let v_serialize = SerializeDescriptors::new(&v);
        let json = serde_json::to_string(&v_serialize).unwrap();
        let descriptors = v_serialize.into_descriptors();
        // Prevent the files in `v` from dropping while allowing the HashMap itself to drop. It is
        // done this way to prevent a double close of the files (which should reside in `res`)
        // without triggering the leak sanitizer on `v`'s HashMap heap memory.
        let v: HashMap<_, _> = v
            .into_iter()
            .map(|(k, v)| (k, ManuallyDrop::new(v)))
            .collect();
        let res: HashMap<String, FileSerdeWrapper> = deserialize(&json, &descriptors);

        assert_eq!(v.len(), res.len());
        for (k, v) in v.iter() {
            assert_eq!(
                res.get(k).unwrap().as_raw_descriptor(),
                v.as_raw_descriptor()
            );
        }
    }
}


text:
foam.CLASS({
  package: 'nodetooldemo',
  name: 'TestBaseClass',
});


text:
using System;
using System.ComponentModel;
using System.Diagnostics;

namespace MVVm.Core
{
    /// <summary>
    /// Base class for all ViewModel classes in the application.
    /// It provides support for property change notifications
    /// and has a DisplayName property.  This class is abstract.
    /// </summary>
    public abstract class ViewModelBase : INotifyPropertyChanged, IDisposable
    {

        #region Constructor

        protected ViewModelBase()
        {

        }

        #endregion // Constructor

        #region DisplayName

        /// <summary>
        /// Returns the user-friendly name of this object.
        /// Child classes can set this property to a new value,
        /// or override it to determine the value on-demand.
        /// </summary>
        public virtual string DisplayName { get; protected set; }

        #endregion // DisplayName

        #region Debugging Aides

        /// <summary>
        /// Warns the developer if this object does not have
        /// a public property with the specified name. This
        /// method does not exist in a Release build.
        /// </summary>
        [Conditional("DEBUG")]
        [DebuggerStepThrough]
        public void VerifyPropertyName(string propertyName)
        {
            // Verify that the property name matches a real,
            // public, instance property on this object.
            if (TypeDescriptor.GetProperties(this)[propertyName] == null)
            {
                string msg = "Invalid property name: " + propertyName;

                if (this.ThrowOnInvalidPropertyName)
                    throw new Exception(msg);
                else
                    Debug.Fail(msg);
            }
        }

        /// <summary>
        /// Returns whether an exception is thrown, or if a Debug.Fail() is used
        /// when an invalid property name is passed to the VerifyPropertyName method.
        /// The default value is false, but subclasses used by unit tests might
        /// override this property's getter to return true.
        /// </summary>
        protected virtual bool ThrowOnInvalidPropertyName { get; private set; }

        #endregion // Debugging Aides

        #region INotifyPropertyChanged Members

        /// <summary>
        /// Raised when a property on this object has a new value.
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// Raises this object's PropertyChanged event.
        /// </summary>
        /// <param name="propertyName">The property that has a new value.</param>
        public virtual void OnPropertyChanged(string propertyName)
        {
            this.VerifyPropertyName(propertyName);

            PropertyChangedEventHandler handler = this.PropertyChanged;
            if (handler != null)
            {
                var e = new PropertyChangedEventArgs(propertyName);
                handler(this, e);
            }
        }

        #endregion // INotifyPropertyChanged Members

        #region IDisposable Members

        /// <summary>
        /// Invoked when this object is being removed from the application
        /// and will be subject to garbage collection.
        /// </summary>
        public void Dispose()
        {
            this.OnDispose();
        }

        /// <summary>
        /// Child classes can override this method to perform
        /// clean-up logic, such as removing event handlers.
        /// </summary>
        protected virtual void OnDispose()
        {
        }

#if DEBUG
        /// <summary>
        /// Useful for ensuring that ViewModel objects are properly garbage collected.
        /// </summary>
        ~ViewModelBase()
        {
            string msg = string.Format("{0} ({1}) ({2}) Finalized", this.GetType().Name, this.DisplayName, this.GetHashCode());
            System.Diagnostics.Debug.WriteLine(msg);
        }
#endif

        #endregion // IDisposable Members
    }
}


text:
// Package gsutil is collection of helper functions for storage tools.
package gsutil

import (
	"context"
	"flag"
	"fmt"
	"log"
	"os"
	"os/signal"
	"strings"
	"syscall"

	"kythe.io/kythe/go/services/graphstore"
	"kythe.io/kythe/go/storage/inmemory"
)

// Handler returns a graphstore.Service based on the given specification.
// See also: Register(string, Handler).
type Handler func(spec string) (graphstore.Service, error)

var (
	handlers = map[string]Handler{
		"in-memory": func(_ string) (graphstore.Service, error) {
			return new(inmemory.GraphStore), nil
		},
	}
	defaultHandlerKind string
)

// Register exposes the given Handler to ParseGraphStore.  Each string starting
// with kind+":" will be passed to the given Handler.  A kind can only be
// registered once.
func Register(kind string, h Handler) {
	if _, exists := handlers[kind]; exists {
		log.Fatalf("gsutil Handler for kind %q already exists", kind)
	}
	handlers[kind] = h
}

// RegisterDefault gives ParseGraphStore a fallback kind if not given any
// "____:" prefix.  A default can only be set once.
func RegisterDefault(kind string) {
	if defaultHandlerKind != "" {
		log.Fatalf("default gsutil Handler kind already registered as %q", defaultHandlerKind)
	}
	defaultHandlerKind = kind
}

type gsFlag struct {
	gs *graphstore.Service
}

// String implements part of the flag.Value interface.
func (f *gsFlag) String() string {
	if f.gs == nil {
		return "<graphstore>"
	}
	return fmt.Sprintf("%T", *f.gs)
}

// Get implements part of the flag.Getter interface.
func (f *gsFlag) Get() interface{} {
	return *f.gs
}

// Set implements part of the flag.Value interface.
func (f *gsFlag) Set(str string) (err error) {
	*f.gs, err = ParseGraphStore(str)
	return
}

// Flag defines a GraphStore flag with the specified name and usage string.
func Flag(gs *graphstore.Service, name, usage string) {
	if gs == nil {
		log.Fatal("GraphStoreFlag given nil GraphStore pointer")
	}
	f := gsFlag{gs: gs}
	flag.Var(&f, name, usage)
}

// ParseGraphStore returns a GraphStore for the given specification.
func ParseGraphStore(str string) (graphstore.Service, error) {
	str = strings.TrimSpace(str)
	split := strings.SplitN(str, ":", 2)
	var kind, spec string
	if len(split) == 2 {
		spec = split[1]
		kind = split[0]
	} else {
		spec = str
		switch {
		case spec == "" || spec == "in-memory":
			kind = "in-memory"
		case defaultHandlerKind != "":
			kind = defaultHandlerKind
		default:
			return nil, fmt.Errorf("unknown GraphStore: %q", str)
		}
	}

	h, ok := handlers[kind]
	if !ok {
		return nil, fmt.Errorf("no gsutil Handler registered for kind %q", kind)
	}
	return h(spec)
}

// EnsureGracefulExit will try to close each gs when notified of an Interrupt,
// SIGTERM, or Kill signal and immediately exit the program unsuccessfully. Any
// errors will be logged. This function should only be called once and closing
// the GraphStores manually is still needed when the program does not receive a
// signal to quit.
func EnsureGracefulExit(gs ...graphstore.Service) {
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	signal.Notify(c, syscall.SIGTERM)
	signal.Notify(c, os.Kill)
	go func() {
		sig := <-c
		log.Printf("graphstore: signal %v", sig)
		for _, g := range gs {
			LogClose(context.Background(), g)
		}
		os.Exit(1)
	}()
}

// LogClose closes gs and logs any resulting error.
func LogClose(ctx context.Context, gs graphstore.Service) {
	if err := gs.Close(ctx); err != nil {
		log.Printf("GraphStore failed to close: %v", err)
	}
}


text:
#ifndef _MYLIB
#define _MYLIB

#ifdef __cplusplus

extern "C" {

#else

#ifndef _MSC_VER

#define inline __inline

#endif

#endif

#include <stdio.h>
#include <stdlib.h>

#define NUM_THREADS \
  8  //  number of simultaneously executing threads you can have on
     //    your machine (not the number of threads you can spawn).
     //    Typically this equals the number of cores.

#define M(x) \
  x  //  parameter x is (M)odified by the routine, i.e. input & output
#define O(x) x  //  parameter x is set by the routine, i.e. (O)utput only

#define G(x) \
  x  //  function is a (G)enerator.  If function returns a bundle then all
     //  objects of
     //    the bundle are generated (but not the bundle!)
#define R(x) x  //  parameter x is the (R)eturn value

#define I(x) x  //  parameter x has its reference count (I)ncremented
#define C(x) x  //  a reference to parameter x is (C) consumed
#define S(x) \
  x  //  a reference to parameter x is (S) subsumed, i.e. made a (S)ub-object
#define F(x) x  //  parameter x is (F)reed by the routine
#define K(x) x  //  parameter x is (K)illed by the routine

#define X(x)  //  comment on parameters or effect of routine

typedef unsigned char uint8;
typedef unsigned short uint16;
typedef unsigned int uint32;
typedef unsigned long long uint64;
typedef signed char int8;
typedef signed short int16;
typedef signed int int32;
typedef signed long long int64;
typedef float float32;
typedef double float64;

typedef char *string;  //  Used to emphasize '\0' terminated string
typedef int boolean;   //  Used to emphasize == 0 is false, != 0 is on
typedef int tristate;  //  Used to emphasize == 0, > 0, < 0 is what matters

typedef int32 Dimn_Type;  //  Type of an array dimension
typedef int64 Indx_Type;  //  Type of an index into the data space of an array
typedef int64 Size_Type;  //  Type of the size of an array
typedef int64 Offs_Type;  //  Type of an offset within an array

#define DIMN_TYPE INT32_TYPE
#define INDX_TYPE INT64_TYPE
#define SIZE_TYPE INT64_TYPE
#define OFFS_TYPE INT64_TYPE

#define DIMN_SCALE 32
#define INDX_SCALE 64
#define SIZE_SCALE 64
#define OFFS_SCALE 64

typedef enum {
  UINT8_TYPE = 0,
  UINT16_TYPE = 1,
  UINT32_TYPE = 2,
  UINT64_TYPE = 3,
  INT8_TYPE = 4,
  INT16_TYPE = 5,
  INT32_TYPE = 6,
  INT64_TYPE = 7,
  FLOAT32_TYPE = 8,
  FLOAT64_TYPE = 9
} Value_Type;

typedef enum   //  Operations on array elements
{ SET_OP = 0,  //    See Array_Op_Scalar and Array_Op_Array below
  ADD_OP = 1,
  SUB_OP = 2,
  MUL_OP = 3,
  DIV_OP = 4,
  POW_OP = 5,
  LSH_OP = 6,
  RSH_OP = 7,
  MIN_OP = 8,
  MAX_OP = 9,
} Operator;

typedef enum    //  Comparator ops for defining regions: see Draw_Floodfill in
                //  draw.h &
{ LE_COMP = 0,  //     Record_Region in region.h
  LT_COMP = 1,
  EQ_COMP = 2,
  NE_COMP = 3,
  GT_COMP = 4,
  GE_COMP = 5 } Comparator;

typedef union {
  uint64 uval;   //    Use this variant for the 4 unsigned integers types
  int64 ival;    //    Use this variant for the 4 signed integer types
  float64 fval;  //    Use this variant for the 2 floating point number types
} Value;

typedef enum  //  The three possible "kinds" of types in a Value
{ UVAL = 0,
  IVAL = 1,
  FVAL = 2,
} Value_Kind;

#ifdef _MSC_VER

_inline Value VALU(uint64 u) {
  Value v;
  v.uval = u;
  return v;
}
_inline Value VALI(int64 i) {
  Value v;
  v.ival = i;
  return v;
}
_inline Value VALF(float64 f) {
  Value v;
  v.fval = f;
  return v;
}

#else

#define VALU(u) ((Value)(uint64)(u))
#define VALI(i) ((Value)(int64)(i))
#define VALF(f) ((Value)(float64)(f))

#endif

void Use_Zero_Boundary();
void Use_Reflective_Boundary();
void Use_Wrap_Boundary();
void Use_Extend_Boundary();
void Use_Inversion_Boundary();

#ifdef __cplusplus
}
#endif

#endif


text:
<?php

namespace mako\security\crypto;

use RuntimeException;

/**
 * Crypto exception.
 *
 * @author Yamada Taro
 */
class CryptoException extends RuntimeException
{

}


text:
require 'ebay/responses/abstract'
require 'ebay/responses/add_dispute'
require 'ebay/responses/add_dispute_response'
require 'ebay/responses/add_item'
require 'ebay/responses/add_live_auction_item'
require 'ebay/responses/add_member_message_aaq_to_partner'
require 'ebay/responses/add_member_message_rtq'
require 'ebay/responses/add_member_messages_aaq_to_bidder'
require 'ebay/responses/add_order'
require 'ebay/responses/add_second_chance_item'
require 'ebay/responses/add_to_item_description'
require 'ebay/responses/add_to_watch_list'
require 'ebay/responses/add_transaction_confirmation_item'
require 'ebay/responses/approve_live_auction_bidders'
require 'ebay/responses/complete_sale'
require 'ebay/responses/delete_my_messages'
require 'ebay/responses/end_item'
require 'ebay/responses/fetch_token'
require 'ebay/responses/get_account'
require 'ebay/responses/get_ad_format_leads'
require 'ebay/responses/get_all_bidders'
require 'ebay/responses/get_api_access_rules'
require 'ebay/responses/get_attributes_cs'
require 'ebay/responses/get_attributes_xsl'
require 'ebay/responses/get_best_offers'
require 'ebay/responses/get_bidder_list'
require 'ebay/responses/get_cart'
require 'ebay/responses/get_categories'
require 'ebay/responses/get_category2_cs'
require 'ebay/responses/get_category_features'
require 'ebay/responses/get_category_listings'
require 'ebay/responses/get_category_mappings'
require 'ebay/responses/get_category_specifics'
require 'ebay/responses/get_challenge_token'
require 'ebay/responses/get_charities'
require 'ebay/responses/get_contextual_keywords'
require 'ebay/responses/get_cross_promotions'
require 'ebay/responses/get_description_templates'
require 'ebay/responses/get_dispute'
require 'ebay/responses/get_feedback'
require 'ebay/responses/get_high_bidders'
require 'ebay/responses/get_item'
require 'ebay/responses/get_item_recommendations'
require 'ebay/responses/get_item_shipping'
require 'ebay/responses/get_item_transactions'
require 'ebay/responses/get_items_awaiting_feedback'
require 'ebay/responses/get_live_auction_bidders'
require 'ebay/responses/get_live_auction_catalog_details'
require 'ebay/responses/get_member_messages'
require 'ebay/responses/get_message_preferences'
require 'ebay/responses/get_my_messages'
require 'ebay/responses/get_my_ebay_buying'
require 'ebay/responses/get_my_ebay_reminders'
require 'ebay/responses/get_my_ebay_selling'
require 'ebay/responses/get_notification_preferences'
require 'ebay/responses/get_notifications_usage'
require 'ebay/responses/get_order_transactions'
require 'ebay/responses/get_orders'
require 'ebay/responses/get_picture_manager_details'
require 'ebay/responses/get_picture_manager_options'
require 'ebay/responses/get_popular_keywords'
require 'ebay/responses/get_product_family_members'
require 'ebay/responses/get_product_finder'
require 'ebay/responses/get_product_finder_xsl'
require 'ebay/responses/get_product_search_page'
require 'ebay/responses/get_product_search_results'
require 'ebay/responses/get_product_selling_pages'
require 'ebay/responses/get_products'
require 'ebay/responses/get_promotion_rules'
require 'ebay/responses/get_promotional_sale_details'
require 'ebay/responses/get_return_url'
require 'ebay/responses/get_ru_name'
require 'ebay/responses/get_search_results'
require 'ebay/responses/get_search_results_express'
require 'ebay/responses/get_seller_events'
require 'ebay/responses/get_seller_list'
require 'ebay/responses/get_seller_payments'
require 'ebay/responses/get_seller_transactions'
require 'ebay/responses/get_shipping_discount_profiles'
require 'ebay/responses/get_store'
require 'ebay/responses/get_store_category_update_status'
require 'ebay/responses/get_store_custom_page'
require 'ebay/responses/get_store_options'
require 'ebay/responses/get_store_preferences'
require 'ebay/responses/get_suggested_categories'
require 'ebay/responses/get_tax_table'
require 'ebay/responses/get_user'
require 'ebay/responses/get_user_contact_details'
require 'ebay/responses/get_user_disputes'
require 'ebay/responses/get_user_preferences'
require 'ebay/responses/get_vero_reason_code_details'
require 'ebay/responses/get_vero_report_status'
require 'ebay/responses/get_want_it_now_post'
require 'ebay/responses/get_want_it_now_search_results'
require 'ebay/responses/get_ebay_details'
require 'ebay/responses/get_ebay_official_time'
require 'ebay/responses/issue_refund'
require 'ebay/responses/leave_feedback'
require 'ebay/responses/place_offer'
require 'ebay/responses/relist_item'
require 'ebay/responses/remove_from_watch_list'
require 'ebay/responses/respond_to_best_offer'
require 'ebay/responses/respond_to_feedback'
require 'ebay/responses/respond_to_want_it_now_post'
require 'ebay/responses/revise_checkout_status'
require 'ebay/responses/revise_item'
require 'ebay/responses/revise_live_auction_item'
require 'ebay/responses/revise_my_messages'
require 'ebay/responses/revise_my_messages_folders'
require 'ebay/responses/seller_reverse_dispute'
require 'ebay/responses/send_invoice'
require 'ebay/responses/set_cart'
require 'ebay/responses/set_message_preferences'
require 'ebay/responses/set_notification_preferences'
require 'ebay/responses/set_picture_manager_details'
require 'ebay/responses/set_promotional_sale'
require 'ebay/responses/set_promotional_sale_listings'
require 'ebay/responses/set_return_url'
require 'ebay/responses/set_shipping_discount_profiles'
require 'ebay/responses/set_store'
require 'ebay/responses/set_store_categories'
require 'ebay/responses/set_store_custom_page'
require 'ebay/responses/set_store_preferences'
require 'ebay/responses/set_tax_table'
require 'ebay/responses/set_user_notes'
require 'ebay/responses/set_user_preferences'
require 'ebay/responses/upload_site_hosted_pictures'
require 'ebay/responses/validate_challenge_input'
require 'ebay/responses/validate_test_user_registration'
require 'ebay/responses/vero_report_items'
require 'ebay/responses/verify_add_item'
require 'ebay/responses/verify_add_second_chance_item'