text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.trino.sql.planner;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import io.airlift.log.Logger;
import io.trino.Session;
import io.trino.server.DynamicFilterService;
import io.trino.spi.connector.Constraint;
import io.trino.spi.connector.DynamicFilter;
import io.trino.spi.predicate.TupleDomain;
import io.trino.split.SampledSplitSource;
import io.trino.split.SplitManager;
import io.trino.split.SplitSource;
import io.trino.sql.DynamicFilters;
import io.trino.sql.PlannerContext;
import io.trino.sql.planner.plan.AggregationNode;
import io.trino.sql.planner.plan.AssignUniqueId;
import io.trino.sql.planner.plan.DeleteNode;
import io.trino.sql.planner.plan.DistinctLimitNode;
import io.trino.sql.planner.plan.DynamicFilterSourceNode;
import io.trino.sql.planner.plan.EnforceSingleRowNode;
import io.trino.sql.planner.plan.ExchangeNode;
import io.trino.sql.planner.plan.ExplainAnalyzeNode;
import io.trino.sql.planner.plan.FilterNode;
import io.trino.sql.planner.plan.GroupIdNode;
import io.trino.sql.planner.plan.IndexJoinNode;
import io.trino.sql.planner.plan.JoinNode;
import io.trino.sql.planner.plan.LimitNode;
import io.trino.sql.planner.plan.MarkDistinctNode;
import io.trino.sql.planner.plan.MergeProcessorNode;
import io.trino.sql.planner.plan.MergeWriterNode;
import io.trino.sql.planner.plan.OutputNode;
import io.trino.sql.planner.plan.PatternRecognitionNode;
import io.trino.sql.planner.plan.PlanNode;
import io.trino.sql.planner.plan.PlanNodeId;
import io.trino.sql.planner.plan.PlanVisitor;
import io.trino.sql.planner.plan.ProjectNode;
import io.trino.sql.planner.plan.RefreshMaterializedViewNode;
import io.trino.sql.planner.plan.RemoteSourceNode;
import io.trino.sql.planner.plan.RowNumberNode;
import io.trino.sql.planner.plan.SampleNode;
import io.trino.sql.planner.plan.SemiJoinNode;
import io.trino.sql.planner.plan.SortNode;
import io.trino.sql.planner.plan.SpatialJoinNode;
import io.trino.sql.planner.plan.StatisticsWriterNode;
import io.trino.sql.planner.plan.TableDeleteNode;
import io.trino.sql.planner.plan.TableExecuteNode;
import io.trino.sql.planner.plan.TableFinishNode;
import io.trino.sql.planner.plan.TableScanNode;
import io.trino.sql.planner.plan.TableWriterNode;
import io.trino.sql.planner.plan.TopNNode;
import io.trino.sql.planner.plan.TopNRankingNode;
import io.trino.sql.planner.plan.UnionNode;
import io.trino.sql.planner.plan.UnnestNode;
import io.trino.sql.planner.plan.UpdateNode;
import io.trino.sql.planner.plan.ValuesNode;
import io.trino.sql.planner.plan.WindowNode;
import io.trino.sql.tree.Expression;

import javax.inject.Inject;

import java.util.List;
import java.util.Map;
import java.util.Optional;

import static com.google.common.collect.Iterables.getOnlyElement;
import static io.trino.spi.connector.Constraint.alwaysTrue;
import static io.trino.spi.connector.DynamicFilter.EMPTY;
import static io.trino.sql.ExpressionUtils.filterConjuncts;
import static java.util.Objects.requireNonNull;

public class SplitSourceFactory
{
    private static final Logger log = Logger.get(SplitSourceFactory.class);

    private final SplitManager splitManager;
    private final PlannerContext plannerContext;
    private final DynamicFilterService dynamicFilterService;
    private final TypeAnalyzer typeAnalyzer;

    @Inject
    public SplitSourceFactory(SplitManager splitManager, PlannerContext plannerContext, DynamicFilterService dynamicFilterService, TypeAnalyzer typeAnalyzer)
    {
        this.splitManager = requireNonNull(splitManager, "splitManager is null");
        this.plannerContext = requireNonNull(plannerContext, "metadata is null");
        this.dynamicFilterService = requireNonNull(dynamicFilterService, "dynamicFilterService is null");
        this.typeAnalyzer = requireNonNull(typeAnalyzer, "typeAnalyzer is null");
    }

    public Map<PlanNodeId, SplitSource> createSplitSources(Session session, PlanFragment fragment)
    {
        ImmutableList.Builder<SplitSource> allSplitSources = ImmutableList.builder();
        try {
            // get splits for this fragment, this is lazy so split assignments aren't actually calculated here
            return fragment.getRoot().accept(
                    new Visitor(session, TypeProvider.copyOf(fragment.getSymbols()), allSplitSources),
                    null);
        }
        catch (Throwable t) {
            allSplitSources.build().forEach(SplitSourceFactory::closeSplitSource);
            throw t;
        }
    }

    private static void closeSplitSource(SplitSource source)
    {
        try {
            source.close();
        }
        catch (Throwable t) {
            log.warn(t, "Error closing split source");
        }
    }

    private final class Visitor
            extends PlanVisitor<Map<PlanNodeId, SplitSource>, Void>
    {
        private final Session session;
        private final TypeProvider typeProvider;
        private final ImmutableList.Builder<SplitSource> splitSources;

        private Visitor(
                Session session,
                TypeProvider typeProvider,
                ImmutableList.Builder<SplitSource> allSplitSources)
        {
            this.session = session;
            this.typeProvider = typeProvider;
            this.splitSources = allSplitSources;
        }

        @Override
        public Map<PlanNodeId, SplitSource> visitExplainAnalyze(ExplainAnalyzeNode node, Void context)
        {
            return node.getSource().accept(this, context);
        }

        @Override
        public Map<PlanNodeId, SplitSource> visitTableScan(TableScanNode node, Void context)
        {
            return visitScanAndFilter(node, Optional.empty());
        }

        private Map<PlanNodeId, SplitSource> visitScanAndFilter(TableScanNode node, Optional<FilterNode> filter)
        {
            Optional<Expression> filterPredicate = filter
                    .map(FilterNode::getPredicate);

            List<DynamicFilters.Descriptor> dynamicFilters = filterPredicate
                    .map(DynamicFilters::extractDynamicFilters)
                    .map(DynamicFilters.ExtractResult::getDynamicConjuncts)
                    .orElse(ImmutableList.of());

            DynamicFilter dynamicFilter = EMPTY;
            if (!dynamicFilters.isEmpty()) {
                log.debug("Dynamic filters: %s", dynamicFilters);
                dynamicFilter = dynamicFilterService.createDynamicFilter(session.getQueryId(), dynamicFilters, node.getAssignments(), typeProvider);
            }

            Constraint constraint = filterPredicate
                    .map(predicate -> filterConjuncts(plannerContext.getMetadata(), predicate, expression -> !DynamicFilters.isDynamicFilter(expression)))
                    .map(predicate -> new LayoutConstraintEvaluator(plannerContext, typeAnalyzer, session, typeProvider, node.getAssignments(), predicate))
                    .map(evaluator -> new Constraint(TupleDomain.all(), evaluator::isCandidate, evaluator.getArguments())) // we are interested only in functional predicate here, so we set the summary to ALL.
                    .orElse(alwaysTrue());

            // get dataSource for table
            SplitSource splitSource = splitManager.getSplits(
                    session,
                    node.getTable(),
                    dynamicFilter,
                    constraint);

            splitSources.add(splitSource);

            return ImmutableMap.of(node.getId(), splitSource);
        }

        @Override
        public Map<PlanNodeId, SplitSource> visitJoin(JoinNode node, Void context)
        {
            Map<PlanNodeId, SplitSource> leftSplits = node.getLeft().accept(this, context);
            Map<PlanNodeId, SplitSource> rightSplits = node.getRight().accept(this, context);
            return ImmutableMap.<PlanNodeId, SplitSource>builder()
                    .putAll(leftSplits)
                    .putAll(rightSplits)
                    .buildOrThrow();
        }

        @Override
        public Map<PlanNodeId, SplitSource> visitSemiJoin(SemiJoinNode node, Void context)
        {
            Map<PlanNodeId, SplitSource> sourceSplits = node.getSource().accept(this, context);
            Map<PlanNodeId, SplitSource> filteringSourceSplits = node.getFilteringSource().accept(this, context);
            return ImmutableMap.<PlanNodeId, SplitSource>builder()
                    .putAll(sourceSplits)
                    .putAll(filteringSourceSplits)
                    .buildOrThrow();
        }

        @Override
        public Map<PlanNodeId, SplitSource> visitSpatialJoin(SpatialJoinNode node, Void context)
        {
            Map<PlanNodeId, SplitSource> leftSplits = node.getLeft().accept(this, context);
            Map<PlanNodeId, SplitSource> rightSplits = node.getRight().accept(this, context);
            return ImmutableMap.<PlanNodeId, SplitSource>builder()
                    .putAll(leftSplits)
                    .putAll(rightSplits)
                    .buildOrThrow();
        }

        @Override
        public Map<PlanNodeId, SplitSource> visitIndexJoin(IndexJoinNode node, Void context)
        {
            return node.getProbeSource().accept(this, context);
        }

        @Override
        public Map<PlanNodeId, SplitSource> visitDynamicFilterSource(DynamicFilterSourceNode node, Void context)
        {
            return node.getSource().accept(this, context);
        }

        @Override
        public Map<PlanNodeId, SplitSource> visitRemoteSource(RemoteSourceNode node, Void context)
        {
            // remote source node does not have splits
            return ImmutableMap.of();
        }

        @Override
        public Map<PlanNodeId, SplitSource> visitValues(ValuesNode node, Void context)
        {
            // values node does not have splits
            return ImmutableMap.of();
        }

        @Override
        public Map<PlanNodeId, SplitSource> visitFilter(FilterNode node, Void context)
        {
            if (node.getSource() instanceof TableScanNode) {
                TableScanNode scan = (TableScanNode) node.getSource();
                return visitScanAndFilter(scan, Optional.of(node));
            }

            return node.getSource().accept(this, context);
        }

        @Override
        public Map<PlanNodeId, SplitSource> visitSample(SampleNode node, Void context)
        {
            return switch (node.getSampleType()) {
                case BERNOULLI -> node.getSource().accept(this, context);
                case SYSTEM -> {
                    Map<PlanNodeId, SplitSource> nodeSplits = node.getSource().accept(this, context);
                    // TODO: when this happens we should switch to either BERNOULLI or page sampling
                    if (nodeSplits.size() == 1) {
                        PlanNodeId planNodeId = getOnlyElement(nodeSplits.keySet());
                        SplitSource sampledSplitSource = new SampledSplitSource(nodeSplits.get(planNodeId), node.getSampleRatio());
                        yield ImmutableMap.of(planNodeId, sampledSplitSource);
                    }
                    // table sampling on a sub query without splits is meaningless
                    yield nodeSplits;
                }
            };
        }

        @Override
        public Map<PlanNodeId, SplitSource> visitAggregation(AggregationNode node, Void context)
        {
            return node.getSource().accept(this, context);
        }

        @Override
        public Map<PlanNodeId, SplitSource> visitGroupId(GroupIdNode node, Void context)
        {
            return node.getSource().accept(this, context);
        }

        @Override
        public Map<PlanNodeId, SplitSource> visitMarkDistinct(MarkDistinctNode node, Void context)
        {
            return node.getSource().accept(this, context);
        }

        @Override
        public Map<PlanNodeId, SplitSource> visitWindow(WindowNode node, Void context)
        {
            return node.getSource().accept(this, context);
        }

        @Override
        public Map<PlanNodeId, SplitSource> visitPatternRecognition(PatternRecognitionNode node, Void context)
        {
            return node.getSource().accept(this, context);
        }

        @Override
        public Map<PlanNodeId, SplitSource> visitRowNumber(RowNumberNode node, Void context)
        {
            return node.getSource().accept(this, context);
        }

        @Override
        public Map<PlanNodeId, SplitSource> visitTopNRanking(TopNRankingNode node, Void context)
        {
            return node.getSource().accept(this, context);
        }

        @Override
        public Map<PlanNodeId, SplitSource> visitProject(ProjectNode node, Void context)
        {
            return node.getSource().accept(this, context);
        }

        @Override
        public Map<PlanNodeId, SplitSource> visitUnnest(UnnestNode node, Void context)
        {
            return node.getSource().accept(this, context);
        }

        @Override
        public Map<PlanNodeId, SplitSource> visitTopN(TopNNode node, Void context)
        {
            return node.getSource().accept(this, context);
        }

        @Override
        public Map<PlanNodeId, SplitSource> visitOutput(OutputNode node, Void context)
        {
            return node.getSource().accept(this, context);
        }

        @Override
        public Map<PlanNodeId, SplitSource> visitEnforceSingleRow(EnforceSingleRowNode node, Void context)
        {
            return node.getSource().accept(this, context);
        }

        @Override
        public Map<PlanNodeId, SplitSource> visitAssignUniqueId(AssignUniqueId node, Void context)
        {
            return node.getSource().accept(this, context);
        }

        @Override
        public Map<PlanNodeId, SplitSource> visitLimit(LimitNode node, Void context)
        {
            return node.getSource().accept(this, context);
        }

        @Override
        public Map<PlanNodeId, SplitSource> visitDistinctLimit(DistinctLimitNode node, Void context)
        {
            return node.getSource().accept(this, context);
        }

        @Override
        public Map<PlanNodeId, SplitSource> visitSort(SortNode node, Void context)
        {
            return node.getSource().accept(this, context);
        }

        @Override
        public Map<PlanNodeId, SplitSource> visitRefreshMaterializedView(RefreshMaterializedViewNode node, Void context)
        {
            // RefreshMaterializedViewNode does not have splits
            return ImmutableMap.of();
        }

        @Override
        public Map<PlanNodeId, SplitSource> visitTableWriter(TableWriterNode node, Void context)
        {
            return node.getSource().accept(this, context);
        }

        @Override
        public Map<PlanNodeId, SplitSource> visitTableFinish(TableFinishNode node, Void context)
        {
            return node.getSource().accept(this, context);
        }

        @Override
        public Map<PlanNodeId, SplitSource> visitStatisticsWriterNode(StatisticsWriterNode node, Void context)
        {
            return node.getSource().accept(this, context);
        }

        @Override
        public Map<PlanNodeId, SplitSource> visitDelete(DeleteNode node, Void context)
        {
            return node.getSource().accept(this, context);
        }

        @Override
        public Map<PlanNodeId, SplitSource> visitUpdate(UpdateNode node, Void context)
        {
            return node.getSource().accept(this, context);
        }

        @Override
        public Map<PlanNodeId, SplitSource> visitMergeWriter(MergeWriterNode node, Void context)
        {
            return node.getSource().accept(this, context);
        }

        @Override
        public Map<PlanNodeId, SplitSource> visitMergeProcessor(MergeProcessorNode node, Void context)
        {
            return node.getSource().accept(this, context);
        }

        @Override
        public Map<PlanNodeId, SplitSource> visitTableDelete(TableDeleteNode node, Void context)
        {
            // node does not have splits
            return ImmutableMap.of();
        }

        @Override
        public Map<PlanNodeId, SplitSource> visitTableExecute(TableExecuteNode node, Void context)
        {
            return node.getSource().accept(this, context);
        }

        @Override
        public Map<PlanNodeId, SplitSource> visitUnion(UnionNode node, Void context)
        {
            return processSources(node.getSources(), context);
        }

        @Override
        public Map<PlanNodeId, SplitSource> visitExchange(ExchangeNode node, Void context)
        {
            return processSources(node.getSources(), context);
        }

        private Map<PlanNodeId, SplitSource> processSources(List<PlanNode> sources, Void context)
        {
            ImmutableMap.Builder<PlanNodeId, SplitSource> result = ImmutableMap.builder();
            for (PlanNode child : sources) {
                result.putAll(child.accept(this, context));
            }

            return result.buildOrThrow();
        }

        @Override
        protected Map<PlanNodeId, SplitSource> visitPlan(PlanNode node, Void context)
        {
            throw new UnsupportedOperationException("not yet implemented: " + node.getClass().getName());
        }
    }
}


