text:
package org.optaplanner.core.impl.partitionedsearch;

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.optaplanner.core.api.domain.solution.PlanningSolution;
import org.optaplanner.core.config.heuristic.policy.HeuristicConfigPolicy;
import org.optaplanner.core.config.phase.PhaseConfig;
import org.optaplanner.core.config.solver.recaller.BestSolutionRecallerConfig;
import org.optaplanner.core.impl.heuristic.move.Move;
import org.optaplanner.core.impl.partitionedsearch.event.PartitionedSearchPhaseLifecycleListener;
import org.optaplanner.core.impl.partitionedsearch.partitioner.SolutionPartitioner;
import org.optaplanner.core.impl.partitionedsearch.queue.PartitionQueue;
import org.optaplanner.core.impl.partitionedsearch.scope.PartitionChangeMove;
import org.optaplanner.core.impl.partitionedsearch.scope.PartitionedSearchPhaseScope;
import org.optaplanner.core.impl.partitionedsearch.scope.PartitionedSearchStepScope;
import org.optaplanner.core.impl.phase.AbstractPhase;
import org.optaplanner.core.impl.phase.Phase;
import org.optaplanner.core.impl.score.director.InnerScoreDirector;
import org.optaplanner.core.impl.solver.ChildThreadType;
import org.optaplanner.core.impl.solver.recaller.BestSolutionRecaller;
import org.optaplanner.core.impl.solver.scope.DefaultSolverScope;
import org.optaplanner.core.impl.solver.termination.ChildThreadPlumbingTermination;
import org.optaplanner.core.impl.solver.termination.OrCompositeTermination;
import org.optaplanner.core.impl.solver.termination.Termination;

/**
 * Default implementation of {@link PartitionedSearchPhase}.
 * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
 */
