text:
var Querystring = require('querystring');
var Crypto = require('crypto');
var Url = require('url');
var Hoek = require('hoek');
var Boom = require('boom');
var Cryptiles = require('cryptiles');
var Wreck = require('wreck');

// Declare internals

var internals = {};

exports.v1 = function (settings) {

    var client = new internals.Client(settings);

    return function (request, reply) {

        var cookie = settings.cookie;
        var name = settings.name;
        var query = request.query;
        var protocol = settings.forceHttps ? 'https' : 'http';

        // Bail if the upstream service returns an error

        if (query.error === 'access_denied' ||
            query.denied) {

            return reply(Boom.internal('Application rejected'));
        }

        // Sign-in Initialization

        if (!request.query.oauth_token) {

            // Obtain temporary OAuth credentials

            var oauth_callback = internals.location(request, protocol, settings.location);

            return client.temporary(oauth_callback, function (err, payload) {

                if (err) {
                    return reply(err);
                }

                var state = {
                    token: payload.oauth_token,
                    secret: payload.oauth_token_secret,
                    query: request.query
                };

                reply.state(cookie, state);

                var query = settings.providerParams ? Hoek.clone(settings.providerParams) : {};
                query.oauth_token = payload.oauth_token;

                return reply.redirect(settings.provider.auth + '?' + Querystring.encode(query));
            });
        }

        // Authorization callback

        if (!request.query.oauth_verifier) {
            return reply(Boom.internal('Missing verifier parameter in ' + name + ' authorization response'));
        }

        var state = request.state[cookie];
        if (!state) {
            return reply(Boom.internal('Missing ' + name + ' request token cookie'));
        }

        reply.unstate(cookie);

        if (request.query.oauth_token !== state.token) {
            return reply(Boom.internal(name + ' authorized request token mismatch'));
        }

        // Obtain token OAuth credentials

        client.token(state.token, request.query.oauth_verifier, state.secret, function (err, payload) {

            if (err) {
                return reply(err);
            }

            var credentials = {
                provider: name,
                token: payload.oauth_token,
                secret: payload.oauth_token_secret,
                query: state.query
            };

            if (!settings.provider.profile) {
                return reply(null, { credentials: credentials });
            }

            // Obtain user profile

            var get = function (uri, params, callback) {

                if (settings.profileParams) {
                    Hoek.merge(params, settings.profileParams);
                }

                return client.get(uri, params, payload.oauth_token, payload.oauth_token_secret, function (err, response) {

                    if (err) {
                        return reply(err);
                    }

                    callback(response);
                });
            };

            settings.provider.profile.call(settings, credentials, payload, get, function () {

                return reply(null, { credentials: credentials });
            });
        });
    };
};

exports.v2 = function (settings) {

    return function (request, reply) {

        var cookie = settings.cookie;
        var name = settings.name;
        var protocol = settings.forceHttps ? 'https' : 'http';

        // Bail if the upstream service returns an error
        if (request.query.error === 'access_denied' || request.query.denied) {
          return reply(Boom.internal('App was rejected'));
        }

        // Sign-in Initialization

        if (!request.query.code) {
            var nonce = Cryptiles.randomString(22);
            var query = Hoek.clone(settings.providerParams) || {};
            query.client_id = settings.clientId;
            query.response_type = 'code';
            query.redirect_uri = internals.location(request, protocol, settings.location);
            query.state = nonce;

            var scope = settings.scope || settings.provider.scope;
            if (scope) {
                query.scope = scope.join(settings.provider.scopeSeparator || ' ');
            }

            var state = {
                nonce: nonce,
                query: request.query
            };

            reply.state(cookie, state);
            return reply.redirect(settings.provider.auth + '?' + Querystring.encode(query));
        }

        // Authorization callback

        var state = request.state[cookie];
        if (!state) {
            return reply(Boom.internal('Missing ' + name + ' request token cookie'));
        }

        reply.unstate(cookie);

        if (state.nonce !== request.query.state) {
            return reply(Boom.internal('Incorrect ' + name + ' state parameter'));
        }

        var query = {
            client_id: settings.clientId,
            client_secret: settings.clientSecret,
            grant_type: 'authorization_code',
            code: request.query.code,
            redirect_uri: internals.location(request, protocol, settings.location)
        };

        var requestOptions = {
            payload: Querystring.stringify(query),
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
                // Authorization: 'Basic ' +  + (new Buffer(settings.clientId + ':' + settings.clientSecret, 'utf8')).toString('base64')
            }
        };

        if (settings.provider.headers) {
            Hoek.merge(requestOptions.headers, settings.provider.headers);
        }

        // Obtain token

        Wreck.post(settings.provider.token, requestOptions, function (err, res, payload) {

            if (err ||
                res.statusCode !== 200) {

                return reply(Boom.internal('Failed obtaining ' + name + ' access token', err || payload));
            }

            payload = internals.parse(payload);
            if (payload instanceof Error) {
                return reply(Boom.internal('Received invalid payload from ' + name + ' access token endpoint', payload));
            }

            var credentials = {
                provider: name,
                token: payload.access_token,
                refreshToken: payload.refresh_token,
                query: state.query
            };

            if (!settings.provider.profile) {
                return reply(null, { credentials: credentials });
            }

            // Obtain user profile

            var get = function (uri, params, callback) {

                var getOptions = {
                    headers: {
                        Authorization: 'Bearer ' + payload.access_token
                    }
                };

                if (settings.profileParams) {
                    Hoek.merge(params, settings.profileParams);
                }

                if (settings.provider.headers) {
                    Hoek.merge(getOptions.headers, settings.provider.headers);
                }

                var query = (params ? '?' + Querystring.encode(params) : '');
                Wreck.get(uri + query, getOptions, function (err, res, response) {

                    if (err ||
                        res.statusCode !== 200) {

                        return reply(Boom.internal('Failed obtaining ' + name + ' user profile', err || response));
                    }

                    response = internals.parse(response);
                    if (response instanceof Error) {
                        return reply(Boom.internal('Received invalid payload from ' + name + ' user profile', response));
                    }

                    return callback(response);
                });
            };

            settings.provider.profile.call(settings, credentials, payload, get, function () {

                return reply(null, { credentials: credentials });
            });
        });
    };
};

exports.Client = internals.Client = function (options) {

    this.provider = options.name;
    this.settings = {
        temporary: internals.Client.baseUri(options.provider.temporary),
        token: internals.Client.baseUri(options.provider.token),
        clientId: options.clientId,
        clientSecret: internals.encode(options.clientSecret || '') + '&',
        version: options.provider.version || ''
    };
};

internals.Client.prototype.temporary = function (oauth_callback, callback) {

    // Temporary Credentials (2.1)

    var oauth = {
        oauth_callback: oauth_callback
    };

    this.request('post', this.settings.temporary, null, oauth, undefined, 'temporary credentials', callback);
};

internals.Client.prototype.token = function (oauth_token, oauth_verifier, tokenSecret, callback) {

    // Token Credentials (2.3)

    var oauth = {
        oauth_token: oauth_token,
        oauth_verifier: oauth_verifier
    };

    this.request('post', this.settings.token, null, oauth, tokenSecret, 'token credentials', callback);
};

internals.Client.prototype.get = function (uri, params, oauth_token, tokenSecret, callback) {

    // Making Requests (3.1)

    var oauth = {
        oauth_token: oauth_token
    };

    this.request('get', uri, params, oauth, tokenSecret, 'token credentials', callback);
};

internals.Client.prototype.request = function (method, uri, params, oauth, tokenSecret, type, callback) {

    var provider = this.provider;

    if (this.settings.version) {
        oauth.oauth_version = this.settings.version;
    }

    oauth.oauth_nonce = Cryptiles.randomString(22);
    oauth.oauth_timestamp = Math.floor(Date.now() / 1000).toString();
    oauth.oauth_consumer_key = this.settings.clientId;
    oauth.oauth_signature_method = 'HMAC-SHA1';
    oauth.oauth_signature = this.signature(method, uri, params, oauth, tokenSecret);

    var query = params ? ('?' + Querystring.encode(params)) : '';
    Wreck[method](uri + query, { headers: { Authorization: internals.Client.header(oauth) } }, function (err, res, payload) {

        if (err ||
            res.statusCode !== 200) {

            return callback(Boom.internal('Failed obtaining ' + provider + ' ' + type, err || payload));
        }

        payload = internals.parse(payload);
        if (payload instanceof Error) {
            return callback(Boom.internal('Received invalid payload from ' + provider + ' ' + type + ' endpoint', payload));
        }

        return callback(null, payload);
    });
};

internals.Client.header = function (oauth) {

    // Authorization Header (3.5.1)

    var header = 'OAuth ';
    var names = Object.keys(oauth);
    for (var i = 0, il = names.length; i < il; ++i) {
        var name = names[i];
        header += (i ? ', ' : '') + name + '="' + internals.encode(oauth[name]) + '"';
    }

    return header;
};

internals.Client.baseUri = function (uri) {

    // Base String URI (3.4.1.2)

    var resource = Url.parse(uri, true);

    var protocol = resource.protocol.toLowerCase();
    var isDefaultPort = resource.port && ((protocol === 'http:' && resource.port === '80') || (protocol === 'https:' && resource.port === '443'));
    var baseUri = protocol + '//' + resource.hostname.toLowerCase() + (isDefaultPort || !resource.port ? '' : ':' + resource.port) + resource.pathname;
    return baseUri;
};

internals.Client.prototype.signature = function (method, baseUri, params, oauth, tokenSecret) {

    // Parameters Normalization (3.4.1.3.2)

    var normalized = [];
    var normalize = function (source) {
        var names = Object.keys(source);
        for (var i = 0, il = names.length; i < il; ++i) {
            var name = names[i];
            var value = source[name];

            var encodedName = internals.encode(name);
            if (Array.isArray(value)) {
                for (var v = 0, vl = value.length; v < vl; ++v) {
                    normalized.push([encodedName, internals.encode(value[v])]);
                }
            }
            else {
                normalized.push([encodedName, internals.encode(value)]);
            }
        }
    };

    if (params) {
        normalize(params);
    }

    normalize(oauth);

    normalized.sort(function (a, b) {

        return (a[0] < b[0] ? -1
                            : (a[0] > b[0] ? 1
                                           : (a[1] < b[1] ? -1
                                                          : (a[1] > b[1] ? 1 : 0))));
    });

    var normalizedParam = '';
    for (var i = 0, il = normalized.length; i < il; ++i) {
        normalizedParam += (i ? '&' : '') + normalized[i][0] + '=' + normalized[i][1];
    }

    // String Construction (3.4.1.1)

    var baseString = internals.encode(method.toUpperCase()) + '&' +
                     internals.encode(baseUri) + '&' +
                     internals.encode(normalizedParam);

    // HMAC-SHA1 (3.4.2)

    var key = tokenSecret ? (this.settings.clientSecret + internals.encode(tokenSecret)) : this.settings.clientSecret;
    return Crypto.createHmac('sha1', key).update(baseString).digest('base64');
};

