text:
package com.querydsl.jpa.hibernate.sql;

import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Nullable;

import org.hibernate.Query;
import org.hibernate.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

import com.google.common.collect.ListMultimap;
import com.google.common.collect.Sets;
import com.mysema.commons.lang.CloseableIterator;
import com.querydsl.core.*;
import com.querydsl.core.NonUniqueResultException;
import com.querydsl.core.types.Expression;
import com.querydsl.core.types.FactoryExpression;
import com.querydsl.jpa.AbstractSQLQuery;
import com.querydsl.jpa.FactoryExpressionTransformer;
import com.querydsl.jpa.NativeSQLSerializer;
import com.querydsl.jpa.ScrollableResultsIterator;
import com.querydsl.jpa.hibernate.DefaultSessionHolder;
import com.querydsl.jpa.hibernate.HibernateUtil;
import com.querydsl.jpa.hibernate.SessionHolder;
import com.querydsl.jpa.hibernate.StatelessSessionHolder;
import com.querydsl.sql.Configuration;
import com.querydsl.sql.SQLSerializer;

/**
 * {@code AbstractHibernateSQLQuery} is the base class for Hibernate Native SQL queries
 *
 * @param <T> result type
 * @param <Q> concrete subtype
 *
 * @author tiwe
 */
public abstract class AbstractHibernateSQLQuery<T, Q extends AbstractHibernateSQLQuery<T, Q>> extends AbstractSQLQuery<T, Q> {

    private static final Logger logger = LoggerFactory.getLogger(AbstractHibernateSQLQuery.class);

    protected Boolean cacheable, readOnly;

    protected String cacheRegion;

    protected int fetchSize = 0;

    private final SessionHolder session;

    protected int timeout = 0;

    public AbstractHibernateSQLQuery(Session session, Configuration conf) {
        this(new DefaultSessionHolder(session), conf, new DefaultQueryMetadata());
    }

    public AbstractHibernateSQLQuery(StatelessSession session, Configuration conf) {
        this(new StatelessSessionHolder(session), conf, new DefaultQueryMetadata());
    }

    public AbstractHibernateSQLQuery(SessionHolder session, Configuration conf, QueryMetadata metadata) {
        super(metadata, conf);
        this.session = session;
    }

    public Query createQuery() {
        return createQuery(false);
    }

    private Query createQuery(boolean forCount) {
        NativeSQLSerializer serializer = (NativeSQLSerializer) serialize(forCount);
        String queryString = serializer.toString();
        logQuery(queryString, serializer.getConstantToAllLabels());
        org.hibernate.SQLQuery query = session.createSQLQuery(queryString);
        // set constants
        HibernateUtil.setConstants(query, serializer.getConstantToNamedLabel(), serializer.getConstantToNumberedLabel(),
                queryMixin.getMetadata().getParams());

        if (!forCount) {
            ListMultimap<Expression<?>, String> aliases = serializer.getAliases();
            Set<String> used = Sets.newHashSet();
            // set entity paths
            Expression<?> projection = queryMixin.getMetadata().getProjection();
            if (projection instanceof FactoryExpression) {
                for (Expression<?> expr : ((FactoryExpression<?>) projection).getArgs()) {
                    if (isEntityExpression(expr)) {
                        query.addEntity(extractEntityExpression(expr).toString(), expr.getType());
                    } else if (aliases.containsKey(expr)) {
                        for (String scalar : aliases.get(expr)) {
                            if (!used.contains(scalar)) {
                                query.addScalar(scalar);
                                used.add(scalar);
                                break;
                            }
                        }
                    }
                }
            } else if (isEntityExpression(projection)) {
                query.addEntity(extractEntityExpression(projection).toString(), projection.getType());
            } else if (aliases.containsKey(projection)) {
                for (String scalar : aliases.get(projection)) {
                    if (!used.contains(scalar)) {
                        query.addScalar(scalar);
                        used.add(scalar);
                        break;
                    }
                }
            }

            // set result transformer, if projection is a FactoryExpression instance
            if (projection instanceof FactoryExpression) {
                query.setResultTransformer(new FactoryExpressionTransformer((FactoryExpression<?>) projection));
            }
        }

        if (fetchSize > 0) {
            query.setFetchSize(fetchSize);
        }
        if (timeout > 0) {
            query.setTimeout(timeout);
        }
        if (cacheable != null) {
            query.setCacheable(cacheable);
        }
        if (cacheRegion != null) {
            query.setCacheRegion(cacheRegion);
        }
        if (readOnly != null) {
            query.setReadOnly(readOnly);
        }
        return query;
    }

    @Override
    protected SQLSerializer createSerializer() {
        return new NativeSQLSerializer(configuration, true);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<T> fetch() {
        try {
            return createQuery().list();
        } finally {
            reset();
        }
    }

    @Override
    public CloseableIterator<T> iterate() {
        try {
            Query query = createQuery();
            ScrollableResults results = query.scroll(ScrollMode.FORWARD_ONLY);
            return new ScrollableResultsIterator<T>(results);
        } finally {
            reset();
        }
    }

    @Override
    public QueryResults<T> fetchResults() {
        // TODO : handle entity projections as well
        try {
            Query query = createQuery(true);
            long total = ((Number) query.uniqueResult()).longValue();
            if (total > 0) {
                QueryModifiers modifiers = queryMixin.getMetadata().getModifiers();
                query = createQuery(false);
                @SuppressWarnings("unchecked")
                List<T> list = query.list();
                return new QueryResults<T>(list, modifiers, total);
            } else {
                return QueryResults.emptyResults();
            }
        } finally {
            reset();
        }
    }

    protected void logQuery(String queryString, Map<Object, String> parameters) {
        if (logger.isDebugEnabled()) {
            String normalizedQuery = queryString.replace('\n', ' ');
            MDC.put(MDC_QUERY, normalizedQuery);
            MDC.put(MDC_PARAMETERS, String.valueOf(parameters));
            logger.debug(normalizedQuery);
        }
    }

    protected void cleanupMDC() {
        MDC.remove(MDC_QUERY);
        MDC.remove(MDC_PARAMETERS);
    }

    protected void reset() {
        cleanupMDC();
    }

    @SuppressWarnings("unchecked")
    @Override
    public T fetchOne() throws NonUniqueResultException {
        try {
            Query query = createQuery();
            return (T) uniqueResult(query);
        } finally {
            reset();
        }
    }

    @Nullable
    private Object uniqueResult(Query query) {
        try {
            return query.uniqueResult();
        } catch (org.hibernate.NonUniqueResultException e) {
            throw new NonUniqueResultException(e);
        }
    }

    /**
     * Enable caching of this query result set.
     * @param cacheable Should the query results be cacheable?
     */
    @SuppressWarnings("unchecked")
    public Q setCacheable(boolean cacheable) {
        this.cacheable = cacheable;
        return (Q) this;
    }

    /**
     * Set the name of the cache region.
     * @param cacheRegion the name of a query cache region, or <tt>null</tt>
     * for the default query cache
     */
    @SuppressWarnings("unchecked")
    public Q setCacheRegion(String cacheRegion) {
        this.cacheRegion = cacheRegion;
        return (Q) this;
    }

    /**
     * Set a fetchJoin size for the underlying JDBC query.
     * @param fetchSize the fetchJoin size
     */
    @SuppressWarnings("unchecked")
    public Q setFetchSize(int fetchSize) {
        this.fetchSize = fetchSize;
        return (Q) this;
    }

    /**
     * Entities retrieved by this query will be loaded in
     * a read-only mode where Hibernate will never dirty-check
     * them or make changes persistent.
     *
     */
    @SuppressWarnings("unchecked")
    public Q setReadOnly(boolean readOnly) {
        this.readOnly = readOnly;
        return (Q) this;
    }

    /**
     * Set a timeout for the underlying JDBC query.
     * @param timeout the timeout in seconds
     */
    @SuppressWarnings("unchecked")
    public Q setTimeout(int timeout) {
        this.timeout = timeout;
        return (Q) this;
    }

    @Override
    protected void clone(Q query) {
        super.clone(query);
        cacheable = query.cacheable;
        cacheRegion = query.cacheRegion;
        fetchSize = query.fetchSize;
        readOnly = query.readOnly;
        timeout = query.timeout;
    }

    protected abstract Q clone(SessionHolder session);

    public Q clone(Session session) {
        return this.clone(new DefaultSessionHolder(session));
    }

    public Q clone(StatelessSession statelessSession) {
        return this.clone(new StatelessSessionHolder(statelessSession));
    }

    @Override
    public Q clone() {
        return this.clone(this.session);
    }

}


text:
package org.isisaddons.module.security.facets;

import java.util.List;

import com.google.common.base.Predicate;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;

import org.apache.isis.applib.services.queryresultscache.QueryResultsCache;
import org.apache.isis.applib.services.user.UserService;
import org.apache.isis.core.metamodel.facetapi.FacetHolder;
import org.apache.isis.core.metamodel.facetapi.FacetUtil;
import org.apache.isis.core.metamodel.facetapi.FeatureType;
import org.apache.isis.core.metamodel.facets.FacetFactoryAbstract;
import org.apache.isis.core.metamodel.services.ServicesInjector;
import org.apache.isis.core.metamodel.services.ServicesInjectorAware;

import org.isisaddons.module.security.dom.tenancy.ApplicationTenancyEvaluator;
import org.isisaddons.module.security.dom.tenancy.ApplicationTenancyPathEvaluator;
import org.isisaddons.module.security.dom.tenancy.HasAtPath;
import org.isisaddons.module.security.dom.user.ApplicationUserRepository;

public class TenantedAuthorizationFacetFactory extends FacetFactoryAbstract implements ServicesInjectorAware {