text:
      Posted on

      by

      Deleted User

redpajama_set_name: RedPajamaGithub


text:
namespace extensions {
namespace preference_helpers {

namespace {

const char kIncognitoPersistent[] = "incognito_persistent";
const char kIncognitoSessionOnly[] = "incognito_session_only";
const char kRegular[] = "regular";
const char kRegularOnly[] = "regular_only";

const char kLevelOfControlKey[] = "levelOfControl";

const char kNotControllable[] = "not_controllable";
const char kControlledByOtherExtensions[] = "controlled_by_other_extensions";
const char kControllableByThisExtension[] = "controllable_by_this_extension";
const char kControlledByThisExtension[] = "controlled_by_this_extension";

}  // namespace

bool StringToScope(const std::string& s,
                   extensions::ExtensionPrefsScope* scope) {
  if (s == kRegular)
    *scope = extensions::kExtensionPrefsScopeRegular;
  else if (s == kRegularOnly)
    *scope = extensions::kExtensionPrefsScopeRegularOnly;
  else if (s == kIncognitoPersistent)
    *scope = extensions::kExtensionPrefsScopeIncognitoPersistent;
  else if (s == kIncognitoSessionOnly)
    *scope = extensions::kExtensionPrefsScopeIncognitoSessionOnly;
  else
    return false;
  return true;
}

const char* GetLevelOfControl(
    Profile* profile,
    const std::string& extension_id,
    const std::string& browser_pref,
    bool incognito) {
  PrefService* prefs = incognito ? profile->GetOffTheRecordPrefs()
                                 : profile->GetPrefs();
  bool from_incognito = false;
  bool* from_incognito_ptr = incognito ? &from_incognito : NULL;
  const PrefService::Preference* pref =
      prefs->FindPreference(browser_pref.c_str());
  CHECK(pref);
  extensions::ExtensionPrefs* ep =
      profile->GetExtensionService()->extension_prefs();

  if (!pref->IsExtensionModifiable())
    return kNotControllable;

  if (ep->DoesExtensionControlPref(extension_id,
                                   browser_pref,
                                   from_incognito_ptr)) {
    return kControlledByThisExtension;
  }

  if (ep->CanExtensionControlPref(extension_id, browser_pref, incognito))
    return kControllableByThisExtension;

  return kControlledByOtherExtensions;
}

void DispatchEventToExtensions(
    Profile* profile,
    const std::string& event_name,
    ListValue* args,
    extensions::APIPermission::ID permission,
    bool incognito,
    const std::string& browser_pref) {
  extensions::EventRouter* router =
      extensions::ExtensionSystem::Get(profile)->event_router();
  if (!router || !router->HasEventListener(event_name))
    return;
  ExtensionService* extension_service = profile->GetExtensionService();
  const ExtensionSet* extensions = extension_service->extensions();
  extensions::ExtensionPrefs* extension_prefs =
      extension_service->extension_prefs();
  for (ExtensionSet::const_iterator it = extensions->begin();
       it != extensions->end(); ++it) {
    std::string extension_id = (*it)->id();
    // TODO(bauerb): Only iterate over registered event listeners.
    if (router->ExtensionHasEventListener(extension_id, event_name) &&
        (*it)->HasAPIPermission(permission) &&
        (!incognito || (*it)->incognito_split_mode() ||
         extension_service->CanCrossIncognito(*it))) {
      // Inject level of control key-value.
      DictionaryValue* dict;
      bool rv = args->GetDictionary(0, &dict);
      DCHECK(rv);
      std::string level_of_control =
          GetLevelOfControl(profile, extension_id, browser_pref, incognito);
      dict->SetString(kLevelOfControlKey, level_of_control);

      // If the extension is in incognito split mode,
      // a) incognito pref changes are visible only to the incognito tabs
      // b) regular pref changes are visible only to the incognito tabs if the
      //    incognito pref has not alredy been set
      Profile* restrict_to_profile = NULL;
      bool from_incognito = false;
      if ((*it)->incognito_split_mode()) {
        if (incognito && extension_service->IsIncognitoEnabled(extension_id)) {
          restrict_to_profile = profile->GetOffTheRecordProfile();
        } else if (!incognito &&
                   extension_prefs->DoesExtensionControlPref(
                       extension_id,
                       browser_pref,
                       &from_incognito) &&
                   from_incognito) {
          restrict_to_profile = profile;
        }
      }

      scoped_ptr<ListValue> args_copy(args->DeepCopy());
      scoped_ptr<Event> event(new Event(event_name, args_copy.Pass()));
      event->restrict_to_profile = restrict_to_profile;
      router->DispatchEventToExtension(extension_id, event.Pass());
    }
  }
}

}  // namespace preference_helpers
}  // namespace extensions


text:
// Code generated by lister-gen. DO NOT EDIT.

package v1

// ComponentStatusListerExpansion allows custom methods to be added to
// ComponentStatusLister.
type ComponentStatusListerExpansion interface{}

// ConfigMapListerExpansion allows custom methods to be added to
// ConfigMapLister.
type ConfigMapListerExpansion interface{}

// ConfigMapNamespaceListerExpansion allows custom methods to be added to
// ConfigMapNamespaceLister.
type ConfigMapNamespaceListerExpansion interface{}

// EndpointsListerExpansion allows custom methods to be added to
// EndpointsLister.
type EndpointsListerExpansion interface{}

// EndpointsNamespaceListerExpansion allows custom methods to be added to
// EndpointsNamespaceLister.
type EndpointsNamespaceListerExpansion interface{}

// EventListerExpansion allows custom methods to be added to
// EventLister.
type EventListerExpansion interface{}

// EventNamespaceListerExpansion allows custom methods to be added to
// EventNamespaceLister.
type EventNamespaceListerExpansion interface{}

// LimitRangeListerExpansion allows custom methods to be added to
// LimitRangeLister.
type LimitRangeListerExpansion interface{}

// LimitRangeNamespaceListerExpansion allows custom methods to be added to
// LimitRangeNamespaceLister.
type LimitRangeNamespaceListerExpansion interface{}

// NamespaceListerExpansion allows custom methods to be added to
// NamespaceLister.
type NamespaceListerExpansion interface{}

// NodeListerExpansion allows custom methods to be added to
// NodeLister.
type NodeListerExpansion interface{}

// PersistentVolumeListerExpansion allows custom methods to be added to
// PersistentVolumeLister.
type PersistentVolumeListerExpansion interface{}