public class DefaultPartitionedSearchPhase<Solution_> extends AbstractPhase<Solution_>
        implements PartitionedSearchPhase<Solution_>, PartitionedSearchPhaseLifecycleListener<Solution_> {

    protected SolutionPartitioner<Solution_> solutionPartitioner;
    protected ThreadFactory threadFactory;
    protected Integer runnablePartThreadLimit;

    protected List<PhaseConfig> phaseConfigList;
    protected HeuristicConfigPolicy configPolicy;

    public DefaultPartitionedSearchPhase(int phaseIndex, String logIndentation,
            BestSolutionRecaller<Solution_> bestSolutionRecaller, Termination termination) {
        super(phaseIndex, logIndentation, bestSolutionRecaller, termination);
    }

    public void setSolutionPartitioner(SolutionPartitioner<Solution_> solutionPartitioner) {
        this.solutionPartitioner = solutionPartitioner;
    }

    public void setThreadFactory(ThreadFactory threadFactory) {
        this.threadFactory = threadFactory;
    }

    public void setRunnablePartThreadLimit(Integer runnablePartThreadLimit) {
        this.runnablePartThreadLimit = runnablePartThreadLimit;
    }

    public void setPhaseConfigList(List<PhaseConfig> phaseConfigList) {
        this.phaseConfigList = phaseConfigList;
    }

    public void setConfigPolicy(HeuristicConfigPolicy configPolicy) {
        this.configPolicy = configPolicy;
    }

    @Override
    public String getPhaseTypeString() {
        return "Partitioned Search";
    }

    // ************************************************************************
    // Worker methods
    // ************************************************************************

    @Override
    public void solve(DefaultSolverScope<Solution_> solverScope) {
        PartitionedSearchPhaseScope<Solution_> phaseScope = new PartitionedSearchPhaseScope<>(solverScope);
        List<Solution_> partList = solutionPartitioner.splitWorkingSolution(
                solverScope.getScoreDirector(), runnablePartThreadLimit);
        int partCount = partList.size();
        phaseScope.setPartCount(partCount);
        phaseStarted(phaseScope);
        ExecutorService executor = createThreadPoolExecutor(partCount);
        ChildThreadPlumbingTermination childThreadPlumbingTermination = new ChildThreadPlumbingTermination();
        PartitionQueue<Solution_> partitionQueue = new PartitionQueue<>(partCount);
        Semaphore runnablePartThreadSemaphore
                = runnablePartThreadLimit == null ? null : new Semaphore(runnablePartThreadLimit, true);
        try {
            for (ListIterator<Solution_> it = partList.listIterator(); it.hasNext();) {
                int partIndex = it.nextIndex();
                Solution_ part = it.next();
                PartitionSolver<Solution_> partitionSolver = buildPartitionSolver(
                        childThreadPlumbingTermination, runnablePartThreadSemaphore, solverScope);
                partitionSolver.addEventListener(event -> {
                    InnerScoreDirector<Solution_> childScoreDirector = partitionSolver.solverScope.getScoreDirector();
                    PartitionChangeMove<Solution_> move = PartitionChangeMove.createMove(childScoreDirector, partIndex);
                    InnerScoreDirector<Solution_> parentScoreDirector = solverScope.getScoreDirector();
                    move = move.rebase(parentScoreDirector);
                    partitionQueue.addMove(partIndex, move);
                });
                executor.submit(() -> {
                    try {
                        partitionSolver.solve(part);
                        partitionQueue.addFinish(partIndex);
                    } catch (Throwable throwable) {
                        // Any Exception or even Error that happens here (on a partition thread) must be stored
                        // in the partitionQueue in order to be propagated to the solver thread.
                        partitionQueue.addExceptionThrown(partIndex, throwable);
                    }
                });
            }
            for (PartitionChangeMove<Solution_> step : partitionQueue) {
                PartitionedSearchStepScope<Solution_> stepScope = new PartitionedSearchStepScope<>(phaseScope);
                stepStarted(stepScope);
                stepScope.setStep(step);
                if (logger.isDebugEnabled()) {
                    stepScope.setStepString(step.toString());
                }
                doStep(stepScope);
                stepEnded(stepScope);
                phaseScope.setLastCompletedStepScope(stepScope);
            }
        } finally {
            // 1. In case one of the partition threads threw an Exception, it is propagated here
            // but the other partition threads are not aware of the failure and may continue solving for a long time,
            // so we need to ask them to terminate. In case no exception was thrown, this does nothing.
            childThreadPlumbingTermination.terminateChildren();

            // Intentionally clearing the interrupted flag so that awaitTermination() in step 3 works.
            if (Thread.interrupted()) {
                // 2a. If the current thread is interrupted, propagate interrupt signal to children by initiating
                // an abrupt shutdown.
                executor.shutdownNow();
            } else {
                // 2b. Otherwise, initiate an orderly shutdown of the executor. This allows partition solvers to finish
                // solving upon detecting the termination issued previously (step 1). Shutting down the executor
                // service is important because the JVM cannot exit until all nondaemon threads have terminated.
                executor.shutdown();
            }

            // 3. Finally, wait until the executor finishes shutting down.
            try {
                final int awaitingSeconds = 1;
                if (!executor.awaitTermination(awaitingSeconds, TimeUnit.SECONDS)) {
                    // Some solvers refused to complete. Busy threads will be interrupted in the finally block.
                    // We're only logging the error instead throwing an exception to prevent eating the original
                    // exception.
                    logger.error(
                            "{}Partitioned Search threadPoolExecutor didn't terminate within timeout ({} second).",
                            logIndentation,
                            awaitingSeconds);
                }
            } catch (InterruptedException e) {
                // Interrupted while waiting for thread pool termination. Busy threads will be interrupted
                // in the finally block.
                Thread.currentThread().interrupt();
                // If there is an original exception it will be eaten by this.
                throw new IllegalStateException("Thread pool termination was interrupted.", e);
            } finally {
                // Initiate an abrupt shutdown for the case when any of the previous measures failed.
                executor.shutdownNow();
            }
        }
        phaseEnded(phaseScope);
    }

    private ExecutorService createThreadPoolExecutor(int partCount) {
        ThreadPoolExecutor threadPoolExecutor
                = (ThreadPoolExecutor) Executors.newFixedThreadPool(partCount, threadFactory);

        if (threadPoolExecutor.getMaximumPoolSize() < partCount) {
            throw new IllegalStateException(
                    "The threadPoolExecutor's maximumPoolSize (" + threadPoolExecutor.getMaximumPoolSize()
                    + ") is less than the partCount (" + partCount + "), so some partitions will starve.\n"
                    + "Normally this is impossible because the threadPoolExecutor should be unbounded:"
                    + " Use runnablePartThreadLimit (" + runnablePartThreadLimit
                    + ") instead to avoid CPU hogging and live locks.");
        }

        return threadPoolExecutor;
    }

    public PartitionSolver<Solution_> buildPartitionSolver(
            ChildThreadPlumbingTermination childThreadPlumbingTermination, Semaphore runnablePartThreadSemaphore,
            DefaultSolverScope<Solution_> solverScope) {
        Termination partTermination = new OrCompositeTermination(childThreadPlumbingTermination,
                termination.createChildThreadTermination(solverScope, ChildThreadType.PART_THREAD));
        BestSolutionRecaller<Solution_> bestSolutionRecaller = new BestSolutionRecallerConfig()
                .buildBestSolutionRecaller(configPolicy.getEnvironmentMode());
        List<Phase<Solution_>> phaseList = new ArrayList<>(phaseConfigList.size());
        int partPhaseIndex = 0;
        for (PhaseConfig phaseConfig : phaseConfigList) {
            phaseList.add(phaseConfig.buildPhase(partPhaseIndex, configPolicy, bestSolutionRecaller, partTermination));
            partPhaseIndex++;
        }
        // TODO create PartitionSolverScope alternative to deal with 3 layer terminations
        DefaultSolverScope<Solution_> partSolverScope
                = solverScope.createChildThreadSolverScope(ChildThreadType.PART_THREAD);
        partSolverScope.setRunnableThreadSemaphore(runnablePartThreadSemaphore);
        return new PartitionSolver<>(partTermination, bestSolutionRecaller, phaseList, partSolverScope);
    }

    protected void doStep(PartitionedSearchStepScope<Solution_> stepScope) {
        Move<Solution_> nextStep = stepScope.getStep();
        nextStep.doMove(stepScope.getScoreDirector());
        calculateWorkingStepScore(stepScope, nextStep);
        bestSolutionRecaller.processWorkingSolutionDuringStep(stepScope);
    }

    @Override
    public void phaseStarted(PartitionedSearchPhaseScope<Solution_> phaseScope) {
        super.phaseStarted(phaseScope);
    }

    @Override
    public void stepStarted(PartitionedSearchStepScope<Solution_> stepScope) {
        super.stepStarted(stepScope);
    }

    @Override
    public void stepEnded(PartitionedSearchStepScope<Solution_> stepScope) {
        super.stepEnded(stepScope);
        PartitionedSearchPhaseScope<Solution_> phaseScope = stepScope.getPhaseScope();
        if (logger.isDebugEnabled()) {
            logger.debug("{}    PS step ({}), time spent ({}), score ({}), {} best score ({}), picked move ({}).",
                    logIndentation,
                    stepScope.getStepIndex(),
                    phaseScope.calculateSolverTimeMillisSpentUpToNow(),
                    stepScope.getScore(),
                    (stepScope.getBestScoreImproved() ? "new" : "   "), phaseScope.getBestScore(),
                    stepScope.getStepString());
        }
    }

    @Override
    public void phaseEnded(PartitionedSearchPhaseScope<Solution_> phaseScope) {
        super.phaseEnded(phaseScope);
        phaseScope.endingNow();
        logger.info("{}Partitioned Search phase ({}) ended: time spent ({}), best score ({}),"
                + " score calculation speed ({}/sec), step total ({}), partCount ({}), runnablePartThreadLimit ({}).",
                logIndentation,
                phaseIndex,
                phaseScope.calculateSolverTimeMillisSpentUpToNow(),
                phaseScope.getBestScore(),
                phaseScope.getPhaseScoreCalculationSpeed(),
                phaseScope.getNextStepIndex(),
                phaseScope.getPartCount(),
                runnablePartThreadLimit);
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>rc.championship.platform</groupId>
    <artifactId>rc-championship-platform-parent</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>pom</packaging>

    <name>rc-championship-platform-parent</name>

    <repositories>
        <!--
        Repository hosting NetBeans modules, especially APIs.
        Versions are based on IDE releases, e.g.: RELEASE691
        To create your own repository, use: nbm:populate-repository
        -->
        <repository>
            <id>netbeans</id>
            <name>NetBeans</name>
            <url>http://bits.netbeans.org/nexus/content/groups/netbeans/</url>
        </repository>
    </repositories>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.12</version>
            </dependency>
            <dependency>
                <groupId>org.apache.commons</groupId>
                <artifactId>commons-lang3</artifactId>
                <version>3.3.2</version>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.codehaus.mojo</groupId>
                    <artifactId>nbm-maven-plugin</artifactId>
                    <version>3.14</version>
                    <extensions>true</extensions>
                    <configuration>
                        <brandingToken>${brandingToken}</brandingToken>
                        <cluster>${brandingToken}</cluster>
                    </configuration>
                </plugin>
                <plugin>
                    <!-- NetBeans 6.9+ requires JDK 6, starting NetBeans 7.4 source 1.7 is required -->
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.1</version>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                        <encoding>${project.build.sourceEncoding}</encoding>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-jar-plugin</artifactId>
                    <version>2.6</version>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>2.7</version>
                    <configuration>
                        <encoding>${project.build.sourceEncoding}</encoding>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.18.1</version>
                    <configuration>
                        <argLine>-Dfile.encoding=UTF-8</argLine>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>${project.build.sourceEncoding}</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <configuration>
                    <encoding>${project.build.sourceEncoding}</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <modules>
        <module>branding</module>
        <module>application</module>
        <module>rc-championship-practies</module>
        <module>rc-championship-api</module>
        <module>storage-h2-database</module>
        <module>rc-championship-decoders</module>
    </modules>

    <properties>
        <netbeans.version>RELEASE81</netbeans.version>
        <brandingToken>rcchampionshipplatform</brandingToken>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
</project>

redpajama_set_name: RedPajamaGithub


text:
package flex.messaging.services;

import java.util.EventListener;

/**
 * The listener interface for receiving <tt>AuthenticationEvent</tt>s.
 * <tt>AuthenticationListener</tt>s are registered with the <tt>AuthenticationService</tt>
 * and allow for custom post-processing of successful user login and logout events.
 */
public interface AuthenticationListener extends EventListener
{
    /**
     * Invoked after a user has successfully logged in.
     */
    void loginSucceeded(AuthenticationEvent event);

    /**
     * Invoked after a user has successfully logged out.
     */
    void logoutSucceeded(AuthenticationEvent event);
}


text:
- Objective: Advanced Gestures and Animations
- Hours: 12+
- Status: All required stories and optionals (sorta, full screen is buggy)

![GIF Walkthrough](/assets/hu-facebook-overview.gif)

#### Requirements
Static photo tiles on the initial screen
* [x] Tapping on a photo in the news feed should expand the photo full screen.
* [x] Tapping the Done button should animate the photo back into its position in the news feed.
* [x] On scroll of the full screen photo, the background should start to become transparent, revealing the feed.
* [x] If the user scrolls a large amount and releases, the full screen photo should dismiss.
* [x] Optional: The full screen photo should be zoomable. <--- this is super buggy due to scrollview paging
* [x] Optional: The user should be able to page through the other photos in full screen mode.

#### Acknowledegment
- Created with the help from the good folks at Codepath and mentors. Much <3 to Joe for sticking it out on Sat.
- GIF > Licecap http://www.cockos.com/licecap/

#### License
[MIT](LICENSE.md).


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="CategoryAttributeExample.cs" company="PropertyTools">
//   Copyright (c) 2014 PropertyTools contributors
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace ExampleLibrary
{
    [PropertyGridExample]
    public class CategoryAttributeExample : Example
    {
        [System.ComponentModel.Category("Tab1|Category1")]
        public string Name1 { get; set; }

        [System.ComponentModel.Category("Tab1|Category2")]
        public string Name2 { get; set; }

        [System.ComponentModel.Category("Tab2|Category3")]
        public string Name3 { get; set; }

        [PropertyTools.DataAnnotations.Category("Tab1|Category1 (PropertyTools.DataAnnotations)")]
        public string Name11 { get; set; }

        [PropertyTools.DataAnnotations.Category("Tab1|Category2 (PropertyTools.DataAnnotations)")]
        public string Name12 { get; set; }

        [PropertyTools.DataAnnotations.Category("Tab2|Category3 (PropertyTools.DataAnnotations)")]
        public string Name13 { get; set; }
    }
}


text:
package com.cinchapi.concourse.testsuite;

import org.junit.extensions.cpsuite.ClasspathSuite;
import org.junit.extensions.cpsuite.ClasspathSuite.ClassnameFilters;
import org.junit.runner.RunWith;

/**
 * Unit tests for the import package
 *
 * @author Jeff Nelson
 */
@RunWith(ClasspathSuite.class)
@ClassnameFilters({"com.cinchapi.concourse.importer.*"})
public class ImportTestSuite {

}


text:
use CrateCtxt;

use astconv::AstConv;
use check::{self, FnCtxt};
use middle::ty::{self, Ty, ToPolyTraitRef, ToPredicate, HasTypeFlags};
use middle::def;
use middle::lang_items::FnOnceTraitLangItem;
use middle::subst::Substs;
use middle::traits::{Obligation, SelectionContext};
use metadata::{csearch, cstore, decoder};

use syntax::{ast, ast_util};
use syntax::codemap::Span;
use syntax::print::pprust;

use std::cell;
use std::cmp::Ordering;

use super::{MethodError, NoMatchData, CandidateSource, impl_item, trait_item};
use super::probe::Mode;

pub fn report_error<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
                              span: Span,
                              rcvr_ty: Ty<'tcx>,
                              item_name: ast::Name,
                              rcvr_expr: Option<&ast::Expr>,
                              error: MethodError<'tcx>)
{
    // avoid suggestions when we don't know what's going on.
    if rcvr_ty.references_error() {
        return
    }

    match error {
        MethodError::NoMatch(NoMatchData { static_candidates: static_sources,
                                           unsatisfied_predicates,
                                           out_of_scope_traits,
                                           mode }) => {
            let cx = fcx.tcx();

            fcx.type_error_message(
                span,
                |actual| {
                    format!("no {} named `{}` found for type `{}` \
                             in the current scope",
                            if mode == Mode::MethodCall { "method" }
                            else { "associated item" },
                            item_name,
                            actual)
                },
                rcvr_ty,
                None);

            // If the item has the name of a field, give a help note
            if let (&ty::TyStruct(def, substs), Some(expr)) = (&rcvr_ty.sty, rcvr_expr) {
                if let Some(field) = def.struct_variant().find_field_named(item_name) {
                    let expr_string = match cx.sess.codemap().span_to_snippet(expr.span) {
                        Ok(expr_string) => expr_string,
                        _ => "s".into() // Default to a generic placeholder for the
                                        // expression when we can't generate a string
                                        // snippet
                    };

                    let span_stored_function = || {
                        cx.sess.span_note(span,
                                          &format!("use `({0}.{1})(...)` if you meant to call \
                                                    the function stored in the `{1}` field",
                                                   expr_string, item_name));
                    };

                    let span_did_you_mean = || {
                        cx.sess.span_note(span, &format!("did you mean to write `{0}.{1}`?",
                                                         expr_string, item_name));
                    };

                    // Determine if the field can be used as a function in some way
                    let field_ty = field.ty(cx, substs);
                    if let Ok(fn_once_trait_did) = cx.lang_items.require(FnOnceTraitLangItem) {
                        let infcx = fcx.infcx();
                        infcx.probe(|_| {
                            let fn_once_substs = Substs::new_trait(vec![infcx.next_ty_var()],
                                                                   Vec::new(),
                                                                   field_ty);
                            let trait_ref = ty::TraitRef::new(fn_once_trait_did,
                                                              cx.mk_substs(fn_once_substs));
                            let poly_trait_ref = trait_ref.to_poly_trait_ref();
                            let obligation = Obligation::misc(span,
                                                              fcx.body_id,
                                                              poly_trait_ref.to_predicate());
                            let mut selcx = SelectionContext::new(infcx);

                            if selcx.evaluate_obligation(&obligation) {
                                span_stored_function();
                            } else {
                                span_did_you_mean();
                            }
                        });
                    } else {
                        match field_ty.sty {
                            // fallback to matching a closure or function pointer
                            ty::TyClosure(..) | ty::TyBareFn(..) => span_stored_function(),
                            _ => span_did_you_mean(),
                        }
                    }
                }
            }

            if !static_sources.is_empty() {
                cx.sess.fileline_note(
                    span,
                    "found defined static methods, maybe a `self` is missing?");

                report_candidates(fcx, span, item_name, static_sources);
            }

            if !unsatisfied_predicates.is_empty() {
                let bound_list = unsatisfied_predicates.iter()
                    .map(|p| format!("`{} : {}`",
                                     p.self_ty(),
                                     p))
                    .collect::<Vec<_>>()
                    .join(", ");
                cx.sess.fileline_note(
                    span,
                    &format!("the method `{}` exists but the \
                             following trait bounds were not satisfied: {}",
                             item_name,
                             bound_list));
            }

            suggest_traits_to_import(fcx, span, rcvr_ty, item_name,
                                     rcvr_expr, out_of_scope_traits)
        }

        MethodError::Ambiguity(sources) => {
            span_err!(fcx.sess(), span, E0034,
                      "multiple applicable items in scope");

            report_candidates(fcx, span, item_name, sources);
        }

        MethodError::ClosureAmbiguity(trait_def_id) => {
            let msg = format!("the `{}` method from the `{}` trait cannot be explicitly \
                               invoked on this closure as we have not yet inferred what \
                               kind of closure it is",
                               item_name,
                               fcx.tcx().item_path_str(trait_def_id));
            let msg = if let Some(callee) = rcvr_expr {
                format!("{}; use overloaded call notation instead (e.g., `{}()`)",
                        msg, pprust::expr_to_string(callee))
            } else {
                msg
            };
            fcx.sess().span_err(span, &msg);
        }
    }

    fn report_candidates(fcx: &FnCtxt,
                         span: Span,
                         item_name: ast::Name,
                         mut sources: Vec<CandidateSource>) {
        sources.sort();
        sources.dedup();

        for (idx, source) in sources.iter().enumerate() {
            match *source {
                CandidateSource::ImplSource(impl_did) => {
                    // Provide the best span we can. Use the item, if local to crate, else
                    // the impl, if local to crate (item may be defaulted), else the call site.
                    let item = impl_item(fcx.tcx(), impl_did, item_name).unwrap();
                    let impl_span = fcx.tcx().map.def_id_span(impl_did, span);
                    let item_span = fcx.tcx().map.def_id_span(item.def_id(), impl_span);

                    let impl_ty = check::impl_self_ty(fcx, span, impl_did).ty;

                    let insertion = match fcx.tcx().impl_trait_ref(impl_did) {
                        None => format!(""),
                        Some(trait_ref) => {
                            format!(" of the trait `{}`",
                                    fcx.tcx().item_path_str(trait_ref.def_id))
                        }
                    };

                    span_note!(fcx.sess(), item_span,
                               "candidate #{} is defined in an impl{} for the type `{}`",
                               idx + 1,
                               insertion,
                               impl_ty);
                }
                CandidateSource::TraitSource(trait_did) => {
                    let item = trait_item(fcx.tcx(), trait_did, item_name).unwrap();
                    let item_span = fcx.tcx().map.def_id_span(item.def_id(), span);
                    span_note!(fcx.sess(), item_span,
                               "candidate #{} is defined in the trait `{}`",
                               idx + 1,
                               fcx.tcx().item_path_str(trait_did));
                }
            }
        }
    }
}

pub type AllTraitsVec = Vec<TraitInfo>;

fn suggest_traits_to_import<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
                                      span: Span,
                                      rcvr_ty: Ty<'tcx>,
                                      item_name: ast::Name,
                                      rcvr_expr: Option<&ast::Expr>,
                                      valid_out_of_scope_traits: Vec<ast::DefId>)
{
    let tcx = fcx.tcx();

    if !valid_out_of_scope_traits.is_empty() {
        let mut candidates = valid_out_of_scope_traits;
        candidates.sort();
        candidates.dedup();
        let msg = format!(
            "items from traits can only be used if the trait is in scope; \
             the following {traits_are} implemented but not in scope, \
             perhaps add a `use` for {one_of_them}:",
            traits_are = if candidates.len() == 1 {"trait is"} else {"traits are"},
            one_of_them = if candidates.len() == 1 {"it"} else {"one of them"});

        fcx.sess().fileline_help(span, &msg[..]);

        for (i, trait_did) in candidates.iter().enumerate() {
            fcx.sess().fileline_help(span,
                                     &*format!("candidate #{}: use `{}`",
                                               i + 1,
                                               fcx.tcx().item_path_str(*trait_did)))

        }
        return
    }

    let type_is_local = type_derefs_to_local(fcx, span, rcvr_ty, rcvr_expr);

    // there's no implemented traits, so lets suggest some traits to
    // implement, by finding ones that have the item name, and are
    // legal to implement.
    let mut candidates = all_traits(fcx.ccx)
        .filter(|info| {
            // we approximate the coherence rules to only suggest
            // traits that are legal to implement by requiring that
            // either the type or trait is local. Multidispatch means
            // this isn't perfect (that is, there are cases when
            // implementing a trait would be legal but is rejected
            // here).
            (type_is_local || ast_util::is_local(info.def_id))
                && trait_item(tcx, info.def_id, item_name).is_some()
        })
        .collect::<Vec<_>>();

    if !candidates.is_empty() {
        // sort from most relevant to least relevant
        candidates.sort_by(|a, b| a.cmp(b).reverse());
        candidates.dedup();

        // FIXME #21673 this help message could be tuned to the case
        // of a type parameter: suggest adding a trait bound rather
        // than implementing.
        let msg = format!(
            "items from traits can only be used if the trait is implemented and in scope; \
             the following {traits_define} an item `{name}`, \
             perhaps you need to implement {one_of_them}:",
            traits_define = if candidates.len() == 1 {"trait defines"} else {"traits define"},
            one_of_them = if candidates.len() == 1 {"it"} else {"one of them"},
            name = item_name);

        fcx.sess().fileline_help(span, &msg[..]);

        for (i, trait_info) in candidates.iter().enumerate() {
            fcx.sess().fileline_help(span,
                                     &*format!("candidate #{}: `{}`",
                                               i + 1,
                                               fcx.tcx().item_path_str(trait_info.def_id)))
        }
    }
}

/// Checks whether there is a local type somewhere in the chain of
/// autoderefs of `rcvr_ty`.
fn type_derefs_to_local<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
                                  span: Span,
                                  rcvr_ty: Ty<'tcx>,
                                  rcvr_expr: Option<&ast::Expr>) -> bool {
    fn is_local(ty: Ty) -> bool {
        match ty.sty {
            ty::TyEnum(def, _) | ty::TyStruct(def, _) => ast_util::is_local(def.did),

            ty::TyTrait(ref tr) => ast_util::is_local(tr.principal_def_id()),

            ty::TyParam(_) => true,

            // everything else (primitive types etc.) is effectively
            // non-local (there are "edge" cases, e.g. (LocalType,), but
            // the noise from these sort of types is usually just really
            // annoying, rather than any sort of help).
            _ => false
        }
    }

    // This occurs for UFCS desugaring of `T::method`, where there is no
    // receiver expression for the method call, and thus no autoderef.
    if rcvr_expr.is_none() {
        return is_local(fcx.resolve_type_vars_if_possible(rcvr_ty));
    }

    check::autoderef(fcx, span, rcvr_ty, None,
                     check::UnresolvedTypeAction::Ignore, check::NoPreference,
                     |ty, _| {
        if is_local(ty) {
            Some(())
        } else {
            None
        }
    }).2.is_some()
}