    private ServicesInjector servicesInjector;

    public TenantedAuthorizationFacetFactory() {
        super(FeatureType.EVERYTHING);
    }

    @Override
    public void process(final ProcessClassContext processClassContext) {
        final Class<?> cls = processClassContext.getCls();

        FacetHolder facetHolder = processClassContext.getFacetHolder();
        FacetUtil.addFacet(createFacet(cls, facetHolder));
    }

    @Override
    public void process(final ProcessMethodContext processMethodContext) {
        final Class<?> cls = processMethodContext.getCls();
        FacetHolder facetHolder = processMethodContext.getFacetHolder();
        FacetUtil.addFacet(createFacet(cls, facetHolder));
    }

    @Override
    public void processParams(final ProcessParameterContext processParameterContext) {
        final Class<?> cls = processParameterContext.getCls();
        FacetHolder facetHolder = processParameterContext.getFacetHolder();
        FacetUtil.addFacet(createFacet(cls, facetHolder));
    }

    private TenantedAuthorizationFacetDefault createFacet(
            final Class<?> cls, final FacetHolder holder) {

        List<ApplicationTenancyEvaluator> evaluators = servicesInjector.lookupServices(ApplicationTenancyEvaluator.class);
        if(isNullOrEmpty(evaluators)) {
            evaluators = Lists.newArrayList();

            // fallback to previous SPI
            List<ApplicationTenancyPathEvaluator> pathEvaluators =
                    servicesInjector.lookupServices(ApplicationTenancyPathEvaluator.class);
            if(isNullOrEmpty(pathEvaluators)) {
                pathEvaluators = Lists.newArrayList();
                final ApplicationTenancyPathEvaluator pathEvaluator = new ApplicationTenancyPathEvaluatorDefault();
                servicesInjector.injectServicesInto(pathEvaluator);
                pathEvaluators.add(pathEvaluator);
            }

            for (ApplicationTenancyPathEvaluator pathEvaluator : pathEvaluators) {
                final ApplicationTenancyEvaluatorUsingPaths evaluator = new ApplicationTenancyEvaluatorUsingPaths(pathEvaluator);
                servicesInjector.injectServicesInto(evaluator);
                evaluators.add(evaluator);
            }
        }

        final ImmutableList<ApplicationTenancyEvaluator> evaluatorsForCls =
                FluentIterable.from(evaluators).filter(new Predicate<ApplicationTenancyEvaluator>() {
            @Override
            public boolean apply(ApplicationTenancyEvaluator applicationTenancyEvaluator) {
                return applicationTenancyEvaluator.handles(cls);
            }
        }).toList();

        if(evaluatorsForCls.isEmpty()) {
            return null;
        }

        final ApplicationUserRepository applicationUserRepository =
                servicesInjector.lookupService(ApplicationUserRepository.class);
        final QueryResultsCache queryResultsCache = servicesInjector.lookupService(QueryResultsCache.class);
        final UserService userService = servicesInjector.lookupService(UserService.class);

        return new TenantedAuthorizationFacetDefault(evaluatorsForCls, applicationUserRepository, queryResultsCache, userService, holder);
    }

    private static boolean isNullOrEmpty(final List<?> list) {
        return list == null || list.isEmpty();
    }

    @Deprecated
    static class ApplicationTenancyPathEvaluatorDefault implements ApplicationTenancyPathEvaluator {

        @Override
        public boolean handles(final Class<?> cls) {
            return HasAtPath.class.isAssignableFrom(cls);
        }

        public String applicationTenancyPathFor(final Object domainObject) {
            // always safe, facet factory only installs facet for classes implementing HasAtPath
            final HasAtPath tenantedObject = (HasAtPath) domainObject;

            return tenantedObject.getAtPath();
        }
    }

    @Override
    public void setServicesInjector(ServicesInjector servicesInjector) {
        this.servicesInjector = servicesInjector;
    }
}

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) 2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#ifndef BITCOIN_QT_WALLETCONTROLLER_H
#define BITCOIN_QT_WALLETCONTROLLER_H

#include <qt/walletmodel.h>
#include <sync.h>

#include <QMutex>

#include <map>
#include <memory>
#include <vector>

#include <QMessageBox>
#include <QThread>

class OptionsModel;
class PlatformStyle;

namespace interfaces {
class Handler;
class Node;
} // namespace interfaces

class OpenWalletActivity;

/**
 * Controller between interfaces::Node, WalletModel instances and the GUI.
 */
class WalletController : public QObject {
    Q_OBJECT

    WalletModel *getOrCreateWallet(std::unique_ptr<interfaces::Wallet> wallet);
    void removeAndDeleteWallet(WalletModel *wallet_model);

public:
    WalletController(interfaces::Node &node,
                     const PlatformStyle *platform_style,
                     OptionsModel *options_model, QObject *parent);
    ~WalletController();

    //! Returns wallet models currently open.
    std::vector<WalletModel *> getOpenWallets() const;

    //! Returns all wallet names in the wallet dir mapped to whether the wallet
    //! is loaded.
    std::map<std::string, bool> listWalletDir() const;

    OpenWalletActivity *openWallet(const CChainParams &params,
                                   const std::string &name,
                                   QWidget *parent = nullptr);
    void closeWallet(WalletModel *wallet_model, QWidget *parent = nullptr);

Q_SIGNALS:
    void walletAdded(WalletModel *wallet_model);
    void walletRemoved(WalletModel *wallet_model);

    void coinsSent(WalletModel *wallet_model, SendCoinsRecipient recipient,
                   QByteArray transaction);

private:
    QThread m_activity_thread;
    interfaces::Node &m_node;
    const PlatformStyle *const m_platform_style;
    OptionsModel *const m_options_model;
    mutable QMutex m_mutex;
    std::vector<WalletModel *> m_wallets;
    std::unique_ptr<interfaces::Handler> m_handler_load_wallet;

    friend class OpenWalletActivity;
};

class OpenWalletActivity : public QObject {
    Q_OBJECT

public:
    OpenWalletActivity(WalletController *wallet_controller,
                       const std::string &name, const CChainParams &params);

public Q_SLOTS:
    void open();

Q_SIGNALS:
    void message(QMessageBox::Icon icon, const QString text);
    void finished();
    void opened(WalletModel *wallet_model);

private:
    WalletController *const m_wallet_controller;
    std::string const m_name;
    const CChainParams &m_chain_params;
};

#endif // BITCOIN_QT_WALLETCONTROLLER_H


text:
using System.Reflection;
using System.Runtime.CompilerServices;