// PersistentVolumeClaimListerExpansion allows custom methods to be added to
// PersistentVolumeClaimLister.
type PersistentVolumeClaimListerExpansion interface{}

// PersistentVolumeClaimNamespaceListerExpansion allows custom methods to be added to
// PersistentVolumeClaimNamespaceLister.
type PersistentVolumeClaimNamespaceListerExpansion interface{}

// PodListerExpansion allows custom methods to be added to
// PodLister.
type PodListerExpansion interface{}

// PodNamespaceListerExpansion allows custom methods to be added to
// PodNamespaceLister.
type PodNamespaceListerExpansion interface{}

// PodTemplateListerExpansion allows custom methods to be added to
// PodTemplateLister.
type PodTemplateListerExpansion interface{}

// PodTemplateNamespaceListerExpansion allows custom methods to be added to
// PodTemplateNamespaceLister.
type PodTemplateNamespaceListerExpansion interface{}

// ResourceQuotaListerExpansion allows custom methods to be added to
// ResourceQuotaLister.
type ResourceQuotaListerExpansion interface{}

// ResourceQuotaNamespaceListerExpansion allows custom methods to be added to
// ResourceQuotaNamespaceLister.
type ResourceQuotaNamespaceListerExpansion interface{}

// SecretListerExpansion allows custom methods to be added to
// SecretLister.
type SecretListerExpansion interface{}

// SecretNamespaceListerExpansion allows custom methods to be added to
// SecretNamespaceLister.
type SecretNamespaceListerExpansion interface{}

// ServiceListerExpansion allows custom methods to be added to
// ServiceLister.
type ServiceListerExpansion interface{}

// ServiceNamespaceListerExpansion allows custom methods to be added to
// ServiceNamespaceLister.
type ServiceNamespaceListerExpansion interface{}

// ServiceAccountListerExpansion allows custom methods to be added to
// ServiceAccountLister.
type ServiceAccountListerExpansion interface{}

// ServiceAccountNamespaceListerExpansion allows custom methods to be added to
// ServiceAccountNamespaceLister.
type ServiceAccountNamespaceListerExpansion interface{}


text:
(function() {
  'use strict';

  /**
   * requestAnimationFrame polyfill by Erik Möller
   * fixes from Paul Irish and Tino Zijdel
   *
   * http://paulirish.com/2011/requestanimationframe-for-smart-animating/
   * http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
   */
  var lastTime = 0;
  var vendors = ['ms', 'moz', 'webkit', 'o'];
  for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
    window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
    window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] ||
                            window[vendors[x] + 'CancelRequestAnimationFrame'];
  }

  if (!window.requestAnimationFrame) {
    window.requestAnimationFrame = function(callback, element) {
      var currTime = new Date().getTime();
      var timeToCall = Math.max(0, 16 - (currTime - lastTime));
      var id = window.setTimeout(function() {
        callback(currTime + timeToCall);
      }, timeToCall);
      lastTime = currTime + timeToCall;
      return id;
    };
  }

  if (!window.cancelAnimationFrame) {
    window.cancelAnimationFrame = function(id) {
      clearTimeout(id);
    };
  }

  // textContent for IE8
  if (Object.defineProperty &&
    Object.getOwnPropertyDescriptor &&
    Object.getOwnPropertyDescriptor(Element.prototype, 'textContent') &&
    !Object.getOwnPropertyDescriptor(Element.prototype, 'textContent').get) {
    (function() {
      var innerText = Object
        .getOwnPropertyDescriptor(Element.prototype, 'innerText');

      Object.defineProperty(Element.prototype, 'textContent', {
        get: function() {
          return innerText.get.call(this);
        },
        set: function(s) {
          return innerText.set.call(this, s);
        }
      });
    })();
  }
})();


text:
package industry_brain

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)

// AsyncResponsePost invokes the industry_brain.AsyncResponsePost API synchronously
func (client *Client) AsyncResponsePost(request *AsyncResponsePostRequest) (response *AsyncResponsePostResponse, err error) {
	response = CreateAsyncResponsePostResponse()
	err = client.DoAction(request, response)
	return
}

// AsyncResponsePostWithChan invokes the industry_brain.AsyncResponsePost API asynchronously
func (client *Client) AsyncResponsePostWithChan(request *AsyncResponsePostRequest) (<-chan *AsyncResponsePostResponse, <-chan error) {
	responseChan := make(chan *AsyncResponsePostResponse, 1)
	errChan := make(chan error, 1)
	err := client.AddAsyncTask(func() {
		defer close(responseChan)
		defer close(errChan)
		response, err := client.AsyncResponsePost(request)
		if err != nil {
			errChan <- err
		} else {
			responseChan <- response
		}
	})
	if err != nil {
		errChan <- err
		close(responseChan)
		close(errChan)
	}
	return responseChan, errChan
}

// AsyncResponsePostWithCallback invokes the industry_brain.AsyncResponsePost API asynchronously
func (client *Client) AsyncResponsePostWithCallback(request *AsyncResponsePostRequest, callback func(response *AsyncResponsePostResponse, err error)) <-chan int {
	result := make(chan int, 1)
	err := client.AddAsyncTask(func() {
		var response *AsyncResponsePostResponse
		var err error
		defer close(result)
		response, err = client.AsyncResponsePost(request)
		callback(response, err)
		result <- 1
	})
	if err != nil {
		defer close(result)
		callback(nil, err)
		result <- 0
	}
	return result
}

// AsyncResponsePostRequest is the request struct for api AsyncResponsePost
type AsyncResponsePostRequest struct {
	*requests.RpcRequest
	Data     string         `position:"Query" name:"Data"`
	Context  string         `position:"Query" name:"Context"`
	Progress requests.Float `position:"Query" name:"Progress"`
	Message  string         `position:"Query" name:"Message"`
	TaskId   string         `position:"Query" name:"TaskId"`
	Status   string         `position:"Query" name:"Status"`
}

// AsyncResponsePostResponse is the response struct for api AsyncResponsePost
type AsyncResponsePostResponse struct {
	*responses.BaseResponse
	RequestId string `json:"RequestId" xml:"RequestId"`
	Data      string `json:"Data" xml:"Data"`
	Status    string `json:"Status" xml:"Status"`
	Code      string `json:"Code" xml:"Code"`
	Message   string `json:"Message" xml:"Message"`
}

// CreateAsyncResponsePostRequest creates a request to invoke AsyncResponsePost API
func CreateAsyncResponsePostRequest() (request *AsyncResponsePostRequest) {
	request = &AsyncResponsePostRequest{
		RpcRequest: &requests.RpcRequest{},
	}
	request.InitWithApiInfo("industry-brain", "2019-06-29", "AsyncResponsePost", "", "")
	request.Method = requests.POST
	return
}

// CreateAsyncResponsePostResponse creates a response to parse from AsyncResponsePost response
func CreateAsyncResponsePostResponse() (response *AsyncResponsePostResponse) {
	response = &AsyncResponsePostResponse{
		BaseResponse: &responses.BaseResponse{},
	}
	return
}


text:
from requestbuilder import Arg, MutuallyExclusiveArgList

from euca2ools.commands.cloudformation import CloudFormationRequest

class ValidateTemplate(CloudFormationRequest):
    DESCRIPTION = 'Validate a template'
    ARGS = [MutuallyExclusiveArgList(
                Arg('--template-file', dest='TemplateBody',
                    metavar='FILE', type=open,
                    help='file location containing JSON template'),
                Arg('--template-url', dest='TemplateURL',
                    metavar='URL', help='S3 URL for JSON template'))
            .required()]
    LIST_TAGS = ['Parameters', 'Capabilities']

    def print_result(self, result):
        print self.tabify(('DESCRIPTION', result.get('Description')))
        for cap in result.get('Capabilities') or []:
            print self.tabify(('CAPABILITY', cap))
        if result.get('CapabilitiesReason'):
            print self.tabify(('CAPABILITIESREASON',
                               result['CapabilitiesReason']))
        for param in result.get('Parameters') or []:
            print self.tabify(('PARAMETER', param.get('ParameterKey'),
                               param.get('NoEcho'), param.get('DefaultValue'),
                               param.get('Description')))


text:
package com.treasure_data.td_import.integration;

import java.io.IOException;

import org.junit.Ignore;

@Ignore
public class HeaderlessTSVFileGenerator extends TSVFileGenerator {

    public HeaderlessTSVFileGenerator(String fileName, String[] header)
            throws IOException {
        super(fileName, header);
    }

    @Override
    public void writeHeader() throws IOException {
        // header-less
    }
}


text:
  Template.registerHelper('Config', function() {
    return Config;
  });

  Template.registerHelper('NCSchemas', function() {
    return NCSchemas;
  });

  Template.registerHelper('socialMedia', function() {
    return _.map(Config.socialMedia, function(obj) {
      return obj;
    });
  });

  Template.registerHelper('Utils', function() {
    return Utils;
  });

  Template.registerHelper('currentRoute', function() {
    if (Router && Router.current && Router.current()) {
      return Router.current();
    }
  });

  Template.registerHelper('isRouteReady', function() {
    return Router && Router.current && Router.current() && Router.current()._waitlist._notReadyCount === 0;
  });


text:
package at.rovo.drum.event;

import at.rovo.drum.DrumListener;
import at.rovo.drum.Merger;

/**
 * Informs {@link DrumListener listeners} that the {@link Merger} has changed its internal state. The new state of the
 * {@link Merger} can be retrieved via {@link #getBucketId()}.
 *
 * @author Roman Vottner
 */
public class MergerStateUpdate extends DrumEvent<MergerStateUpdate> {

    /**
     * The bucket ID the event was triggered from
     */
    private Integer bucketId = null;
    /**
     * The new state of the merger
     */
    private MergerState state;

    /**
     * Initializes a new {@link Merger} state change event.
     *
     * @param drumName The name of the DRUM instance this event was issued from
     * @param state    The new state the merger is in
     */
    public MergerStateUpdate(String drumName, MergerState state) {
        super(drumName, MergerStateUpdate.class);
        this.state = state;
    }

    /**
     * Initializes a new {@link Merger} state change event.
     *
     * @param drumName The name of the DRUM instance this event was issued from
     * @param state    The new state the merger is in
     * @param bucketId The identifier of the bucket the event was triggered from
     */
    public MergerStateUpdate(String drumName, MergerState state, int bucketId) {
        super(drumName, MergerStateUpdate.class);
        this.state = state;
        this.bucketId = bucketId;
    }

    /**
     * The current state the {@link Merger} is in.
     *
     * @return The new state of the merger
     */
    public MergerState getState() {
        return this.state;
    }

    /**
     * The identifier of the bucket the event was issued from.
     *
     * @return The bucket identifier the event was sent from
     */
    public Integer getBucketId() {
        return this.bucketId;
    }

    @Override
    public String toString() {
        return this.drumName + " - " + this.currentThread.getName() + " - Merger state changed to: " + this.state;
    }
}


text:
#ifndef ScrollingCoordinator_h
#define ScrollingCoordinator_h

#include "EventTrackingRegions.h"
#include "IntRect.h"
#include "LayoutRect.h"
#include "PlatformWheelEvent.h"
#include "ScrollTypes.h"
#include <wtf/Forward.h>
#include <wtf/ThreadSafeRefCounted.h>
#include <wtf/TypeCasts.h>