#[derive(Copy, Clone)]
pub struct TraitInfo {
    pub def_id: ast::DefId,
}

impl TraitInfo {
    fn new(def_id: ast::DefId) -> TraitInfo {
        TraitInfo {
            def_id: def_id,
        }
    }
}
impl PartialEq for TraitInfo {
    fn eq(&self, other: &TraitInfo) -> bool {
        self.cmp(other) == Ordering::Equal
    }
}
impl Eq for TraitInfo {}
impl PartialOrd for TraitInfo {
    fn partial_cmp(&self, other: &TraitInfo) -> Option<Ordering> { Some(self.cmp(other)) }
}
impl Ord for TraitInfo {
    fn cmp(&self, other: &TraitInfo) -> Ordering {
        // accessible traits are more important/relevant than
        // inaccessible ones, local crates are more important than
        // remote ones (local: cnum == 0), and NodeIds just for
        // totality.

        let lhs = (other.def_id.krate, other.def_id.node);
        let rhs = (self.def_id.krate, self.def_id.node);
        lhs.cmp(&rhs)
    }
}

/// Retrieve all traits in this crate and any dependent crates.
pub fn all_traits<'a>(ccx: &'a CrateCtxt) -> AllTraits<'a> {
    if ccx.all_traits.borrow().is_none() {
        use syntax::visit;

        let mut traits = vec![];

        // Crate-local:
        //
        // meh.
        struct Visitor<'a> {
            traits: &'a mut AllTraitsVec,
        }
        impl<'v, 'a> visit::Visitor<'v> for Visitor<'a> {
            fn visit_item(&mut self, i: &'v ast::Item) {
                match i.node {
                    ast::ItemTrait(..) => {
                        self.traits.push(TraitInfo::new(ast_util::local_def(i.id)));
                    }
                    _ => {}
                }
                visit::walk_item(self, i)
            }
        }
        visit::walk_crate(&mut Visitor {
            traits: &mut traits
        }, ccx.tcx.map.krate());

        // Cross-crate:
        fn handle_external_def(traits: &mut AllTraitsVec,
                               ccx: &CrateCtxt,
                               cstore: &cstore::CStore,
                               dl: decoder::DefLike) {
            match dl {
                decoder::DlDef(def::DefTrait(did)) => {
                    traits.push(TraitInfo::new(did));
                }
                decoder::DlDef(def::DefMod(did)) => {
                    csearch::each_child_of_item(cstore, did, |dl, _, _| {
                        handle_external_def(traits, ccx, cstore, dl)
                    })
                }
                _ => {}
            }
        }
        let cstore = &ccx.tcx.sess.cstore;
        cstore.iter_crate_data(|cnum, _| {
            csearch::each_top_level_item_of_crate(cstore, cnum, |dl, _, _| {
                handle_external_def(&mut traits, ccx, cstore, dl)
            })
        });

        *ccx.all_traits.borrow_mut() = Some(traits);
    }

    let borrow = ccx.all_traits.borrow();
    assert!(borrow.is_some());
    AllTraits {
        borrow: borrow,
        idx: 0
    }
}

pub struct AllTraits<'a> {
    borrow: cell::Ref<'a, Option<AllTraitsVec>>,
    idx: usize
}

impl<'a> Iterator for AllTraits<'a> {
    type Item = TraitInfo;

    fn next(&mut self) -> Option<TraitInfo> {
        let AllTraits { ref borrow, ref mut idx } = *self;
        // ugh.
        borrow.as_ref().unwrap().get(*idx).map(|info| {
            *idx += 1;
            *info
        })
    }
}


text:
namespace IronSmarkets.Clients
{
    public interface IAsyncHttpFoundHandler<T>
    {
        void BeginFetchHttpFound(ISyncRequest<T> syncRequest, Proto.Seto.Payload payload);
        void SetClient(ISmarketsClient client);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/pop_layout"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@color/background_normal"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    android:paddingBottom="10dip"
    >

    <include layout="@layout/include_fillparent_line" />

    <!-- <Button
        android:id="@+id/btn_set_cover"
        style="@style/PopupWindow_btn_style"
        android:background="@drawable/blue_btn_selector"
        android:text="设为封面" />

    <Button
        android:id="@+id/btn_take_photo"
        style="@style/PopupWindow_btn_style"
        android:background="@drawable/blue_btn_selector"
        android:text="拍照" />

    <Button
        android:id="@+id/btn_pick_photo"
        style="@style/PopupWindow_btn_style"
        android:background="@drawable/blue_btn_selector"
        android:text="相册选择" />

    <Button
        android:id="@+id/btn_delete"
        style="@style/PopupWindow_btn_style"
        android:background="@drawable/red_btn_selector"
        android:text="删除头像" /> -->

</LinearLayout>


text:
package example.repo;

import example.model.Customer1811;

import java.util.List;

import org.springframework.data.repository.CrudRepository;

public interface Customer1811Repository extends CrudRepository<Customer1811, Long> {