internals.encodeLookup = function () {

    var lookup = {};
    for (var i = 0; i < 128; ++i) {
        if ((i >= 48 && i <= 57) || // 09
            (i >= 65 && i <= 90) || // AZ
            (i >= 97 && i <= 122) || // az
            i == 45 || // -
            i == 95 || // _
            i == 46 || // .
            i == 126) // ~
        {
            lookup[i] = String.fromCharCode(i);
        }
        else {
            lookup[i] = '%' + i.toString(16).toUpperCase();
        }
    }

    return lookup;
}();

internals.encode = function (string) {

    if (!string) {
        return '';
    }

    // Percent Encoding (3.6)

    var encoded = '';
    for (var i = 0, il = string.length; i < il; ++i) {
        encoded += internals.encodeLookup[string.charCodeAt(i)];
    }

    return encoded;
};

internals.parse = function (payload) {

    if (payload[0] === '{') {
        try {
            return JSON.parse(payload);
        }
        catch (err) {
            return err;
        }
    }

    return Querystring.parse(payload);
};

internals.location = function (request, protocol, location) {
    if (location) {
        return location + request.path;
    }
    // var info = request.connection.info;
    // var host = request.info.host || (info.host + ':' + info.port);
    var host = request.info.host || (request._host + ':' + request._port);

    return protocol + '://' + host + request.path;
};


text:
\chapter{Introduction}
\label{chap:introduction}

\section{Why HyperDex?}
\label{sec:introduction:why}

HyperDex is the next-generation key-value store, designed from the ground up to
provide a convenient user interface without sacrificing reliability, robustness,
or performance.  First and foremost, HyperDex enables developers to create new
applications quickly and with strong correctness guarantees.
HyperDex features:

\begin{description}
\item[Performance:]  HyperDex achieves lower latency and higher throughput than
many other key-value stores.  Support your application with fewer machines and
save on operational costs.

\item[Consistency:]  HyperDex provides strongly-consistent reads, writes, and
atomic operations, making strong guarantees to your application.  Other
key-value stores promise \texttt{eventual} consistency, leaving your application
to pick up the slack.  HyperDex solves the tough problems, enabling you to write
correct applications quickly with less effort.

\item[Fault Tolerance:]  HyperDex employs a unique, built-in fault-tolerance
mechanism to safe-guard your data.  Simply tell HyperDex how many failures your
cluster is likely to experience, and HyperDex ensures that your data is
replicated to withstand at least that many failures.  Where other systems
require you to fully understand the replication internals to bring
fault-tolerance your data, HyperDex's fault-tolerance mechanism is simple to
understand and straightforward to use.

\item[Scalability:]  HyperDex automatically scales as more machines are added to
the system.  Add additional servers to your HyperDex cluster to increase storage
capacity and achievable throughput.

\item[Easy-to-Use:]  HyperDex is easy to use in both development and production
environments.  Set up a HyperDex cluster quickly, and scale out to multiple
machines without any application-level changes.  Other systems may require that
your application know about internals of the deployment, such as cluster
membership, replication options, and sharding configurations.  HyperDex
internally and automatically manages your cluster so your application doesn't
have to.
\end{description}

\section{About this Book}
\label{sec:introduction:about}

This book is the definitive HyperDex reference manual for users, administrators,
and developers.  The HyperDex developers update this manual in tandem with each
release to ensure that the book serves as the best reference for HyperDex.

This book is divided into three parts, each of which is directed to a different
audience.  Part~\ref{part:for-developers}, ``For Developers'', provides an
introduction to HyperDex suitable for developers looking to build applications
on top of HyperDex.  The ``For Developers'' part of this book is written as a
series of tutorials that acquaint you with HyperDex's API and describe many of
the features available within HyperDex.

Part~\ref{part:for-admins}, ``For Administrators'', describes the day-to-day
maintenance of a HyperDex cluster.  The ``For Administrators'' portion of this
book is written as a series of small, isolated recipes that provide instruction
for maintaining and monitoring HyperDex clusters.

%Part~\ref{part:for-hackers}, ``For Hackers'', should be of interest to
%individuals looking to hack on HyperDex itself.  This portion of the book
%provides pointers to enterprising individuals looking to extend, modify, or
%contribute to HyperDex development.

Finally, Part~\ref{part:api-ref} provides an API reference for HyperDex.  This
section serves primarily as a reference of the developer-visible, and
operations-visible, components of HyperDex and should probably be used for
reference rather than read in its entirety.