#if ENABLE(ASYNC_SCROLLING)
#include <wtf/HashMap.h>
#include <wtf/ThreadSafeRefCounted.h>
#include <wtf/Threading.h>
#endif

#if PLATFORM(COCOA)
#include <wtf/RetainPtr.h>
#endif

#if ENABLE(CSS_SCROLL_SNAP)
#include "AxisScrollSnapOffsets.h"
#endif

namespace WebCore {

typedef unsigned SynchronousScrollingReasons;
typedef uint64_t ScrollingNodeID;

enum ScrollingNodeType { FrameScrollingNode, OverflowScrollingNode, FixedNode, StickyNode };

class Document;
class Frame;
class FrameView;
class GraphicsLayer;
class Page;
class Region;
class ScrollableArea;
class TextStream;
class ViewportConstraints;

#if ENABLE(ASYNC_SCROLLING)
class ScrollingTree;
#endif

enum SetOrSyncScrollingLayerPosition {
    SetScrollingLayerPosition,
    SyncScrollingLayerPosition
};

struct ScrollableAreaParameters {
    ScrollElasticity horizontalScrollElasticity;
    ScrollElasticity verticalScrollElasticity;

    ScrollbarMode horizontalScrollbarMode;
    ScrollbarMode verticalScrollbarMode;

    bool hasEnabledHorizontalScrollbar;
    bool hasEnabledVerticalScrollbar;

    ScrollableAreaParameters()
        : horizontalScrollElasticity(ScrollElasticityNone)
        , verticalScrollElasticity(ScrollElasticityNone)
        , horizontalScrollbarMode(ScrollbarAuto)
        , verticalScrollbarMode(ScrollbarAuto)
        , hasEnabledHorizontalScrollbar(false)
        , hasEnabledVerticalScrollbar(false)
    {
    }

    bool operator==(const ScrollableAreaParameters& other) const
    {
        return horizontalScrollElasticity == other.horizontalScrollElasticity
            && verticalScrollElasticity == other.verticalScrollElasticity
            && horizontalScrollbarMode == other.horizontalScrollbarMode
            && verticalScrollbarMode == other.verticalScrollbarMode
            && hasEnabledHorizontalScrollbar == other.hasEnabledHorizontalScrollbar
            && hasEnabledVerticalScrollbar == other.hasEnabledVerticalScrollbar;
    }
};

class ScrollingCoordinator : public ThreadSafeRefCounted<ScrollingCoordinator> {
public:
    static Ref<ScrollingCoordinator> create(Page*);
    virtual ~ScrollingCoordinator();

    WEBCORE_EXPORT virtual void pageDestroyed();

    virtual bool isAsyncScrollingCoordinator() const { return false; }
    virtual bool isRemoteScrollingCoordinator() const { return false; }

    // Return whether this scrolling coordinator handles scrolling for the given frame view.
    virtual bool coordinatesScrollingForFrameView(const FrameView&) const;

    // Should be called whenever the given frame view has been laid out.
    virtual void frameViewLayoutUpdated(FrameView&) { }

    // Should be called whenever the slow repaint objects counter changes between zero and one.
    void frameViewHasSlowRepaintObjectsDidChange(FrameView&);

    // Should be called whenever the set of fixed objects changes.
    void frameViewFixedObjectsDidChange(FrameView&);

    // Called whenever the non-fast scrollable region changes for reasons other than layout.
    virtual void frameViewEventTrackingRegionsChanged(FrameView&) { }

    // Should be called whenever the root layer for the given frame view changes.
    virtual void frameViewRootLayerDidChange(FrameView&);

    // Return whether this scrolling coordinator can keep fixed position layers fixed to their
    // containers while scrolling.
    virtual bool supportsFixedPositionLayers() const { return false; }

#if PLATFORM(COCOA)
    // Dispatched by the scrolling tree during handleWheelEvent. This is required as long as scrollbars are painted on the main thread.
    void handleWheelEventPhase(PlatformWheelEventPhase);
#endif

#if ENABLE(WEB_REPLAY)
    // Called when the page transitions between executing normally and deterministically.
    void replaySessionStateDidChange();
#endif

    // Force all scroll layer position updates to happen on the main thread.
    WEBCORE_EXPORT void setForceSynchronousScrollLayerPositionUpdates(bool);

    // These virtual functions are currently unique to the threaded scrolling architecture.
    // Their meaningful implementations are in ScrollingCoordinatorMac.
    virtual void commitTreeStateIfNeeded() { }
    virtual bool requestScrollPositionUpdate(FrameView&, const IntPoint&) { return false; }
    virtual bool handleWheelEvent(FrameView&, const PlatformWheelEvent&) { return true; }
    virtual ScrollingNodeID attachToStateTree(ScrollingNodeType, ScrollingNodeID newNodeID, ScrollingNodeID /*parentID*/) { return newNodeID; }
    virtual void detachFromStateTree(ScrollingNodeID) { }
    virtual void clearStateTree() { }
    virtual void updateViewportConstrainedNode(ScrollingNodeID, const ViewportConstraints&, GraphicsLayer*) { }

    struct ScrollingGeometry {
        FloatSize scrollableAreaSize;
        FloatSize contentSize;
        FloatSize reachableContentSize; // Smaller than contentSize when overflow is hidden on one axis.
        FloatPoint scrollPosition;
        IntPoint scrollOrigin;
#if ENABLE(CSS_SCROLL_SNAP)
        Vector<LayoutUnit> horizontalSnapOffsets;
        Vector<LayoutUnit> verticalSnapOffsets;
        unsigned currentHorizontalSnapPointIndex;
        unsigned currentVerticalSnapPointIndex;
#endif
    };

    virtual void updateFrameScrollingNode(ScrollingNodeID, GraphicsLayer* /*scrollLayer*/, GraphicsLayer* /*scrolledContentsLayer*/, GraphicsLayer* /*counterScrollingLayer*/, GraphicsLayer* /*insetClipLayer*/, const ScrollingGeometry* = nullptr) { }
    virtual void updateOverflowScrollingNode(ScrollingNodeID, GraphicsLayer* /*scrollLayer*/, GraphicsLayer* /*scrolledContentsLayer*/, const ScrollingGeometry* = nullptr) { }
    virtual void syncChildPositions(const LayoutRect&) { }
    virtual String scrollingStateTreeAsText() const;
    virtual bool isRubberBandInProgress() const { return false; }
    virtual bool isScrollSnapInProgress() const { return false; }
    virtual void updateScrollSnapPropertiesWithFrameView(const FrameView&) { }
    virtual void setScrollPinningBehavior(ScrollPinningBehavior) { }

    // Generated a unique id for scroll layers.
    ScrollingNodeID uniqueScrollLayerID();

    enum MainThreadScrollingReasonFlags {
        ForcedOnMainThread                                          = 1 << 0,
        HasSlowRepaintObjects                                       = 1 << 1,
        HasViewportConstrainedObjectsWithoutSupportingFixedLayers   = 1 << 2,
        HasNonLayerViewportConstrainedObjects                       = 1 << 3,
        IsImageDocument                                             = 1 << 4
    };

    SynchronousScrollingReasons synchronousScrollingReasons(const FrameView&) const;
    bool shouldUpdateScrollLayerPositionSynchronously(const FrameView&) const;

    virtual void willDestroyScrollableArea(ScrollableArea&) { }
    virtual void scrollableAreaScrollLayerDidChange(ScrollableArea&) { }
    virtual void scrollableAreaScrollbarLayerDidChange(ScrollableArea&, ScrollbarOrientation) { }

    static String synchronousScrollingReasonsAsText(SynchronousScrollingReasons);
    String synchronousScrollingReasonsAsText() const;

    EventTrackingRegions absoluteEventTrackingRegions() const;

protected:
    explicit ScrollingCoordinator(Page*);

    static GraphicsLayer* scrollLayerForScrollableArea(ScrollableArea&);

    GraphicsLayer* scrollLayerForFrameView(FrameView&);
    GraphicsLayer* counterScrollingLayerForFrameView(FrameView&);
    GraphicsLayer* insetClipLayerForFrameView(FrameView&);
    GraphicsLayer* rootContentLayerForFrameView(FrameView&);
    GraphicsLayer* contentShadowLayerForFrameView(FrameView&);
    GraphicsLayer* headerLayerForFrameView(FrameView&);
    GraphicsLayer* footerLayerForFrameView(FrameView&);

    virtual void willCommitTree() { }

    Page* m_page; // FIXME: ideally this would be a reference but it gets nulled on async teardown.

private:
    virtual void setSynchronousScrollingReasons(SynchronousScrollingReasons) { }

    virtual bool hasVisibleSlowRepaintViewportConstrainedObjects(const FrameView&) const;
    void updateSynchronousScrollingReasons(const FrameView&);

    EventTrackingRegions absoluteEventTrackingRegionsForFrame(const Frame&) const;

    bool m_forceSynchronousScrollLayerPositionUpdates { false };
};

WEBCORE_EXPORT TextStream& operator<<(TextStream&, ScrollingNodeType);

} // namespace WebCore

#define SPECIALIZE_TYPE_TRAITS_SCROLLING_COORDINATOR(ToValueTypeName, predicate) \
SPECIALIZE_TYPE_TRAITS_BEGIN(ToValueTypeName) \
    static bool isType(const WebCore::ScrollingCoordinator& value) { return value.predicate; } \
SPECIALIZE_TYPE_TRAITS_END()

#endif // ScrollingCoordinator_h


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!--
 *  Copyright (c) 2005, The University of Sheffield.
 *
 *  This file is part of the GATE/UIMA integration layer, and is free
 *  software, released under the terms of the GNU Lesser General Public
 *  Licence, version 2.1 (or any later version).  A copy of this licence
 *  is provided in the file LICENCE in the distribution.
 *
 *  UIMA is a product of IBM, details are available from
 *  http://alphaworks.ibm.com/tech/uima
-->

<!-- Descriptor for the example annotator that removes tokens whose length is
an even number. -->

<taeDescription xmlns="http://uima.apache.org/resourceSpecifier">
<frameworkImplementation>org.apache.uima.java</frameworkImplementation>
<primitive>true</primitive>
<annotatorImplementationName>gate.uima.examples.RemoveEvenLengthTokens</annotatorImplementationName>

<analysisEngineMetaData>
  <name>Remove even length tokens</name>
  <description>
    An annotator that removes all Tokens from the annotation index that span an
    even number of characters.
  </description>
  <version>1.0</version>
  <vendor>GATE</vendor>

<!-- TypeSystem Definition -->
  <typeSystemDescription>
    <types>
      <typeDescription>
        <name>gate.uima.cas.Token</name>
        <description>A token in text</description>
        <supertypeName>uima.tcas.Annotation</supertypeName>
      </typeDescription>
    </types>
  </typeSystemDescription>

<!-- Capabilities: Inputs, Outputs, and Preconditions -->
  <capabilities>
    <capability>
      <inputs>
        <type>gate.uima.cas.Token</type>
      </inputs>
      <outputs>
        <feature>gate.uima.cas.Token</feature>
      </outputs>
      <languagesSupported>
        <language>en</language>
      </languagesSupported>
    </capability>
  </capabilities>

</analysisEngineMetaData>
</taeDescription>