	List<Customer1811> findByLastName(String lastName);
}


text:
namespace base {
class DictionaryValue;
class ListValue;
}

namespace WebKit {
class WebFrame;
}

namespace content {
class Shell;
}

namespace nwapi {

class Base;

class DispatcherHost : public content::WebContentsObserver {
 public:
  explicit DispatcherHost(content::RenderViewHost* render_view_host);
  virtual ~DispatcherHost();

  // Get C++ object from its id.
  static Base* GetApiObject(int id);

  static int AllocateId();

  // Helper function to convert type.
  template<class T>
  static T* GetApiObject(int id) {
    return static_cast<T*>(GetApiObject(id));
  }

  static void ClearObjectRegistry();

  // Send event to C++ object's corresponding js object.
  void SendEvent(Base* object,
                 const std::string& event,
                 const base::ListValue& arguments);

  virtual bool Send(IPC::Message* message) OVERRIDE;
  virtual void RenderViewHostChanged(content::RenderViewHost* old_host,
                                     content::RenderViewHost* new_host) OVERRIDE;
  content::RenderViewHost* render_view_host() const {
    return render_view_host_;
  }

 private:
  content::RenderViewHost* render_view_host_;
  friend class content::Shell;

  static IDMap<Base, IDMapOwnPointer> objects_registry_;
  static int next_object_id_;

  std::set<int> objects_;

  // Factory to generate weak pointer
  base::WeakPtrFactory<DispatcherHost> weak_ptr_factory_;

  // RenderViewHostObserver implementation.
  // WebContentsObserver implementation:
  virtual bool OnMessageReceived(content::RenderViewHost* render_view_host, const IPC::Message& message) OVERRIDE;

  void OnAllocateObject(int object_id,
                        const std::string& type,
                        const base::DictionaryValue& option);
  void OnDeallocateObject(int object_id);
  void OnCallObjectMethod(int object_id,
                          const std::string& type,
                          const std::string& method,
                          const base::ListValue& arguments);
  void OnCallObjectMethodSync(int object_id,
                              const std::string& type,
                              const std::string& method,
                              const base::ListValue& arguments,
                              base::ListValue* result);
  void OnCallStaticMethod(const std::string& type,
                          const std::string& method,
                          const base::ListValue& arguments);
  void OnCallStaticMethodSync(const std::string& type,
                              const std::string& method,
                              const base::ListValue& arguments,
                              base::ListValue* result);
  void OnUncaughtException(const std::string& err);
  void OnGetShellId(int* id);
  void OnCreateShell(const std::string& url,
                     const base::DictionaryValue& manifest,
                     int* routing_id);
  void OnAllocateId(int* ret);
  void OnSetForceClose(bool force, int* ret);

  DISALLOW_COPY_AND_ASSIGN(DispatcherHost);
};

nwapi::DispatcherHost* FindDispatcherHost(content::RenderViewHost* render_view_host);

}  // namespace nwapi

#endif  // CONTENT_NW_SRC_API_DISPATCHER_HOST_H_


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

<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=utf-8">
<TITLE>
Ruby Scripting
</TITLE>

Ruby Scripting

	The Ruby Scripting add-on allows you to integrate Ruby scripts in ZAP.

	It's bundled JRuby 1.7.4.

	When you create a new script you will be given the option to use Ruby, as well as the option to choose from various Ruby templates.


text:
package com.cloudant.client.cache.tests.redis;

import com.cloudant.client.cache.redis.RedisCache;
import com.cloudant.client.cache.tests.DatabaseCacheTests;

public class DatabaseRedisCacheTests extends DatabaseCacheTests {

    @Override
    protected RedisCache<String, Object> getNewCacheInstance() {
        return new RedisCache<>("localhost", 6379, 60, CACHE_LIFETIME);
    }
}


text: Check this if you want to search for the version in the remote file path instead of the file content.


text:
package org.apache.commons.configuration2.interpol;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

import org.apache.commons.lang3.text.StrLookup;
import org.apache.commons.lang3.text.StrSubstitutor;

/**
 *

 * A class that handles interpolation (variable substitution) for configuration
 * objects.
 *

 *

 * Each instance of {@code AbstractConfiguration} is associated with an object
 * of this class. All interpolation tasks are delegated to this object.
 *

 *

 * {@code ConfigurationInterpolator} internally uses the {@code StrSubstitutor}
 * class from Commons Lang. Thus it
 * supports the same syntax of variable expressions.
 *

 *

 * The basic idea of this class is that it can maintain a set of primitive
 * {@link Lookup} objects, each of which is identified by a special prefix. The
 * variables to be processed have the form ${prefix:name}.
 * {@code ConfigurationInterpolator} will extract the prefix and determine,
 * which primitive lookup object is registered for it. Then the name of the
 * variable is passed to this object to obtain the actual value. It is also
 * possible to define an arbitrary number of default lookup objects, which are
 * used for variables that do not have a prefix or that cannot be resolved by
 * their associated lookup object. When adding default lookup objects their
 * order matters; they are queried in this order, and the first non-null
 * variable value is used.
 *

 *

 * After an instance has been created it does not contain any {@code Lookup}
 * objects. The current set of lookup objects can be modified using the
 * {@code registerLookup()} and {@code deregisterLookup()} methods. Default
 * lookup objects (that are invoked for variables without a prefix) can be added
 * or removed with the {@code addDefaultLookup()} and
 * {@code removeDefaultLookup()} methods respectively. (When a
 * {@code ConfigurationInterpolator} instance is created by a configuration
 * object, a default lookup object is added pointing to the configuration
 * itself, so that variables are resolved using the configuration's properties.)
 *

 *

 * The default usage scenario is that on a fully initialized instance the
 * {@code interpolate()} method is called. It is passed an object value which
 * may contain variables. All these variables are substituted if they can be
 * resolved. The result is the passed in value with variables replaced.
 * Alternatively, the {@code resolve()} method can be called to obtain the
 * values of specific variables without performing interpolation.
 *

 *

 * Implementation node: This class is thread-safe. Lookup objects can be added
 * or removed at any time concurrent to interpolation operations.
 *

 *
 * @version $Id$
 * @since 1.4
 * @author Commons
 *         Configuration team
 */
public class ConfigurationInterpolator
{
    /** Constant for the prefix separator. */
    private static final char PREFIX_SEPARATOR = ':';

    /** A map containing the default prefix lookups. */
    private static final Map<String, Lookup> DEFAULT_PREFIX_LOOKUPS;

    /** A map with the currently registered lookup objects. */
    private final Map<String, Lookup> prefixLookups;

    /** Stores the default lookup objects. */
    private final List<Lookup> defaultLookups;

    /** The helper object performing variable substitution. */
    private final StrSubstitutor substitutor;

    /** Stores a parent interpolator objects if the interpolator is nested hierarchically. */
    private volatile ConfigurationInterpolator parentInterpolator;

    /**
     * Creates a new instance of {@code ConfigurationInterpolator}.
     */
    public ConfigurationInterpolator()
    {
        prefixLookups = new ConcurrentHashMap<String, Lookup>();
        defaultLookups = new CopyOnWriteArrayList<Lookup>();
        substitutor = initSubstitutor();
    }

    /**
     * Creates a new {@code ConfigurationInterpolator} instance based on the
     * passed in specification object. If the {@code InterpolatorSpecification}
     * already contains a {@code ConfigurationInterpolator} object, it is used
     * directly. Otherwise, a new instance is created and initialized with the
     * properties stored in the specification.
     *
     * @param spec the {@code InterpolatorSpecification} (must not be
     *        null)
     * @return the {@code ConfigurationInterpolator} obtained or created based
     *         on the given specification
     * @throws IllegalArgumentException if the specification is null
     * @since 2.0
     */
    public static ConfigurationInterpolator fromSpecification(
            InterpolatorSpecification spec)
    {
        if (spec == null)
        {
            throw new IllegalArgumentException(
                    "InterpolatorSpecification must not be null!");
        }
        return (spec.getInterpolator() != null) ? spec.getInterpolator()
                : createInterpolator(spec);
    }

    /**
     * Returns a map containing the default prefix lookups. Every configuration
     * object derived from {@code AbstractConfiguration} is by default
     * initialized with a {@code ConfigurationInterpolator} containing these
     * {@code Lookup} objects and their prefixes. The map cannot be modified
     *
     * @return a map with the default prefix {@code Lookup} objects and their
     *         prefixes
     * @since 2.0
     */
    public static Map<String, Lookup> getDefaultPrefixLookups()
    {
        return DEFAULT_PREFIX_LOOKUPS;
    }

    /**
     * Utility method for obtaining a {@code Lookup} object in a safe way. This
     * method always returns a non-null {@code Lookup} object. If the
     * passed in {@code Lookup} is not null, it is directly returned.
     * Otherwise, result is a dummy {@code Lookup} which does not provide any
     * values.
     *
     * @param lookup the {@code Lookup} to check
     * @return a non-null {@code Lookup} object
     * @since 2.0
     */
    public static Lookup nullSafeLookup(Lookup lookup)
    {
        if (lookup == null)
        {
            lookup = DummyLookup.INSTANCE;
        }
        return lookup;
    }

    /**
     * Returns a map with the currently registered {@code Lookup} objects and
     * their prefixes. This is a snapshot copy of the internally used map. So
     * modifications of this map do not effect this instance.
     *
     * @return a copy of the map with the currently registered {@code Lookup}
     *         objects
     */
    public Map<String, Lookup> getLookups()
    {
        return new HashMap<String, Lookup>(prefixLookups);
    }

    /**
     * Registers the given {@code Lookup} object for the specified prefix at
     * this instance. From now on this lookup object will be used for variables
     * that have the specified prefix.
     *
     * @param prefix the variable prefix (must not be null)
     * @param lookup the {@code Lookup} object to be used for this prefix (must
     *        not be null)
     * @throws IllegalArgumentException if either the prefix or the
     *         {@code Lookup} object is null
     */
    public void registerLookup(String prefix, Lookup lookup)
    {
        if (prefix == null)
        {
            throw new IllegalArgumentException(
                    "Prefix for lookup object must not be null!");
        }
        if (lookup == null)
        {
            throw new IllegalArgumentException(
                    "Lookup object must not be null!");
        }
        prefixLookups.put(prefix, lookup);
    }

    /**
     * Registers all {@code Lookup} objects in the given map with their prefixes
     * at this {@code ConfigurationInterpolator}. Using this method multiple
     * {@code Lookup} objects can be registered at once. If the passed in map is
     * null, this method does not have any effect.
     *
     * @param lookups the map with lookups to register (may be null)
     * @throws IllegalArgumentException if the map contains entries
     */
    public void registerLookups(Map<String, ? extends Lookup> lookups)
    {
        if (lookups != null)
        {
            prefixLookups.putAll(lookups);
        }
    }

    /**
     * Deregisters the {@code Lookup} object for the specified prefix at this
     * instance. It will be removed from this instance.
     *
     * @param prefix the variable prefix
     * @return a flag whether for this prefix a lookup object had been
     *         registered
     */
    public boolean deregisterLookup(String prefix)
    {
        return prefixLookups.remove(prefix) != null;
    }