[assembly: AssemblyTitle("Voyage")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("2014 Richard Sartor")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

[assembly: AssemblyVersion("0.0.*")]

//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]


text:
layout: post
author: sunhwap
title: pipes and filter
date: 2014-03-13
---

## Pipes and filter exercises

1.  The plain sort just considers the text as a string of characters rather than a single numerical element whereas
    sort -n arranges the given list of numbers numerically in the ascending order of the numerical value of each number.
2.  wc -l < mydata.dat:  this command reads from a file, mydata.dat instead of from standard input and shows the number
    of lines int he file whereas wc -1 mydata.dat shows the number of lines in the file, mydata.dat.  One thing that I
    noticed between these two commands is that the one with the '<' does not list the filename in the output, whereas the
    one without it does.
3.  Since uniq only removes adjacent duplicated lines, the lines in the file should be sorted using sort command and then
    pipe the output to the the uniq command.  That is, sort salmon.txt | uniq.  The reason why uniq removes just adjacent
    duplicated lines is that I guess that it is just computationally easier to perform the operation on adjacent items, since
    you would have to do a lot of looping if the dataset happens to be very large.
4. cat animals.txt command displays the content of the whole file.  cat animals.txt | head -5, this command passes teh top five
   content through the pipe.  cat animals.txt | head -5 | tails -3, this command passes the bottom three content through the
   pipe.  cat animals.txt | head -5 | tails-3 | sort -r, this command sort the three content in reversed order.  That is, the top
   one goes to the bottom position; the middle one goes to the top position, and the bottom one goes to the middle position.
5. cut -d, -f 2 animals.txt:  this command extract only the second field of the file delimited by comma.  In order to extract
   a single instance of each animals from this text file, sort and uniq commands should be added.  That is, cut -d, -f 2 animals.txt
   | sort | uniq


text:
# -*- coding: utf-8 -*-

#       Licensed to the Apache Software Foundation (ASF) under one
#       or more contributor license agreements.  See the NOTICE file
#       distributed with this work for additional information
#       regarding copyright ownership.  The ASF licenses this file
#       to you under the Apache License, Version 2.0 (the
#       "License"); you may not use this file except in compliance
#       with the License.  You may obtain a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#       Unless required by applicable law or agreed to in writing,
#       software distributed under the License is distributed on an
#       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
#       KIND, either express or implied.  See the License for the
#       specific language governing permissions and limitations
#       under the License.

try:
    from setuptools import setup, find_packages
except ImportError:
    from ez_setup import use_setuptools
    use_setuptools()
    from setuptools import setup, find_packages

exec open('allura/version.py').read()

PROJECT_DESCRIPTION = '''
Allura is an open source implementation of a software "forge", a web site
that manages source code repositories, bug reports, discussions, mailing
lists, wiki pages, blogs and more for any number of individual projects.
'''
setup(
    name='Allura',
    version=__version__,
    description='Base distribution of the Allura development platform',
    long_description=PROJECT_DESCRIPTION,
    author='Allura Team',
    url='https://forge-allura.apache.org/p/allura/',
    keywords='allura forge turbogears pylons jinja2 mongodb',
    license='Apache License, http://www.apache.org/licenses/LICENSE-2.0',
    platforms=[
        'Linux',
        'MacOS X',
    ],
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Web Environment',
        'Framework :: Pylons',
        'Framework :: TurboGears',
        'Intended Audience :: Developers',
        'Programming Language :: Python :: 2.6',
        'Topic :: Internet :: WWW/HTTP :: WSGI :: Application',
        'License :: OSI Approved :: Apache Software License',
    ],
    install_requires=[
        "TurboGears2",
        "pypeline",
        "datadiff",
        "BeautifulSoup",
        "PasteScript",
        "Babel >= 0.9.4",
        "jinja2",
        "pysolr",
        "Markdown >= 2.0.3",
        "Pygments >= 1.1.1",
        "EasyWidgets >= 0.1.1",
        "iso8601",
        "chardet >= 1.0.1",
        "feedparser >= 5.0.1",
        "oauth2 >= 1.2.0",
        "Ming >= 0.2.2dev-20110930",
    ],
    setup_requires=["PasteScript >= 1.7"],
    paster_plugins=['PasteScript', 'Pylons', 'TurboGears2', 'Ming'],
    packages=find_packages(exclude=['ez_setup']),
    include_package_data=True,
    test_suite='nose.collector',
    tests_require=['WebTest >= 1.2', 'BeautifulSoup', 'poster', 'nose'],
    package_data={'allura': ['i18n/*/LC_MESSAGES/*.mo',
                             'templates/**.html',
                             'templates/**.py',
                             'templates/**.xml',
                             'templates/**.txt',
                             'public/*/*/*/*/*',
                             ]},
    message_extractors={'allura': [
        ('**.py', 'python', None),
        ('templates/**.html', 'genshi', None),
        ('public/**', 'ignore', None)]},

    entry_points="""
    [paste.app_factory]
    main = allura.config.middleware:make_app
    task = allura.config.middleware:make_task_app
    tool_test = allura.config.middleware:make_tool_test_app

    [paste.app_install]
    main = pylons.util:PylonsInstaller
    tool_test = pylons.util:PylonsInstaller

    [allura]
    profile = allura.ext.user_profile:UserProfileApp
    admin = allura.ext.admin:AdminApp
    search = allura.ext.search:SearchApp
    home = allura.ext.project_home:ProjectHomeApp

    [allura.auth]
    local = allura.lib.plugin:LocalAuthenticationProvider
    ldap = allura.lib.plugin:LdapAuthenticationProvider

    [allura.user_prefs]
    local = allura.lib.plugin:LocalUserPreferencesProvider

    [allura.project_registration]
    local = allura.lib.plugin:LocalProjectRegistrationProvider

    [allura.theme]
    allura = allura.lib.plugin:ThemeProvider

    [allura.spam]
    akismet = allura.lib.spam.akismetfilter:AkismetSpamFilter
    mollom = allura.lib.spam.mollomfilter:MollomSpamFilter

    [allura.site_admin]
    stats = allura.controllers.site_admin:StatsSiteAdminExtension
    troves = allura.controllers.trovecategories:TroveCategorySiteAdminExtension

    [allura.user_profile.sections]
    personal-data = allura.ext.user_profile.user_main:PersonalDataSection
    projects = allura.ext.user_profile.user_main:ProjectsSection
    skills = allura.ext.user_profile.user_main:SkillsSection
    tools = allura.ext.user_profile.user_main:ToolsSection
    social = allura.ext.user_profile.user_main:SocialSection

    [paste.paster_command]
    taskd = allura.command.taskd:TaskdCommand
    taskd_cleanup = allura.command.taskd_cleanup:TaskdCleanupCommand
    task = allura.command.taskd:TaskCommand
    models = allura.command:ShowModelsCommand
    reindex = allura.command:ReindexCommand
    ensure_index = allura.command:EnsureIndexCommand
    script = allura.command:ScriptCommand
    set-tool-access = allura.command:SetToolAccessCommand
    smtp_server=allura.command:SMTPServerCommand
    create-neighborhood = allura.command:CreateNeighborhoodCommand
    update-neighborhood-home-tool = allura.command:UpdateNeighborhoodCommand
    create-trove-categories = allura.command:CreateTroveCategoriesCommand
    set-neighborhood-features = allura.command:SetNeighborhoodFeaturesCommand
    reclone-repo = allura.command.reclone_repo:RecloneRepoCommand

    [easy_widgets.resources]
    ew_resources=allura.config.resources:register_ew_resources

    [easy_widgets.engines]
    jinja = allura.config.app_cfg:JinjaEngine

    [activitystream]
    storage = activitystream.storage.mingstorage:MingStorage
    director = allura.model.timeline:Director
    aggregator = allura.model.timeline:Aggregator
    """,
)


text:
package org.apache.flink.table.runtime.operators.over.frame;

import org.apache.flink.table.data.RowData;
import org.apache.flink.table.runtime.generated.GeneratedAggsHandleFunction;
import org.apache.flink.table.runtime.util.ResettableExternalBuffer;
import org.apache.flink.table.types.logical.RowType;

/**
 * The row sliding window frame calculates frames with the following SQL form: ... ROW BETWEEN
 * [window frame preceding] AND [window frame following] [window frame preceding] ::=
 * [unsigned_value_specification] PRECEDING | CURRENT ROW [window frame following] ::=
 * [unsigned_value_specification] FOLLOWING | CURRENT ROW
 *
 * <p>e.g.: ... ROW BETWEEN 1 PRECEDING AND 1 FOLLOWING.
 */
public class RowSlidingOverFrame extends SlidingOverFrame {

    private final long leftBound;
    private final long rightBound;

    /** Index of the right bound input row. */
    private int inputRightIndex = 0;

    /** Index of the left bound input row. */
    private int inputLeftIndex = 0;

    public RowSlidingOverFrame(
            RowType inputType,
            RowType valueType,
            GeneratedAggsHandleFunction aggsHandleFunction,
            long leftBound,
            long rightBound) {
        super(inputType, valueType, aggsHandleFunction);
        this.leftBound = leftBound;
        this.rightBound = rightBound;
    }

    @Override
    public void prepare(ResettableExternalBuffer rows) throws Exception {
        super.prepare(rows);
        inputRightIndex = 0;
        inputLeftIndex = 0;
    }

    @Override
    public RowData process(int index, RowData current) throws Exception {
        boolean bufferUpdated = index == 0;

        // Drop all rows from the buffer util left bound.
        while (!buffer.isEmpty() && inputLeftIndex < index + leftBound) {
            buffer.remove();
            inputLeftIndex += 1;
            bufferUpdated = true;
        }

        // Add all rows to the buffer util right bound.
        while (nextRow != null && inputRightIndex <= index + rightBound) {
            if (inputLeftIndex < index + leftBound) {
                inputLeftIndex += 1;
            } else {
                buffer.add(inputSer.copy(nextRow));
                bufferUpdated = true;
            }
            nextRow = OverWindowFrame.getNextOrNull(inputIterator);
            inputRightIndex += 1;
        }

        return accumulateBuffer(bufferUpdated);
    }
}


text:
/// <reference path="CommonRobotModelImpl.ts" />
/// <reference path="robotParts/LightSensor.ts" />
/// <reference path="TrikKit/parts/TrikInfraredSensor.ts" />
/// <reference path="TrikKit/parts/TrikSonarSensor.ts" />
/// <reference path="TrikKit/parts/TrikLineSensor.ts" />
/// <reference path="../../interfaces/robotModel/RobotModelInterface.ts" />
/// <reference path="../../interfaces/robotModel/PortInfo.ts" />
/// <reference path="../../../constants/GeneralConstants.d.ts" />

class TwoDRobotModel extends CommonRobotModelImpl {
    private name: string;
    private image: string;
    private realModel: RobotModelInterface;

    constructor(realModel: RobotModelInterface, name: string) {
        super();
        var twoDRobotModel = this;
        this.realModel = realModel;
        this.name = name;
        this.image = GeneralConstants.APP_ROOT_PATH + "images/2dmodel/trikKit/trikTwoDRobot.svg"

        realModel.getAvailablePorts().forEach(function(port) {
            twoDRobotModel.addAllowedConnection(port, realModel.getAllowedDevices(port));
        });
    }

    sensorImagePath(deviceType: DeviceInfo): string {
        if (deviceType.isA(LightSensor)) {
            return GeneralConstants.APP_ROOT_PATH + "images/2dmodel/trikKit/twoDColorEmpty.svg";
        } else if (deviceType.isA(TrikInfraredSensor)) {
            return GeneralConstants.APP_ROOT_PATH + "images/2dmodel/trikKit/twoDIrRangeSensor.svg";
        } else if (deviceType.isA(TrikSonarSensor)) {
            return GeneralConstants.APP_ROOT_PATH + "images/2dmodel/trikKit/twoDUsRangeSensor.svg";
        } else if (deviceType.isA(TrikLineSensor)) {
            return GeneralConstants.APP_ROOT_PATH + "images/2dmodel/trikKit/twoDVideoModule.svg";
        }

        return null;
    }

    getName(): string {
        return this.name;
    }