text:
// <copyright company="eXtensoft, LLC" file="DebugEventWriter.cs">
// Copyright © 2016 All Right Reserved
// </copyright>

namespace XF.Common
{
    using System;
using System.Collections.Generic;
using System.Diagnostics;

public class DebugEventWriter : EventWriterBase
{

    protected override void Publish(EventTypeOption eventType, List<TypedItem> properties)
    {
        Debug.WriteLine(String.Format("An {0} occurred", eventType.ToString()));
        foreach (var property in properties)
        {
            Debug.WriteLine(String.Format("{0}:\t{1}", property.Key, property.Value.ToString()));
        }
    }

    protected override void Publish(eXMetric metric)
    {
        Debug.WriteLine(metric.ToString());
    }
}
}


text:
using Windows.UI.Xaml.Navigation;

namespace QMunicate.Core.Navigation
{
    public interface INavigationAware
    {
        void OnNavigatedTo(NavigationEventArgs e);

        void OnNavigatedFrom(NavigationEventArgs e);
    }
}


text:
package android.support.v4.preference;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.Preference;
import android.preference.PreferenceGroup;
import android.preference.PreferenceManager;
import android.preference.PreferenceScreen;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.widget.ListView;

import com.alexstyl.specialdates.R;

@SuppressWarnings("all")
public abstract class PreferenceFragment extends Fragment implements
		PreferenceManagerCompat.OnPreferenceTreeClickListener {

	private static final String PREFERENCES_TAG = "android:preferences";

    private PreferenceManager mPreferenceManager;
    private ListView mList;
    private boolean mHavePrefs;
    private boolean mInitDone;

    /**
     * The starting request code given out to preference framework.
     */
    private static final int FIRST_REQUEST_CODE = 100;

    private static final int MSG_BIND_PREFERENCES = 1;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {

                case MSG_BIND_PREFERENCES:
                    bindPreferences();
                    break;
            }
        }
    };

    final private Runnable mRequestFocus = new Runnable() {
        public void run() {
            mList.focusableViewAvailable(mList);
        }
    };

    /**
     * Interface that PreferenceFragment's containing activity should
     * implement to be able to process preference items that wish to
     * switch to a new fragment.
     */
    public interface OnPreferenceStartFragmentCallback {
        /**
         * Called when the user has clicked on a Preference that has
         * a fragment class name associated with it.  The implementation
         * to should instantiate and switch to an instance of the given
         * fragment.
         */
        boolean onPreferenceStartFragment(PreferenceFragment caller, Preference pref);
    }

    @Override
	public void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		mPreferenceManager = PreferenceManagerCompat.newInstance(getActivity(), FIRST_REQUEST_CODE);
		PreferenceManagerCompat.setFragment(mPreferenceManager, this);
	}

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

    }

    @Override
	public View onCreateView(LayoutInflater paramLayoutInflater, ViewGroup paramViewGroup,
			Bundle paramBundle) {
		return paramLayoutInflater.inflate(
                R.layout.preference_list_fragment, paramViewGroup,
				false);
	}

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        if (mHavePrefs) {
            bindPreferences();
        }

        mInitDone = true;

        if (savedInstanceState != null) {
            Bundle container = savedInstanceState.getBundle(PREFERENCES_TAG);
            if (container != null) {
                final PreferenceScreen preferenceScreen = getPreferenceScreen();
                if (preferenceScreen != null) {
                    preferenceScreen.restoreHierarchyState(container);
                }
            }
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        PreferenceManagerCompat.setOnPreferenceTreeClickListener(mPreferenceManager, this);
    }

    @Override
	public void onStop() {
		super.onStop();
		PreferenceManagerCompat.dispatchActivityStop(mPreferenceManager);
		PreferenceManagerCompat.setOnPreferenceTreeClickListener(mPreferenceManager, null);
	}

    @Override
	public void onDestroyView() {
		mList = null;
		mHandler.removeCallbacks(mRequestFocus);
		mHandler.removeMessages(MSG_BIND_PREFERENCES);
		super.onDestroyView();
	}

    @Override
	public void onDestroy() {
		super.onDestroy();
		PreferenceManagerCompat.dispatchActivityDestroy(mPreferenceManager);
	}

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        final PreferenceScreen preferenceScreen = getPreferenceScreen();
        if (preferenceScreen != null) {
            Bundle container = new Bundle();
            preferenceScreen.saveHierarchyState(container);
            outState.putBundle(PREFERENCES_TAG, container);
        }
    }

    @Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

        PreferenceManagerCompat.dispatchActivityResult(mPreferenceManager, requestCode, resultCode, data);
	}

    /**
     * Returns the {@link PreferenceManager} used by this fragment.
     * @return The {@link PreferenceManager}.
     */
    public PreferenceManager getPreferenceManager() {
        return mPreferenceManager;
    }

    /**
     * Sets the root of the preference hierarchy that this fragment is showing.
     *
     * @param preferenceScreen The root {@link PreferenceScreen} of the preference hierarchy.
     */
    public void setPreferenceScreen(PreferenceScreen preferenceScreen) {
        if (PreferenceManagerCompat.setPreferences(mPreferenceManager, preferenceScreen) && preferenceScreen != null) {
            mHavePrefs = true;
            if (mInitDone) {
                postBindPreferences();
            }
        }
    }

    /**
     * Gets the root of the preference hierarchy that this fragment is showing.
     *
     * @return The {@link PreferenceScreen} that is the root of the preference
     *         hierarchy.
     */
    public PreferenceScreen getPreferenceScreen() {
        return PreferenceManagerCompat.getPreferenceScreen(mPreferenceManager);
    }

    /**
     * Adds preferences from activities that match the given {@link Intent}.
     *
     * @param intent The {@link Intent} to query activities.
     */
    public void addPreferencesFromIntent(Intent intent) {
        requirePreferenceManager();

        setPreferenceScreen(PreferenceManagerCompat.inflateFromIntent(mPreferenceManager, intent, getPreferenceScreen()));
    }

    /**
     * Inflates the given XML resource and adds the preference hierarchy to the current
     * preference hierarchy.
     *
     * @param preferencesResId The XML resource ID to inflate.
     */
    public void addPreferencesFromResource(int preferencesResId) {
        requirePreferenceManager();

        setPreferenceScreen(PreferenceManagerCompat.inflateFromResource(mPreferenceManager, getActivity(),
        		preferencesResId, getPreferenceScreen()));
    }

    /**
     * {@inheritDoc}
     */
    public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen,
            Preference preference) {
        //if (preference.getFragment() != null &&
    	if (
                getActivity() instanceof OnPreferenceStartFragmentCallback) {
            return ((OnPreferenceStartFragmentCallback)getActivity()).onPreferenceStartFragment(
                    this, preference);
        }
        return false;
    }

    /**
     * Finds a {@link Preference} based on its key.
     *
     * @param key The key of the preference to retrieve.
     * @return The {@link Preference} with the key, or null.
     * @see PreferenceGroup#findPreference(CharSequence)
     */
    public Preference findPreference(CharSequence key) {
        if (mPreferenceManager == null) {
            return null;
        }
        return mPreferenceManager.findPreference(key);
    }

    private void requirePreferenceManager() {
        if (mPreferenceManager == null) {
            throw new RuntimeException("This should be called after super.onCreate.");
        }
    }

    private void postBindPreferences() {
        if (mHandler.hasMessages(MSG_BIND_PREFERENCES)) return;
        mHandler.obtainMessage(MSG_BIND_PREFERENCES).sendToTarget();
    }

    private void bindPreferences() {
        final PreferenceScreen preferenceScreen = getPreferenceScreen();
        if (preferenceScreen != null) {
            preferenceScreen.bind(getListView());
        }
    }

    public ListView getListView() {
        ensureList();
        return mList;
    }

    private void ensureList() {
        if (mList != null) {
            return;
        }
        View root = getView();
        if (root == null) {
            throw new IllegalStateException("Content view not yet created");
        }
        View rawListView = root.findViewById(android.R.id.list);
        if (!(rawListView instanceof ListView)) {
            throw new RuntimeException(
                    "Content has view with id attribute 'android.R.id.list' "
                    + "that is not a ListView class");
        }
        mList = (ListView)rawListView;
        if (mList == null) {
            throw new RuntimeException(
                    "Your content must have a ListView whose id attribute is " +
                    "'android.R.id.list'");
        }
        mList.setOnKeyListener(mListOnKeyListener);
        mHandler.post(mRequestFocus);
    }

    private OnKeyListener mListOnKeyListener = new OnKeyListener() {

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            Object selectedItem = mList.getSelectedItem();
            if (selectedItem instanceof Preference) {
                @SuppressWarnings("unused")
				View selectedView = mList.getSelectedView();
                //return ((Preference)selectedItem).onKey(
                //        selectedView, keyCode, event);
                return false;
            }
            return false;
        }

    };

}


text:
有人说 rabbitmq 做队列好
有人说 kafka 做队列好

###Kafka VS Rabbitmq

Message queue is a well known architectural pattern that provide an asynchronous communication protocol. It means that sender and receiver of the message are completely detached, they do not need to interact with a queueing system at the same time.

####MQ makes message queues (or message brokers) very useful for:

decoupling of services

painless scaling

backpressure management

==============

Kafka: - high-throughput distributed messaging system

RabbitMQ - reliable message broker (AMQP based)

| Feature | RabbitMq | Kafka |
| :—         |     :—:      |          —: |
| ` what is it   |  RabbitMQ is a solid, mature, general purpose message broker that supports several standardized protocols such as AMQP      | Apache Kafka is a message bus optimized for high-ingress data streams and replay   |
|  Primary use   |  High-throughput and reliable background jobs, communication and integration within, and between applications.      | Build applications that process and re-process streamed data on disk    |
|  routing approach   |  rich: topic -> direct,topic,headers,fanout      | simple: topic -> Consumer Group    |
| throuput / 1 pc     | 20000 msg/sec      | 100000 msg/sec     |
| client SDK support    | multiple languages      | multiple languages      |
| message delay    |  μs      | ms      |
| federated queues    |  can be use to migrate cluster      | kafka mirror-maker have same function     |
| availability and failover    |    HA with mirror queue    | HA with replica      |
| message lost   |   under control    | Under control after 0.11      |
| message duplicated    |    under control    |1) not avoidable prior to 0.11 because of at lease once semantics, 0.11 introduced exactly once semantics 2)kafka stream     |
| Order Message    |  Exclusive Consumer or Exclusive Queues can ensure ordering      | Ensure ordering of messages within a partition     |
| message priority    |  supported      | not supported      |
| message track    |  supported      | not supported      |
| Management and Operation Tools    |  supported as plugin     | not supported (need to install 3rd party tool e.g. kafka-manager)    |
| scalibility`    | Depends on the consumer,  you can add many consumers as you want, and there is no limit in theory      | Depends on the partition number, eg: 500 partitions, only 500 threads can consume from the topic, not meaning to add more threads.      |

Conclusion is simple:

Kafka is good for high throuput scenario