    /**
     * Returns an unmodifiable set with the prefixes, for which {@code Lookup}
     * objects are registered at this instance. This means that variables with
     * these prefixes can be processed.
     *
     * @return a set with the registered variable prefixes
     */
    public Set<String> prefixSet()
    {
        return Collections.unmodifiableSet(prefixLookups.keySet());
    }

    /**
     * Returns a collection with the default {@code Lookup} objects
     * added to this {@code ConfigurationInterpolator}. These objects are not
     * associated with a variable prefix. The returned list is a snapshot copy
     * of the internal collection of default lookups; so manipulating it does
     * not affect this instance.
     *
     * @return the default lookup objects
     */
    public List<Lookup> getDefaultLookups()
    {
        return new ArrayList<Lookup>(defaultLookups);
    }

    /**
     * Adds a default {@code Lookup} object. Default {@code Lookup} objects are
     * queried (in the order they were added) for all variables without a
     * special prefix. If no default {@code Lookup} objects are present, such
     * variables won't be processed.
     *
     * @param defaultLookup the default {@code Lookup} object to be added (must
     *        not be null)
     * @throws IllegalArgumentException if the {@code Lookup} object is
     *         null
     */
    public void addDefaultLookup(Lookup defaultLookup)
    {
        defaultLookups.add(defaultLookup);
    }

    /**
     * Adds all {@code Lookup} objects in the given collection as default
     * lookups. The collection can be null, then this method has no
     * effect. It must not contain null entries.
     *
     * @param lookups the {@code Lookup} objects to be added as default lookups
     * @throws IllegalArgumentException if the collection contains a null
     *         entry
     */
    public void addDefaultLookups(Collection<? extends Lookup> lookups)
    {
        if (lookups != null)
        {
            defaultLookups.addAll(lookups);
        }
    }

    /**
     * Removes the specified {@code Lookup} object from the list of default
     * {@code Lookup}s.
     *
     * @param lookup the {@code Lookup} object to be removed
     * @return a flag whether this {@code Lookup} object actually existed and
     *         was removed
     */
    public boolean removeDefaultLookup(Lookup lookup)
    {
        return defaultLookups.remove(lookup);
    }

    /**
     * Sets the parent {@code ConfigurationInterpolator}. This object is used if
     * the {@code Lookup} objects registered at this object cannot resolve a
     * variable.
     *
     * @param parentInterpolator the parent {@code ConfigurationInterpolator}
     *        object (can be null)
     */
    public void setParentInterpolator(
            ConfigurationInterpolator parentInterpolator)
    {
        this.parentInterpolator = parentInterpolator;
    }

    /**
     * Returns the parent {@code ConfigurationInterpolator}.
     *
     * @return the parent {@code ConfigurationInterpolator} (can be null)
     */
    public ConfigurationInterpolator getParentInterpolator()
    {
        return this.parentInterpolator;
    }

    /**
     * Sets a flag that variable names can contain other variables. If enabled,
     * variable substitution is also done in variable names.
     *
     * @return the substitution in variables flag
     */
    public boolean isEnableSubstitutionInVariables()
    {
        return substitutor.isEnableSubstitutionInVariables();
    }

    /**
     * Sets the flag whether variable names can contain other variables. This
     * flag corresponds to the {@code enableSubstitutionInVariables} property of
     * the underlying {@code StrSubstitutor} object.
     *
     * @param f the new value of the flag
     */
    public void setEnableSubstitutionInVariables(boolean f)
    {
        substitutor.setEnableSubstitutionInVariables(f);
    }

    /**
     * Performs interpolation of the passed in value. If the value is of type
     * String, this method checks whether it contains variables. If so, all
     * variables are replaced by their current values (if possible). For non
     * string arguments, the value is returned without changes.
     *
     * @param value the value to be interpolated
     * @return the interpolated value
     */
    public Object interpolate(Object value)
    {
        if (value instanceof String)
        {
            return substitutor.replace((String) value);
        }
        return value;
    }

    /**
     * Resolves the specified variable. This implementation tries to extract
     * a variable prefix from the given variable name (the first colon (':') is
     * used as prefix separator). It then passes the name of the variable with
     * the prefix stripped to the lookup object registered for this prefix. If
     * no prefix can be found or if the associated lookup object cannot resolve
     * this variable, the default lookup objects are used. If this is not
     * successful either and a parent {@code ConfigurationInterpolator} is
     * available, this object is asked to resolve the variable.
     *
     * @param var the name of the variable whose value is to be looked up
     * @return the value of this variable or null if it cannot be
     * resolved
     */
    public Object resolve(String var)
    {
        if (var == null)
        {
            return null;
        }

        int prefixPos = var.indexOf(PREFIX_SEPARATOR);
        if (prefixPos >= 0)
        {
            String prefix = var.substring(0, prefixPos);
            String name = var.substring(prefixPos + 1);
            Object value = fetchLookupForPrefix(prefix).lookup(name);
            if (value != null)
            {
                return value;
            }
        }

        for (Lookup l : defaultLookups)
        {
            Object value = l.lookup(var);
            if (value != null)
            {
                return value;
            }
        }

        ConfigurationInterpolator parent = getParentInterpolator();
        if (parent != null)
        {
            return getParentInterpolator().resolve(var);
        }
        return null;
    }

    /**
     * Obtains the lookup object for the specified prefix. This method is called
     * by the {@code lookup()} method. This implementation will check
     * whether a lookup object is registered for the given prefix. If not, a
     * null lookup object will be returned (never null).
     *
     * @param prefix the prefix
     * @return the lookup object to be used for this prefix
     */
    protected Lookup fetchLookupForPrefix(String prefix)
    {
        return nullSafeLookup(prefixLookups.get(prefix));
    }

    /**
     * Creates and initializes a {@code StrSubstitutor} object which is used for
     * variable substitution. This {@code StrSubstitutor} is assigned a
     * specialized lookup object implementing the correct variable resolving
     * algorithm.
     *
     * @return the {@code StrSubstitutor} used by this object
     */
    private StrSubstitutor initSubstitutor()
    {
        return new StrSubstitutor(new StrLookup<Object>()
        {
            @Override
            public String lookup(String key)
            {
                Object result = resolve(key);
                return (result != null) ? result.toString() : null;
            }
        });
    }

    /**
     * Creates a new instance based on the properties in the given specification
     * object.
     *
     * @param spec the {@code InterpolatorSpecification}
     * @return the newly created instance
     */
    private static ConfigurationInterpolator createInterpolator(
            InterpolatorSpecification spec)
    {
        ConfigurationInterpolator ci = new ConfigurationInterpolator();
        ci.addDefaultLookups(spec.getDefaultLookups());
        ci.registerLookups(spec.getPrefixLookups());
        ci.setParentInterpolator(spec.getParentInterpolator());
        return ci;
    }

    static
    {
        Map<String, Lookup> lookups = new HashMap<String, Lookup>();
        for (DefaultLookups l : DefaultLookups.values())
        {
            lookups.put(l.getPrefix(), l.getLookup());
        }
        DEFAULT_PREFIX_LOOKUPS = Collections.unmodifiableMap(lookups);
    }
}


text:
actions :create
default_action :create

attribute :name, kind_of: String, name_attribute: true
attribute :port_group, kind_of: String
attribute :source, kind_of: String
attribute :options, kind_of: Hash
attribute :full_path, kind_of: String
attribute :default_options, kind_of: Hash, default: {}
attribute :current_options, kind_of: Hash, default: {}
attribute :file_writer, kind_of: String

def initialize(*args)
  super
	if not port_group.nil?
		@full_path = "/var/db/ports/#{port_group}_#{name}/options" # don't think this works
	else
		@full_path = "/var/db/ports/#{name}/options"
	end
end


text:
<?php

namespace UTBM\ArticleDevBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * QuestionRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class QuestionRepository extends EntityRepository
{
    /**
     *  Récupère les questions ainsi que les propositon de réponses appartenant au sous menus courrant
     */
    public function getQuestions($idSC){

        $query = $this->createQueryBuilder('q')
                      ->leftJoin('q.subCategory', 'sc')
                        ->addSelect('sc')
                      ->where("sc.id = :id")
                     // ->setMaxResults(3)
                      ->setParameter('id', $idSC)
                      ->getQuery();
        return $query->getResult();
    }
}


text:
"use strict";
var inherits = require('util').inherits;
var Token = require('./core').Token;

var Expression = function (ctx, expression, toBeEscaped) {
	this.ctx = ctx;
	this.expression = expression;
	this.toBeEscaped = toBeEscaped;
};
inherits(Expression, Token);

Expression.prototype.visitGenerator = function (generator) {
	generator.onExpressionToken(this);
};

module.exports = Expression;


text:
from rest_framework_extensions.routers import ExtendedSimpleRouter

from .views import (
    UserViewSetWithEmailLookup,
    GroupViewSet,
)

router = ExtendedSimpleRouter()
# main routes
(
    router.register(r'users', UserViewSetWithEmailLookup)
          .register(r'groups', GroupViewSet, 'users-group', parents_query_lookups=['user_groups__email'])
)

urlpatterns = router.urls


text:
package org.apache.jackrabbit.oak.spi.security.authorization.cug.impl;

import java.util.ArrayList;
import java.util.List;
import javax.annotation.Nonnull;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import org.apache.jackrabbit.JcrConstants;
import org.apache.jackrabbit.oak.api.ContentSession;
import org.apache.jackrabbit.oak.api.PropertyState;
import org.apache.jackrabbit.oak.api.Root;
import org.apache.jackrabbit.oak.api.Tree;
import org.apache.jackrabbit.oak.api.Type;
import org.apache.jackrabbit.oak.commons.PathUtils;
import org.apache.jackrabbit.oak.namepath.NamePathMapper;
import org.apache.jackrabbit.oak.plugins.identifier.IdentifierManager;
import org.apache.jackrabbit.oak.spi.nodetype.NodeTypeConstants;
import org.apache.jackrabbit.oak.plugins.tree.TreeType;
import org.apache.jackrabbit.oak.plugins.version.ReadOnlyVersionManager;
import org.apache.jackrabbit.oak.spi.version.VersionConstants;
import org.apache.jackrabbit.oak.spi.security.authorization.permission.Permissions;
import org.apache.jackrabbit.oak.spi.security.authorization.permission.TreePermission;
import org.apache.jackrabbit.oak.spi.security.principal.EveryonePrincipal;
import org.apache.jackrabbit.oak.plugins.tree.TreeUtil;
import org.junit.Before;
import org.junit.Test;

import static com.google.common.base.Preconditions.checkNotNull;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;

/**
 * Test read access to version related information both in the regular
 * content and in the version storage.
 */
public class VersionTest extends AbstractCugTest implements NodeTypeConstants, VersionConstants {

    private ContentSession testSession;
    private Root testRoot;
    private ReadOnlyVersionManager versionManager;

    private List<String> readAccess = new ArrayList<String>();
    private List<String> noReadAccess = new ArrayList<String>();