    getRobotImage(): string {
        return this.image;
    }

    getConfigurablePorts(): PortInfo[] {
        return this.realModel.getConfigurablePorts();
    }
}


text:
function Test-PendingReboot {
    <#
        .SYNOPSIS
            Based on https://github.com/adbertram/PSSqlUpdater
            This function tests various registry values to see if the local computer is pending a reboot
        .NOTES
            Inspiration from: https://gallery.technet.microsoft.com/scriptcenter/Get-PendingReboot-Query-bdb79542
        .EXAMPLE
            PS> Test-PendingReboot

            This example checks various registry values to see if the local computer is pending a reboot.
    #>
    [OutputType([bool])]
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [DbaInstanceParameter]$ComputerName,
        [pscredential]$Credential
    )
    process {
        $icmParams = @{
            ComputerName = $ComputerName.ComputerName
            Raw          = $true
            ErrorAction  = 'Stop'
        }
        if (Test-Bound -ParameterName Credential) {
            $icmParams.Credential = $Credential
        }

        $OperatingSystem = Get-DbaCmObject -ComputerName $ComputerName.ComputerName  -Credential $Credential -ClassName Win32_OperatingSystem -EnableException

        # If Vista/2008 & Above query the CBS Reg Key
        If ($OperatingSystem.BuildNumber -ge 6001) {
            $PendingReboot = Invoke-Command2 @icmParams -ScriptBlock { Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing' -Name 'RebootPending' -ErrorAction SilentlyContinue }
            if ($PendingReboot) {
                Write-Message -Level Verbose -Message 'Reboot pending detected in the Component Based Servicing registry key'
                return $true
            }
        }

        # Query WUAU from the registry
        $PendingReboot = Invoke-Command2 @icmParams -ScriptBlock { Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update' -Name 'RebootRequired' -ErrorAction SilentlyContinue }
        if ($PendingReboot) {
            Write-Message -Level Verbose -Message 'WUAU has a reboot pending'
            return $true
        }

        # Query PendingFileRenameOperations from the registry
        $PendingReboot = Invoke-Command2 @icmParams -ScriptBlock { Get-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager' -Name 'PendingFileRenameOperations' -ErrorAction SilentlyContinue }
        if ($PendingReboot -and $PendingReboot.PendingFileRenameOperations) {
            Write-Message -Level Verbose -Message 'Reboot pending in the PendingFileRenameOperations registry value'
            return $true
        }
        return $false
    }
}


text:
opera.isReady(function(){

    var tab = [];
    var test = async_test("Check back broadCast popup", {timeout: 30000});

    function onMessage(event) {

	test.step(function(){
	    assert_equals("Message from popup", event.data, "Message received from the popup.");
	});
	test.done();
    }
    function onConnect(event) {
	opera.extension.broadcastMessage("Reply to this immediately. All of you");
    }

    opera.extension.onmessage = onMessage;
    opera.extension.onconnect = onConnect;

    try {
	var UIItemProperties = {
	    disabled: false,
	    title: "001 - broadcast popup",
	    icon: "oex/icon.png",
	    popup: {
		href: "oex/popup.html"
	    },
	    onclick: function(){
		testStarted = true;
		console.log('test started');
	    }

	}
	theButton = opera.contexts.toolbar.createItem( UIItemProperties );
	theButton.addEventListener('click', function(){console.log('dupa')});
	opera.contexts.toolbar.addItem( theButton );

	var uri = "data:text/html,<!DOCTYPE html>" + encodeURIComponent("Please click on the button to load the popup. Once the popup loads, a broadcast will be sent out.");
	createTab({url: uri, focused: true });

    } catch (e) {
        tests.step(function() {
            assert_unreached("Couldn't create button");
        });
    }
});


text:
from __future__ import print_function

import cx_Oracle
import SampleEnv

def OutputTypeHandler(cursor, name, defaultType, size, precision, scale):
    if defaultType in (cx_Oracle.STRING, cx_Oracle.FIXED_CHAR):
        return cursor.var(unicode, size, cursor.arraysize)

connection = cx_Oracle.Connection(SampleEnv.MAIN_CONNECT_STRING)
connection.outputtypehandler = OutputTypeHandler
cursor = connection.cursor()
cursor.execute("select * from TestStrings")
for row in cursor:
    print("Row:", row)


text:
SHIELD Documentation
====================

This directory contains the documentation for SHIELD.
Documents are grouped by audience: one for developers
(`docs/devs`) and another for operators (`docs/ops`).

Style Guide
-----------

Maintaining a consistent tone and voice throughout all of the
documentation is vital.  To that end, we adhere to the following
style guide:

  1. SHIELD is always uppercase, with no extra dots.
  2. Use informal first, or second person.

     For example, if explaining how to plan out where SHIELD and
     its agents get deployed, you might say the following:

     > Figuring out where the agents live is a matter of personal
     > opinion, driven by **your** situation.  **You will want
     > to** run the SHIELD agent as close as possible to the data
     > system as ...

  3. Less is more.  Shorter sentences have more power and impact
     than longer sentences.

  4. Never leverage a grandiloquent and ornate word when a
     diminutive one will suffice.

     Small words are okay.

  5. Use `back ticks`, in-line, for Commands, file names, and other
     computer-ish parts.

  6. Always spell-check.  Yes, it's a pain thanks to all the
     jargon and initialism, but it's worth it every time.

  7. Use emphasis _sparingly_, but **use it when you need to.**

  8. Avoid the passive voice.

Building the Documentation
--------------------------

In the end, we want to maintain versioned copies of the rendered
documentation for each minor version (`x.y`) of SHIELD, on the
[shieldproject.io][1] website.

The `mkdocs` utility helps with that.  It does a few
things:

  - Create the directory structure
  - Resolves variables in the markdown to version-specific URLs
  - Renders HTML from the markdown

From the root of the codebase, run `./bin/mkdocs` to get the
help and usage information.

To generate _working copy_ documentation, suitable for hosting
with something like [gow](https://github.com/jhunt/gow):

    $ ./bin/mkdocs --version 8.2.0   \
                   --docroot /docs   \
                   --output tmp/docs \
                   --style basic
    [mkdir]  tmp/docs/ops
    [render] tmp/docs/ops/architecture.md
    [render] tmp/docs/ops/getting-started.md
    [render] tmp/docs/ops/plugins.md
    [render] tmp/docs/ops/manual.md
    [mkdir]  tmp/docs/ops/architecture
    [copy]   tmp/docs/ops/architecture/agent.png
    [copy]   tmp/docs/ops/architecture/webui.png
    [copy]   tmp/docs/ops/architecture/database.png
    [copy]   tmp/docs/ops/architecture/overview.png
    ... etc ...

    $ (cd tmp/doc && gow)
    binding *:3001 to serve / -> .

You can now access the documentation at
<http://127.0.0.1:3001/docs>.

You can also just run

    make docs

:)

Screenshots / Terminal Output
-----------------------------

To help with consistency, we provide a Docker Compose recipe for
running a configured v8.x SHIELD core + agent.  Use this
environment any time you need a screenshot, or some terminal
output.

To use it (assuming you have Docker and Docker Compose
[installed][2]):

    $ cd docs
    $ docker-compose up

SHIELD should be available at http://localhost:9009/; you can
visit that in your browser, or hit it via the CLI.  The default
admin (failsafe) credentials are `admin` / `password`.

There is a SHIELD import file, `docs/documentum.yml`, that you can
then use to re-inflate all of the test data.  This import data set
will evolve and grow over time, so add to it as needed.

    $ cd docs
    $ shield api http://localhost:9009 documentum
    $ shield -c documentum login
      ... provide admin creds ...
    $ shield -c documentum import documentum.yml

Now you have a fully-populated SHIELD instance that will stay
consistent across developers, machines, and environments!  Go you!

Firefox has this wonderful thing called _Responsive Mode_.  It's
actually for testing out mobile platforms without needing one of
every phone / tablet / phablet that has ever been made, but it has
a few interesting features that make it ideal for distributed
screenshot taking:

  1. It allows you to set the screen dimensions
  2. It has a _screenshot_ button

You can access it via the context menu > Web Developer >
Responsive Design Mode.  If you prefer shortcuts, its ⌥⌘ (at least
on macOS).

All screenshots are 1200px wide, unless you have a very good
reason to need something smaller.  Scrensshots should be as tall
as necessary to show what needs showing, but no taller.

Asset Organization
------------------

Each document exists as a `.md` file (containing the markdown),
and a directory, that share a short name.  For example, the
_Getting Started_ document's short name is `getting-started`.  If
you look in the `docs/ops` folder, you will see the following:

- `getting-started.md` - The text of the document.
- `getting-started/` - All assets pertinent to the document.

This helps us avoid naming collisions that we would otherwise run
into with a shared directory for images, SVG files, YAML, etc.

When the documentation is built into its final HTML form, the
markdown file will be saved _into_ the asset folder as
`index.html`.  You'll want to avoid naming an asset `index.html`
for this reason.  This also lets you link to or embed other assets
using relative HTTP paths.  For example:

    <img src="intro.png">

Will resolve from inside of the `getting-started/` directory, and
find the appropriate image.  This is the most portable way, that
allows us (and our pipelines!) to auto-generate and relocate
instances of the documentation, as need arises.

The Document Landscape
----------------------

- **Getting Started**

  Audience: operators who want to install SHIELD.

  Having read this, and following the (detailed) instructions in
  this document, an operator should have a running SHIELD core, a
  few agents, and have properly backed up and restored a single
  thing.  Their next step is the _Operations Manual_.

- **Quickstart**

  Audience: operators who just want to get SHIELD up and running,
  without reading too much; the `tl;dr` crowd.

  This is (more or less) the same document as _Getting Started_,
  in fewer words.

- **SHIELD Architecture**

  Audience: operators evaluating SHIELD to determine if it is a
  good fit for their use-case, from the architectural "pieces and
  parts" standpoint.

  Required reading for all developers wishing to get involved in
  contributing to SHIELD, and for all operators who want to truly
  understand the guts of SHIELD.

- **Operations Manual**

  Audience: operators who want to learn how to use SHIELD, in full
  detail.  This document also serves as reference material for more
  seasoned operators.

  The Operations Manual is _big_.  It covers all functional parts
  of SHIELD, including:

    - Architecture
    - The Web UI and CLI
    - Configuration
    - RBAC and Multi-tenancy
    - Plugins
    - Encryption

- **API Reference**

  Audience: developers who wish to understand more about how
  SHIELD works, either to integrate something _with_ SHIELD, or to
   fix / patch / extend the SHIELD software itself.

  (This one has some bespoke tooling that makes its compilation
   easier and less error-prone.)

- **Plugin Architecture**

  Audience: developers wishing to write / modify SHIELD plugins

[1]: https://shieldproject.io
[2]: https://docs.docker.com/compose/install/


text:
class CIPiece : public CPieceAbstract {

	public:
		CIPiece(unsigned int dim, int iX, int iY, const CVector3& color);
		~CIPiece();
		void Turn();

};

#endif


text:
<?php declare(strict_types=1);

namespace PHPUnit\Framework\TestStatus;

/**
 * @no-named-arguments Parameter names are not covered by the backward compatibility promise for PHPUnit
 *
 * @psalm-immutable
 */
final class Unknown extends TestStatus
{
    /**
     * @psalm-assert-if-true Unknown $this
     */
    public function isUnknown(): bool
    {
        return true;
    }

    public function asInt(): int
    {
        return -1;
    }

    public function asString(): string
    {
        return 'unknown';
    }
}


text:
var moment = require('moment');

/*
 * todo: complete rewrite. Current version is extremely inefficient and was
 * never meant to be used for anything other than PoF.
 */

function StreakMetrics(o) {
  this.endDate = o.endDate || moment().startOf('day').format('YYYY-MM-DD');
  this.startDate = o.startDate;
  this.excludedDays = o.excludedDays || [];
  this.range = o.range && o.range.length ?
    o.range.slice() : [Number.MIN_VALUE, Number.MAX_VALUE];
  this.range.sort(function (l, r) { return l - r; });
  this.inverted = !!o.inverted;
  this.data = o.data;
}

StreakMetrics.prototype.totalEntries = function () {
  var data = this.data;
  var startDate = this.startDate;
  var excludedDays = this.excludedDays;
  return Object.keys(data).reduce(
    function (v, key) {
      return v + ((!startDate || startDate <= key) && data[key] &&
        !~excludedDays.indexOf(moment(key).day()) ? 1 : 0);
    }, 0);
};

StreakMetrics.prototype.longestStreak = function () {
  var data = this.data;
  var endDate = moment(this.endDate);
  var startDate = this.startDate ? moment(this.startDate) : null;
  var excludedDays = this.excludedDays;
  var range = this.range;
  var inverted = this.inverted;
  var keys = Object.keys(data).sort();
  var entries = [];
  if (inverted) {
    entries.push(moment(startDate));
  }
  var dayBeforeStartDate = moment(startDate).subtract(1, 'day');
  var dayAfterEndDate = moment(endDate).add(1, 'day');
  keys.forEach(function (key) {
    var d = moment(key);
    if (data[key] &&
        (!startDate || d.isAfter(dayBeforeStartDate)) &&
        d.isBefore(dayAfterEndDate) &&
        !~excludedDays.indexOf(moment(key).day()) &&
        range[0] <= data[key] && data[key] <= range[1]) {
      entries.push(d);
    }
  });
  if (inverted) {
    entries.push(endDate);
  }
  if (entries.length === (inverted ? 2 : 0)) {
    return inverted ? endDate.diff(startDate, 'days') + 1 : 0;
  }
  var longest = 0;
  var streak = 1;
  for (var i = 0, j, end = entries.length - 1; i < end; i++) {
    j = 0;
    var nextDay = moment(entries[i]);
    do {
      nextDay.add(1, 'day');
      j++;
    } while (~excludedDays.indexOf(nextDay.day()));
    if (inverted) {
      streak = entries[i + 1].diff(entries[i], 'days') - j + 1;
      if (longest < streak) {
        longest = streak;
      }
    } else {
      if (moment(entries[i]).add(j, 'day').isSame(entries[i + 1])) {
        streak++;
      } else {
        if (longest < streak) {
          longest = streak;
        }
        streak = 1;
      }
    }
  }
  if (longest < streak) {
    longest = streak;
  }
  return longest;
};

StreakMetrics.prototype.currentStreak = function () {
  var data = this.data;
  var endDate = moment(this.endDate);
  var startDate = this.startDate ? moment(this.startDate) : null;
  var excludedDays = this.excludedDays;
  var range = this.range;
  var inverted = this.inverted;
  var result = 0;
  var countDown = startDate ? endDate.diff(startDate, 'days') + 1 :
    Number.MAX_VALUE;
  var dayBeforeStartDate = moment(startDate).subtract(1, 'day');
  var dayAfterEndDate = moment(endDate).add(1, 'day');
  var dataSpecified = function (key) {
    var d = moment(key);
    return (data[key] &&
      (!startDate || d.isAfter(dayBeforeStartDate)) &&
      d.isBefore(dayAfterEndDate) &&
      range[0] <= data[key] && data[key] <= range[1]) ||
      ~excludedDays.indexOf(d.day());
  };
  while ((dataSpecified(endDate.format('YYYY-MM-DD')) ^ inverted) &&
    countDown--) {
    if (!~excludedDays.indexOf(endDate.day())) {
      result++;
    }
    endDate.subtract(1, 'day');
  }
  return result;
};

module.exports = StreakMetrics;


text:
package adb_test

import (
	"context"
	"testing"

	"github.com/google/gapid/core/assert"
	"github.com/google/gapid/core/log"
	"github.com/google/gapid/core/os/android/adb"
)

func mustConnect(ctx context.Context, serial string) adb.Device {
	devices, err := adb.Devices(ctx)
	if err != nil {
		log.F(ctx, true, "Couldn't get devices. Error: %v", err)
		return nil
	}
	for _, d := range devices {
		if d.Instance().Serial == serial {
			return d
		}
	}
	log.F(ctx, true, "Couldn't find device '%v'", serial)
	return nil
}

func TestADBShell(t_ *testing.T) {
	ctx := log.Testing(t_)
	d := mustConnect(ctx, "production_device")
	assert.For(ctx, "Device").ThatString(d).Equals("production_device")
	assert.For(ctx, "Device shell").ThatString(d.Shell("").Target).Equals("shell:production_device")
}


text:
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
                        unicode_literals, with_statement)

import logging
import os
import re
import traceback
from collections import defaultdict

import six
from pathspec import PathSpec
from pathspec.gitignore import GitIgnorePattern
from twitter.common.collections import OrderedSet

from pants.base.build_environment import get_buildroot
from pants.base.build_file import BuildFile
from pants.base.specs import DescendantAddresses, SiblingAddresses, SingleAddress
from pants.build_graph.address import Address, parse_spec
from pants.build_graph.address_lookup_error import AddressLookupError
from pants.build_graph.build_file_parser import BuildFileParser
from pants.util.dirutil import fast_relpath

logger = logging.getLogger(__name__)

# Note: Significant effort has been made to keep the types BuildFile, BuildGraph, Address, and
# Target separated appropriately.  The BuildFileAddressMapper is intended to have knowledge
# of just BuildFile, BuildFileParser and Address.
#
# Here are some guidelines to help maintain this abstraction:
#  - Use the terminology 'address' instead of 'target' in symbols and user messages
#  - Wrap exceptions from BuildFile and BuildFileParser with a subclass of AddressLookupError
#     so that callers do not have to reference those modules
#
# Note: 'spec' should not be a user visible term, substitute 'address' instead.
class BuildFileAddressMapper(object):
  """Maps addresses in the pants virtual address space to corresponding BUILD file declarations."""

  class AddressNotInBuildFile(AddressLookupError):
    """Indicates an address cannot be found in an existing BUILD file."""

  class EmptyBuildFileError(AddressLookupError):
    """Indicates no addresses are defined in a BUILD file."""

  class InvalidBuildFileReference(AddressLookupError):
    """Indicates no BUILD file exists at the address referenced."""

  class InvalidAddressError(AddressLookupError):
    """Indicates an address cannot be parsed."""

  class BuildFileScanError(AddressLookupError):
    """Indicates a problem was encountered scanning a tree of BUILD files."""

  class InvalidRootError(BuildFileScanError):
    """Indicates an invalid scan root was supplied."""

  # Target specs are mapped to the patterns which match them, if any. This variable is a key for
  # specs which don't match any exclusion regexps. We know it won't already be in the list of
  # patterns, because the asterisks in its name make it an invalid regexp.
  _UNMATCHED_KEY = '** unmatched **'

  def __init__(self, build_file_parser, project_tree, build_ignore_patterns=None, exclude_target_regexps=None):
    """Create a BuildFileAddressMapper.

    :param build_file_parser: An instance of BuildFileParser
    :param build_file_type: A subclass of BuildFile used to construct and cache BuildFile objects
    """
    self._build_file_parser = build_file_parser
    self._spec_path_to_address_map_map = {}  # {spec_path: {address: addressable}} mapping
    self._project_tree = project_tree
    self._build_ignore_patterns = PathSpec.from_lines(GitIgnorePattern, build_ignore_patterns or [])

    self._exclude_target_regexps = exclude_target_regexps or []
    self._exclude_patterns = [re.compile(pattern) for pattern in self._exclude_target_regexps]

  @property
  def root_dir(self):
    return self._build_file_parser.root_dir

  def _raise_incorrect_address_error(self, spec_path, wrong_target_name, targets):
    """Search through the list of targets and return those which originate from the same folder
    which wrong_target_name resides in.

    :raises: A helpful error message listing possible correct target addresses.
    """
    was_not_found_message = '{target_name} was not found in BUILD files from {spec_path}'.format(
      target_name=wrong_target_name, spec_path=os.path.join(self._project_tree.build_root, spec_path))

    if not targets:
      raise self.EmptyBuildFileError(
        '{was_not_found_message}, because that directory contains no BUILD files defining addressable entities.'
          .format(was_not_found_message=was_not_found_message))

    # Print BUILD file extensions if there's more than one BUILD file with targets only.
    if len(set([target.build_file for target in targets])) == 1:
      specs = [':{}'.format(target.target_name) for target in targets]
    else:
      specs = [':{} (from {})'.format(target.target_name, os.path.basename(target.build_file.relpath))
               for target in targets]

    # Might be neat to sort by edit distance or something, but for now alphabetical is fine.
    specs = [''.join(pair) for pair in sorted(specs)]

    # Give different error messages depending on whether BUILD file was empty.
    one_of = ' one of' if len(specs) > 1 else ''  # Handle plurality, just for UX.
    raise self.AddressNotInBuildFile(
      '{was_not_found_message}. Perhaps you '
      'meant{one_of}: \n  {specs}'.format(was_not_found_message=was_not_found_message,
                                          one_of=one_of,
                                          specs='\n  '.join(specs)))

  def resolve(self, address):
    """Maps an address in the virtual address space to an object.

    :param Address address: the address to lookup in a BUILD file
    :raises AddressLookupError: if the path to the address is not found.
    :returns: A tuple of the natively mapped BuildFileAddress and the Addressable it points to.
    """
    address_map = self._address_map_from_spec_path(address.spec_path)
    if address not in address_map:
      self._raise_incorrect_address_error(address.spec_path, address.target_name, address_map)
    else:
      return address_map[address]

  def resolve_spec(self, spec):
    """Converts a spec to an address and maps it using `resolve`"""
    try:
      address = Address.parse(spec)
    except ValueError as e:
      raise self.InvalidAddressError(e)
    _, addressable = self.resolve(address)
    return addressable

  def _address_map_from_spec_path(self, spec_path):
    """Returns a resolution map of all addresses in a "directory" in the virtual address space.
    :returns {Address: (Address, <resolved Object>)}:
    """
    if spec_path not in self._spec_path_to_address_map_map:
      try:
        build_files = list(BuildFile.get_build_files_family(self._project_tree, spec_path,
                                                            self._build_ignore_patterns))
        if not build_files:
          raise self.BuildFileScanError("{spec_path} does not contain any BUILD files."
                                        .format(spec_path=os.path.join(self.root_dir, spec_path)))
        mapping = self._build_file_parser.address_map_from_build_files(build_files)
      except BuildFileParser.BuildFileParserError as e:
        raise AddressLookupError("{message}\n Loading addresses from '{spec_path}' failed."
                                 .format(message=e, spec_path=spec_path))

      address_map = {address: (address, addressed) for address, addressed in mapping.items()}
      self._spec_path_to_address_map_map[spec_path] = address_map
    return self._spec_path_to_address_map_map[spec_path]

  def addresses_in_spec_path(self, spec_path):
    """Returns only the addresses gathered by `address_map_from_spec_path`, with no values."""
    return self._address_map_from_spec_path(spec_path).keys()

  def spec_to_address(self, spec, relative_to=''):
    """A helper method for mapping a spec to the correct build file address.

    :param string spec: A spec to lookup in the map.
    :param string relative_to: Path the spec might be relative to
    :raises :class:`pants.build_graph.address_lookup_error.AddressLookupError`
            If the BUILD file cannot be found in the path specified by the spec.
    :returns: A new Address instance.
    :rtype: :class:`pants.build_graph.address.BuildFileAddress`
    """
    spec_path, name = parse_spec(spec, relative_to=relative_to)
    address = Address(spec_path, name)
    try:
      build_file_address, _ = self.resolve(address)
      return build_file_address
    except AddressLookupError as e:
      raise self.InvalidBuildFileReference('{message}\n  when translating spec {spec}'
                                           .format(message=e, spec=spec))

  def scan_build_files(self, base_path):
    return BuildFile.scan_build_files(self._project_tree, base_path,
                                      build_ignore_patterns=self._build_ignore_patterns)

  def specs_to_addresses(self, specs, relative_to=''):
    """The equivalent of `spec_to_address` for a group of specs all relative to the same path.

    :param spec: iterable of Addresses.
    :raises AddressLookupError: if the BUILD file cannot be found in the path specified by the spec
    """
    for spec in specs:
      yield self.spec_to_address(spec, relative_to=relative_to)

  def scan_addresses(self, root=None):
    """Recursively gathers all addresses visible under `root` of the virtual address space.

    :param string root: The absolute path of the root to scan; defaults to the root directory of the
                        pants project.
    :rtype: set of :class:`pants.build_graph.address.Address`
    :raises AddressLookupError: if there is a problem parsing a BUILD file
    """
    root_dir = get_buildroot()
    base_path = None

    if root:
      try:
        base_path = fast_relpath(root, root_dir)
      except ValueError as e:
        raise self.InvalidRootError(e)

    addresses = set()
    try:
      for build_file in BuildFile.scan_build_files(self._project_tree,
                                                   base_relpath=base_path,
                                                   build_ignore_patterns=self._build_ignore_patterns):
        for address in self.addresses_in_spec_path(build_file.spec_path):
          addresses.add(address)
    except BuildFile.BuildFileError as e:
      # Handle exception from BuildFile out of paranoia.  Currently, there is no way to trigger it.
      raise self.BuildFileScanError("{message}\n while scanning BUILD files in '{root}'."
                                    .format(message=e, root=root))
    return addresses

  def scan_specs(self, specs, fail_fast=True):
    """Execute a collection of `specs.Spec` objects and return an ordered set of Addresses."""
    excluded_target_map = defaultdict(set)  # pattern -> targets (for debugging)

    def exclude_spec(spec):
      for pattern in self._exclude_patterns:
        if pattern.search(spec) is not None:
          excluded_target_map[pattern.pattern].add(spec)
          return True
      excluded_target_map[self._UNMATCHED_KEY].add(spec)
      return False

    def exclude_address(address):
      return exclude_spec(address.spec)

    addresses = OrderedSet()
    for spec in specs:
      for address in self._scan_spec(spec, fail_fast, exclude_spec):
        if not exclude_address(address):
          addresses.add(address)

    # Print debug information about the excluded targets
    if logger.getEffectiveLevel() <= logging.DEBUG and excluded_target_map:
      logger.debug('excludes:\n  {excludes}'
                   .format(excludes='\n  '.join(self._exclude_target_regexps)))
      targets = ', '.join(excluded_target_map[self._UNMATCHED_KEY])
      logger.debug('Targets after excludes: %s', targets)
      excluded_count = 0
      for pattern, targets in six.iteritems(excluded_target_map):
        if pattern != self._UNMATCHED_KEY:
          logger.debug('Targets excluded by pattern {pattern}\n  {targets}'
                       .format(pattern=pattern,
                               targets='\n  '.join(targets)))
          excluded_count += len(targets)
      logger.debug('Excluded {count} target{plural}.'
                   .format(count=excluded_count,
                           plural=('s' if excluded_count != 1 else '')))
    return addresses

  def _scan_spec(self, spec, fail_fast, exclude_spec):
    """Scans the given address spec."""

    errored_out = []

    if type(spec) is DescendantAddresses:
      addresses = set()
      try:
        build_files = self.scan_build_files(base_path=spec.directory)
      except BuildFile.BuildFileError as e:
        raise AddressLookupError(e)

      for build_file in build_files:
        try:
          addresses.update(self.addresses_in_spec_path(build_file.spec_path))
        except (BuildFile.BuildFileError, AddressLookupError) as e:
          if fail_fast:
            raise AddressLookupError(e)
          errored_out.append('--------------------')
          errored_out.append(traceback.format_exc())
          errored_out.append('Exception message: {0}'.format(e))
      if errored_out:
        error_msg = '\n'.join(errored_out + ["Invalid BUILD files for [{0}]".format(spec.to_spec_string())])
        raise AddressLookupError(error_msg)
      return addresses
    elif type(spec) is SiblingAddresses:
      return set(self.addresses_in_spec_path(spec.directory))
    elif type(spec) is SingleAddress:
      return {self.spec_to_address(spec.to_spec_string())}
    else:
      raise ValueError('Unsupported Spec type: {}'.format(spec))


text:
package com.zwzfj2.badboy;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;

public class GuidePageActivity extends Activity {

	private ViewPager viewPager;
	private ArrayList<View> pageViews;
	private ViewGroup main;

	 @Override
	 public void onCreate(Bundle savedInstanceState) {
		 super.onCreate(savedInstanceState);
	     requestWindowFeature(Window.FEATURE_NO_TITLE);

	     //获取SharedPreferences对象,路径在/data/data/cn.itcast.preferences/shared_pref/paramater.xml
	     SharedPreferences sp=getSharedPreferences("paramater", Context.MODE_PRIVATE);
	     //获取编辑器
	     Editor editor=sp.edit();
	     //通过editor进行设置
	     editor.putString("firstOpen", "1");
	     //提交修改,将数据写到文件
	     editor.commit();

	     LayoutInflater li = getLayoutInflater();
	     pageViews = new ArrayList<View>();
	     pageViews.add(li.inflate(R.layout.guidepage0, null));
	     pageViews.add(li.inflate(R.layout.guidepage1, null));
	     pageViews.add(li.inflate(R.layout.guidepage2, null));
	     pageViews.add(li.inflate(R.layout.guidepage3, null));
	     main =  (ViewGroup)li.inflate(R.layout.activity_splash_page, null);
	     viewPager = (ViewPager)main.findViewById(R.id.guidePages);
	     setContentView(main);
	     viewPager.setAdapter(new GuidePageAdapter());
	 }

	    /** 指引页面Adapter */
	    class GuidePageAdapter extends PagerAdapter {
	        @Override
	        public int getCount() {
	            return pageViews.size();
	        }
	        @Override
	        public boolean isViewFromObject(View arg0, Object arg1) {
	            return arg0 == arg1;
	        }
	        @Override
	        public int getItemPosition(Object object) {
	            // TODO Auto-generated method stub
	            return super.getItemPosition(object);
	        }
	        @Override
	        public void destroyItem(View arg0, int arg1, Object arg2) {
	            // TODO Auto-generated method stub
	            ((ViewPager) arg0).removeView(pageViews.get(arg1));
	        }
	        @Override
	        public Object instantiateItem(View arg0, int arg1) {
	            // TODO Auto-generated method stub
	            ((ViewPager) arg0).addView(pageViews.get(arg1));
	            return pageViews.get(arg1);
	        }
	        @Override
	        public void restoreState(Parcelable arg0, ClassLoader arg1) {
	            // TODO Auto-generated method stub

	        }

	        @Override
	        public Parcelable saveState() {
	            // TODO Auto-generated method stub
	            return null;
	        }

	        @Override
	        public void startUpdate(View arg0) {
	            // TODO Auto-generated method stub

	        }

	        @Override
	        public void finishUpdate(View arg0) {
	            // TODO Auto-generated method stub

	        }
	    }
}


text:
<?php
include 'RestApi.php';
/**
 * Twitter
 *
 * with help of the API this class delivers all kind of tweeted images from twitter
 *
 * @package    socialstreams
 * @subpackage socialstreams/twitter
 * @author     ThemePunch <info@themepunch.com>
 */

class TP_twitter {

  /**
   * Consumer Key
   *
   * @since    1.0.0
   * @access   private
   * @var      string    $consumer_key    Consumer Key
   */
  private $consumer_key;

  /**
   * Consumer Secret
   *
   * @since    1.0.0
   * @access   private
   * @var      string    $consumer_secret    Consumer Secret
   */
  private $consumer_secret;

  /**
   * Access Token
   *
   * @since    1.0.0
   * @access   private
   * @var      string    $access_token    Access Token
   */
  private $access_token;

  /**
   * Access Token Secret
   *
   * @since    1.0.0
   * @access   private
   * @var      string    $access_token_secret    Access Token Secret
   */
  private $access_token_secret;

  /**
   * Initialize the class and set its properties.
   *
   * @since    1.0.0
   * @param      string    $api_key flickr API key.
   */
  public function __construct($consumer_key,$consumer_secret,$access_token,$access_token_secret) {
    $this->consumer_key         =   $consumer_key;
    $this->consumer_secret      =   $consumer_secret;
    $this->access_token         =   $access_token;
    $this->access_token_secret  =   $access_token_secret;
  }

  /**
   * Get Tweets
   *
   * @since    1.0.0
   * @param    string    $twitter_account   Twitter account without trailing @ char
   */
  public function get_public_photos($twitter_account){
    $twitter = new \TwitterPhp\RestApi($this->consumer_key,$this->consumer_secret,$this->access_token,$this->access_token_secret);
    /*
     * Connect as application
     * https://dev.twitter.com/docs/auth/application-only-auth
     */
    $connection = $twitter->connectAsApplication();

    /*
     * Collection of the most recent Tweets posted by the user indicated by the screen_name, without replies
     * https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline
     */
    $tweets = $connection->get('/statuses/user_timeline',array('screen_name' => $twitter_account,  'entities' => 1, 'trim_user' => 0 , 'exclude_replies' => 'true'));
    //var_dump($tweets);
    return $tweets;
  }

  /**
   * Find Key in array and return value (multidim array possible)
   *
   * @since    1.0.0
   * @param    string    $key   Needle
   * @param    array     $form  Haystack
   */
  public static function array_find_element_by_key($key, $form) {
      if (array_key_exists($key, $form)) {
        $ret =& $form[$key];
        return $ret;
      }
      foreach ($form as $k => $v) {
        if (is_array($v)) {
          $ret =TP_twitter::array_find_element_by_key($key, $form[$k]);
          if ($ret) {
            return $ret;
          }
        }
      }
      return FALSE;
  }

  /**
   * Prepare output array $stream
   *
   * @since    1.0.0
   * @param    string    $tweets  Twitter Output Data
   */
  public static function makeClickableLinks($s) {
    return preg_replace('@(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-]*(\?\S+)?[^\.\s])?)?)@', '$1', $s);
  }

}
?>


text:
package org.zackratos.weather.mvp;

/**
 * Created by Administrator on 2017/7/6.
 */

public interface BaseView {
}


text:
import { Injectable } from '@angular/core';

// @Injectable()
export class PagerService {
  public getPager(totalItems: number, currentPage: number = 1, pageSize: number = 10) {
    // calculate total pages
    let totalPages = Math.ceil(totalItems / pageSize);

    let startPage: number, endPage: number;
    if (totalPages <= 10) {
      // less than 10 total pages so show all
      startPage = 1;
      endPage = totalPages;
    } else {
      // more than 10 total pages so calculate start and end pages
      if (currentPage <= 6) {
        startPage = 1;
        endPage = 10;
      } else if (currentPage + 4 >= totalPages) {
        startPage = totalPages - 9;
        endPage = totalPages;
      } else {
        startPage = currentPage - 5;
        endPage = currentPage + 4;
      }
    }

    // calculate start and end item indexes
    let startIndex = (currentPage - 1) * pageSize;
    let endIndex = Math.min(startIndex + pageSize - 1, totalItems - 1);

    // return object with all pager properties required by the view
    return {
      totalItems: totalItems,
      currentPage: currentPage,
      pageSize: pageSize,
      totalPages: totalPages,
      startPage: startPage,
      endPage: endPage,
      startIndex: startIndex,
      endIndex: endIndex
    };
  }
}


text:
module CSS
  class BorderUnitProperty < MarginProperty
    def init(parent, name, value)
      @name = name
      super
    end

    def name
      @name
    end

    def to_style
      [@parent.try(:name), super].compact.join('-')
    end
  end
end


text:
@interface PodsDummy_Pods_PLAudioStreamingKit : NSObject
@end
@implementation PodsDummy_Pods_PLAudioStreamingKit
@end


text:
package Paws::CloudSearch::DescribeIndexFieldsResponse;
  use Moose;
  has IndexFields => (is => 'ro', isa => 'ArrayRef[Paws::CloudSearch::IndexFieldStatus]', required => 1);

  has _request_id => (is => 'ro', isa => 'Str');
1;

### main pod documentation begin ###

=head1 NAME

Paws::CloudSearch::DescribeIndexFieldsResponse

=head1 ATTRIBUTES

=head2 B<REQUIRED> IndexFields => ArrayRef[L<Paws::CloudSearch::IndexFieldStatus>]

The index fields configured for the domain.

=head2 _request_id => Str

=cut


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.network.fluent.models;

import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.network.models.ApplicationGatewayBackendAddressPool;
import com.azure.resourcemanager.network.models.ApplicationGatewayBackendHealthHttpSettings;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;

/** Result of on demand test probe. */
@Fluent
public final class ApplicationGatewayBackendHealthOnDemandInner {
    @JsonIgnore
    private final ClientLogger logger = new ClientLogger(ApplicationGatewayBackendHealthOnDemandInner.class);

    /*
     * Reference to an ApplicationGatewayBackendAddressPool resource.
     */
    @JsonProperty(value = "backendAddressPool")
    private ApplicationGatewayBackendAddressPool backendAddressPool;

    /*
     * Application gateway BackendHealthHttp settings.
     */
    @JsonProperty(value = "backendHealthHttpSettings")
    private ApplicationGatewayBackendHealthHttpSettings backendHealthHttpSettings;

    /**
     * Get the backendAddressPool property: Reference to an ApplicationGatewayBackendAddressPool resource.
     *
     * @return the backendAddressPool value.
     */
    public ApplicationGatewayBackendAddressPool backendAddressPool() {
        return this.backendAddressPool;
    }

    /**
     * Set the backendAddressPool property: Reference to an ApplicationGatewayBackendAddressPool resource.
     *
     * @param backendAddressPool the backendAddressPool value to set.
     * @return the ApplicationGatewayBackendHealthOnDemandInner object itself.
     */
    public ApplicationGatewayBackendHealthOnDemandInner withBackendAddressPool(
        ApplicationGatewayBackendAddressPool backendAddressPool) {
        this.backendAddressPool = backendAddressPool;
        return this;
    }

    /**
     * Get the backendHealthHttpSettings property: Application gateway BackendHealthHttp settings.
     *
     * @return the backendHealthHttpSettings value.
     */
    public ApplicationGatewayBackendHealthHttpSettings backendHealthHttpSettings() {
        return this.backendHealthHttpSettings;
    }

    /**
     * Set the backendHealthHttpSettings property: Application gateway BackendHealthHttp settings.
     *
     * @param backendHealthHttpSettings the backendHealthHttpSettings value to set.
     * @return the ApplicationGatewayBackendHealthOnDemandInner object itself.
     */
    public ApplicationGatewayBackendHealthOnDemandInner withBackendHealthHttpSettings(
        ApplicationGatewayBackendHealthHttpSettings backendHealthHttpSettings) {
        this.backendHealthHttpSettings = backendHealthHttpSettings;
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
        if (backendAddressPool() != null) {
            backendAddressPool().validate();
        }
        if (backendHealthHttpSettings() != null) {
            backendHealthHttpSettings().validate();
        }
    }
}


text:
package com.github.dockerjava.api.model;

import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;

import javax.annotation.CheckForNull;
import java.io.Serializable;

@JsonInclude(Include.NON_NULL)
public class AuthConfig implements Serializable {
    private static final long serialVersionUID = 1L;

    /**
     * For backwards compatibility. Make sure you update the properties if you change this.
     *
     * @see "/docker.io.properties"
     */
    public static final String DEFAULT_SERVER_ADDRESS = "https://index.docker.io/v1/";

    @JsonProperty
    private String username;

    @JsonProperty
    private String password;

    @JsonProperty
    private String email;

    @JsonProperty("serveraddress")
    private String registryAddress = DEFAULT_SERVER_ADDRESS;

    @JsonProperty("auth")
    private String auth;

    /**
     * @since {@link com.github.dockerjava.core.RemoteApiVersion#VERSION_1_22}
     */
    @JsonProperty("registrytoken")
    private String registrytoken;

    public String getUsername() {
        return username;
    }

    public AuthConfig withUsername(String username) {
        this.username = username;
        return this;
    }

    public String getPassword() {
        return password;
    }

    public AuthConfig withPassword(String password) {
        this.password = password;
        return this;
    }

    public String getEmail() {
        return email;
    }

    public AuthConfig withEmail(String email) {
        this.email = email;
        return this;
    }

    public String getRegistryAddress() {
        return registryAddress;
    }

    public AuthConfig withRegistryAddress(String registryAddress) {
        this.registryAddress = registryAddress;
        return this;
    }

    public String getAuth() {
        return auth;
    }

    public AuthConfig withAuth(String auth) {
        this.auth = auth;
        return this;
    }

    /**
     * @see #registrytoken
     */
    @CheckForNull
    public String getRegistrytoken() {
        return registrytoken;
    }

    /**
     * @see #registrytoken
     */
    public AuthConfig withRegistrytoken(String registrytoken) {
        this.registrytoken = registrytoken;
        return this;
    }

    @Override
    public String toString() {
        return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE);
    }

    // CHECKSTYLE:OFF
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((auth == null) ? 0 : auth.hashCode());
        result = prime * result + ((email == null) ? 0 : email.hashCode());
        result = prime * result + ((password == null) ? 0 : password.hashCode());
        result = prime * result + ((registryAddress == null) ? 0 : registryAddress.hashCode());
        result = prime * result + ((username == null) ? 0 : username.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        AuthConfig other = (AuthConfig) obj;
        if (auth == null) {
            if (other.auth != null)
                return false;
        } else if (!auth.equals(other.auth))
            return false;
        if (email == null) {
            if (other.email != null)
                return false;
        } else if (!email.equals(other.email))
            return false;
        if (password == null) {
            if (other.password != null)
                return false;
        } else if (!password.equals(other.password))
            return false;
        if (registryAddress == null) {
            if (other.registryAddress != null)
                return false;
        } else if (!registryAddress.equals(other.registryAddress))
            return false;
        if (username == null) {
            if (other.username != null)
                return false;
        } else if (!username.equals(other.username))
            return false;
        return true;
    }
    // CHECKSTYLE:ON
}