RabbitMQ is good for reliable and flexible topic routing scenario ((surely, rabbitmq can also handle large throuput, but it needs more machines compred with kafka.)

###Our rabbitmq use case:

Notification center service'

Once message arrives, will notify client

Why Rabbitmq in Notification center

Rabbitmq is mature, and developer is veryfamaliar with python + rabbitmq, and rabbitmq is reliable.

This function can be implemented with kafka as well, but developer thinks rabbitmq is much easier, and the exchange routing strategy is more flexsible.

Other rabbitmq use case

User order priority in shopping mall

e.g.: pub A -> Rabbitmq -> consumer B

consumer B get all the orders from rabbitmq to handle, B can take priority of the order from VIP customer, this makes sense.

Note: There are only two hard problems in distributed systems

Exactly-once delivery

Guaranteed order of messages

####Reference:

rabbitmq-hits-one-million-messages-per-second-on-google-compute-engine

https://content.pivotal.io/blog/rabbitmq-hits-one-million-messages-per-second-on-google-compute-engine


text:
"use strict";

var gulp = require('gulp');
var autoprefixer = require('gulp-autoprefixer');
var concat = require('gulp-concat');
var connect = require('gulp-connect');
var imagemin = require('gulp-imagemin');
var notify = require('gulp-notify');
var plumber = require('gulp-plumber');
var pngquant = require('imagemin-pngquant');
var rename = require('gulp-rename');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var uglify = require('gulp-uglify');

var dist = "./dist";
var errorHandlerFactory = function (taskName) {
    return function (err) {
        notify.onError({
            title: "Gulp Error: " + taskName,
            message: "<%= error.message %>",
            sound: "Beep"
        })(err);

        this.emit('end');
    };
};

gulp.task('html', function () {
    return gulp.src('./**/*.htm')
        .pipe(connect.reload());
});

gulp.task('images', function () {
    var onError = errorHandlerFactory('images');

    return gulp.src('./src/img/*')
        .pipe(plumber({ errorHandler: onError }))
        .pipe(imagemin({
            use: [pngquant()]
        }))
        .pipe(gulp.dest(dist + '/img'));
});

gulp.task('scripts', function () {
    var onError = errorHandlerFactory('scripts');

    return gulp.src('./src/js/app.js')
        .pipe(plumber({ errorHandler: onError }))
        .pipe(sourcemaps.init())
        .pipe(concat('app.js'))
        //.pipe(gulp.dest('./dist/js')) uncomment to create an un-minified version
        .pipe(rename({ suffix: '.min' }))
        .pipe(uglify())
        .pipe(sourcemaps.write())
        .pipe(gulp.dest(dist + '/js'))
        .pipe(connect.reload());
});

gulp.task('styles', function () {
    var onError = errorHandlerFactory('styles');

    return gulp.src('./src/scss/*.scss')
        .pipe(plumber({ errorHandler: onError }))
        .pipe(sourcemaps.init())
        .pipe(sass({ outputStyle: 'compressed' }).on('error', sass.logError))
        .pipe(autoprefixer())
        .pipe(rename({ suffix: '.min' }))
        .pipe(sourcemaps.write())
        .pipe(gulp.dest(dist + '/css'))
        .pipe(connect.reload());
});

gulp.task('watch', function () {
    gulp.watch('./src/scss/*.scss', ['styles']);
    gulp.watch('./src/js/*.js', ['scripts']);
    gulp.watch('./**/*.htm', ['html']);
});

gulp.task('connect', function () {
    return connect.server({
        root: [__dirname],
        livereload: true,
        fallback: './index.htm',
        host: '0.0.0.0'
    });
});

gulp.task('build', ['scripts', 'styles', 'html', 'images']);

gulp.task('default', ['build', 'watch', 'connect']);


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/html; charset=utf-8" />
<title>权限列表</title>
<link href="../../../styles/css/privilege/v1.0/css/style.css" type="text/css" rel="stylesheet"/>

当前位置:首页$!menuName

		 添 加

		修 改

		删 除

	 角色名称:<input name="rolename" id="rolename" type="text" class="text_input"/>

查 询

  	     #parse("foundation/privilege/role/pagelet/v1.0/role_list_grid.html")


text:
#pragma once

#include <cassert>
#include <libbase/helper.h>
#include <libbase/k60/flash.h>

using namespace libbase::k60;

class pFlash : public Flash
{

public:

	struct Config
	{
		void			*tablePtr;
		uint16_t	tableSize;

		Config(void *_tablePtr, uint16_t _tableSize)
		:
			tablePtr(_tablePtr),
			tableSize(_tableSize)
		{}
	};

	pFlash(Config config);

	void eraseAll(void);

	void readConfig(void* tablePtr, size_t tableSize);
	void writeConfig(void);
	void writeConfig(void *addr);

	void changeSize(size_t tableSize);

	void *getConfigTablePtr(void) const;

private:

	void				*m_tablePtr;
	size_t			m_sizeNeeded;

};


text:
package forimpatient.chapter10

import java.awt.Point

/**
  * Created by Iryna Kharaborkina on 8/8/16.
  *
  * Solution to the Chapter 10 Exercise 02 'Scala for the Impatient' by Horstmann C.S.
  *
  * Define a class OrderedPoint by mixing scala.math.Ordered[Point] into java.awt.Point.
  * Use lexicographic ordering, i.e. (x, y) < (x', y') if x < x' or x = x' and y < y'
  */
object Exercise02 extends App {
  println("Chapter 10 Exercise 02")

  val points = Seq(new OrderedPoint(8, 1), new OrderedPoint(2, 9), new OrderedPoint(5, 1), new OrderedPoint(2, 4))
  println(points)
  println(points.sortBy(a => (a.getX, a.getY)))
  println(points(1) + " > " + points(3) + ": " + (points(1) > points(3)))
  println(points(0) + " < " + points(2) + ": " + (points(0) < points(2)))

  class OrderedPoint(x: Int, y: Int) extends Point(x: Int, y: Int) with Ordered[Point] {
    override def compare(that: Point): Int = {
      if (x < that.x && y < that.y) -1
      else if (x == that.x) {if (y < that.y) -1 else if (y == that.y) 0 else 1 }
      else 1
    }

    override def toString: String = "Point[" + x + "x" + y + "]"
  }
}


text:
FROM ubuntu:14.04

MAINTAINER "Apache CloudStack" <dev@cloudstack.apache.org>
LABEL Description="Apache CloudStack EC2stack; Python based AWS EC2 Interface to the CloudStack API"
LABEL Vendor="apache.org"
LABEL License=ApacheV2
LABEL Version=1.0.0

RUN apt-get update
RUN apt-get install -y python
RUN apt-get install -y python-pip
RUN apt-get clean all

RUN pip install ec2stack
RUN pip install --upgrade requests

EXPOSE 5000

CMD ["ec2stack"]


text:
package ex01;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.stream.Collectors;

public class NormalSaver implements Saver {

    @Override
    public void save(String fileName, Integer[] array) {

        String out = Arrays
            .stream(array)
            .map(elm -> elm.toString())
            .collect(Collectors.joining(" "));

        try {
            Files.write(Paths.get(fileName), out.getBytes());
        } catch (IOException ex) {
            System.out.println("Błąd związany z zapisem pliku.");
        }

    }

}


text:
"""Standalone helper functions"""

import contextlib

from maya import cmds, mel
from maya.api import OpenMaya as om

def unique_name(name, format="%02d", namespace="", prefix="", suffix=""):
    """Return unique `name`

    The function takes into consideration an optional `namespace`
    and `suffix`. The suffix is included in evaluating whether a
    name exists - such as `name` + "_GRP" - but isn't included
    in the returned value.

    If a namespace is provided, only names within that namespace
    are considered when evaluating whether the name is unique.

    Arguments:
        format (str, optional): The `name` is given a number, this determines
            how this number is formatted. Defaults to a padding of 2.
            E.g. my_name01, my_name02.
        namespace (str, optional): Only consider names within this namespace.
        suffix (str, optional): Only consider names with this suffix.

    Example:
        >>> name = cmds.createNode("transform", name="MyName")
        >>> cmds.objExists(name)
        True
        >>> unique = unique_name(name)
        >>> cmds.objExists(unique)
        False

    """

    iteration = 1
    unique = prefix + (name + format % iteration) + suffix

    while cmds.objExists(namespace + ":" + unique):
        iteration += 1
        unique = prefix + (name + format % iteration) + suffix

    if suffix:
        return unique[:-len(suffix)]

    return unique

def unique_namespace(namespace, format="%02d", prefix="", suffix=""):
    """Return unique namespace

    Similar to :func:`unique_name` but evaluating namespaces
    as opposed to object names.

    Arguments:
        namespace (str): Name of namespace to consider
        format (str, optional): Formatting of the given iteration number
        suffix (str, optional): Only consider namespaces with this suffix.

    """

    iteration = 1
    unique = prefix + (namespace + format % iteration) + suffix

    # The `existing` set does not just contain the namespaces but *all* nodes
    # within "current namespace". We need all because the namespace could
    # also clash with a node name. To be truly unique and valid one needs to
    # check against all.
    existing = set(cmds.namespaceInfo(listNamespace=True))
    while unique in existing:
        iteration += 1
        unique = prefix + (namespace + format % iteration) + suffix

    return unique

def read(node):
    """Return user-defined attributes from `node`"""

    data = dict()

    for attr in cmds.listAttr(node, userDefined=True) or list():
        try:
            value = cmds.getAttr(node + "." + attr, asString=True)

        except RuntimeError:
            # For Message type attribute or others that have connections,
            # take source node name as value.
            source = cmds.listConnections(node + "." + attr,
                                          source=True,
                                          destination=False)
            source = cmds.ls(source, long=True) or [None]
            value = source[0]

        except ValueError:
            # Some attributes cannot be read directly,
            # such as mesh and color attributes. These
            # are considered non-essential to this
            # particular publishing pipeline.
            value = None

        data[attr] = value

    return data

def export_alembic(nodes,
                   file,
                   frame_range=None,
                   write_uv=True,
                   write_visibility=True,
                   attribute_prefix=None):
    """Wrap native MEL command with limited set of arguments

    Arguments:
        nodes (list): Long names of nodes to cache

        file (str): Absolute path to output destination

        frame_range (tuple, optional): Start- and end-frame of cache,
            default to current animation range.

        write_uv (bool, optional): Whether or not to include UVs,
            default to True

        write_visibility (bool, optional): Turn on to store the visibility
        state of objects in the Alembic file. Otherwise, all objects are
        considered visible, default to True

        attribute_prefix (str, optional): Include all user-defined
            attributes with this prefix.

    """

    if frame_range is None:
        frame_range = (
            cmds.playbackOptions(query=True, ast=True),
            cmds.playbackOptions(query=True, aet=True)
        )

    options = [
        ("file", file),
        ("frameRange", "%s %s" % frame_range),
    ] + [("root", mesh) for mesh in nodes]

    if isinstance(attribute_prefix, basestring):
        # Include all attributes prefixed with "mb"
        # TODO(marcus): This would be a good candidate for
        #   external registration, so that the developer
        #   doesn't have to edit this function to modify
        #   the behavior of Alembic export.
        options.append(("attrPrefix", str(attribute_prefix)))

    if write_uv:
        options.append(("uvWrite", ""))

    if write_visibility:
        options.append(("writeVisibility", ""))

    # Generate MEL command
    mel_args = list()
    for key, value in options:
        mel_args.append("-{0} {1}".format(key, value))

    mel_args_string = " ".join(mel_args)
    mel_cmd = "AbcExport -j \"{0}\"".format(mel_args_string)

    # For debuggability, put the string passed to MEL in the Script editor.
    print("mel.eval('%s')" % mel_cmd)

    return mel.eval(mel_cmd)

@contextlib.contextmanager
def undo_chunk():
    """Open a undo chunk during context."""

    try:
        cmds.undoInfo(openChunk=True)
        yield
    finally:
        cmds.undoInfo(closeChunk=True)

def imprint(node, data):
    """Write `data` to `node` as userDefined attributes

    Arguments:
        node (str): Long name of node
        data (dict): Dictionary of key/value pairs

    Example:
        >>> from maya import cmds
        >>> def compute():
        ...   return 6
        ...
        >>> cube, generator = cmds.polyCube()
        >>> imprint(cube, {
        ...   "regularString": "myFamily",
        ...   "computedValue": lambda: compute()
        ... })
        ...
        >>> cmds.getAttr(cube + ".computedValue")
        6

    """

    for key, value in data.items():

        if callable(value):
            # Support values evaluated at imprint
            value = value()

        if isinstance(value, bool):
            add_type = {"attributeType": "bool"}
            set_type = {"keyable": False, "channelBox": True}
        elif isinstance(value, basestring):
            add_type = {"dataType": "string"}
            set_type = {"type": "string"}
        elif isinstance(value, int):
            add_type = {"attributeType": "long"}
            set_type = {"keyable": False, "channelBox": True}
        elif isinstance(value, float):
            add_type = {"attributeType": "double"}
            set_type = {"keyable": False, "channelBox": True}
        elif isinstance(value, (list, tuple)):
            add_type = {"attributeType": "enum", "enumName": ":".join(value)}
            set_type = {"keyable": False, "channelBox": True}
            value = 0  # enum default
        else:
            raise TypeError("Unsupported type: %r" % type(value))

        cmds.addAttr(node, longName=key, **add_type)
        cmds.setAttr(node + "." + key, value, **set_type)

@contextlib.contextmanager
def without_extension():
    """Use cmds.file with defaultExtensions=False"""
    previous_setting = cmds.file(defaultExtensions=True, query=True)
    try:
        cmds.file(defaultExtensions=False)
        yield
    finally:
        cmds.file(defaultExtensions=previous_setting)

@contextlib.contextmanager
def maintained_selection():
    """Maintain selection during context

    Example:
        >>> scene = cmds.file(new=True, force=True)
        >>> node = cmds.createNode("transform", name="Test")
        >>> cmds.select("persp")
        >>> with maintained_selection():
        ...     cmds.select("Test", replace=True)
        >>> "Test" in cmds.ls(selection=True)
        False

    """

    previous_selection = cmds.ls(selection=True)
    try:
        yield
    finally:
        if previous_selection:
            cmds.select(previous_selection,
                        replace=True,
                        noExpand=True)
        else:
            cmds.select(clear=True)

@contextlib.contextmanager
def suspended_refresh():
    """Suspend viewport refreshes"""

    try:
        cmds.refresh(suspend=True)
        yield
    finally:
        cmds.refresh(suspend=False)

def serialise_shaders(nodes):
    """Generate a shader set dictionary

    Arguments:
        nodes (list): Absolute paths to nodes

    Returns:
        dictionary of (shader: id) pairs

    Schema:
        {
            "shader1": ["id1", "id2"],
            "shader2": ["id3", "id1"]
        }

    Example:
        {
            "Bazooka_Brothers01_:blinn4SG": [
                "f9520572-ac1d-11e6-b39e-3085a99791c9.f[4922:5001]",
                "f9520572-ac1d-11e6-b39e-3085a99791c9.f[4587:4634]",
                "f9520572-ac1d-11e6-b39e-3085a99791c9.f[1120:1567]",
                "f9520572-ac1d-11e6-b39e-3085a99791c9.f[4251:4362]"
            ],
            "lambert2SG": [
                "f9520571-ac1d-11e6-9dbb-3085a99791c9"
            ]
        }

    """

    valid_nodes = cmds.ls(
        nodes,
        long=True,
        recursive=True,
        showType=True,
        objectsOnly=True,
        type="transform"
    )

    meshes_by_id = {}
    for mesh in valid_nodes:
        shapes = cmds.listRelatives(valid_nodes[0],
                                    shapes=True,
                                    fullPath=True) or list()

        if shapes:
            shape = shapes[0]
            if not cmds.nodeType(shape):
                continue

            try:
                id_ = cmds.getAttr(mesh + ".mbID")

                if id_ not in meshes_by_id:
                    meshes_by_id[id_] = list()

                meshes_by_id[id_].append(mesh)

            except ValueError:
                continue

    meshes_by_shader = dict()
    for id_, mesh in meshes_by_id.items():
        shape = cmds.listRelatives(mesh,
                                   shapes=True,
                                   fullPath=True) or list()

        for shader in cmds.listConnections(shape,
                                           type="shadingEngine") or list():

            # Objects in this group are those that haven't got
            # any shaders. These are expected to be managed
            # elsewhere, such as by the default model loader.
            if shader == "initialShadingGroup":
                continue

            if shader not in meshes_by_shader:
                meshes_by_shader[shader] = list()

            shaded = cmds.sets(shader, query=True) or list()
            meshes_by_shader[shader].extend(shaded)

    shader_by_id = {}
    for shader, shaded in meshes_by_shader.items():

        if shader not in shader_by_id:
            shader_by_id[shader] = list()

        for mesh in shaded:

            # Enable shader assignment to faces.
            name = mesh.split(".f[")[0]

            transform = name
            if cmds.objectType(transform) == "mesh":
                transform = cmds.listRelatives(name, parent=True)[0]

            try:
                id_ = cmds.getAttr(transform + ".mbID")
                shader_by_id[shader].append(mesh.replace(name, id_))
            except KeyError:
                continue

        # Remove duplicates
        shader_by_id[shader] = list(set(shader_by_id[shader]))

    return shader_by_id

def apply_shaders(relationships, namespace=None):
    """Given a dictionary of `relationships`, apply shaders to meshes

    Arguments:
        relationships (avalon-core:shaders-1.0): A dictionary of
            shaders and how they relate to meshes.

    """

    if namespace is not None:
        # Append namespace to shader group identifier.
        # E.g. `blinn1SG` -> `Bruce_:blinn1SG`
        relationships = {
            "%s:%s" % (namespace, shader): relationships[shader]
            for shader in relationships
        }

    for shader, ids in relationships.items():
        print("Looking for '%s'.." % shader)
        shader = next(iter(cmds.ls(shader)), None)
        assert shader, "Associated shader not part of asset, this is a bug"

        for id_ in ids:
            mesh, faces = (id_.rsplit(".", 1) + [""])[:2]

            # Find all meshes matching this particular ID
            # Convert IDs to mesh + id, e.g. "nameOfNode.f[1:100]"
            meshes = list(".".join([mesh, faces])
                          for mesh in lsattr("mbID", value=mesh))

            if not meshes:
                continue

            print("Assigning '%s' to '%s'" % (shader, ", ".join(meshes)))
            cmds.sets(meshes, forceElement=shader)

def lsattr(attr, value=None):
    """Return nodes matching `key` and `value`

    Arguments:
        attr (str): Name of Maya attribute
        value (object, optional): Value of attribute. If none
            is provided, return all nodes with this attribute.

    Example:
        >> lsattr("id", "myId")
        ["myNode"]
        >> lsattr("id")
        ["myNode", "myOtherNode"]

    """

    if value is None:
        return cmds.ls("*.%s" % attr,
                       recursive=True,
                       objectsOnly=True,
                       long=True)
    return lsattrs({attr: value})

def lsattrs(attrs):
    """Return nodes with the given attribute(s).

    Arguments:
        attrs (dict): Name and value pairs of expected matches

    Example:
        >> # Return nodes with an `age` of five.
        >> lsattr({"age": "five"})
        >> # Return nodes with both `age` and `color` of five and blue.
        >> lsattr({"age": "five", "color": "blue"})

    Return:
         list: matching nodes.

    """

    dep_fn = om.MFnDependencyNode()
    dag_fn = om.MFnDagNode()
    selection_list = om.MSelectionList()

    first_attr = attrs.iterkeys().next()

    try:
        selection_list.add("*.{0}".format(first_attr),
                           searchChildNamespaces=True)
    except RuntimeError as exc:
        if str(exc).endswith("Object does not exist"):
            return []

    matches = set()
    for i in range(selection_list.length()):
        node = selection_list.getDependNode(i)
        if node.hasFn(om.MFn.kDagNode):
            fn_node = dag_fn.setObject(node)
            full_path_names = [path.fullPathName()
                               for path in fn_node.getAllPaths()]
        else:
            fn_node = dep_fn.setObject(node)
            full_path_names = [fn_node.name()]

        for attr in attrs:
            try:
                plug = fn_node.findPlug(attr, True)
                if plug.asString() != attrs[attr]:
                    break
            except RuntimeError:
                break
        else:
            matches.update(full_path_names)

    return list(matches)


text:
require 'cuprum'
require 'cuprum/matching'

module Cuprum
  # Provides result matching based on result status, error, and value.
  #
  # First, define match clauses using the .match DSL. Each match clause has a
  # status and optionally a value class and/or error class. A result will only
  # match the clause if the result status is the same as the clause's status.
  # If the clause sets a value class, then the result value must be an instance
  # of that class (or an instance of a subclass). If the clause sets an error
  # class, then the result error must be an instance of that class (or an
  # instance of a subclass).
  #
  # Once the matcher defines one or more match clauses, call #call with a result
  # to match the result. The matcher will determine the best match with the same
  # status (value and error match the result, only value or error match, or just
  # status matches) and then call the match clause with the result. If no match
  # clauses match the result, the matcher will instead raise a
  # Cuprum::Matching::NoMatchError.
  #
  # @example Matching A Status
  #   matcher = Cuprum::Matcher.new do
  #     match(:failure) { 'Something went wrong' }
  #
  #     match(:success) { 'Ok' }
  #   end
  #
  #   matcher.call(Cuprum::Result.new(status: :failure))
  #   #=> 'Something went wrong'
  #
  #   matcher.call(Cuprum::Result.new(status: :success))
  #   #=> 'Ok'
  #
  # @example Matching An Error
  #   matcher = Cuprum::Matcher.new do
  #     match(:failure) { 'Something went wrong' }
  #
  #     match(:failure, error: CustomError) { |result| result.error.message }
  #
  #     match(:success) { 'Ok' }
  #   end
  #
  #   matcher.call(Cuprum::Result.new(status: :failure))
  #   #=> 'Something went wrong'
  #
  #   error = CustomError.new(message: 'The magic smoke is escaping.')
  #   matcher.call(Cuprum::Result.new(error: error))
  #   #=> 'The magic smoke is escaping.'
  #
  # @example Using A Match Context
  #   context = Struct.new(:name).new('programs')
  #   matcher = Cuprum::Matcher.new(context) do
  #     match(:failure) { 'Something went wrong' }
  #
  #     match(:success) { "Greetings, #{name}!" }
  #   end
  #
  #   matcher.call(Cuprum::Result.new(status: :success)
  #   #=> 'Greetings, programs!'
  class Matcher
    include Cuprum::Matching

    # @param match_context [Object] the execution context for a matching clause.
    #
    # @yield Executes the block in the context of the singleton class. This is
    #   used to define match clauses when instantiating a Matcher instance.
    def initialize(match_context = nil, &block)
      @match_context = match_context

      singleton_class.instance_exec(&block) if block_given?
    end

    # Returns a copy of the matcher with the given execution context.
    #
    # @param match_context [Object] the execution context for a matching clause.
    #
    # @return [Cuprum::Matcher] the copied matcher.
    def with_context(match_context)
      clone.tap { |copy| copy.match_context = match_context }
    end
    alias_method :using_context, :with_context

    protected

    attr_writer :match_context
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Mendham.Domain
{
    public abstract class SingleFieldValueObject<TSingleField, TValueObject> : ValueObject<TValueObject>, ISingleFieldValueObject<TSingleField>
        where TValueObject : SingleFieldValueObject<TSingleField, TValueObject>
    {
        public TSingleField Value { get; protected set; }

        public SingleFieldValueObject(TSingleField value)
        {
            value.VerifyArgumentNotDefaultValue(nameof(value), "Value is required");
            this.Value = value;
        }

        public static implicit operator TSingleField(SingleFieldValueObject<TSingleField, TValueObject> singleFieldValueObject)
        {
            return singleFieldValueObject.Value;
        }
    }
}


text:
declare module B {
  function doSomething();
}


text:
import * as R from 'ramda'
import React, { Component } from 'react'
import OptionTextInput from '../OptionTextInput'
import settings from '../../settings'

class OptionsEditor extends Component {
  render() {
    const {
      selectedActionOptions,
      onUpdateOption
    } = this.props
    const getOptions = R.compose(
      R.values,
      R.mapObjIndexed((option, key) => {
        if (option.type === settings.OPTIONS.types.string) {
          return (
            <OptionTextInput
              id={key}
              label={option.title}
              key={`OptionTextTemplate-${key}`}
              onUpdateOption={onUpdateOption}
            />
          )
        } else {
          throw Error('Unrecognised option field!', option)
        }
      }),
    )
    const options = getOptions(selectedActionOptions)
    return <div>{options}</div>
  }
}

export default OptionsEditor


text:
using System;

using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.X509;

namespace Org.BouncyCastle.Asn1.Ocsp
{
    public class Signature
        : Asn1Encodable
    {
        internal AlgorithmIdentifier	signatureAlgorithm;
        internal DerBitString			signatureValue;
        internal Asn1Sequence			certs;

		public static Signature GetInstance(
			Asn1TaggedObject	obj,
			bool				explicitly)
		{
			return GetInstance(Asn1Sequence.GetInstance(obj, explicitly));
		}

		public static Signature GetInstance(
			object  obj)
		{
			if (obj == null || obj is Signature)
			{
				return (Signature)obj;
			}

			if (obj is Asn1Sequence)
			{
				return new Signature((Asn1Sequence)obj);
			}

			throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj");
		}

		public Signature(
            AlgorithmIdentifier signatureAlgorithm,
            DerBitString        signatureValue)
			: this(signatureAlgorithm, signatureValue, null)
        {
        }

		public Signature(
            AlgorithmIdentifier	signatureAlgorithm,
            DerBitString		signatureValue,
            Asn1Sequence		certs)
        {
			if (signatureAlgorithm == null)
				throw new ArgumentException("signatureAlgorithm");
			if (signatureValue == null)
				throw new ArgumentException("signatureValue");

			this.signatureAlgorithm = signatureAlgorithm;
            this.signatureValue = signatureValue;
            this.certs = certs;
        }

		private Signature(
            Asn1Sequence seq)
        {
            signatureAlgorithm = AlgorithmIdentifier.GetInstance(seq[0]);
            signatureValue = (DerBitString)seq[1];

			if (seq.Count == 3)
            {
                certs = Asn1Sequence.GetInstance(
					(Asn1TaggedObject)seq[2], true);
            }
        }

		public AlgorithmIdentifier SignatureAlgorithm
		{
			get { return signatureAlgorithm; }
		}

		public DerBitString SignatureValue
		{
			get { return signatureValue; }
		}

		public Asn1Sequence Certs
		{
			get { return certs; }
		}

		/**
         * Produce an object suitable for an Asn1OutputStream.
         * <pre>
         * Signature       ::=     Sequence {
         *     signatureAlgorithm      AlgorithmIdentifier,
         *     signature               BIT STRING,
         *     certs               [0] EXPLICIT Sequence OF Certificate OPTIONAL}
         * </pre>
         */
        public override Asn1Object ToAsn1Object()
        {
            Asn1EncodableVector v = new Asn1EncodableVector(
				signatureAlgorithm, signatureValue);

			if (certs != null)
            {
                v.Add(new DerTaggedObject(true, 0, certs));
            }

			return new DerSequence(v);
        }
    }
}


text:
*[src*="ads.salesmore.pl"],
*[src*="afx.tagcdn.com"],
*[src*="s0.2mdn.net"],
a[href*="clk.tradedoubler.com"],
a[href*="owabgxis.wp.pl"],
*[id*="_adr_abp_iframe"] /* rmfon.pl */,
*[id*="clickonometrics"] /* natemat.pl */ {
 display:none !important;
}

/* poczta.wp.pl */
body > div#main > div#middle > div#mainColumn > div:nth-child(2),
body > div#main > div#middle > div#rightColumn,
body > div#main > div#middle > div#leftColumn > div#leftColumnInner > table.dragdrop-dropTarget > tbody > tr:nth-child(5),
body > div#main > div#middle > div#leftColumn > div#leftColumnInner > table.dragdrop-dropTarget > tbody > tr:nth-child(6),
div[style*="750px"][style*="200px"],
.wpAdv,
.nepal-fullpage,
.ml20, .mt16,
div[id*="adv"],
iframe[id*="advdyn"],
#bx3Collapser,
a[href*="gemius.pl"],
a[href*="//ad.doubleclick.net/"],
a[href*="//owabgxis.wp.pl"],
*[src*="//rek.www.wp.pl/rgr.html"],
*[src*="//adv.wp.pl"],
*[src*="pomagasz"],
*[srcdoc*="//adv.wp.pl"],
.postSendWnd tr:nth-child(4),
#w345_dr,
div[onclick="window.open(window.clickTag, '_blank ')"],
#poczta_loginbox_iframe {
 display:none !important;
}
/* write message window */
.popupMiddleCenterInner { overflow: hidden !important; }
/* login page */
.bxLogowanie {
 height: 413px !important;
}
#stgHeader,
#stgFooter,
#rightLogBox,
.bxZalety {
 display:block !important;
}
#stgHeader { border-top: none !important; }
#stgMain {
 position: static !important;
 width: 970px !important;
 height: auto !important;
 left: auto !important;
 top: auto !important;
}
#stgMain { background-color: #fff !important; }