    @Before
    @Override
    public void before() throws Exception {
        super.before();

        // create cugs
        // - /content/a     : allow testGroup, deny everyone
        // - /content/aa/bb : allow testGroup, deny everyone
        // - /content/a/b/c : allow everyone,  deny testGroup (isolated)
        // - /content2      : allow everyone,  deny testGroup (isolated)
        setupCugsAndAcls();

        readAccess = ImmutableList.of(
                SUPPORTED_PATH,
                "/content/subtree",
                "/content/aa");

        noReadAccess = ImmutableList.of(
                UNSUPPORTED_PATH,  /* no access */
                "/content2",       /* granted by cug only */
                "/content/a",      /* granted by ace, denied by cug */
                "/content/aa/bb"   /* granted by ace, denied by cug */
        );

        for (String path : Iterables.concat(readAccess, noReadAccess)) {
            addVersionContent(path);
        }

        testSession = createTestSession();
        testRoot = testSession.getLatestRoot();

        versionManager = ReadOnlyVersionManager.getInstance(root, NamePathMapper.DEFAULT);
    }

    @Override
    public void after() throws Exception {
        try {
            if (testSession != null) {
                testSession.close();
            }
        } finally {
            super.after();
        }
    }

    private Tree addVersionContent(@Nonnull String path) throws Exception {
        Tree t = root.getTree(path);

        Tree typesRoot = root.getTree(NodeTypeConstants.NODE_TYPES_PATH);
        TreeUtil.addMixin(t, JcrConstants.MIX_VERSIONABLE, typesRoot, null);
        root.commit();

        // force the creation of a version with frozen node
        t.setProperty(JCR_ISCHECKEDOUT, false);
        root.commit();
        t.setProperty(JCR_ISCHECKEDOUT, true);
        root.commit();

        if (testRoot != null) {
            testRoot.refresh();
        }

        return t;
    }

    @Test
    public void testReadVersionContent() throws Exception {
        IdentifierManager idMgr = new IdentifierManager(testRoot);
        ReadOnlyVersionManager vMgr = ReadOnlyVersionManager.getInstance(testRoot, NamePathMapper.DEFAULT);

        for (String path : readAccess) {
            Tree t = testRoot.getTree(path);
            assertTrue(path, t.exists());

            PropertyState ps = t.getProperty(JCR_VERSIONHISTORY);
            assertNotNull(ps);

            String vhUUID = ps.getValue(Type.STRING);
            assertEquals(vhUUID, ps.getValue(Type.STRING));

            Tree versionHistory = vMgr.getVersionHistory(t);
            assertNotNull(versionHistory);
            assertTrue(versionHistory.exists());
            assertTrue(versionHistory.getChild(JCR_ROOTVERSION).exists());
            assertFalse(versionHistory.getParent().exists());

            Tree vhTree = testRoot.getTree(versionHistory.getPath());
            assertTrue(vhTree.exists());

            String vhPath = idMgr.resolveUUID(vhUUID);
            assertNotNull(vhPath);

            assertEquals(versionHistory.getPath(), vhPath);
            assertTrue(testRoot.getTree(vhPath).exists());

            assertTrue(testRoot.getTree(vhPath + '/' + JCR_ROOTVERSION).exists());
        }
    }

    @Test
    public void testReadVersionContentNoAccess() throws Exception {
        IdentifierManager idMgr = new IdentifierManager(testRoot);

        for (String path : noReadAccess) {
            String vhUUID = checkNotNull(TreeUtil.getString(root.getTree(path), JCR_VERSIONHISTORY));
            String vhPath = PathUtils.concat(VERSION_STORE_PATH, versionManager.getVersionHistoryPath(vhUUID));

            Tree vHistory = testRoot.getTree(vhPath);
            assertFalse(vHistory.exists());
            assertFalse(vHistory.getParent().exists());
            assertFalse(vHistory.getChild(JCR_ROOTVERSION).exists());
            assertFalse(testRoot.getTree(vhPath + '/' + JCR_ROOTVERSION).exists());

            String vh = idMgr.resolveUUID(vhUUID);
            assertNull(path, vh);
        }
    }

    @Test
    public void testReadVersionStorage() {
        assertFalse(testRoot.getTree(VersionConstants.VERSION_STORE_PATH).exists());
    }

    @Test
    public void testSupportedPermissions() throws Exception {
        Tree versionable = addVersionContent("/content/a/b/c");

        CugPermissionProvider pp = createCugPermissionProvider(ImmutableSet.of(SUPPORTED_PATH, SUPPORTED_PATH2));

        Tree versionStorage = root.getTree(VersionConstants.VERSION_STORE_PATH);
        assertEquals(Permissions.NO_PERMISSION, pp.supportedPermissions(versionStorage, null, Permissions.READ));
        assertEquals(Permissions.NO_PERMISSION, pp.supportedPermissions(versionStorage.getParent(), null, Permissions.READ));

        // tree with cug (access is granted)
        Tree vh = versionManager.getVersionHistory(versionable);
        assertEquals(Permissions.READ, pp.supportedPermissions(vh, null, Permissions.READ));

        // tree with cug (but no access granted)
        vh = versionManager.getVersionHistory(root.getTree("/content2"));
        assertEquals(Permissions.READ, pp.supportedPermissions(vh, null, Permissions.READ));

        // tree without cug
        vh = versionManager.getVersionHistory(root.getTree(UNSUPPORTED_PATH));
        assertEquals(Permissions.NO_PERMISSION, pp.supportedPermissions(vh, null, Permissions.READ));

        // tree without cug
        vh = versionManager.getVersionHistory(root.getTree(SUPPORTED_PATH));
        assertEquals(Permissions.NO_PERMISSION, pp.supportedPermissions(vh, null, Permissions.READ));
    }

    @Test
    public void testVersionableRemoved() throws Exception {
        // cug at /content/a/b/c grants access
        Tree versionable = addVersionContent("/content/a/b/c");

        Tree vh = checkNotNull(versionManager.getVersionHistory(versionable));

        assertTrue(testRoot.getTree(vh.getPath()).exists());

        versionable.remove();
        root.commit();

        // the cug-permission provider still supports the path as there exists
        // a cug higher up in the hierarchy
        // -> the parent cug takes effect now
        CugPermissionProvider pp = createCugPermissionProvider(ImmutableSet.of(SUPPORTED_PATH, SUPPORTED_PATH2));
        assertEquals(Permissions.READ, pp.supportedPermissions(vh, null, Permissions.READ));
        assertFalse(pp.isGranted(vh, null, Permissions.READ));

        // the vh associated with /content/a/b/c is no longer accessible
        testRoot.refresh();
        assertFalse(testRoot.getTree(vh.getPath()).exists());
    }

    @Test
    public void testVersionableRemoved2() throws Exception {
        // cug at /content/a/b/c denies access
        Tree versionable = root.getTree("/content/a");

        Tree vh = checkNotNull(versionManager.getVersionHistory(versionable));

        assertFalse(testRoot.getTree(vh.getPath()).exists());

        versionable.remove();
        root.commit();

        // removing this versionable node removes the CUG in this tree
        // -> the permission provider is no longer responsible
        CugPermissionProvider pp = createCugPermissionProvider(ImmutableSet.of(SUPPORTED_PATH, SUPPORTED_PATH2));
        assertEquals(Permissions.NO_PERMISSION, pp.supportedPermissions(vh, null, Permissions.READ));
        assertFalse(pp.isGranted(vh, null, Permissions.READ));

        // subsequently the deny of the former CUG is gone as well
        testRoot.refresh();
        assertTrue(testRoot.getTree(vh.getPath()).exists());
    }

    @Test
    public void testTreePermissionVersionable() throws Exception {
        Tree versionable = root.getTree("/content/a");
        Tree vh = checkNotNull(versionManager.getVersionHistory(versionable));

        CugPermissionProvider pp = createCugPermissionProvider(ImmutableSet.of(SUPPORTED_PATH, SUPPORTED_PATH2), EveryonePrincipal.getInstance());

        Tree t = root.getTree("/");
        TreePermission tp = pp.getTreePermission(t, TreePermission.EMPTY);

        String path = PathUtils.concat(vh.getPath(), "1.0", JCR_FROZENNODE, "b/c");
        for (String segm : PathUtils.elements(path)) {
            t = t.getChild(segm);
            tp = pp.getTreePermission(t, tp);

            if (JCR_SYSTEM.equals(segm) || ReadOnlyVersionManager.isVersionStoreTree(t)) {
                assertTrue(t.getPath(), tp instanceof EmptyCugTreePermission);
            } else {
                assertTrue(t.getPath(), tp instanceof CugTreePermission);
                assertEquals(t.getPath(), "c".equals(segm), tp.canRead());
            }
        }
    }

    @Test
    public void testTreePermissionVersionable2() throws Exception {
        Tree versionable = root.getTree("/content");
        Tree vh = checkNotNull(versionManager.getVersionHistory(versionable));

        CugPermissionProvider pp = createCugPermissionProvider(ImmutableSet.of(SUPPORTED_PATH, SUPPORTED_PATH2));

        Tree t = root.getTree("/");
        TreePermission tp = pp.getTreePermission(t, TreePermission.EMPTY);

        String path = PathUtils.concat(vh.getPath(), "1.0", JCR_FROZENNODE, "aa");
        for (String segm : PathUtils.elements(path)) {
            t = t.getChild(segm);
            tp = pp.getTreePermission(t, tp);

            if (JCR_SYSTEM.equals(segm) || ReadOnlyVersionManager.isVersionStoreTree(t)) {
                assertTrue(t.getPath(), tp instanceof EmptyCugTreePermission);
            } else {
                assertTrue(t.getPath(), tp instanceof CugTreePermission);
            }
        }
    }

    @Test
    public void testTreePermissionVersionableUnsupportedPath() throws Exception {
        Tree versionable = root.getTree(UNSUPPORTED_PATH);
        Tree vh = checkNotNull(versionManager.getVersionHistory(versionable));

        CugPermissionProvider pp = createCugPermissionProvider(ImmutableSet.of(SUPPORTED_PATH, SUPPORTED_PATH2));

        Tree t = root.getTree("/");
        TreePermission tp = pp.getTreePermission(t, TreePermission.EMPTY);

        for (String segm : PathUtils.elements(vh.getPath())) {
            t = t.getChild(segm);
            tp = pp.getTreePermission(t, tp);

            if (JCR_SYSTEM.equals(segm) || ReadOnlyVersionManager.isVersionStoreTree(t)) {
                assertTrue(t.getPath(), tp instanceof EmptyCugTreePermission);
            } else {
                assertSame(t.getPath(), TreePermission.NO_RECOURSE, tp);
            }
        }
    }

    @Test
    public void testTreePermissionAtVersionableAboveSupported() throws Exception {
        Tree vh = checkNotNull(versionManager.getVersionHistory(root.getTree(SUPPORTED_PATH)));

        CugPermissionProvider pp = createCugPermissionProvider(ImmutableSet.of(SUPPORTED_PATH + "/a"));
        TreePermission tp = getTreePermission(root, vh.getPath(), pp);
        assertTrue(tp instanceof EmptyCugTreePermission);
    }