text:
namespace Tempest{

class IndexBufferBase{
  public:
    virtual ~IndexBufferBase(){}
  };

template< class Index >
class IndexBuffer : public IndexBufferBase {
  public:
    typedef AbstractHolder< Tempest::IndexBufferBase,
                            AbstractAPI::IndexBuffer > Holder;

    IndexBuffer(): m_size(0), m_first(0),
                   data( Holder::ImplManip(0) ){}

    IndexBuffer( Holder &h, int s ): m_size(s), m_first(0),
                                     data( h.makeManip() ){
      }

    virtual ~IndexBuffer(){
      }

    int size() const {
      return m_size;
      }

    IndexBuffer<Index> slice( int first, int size ) const {
      T_ASSERT( first+size <= m_size );

      IndexBuffer<Index> tmp = *this;
      tmp.m_first += first;
      tmp.m_size   = size;

      return tmp;
      }

    IndexBuffer<Index> slice( int first ) const {
      return slice( first, size()-first );
      }

    template< class I >
    void get( I begin, I end, int b ) const {
      if( end-begin==0 )
        return;

      ((IndexBufferHolder&)data.manip.holder()).get( *this, begin, end, b );
      }

    size_t handle() const {
      return reinterpret_cast<size_t>( data.const_value() );
      }
  private:
    int      m_size, m_first;