This book is a continuous work in progress, and newer versions are available at
the \href{http://hyperdex.org/}{HyperDex website}.  The book's sources are
maintained alongside the HyperDex source code as the de-facto documentation for
HyperDex.  Patches, suggestions, and feedback about this book are welcome and
may be submitted using the contact information in the next section.

\section{Help and Support}
\label{sec:introduction:support}

If you run into trouble while working with HyperDex, don't panic!  The HyperDex
team have put together many support avenues to assist you.  Many of the
resources are available online for free.  When you need more support than that,
the HyperDex team is on standby with commercial support options that ensure that
you're never left in the dark.

\subsection{Online and Free Resources}
\label{sec:introduction:support:free}

The HyperDex team have assembled several free online resources to help you make
the most of HyperDex:

\begin{itemize}
\item HyperDex Reference Manual:  This document is the best avenue for support
    and assistance.  It serves as the canonical documentation of HyperDex and
    should be your first stop with any questions or problems.
\item \href{https://groups.google.com/group/hyperdex-discuss}{HyperDex Mailing List}:
    This open mailing list is the first resource most users turn to when solving
    problems.  Messages to the list are archived which makes it easy to search
    for solutions to your problem.  If you don't find a solution in the
    archives, start a new thread with your question and the HyperDex developers
    will try to help answer your questions.
\item \href{http://webchat.freenode.net/?channels=hyperdex\&uio=d4}{HyperDex IRC Channel}:
    The \texttt{\#hyperdex} IRC channel on Freenode is a great place to ask
    questions and interact with the HyperDex developers in real-time.
\item \href{https://github.com/rescrv/HyperDex/issues}{HyperDex Bug Tracker}:
    If you've encountered an error in the code that you think may be a bug,
    check the bug tracker to see if other users have reported the same problem.
    Consider reporting the problem yourself if it looks like the problem has not
    yet been reported.
\item \href{http://hyperdex.org/FAQ/}{HyperDex FAQ}:
    If you've got a question, check out the FAQ for frequently asked (and
    answered) questions.  The FAQ contains pointers to other resources to help
    solve your problems.
\item \href{http://hyperdex.org/papers/}{HyperDex Papers}:
    If you're interested in developing or changing the internals of HyperDex,
    we've published papers that detail the internal architecture and design
    principles of HyperDex.
\end{itemize}

\subsection{Commercial Support}
\label{sec:introduction:support:commercial}

Should you require more support, the HyperDex team is always on standby with
commercial support options to ensure you're never left in the dark.  If you're
in need of support, you can contact the HyperDex developers directly at {\em
support}@{\em hyperdex.org}.

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.12"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Mozzi: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="custom_stylesheet.css" rel="stylesheet" type="text/css"/>

Mozzi
    version 2016-12-11-17:03

sound synthesis library for Arduino

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Line< unsigned long > Member List

This is the complete list of members for Line< unsigned long >, including all inherited members.

Line()	Line< unsigned long >	inline

next()	Line< unsigned long >	inline

set(unsigned long value)	Line< unsigned long >	inline

set(unsigned long targetvalue, unsigned long num_steps)	Line< unsigned long >	inline

set(unsigned long startvalue, unsigned long targetvalue, unsigned long num_steps)	Line< unsigned long >	inline

Generated on Sun Dec 11 2016 17:03:11 for Mozzi by

     1.8.12


text:
import {NgModule} from '@angular/core';
import {MatIconModule} from '@angular/material/icon';
import {MatTableModule} from '@angular/material-experimental/mdc-table';
import {RouterModule} from '@angular/router';
import {MdcTableDemo} from './mdc-table-demo';
import {MdcTableExamplesModule} from '@angular/components-examples/material-experimental/mdc-table';

@NgModule({
  imports: [
    MatIconModule,
    MatTableModule,
    MdcTableExamplesModule,
    RouterModule.forChild([{path: '', component: MdcTableDemo}]),
  ],
  declarations: [MdcTableDemo],
})
export class MdcTableDemoModule {
}


text:
module Types
  class GroupType < NamespaceType
    graphql_name 'Group'

    authorize :read_group

    expose_permissions Types::PermissionTypes::Group

    field :web_url, GraphQL::STRING_TYPE, null: false,
          description: 'Web URL of the group'

    field :avatar_url, GraphQL::STRING_TYPE, null: true,
          description: 'Avatar URL of the group',
          resolve: -> (group, args, ctx) do
            group.avatar_url(only_path: false)
          end

    field :share_with_group_lock, GraphQL::BOOLEAN_TYPE, null: true,
          description: 'Indicates if sharing a project with another group within this group is prevented'

    field :project_creation_level, GraphQL::STRING_TYPE, null: true, method: :project_creation_level_str,
          description: 'The permission level required to create projects in the group'
    field :subgroup_creation_level, GraphQL::STRING_TYPE, null: true, method: :subgroup_creation_level_str,
          description: 'The permission level required to create subgroups within the group'

    field :require_two_factor_authentication, GraphQL::BOOLEAN_TYPE, null: true,
          description: 'Indicates if all users in this group are required to set up two-factor authentication'
    field :two_factor_grace_period, GraphQL::INT_TYPE, null: true,
          description: 'Time before two-factor authentication is enforced'

    field :auto_devops_enabled, GraphQL::BOOLEAN_TYPE, null: true,
          description: 'Indicates whether Auto DevOps is enabled for all projects within this group'

    field :emails_disabled, GraphQL::BOOLEAN_TYPE, null: true,
          description: 'Indicates if a group has email notifications disabled'

    field :mentions_disabled, GraphQL::BOOLEAN_TYPE, null: true,
          description: 'Indicates if a group is disabled from getting mentioned'

    field :parent, GroupType, null: true,
          description: 'Parent group',
          resolve: -> (obj, _args, _ctx) { Gitlab::Graphql::Loaders::BatchModelLoader.new(Group, obj.parent_id).find }

    field :issues,
          Types::IssueType.connection_type,
          null: true,
          description: 'Issues of the group',
          resolver: Resolvers::GroupIssuesResolver

    field :milestones, Types::MilestoneType.connection_type, null: true,
          description: 'Milestones of the group',
          resolver: Resolvers::GroupMilestonesResolver

    field :boards,
          Types::BoardType.connection_type,
          null: true,
          description: 'Boards of the group',
          max_page_size: 2000,
          resolver: Resolvers::BoardsResolver

    field :board,
          Types::BoardType,
          null: true,
          description: 'A single board of the group',
          resolver: Resolvers::BoardsResolver.single

    field :label,
          Types::LabelType,
          null: true,
          description: 'A label available on this group' do
            argument :title, GraphQL::STRING_TYPE,
              required: true,
              description: 'Title of the label'
          end

    def label(title:)
      BatchLoader::GraphQL.for(title).batch(key: group) do |titles, loader, args|
        LabelsFinder
          .new(current_user, group: args[:key], title: titles)
          .execute
          .each { |label| loader.call(label.title, label) }
      end
    end

    field :labels,
          Types::LabelType.connection_type,
          null: true,
          description: 'Labels available on this group' do
            argument :search_term, GraphQL::STRING_TYPE,
              required: false,
              description: 'A search term to find labels with'
          end

    def labels(search_term: nil)
      LabelsFinder
        .new(current_user, group: group, search: search_term)
        .execute
    end

    private

    def group
      object.respond_to?(:sync) ? object.sync : object
    end
  end
end

Types::GroupType.prepend_if_ee('EE::Types::GroupType')


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Package org.apache.hadoop.hdfs.util (Apache Hadoop HDFS 2.3.0 API)
</TITLE>

<META NAME="date" CONTENT="2015-03-06">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Package
org.apache.hadoop.hdfs.util

Packages that use org.apache.hadoop.hdfs.util

org.apache.hadoop.hdfs.server.namenode

org.apache.hadoop.hdfs.server.namenode.snapshot

org.apache.hadoop.hdfs.util

Classes in org.apache.hadoop.hdfs.util used by org.apache.hadoop.hdfs.server.namenode

Diff.Element

          An interface for the elements in a Diff.

EnumCounters

          Counters for an enum type.

EnumCounters.Map

          A key-value map which maps the keys to EnumCounters.

Classes in org.apache.hadoop.hdfs.util used by org.apache.hadoop.hdfs.server.namenode.snapshot

Diff.Element

          An interface for the elements in a Diff.

Classes in org.apache.hadoop.hdfs.util used by org.apache.hadoop.hdfs.util

Diff

          The difference between the current state and a previous state of a list.

Diff.Container

          Containing exactly one element.

Diff.Element

          An interface for the elements in a Diff.

Diff.ListType

Diff.Processor

          An interface for passing a method in order to process elements.

Diff.UndoInfo

          Undo information for some operations such as delete(E)
 and Diff.modify(Element, Element).

EnumCounters

          Counters for an enum type.

EnumCounters.Factory

          A factory for creating counters.

LightWeightHashSet

          A low memory linked hash set implementation, which uses an array for storing
 the elements and linked lists for collision resolution.

XMLUtils.InvalidXmlException

          Exception that reflects an invalid XML document.

XMLUtils.Stanza

          Represents a bag of key-value pairs encountered during parsing an XML
 file.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2015 Apache Software Foundation. All Rights Reserved.


text:
<!DOCTYPE html>

    <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="">
    <meta name="author" content="">

    <title>Outside Chat</title>

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

    <link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=Merriweather:400,300,300italic,400italic,700,700italic,900,900italic' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="font-awesome/css/font-awesome.min.css" type="text/css">

    <link rel="stylesheet" href="css/animate.min.css" type="text/css">

    <link rel="stylesheet" href="css/creative.css" type="text/css">

                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                OutsideChat

                        About

                        Features

Never get held back by data or WiFi again.

Keep in touch with friends and communicate with fellow Outside Lands attendees via our peer-to-peer dataless mesh network.

                Coming Soon

100,000 concertgoers does a lot of damage to the network.

Any attendee with our iOS app will be able to communicate with one another without using cellular data or WiFi (and even with a phone in airplane mode!). That means that even at music festivals with huge crowds, your messages to friends will always go through. Never again will you be alone in a crowd, unaware of where your group is.

                    Check it out!

Features

Encrypted Direct Messaging

Rest assured, any message sent through our mesh network can only be accessed by the intended recipient.

Location Updates

Share your location with contacts and find friends.

Admin Account

Organizers can broadcast updates that all festival attendees will receive.

Weather

Get notified of the weather, even without a data connection.

Made with Love

Zachary Liu, Monica Shi, Victor Zhou


text:
    <meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" />
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" />
    <title>Append Method</title>
    <xml>
    </xml>
    <link rel="stylesheet" type="text/css" href="MSDN.css" />

            log4net SDK Documentation - Microsoft .NET Framework 4.0

AspNetTraceAppender.Append Method

 Write the logging event to the ASP.NET trace

Overload List

 Write the logging event to the ASP.NET trace

        protected override void Append(LoggingEvent);

Inherited from AppenderSkeleton.

        protected virtual void Append(LoggingEvent[]);

See Also

        AspNetTraceAppender Class | log4net.Appender Namespace

          Copyright 2004-2011 The Apache Software Foundation.


text: export { default } from "./useDataViewerMenu";


text:
namespace bluez {

// BluetoothGattServiceServiceProvider is used to provide a D-Bus object that
// the Bluetooth daemon can communicate with to register GATT service
// hierarchies.
//
// Instantiate with a chosen D-Bus object path (that conforms to the BlueZ GATT
// service specification), service UUID, and the list of included services, and
// pass the D-Bus object path as the |service_path| argument to the
// bluez::BluetoothGattManagerClient::RegisterService method. Make sure to
// create characteristic and descriptor objects using the appropriate service
// providers before registering a GATT service with the Bluetooth daemon.
class DEVICE_BLUETOOTH_EXPORT BluetoothGattServiceServiceProvider {
 public:
  BluetoothGattServiceServiceProvider(
      const BluetoothGattServiceServiceProvider&) = delete;
  BluetoothGattServiceServiceProvider& operator=(
      const BluetoothGattServiceServiceProvider&) = delete;

  virtual ~BluetoothGattServiceServiceProvider();

  // Writes an array of the service's properties into the provided writer.
  virtual void WriteProperties(dbus::MessageWriter* writer) {}

  virtual const dbus::ObjectPath& object_path() const = 0;

  // Creates the instance where |bus| is the D-Bus bus connection to export the
  // object onto, |object_path| is the object path that it should have, |uuid|
  // is the 128-bit GATT service UUID, and |includes| are a list of object paths
  // belonging to other exported GATT services that are included by the GATT
  // service being created. Make sure that all included services have been
  // exported before registering a GATT services with the GATT manager.
  static BluetoothGattServiceServiceProvider* Create(
      dbus::Bus* bus,
      const dbus::ObjectPath& object_path,
      const std::string& uuid,
      bool is_primary,
      const std::vector<dbus::ObjectPath>& includes);

 protected:
  BluetoothGattServiceServiceProvider();
};

}  // namespace bluez

#endif  // DEVICE_BLUETOOTH_DBUS_BLUETOOTH_GATT_SERVICE_SERVICE_PROVIDER_H_


text:
<?php

namespace Amadeus\Client\Struct\Pnr\AddMultiElements;

/**
 * Account
 *
 * @package Amadeus\Client\Struct\Pnr\AddMultiElements
 */
class Account
{
    /**
     * @var string
     */
    public $number;

    /**
     * @var string
     */
    public $costNumber;

    /**
     * @var string
     */
    public $companyNumber;

    /**
     * @var string
     */
    public $clientReference;

    /**
     * @var string
     */
    public $gSTTaxDetails;

    /**
     * Account constructor.
     *
     * @param null $number
     */
    public function __construct($number = null)
    {
        $this->number = $number;
    }
}


text:
FactoryGirl.define do

  factory :video, :class => 'Postablr::Entry::Video' do
    url "http://vimeo.com/55769583"
    #title "MyString"
    #product_id 1
    #thumbnail "MyString"
    #embed_url ""
    #embed_html "MyText"
    #flv "MyString"
    #download_url "MyString"
    #service "MyString"
    #duration 1
  end

  factory :youtube_video, :parent => :video do
    url "https://www.youtube.com/watch?v=5aFRBbnF-ag"
  end

end


text:
package com.flowpowered.api.generator;

import com.flowpowered.api.geo.World;
import com.flowpowered.api.material.BlockMaterial;
import com.flowpowered.api.util.cuboid.CuboidBlockMaterialBuffer;

/**
 * Generates an empty world using air blocks
 */
public class EmptyWorldGenerator implements WorldGenerator {
    @Override
    public void generate(CuboidBlockMaterialBuffer blockData, World world) {
        blockData.flood(BlockMaterial.AIR);
    }

    @Override
    public Populator[] getPopulators() {
        return new Populator[0];
    }

    @Override
    public String getName() {
        return "EmptyWorld";
    }
}


text:
import os
import locale
import datetime
import time
import urwid as uw
from urwid_timed_progress import TimedProgressBar

class App(object):

    palette = [
        ('normal',   'white', 'black', 'standout'),
        ('complete', 'white', 'dark magenta'),
        ('footer',   'white', 'dark gray'),
    ]

    # Using SI units: https://en.wikipedia.org/wiki/Kilobyte
    units = [
        ('B', 1),
        ('kB', 1000),
        ('MB', 1000000),
        ('GB', 1000000000),
    ]

    locale.setlocale(locale.LC_ALL, '')

    def __init__(self, reaper, rm_after_download=True, auto_run=False,
                 sd_data_dir=''):
        self.rm_after_download = rm_after_download
        self.sd_data_dir = sd_data_dir
        self.reaper = reaper
        self.file_progress = TimedProgressBar('normal',
                                              'complete',
                                              label='Current File',
                                              label_width=13,
                                              units=App.units,
                                              done=.001)

        self.overall_progress = TimedProgressBar('normal',
                                                 'complete',
                                                 label='Overall',
                                                 label_width=13,
                                                 units=App.units,
                                                 done=.001)

        info = self.reaper.info()
        self.device_id = info['samd_id'][2:]
        self.file_count = uw.Text('')
        self.file_list = self.reaper.ls(self.sd_data_dir)
        self.update_file_count()

        info_text = [
            'Device Id: {}'.format(self.device_id),
            'Port: {}'.format(self.reaper.conn.name),
            'SD Info: {} {} {} {} {}'.format(
                info['sd_mid'][2:],
                info['sd_oid'],
                info['sd_pnm'],
                info['sd_prv'],
                info['sd_mdt']),
            'SD Serial: {}'.format(info['sd_psn'][2:]),
            'SD Size: {:.2f} GB'.format(float(info['sd_size']) * 512 / 1e9),
        ]

        # Lookup device name, create a short one if not found
        device_name = self.reaper.get_device_name(self.device_id)
        if device_name is None:
            device_name = 'tag-{}'.format(self.device_id[-5:])
            self.reaper.set_device_name(device_name, self.device_id)

        # Invoked when editing device name is complete
        def device_name_handler(new_name):
            device_id = self.reaper.get_device_id(new_name)

            # name not changed
            if device_id == self.device_id:
                self.status('-ready-')
                return True

            # name not being used yet
            if device_id is None:
                self.reaper.set_device_name(new_name, self.device_id)
                self.status('-ready-')
                return True

            # name already being used
            else:
                msg = ('Device Name "{}" already used for device "{}"\n' +
                       'Please choose another name.').format(new_name,
                                                             device_id)
                self.status(msg)
                return False

        # device name edit field
        self.device_name = edit_field('Device Name: ',
                                      device_name,
                                      device_name_handler)

        info_left = uw.Pile(
            [self.device_name] +
            [uw.Text(t) for t in info_text] +
            [self.file_count])

        self.clock = Clock('')

        info_right = uw.Pile([uw.Padding(self.clock, align='right', width=13)])

        info_box = uw.LineBox(uw.Columns([info_left, info_right]))

        self._status = uw.Text('-ready-')
        self.debug_message = uw.Text('')

        commands = [('r', 'run download'),
                    ('n', 'set device name'),
                    ('c', 'set device clock'),
                    ('q', 'exit')]

        footer = uw.Text(' | '.join(['{} = {}'.format(key, text)
                                    for key, text in commands]))

        self.footer = uw.AttrWrap(footer, 'footer')

        main_view = uw.Frame(uw.ListBox([info_box,
                                         uw.Divider(),
                                         self.file_progress,
                                         uw.Divider(),
                                         uw.Divider(),
                                         self.overall_progress,
                                         uw.Divider(),
                                         uw.Divider(),
                                         self._status,
                                         uw.Divider(),
                                         self.debug_message,
                                         ]),
                             footer=self.footer)

        def keypress(key):
            if key in ('q', 'Q'):
                raise uw.ExitMainLoop()
            elif key in ('r', 'R'):
                self.download()
            elif key in ('c', 'C'):
                self.set_device_clock()
            elif key in ('n', 'N'):
                self.status('Enter new Device Name')
                self.device_name.edit_mode()

        self.loop = uw.MainLoop(main_view,
                                App.palette,
                                unhandled_input=keypress)
        if auto_run:
            def run(*args, **kwargs):
                self.set_device_clock()
                time.sleep(.5)
                self.download()
            self.loop.set_alarm_in(0.5, run)
        else:
            self.loop.set_alarm_in(0.5, self.set_device_clock)

        self.loop.set_alarm_in(1, self.clock.refresh)
        self.loop.run()

    def set_device_clock(self, *args, **kwargs):
        self.status('Setting device clock to current UTC time ...')
        self.reaper.set_time()
        dt = self.reaper.get_time()
        self.status('Device clock set to {}\n\n-ready-'.format(dt))

    def status(self, msg):
        self._status.set_text(msg)
        self.clock.refresh_once()
        self.loop.draw_screen()

    def update_file_count(self):
        if self.file_list is None:
            t = 'n/a'
        else:
            t = locale.format('%d', len(self.file_list), grouping=True)
        self.file_count.set_text('# of Files: {}'.format(t))

    def download(self):
        if self.file_list is None:
            self.get_file_list()
        total_size = sum([f['size'] for f in self.file_list])
        self.overall_progress.done = total_size if total_size != 0 else .001
        self.status('starting download ...')
        for f in list(self.file_list):
            if f['size'] > 0:
                self.file_progress.reset()
                self.file_progress.done = f['size']
                self.loop.draw_screen()

                def progress_fun(num_bytes, _):
                    self.file_progress.add_progress(num_bytes)
                    self.overall_progress.add_progress(num_bytes)
                    self.clock.refresh_once()
                    self.loop.draw_screen()

                data_dir = os.path.join(self.reaper.data_dir, self.device_id)

                sd_filename = f['name'].lstrip('/')
                local_filename = os.path.join(data_dir, sd_filename)
                dirname = os.path.dirname(local_filename)
                if not os.path.exists(dirname):
                    os.makedirs(dirname)

                while os.path.exists(local_filename):
                    local_filename = increment_filename(local_filename)

                self.status('downloading {} to {} ...'.format(sd_filename,
                                                              local_filename))
                self.reaper.cp(sd_filename,
                               local_filename,
                               f['size'],
                               progress_fun)

            # remove file
            if self.rm_after_download:
                self.reaper.rm(f['name'])
            self.file_list = self.file_list[1:]
            self.update_file_count()
        self.status('-ready-')

    def debug(self, m):
        self.debug_message.set_text(m)
        self.loop.draw_screen()

def edit_field(caption, edit_text, handler):
    edit = uw.Edit(caption, edit_text)
    ef = EditField(edit, handler)
    return uw.BoxAdapter(ef, height=1)

class Clock(uw.Text):
    def refresh_once(self):
        now = datetime.datetime.utcnow()
        self.set_text('{}\n{}'.format(
            now.strftime('%Y-%m-%d'),
            now.strftime('%H:%M:%S UTC')))

    def refresh(self, loop=None, data=None):
        self.refresh_once()
        loop.set_alarm_in(1, self.refresh)

class EditField(uw.Filler):
    def __init__(self, edit, handler):
        super(EditField, self).__init__(edit)
        self.edit_widget = edit
        self.handler = handler
        self.text_widget = uw.Text('')
        self.value = self.edit_widget.edit_text
        self.text_mode()

    def edit_mode(self):
        self.original_widget = self.edit_widget

    def text_mode(self):
        self.text_widget.set_text(self.edit_widget.caption + self.value)
        self.original_widget = self.text_widget

    def keypress(self, size, key):
        if key == 'esc':
            self.text_mode()
            self.handler(self.value)

        elif key == 'enter':
            if self.edit_widget.edit_text != self.value:
                if self.handler(self.edit_widget.edit_text):
                    self.value = self.edit_widget.edit_text
                    self.text_mode()
        else:
            return super(EditField, self).keypress(size, key)

def increment_filename(filename):
    parts = filename.rsplit('-', 1)
    try:
        counter = int(parts[1])
    except:
        counter = 0
    return '{}-{}'.format(parts[0], counter + 1)


text:
<Alloy>
    <Window id="win" class="container" formFactor="handheld">
        <View id="viewMain">
            <View id="viewHeader">Startsiden</View>
            <ListView>
                <ListSection>
                    <ListItem title="News Article 1"></ListItem>
                    <ListItem title="News Article 2"></ListItem>
                    <ListItem title="News Article 3"></ListItem>
                </ListSection>
            </ListView>
        </View>
    </Window>
    <Window id="win" class="container" formFactor="tablet">
        <View id="viewMain">
            <View id="viewHeader">Startsiden</View>
            <WebView id="webBrowserView" hideLoadIndicator="true" scrollsToTop="true" url="http://www.abcnyheter.no" />
        </View>
    </Window>
</Alloy>


text:
title: Palringo python bot
tags: [python,python 3.4,palringo,bot]
category: blog
layout: post

---

This is a Palringo bot developed in python by me. It's completely open source and easy to __build__ upon.
The bot uses __Python 3.4+__

In order to log on you must enter your __credentials__ on main.py. line:

```python
##LOGON INFORMATION HERE ===================================
parser.sendLogon('email@domain.ltd')
passwd = "password"
## ---------------------------------------------------------
```
In order to alter the bot's functionality you must change the code in main.py. There are a few functions that handle data, such as:

```python
#getters

parser.getCommand()   #gets the packet commend
parser.getSourceID()  #returns the userID of the person who sent the message(packet)
parser.getTargetID()  #returns the group the message(packet) was sent in
parser.getPayload()   #returns the packet payload. whether it be a message or any other information

#handy functions

parser.sendGroupMessage('groupID', 'message')
parser.sendPrivateMessage('userID', 'message')

```

I've included in the source code a few examples on what the bot can do based on packets/messages sent to it. Example:

```python
#if a group message comes in
if ( parser.getCommand() == 'GroupMESG'):
  ## if someone talks
    if ( parser.getSourceID() != 0 ):
        parser.sendGroupMessage(parser.getTargetID(), "shut up")
```

As you can see, you can change the __bot__ to behave how you want, which is pretty cool, the only problem is that this is not yet complete

The bot and source-code are free for download from github under an MIT license. [palring-python-bot-3.4](https://github.com/ArielSaldana/palringo-python-bot).

Connect with Ariel on [Twitter](https://twitter.com/yerariel) & <a rel="author" href="https://plus.google.com/+ArielSal"> Google+ </a>


text:
/// Copyright (c) 2012 Ecma International.  All rights reserved.
/**
 * @path ch15/15.2/15.2.3/15.2.3.6/15.2.3.6-2-16.js
 * @description Object.defineProperty - argument 'P' is a number that converts to a string (value is 1(following 22 zeros))
 */

function testcase() {
        var obj = {};
        Object.defineProperty(obj, 10000000000000000000000, {});

        return obj.hasOwnProperty("1e+22");

    }
runTestCase(testcase);


text:
if (serverhandlers.requestHandler === undefined) {
  throw new Packages.net.appjet.oui.NoHandlerException("No request handler defined!");
}

// default content type for request
response.setContentType('text/html; charset=utf-8');

serverhandlers.requestHandler();


text:
package com.jcwhatever.nucleus.internal.managed.scripting.api.views;

import com.jcwhatever.nucleus.mixins.IDisposable;
import com.jcwhatever.nucleus.utils.PreCon;
import com.jcwhatever.nucleus.utils.items.ItemFilter;
import com.jcwhatever.nucleus.utils.text.TextUtils;
import com.jcwhatever.nucleus.views.View;
import com.jcwhatever.nucleus.views.ViewSession;
import com.jcwhatever.nucleus.views.anvil.FilteredAnvilView;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;

import javax.annotation.Nullable;

/**
 * A {@link FilteredAnvilView} implementation for scripts.
 */
public class ScriptAnvilView extends FilteredAnvilView implements IDisposable {

    private final Player _player;

    private CharSequence _denyMsg;
    private boolean _isDisposed;

    /**
     * Constructor.
     *
     * @param plugin      The views owning plugin.
     * @param player      The player the view is for.
     * @param itemFilter  The filter manager used to allow or deny specific items.
     */
    public ScriptAnvilView(Plugin plugin, Player player, ItemFilter itemFilter) {
        super(plugin, itemFilter);

        PreCon.notNull(player);

        _player = player;
    }

    /**
     * Open the view to the player.
     *
     * @return  Self for chaining.
     */
    public ScriptAnvilView open() {

        ViewSession viewSession = ViewSession.get(_player, null);

        viewSession.next(this);

        return this;
    }

    /**
     * Close the view to the player.
     *
     * @return  Self for chaining.
     */
    public ScriptAnvilView close() {

        ViewSession viewSession = ViewSession.get(_player, null);

        if (!viewSession.contains(this))
            return this;

        View view = viewSession.getCurrent();

        // close all views opened after this view
        while (view != null && !view.equals(this)) {
            viewSession.previous();
            view = viewSession.getCurrent();
        }

        if (view != null && view.equals(this))
            viewSession.previous();

        return this;
    }

    @Override
    public boolean isDisposed() {
        return _isDisposed;
    }

    @Override
    public void dispose() {
        _isDisposed = true;
    }

    @Override
    public String getDenyMessage() {
        return _denyMsg == null ? super.getDenyMessage() : _denyMsg.toString();
    }

    public void setDenyMessage(@Nullable CharSequence message) {

        if (message != null)
            message = TextUtils.format(message);

        _denyMsg = message;
    }
}


text:
namespace Microsoft.Azure.Management.Internal.Network.Version2017_10_01.Models
{

    /// <summary>
    /// Defines values for Direction.
    /// </summary>
    public static class Direction
    {
        public const string Inbound = "Inbound";
        public const string Outbound = "Outbound";
    }
}


text:
layout: post
title: Convert data and ASCII
author: FrozenFOXX
tags:
 - shell
 - devops
---

Ever have to supply the contents of a binary file from a text source like Hiera? It's rare but it's happened to me, particularly with Jenkins. Turns out there's a quick and easy way to do so using our old friend `dd`.

To convert from a binary data file to an ASCII file: `dd conv=ascii if=[data file] of=[ascii file]`.

To convert from an ASCII file back into a binary data file: `dd conv=ebcdic if=[ascii file] of=[data file]`

Hopefully you'll never find yourself in a position like this but it can be useful for all sorts of times when binary information needs to be read or written using tools that just aren't used to handling it.


text:
from django.db.models.signals import post_save, post_delete
from django.db import models

from wagtail.wagtailsearch.index import Indexed
from wagtail.wagtailsearch.backends import get_search_backends

def post_save_signal_handler(instance, **kwargs):
    for backend in get_search_backends():
        backend.add(instance)

def post_delete_signal_handler(instance, **kwargs):
    for backend in get_search_backends():
        backend.delete(instance)

def register_signal_handlers():
    # Get list of models that should be indexed
    indexed_models = [model for model in models.get_models() if issubclass(model, Indexed)]

    # Loop through list and register signal handlers for each one
    for model in indexed_models:
        post_save.connect(post_save_signal_handler, sender=model)
        post_delete.connect(post_delete_signal_handler, sender=model)


text:
$.fn.uploadHandler = function(s3presignedApiUri) {
	var fileupload = this,
		fileupload0 = fileupload[0];

	function readfiles(files) {
		var fileCounter=files.length;

		for (var file, i = 0; i < fileCounter; i++) {
			file = files[i];
			// if(files[i].name && !files[i].name.match(/.(gif|jpe?g|png|svg)$/i)) {
			// 	alert("images only");
			// 	return;
			// }
			$.ajax({
				url : s3presignedApiUri,
				data: 'file='+ file.name + '&mime=' + file.type,
				type : "GET",
				dataType : "json",
				cache : false,
			})
			.done(function(data) {
				if(data.error) {
					console.error(data.error); // REMOVE ME FOR PRODUCTION USE
				} else {
					uploadFile(file, data.url);
				}
			})
			.fail(function(e) {
				console.error("S3 Upload not supported",e); // REMOVE ME FOR PRODUCTION USE
			});
		}

	}

	function uploadFile(file, s3presignedUrl) {
		$.ajax({
			url : s3presignedUrl,
			type : "PUT",
			data : file,
			dataType : "text",
			cache : false,
			contentType : file.type,
			processData : false
		})
		.done(function() {
			var newFileUrl = s3presignedUrl.split('?')[0].substr(6);
			console.info("s3-upload done: ", newFileUrl); // REMOVE ME FOR PRODUCTION USE

			////////////////////////////////////////////
			// do something here with the file url //
			////////////////////////////////////////////
		})
		.fail(function(e) {
			console.error("s3-upload failed",e); // REMOVE ME FOR PRODUCTION USE
		});
	}

	fileupload0.onchange = function () {
		if(this.files.length) {
			readfiles(this.files);
		}
	};

};


text:
import {Injector} from '../../di/injector';

import {assertLView} from '../assert';
import {discoverLocalRefs, getComponentAtNodeIndex, getDirectivesAtNodeIndex, getLContext} from '../context_discovery';
import {NodeInjector} from '../di';
import {LContext} from '../interfaces/context';
import {DirectiveDef} from '../interfaces/definition';
import {TElementNode, TNode, TNodeProviderIndexes} from '../interfaces/node';
import {CLEANUP, CONTEXT, FLAGS, HOST, LView, LViewFlags, TVIEW} from '../interfaces/view';
import {renderStringify} from './misc_utils';
import {getLViewParent, getRootContext} from './view_traversal_utils';
import {unwrapRNode} from './view_utils';

/**
 * Returns the component instance associated with a given DOM host element.
 * Elements which don't represent components return `null`.
 *
 * @param element Host DOM element from which the component should be retrieved.
 *
 * ```
 * <my-app>
 *   #VIEW
 *     <div>
 *       <child-comp></child-comp>
 *     </div>
 * </mp-app>
 *
 * expect(getComponent(<child-comp>) instanceof ChildComponent).toBeTruthy();
 * expect(getComponent(<my-app>) instanceof MyApp).toBeTruthy();
 * ```
 *
 * @publicApi
 */
export function getComponent<T = {}>(element: Element): T|null {
  const context = loadLContextFromNode(element);

  if (context.component === undefined) {
    context.component = getComponentAtNodeIndex(context.nodeIndex, context.lView);
  }

  return context.component as T;
}

/**
 * Returns the component instance associated with a given DOM host element.
 * Elements which don't represent components return `null`.
 *
 * @param element Host DOM element from which the component should be retrieved.
 *
 * ```
 * <my-app>
 *   #VIEW
 *     <div>
 *       <child-comp></child-comp>
 *     </div>
 * </mp-app>
 *
 * expect(getComponent(<child-comp>) instanceof ChildComponent).toBeTruthy();
 * expect(getComponent(<my-app>) instanceof MyApp).toBeTruthy();
 * ```
 *
 * @publicApi
 */
export function getContext<T = {}>(element: Element): T|null {
  const context = loadLContextFromNode(element) !;
  return context.lView[CONTEXT] as T;
}

/**
 * Returns the component instance associated with view which owns the DOM element (`null`
 * otherwise).
 *
 * @param element DOM element which is owned by an existing component's view.
 *
 * ```
 * <my-app>
 *   #VIEW
 *     <div>
 *       <child-comp></child-comp>
 *     </div>
 * </mp-app>
 *
 * expect(getViewComponent(<child-comp>) instanceof MyApp).toBeTruthy();
 * expect(getViewComponent(<my-app>)).toEqual(null);
 * ```
 *
 * @publicApi
 */
export function getViewComponent<T = {}>(element: Element | {}): T|null {
  const context = loadLContext(element) !;
  let lView = context.lView;
  let parent: LView|null;
  ngDevMode && assertLView(lView);
  while (lView[HOST] === null && (parent = getLViewParent(lView) !)) {
    // As long as lView[HOST] is null we know we are part of sub-template such as `*ngIf`
    lView = parent;
  }
  return lView[FLAGS] & LViewFlags.IsRoot ? null : lView[CONTEXT] as T;
}

/**
 * Retrieve all root components.
 *
 * Root components are those which have been bootstrapped by Angular.
 *
 * @param target A DOM element, component or directive instance.
 *
 * @publicApi
 */
export function getRootComponents(target: {}): any[] {
  return [...getRootContext(target).components];
}

/**
 * Retrieves an `Injector` associated with the element, component or directive.
 *
 * @param target A DOM element, component or directive instance.
 *
 * @publicApi
 */
export function getInjector(target: {}): Injector {
  const context = loadLContext(target);
  const tNode = context.lView[TVIEW].data[context.nodeIndex] as TElementNode;
  return new NodeInjector(tNode, context.lView);
}

/**
 * Retrieve a set of injection tokens at a given DOM node.
 *
 * @param element Element for which the injection tokens should be retrieved.
 * @publicApi
 */
export function getInjectionTokens(element: Element): any[] {
  const context = loadLContext(element, false);
  if (!context) return [];
  const lView = context.lView;
  const tView = lView[TVIEW];
  const tNode = tView.data[context.nodeIndex] as TNode;
  const providerTokens: any[] = [];
  const startIndex = tNode.providerIndexes & TNodeProviderIndexes.ProvidersStartIndexMask;
  const endIndex = tNode.directiveEnd;
  for (let i = startIndex; i < endIndex; i++) {
    let value = tView.data[i];
    if (isDirectiveDefHack(value)) {
      // The fact that we sometimes store Type and sometimes DirectiveDef in this location is a
      // design flaw.  We should always store same type so that we can be monomorphic. The issue
      // is that for Components/Directives we store the def instead the type. The correct behavior
      // is that we should always be storing injectable type in this location.
      value = value.type;
    }
    providerTokens.push(value);
  }
  return providerTokens;
}

/**
 * Retrieves directives associated with a given DOM host element.
 *
 * @param target A DOM element, component or directive instance.
 *
 * @publicApi
 */
export function getDirectives(target: {}): Array<{}> {
  const context = loadLContext(target) !;

  if (context.directives === undefined) {
    context.directives = getDirectivesAtNodeIndex(context.nodeIndex, context.lView, false);
  }

  return context.directives || [];
}

/**
 * Returns LContext associated with a target passed as an argument.
 * Throws if a given target doesn't have associated LContext.
 *
 */
export function loadLContext(target: {}): LContext;
export function loadLContext(target: {}, throwOnNotFound: false): LContext|null;
export function loadLContext(target: {}, throwOnNotFound: boolean = true): LContext|null {
  const context = getLContext(target);
  if (!context && throwOnNotFound) {
    throw new Error(
        ngDevMode ? `Unable to find context associated with ${renderStringify(target)}` :
                    'Invalid ng target');
  }
  return context;
}

/**
 * Retrieve map of local references.
 *
 * The references are retrieved as a map of local reference name to element or directive instance.
 *
 * @param target A DOM element, component or directive instance.
 *
 * @publicApi
 */
export function getLocalRefs(target: {}): {[key: string]: any} {
  const context = loadLContext(target) !;

  if (context.localRefs === undefined) {
    context.localRefs = discoverLocalRefs(context.lView, context.nodeIndex);
  }

  return context.localRefs || {};
}

/**
 * Retrieve the host element of the component.
 *
 * Use this function to retrieve the host element of the component. The host
 * element is the element which the component is associated with.
 *
 * @param directive Component or Directive for which the host element should be retrieved.
 *
 * @publicApi
 */
export function getHostElement<T>(directive: T): Element {
  return getLContext(directive) !.native as never as Element;
}

/**
 * Retrieves the rendered text for a given component.
 *
 * This function retrieves the host element of a component and
 * and then returns the `textContent` for that element. This implies
 * that the text returned will include re-projected content of
 * the component as well.
 *
 * @param component The component to return the content text for.
 */
export function getRenderedText(component: any): string {
  const hostElement = getHostElement(component);
  return hostElement.textContent || '';
}

export function loadLContextFromNode(node: Node): LContext {
  if (!(node instanceof Node)) throw new Error('Expecting instance of DOM Node');
  return loadLContext(node) !;
}

export interface Listener {
  name: string;
  element: Element;
  callback: (value: any) => any;
  useCapture: boolean|null;
}

export function isBrowserEvents(listener: Listener): boolean {
  // Browser events are those which don't have `useCapture` as boolean.
  return typeof listener.useCapture === 'boolean';
}

/**
 * Retrieves a list of DOM listeners.
 *
 * ```
 * <my-app>
 *   #VIEW
 *     <div (click)="doSomething()">
 *     </div>
 * </mp-app>
 *
 * expect(getListeners(<div>)).toEqual({
 *   name: 'click',
 *   element: <div>,
 *   callback: () => doSomething(),
 *   useCapture: false
 * });
 * ```
 *
 * @param element Element for which the DOM listeners should be retrieved.
 * @publicApi
 */
export function getListeners(element: Element): Listener[] {
  const lContext = loadLContextFromNode(element);
  const lView = lContext.lView;
  const tView = lView[TVIEW];
  const lCleanup = lView[CLEANUP];
  const tCleanup = tView.cleanup;
  const listeners: Listener[] = [];
  if (tCleanup && lCleanup) {
    for (let i = 0; i < tCleanup.length;) {
      const firstParam = tCleanup[i++];
      const secondParam = tCleanup[i++];
      if (typeof firstParam === 'string') {
        const name: string = firstParam;
        const listenerElement = unwrapRNode(lView[secondParam]) as any as Element;
        const callback: (value: any) => any = lCleanup[tCleanup[i++]];
        const useCaptureOrIndx = tCleanup[i++];
        // if useCaptureOrIndx is boolean then report it as is.
        // if useCaptureOrIndx is positive number then it in unsubscribe method
        // if useCaptureOrIndx is negative number then it is a Subscription
        const useCapture = typeof useCaptureOrIndx === 'boolean' ?
            useCaptureOrIndx :
            (useCaptureOrIndx >= 0 ? false : null);
        if (element == listenerElement) {
          listeners.push({element, name, callback, useCapture});
        }
      }
    }
  }
  listeners.sort(sortListeners);
  return listeners;
}

function sortListeners(a: Listener, b: Listener) {
  if (a.name == b.name) return 0;
  return a.name < b.name ? -1 : 1;
}

/**
 * This function should not exist because it is megamorphic and only mostly correct.
 *
 * See call site for more info.
 */
function isDirectiveDefHack(obj: any): obj is DirectiveDef<any> {
  return obj.type !== undefined && obj.template !== undefined && obj.declaredInputs !== undefined;
}


text:
const static NSInteger AROnboardingPromptDefault = 25;

NSString *const ARUserIdentifierDefault = @"ARUserIdentifier";
NSString *const ARUseStagingDefault = @"ARUseStagingDefault";

NSString *const AROAuthTokenDefault = @"AROAuthToken";
NSString *const AROAuthTokenExpiryDateDefault = @"AROAuthTokenExpiryDate";

NSString *const ARXAppTokenDefault = @"ARXAppTokenDefault";
NSString *const ARXAppTokenExpiryDateDefault = @"ARXAppTokenExpiryDateDefault";

NSString *const ARHasSubmittedDeviceTokenDefault = @"ARHasSubmittedFullDeviceToken";

NSString *const AROnboardingSkipPersonalizeDefault = @"eigen-onboard-skip-personalize";
NSString *const AROnboardingSkipCollectorLevelDefault = @"eigen-onboard-skip-collector-level";
NSString *const AROnboardingSkipPriceRangeDefault = @"eigen-onboard-skip-price-range";
NSString *const AROnboardingPromptThresholdDefault = @"eigen-onboard-prompt-threshold";
NSString *const ARShowAuctionResultsButtonDefault = @"auction-results";

@implementation ARDefaults

+ (void)setup
{
    BOOL useStagingDefault;
#if DEBUG
    useStagingDefault = YES;
#else
    useStagingDefault = NO;
#endif

    [[NSUserDefaults standardUserDefaults] registerDefaults:@{
        ARUseStagingDefault: @(useStagingDefault),
        AROnboardingPromptThresholdDefault: @(AROnboardingPromptDefault),
        AROnboardingSkipPersonalizeDefault: @(NO),
        AROnboardingSkipCollectorLevelDefault: @(NO),
        AROnboardingSkipPriceRangeDefault: @(NO),
        AROnboardingPromptThresholdDefault: @(NO)
        }
     ];
}

+ (void)resetDefaults
{
    [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:[[NSBundle mainBundle] bundleIdentifier]];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

@end


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="alternate" href="/feed/" title="RSS feed" type="application/rss+xml" />

    <title><?php echo SITE_NAME . ' || ' . $pagetitle; ?></title>

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

    <link href="assets/css/modern-business.css" rel="stylesheet">
    <link href="assets/font-awesome/css/font-awesome.css" rel="stylesheet">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
                    Toggle navigation

                </button>

                <?php echo SITE_NAME ?>


text:
| Status        | Accepted     |
:-------------- |:---------------------------------------------------- |
| **RFC #**     | [20210504-kernel-extension-variable-ops](https://github.com/tensorflow/community/pull/20210504-kernel-extension-variable-ops) |
| **Author(s)** | Kulin Seth (Apple), Charles Brissart (Apple)                                                                                |
| **Sponsor**   | Saurabh Saxena (srbs@google.com)                                                                                |
| **Updated**   | 2021-05-04                                                                                |

## Objective

The proposal extends the current [Kernel C API](https://github.com/tensorflow/community/blob/master/rfcs/20190814-kernel-and-op-registration.md) to enable plugin writers to add support for :

* Optimizer operations like SGD, Adam etc.
* Variable updates like Assign, AssignUpdate

## Motivation

Tensorflow has proposed the [Modular Tensorflow design](https://github.com/tensorflow/community/blob/master/rfcs/20190305-modular-tensorflow.md).  This provides plugin (e.g GPU) writers to register the device in a [pluggable way](https://github.com/tensorflow/community/blob/master/rfcs/20200624-pluggable-device-for-tensorflow.md).
To register the OpKernels Tensorflow provides [C++ API](https://github.com/tensorflow/community/blob/master/rfcs/20190814-kernel-and-op-registration.md) for implementing kernels and ops. It creates a modular/plugin-based TF implementation with API and ABI surfaces.
In order to support operations like Optimizers and Resource Variable updates
used in all Training networks, we would need to extend the Kernel C++ API as
currently their support is missing. This Proposal provides high-level API to add support for
Variable ops and Optimizer operations.

## User Benefit

Training support for pluggable vendors.

## Design Proposal

The proposal extends the Kernel C API to add support for variable operations
used in optimizer and resource variable operations such as "GradientDescent".
These operations show up in Training graphs for instance:

```
node {
  name: "SGD/SGD/AssignAddVariableOp"
  op: "AssignAddVariableOp"
  input: "sgd_sgd_assignaddvariableop_resource"
  input: "SGD/SGD/Const"
  device: "/job:localhost/replica:0/task:0/device:GPU:0"
  attr {
    key: "dtype"
    value {
      type: DT_INT64
    }
  }
}
```

The above GraphDef snippet shows the resource variable update operation being
used as part of the optimizer Op "SGD (Stochastic Gradient Descent), while
training a simple classification network. To perform this operation in Plugin
there would need to be support in Core TensorFlow to expose updating the Input
tensors through variable updates in a thread-safe manner. The below API proposes
how to extend the current API to support that.

### Interface Changes

*Optimizers Operations*

Following are the interface changes we are proposing for optimizer operations.
These operations follow the pattern of:

1. Locking the input variables to perform the updates in thread-safe way
2. Get the corresponding input Tensor from Variable.
3. Performing the optimizer update (implemented by the plugin)
4. Forwarding the reference from input to output
5. Releasing the lock.

Below APIs provide the functionality to implement the above list of operations
(1), (2), (4) and (5) in core. This provides a higher level interface to
implement all the optimizer ops like GradientDescent , Adam, Momentum etc.

```

// This is a helper function which acquires mutexes in-order to provide thread-safe
// way of performing weights update during the optimizer op. It returns an opaque
// LockHolder handle back to plugin. This handle is passed to the Release API for
// releasing the locks when the weight update is done.
TF_CAPI_EXPORT extern void TF_MaybeLockVariableInputMutexesInOrder(
                                    TF_OpKernelContext* ctx, bool do_lock, bool sparse,
                                    const int* const input_ids,
                                    size_t len,
                                    TF_VariableInputLockHolder** lockHolder,
                                    TF_Status* status);

// This interface returns out tensor which is updated corresponding to the
// variable passed with input index.
TF_CAPI_EXPORT extern void TF_GetInputTensorFromVariable(
                                        TF_OpKernelContext* ctx,
                                        int input,
                                        bool lock_held,
                                        bool isVariantType,
                                        bool sparse,
                                        void (*copyFunc)(
                                                TF_OpKernelContext * ctx,
                                                TF_Tensor *source,
                                                TF_Tensor *dest),
                                        TF_Tensor** out,
                                                          TF_Status* status);

// This interface forwards the reference from input to the output tensors
// corresponding to the indices provided with input_index and output_index
TF_CAPI_EXPORT extern void TF_OpKernelContext_ForwardRefInputToRefOutput(
                                                   TF_OpKernelContext* ctx,
                                                   int32_t input_index,
                                                   int32_t output_index);

// The API releases the opaque lock handle returned with
// TF_MaybeLockVariableInputMutexesInOrder API
TF_CAPI_EXPORT extern void TF_ReleaseVariableInputLockHolder(
                                  TF_VariableInputLockHolder* lockHolder);

```

*Resource Variables*

Below mentioned APIs expose functionality in Core TensorFlow to allow plugins
to do Assign and Update operations to implement different ResourceVariable
primitives. These are higher level operations which can be easily integrated
into the plugin by directly calling these APIs from the Compute function of
these ops in the Plugin.

```
// Expose higher level Assignment operation for Pluggable vendors to implement
// in the plugin for Training. The API takes in the context with indices for
// the input and value tensors. It also accepts the copy functor provided by
// pluggable vendor to do the copying of the tensors.
TF_CAPI_EXPORT extern void TF_AssignVariable(TF_OpKernelContext* ctx,
                               int input_index,
                               int value_index,
                               void (*copyFunc)(TF_OpKernelContext * ctx,
                                                TF_Tensor *source,
                                                TF_Tensor *dest),
                               TF_Status* status);

// Expose higher level AssignUpdate operation for Pluggable vendors to implement
// in the plugin for Training. The API takes in the context with indices for
// the input and value tensors. It also accepts the update functor provided by
// pluggable vendor to perform these operations respectively.
TF_CAPI_EXPORT extern void TF_AssignUpdateVariable(
                                    TF_OpKernelContext* ctx,
                                    int input_index,
                                    int value_index,
                                    int Op,
                                    bool isVariantType,
                                    void (*updateFunc)(TF_OpKernelContext *ctx,
                                                       TF_Tensor *tensor,
                                                       TF_Tensor *value, int Op),
                                    TF_Status* status);

```

*Helper Function*

We are proposing to add simple helper function which allows plugins to get the Tensor by providing an input_name.

```
// Allows plugin to get TF_Tensor when passed its input_name
TF_CAPI_EXPORT extern void TF_GetInputByName(TF_OpKernelContext* ctx, const char *input_name,
                                             TF_Tensor** tensor, TF_Status* status);

```

### Alternatives Considered

We considered two different ways to add  support for resource variables and
optimizers operations. Option #1 is to expose the required lower level
structures in Tensorflow core like TF_Mutex, TF_ResourceHandle, TF_RefCountPtr
to the plugin vendors. This will allow plugin writers the flexibility to
construct higher level optimizer operations using these lower level primitives
and will be scalable for newer operations. Option #2, is to expose all the
necessary higher level helper methods to implement the Resource variables and
the optimizer ops. This reduces complexity of the interface with keeping lower
level structures intact in the TensorFlow Core. In current proposal we are
discussing the Option #2 to simplify the API design as the first step to add
support. As needed this interface can be built upon in the future to expose lower-level
primitives.

### Performance Implications

We don't expect performance impact due to this RFC. This enables functionality
to update variables used in Training graphs which wasn't supported earlier.

### Dependencies

* This RFC doesn't add new dependencies to external libraries.
* It depends on following modular Tensorflow related RFC:
  * [Modular TensorFlow RFC](https://github.com/tensorflow/community/pull/77)
  * [StreamExecutor C interface RFC](https://github.com/tensorflow/community/pull/257)
  * [Kernel and op registration and implementation API](https://github.com/tensorflow/community/blob/master/rfcs/20190814-kernel-and-op-registration.md)
  * [Pluggable device](https://github.com/tensorflow/community/pull/262)

### Engineering Impact
* The impact to binary size / startup time / build time / test times are minimum
* The TensorFlow team will maintain this code.

### Platforms and Environments

This is an extension to the Kernel C API so the change would work on all the
platforms supported by current implementation. The enhancements are platform
independent.

### Best Practices

This works with Modular TensorFlow which is the direction for integrating new third-party vendors to the current Tensorflow stack.

### Tutorials and Examples

We will work with the Tensorflow core team to provide examples as how to
use these API for plugin vendors.

### Compatibility
* The RFC is an extension to the Kernel C API, it follows the same
  backwards/forwards compatibility requirements
* This proposal will allow plugin vendors to train models in Tensorflow
  ecosystem. Since Modular API is the path forward for newer devices to
  integrate to Tensorflow stack it will enable these devices to train models.
    - Current API doesn't support TFLite
    - It should not impede distribution strategies or serialization to SavedModel

### User Impact

This is an extension of the current Kernel C API as part of Modular design.


text:
package scala.scalanative
package nir
package parser

import fastparse.all._

object Inst extends Base[nir.Inst] {

  import Base.IgnoreWhitespace._

  val None = P("none".! map (_ => nir.Inst.None))
  val Label =
    P(Local.parser ~ ("(" ~ Val.Local.rep(sep = ",") ~ ")").? ~ ":" map {
      case (name, params) => nir.Inst.Label(name, params getOrElse Seq())
    })
  val Let =
    P(Local.parser ~ "=" ~ Op.parser map {
      case (name, op) => nir.Inst.Let(name, op)
    })
  val Unreachable = P("unreachable".! map (_ => nir.Inst.Unreachable))
  val Ret =
    P("ret" ~ Val.parser.? map (v => nir.Inst.Ret(v.getOrElse(nir.Val.None))))
  val Jump = P("jump" ~ Next.parser map (nir.Inst.Jump(_)))
  val If =
    P("if" ~ Val.parser ~ "then" ~ Next.parser ~ "else" ~ Next.parser map {
      case (cond, thenp, elsep) => nir.Inst.If(cond, thenp, elsep)
    })
  val Switch =
    P("switch" ~ Val.parser ~ "{" ~ Next.parser.rep ~ "default:" ~ Next.parser ~ "}" map {
      case (scrut, cases, default) => nir.Inst.Switch(scrut, default, cases)
    })
  val Invoke =
    P(
      "invoke[" ~ Type.parser ~ "]" ~ Val.parser ~ "(" ~ Val.parser.rep(sep =
        ",") ~ ")" ~ "to" ~ Next.parser ~ "unwind" ~ Next.parser map {
        case (ty, ptr, args, succ, fail) =>
          nir.Inst.Invoke(ty, ptr, args, succ, fail)
      })
  val Throw = P("throw" ~ Val.parser map (nir.Inst.Throw(_)))
  val Try =
    P("try" ~ Next.parser ~ "catch" ~ Next.parser map {
      case (normal, exc) => nir.Inst.Try(normal, exc)
    })
  override val parser: P[nir.Inst] =
    None | Label | Let | Unreachable | Ret | Jump | If | Switch | Invoke | Throw | Try
}


text:
<resources>
    <string name="app_name">Acc Device Tags</string>
    <string name="event_lead">Send lead</string>
    <string name="event_cart">Send cart</string>
    <string name="event_purchase">Send purchase</string>

    <!-- Accengage SDK parameters -->

    <!-- Credentials for 'Ap Demo Accengage Android Clients' -->
    <string name="acc_partner_id">comptedemosdk1e3b35fb8ad5024</string>
    <string name="acc_private_key">78dbaf3fac56784aa5f26a3fcf27996983b892fd</string>

    <string name="acc_logging">true</string>

    <string name="m1_easter_egg">M1 - Ohhh Champs Elysées pala palapa, Ohhh Champs Elysées pala palapa</string>
    <string name="m2_easter_egg">M2 - Please, beware of pick pockets</string>
    <string name="m3_easter_egg">M3 - Oh, that\'s my line too!</string>
    <string name="m6_easter_egg">M6 - Come see the \"Tour Eiffel\"</string>
    <string name="m8_easter_egg">M8 - So much stops on this line</string>
    <string name="m11_easter_egg">M11 - Somebody really take this line? I just thought this line was a legend</string>
    <string name="m13_easter_egg">M13 - The famous one… There are so many people on this line, looks like a social media network</string>
    <string name="m14_easter_egg">M14 - The best one, clean and fast</string>
    <string name="rer_a_easter_egg">RER A - Avant de descendre, assurez-vous de ne rien oublier à bord.\nPlease make sure you collect all your belongings before leaving the train.\nPor favor, no olviden de recojer todo su equipaje</string>
    <string name="rer_b_easter_egg">RER B - Does somebody can fix this line please?</string>
    <string name="rer_c_easter_egg">RER C - Please, just wait…</string>
    <string name="rer_d_easter_egg">TRER D - he legend says that you can see some knights and dragons fighting in faraway lands with this line</string>
    <string name="rer_e_easter_egg">RER E - Sorry, line canceled</string>

</resources>


text:
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

using NUnit.Framework;

using Microsoft.Build.BuildEngine;
using Microsoft.Build.Framework;
using Microsoft.Build.UnitTests;

namespace Microsoft.Build.UnitTests.OM.OrcasCompatibility
{
    /// <summary>
    /// STUB Fixture Class for the v9 OM Public Interface Compatibility Tests. RemoteErrorException class
    /// Also see Toolset tests in the Project test class.
    /// </summary>
    [TestFixture]
    public class InvalidToolsetDefinitionException_Tests
    {
        /// <summary>
        /// Ctor Test, ensure message is set.
        /// </summary>
        [Test]
        public void CtorMessage()
        {
            InvalidToolsetDefinitionException toolSetException = new InvalidToolsetDefinitionException("Message");
            Assertion.AssertEquals("Message", toolSetException.Message);
        }

        /// <summary>
        /// Ctor Test, set a null message. We do not guard against this.
        /// </summary>
        [Test]
        public void CtorMessage_Null()
        {
            InvalidToolsetDefinitionException toolSetException = new InvalidToolsetDefinitionException(null);
        }

        /// <summary>
        /// Ctor Test, ensure message is set to empty
        /// </summary>
        [Test]
        public void CtorMessage_Empty()
        {
            InvalidToolsetDefinitionException toolSetException = new InvalidToolsetDefinitionException(String.Empty);
            Assertion.AssertEquals(String.Empty, toolSetException.Message);
        }

        /// <summary>
        /// Ctor Test, set message and inner exception
        /// </summary>
        [Test]
        public void CtorArity2InnerException()
        {
            InvalidToolsetDefinitionException toolSetException = new InvalidToolsetDefinitionException("Message", new Exception("Inner"));
            Assertion.AssertEquals("Message", toolSetException.Message);
            Assertion.AssertEquals("Inner", toolSetException.InnerException.Message);
        }

        /// <summary>
        /// Ctor Test,set message and error code
        /// </summary>
        [Test]
        public void CtorArity2ErrorMessage()
        {
            InvalidToolsetDefinitionException toolSetException = new InvalidToolsetDefinitionException("Message", "Error");
            Assertion.AssertEquals("Message", toolSetException.Message);
            Assertion.AssertEquals("Error", toolSetException.ErrorCode);
        }

        /// <summary>
        /// Ctor Test, set message  error code and Inner excetion
        /// </summary>
        [Test]
        public void CtorArity3()
        {
            InvalidToolsetDefinitionException toolSetException = new InvalidToolsetDefinitionException("Message", "Error", new Exception("Inner"));
            Assertion.AssertEquals("Message", toolSetException.Message);
            Assertion.AssertEquals("Error", toolSetException.ErrorCode);
            Assertion.AssertEquals("Inner", toolSetException.InnerException.Message);
        }

        /// <summary>
        /// XML Serialization Test, not supported, throws invalid operation Exception.
        /// </summary>
        [Test]
        [ExpectedException(typeof(InvalidOperationException))]
        public void SerializationXML()
        {
            InvalidToolsetDefinitionException toolSetException = new InvalidToolsetDefinitionException("Message", "errorCode");
            MemoryStream memoryStream = null;
            try
            {
                memoryStream = new MemoryStream();
                XmlSerializer xs = new XmlSerializer(typeof(InvalidToolsetDefinitionException));
                XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
                xs.Serialize(xmlTextWriter, toolSetException);
                memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
            }
            finally
            {
                memoryStream.Close();
            }
        }

        /// <summary>
        /// Binary Serialization Test, serialize the exception out and back in from a stream. This uses the protected constructor
        /// </summary>
        [Test]
        public void SerializationBinary()
        {
            MemoryStream memoryStream = null;
            InvalidToolsetDefinitionException toolSetException = new InvalidToolsetDefinitionException("Message", "errorCode");
            try
            {
                memoryStream = new MemoryStream();
                IFormatter binaryForamtter = new BinaryFormatter();
                binaryForamtter.Serialize(memoryStream, toolSetException);
                memoryStream.Position = 0; // reset pointer into stream for read
                Object returnObj = binaryForamtter.Deserialize(memoryStream);
                Assertion.Assert(returnObj is InvalidToolsetDefinitionException);
                Assertion.AssertEquals("Message", ((InvalidToolsetDefinitionException)returnObj).Message);
            }
            finally
            {
                memoryStream.Close();
            }
        }

        /// <summary>
        /// Binary Serialization Test, serialize a inherited exception out and back in from a stream.
        /// </summary>
        [Test]
        public void ProtectedConstructorTest()
        {
            ExtendsInvalidToolsetDefinitionException toolSetException = new ExtendsInvalidToolsetDefinitionException("Message", "Error");
            MemoryStream memoryStream = null;
            try
            {
                memoryStream = new MemoryStream();
                IFormatter binaryForamtter = new BinaryFormatter();
                binaryForamtter.Serialize(memoryStream, toolSetException);
                memoryStream.Position = 0; // Reset pointer into stream for read
                Object returnObj = binaryForamtter.Deserialize(memoryStream);
                Assertion.Assert(returnObj is ExtendsInvalidToolsetDefinitionException);
                Assertion.AssertEquals("Message", ((ExtendsInvalidToolsetDefinitionException)returnObj).Message);
                Assertion.AssertEquals("Error", ((ExtendsInvalidToolsetDefinitionException)returnObj).ErrorCode);
            }
            finally
            {
                memoryStream.Close();
            }
        }

        /// <summary>
        /// Helper class to expose the protected constructor through extension
        /// </summary>
        [Serializable]
        internal class ExtendsInvalidToolsetDefinitionException : InvalidToolsetDefinitionException, ISerializable
        {
            /// <summary>
            /// Constructor that takes an MSBuild error code, Override
            /// </summary>
            public ExtendsInvalidToolsetDefinitionException(string message, string errorCode)
                : base(message, errorCode)
            {
            }

            /// <summary>
            /// Basic Constructor Override
            /// </summary>
            public ExtendsInvalidToolsetDefinitionException(SerializationInfo info, StreamingContext context)
                : base(info, context)
            {
            }
        }
    }
}


text:
package org.gradle.architecture.test;

import com.tngtech.archunit.junit.AnalyzeClasses;
import com.tngtech.archunit.junit.ArchTest;
import com.tngtech.archunit.lang.ArchRule;
import org.gradle.internal.accesscontrol.AllowUsingApiForExternalUse;
import org.gradle.internal.accesscontrol.ForExternalUse;

import static com.tngtech.archunit.core.domain.properties.CanBeAnnotated.Predicates.annotatedWith;
import static com.tngtech.archunit.lang.conditions.ArchConditions.beDeclaredInClassesThat;
import static com.tngtech.archunit.lang.conditions.ArchConditions.beProtected;
import static com.tngtech.archunit.lang.conditions.ArchConditions.bePublic;
import static com.tngtech.archunit.lang.conditions.ArchPredicates.are;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.codeUnits;
import static org.gradle.architecture.test.ArchUnitFixture.gradlePublicApi;

@AnalyzeClasses(packages = "org.gradle")
public class ForExternalUseTest {

    @ArchTest
    public static final ArchRule members_for_external_use_are_public_api =
        codeUnits().that().areAnnotatedWith(ForExternalUse.class)
            .should(beDeclaredInClassesThat(are(gradlePublicApi())))
            .andShould(bePublic().or(beProtected()));

    @ArchTest
    public static final ArchRule members_for_external_use_are_not_used_internally =
        codeUnits().that().areAnnotatedWith(ForExternalUse.class)
            .should().onlyBeCalled().byCodeUnitsThat(
                are(annotatedWith(ForExternalUse.class)
                    .or(annotatedWith(AllowUsingApiForExternalUse.class)))
            );
}


text:
<!DOCTYPE html>
<meta charset="utf-8">
<title>Forced colors mode - caret-color.</title>
<link rel="help" href="https://www.w3.org/TR/css-color-adjust-1/#forced-colors-properties">
<link rel=match href="forced-colors-mode-43-ref.html">

The caret color should be overridden to currentColor


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Uses of Class javax.xml.rpc.ServiceFactory (Axis API)
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
javax.xml.rpc.ServiceFactory

Packages that use ServiceFactory

javax.xml.rpc

org.apache.axis.client

Uses of ServiceFactory in javax.xml.rpc

Methods in javax.xml.rpc that return ServiceFactory

static ServiceFactory
ServiceFactory.newInstance()

          Gets an instance of the ServiceFactory

Uses of ServiceFactory in org.apache.axis.client

Subclasses of ServiceFactory in org.apache.axis.client

 class
ServiceFactory

          Helper class for obtaining Services from JNDI.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2005 Apache Web Services Project. All Rights Reserved.


text:
[![Build Status](https://travis-ci.org/buranmert/MBTaskContainer.svg?branch=master)](https://travis-ci.org/buranmert/MBTaskContainer)
[![Version](https://img.shields.io/cocoapods/v/MBTaskContainer.svg?style=flat)](http://cocoapods.org/pods/MBTaskContainer)
[![License](https://img.shields.io/cocoapods/l/MBTaskContainer.svg?style=flat)](http://cocoapods.org/pods/MBTaskContainer)
[![Platform](https://img.shields.io/cocoapods/p/MBTaskContainer.svg?style=flat)](http://cocoapods.org/pods/MBTaskContainer)

## What is MBTaskContainer?

`MBTaskContainer` is a simple class that lets you add your `NSURLSessionTask`s into it and read active tasks from it safely.

### Example scenario

Let's say your server use `OAuth2` authentication standard, so you need to obtain a token before establishing a connection to access your `API`
And again, let's say your application has an architecture like the following:

`ViewController` -> `DataController` *_where_*

1. `ViewController`
  - Typical `UIViewController` subclass
  - it may have an `UIButton` to cancel ongoing network operations
2. `DataController`
  - `NSObject` subclass
  - responsible for making network calls

In that case, we *_cannot_* return actual ongoing network tasks to `ViewController` from `DataController` immediately as even a simple network request would be like the following:

1. `ViewController` calls `DataController`'s `getItems` method
2. `DataController` makes the request
3. Request returns `401 Unauthorized` responsible
4. `DataController` makes another request to obtain a new token
5. After receiving new token, `DataController` retries `getItems` request

In short, there will be many request that are done asynchronously and some follow the others.
In order to address this problem, you can use `MBTaskContainer`!

### Example solution

1. Returns an `MBTaskContainer` instance from `DataController:getItems`.
2. Whenever a new network task is created, add it to returned instance.
3. `ViewController` can access active network tasks at any time.

### Why can't we do that with NSArray?

1. `MBTaskContainer` lets you add/read tasks from multiple threads in a safe way.
  - Multiple readers and single writer/remover at a time.
2. `MBTaskContainer` takes care of removal. You don't need to remove completed tasks.

### Example Usage

```Objective-C
// DataController.m
- (MBTaskContainer *)seriallyGetRepositoriesOrganizationsMembers {
    MBTaskContainer *taskContainer = [MBTaskContainer new];

    NSURLSessionTask *repositories = [self fetchDataWithRelativeURL:repositoriesURL completion:^(NSError *error) {
        if (error == nil) {
            NSURLSessionTask *organizations = nil;
            organizations = [self fetchDataWithRelativeURL:organizationsURL completion:^(NSError *error) {
                if (error == nil) {
                    NSURLSessionTask *members = nil;
                    members = [self fetchDataWithRelativeURL:membersURL completion:nil];

                    [taskContainer addTask:members];
                }
            }];

            [taskContainer addTask:organizations];
        }
    }];

    [taskContainer addTask:repositories];

    return taskContainer;
}

// ViewController.m
...
self.serialTaskContainer = [self.dataController seriallyGetRepositoriesOrganizationsMembers];
NSArray *activeTasks = [self.serialTaskContainer getTasks];
...
// To cancel ongoing and potential new tasks
self.serialTaskContainer.state = MBTaskContainerStateCancelling;
...
```

### Installation

MBTaskContainer is available through [CocoaPods](http://cocoapods.org). To install
it, simply add the following line to your Podfile:

```ruby
pod "MBTaskContainer"
```

## Author

Mert Buran, buranmert@gmail.com

## License

MBTaskContainer is available under the MIT license. See the LICENSE file for more info.


text:
package com.eharmony.matching.seeking.executor.mongodb;

import com.google.code.morphia.Key;
import com.google.code.morphia.mapping.cache.EntityCache;
import com.google.code.morphia.mapping.cache.EntityCacheStatistics;

/**
 * The Morphia Entity cache cannot handle a high throughput of unique objects
 * and ends up consuming too much memory. This is a non-functional mapped entity
 * cache.
 */
public class NonFunctionalEntityCache implements EntityCache {

    private final EntityCacheStatistics stats = new EntityCacheStatistics();

    @Override
    public Boolean exists(Key<?> arg0) {
        return false;
    }

    @Override
    public void flush() {
    }

    @Override
    public <T> T getEntity(Key<T> arg0) {
        return null;
    }

    @Override
    public <T> T getProxy(Key<T> arg0) {
        return null;
    }

    @Override
    public void notifyExists(Key<?> arg0, boolean arg1) {
    }

    @Override
    public <T> void putEntity(Key<T> arg0, T arg1) {
    }

    @Override
    public <T> void putProxy(Key<T> arg0, T arg1) {
    }

    @Override
    public EntityCacheStatistics stats() {
        return stats;
    }

}