text:
import React from 'react';
import ReactDOM from 'react-dom';
import {PricingTable} from '../src/index';
import { shallow , mount} from 'enzyme';
import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-15';

Enzyme.configure({ adapter: new Adapter() });

describe('PricingTable', () => {

    it('renders without crashing', () => {
        const div = document.createElement('div');
        ReactDOM.render(<PricingTable />, div);
    });

    it('should render with "react-pricing-table" class', () => {
      const wrapper = shallow(<PricingTable  />);
      expect(wrapper.hasClass('react-pricing-table')).toBe(true);
    });

});


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center_vertical"
    android:orientation="horizontal"
    android:background="@drawable/scanner_ipaddress_list_item_background">

    <ImageView
        android:id="@+id/tel_icon"
        android:focusable="false"
        android:layout_width="32dp"
        android:layout_height="32dp"
        android:layout_marginTop="8dp"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:contentDescription="@string/scanner_list_icon_desc"
        android:background="@drawable/ic_menu_notifications"/>

     <TextView
	        android:text="@+id/ItemName"
	        android:id="@+id/ItemName"
	        android:focusable="false"
	        android:layout_height="fill_parent"
	        android:layout_width="wrap_content"
	        android:layout_weight="1"
	        android:layout_marginLeft="8dp"
	        android:gravity="center_vertical"
	        android:textAppearance="@android:style/TextAppearance.Medium"
	        android:singleLine="true"/>

	    <TextView
	        android:text="@+id/ItemIP"
	        android:id="@+id/ItemIP"
	        android:focusable="false"
	        android:layout_height="fill_parent"
	        android:layout_width="wrap_content"
	        android:layout_weight="1"
	        android:layout_marginLeft="8dp"
	        android:layout_marginRight="8dp"
	        android:gravity="bottom|right"
	        android:textAppearance="@android:style/TextAppearance.Small"
	        android:textStyle="bold"
	        android:singleLine="true"/>