    @Test
    public void testCugAtRoot() throws Exception {
        Tree versionable = root.getTree(UNSUPPORTED_PATH);
        String vhPath = checkNotNull(versionManager.getVersionHistory(versionable)).getPath();

        try {
            createCug(root, PathUtils.ROOT_PATH, EveryonePrincipal.NAME);
            root.commit();

            CugPermissionProvider pp = createCugPermissionProvider(ImmutableSet.of("/"));

            Tree t = root.getTree("/");
            TreePermission tp = pp.getTreePermission(t, TreePermission.EMPTY);
            assertTrue(tp instanceof CugTreePermission);

            for (String segm : PathUtils.elements(vhPath)) {
                t = t.getChild(segm);
                tp = pp.getTreePermission(t, tp);
                assertTrue(tp instanceof CugTreePermission);
            }
        } finally {
            root.getTree("/").removeProperty(JCR_MIXINTYPES);
            Tree cug = root.getTree("/rep:cugPolicy");
            if (cug.exists()) {
                cug.remove();
            }
            root.commit();
        }
    }

    @Test
    public void testVersionableWithUnsupportedType() throws Exception {
        Tree versionable = root.getTree("/content");
        Tree vh = checkNotNull(versionManager.getVersionHistory(versionable));
        Tree frozen = vh.getChild("1.0").getChild(JCR_FROZENNODE).getChild("a").getChild("b").getChild("c");

        Tree invalidFrozen = frozen.addChild(REP_CUG_POLICY);
        invalidFrozen.setProperty(JCR_PRIMARYTYPE, NT_REP_CUG_POLICY);

        CugPermissionProvider pp = createCugPermissionProvider(ImmutableSet.of(SUPPORTED_PATH, SUPPORTED_PATH2));
        TreePermission tp = getTreePermission(root, PathUtils.concat(vh.getPath(), "1.0", JCR_FROZENNODE, "a/b/c"), pp);

        TreePermission tpForUnsupportedType = pp.getTreePermission(invalidFrozen, TreeType.VERSION, tp);
        assertEquals(TreePermission.NO_RECOURSE, tpForUnsupportedType);
    }

    @Test
    public void testVersionableWithCugParent() throws Exception {
        addVersionContent("/content/aa/bb/cc");

        Tree cc = root.getTree("/content/aa/bb/cc");
        assertFalse(CugUtil.hasCug(cc));

        Tree vh = checkNotNull(versionManager.getVersionHistory(cc));
        Tree t = root.getTree("/");
        CugPermissionProvider pp = createCugPermissionProvider(
                ImmutableSet.of(SUPPORTED_PATH, SUPPORTED_PATH2), getTestGroupPrincipal());

        TreePermission tp = getTreePermission(root, vh.getPath(), pp);

        assertTrue(tp instanceof CugTreePermission);
        assertTrue(((CugTreePermission) tp).isInCug());
        assertTrue(((CugTreePermission) tp).isAllow());
    }
}


text:
import bbio, cape_manager, os, glob
from bbio.platform.util import i2cdev
from config import I2C_BASE_ADDRESSES

class I2CBus(i2cdev.I2CDev):
  def __init__(self, bus):
    assert 1<= bus <= 2, 'Only I2C buses 1 and 2 are available'

    # Run i2cdev.I2CDev initializtion:
    super(I2CBus, self).__init__(bus)

  def open(self, use_10bit_address=False):
    """ I2CDev.open(use_10bit_address=False) -> None

        Initialize the I2C bus interface.
        If use_10bit_address=True the bus will use 10-bit slave addresses
        instead of 7-bit addresses.
    """
    if not os.path.exists('/dev/i2c-%i' % self.bus_num):
      cape_manager.load('BB-I2C%i' % self.hw_bus, auto_unload=False)
      bbio.common.delay(10)
      # Make sure it initialized correctly:
      assert os.path.exists('/dev/i2c-%i' % self.bus_num), \
        'could not enable I2C bus %i' % self.hw_bus

    # Detect bus number:
    for i in glob.glob("/sys/bus/i2c/devices/i2c-*"):
      path = os.path.realpath(i)
      module_addr = int(path.split("/")[4].split(".")[0], 16)
      if module_addr == I2C_BASE_ADDRESSES[self.bus_num]:
        self.bus_num = int(path.split("/")[5][-1])
        break

    super(I2CBus, self).open(use_10bit_address=use_10bit_address)

  def begin(self, use_10bit_address=False):
    """ Same as I2CBus.open() """
    self.open(use_10bit_address=use_10bit_address)

  def end(self):
    """ Same as I2CBus.close() """
    self.close()

def i2c_cleanup():
  """ Closes all open i2c buses. """
  Wire1.close()
  Wire2.close()

Wire1 = I2C1 = I2CBus(1)
Wire2 = I2C2 = I2CBus(2)


text:
package jlibs.nio.util;

import java.nio.ByteBuffer;

import static jlibs.nio.Debugger.DEBUG;
import static jlibs.nio.Debugger.println;

/**
 * @author Santhosh Kumar Tekuri
 */
public class UnpooledBufferAllocator implements BufferAllocator{
    public static final UnpooledBufferAllocator HEAP = new UnpooledBufferAllocator(false);
    public static final UnpooledBufferAllocator DIRECT = new UnpooledBufferAllocator(true);

    private boolean directPreferred;
    private UnpooledBufferAllocator(boolean directPreferred){
        this.directPreferred = directPreferred;
    }

    @Override
    public boolean directPreferred(){
        return directPreferred;
    }

    @Override
    public ByteBuffer allocateHeap(int size){
        if(DEBUG)
            println("unpool.allocate("+size+")");
        return ByteBuffer.allocate(size);
    }

    @Override
    public ByteBuffer allocateDirect(int size){
        return ByteBuffer.allocateDirect(size);
    }

    @Override
    public void free(ByteBuffer buffer){
        // do nothing
    }
}


text:
const path = require( 'path' )

const CWD = process.cwd()
const HOMEDIR = require( 'os' ).homedir()
const CONFIGFILENAME = '.deploy_by_rsync_config'

const message = require('./message')

function searchConfig() {
  var conf
  try {
    conf = require( path.join( HOMEDIR, CONFIGFILENAME ) )
  } catch ( e ) {
    try {
      conf = require( path.join( CWD, CONFIGFILENAME ) )
    } catch ( e ) {
    console.log('e ' , e);
      message.error( 'no config file' )
      conf = null
    }
  }

  return conf
}

module.exports = searchConfig


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Ann. Lyceum Nat. Hist. New York 1:151. 1824

#### Original name
null

### Remarks
null


text:
<?php

namespace Pinq\Tests\Integration\Traversable\Aggregates;

class AnyTest extends \Pinq\Tests\Integration\Traversable\TraversableTest
{
    /**
     * @dataProvider emptyData
     */
    public function testThatAnyReturnsFalseIfEmpty(\Pinq\ITraversable $traversable, array $data)
    {
        $this->assertFalse($traversable->any());
    }

    /**
     * @dataProvider oneToTen
     */
    public function testThatAnyReturnsTrueWhenSomeElementMatch(\Pinq\ITraversable $traversable, array $data)
    {
        $this->assertTrue($traversable->any(function ($i) { return $i > 5; }));
    }

    /**
     * @dataProvider oneToTen
     */
    public function testThatAnyReturnsFalseWhenNoElementMatch(\Pinq\ITraversable $traversable, array $data)
    {
        $this->assertFalse($traversable->any(function ($i) { return $i > 25; }));
    }

    /**
     * @dataProvider everything
     */
    public function testThatAnyOperatesCorrectly(\Pinq\ITraversable $traversable, array $data)
    {
        $this->assertSame(
                count(array_filter($data)) > 0,
                $traversable->any());
    }
}


text:
//
//  MVSWebserviceOperation.h
//  MoltenCore
//
//  Created by Nicholas Bourey on 2/25/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "MVSWebserviceBase.h"

/**
 * @class MVSWebserviceOperation
 * @ingroup Networking
 * @brief A subclass of NSOperation for Webservice calls.
 *
 * An NSOperation subclass for webservice calls. Used internally by all Webservice classes
 * to implement Asynchronous calls to webservice methods. Increases overall performance of
 * the webservice calls allowing multiple calls to be made at the same time.
 */
@interface MVSWebserviceOperation : NSOperation {
@private
	NSURLRequest *request;
	MVSWebserviceBase *service;
	SEL selector;
	SEL serviceCallback;
	id<MVSWebserviceDelegate> client;
	SEL callbackSelector;

	NSMutableData *data;
	NSURLConnection *connection;