    typedef Detail::Ptr<AbstractAPI::IndexBuffer*, Holder::ImplManip> Ptr;
    Ptr data;

  friend class Device;
  friend class IndexBufferHolder;
  };

}

#endif // INDEXBUFFER_H


text:
'use strict';

const fs = require("graceful-fs");
const cp = require("child_process");
const crypto = require("crypto");

const libxml = require("libxmljs");
const {Iconv} = require("iconv");

/* TODO PERF:
 * - Frontload reading in all XML files.
 * - Switch to using multiple threads for XML processing.
 */

module.exports = {
    md5File(file, callback) {
        const hash = crypto.createHash("md5");
        hash.setEncoding("hex");

        fs.createReadStream(file)
            .on("end", () => {
                hash.end();
                callback(hash.read());
            })
            .pipe(hash);
    },

    condCopyFile(from, to, callback) {
        fs.exists(to, exists => {
            if (exists) {
                return callback();
            }

            fs.createReadStream(from)
                .pipe(fs.createWriteStream(to))
                .on("close", callback);
        });
    },

    tidyHTML(html, outputFile, encoding, callback) {
        if (encoding) {
            html = (new Iconv(encoding, "UTF-8")).convert(html);
        }

        // Remove any script tags first (to fix any weird escaping)
        html = html.toString("utf8").replace(/<script[\s\S]*?<\/script>/ig, "");

        const tidy = cp.spawn(
            "tidy",
            [
                "-utf8",
                "-asxml",
                "--hide-comments",
                "yes",
                "--add-xml-decl",
                "yes",
                "--doctype",
                "transitional",
                "--quote-nbsp",
                "no",
                "--show-warnings",
                "0",
                "--force-output",
                "yes",
            ]
        );

        tidy.stdout
            .pipe(fs.createWriteStream(outputFile))
            .on("close", callback);

        tidy.stdin.write(html);
        tidy.stdin.end();
    },

    convertXML(htmlFile, xmlFile, encoding, callback) {
        fs.exists(xmlFile, exists => {
            if (exists) {
                return callback();
            }

            fs.readFile(htmlFile, (err, html) => {
                if (err) {
                    return callback(err);
                }

                this.tidyHTML(html, xmlFile, encoding, callback);
            });
        });
    },

    readXMLFile(xmlFile, callback) {
        fs.exists(xmlFile, exists => {
            if (!exists) {
                return callback({msg: `File does not exist: ${xmlFile}`});
            }

            fs.readFile(xmlFile, "utf8", (err, xmlData) => {
                // Strip out XMLNS to make XPath queries sane
                xmlData = xmlData.replace(/xmlns=\s*".*?"/g, "");

                // TODO: Catch any errors when parsing the XML
                callback(null, libxml.parseXml(xmlData));
            });
        });
    },
};


text:
from .textinput import TextInput
from ..libs import *

class MultilineTextInput(TextInput):
    control_style = ES_MULTILINE | ES_WANTRETURN | ES_AUTOVSCROLL


text:
<?php

namespace Markatom\Accessor;

/**
 * Accessor registry.
 *
 * @author Tomáš Markacz <tomas@markacz.com>
 */
class Registry
{

	/** @var Factory */
	private $factory;

	/** @var Accessor[] */
	private $accessors = [];

	/**
	 * @param Factory $factory
	 */
	public function __construct(Factory $factory)
	{
		$this->factory = $factory;
	}

	/**
	 * Gets accessor for instances of given class.
	 * @param $class
	 * @return Accessor
	 */
	public function getAccessor($class)
	{
		return isset($this->accessors[$class])
			? $this->accessors[$class]
			: $this->accessors[$class] = $this->factory->create($class);
	}

}