</LinearLayout>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">

<TITLE>Die Animationssoftware ANIMAL</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=Windows-1252">
<link rel="stylesheet" type="text/css" href="CrypTool_Help.css">

<OBJECT TYPE="application/x-oleobject" CLASSID="clsid:1e2a7bd0-dab9-11d0-b93a-00c04fc99f9e" VIEWASTEXT>
	<PARAM NAME="Keyword" VALUE="ANIMAL">
</OBJECT>

Die Animationssoftware ANIMAL

Die freie Animationssoftware ANIMAL kann Algorithmen veranschaulichen. ANIMAL ist eine Java-Applikation, die es erlaubt, die Einzelschritte von Algorithmen beliebig genau zu modellieren. Die Schrittfolgen können mit statischen Daten in einer AML-Datei abgelegt werden oder mit dynamischen Daten über AnimalScript definiert werden.

ANIMAL erlaubt, diese Schrittfolgen manuell vor und zurück durchzulaufen oder die gesamte Schrittfolge automatisch abzuspielen. Dabei haben Sie z.B. Optionen zur Geschwindigkeit und Darstellung in ANIMAL selbst.

Mit CrypTool wird ANIMAL 2 ausgeliefert (siehe Menü Einzelverfahren \ Visualisierung von Algorithmen). Da ANIMAL eine Java-Applikation ist, müssen Sie vorher eine Java Runtime-Umgebung installiert haben (mindestens in der Version 1.7), damit CrypTool das ANIMAL-Programm aufrufen kann (das Java Runtime Environment gibt es z.B. unter http://java.sun.com).

Die jeweils aktuelle Fassung von ANIMAL gibt es in Deutsch und Englisch unter http://www.algoanim.info/AnimalAV/. Dort gibt es auch eine große Sammlung freier Animationen von Algorithmen aus ganz verschiedenen Bereichen.

Wenn man ANIMAL lädt, werden zwei Fenster geöffnet:

ein ANIMAL-Steuerfenster und

ein ANIMAL-Anzeigefenster.

Ist das Anzeigefenster nicht sichtbar, kann man es im Steuerfenster über das Menü "Bearbeiten \ Animationsfenster anzeigen" aufrufen.

Die Bedienung des ANIMAL-Anzeigefensters wird im folgenden
  beschrieben:

  Regelt die Geschwindigkeit der Animation

 Vergrößert
  bzw. verkleinert die Darstellungsgröße

  Zum Anfang der Animation

  Zum vorherigen Schritt

  Animation als inverse Slideshow abspielen

  Animationsschritt zurück

  Animation anhalten

  Ausführen des nächsten Schritts

  Animation als Slideshow anzeigen

  Gehe zum nächsten Schritt

  Zum Ende der Animation

  Zum Beenden der Animationen müssen sowohl das Animationsfenster als auch das
  Programmfenster von Animal geschlossen werden.