	// State //
	BOOL isExecuting;
	BOOL isFinished;
}

/**
 * @brief Intialize a Webservice Operation
 * @param aRequest An NSURLRequest for this operation
 * @param service The service that is making this request
 * @param aSelector Service callback selector
 * @param client The delegate object for this call
 * @param callback The delegate callback selector
 *
 * Create a new Webservice Operation for \c aRequest that will call \c selector on \c service when finished.\n
 * Passes \c client and \c callback are passed along to \c selector as parameters.
 */
- (id)initWithURLRequest:(NSURLRequest *)aRequest service:(MVSWebserviceBase *)service selector:(SEL)aSelector client:(id<MVSWebserviceDelegate>)client callbackSelector:(SEL)callback;

/**
 * @brief Initialize a Webservice Operation
 * @param aRequest An NSURLRequest for this operation
 * @param aService The service that is making this request
 * @param aSelector In-between service callback
 * @param aServiceCallback Service callback selector
 * @param aClient The delegate object for this call
 * @param callback The delegate callback selector
 *
 * Create a new Webservice Operation for \c aRequest that will call \c selector on \c service when finished.\n
 * Passes \c client, \c aServiceCallback, \c client and \c callback along to \c selector as parameters.
 */
- (id)initWithURLRequest:(NSURLRequest *)aRequest service:(MVSWebserviceBase *)aService selector:(SEL)aSelector serviceCallback:(SEL)aServiceCallback client:(id<MVSWebserviceDelegate>)aClient callbackSelector:(SEL)callback;
@end


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.ibenben.mapper.TaxRateMapper" >
  <resultMap id="BaseResultMap" type="com.ibenben.domain.TaxRate" >
    <id column="tax_rate_id" property="taxRateId" jdbcType="INTEGER" />
    <result column="tax_rate" property="taxRate" jdbcType="DECIMAL" />
  </resultMap>
  <sql id="Base_Column_List" >
    tax_rate_id, tax_rate
  </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select
    <include refid="Base_Column_List" />
    from tax_rate
    where tax_rate_id = #{taxRateId,jdbcType=INTEGER}
  </select>
  <select id="selectAll" resultMap="BaseResultMap">
  	select
    <include refid="Base_Column_List" />
    from tax_rate
  </select>

  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from tax_rate
    where tax_rate_id = #{taxRateId,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.ibenben.domain.TaxRate" >
    insert into tax_rate (tax_rate_id, tax_rate)
    values (#{taxRateId,jdbcType=INTEGER}, #{taxRate,jdbcType=DECIMAL})
  </insert>
  <insert id="insertSelective" parameterType="com.ibenben.domain.TaxRate" >
    insert into tax_rate
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="taxRateId != null" >
        tax_rate_id,
      </if>
      <if test="taxRate != null" >
        tax_rate,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="taxRateId != null" >
        #{taxRateId,jdbcType=INTEGER},
      </if>
      <if test="taxRate != null" >
        #{taxRate,jdbcType=DECIMAL},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.ibenben.domain.TaxRate" >
    update tax_rate
    <set >
      <if test="taxRate != null" >
        tax_rate = #{taxRate,jdbcType=DECIMAL},
      </if>
    </set>
    where tax_rate_id = #{taxRateId,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.ibenben.domain.TaxRate" >
    update tax_rate
    set tax_rate = #{taxRate,jdbcType=DECIMAL}
    where tax_rate_id = #{taxRateId,jdbcType=INTEGER}
  </update>
</mapper>


text:
package interdroid.vdb;

/**
 * This class holds constants for triggering actions in the vdb-ui package.
 * It has to live here due to the way the android tools structure Library
 * packages. We can't make vdb-ui a Library to import this class into
 * other UI packages that want to launch ui activities so it lives down
 * in this layer even though it really belongs in the vdb-ui system.
 *
 * @author nick
 *
 */
public final class Actions {
	/** Don't allow construction of this class. **/
	private Actions() { }

	/** Base for all actions. **/
	private static final String ACTION_BASE =
			"interdroid.vdb.action.";

	/** The Commit activity action. **/
	public static final String ACTION_COMMIT =
			ACTION_BASE + "COMMIT";

	/** Add a branch action. **/
	public static final String ACTION_ADD_BRANCH =
			ACTION_BASE + "ADD_BRANCH";

	/** Edit a remote hub action. **/
	public static final String ACTION_EDIT_REMOTE =
			ACTION_BASE + "EDIT_REMOTE";

	/** Add a peer action. **/
	public static final String ACTION_ADD_REMOTE =
			ACTION_BASE + "ADD_REMOTE";

	/** Manage local branches action. **/
	public static final String ACTION_MANAGE_LOCAL_BRANCHES =
			ACTION_BASE + "MANAGE_LOCAL_BRANCHES";

	/** Manage all remote repositories action. **/
	public static final String ACTION_MANAGE_REMOTES =
			ACTION_BASE + "MANAGE_REMOTES";

	/** Add a peer action. **/
	public static final String ACTION_ADD_PEER =
			ACTION_BASE + "ADD_PEER";

	/** Manage all peers action. **/
	public static final String ACTION_MANAGE_PEERS =
			ACTION_BASE + "MANAGE_PEERS";

	/** Manage the properties for a repository. **/
	public static final String ACTION_MANAGE_REPOSITORY_PROPERTIES =
			ACTION_BASE + "MANAGE_REPOSITORY_PROPERTIES";

	/** Manage a particular repository action. **/
	public static final String ACTION_MANAGE_REPOSITORY =
			ACTION_BASE + "MANAGE_REPOSITORY";

	/** Manage all repositories action. **/
	public static final String ACTION_MANAGE_REPOSITORIES =
			ACTION_BASE + "MANAGE_REPOSITORIES";

	/** Manage peer information action. **/
	public static final String ACTION_MANAGE_PEER_INFO =
			ACTION_BASE + "MANAGE_PEER_INFO";

	/** Manage local sharing action. **/
	public static final String ACTION_MANAGE_LOCAL_SHARING =
			ACTION_BASE + "MANAGE_LOCAL_SHARING";

	/** Manage remote sharing action. **/
	public static final String ACTION_MANAGE_REMOTE_SHARING =
			ACTION_BASE + "MANAGE_REMOTE_SHARING";

	/** The git service. **/
	public static final String GIT_SERVICE = "interdroid.vdb.GIT_SERVICE";

	/** Initialize a database. **/
	public static final String ACTION_INIT_DB = "interdroid.vdb.INIT_DB";

	/** Register an avro schema. **/
	public static final String REGISTER_SCHEMA =
			"interdroid.vdb.REGISTER_SCHEMA";

}


text:
import unittest

from chainer import testing
from chainer.testing import condition

# The test fixtures of this TestCase is used to be decorated by
# decorator in test. So we do not run them alone.
class MockUnitTest(unittest.TestCase):

    failure_case_counter = 0
    success_case_counter = 0
    probabilistic_case_counter = 0
    probabilistic_case_success_counter = 0
    probabilistic_case_failure_counter = 0

    @staticmethod
    def clear_counter():
        MockUnitTest.failure_case_counter = 0
        MockUnitTest.success_case_counter = 0
        MockUnitTest.probabilistic_case_counter = 0
        MockUnitTest.probabilistic_case_success_counter = 0
        MockUnitTest.probabilistic_case_failure_counter = 0

    def failure_case(self):
        MockUnitTest.failure_case_counter += 1
        self.fail()

    def success_case(self):
        MockUnitTest.success_case_counter += 1
        self.assertTrue(True)

    def error_case(self):
        raise Exception()

    def probabilistic_case(self):
        MockUnitTest.probabilistic_case_counter += 1
        if MockUnitTest.probabilistic_case_counter % 2 == 0:
            MockUnitTest.probabilistic_case_success_counter += 1
            self.assertTrue(True)
        else:
            MockUnitTest.probabilistic_case_failure_counter += 1
            self.fail()

    def runTest(self):
        pass

def _should_fail(self, f):
    try:
        f(self.unit_test)
        self.fail(
            'AssertionError is expected to be raised, but none is raised')
    except AssertionError as e:
        # check if the detail is included in the error object
        self.assertIn('first error message:', str(e))

def _should_pass(self, f):
    f(self.unit_test)

class TestRepeatWithSuccessAtLeast(unittest.TestCase):

    def _decorate(self, f, times, min_success):
        return condition.repeat_with_success_at_least(
            times, min_success)(f)

    def setUp(self):
        self.unit_test = MockUnitTest()
        MockUnitTest.clear_counter()

    def test_all_trials_fail(self):
        f = self._decorate(MockUnitTest.failure_case, 10, 1)
        _should_fail(self, f)
        self.assertEqual(self.unit_test.failure_case_counter, 10)

    def test_all_trials_fail2(self):
        f = self._decorate(MockUnitTest.failure_case, 10, 0)
        _should_pass(self, f)
        self.assertLessEqual(self.unit_test.failure_case_counter, 10)

    def test_all_trials_error(self):
        f = self._decorate(MockUnitTest.error_case, 10, 1)
        _should_fail(self, f)

    def test_all_trials_succeed(self):
        f = self._decorate(MockUnitTest.success_case, 10, 10)
        _should_pass(self, f)
        self.assertEqual(self.unit_test.success_case_counter, 10)

    def test_all_trials_succeed2(self):
        self.assertRaises(AssertionError,
                          condition.repeat_with_success_at_least,
                          10, 11)

    def test_half_of_trials_succeed(self):
        f = self._decorate(MockUnitTest.probabilistic_case, 10, 5)
        _should_pass(self, f)
        self.assertLessEqual(self.unit_test.probabilistic_case_counter, 10)
        self.assertGreaterEqual(
            self.unit_test.probabilistic_case_success_counter, 5)
        self.assertLessEqual(
            self.unit_test.probabilistic_case_failure_counter, 5)

    def test_half_of_trials_succeed2(self):
        f = self._decorate(MockUnitTest.probabilistic_case, 10, 6)
        _should_fail(self, f)
        self.assertLessEqual(self.unit_test.probabilistic_case_counter, 10)
        self.assertLess(
            self.unit_test.probabilistic_case_success_counter, 6)
        self.assertGreaterEqual(
            self.unit_test.probabilistic_case_failure_counter, 5)

class TestRepeat(unittest.TestCase):

    def _decorate(self, f, times):
        return condition.repeat(times)(f)

    def setUp(self):
        self.unit_test = MockUnitTest()
        MockUnitTest.clear_counter()

    def test_failure_case(self):
        f = self._decorate(MockUnitTest.failure_case, 10)
        _should_fail(self, f)
        self.assertLessEqual(self.unit_test.failure_case_counter, 10)

    def test_success_case(self):
        f = self._decorate(MockUnitTest.success_case, 10)
        _should_pass(self, f)
        self.assertEqual(self.unit_test.success_case_counter, 10)

    def test_probabilistic_case(self):
        f = self._decorate(MockUnitTest.probabilistic_case, 10)
        _should_fail(self, f)
        self.assertLessEqual(self.unit_test.probabilistic_case_counter, 10)
        self.assertLess(self.unit_test.probabilistic_case_success_counter, 10)
        self.assertGreater(
            self.unit_test.probabilistic_case_failure_counter, 0)

class TestRetry(unittest.TestCase):

    def _decorate(self, f, times):
        return condition.retry(times)(f)

    def setUp(self):
        self.unit_test = MockUnitTest()
        MockUnitTest.clear_counter()

    def test_failure_case(self):
        f = self._decorate(MockUnitTest.failure_case, 10)
        _should_fail(self, f)
        self.assertEqual(self.unit_test.failure_case_counter, 10)

    def test_success_case(self):
        f = self._decorate(MockUnitTest.success_case, 10)
        _should_pass(self, f)
        self.assertLessEqual(self.unit_test.success_case_counter, 10)

    def test_probabilistic_case(self):
        f = self._decorate(MockUnitTest.probabilistic_case, 10)
        _should_pass(self, f)
        self.assertLessEqual(
            self.unit_test.probabilistic_case_counter, 10)
        self.assertGreater(
            self.unit_test.probabilistic_case_success_counter, 0)
        self.assertLess(self.unit_test.probabilistic_case_failure_counter, 10)

testing.run_module(__name__, __file__)


text:
permalink: /android/topics
last_modified_at: 2018-12-01

title: Android and Kotlin Topics
description: >
  Explore all my articles concerning Android and Kotlin, grouped by topic. The
  focus of content is on good software development practices and how to
  maintain good code quality.

category: android
headline: Android
tagline: >
  Browse articles grouped by topic
---


text:
class CreateSkeleton < ActiveRecord::Migration[5.0]
  def change
    create_table :skeletons do |t|
      t.string :name

      t.timestamps null: false
    end
  end
end


text:
package com.mmnaseri.cs.skiena.ch08.s1;

import com.mmnaseri.cs.qa.annotation.Quality;
import com.mmnaseri.cs.qa.annotation.Stage;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Mohammad Milad Naseri (mmnaseri@programmer.net)
 * @since 1.0 (11/13/16, 8:42 AM)
 */
@Quality(Stage.UNTESTED)
public class MemoizingDynamicFibonacciNumberGenerator implements FibonacciNumberGenerator {

    private final List<BigInteger> cache;

    public MemoizingDynamicFibonacciNumberGenerator() {
        cache = new ArrayList<>();
        cache.add(BigInteger.ONE);
        cache.add(BigInteger.ONE);
    }

    @Override
    public BigInteger generate(int index) {
        while (cache.size() <= index) {
            cache.add(null);
        }
        if (cache.get(index) == null) {
            cache.set(index, generate(index - 1).add(generate(index - 2)));
        }
        return cache.get(index);
    }
}