text:
module Haslo.ErrorHandling (module Control.Monad.Error
                     ,module Haslo.BasicType
                     ,ValidationError (..)
                     ,ValidMonad
                     )
where

import Control.Monad.Error.Class
import Control.Monad.Error
import Haslo.BasicType
import Haslo.InstalmentPlan
import Text.PrettyShow
import Data.Time (Day
                 ,fromGregorian)

-- | Error handlig data type.
data ValidationError =
             -- | Instalment discrepancy:
             --   Instalment amount, Repayment, Interest paid
               InstalmentDiscrepancy !Amount !Amount !Amount

             -- | Incorect interest:
             --   Principal before, Late interest before, Interest calculated (incorectly),
             --   Interest rate
             | IPLInterest !Amount !Interest !Interest !Rate

             -- | Simple follow up interest mismatch (a1 + a2 - a3 /= a4):
             --   Error description, a1, a2, a3, a4
             | FollowUpInterestError String !Interest !Interest !Amount !Interest

             -- | Simple follow up mismatch (a1 - a /= a2):
             --   Error description, a1, a, a2
             | FollowUpError String !Amount !Amount !Amount

             -- | Simpler follow up mismatch (a /= b):
             --   Error description, a, b
             | SimplerFollowUpError String !Amount !Amount

             -- | Deffered interest cannot be paid.
             | NotPaidDefferedInterest !Interest InstalmentPlan

             -- | Capital doesn't amortize. This is due to rounding error if happens.
             | NotAmortized !Amount InstalmentPlan

             | OtherError String

             --  Any error can occur independently before and after financing.
             --   Errors after financing usually are linked to date.
--             | FinancingError Day ValidationError

-- | We make ValidationError an instance of the Error class
--   to be able to throw it as an exception.
instance Error ValidationError where
  noMsg    = OtherError "(!)"
  strMsg s = OtherError s

instance Show ValidationError where
    show (InstalmentDiscrepancy a p iP) = "Instalment discrepancy:\
                     \instalment amount /= repayment + interest paid ("
                          ++ (showAmtWithLen 8 a) ++ "/=" ++
                             (showAmtWithLen 8 p) ++ "+" ++
                             (showAmtWithLen 8 iP) ++ ")"
    show (IPLInterest p iL i r) = "IPL interest discrepancy: \
                          \ recalculated interest=" ++ show iR ++
                          ", given interest=" ++ show i ++
                          " (principal:" ++ showAmtWithLen 8 p ++
                          " (late interest:" ++ showWithLenDec 11 6 iL ++
                          " (interest rate:" ++ show r ++ ")"
        where iR = (fromIntegral p + iL) * r
    show (FollowUpInterestError msg a1 a2 a3 a4) = msg ++
                              show (a1 / 100) ++ " - " ++
                              show (a2 / 100) ++ " + " ++
                              showAmtWithLen 8 a3 ++ " /= " ++
                              show (a4 / 100)
    show (FollowUpError msg a1 a a2) = msg ++
                              showAmtWithLen 8 a1 ++ " - " ++
                              showAmtWithLen 8 a ++ " /= " ++
                              showAmtWithLen 8 a2
    show (SimplerFollowUpError msg a b) = msg ++
                              showAmtWithLen 8 a ++ " /= " ++
                              showAmtWithLen 8 b
    show (NotPaidDefferedInterest iL ip) = "Deferred interest not paid off. Remains:" ++
                                           show (iL / 100) ++
                                           " " ++ show ip
    show (NotAmortized c ip) = "Principal doesn't amortize fully. Remains:" ++ showAmtWithLen 8 c ++
                               " " ++ show ip
    show (OtherError msg) = msg
--    show (FinancingError d err) = show d ++ " " ++ show err

maybeShow Nothing = ""
maybeShow (Just a) = show a ++ " "

-- | Monad wrapping error message or correct value. Broadly used.
type ValidMonad = Either ValidationError

--errMsg moduleName functionName msg = throwError $ OtherError $
--    moduleName ++ " " ++
--    functionName ++ " " ++
--    msg

{-errDate :: Day -> ValidMonad a -> ValidMonad a
errDate d (Left (FollowUpError w x y z _)) = Left $ FollowUpError w x y z (Just d)
errDate d (Left (InstalmentDiscrepancy w x y z _)) = Left $ InstalmentDiscrepancy w x y z (Just d)
errDate d (Left (IPLInterest w x y z _)) = Left $ IPLInterest w x y z (Just d)
errDate _ x                                = x-}

--data FinancingError = SFinancingError Day ValidationError

-- | Allows adding date to any error of @ValidationError@ type.
--liftDate :: MonadError ValidationError m => Day
--                                         -> ValidationError
--                                         -> m a
--liftDate date err = throwError $ FinancingError date err


text:
var infraMonitorDashboardView = (function() {
    var self = this;
    this.load = function (obj) {
        var hashParams = ifNull(obj['hashParams'],{});
        addTabs();
        //Trigger select on tab based on hash
        infraDashboardView.selectTabByHash();
    }
    return {
        load:self.load
    }
})();

function addTabs() {
    /**
     * vRouters Tab
     */
    vRouterDashboardTab = (function() {
        var ViewModel = function() {
            var self = this;
            self.data = ko.observableArray([]);
            self.downCnt =  ko.computed(function() { return dashboardUtils.getDownNodeCnt(self.data());});
            self.upCnt = ko.computed(function() { return self.data().length - self.downCnt();});
            self.totalCnt = ko.computed(function() { return self.upCnt() === '' ? '' : self.upCnt() + self.downCnt();});
        }

        var viewModel = new ViewModel();
        viewModel.data.subscribe(function(newValue) {
            updateView(newValue);
        })
        /**
        * Takes vRouters data(array) as input and creates/updates chart
        */
        var updateView = function(data) {
            var chartObj = {};
            var chartsData = {title:'vRouters',d:[{key:'vRouters',values:data}],chartOptions:{tooltipFn:bgpMonitor.vRouterTooltipFn,clickFn:bgpMonitor.onvRouterDrillDown,xPositive:true,addDomainBuffer:true}};
            var chartObj = {};
            if(!isScatterChartInitialized('#vrouter-bubble')) {
                $('#vrouterStats-header').initWidgetHeader({title:'vRouters',link:{hashParams:{p:'mon_infra_vrouter',q:{node:'vRouters'}}}});
                $('#vrouter-bubble').initScatterChart(chartsData);
            } else {
                data = updateCharts.setUpdateParams(data);
                chartObj['selector'] = $('#content-container').find('#vrouter-bubble > svg').first()[0];
                chartObj['data'] = [{key:'vRouters',values:data}];
                chartObj['type'] = 'infrabubblechart';
                updateCharts.updateView(chartObj);
            }
            self.updatevRouterInfoBoxes();
        }

        this.updatevRouterInfoBoxes = function(){
            var data = viewModel.data();
            var instBuckets,vnBuckets,intfBuckets;
            var vnCount=0,intfCnt=0,instCnt=0,vns=[];
            var vRouterCF = crossfilter(data);
            $.each(data,function(idx,obj) {
                intfCnt += obj['intfCnt'];
                instCnt += obj['instCnt'];
                $.each(obj['vns'],function(idx,val) {
                    if($.inArray(val,vns) == -1)
                        vns.push(val);
                });
            });
            vnCnt = vns.length;
            vnBuckets = bucketizeCFData(vRouterCF,function(d) { return d.vnCnt});
            instBuckets = bucketizeCFData(vRouterCF,function(d) { return d.instCnt});
            intfBuckets = bucketizeCFData(vRouterCF,function(d) { return d.intfCnt});

            var sparklinesData = {
                    instances: {title:'Instances',data:[]},
                    interfaces:{title:'Interfaces',data:[]},
                    vns:{title:'Virtual Networks',data:[]}
            };

            $.each(ifNull(instBuckets['data'],[]), function(key,val){
                sparklinesData['instances']['data'].push(val);
            });

            $.each(ifNull(intfBuckets['data'],[]), function(key,val){
                sparklinesData['interfaces']['data'].push(val);
            });

            $.each(ifNull(vnBuckets['data'],[]), function(key,val){
                sparklinesData['vns']['data'].push(val);
            });

            $('#sparkLineStats').html('');
            var sparkLineTemplate  = contrail.getTemplate4Id('sparkline-template');
            var instElem = $('

').html(sparkLineTemplate({title:'Instances',totalCnt:instCnt,id:'infobox-instances'}));
            var intfElem = $('

').html(sparkLineTemplate({title:'Interfaces',totalCnt:intfCnt,id:'infobox-interfaces'}));
            var vnElem = $('

').html(sparkLineTemplate({title:'VNs',totalCnt:vnCnt,id:'infobox-vns'}));

            $('#sparkLineStats').append(instElem,intfElem,vnElem);
            $.each(sparklinesData,function(key,val){
                drawSparkLineBar('#infobox-' + key + ' .sparkline', val);
            })
        }

        infraDashboardView.addInfoBox({
                    title:'vRouters',
                    dataSourceObj:'computeNodeDS',
                    template:'vrouter-dashboard-tab',
                    viewModel: viewModel,
                    tabId:'vRouter'     //Used in hashParams
                });
    }());

    /**
     * Control Nodes Tab
     */
    ctrlNodesDashboardTab = (function() {
        var ViewModel = function() {
            var self = this;
            self.data = ko.observableArray([]);
            self.downCnt =  ko.computed(function() { return dashboardUtils.getDownNodeCnt(self.data());});
            self.upCnt = ko.computed(function() { return self.data().length - self.downCnt();});
            self.totalCnt = ko.computed(function() { return self.upCnt() === '' ? '' : self.upCnt() + self.downCnt();});
        }
        var viewModel = new ViewModel();

        viewModel.data.subscribe(function(newValue) {
            updateView(newValue);
        })

        var updateView = function(data) {
            if(!isScatterChartInitialized('#ctrlNode-bubble')) {
                $('#ctrlNodeStats-header').initWidgetHeader({title:'Control Nodes',link:{hashParams:{p:'mon_infra_control',q:{node:'Control Nodes'}}}});
                var chartsData = {title:'Control Nodes',chartOptions:{tooltipFn:bgpMonitor.controlNodetooltipFn,clickFn:bgpMonitor.onControlNodeDrillDown,xPositive:true,addDomainBuffer:true},d:[{key:'Control Nodes',values:data}]};
                $('#ctrlNode-bubble').initScatterChart(chartsData);
            } else {
            }
        }

        infraDashboardView.addInfoBox({
                    title:'Control Nodes',
                    template:'ctrlnode-dashboard-tab',
                    dataSourceObj:'controlNodeDS',
                    viewModel:viewModel,
                    tabId:'controlNode'
                });

    }());

    /**
     * Analytics Nodes Tab
     */
    analyticNodesDashboardTab = (function() {
        var AnalyticNodesViewModel = function() {
            var self = this;
            self.data = ko.observableArray([]);
            self.downCnt =  ko.computed(function() { return dashboardUtils.getDownNodeCnt(self.data());});
            self.upCnt = ko.computed(function() { return self.data().length - self.downCnt();});
            self.totalCnt = ko.computed(function() { return self.upCnt() === '' ? '' : self.upCnt() + self.downCnt();});
        }
        var viewModel = new AnalyticNodesViewModel();
        viewModel.data.subscribe(function(newValue) {
            updateView(newValue);
        })
        var updateView = function(data) {
            if(!isScatterChartInitialized('#analyticNode-bubble')) {
                $('#analyticNodeStats-header').initWidgetHeader({title:'Analytics Nodes',link:{hashParams:{p:'mon_infra_analytics',q:{node:'Analytics Nodes'}}}});
                var chartsData = {title:'Analytic Nodes',chartOptions:{tooltipFn:bgpMonitor.analyticNodeTooltipFn,clickFn:bgpMonitor.onAnalyticNodeDrillDown,xPositive:true,addDomainBuffer:true},d:[{key:'Analytics Nodes',values:data}]};
                $('#analyticNode-bubble').initScatterChart(chartsData);
            } else {
            }
        }
        infraDashboardView.addInfoBox({
                    title:'Analytics Nodes',
                    template:'analyticnode-dashboard-tab',
                    dataSourceObj:'analyticsNodeDS',
                    viewModel:viewModel
                });
    }());

    /**
     * Config Node Tab
     */
    configNodesDashboardTab = (function() {

        var ConfigNodesViewModel = function() {
            var self = this;
            self.data = ko.observableArray([]);
            self.downCnt =  ko.computed(function() { return dashboardUtils.getDownNodeCnt(self.data());});
            self.upCnt = ko.computed(function() { return self.data().length - self.downCnt();});
            self.totalCnt = ko.computed(function() { return self.upCnt() === '' ? '' : self.upCnt() + self.downCnt();});
        }

        var viewModel = new ConfigNodesViewModel();
        viewModel.data.subscribe(function(newValue) {
            updateView(newValue);
        })

        var updateView = function(data) {
            if(!isScatterChartInitialized('#configNode-bubble')) {
                $('#configNodeStats-header').initWidgetHeader({title:'Config Nodes',link:{hashParams:{p:'mon_infra_config',q:{node:'Config Nodes'}}}});
                var chartsData = {title:'Config Nodes',chartOptions:{tooltipFn:bgpMonitor.configNodeTooltipFn,clickFn:bgpMonitor.onConfigNodeDrillDown,xPositive:true,addDomainBuffer:true},d:[{key:'Config Nodes',values:data}]};
                $('#configNode-bubble').initScatterChart(chartsData);
            } else {
            }
        }

        infraDashboardView.addInfoBox({
                    title:'Config Nodes',
                    template:'confignode-dashboard-tab',
                    dataSourceObj:'configNodeDS',
                    viewModel:viewModel,
                    tabId:'ConfigNode'
                });
    }());
}

redpajama_set_name: RedPajamaGithub


text:
package com.thoughtworks.go.server.service;

import com.thoughtworks.go.config.Agent;
import com.thoughtworks.go.config.GoConfigDao;
import com.thoughtworks.go.config.PipelineConfig;
import com.thoughtworks.go.domain.*;
import com.thoughtworks.go.domain.buildcause.BuildCause;
import com.thoughtworks.go.domain.materials.svn.Subversion;
import com.thoughtworks.go.domain.materials.svn.SvnCommand;
import com.thoughtworks.go.helper.AgentMother;
import com.thoughtworks.go.helper.SvnTestRepo;
import com.thoughtworks.go.helper.TestRepo;
import com.thoughtworks.go.listener.AgentStatusChangeListener;
import com.thoughtworks.go.server.cache.GoCache;
import com.thoughtworks.go.server.dao.DatabaseAccessHelper;
import com.thoughtworks.go.server.dao.JobInstanceDao;
import com.thoughtworks.go.server.dao.PipelineDao;
import com.thoughtworks.go.server.dao.StageDao;
import com.thoughtworks.go.server.transaction.TransactionTemplate;
import com.thoughtworks.go.util.GoConfigFileHelper;
import com.thoughtworks.go.util.SystemEnvironment;
import com.thoughtworks.go.util.TimeProvider;
import org.apache.commons.io.FileUtils;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;

import java.io.IOException;
import java.nio.file.Path;
import java.sql.SQLException;

import static com.thoughtworks.go.helper.ModificationsMother.modifySomeFiles;
import static com.thoughtworks.go.util.GoConstants.DEFAULT_APPROVED_BY;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;

@ExtendWith(SpringExtension.class)
@ContextConfiguration(locations = {
        "classpath:/applicationContext-global.xml",
        "classpath:/applicationContext-dataLocalAccess.xml",
        "classpath:/testPropertyConfigurer.xml",
        "classpath:/spring-all-servlet.xml",
})
public class ScheduleServiceRescheduleHungJobsIntegrationTest {

    @Autowired private GoConfigService goConfigService;
    @Autowired private GoConfigDao goConfigDao;
    @Autowired private PipelineDao pipelineDao;
    @Autowired private StageDao stageDao;
    @Autowired private JobInstanceDao jobInstanceDao;
    @Autowired private BuildAssignmentService buildAssignmentService;
    @Autowired private ScheduleService scheduleService;
    @Autowired private StageService stageService;
    @Autowired private GoCache goCache;
    @Autowired private DatabaseAccessHelper dbHelper;
    @Autowired private TransactionTemplate transactionTemplate;
    @Autowired private InstanceFactory instanceFactory;

    private PipelineConfig evolveConfig;
    private static final String STAGE_NAME = "dev";
    private static final GoConfigFileHelper CONFIG_HELPER = new GoConfigFileHelper();
    public Subversion repository;
    public static TestRepo testRepo;

    @BeforeAll
    public static void setupRepos(@TempDir Path tempDir) throws IOException {
        testRepo = new SvnTestRepo(tempDir);
    }

    @BeforeEach
    public void setup() throws Exception {
        dbHelper.onSetUp();
        CONFIG_HELPER.usingCruiseConfigDao(goConfigDao);
        CONFIG_HELPER.onSetUp();
        repository = new SvnCommand(null, testRepo.projectRepositoryUrl());
        evolveConfig = CONFIG_HELPER.addPipeline("evolve", STAGE_NAME, repository, "unit");
        CONFIG_HELPER.addPipeline("studios", "stageName", repository, "functional");
        goCache.clear();
    }

    @AfterEach
    public void teardown() throws Exception {
        dbHelper.onTearDown();
        CONFIG_HELPER.onTearDown();
        FileUtils.deleteQuietly(goConfigService.artifactsDir());
    }

    @Test
    public void shouldNotRescheduleCancelledBuilds() throws SQLException {
        String agentId = "uuid";
        final Pipeline pipeline = instanceFactory.createPipelineInstance(evolveConfig, modifySomeFiles(evolveConfig), new DefaultSchedulingContext(
                DEFAULT_APPROVED_BY), "md5-test", new TimeProvider());
        dbHelper.savePipelineWithStagesAndMaterials(pipeline);
        buildAssignmentService.assignWorkToAgent(agent(new Agent(agentId)));

        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            public void doInTransactionWithoutResult(TransactionStatus status) {
                stageService.cancelStage(stageOf(pipeline), null);
            }
        });

        scheduleService.rescheduleHungJobs();

        JobInstance reloaded = jobInstanceDao.buildByIdWithTransitions(buildOf(pipeline).getId());
        assertThat(reloaded.getState(), is(JobState.Completed));
        assertThat(reloaded.getResult(), is(JobResult.Cancelled));
    }

    @Test
    public void shouldRescheduleHungBuildWhenAgentTryToGetWorkWithSameUuid() throws Exception {
        Agent agent = AgentMother.localAgent();
        AgentInstance instance = agent(agent);
        BuildCause buildCause = modifySomeFiles(evolveConfig);
        dbHelper.saveMaterials(buildCause.getMaterialRevisions());
        Pipeline pipeline = instanceFactory.createPipelineInstance(evolveConfig, buildCause, new DefaultSchedulingContext(DEFAULT_APPROVED_BY), "md5-test", new TimeProvider());
        buildAssignmentService.onTimer();

        Stage stage = pipeline.getFirstStage();
        JobInstance jobInstance = stage.getJobInstances().get(0);
        jobInstance.setAgentUuid(agent.getUuid());
        jobInstance.changeState(JobState.Building);
        pipelineDao.saveWithStages(pipeline);

        buildAssignmentService.onTimer();
        buildAssignmentService.assignWorkToAgent(instance);
        buildAssignmentService.onTimer();
        buildAssignmentService.assignWorkToAgent(instance);

        final Stage reloadedStage = stageDao.stageById(stage.getId());
        final JobInstance rescheduledJob = reloadedStage.getJobInstances().getByName(jobInstance.getName());
        assertThat(rescheduledJob.getState(), is(JobState.Assigned));
    }

    private JobInstance buildOf(Pipeline pipeline) {
        return stageOf(pipeline).getJobInstances().first();
    }

    private Stage stageOf(Pipeline pipeline) {
        Stage stage = pipeline.getStages().first();
        for (JobInstance jobInstance : stage.getJobInstances()) {
            jobInstance.setIdentifier(new JobIdentifier(pipeline.getName(), -1, pipeline.getLabel(), stage.getName(),
                    String.valueOf(stage.getCounter()), jobInstance.getName()));
        }
        return stage;
    }

    private AgentInstance agent(Agent agent) {
        return AgentInstance.createFromAgent(agent, new SystemEnvironment(), new AgentStatusChangeListener() {
            @Override
            public void onAgentStatusChange(AgentInstance agentInstance) {
            }
        });
    }
}


text:
package me.androidbox.busbymovies.movielist;

import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.observers.DisposableObserver;
import me.androidbox.busbymovies.models.Movie;
import me.androidbox.busbymovies.models.Movies;
import me.androidbox.busbymovies.models.Results;
import me.androidbox.busbymovies.network.MovieAPIService;
import me.androidbox.busbymovies.utils.Constants;
import me.androidbox.busbymovies.utils.MovieSchedulers;
import timber.log.Timber;

/**
 * Created by steve on 2/19/17.
 */

final public class MovieListModelImp implements MovieListModelContract {

    private MovieAPIService mMovieAPIService;
    private MovieSchedulers movieSchedulers;

    private final CompositeDisposable compositeDisposable = new CompositeDisposable();

    public MovieListModelImp(final MovieAPIService movieAPIService, final MovieSchedulers movieSchedulers) {
        this.mMovieAPIService = movieAPIService;
        this.movieSchedulers = movieSchedulers;
    }

    @Override
    public void getPopularMovies(PopularMovieResultsListener popularMovieResultsListener) {
        if(Constants.MOVIES_API_KEY.isEmpty()) {
            popularMovieResultsListener.onPopularMovieFailure("Empty API Key");
        }
        else {
            compositeDisposable.add(mMovieAPIService.getPopular(Constants.MOVIES_API_KEY)
                    .subscribeOn(movieSchedulers.getBackgroundScheduler())
                    .observeOn(movieSchedulers.getUIScheduler())
                    .subscribeWith(new DisposableObserver<Results<Movies>>() {
                        @Override
                        public void onStart() {
                            super.onStart();
                            Timber.d("onStart");
                        }

                        @Override
                        public void onComplete() {
                            Timber.d("onCompleted");
                        }

                        @Override
                        public void onError(Throwable e) {
                            Timber.e(e, "onError %s", e.getMessage());
                            popularMovieResultsListener.onPopularMovieFailure(e.getMessage());
                        }

                        @Override
                        public void onNext(Results<Movies> results) {
                            Timber.d("onNext");
                            popularMovieResultsListener.onPopularMovieSuccess(results);
                        }
                    }));
        }
    }

    @Override
    public void getTopRatedMovies(TopRatedMovieResultsListener topRatedMovieResultsListener) {
        if(Constants.MOVIES_API_KEY.isEmpty()) {
            topRatedMovieResultsListener.onTopRatedMovieFailure("Empty API Key");
        }
        else {
            compositeDisposable.add(mMovieAPIService.getTopRatedMovies(Constants.MOVIES_API_KEY)
                    .subscribeOn(movieSchedulers.getBackgroundScheduler())
                    .observeOn(movieSchedulers.getUIScheduler())
                    .subscribeWith(new DisposableObserver<Results<Movies>>() {
                        @Override
                        public void onComplete() {
                            Timber.d("onCompleted");
                        }

                        @Override
                        public void onError(Throwable e) {
                            topRatedMovieResultsListener.onTopRatedMovieFailure(e.getMessage());
                            Timber.e(e, e.getMessage());
                        }

                        @Override
                        public void onNext(Results<Movies> movies) {
                            topRatedMovieResultsListener.onTopRatedMovieSuccess(movies);
                        }
                    }));
        }
    }

    @Override
    public void getMovieDetail(int movieId, MovieDetailResultsListener movieDetailResultsListener) {
        if(Constants.MOVIES_API_KEY.isEmpty()) {
            movieDetailResultsListener.onFailure("Empty API Key");
        }
        else {
            compositeDisposable.add(mMovieAPIService.getMovieByIdExt(movieId, Constants.MOVIES_API_KEY)
                    .subscribeOn(movieSchedulers.getBackgroundScheduler())
                    .observeOn(movieSchedulers.getUIScheduler())
                    .subscribeWith(new DisposableObserver<Movie>() {
                        @Override
                        public void onComplete() {
                            Timber.d("onCompleted");
                        }

                        @Override
                        public void onError(Throwable e) {
                            Timber.e(e, "onError %s", e.getMessage());
                            movieDetailResultsListener.onFailure(e.getMessage());
                        }

                        @Override
                        public void onNext(Movie movie) {
                            movieDetailResultsListener.onSuccess(movie);
                            Timber.d("onNext");
                        }
                    }));
        }
    }

    @Override
    public void searchForMovies(String movieName, int movieYear, MovieSearchResultsListener movieSearchResultsListener) {
        if(Constants.MOVIES_API_KEY.isEmpty()) {
            movieSearchResultsListener.onSearchFailure("Empty API Key");
        }
        else {
            compositeDisposable.add(mMovieAPIService.searchMovies(movieName, movieYear, Constants.MOVIES_API_KEY)
                    .subscribeOn(movieSchedulers.getBackgroundScheduler())
                    .observeOn(movieSchedulers.getUIScheduler())
                    .subscribeWith(new DisposableObserver<Results<Movies>>() {
                        @Override
                        public void onComplete() {
                            Timber.d("onCompleted");
                        }

                        @Override
                        public void onError(Throwable e) {
                            Timber.e(e, "OnError: %s", e.getMessage());
                            movieSearchResultsListener.onSearchFailure(e.getMessage());
                        }

                        @Override
                        public void onNext(Results<Movies> moviesResults) {
                            Timber.d("onNext");
                            movieSearchResultsListener.onSearchSuccess(moviesResults);
                        }
                    }));
        }
    }

    @Override
    public void releaseResources() {
        Timber.d("releaseResources");
        compositeDisposable.clear();
    }
}


text:
/**
    File Name:          15.4-2.js
    ECMA Section:       15.4 Array Objects

    Description:        Whenever a property is added whose name is an array
                        index, the length property is changed, if necessary,
                        to be one more than the numeric value of that array
                        index; and whenever the length property is changed,
                        every property whose name is an array index whose value
                        is not smaller  than the new length is automatically
                        deleted.  This constraint applies only to the Array
                        object itself, and is unaffected by length or array
                        index properties that may be inherited from its
                        prototype.

    Author:             christine@netscape.com
    Date:               28 october 1997

*/
    var SECTION = "15.4-2";
    var VERSION = "ECMA_1";
    startTest();
    var TITLE   = "Array Objects";

    writeHeaderToLog( SECTION + " "+ TITLE);

    var testcases = getTestCases();
    test();

function getTestCases() {
    var array = new Array();
    var item = 0;

    array[item++] = new TestCase( SECTION, "var arr=new Array();  arr[Math.pow(2,16)] = 'hi'; arr.length",      Math.pow(2,16)+1,   eval("var arr=new Array();  arr[Math.pow(2,16)] = 'hi'; arr.length") );

    array[item++] = new TestCase( SECTION, "var arr=new Array();  arr[Math.pow(2,30)-2] = 'hi'; arr.length",    Math.pow(2,30)-1,   eval("var arr=new Array();  arr[Math.pow(2,30)-2] = 'hi'; arr.length") );
    array[item++] = new TestCase( SECTION, "var arr=new Array();  arr[Math.pow(2,30)-1] = 'hi'; arr.length",    Math.pow(2,30),     eval("var arr=new Array();  arr[Math.pow(2,30)-1] = 'hi'; arr.length") );
    array[item++] = new TestCase( SECTION, "var arr=new Array();  arr[Math.pow(2,30)] = 'hi'; arr.length",      Math.pow(2,30)+1,   eval("var arr=new Array();  arr[Math.pow(2,30)] = 'hi'; arr.length") );

    array[item++] = new TestCase( SECTION, "var arr=new Array();  arr[Math.pow(2,31)-2] = 'hi'; arr.length",    Math.pow(2,31)-1,   eval("var arr=new Array();  arr[Math.pow(2,31)-2] = 'hi'; arr.length") );
    array[item++] = new TestCase( SECTION, "var arr=new Array();  arr[Math.pow(2,31)-1] = 'hi'; arr.length",    Math.pow(2,31),     eval("var arr=new Array();  arr[Math.pow(2,31)-1] = 'hi'; arr.length") );
    array[item++] = new TestCase( SECTION, "var arr=new Array();  arr[Math.pow(2,31)] = 'hi'; arr.length",      Math.pow(2,31)+1,   eval("var arr=new Array();  arr[Math.pow(2,31)] = 'hi'; arr.length") );

    array[item++] = new TestCase( SECTION, "var arr = new Array(0,1,2,3,4,5); arr.length = 2; String(arr)",     "0,1",              eval("var arr = new Array(0,1,2,3,4,5); arr.length = 2; String(arr)") );
    array[item++] = new TestCase( SECTION, "var arr = new Array(0,1); arr.length = 3; String(arr)",             "0,1,",             eval("var arr = new Array(0,1); arr.length = 3; String(arr)") );
//    array[item++] = new TestCase( SECTION, "var arr = new Array(0,1,2,3,4,5); delete arr[0]; arr.length",       5,                  eval("var arr = new Array(0,1,2,3,4,5); delete arr[0]; arr.length") );
//    array[item++] = new TestCase( SECTION, "var arr = new Array(0,1,2,3,4,5); delete arr[6]; arr.length",       5,                  eval("var arr = new Array(0,1,2,3,4,5); delete arr[6]; arr.length") );

    return ( array );
}
function test( array ) {
    for ( tc=0; tc < testcases.length; tc++ ) {
        testcases[tc].passed = writeTestCaseResult(
                            testcases[tc].expect,
                            testcases[tc].actual,
                            testcases[tc].description +" = "+ testcases[tc].actual );

        testcases[tc].reason += ( testcases[tc].passed ) ? "" : "wrong value ";
    }
    stopTest();
    return ( testcases );
}


text:
define(
({
	loadingInfo: "Načítavanie...",
	emptyInfo: "Žiadne položky na zobrazenie",
	loadFailInfo: "Zlyhalo načítavanie údajov!",
	loadMore: "Načítať viac",
	loadMoreLoading: "Načítavanie...",
	loadPrevious: "Načítať predošlé",
	loadPreviousLoading: "Načítavanie..."
})
);


text:
var obj = function(state = [], action){
    switch (action.type) {
        case "SET_README":
            return {
                ...state,
                readme: action.readme
            };
        default:
            return state;
    };
};

module.exports = obj;


text:
package helpers

import (

  "testing"
  "github.com/stretchr/testify/assert"
)

func TestString(t *testing.T) {

	assert := assert.New(t)

	res0 := string(10)
	res1 := String(10)

	assert.NotEqual(res0, res1)

}

func TestGetBucketName(t *testing.T) {

	assert := assert.New(t)

	res0 := GetBucketName()
	res1 := GetBucketName()

	assert.NotEqual(res0, res1)

}

func TestContains(t *testing.T) {

	assert := assert.New(t)

	args := []string{"a", "b"}

	assert.Equal(true, Contains(args, "a"))

}


text:
FROM node:16 as vue-develop-stage

WORKDIR /frontend

COPY ./Neptune-UI/package*.json ./
RUN npm install --legacy-peer-deps

COPY ./Neptune-UI/ .
RUN npm run build

FROM node:16

WORKDIR /Fluigi-Cloud

COPY --from=vue-develop-stage /frontend/dist ./dist

# Install dependencies
COPY ./Fluigi-Cloud/package*.json ./

RUN npm install --legacy-peer-deps

COPY ./Fluigi-Cloud/ .

EXPOSE 8080
EXPOSE 3000

CMD [ "npm", "start" ]


text:
package com.github.sawied.bean.common;

import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
faultInfo complex typeµÄ Java Àà¡£
 *
 *
ÒÔÏÂģʽƬ¶ÎÖ¸¶¨°üº¬ÔÚ´ËÀàÖеÄÔ¤ÆÚÄÚÈÝ¡£
 *
 *

 * <complexType name="faultInfo">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="errorCode" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *         <element name="reason" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "faultInfo", propOrder = {
    "errorCode",
    "reason"
})
@XmlRootElement(name = "BusinessException", namespace = "http://www.github.com/sawied/services/appManagment")
public class BusinessException
    implements Serializable
{

    private final static long serialVersionUID = 1L;
    @XmlElement(required = true)
    protected String errorCode;
    @XmlElement(required = true)
    protected String reason;

    /**
     * »ñÈ¡errorCodeÊôÐÔµÄÖµ¡£
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getErrorCode() {
        return errorCode;
    }

    /**
     * ÉèÖÃerrorCodeÊôÐÔµÄÖµ¡£
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setErrorCode(String value) {
        this.errorCode = value;
    }

    public boolean isSetErrorCode() {
        return (this.errorCode!= null);
    }

    /**
     * »ñÈ¡reasonÊôÐÔµÄÖµ¡£
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getReason() {
        return reason;
    }

    /**
     * ÉèÖÃreasonÊôÐÔµÄÖµ¡£
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setReason(String value) {
        this.reason = value;
    }

    public boolean isSetReason() {
        return (this.reason!= null);
    }

}


text:
package fr.alexmarsu.attaqueDefense;

import org.bukkit.entity.Player;

public class TimerRun implements Runnable{
	private int temps;
	private Jeu jeu;

	public TimerRun(int temps,Jeu jeu) {
		this.setTemps(temps);
		this.setJeu(jeu);
	}

	@Override
	public void run() {
		jeu.setTempsScoreBoard(temps);
		for(Player p:jeu.getListPlayer()){
			jeu.afficherScoreBoard(p);
		}
		setTemps(getTemps()-1);
		if(getTemps() == -1){
			jeu.finTimer();
		}
	}

	private int getTemps() {
		return temps;
	}

	private void setTemps(int temps) {
		this.temps = temps;
	}

	private Jeu getJeu() {
		return jeu;
	}

	private void setJeu(Jeu jeu) {
		this.jeu = jeu;
	}

}


text:
<resources>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="nav_header_vertical_spacing">16dp</dimen>
    <dimen name="nav_header_height">160dp</dimen>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
    <dimen name="fab_margin">16dp</dimen>

    <!--Standard-->
    <dimen name="activity_margin_0_5">8dp</dimen>
    <dimen name="activity_margin">16dp</dimen>
    <dimen name="activity_margin_2">32dp</dimen>
    <!--Text-->
    <dimen name="text_subheading">16sp</dimen>
    <dimen name="text_title">20sp</dimen>
</resources>


text:
import sys
import traceback
from importlib import import_module

from django.apps import apps
from django.apps.config import MODELS_MODULE_NAME
from django.conf import settings
from django.core.exceptions import AppRegistryNotReady

from oscar.core.exceptions import (
    AppNotFoundError, ClassNotFoundError, ModuleNotFoundError)

def get_class(module_label, classname):
    """
    Dynamically import a single class from the given module.

    This is a simple wrapper around `get_classes` for the case of loading a
    single class.

    Args:
        module_label (str): Module label comprising the app label and the
            module name, separated by a dot.  For example, 'catalogue.forms'.
        classname (str): Name of the class to be imported.

    Returns:
        The requested class object or `None` if it can't be found
    """
    return get_classes(module_label, [classname])[0]

def get_classes(module_label, classnames):
    """
    Dynamically import a list of classes from the given module.

    This works by looping over ``INSTALLED_APPS`` and looking for a match
    against the passed module label.  If the requested class can't be found in
    the matching module, then we attempt to import it from the corresponding
    core Oscar app (assuming the matched module isn't in Oscar).

    This is very similar to ``django.db.models.get_model`` function for
    dynamically loading models.  This function is more general though as it can
    load any class from the matching app, not just a model.

    Args:
        module_label (str): Module label comprising the app label and the
            module name, separated by a dot.  For example, 'catalogue.forms'.
        classname (str): Name of the class to be imported.

    Returns:
        The requested class object or ``None`` if it can't be found

    Examples:

        Load a single class:

        >>> get_class('dashboard.catalogue.forms', 'ProductForm')
        oscar.apps.dashboard.catalogue.forms.ProductForm

        Load a list of classes:

        >>> get_classes('dashboard.catalogue.forms',
        ...             ['ProductForm', 'StockRecordForm'])
        [oscar.apps.dashboard.catalogue.forms.ProductForm,
         oscar.apps.dashboard.catalogue.forms.StockRecordForm]

    Raises:

        AppNotFoundError: If no app is found in ``INSTALLED_APPS`` that matches
            the passed module label.

        ImportError: If the attempted import of a class raises an
            ``ImportError``, it is re-raised
    """
    if '.' not in module_label:
        # Importing from top-level modules is not supported, e.g.
        # get_class('shipping', 'Scale'). That should be easy to fix,
        # but @maikhoepfel had a stab and could not get it working reliably.
        # Overridable classes in a __init__.py might not be a good idea anyway.
        raise ValueError(
            "Importing from top-level modules is not supported")

    # import from Oscar package (should succeed in most cases)
    # e.g. 'oscar.apps.dashboard.catalogue.forms'
    oscar_module_label = "oscar.apps.%s" % module_label
    oscar_module = _import_module(oscar_module_label, classnames)

    # returns e.g. 'oscar.apps.dashboard.catalogue',
    # 'yourproject.apps.dashboard.catalogue' or 'dashboard.catalogue',
    # depending on what is set in INSTALLED_APPS
    installed_apps_entry, app_name = _find_installed_apps_entry(module_label)
    if installed_apps_entry.startswith('oscar.apps.'):
        # The entry is obviously an Oscar one, we don't import again
        local_module = None
    else:
        # Attempt to import the classes from the local module
        # e.g. 'yourproject.dashboard.catalogue.forms'
        sub_module = module_label.replace(app_name, '', 1)
        local_module_label = installed_apps_entry + sub_module
        local_module = _import_module(local_module_label, classnames)

    if oscar_module is local_module is None:
        # This intentionally doesn't raise an ImportError, because ImportError
        # can get masked in complex circular import scenarios.
        raise ModuleNotFoundError(
            "The module with label '%s' could not be imported. This either"
            "means that it indeed does not exist, or you might have a problem"
            " with a circular import." % module_label
        )

    # return imported classes, giving preference to ones from the local package
    return _pluck_classes([local_module, oscar_module], classnames)

def _import_module(module_label, classnames):
    """
    Imports the module with the given name.
    Returns None if the module doesn't exist, but propagates any import errors.
    """
    try:
        return __import__(module_label, fromlist=classnames)
    except ImportError:
        # There are 2 reasons why there could be an ImportError:
        #
        #  1. Module does not exist. In that case, we ignore the import and
        #     return None
        #  2. Module exists but another ImportError occurred when trying to
        #     import the module. In that case, it is important to propagate the
        #     error.
        #
        # ImportError does not provide easy way to distinguish those two cases.
        # Fortunately, the traceback of the ImportError starts at __import__
        # statement. If the traceback has more than one frame, it means that
        # application was found and ImportError originates within the local app
        __, __, exc_traceback = sys.exc_info()
        frames = traceback.extract_tb(exc_traceback)
        if len(frames) > 1:
            raise

def _pluck_classes(modules, classnames):
    """
    Gets a list of class names and a list of modules to pick from.
    For each class name, will return the class from the first module that has a
    matching class.
    """
    klasses = []
    for classname in classnames:
        klass = None
        for module in modules:
            if hasattr(module, classname):
                klass = getattr(module, classname)
                break
        if not klass:
            packages = [m.__name__ for m in modules if m is not None]
            raise ClassNotFoundError("No class '%s' found in %s" % (
                classname, ", ".join(packages)))
        klasses.append(klass)
    return klasses

def _get_installed_apps_entry(app_name):
    """
    Given an app name (e.g. 'catalogue'), walk through INSTALLED_APPS
    and return the first match, or None.
    This does depend on the order of INSTALLED_APPS and will break if
    e.g. 'dashboard.catalogue' comes before 'catalogue' in INSTALLED_APPS.
    """
    for installed_app in settings.INSTALLED_APPS:
        # match root-level apps ('catalogue') or apps with same name at end
        # ('shop.catalogue'), but don't match 'fancy_catalogue'
        if installed_app == app_name or installed_app.endswith('.' + app_name):
            return installed_app
    return None

def _find_installed_apps_entry(module_label):
    """
    Given a module label, finds the best matching INSTALLED_APPS entry.

    This is made trickier by the fact that we don't know what part of the
    module_label is part of the INSTALLED_APPS entry. So we try all possible
    combinations, trying the longer versions first. E.g. for
    'dashboard.catalogue.forms', 'dashboard.catalogue' is attempted before
    'dashboard'
    """
    modules = module_label.split('.')
    # if module_label is 'dashboard.catalogue.forms.widgets', combinations
    # will be ['dashboard.catalogue.forms', 'dashboard.catalogue', 'dashboard']
    combinations = [
        '.'.join(modules[:-count]) for count in range(1, len(modules))]
    for app_name in combinations:
        entry = _get_installed_apps_entry(app_name)
        if entry:
            return entry, app_name
    raise AppNotFoundError(
        "Couldn't find an app to import %s from" % module_label)

def get_profile_class():
    """
    Return the profile model class
    """
    # The AUTH_PROFILE_MODULE setting was deprecated in Django 1.5, but it
    # makes sense for Oscar to continue to use it. Projects built on Django
    # 1.4 are likely to have used a profile class and it's very difficult to
    # upgrade to a single user model. Hence, we should continue to support
    # having a separate profile class even if Django doesn't.
    setting = getattr(settings, 'AUTH_PROFILE_MODULE', None)
    if setting is None:
        return None
    app_label, model_name = settings.AUTH_PROFILE_MODULE.split('.')
    return get_model(app_label, model_name)

def feature_hidden(feature_name):
    """
    Test if a certain Oscar feature is disabled.
    """
    return (feature_name is not None and
            feature_name in settings.OSCAR_HIDDEN_FEATURES)

def get_model(app_label, model_name):
    """
    Fetches a Django model using the app registry.

    This doesn't require that an app with the given app label exists,
    which makes it safe to call when the registry is being populated.
    All other methods to access models might raise an exception about the
    registry not being ready yet.
    Raises LookupError if model isn't found.
    """
    try:
        return apps.get_model(app_label, model_name)
    except AppRegistryNotReady:
        if apps.apps_ready and not apps.models_ready:
            # If this function is called while `apps.populate()` is
            # loading models, ensure that the module that defines the
            # target model has been imported and try looking the model up
            # in the app registry. This effectively emulates
            # `from path.to.app.models import Model` where we use
            # `Model = get_model('app', 'Model')` instead.
            app_config = apps.get_app_config(app_label)
            # `app_config.import_models()` cannot be used here because it
            # would interfere with `apps.populate()`.
            import_module('%s.%s' % (app_config.name, MODELS_MODULE_NAME))
            # In order to account for case-insensitivity of model_name,
            # look up the model through a private API of the app registry.
            return apps.get_registered_model(app_label, model_name)
        else:
            # This must be a different case (e.g. the model really doesn't
            # exist). We just re-raise the exception.
            raise

def is_model_registered(app_label, model_name):
    """
    Checks whether a given model is registered. This is used to only
    register Oscar models if they aren't overridden by a forked app.
    """
    try:
        apps.get_registered_model(app_label, model_name)
    except LookupError:
        return False
    else:
        return True


text:
#ifndef SRC_BGP_ROUTING_INSTANCE_PEER_MANAGER_H_
#define SRC_BGP_ROUTING_INSTANCE_PEER_MANAGER_H_

#include <boost/asio/ip/tcp.hpp>

#include <map>
#include <string>
#include <vector>

#include "bgp/bgp_peer_key.h"
#include "bgp/ipeer.h"
#include "io/tcp_session.h"

class BgpPeer;
class BgpServer;
class RoutingInstance;
class BgpNeighborResp;
class BgpSandeshContext;

class PeerManager {
public:
    typedef std::multimap<BgpPeerKey, BgpPeer *> BgpPeerKeyMap;
    typedef std::map<std::string, BgpPeer *> BgpPeerNameMap;

    explicit PeerManager(RoutingInstance *instance) : instance_(instance) { }
    virtual ~PeerManager() { }

    virtual BgpPeer *PeerFind(std::string address) const;
    virtual BgpPeer *PeerLookup(std::string name) const;
    virtual BgpPeer *PeerLookup(TcpSession::Endpoint remote_endpoint) const;
    virtual BgpPeer *PeerLocate(BgpServer *server,
                                const BgpNeighborConfig *config);
    void PeerResurrect(std::string name);
    BgpPeer *TriggerPeerDeletion(const BgpNeighborConfig *config);
    virtual void DestroyIPeer(IPeer *ipeer);
    void ClearAllPeers();

    const BgpPeer *NextPeer(const BgpPeerKey &key) const;
    size_t GetNeighborCount(std::string up_or_down);

    size_t size() { return peers_by_key_.size(); }
    const std::string &name() const;
    const RoutingInstance *instance() const { return instance_; }
    RoutingInstance *instance() { return instance_; }
    BgpServer *server() const;

    const BgpPeerKeyMap &peer_map() const { return peers_by_key_; }
    BgpPeerKeyMap *peer_map_mutable() { return &peers_by_key_; }

private:
    friend class PeerManagerTest;
    friend class BgpServerTest;

    void InsertPeerByKey(BgpPeerKey key, BgpPeer *peer);
    void RemovePeerByKey(BgpPeerKey key, BgpPeer *peer);
    void InsertPeerByName(const std::string name, BgpPeer *peer);
    void RemovePeerByName(const std::string name, BgpPeer *peer);

    BgpPeerKeyMap peers_by_key_;
    BgpPeerNameMap peers_by_name_;
    RoutingInstance *instance_;
};

#endif  // SRC_BGP_ROUTING_INSTANCE_PEER_MANAGER_H_


text:
+++
date = "2017-06-14T11:39:06-05:00"
link = "http://styleguides.io/podcast/"
title = "Style Guide Podcast"

+++

A small batch series of interviews on Style Guides, hosted by Anna Debenham and Brad Frost.
<!--more-->


text:
module.exports = [
  'in subfolder three, subfolder six'
];


text:
sudo.extensions.listener = {
  // ###bindEvents
  // Bind the events in the data store to this object's $el
  //
  // `returns` {Object} `this`
  bindEvents: function bindEvents() {
    var e;
    if((e = this.model.data.event || this.model.data.events)) this._handleEvents_(e, 1);
    return this;
  },
  // Use the jQuery `on` or 'off' method, optionally delegating to a selector if present
  // `private`
  _handleEvents_: function _handleEvents_(e, which) {
    var i;
    if(Array.isArray(e)) {
      for(i = 0; i < e.length; i++) {
        this._handleEvent_(e[i], which);
      }
    } else {
      this._handleEvent_(e, which);
    }
  },
  // helper for binding and unbinding an individual event
  // `param` {Object} e. An event descriptor
  // `param` {String} which. `on` or `off`
  // `private`
  _handleEvent_: function _handleEvent_(e, which) {
    if(which) {
      this.$el.on(e.name, e.sel, e.data, typeof e.fn === 'string' ? this[e.fn].bind(this) : e.fn);
    } else {
      // do not re-bind the fn going to off otherwise the unbind will fail
      this.$el.off(e.name, e.sel);
    }
  },
  // ###rebindEvents
  // Convenience method for `this.unbindEvents().bindEvents()`
  //
  // 'returns' {object} 'this'
  rebindEvents: function rebindEvents() {
    return this.unbindEvents().bindEvents();
  },
  // ###unbindEvents
  // Unbind the events in the data store from this object's $el
  //
  // `returns` {Object} `this`
  unbindEvents: function unbindEvents() {
    var e;
    if((e = this.model.data.event || this.model.data.events)) this._handleEvents_(e);
    return this;
  }
};


text:
<?php

/**
 * Traits are a method of horizontal code reuse. Classical inheritance is an
 * example of vertical code reuse. In classical inheritance, there is a
 * hierarchy of classes and code can be shared with between ancestors and
 * children in the hierarchy. If you have two similar classes that do not share
 * a common ancestor there is no way to share code in classical inheritance.
 *
 * For example, given the class hierarchy:
 *
 * ```
 * Animal
 *  |
 *  +- Mammal
 *  |   |
 *  |   +- Bat
 *  |   |
 *  |   +- Mouse
 *  |
 *  +- Bird
 * ```
 *
 * Both `Bat` and `Bird` should have a `fly()` method but the nearest common
 * ancestor is `Animal`. If we add `fly()` to `Animal` we end up with flying
 * mice.
 *
 * The solution in PHP 5.4 is traits. In this example, you would create a
 * `Flyer` trait that has a `fly()` method and say `Bird` and `Bat` both
 * extend the trait.
 *
 * In this way, traits are similar to interfaces. The key difference is that
 * traits can contain method implementations and interfaces can not.
 *
 * Like interfaces, a single class can use multiple traits.
 */

abstract class Animal
{
	abstract public function name();
}

abstract class Mammal extends Animal
{
}

trait Flyer
{
	public function fly()
	{
		/**
		 * Trait methods can call methods of the class they are used by. These
		 * are checked at call time rather than compile time.
		 */
		echo 'I\'m a flying ', $this->name();
		echo "\n";
	}
}

class Bat extends Mammal
{
	/**
	 * The `use` keywords lets a class use a trait. In this case, the `Bat`
	 * class will use the `Flyer` trait.
	 */
	use Flyer;

	public function name()
	{
		return 'Bat';
	}
}

class Mouse extends Mammal
{
	public function name()
	{
		return 'Mouse';
	}
}

class Bird extends Animal
{
	use Flyer;

	public function name()
	{
		return 'Bird';
	}
}

$bird = new Bird();
$bird->fly();

$bat = new Bat();
$bat->fly();

/**
 * The `Mouse` class is not using the `Flyer` trait and has no `fly()` method.
 * This will throw an exception.
 */
$mouse = new Mouse();
$mouse->fly();


text:
package com.github.timofeevda.gwt.rxjs.interop.functions;

import jsinterop.annotations.JsFunction;

@JsFunction
@FunctionalInterface
public interface ResultSelector<T, I, R> {

    R selectResult(T outerValue, I innerValue, int outerIndex, int innerIndex);
}


text:
package com.suscipio_solutions.consecro_mud.Abilities.Spells;
import java.util.Vector;

import com.suscipio_solutions.consecro_mud.Abilities.interfaces.Ability;
import com.suscipio_solutions.consecro_mud.Common.interfaces.CMMsg;
import com.suscipio_solutions.consecro_mud.Common.interfaces.CharStats;
import com.suscipio_solutions.consecro_mud.Common.interfaces.Climate;
import com.suscipio_solutions.consecro_mud.Items.interfaces.Weapon;
import com.suscipio_solutions.consecro_mud.Locales.interfaces.Room;
import com.suscipio_solutions.consecro_mud.MOBS.interfaces.MOB;
import com.suscipio_solutions.consecro_mud.core.CMClass;
import com.suscipio_solutions.consecro_mud.core.CMLib;
import com.suscipio_solutions.consecro_mud.core.CMath;
import com.suscipio_solutions.consecro_mud.core.interfaces.Environmental;
import com.suscipio_solutions.consecro_mud.core.interfaces.Physical;
import com.suscipio_solutions.consecro_mud.core.interfaces.Tickable;

@SuppressWarnings("rawtypes")
public class Spell_WeaknessFire extends Spell
{
	@Override public String ID() { return "Spell_WeaknessFire"; }
	private final static String localizedName = CMLib.lang().L("Weakness to Fire");
	@Override public String name() { return localizedName; }
	private final static String localizedStaticDisplay = CMLib.lang().L("(Weakness to Fire)");
	@Override public String displayText() { return localizedStaticDisplay; }
	@Override public int abstractQuality(){return Ability.QUALITY_MALICIOUS;}
	@Override protected int canAffectCode(){return CAN_MOBS;}
	@Override public int classificationCode(){return Ability.ACODE_SPELL|Ability.DOMAIN_TRANSMUTATION;}

	@Override
	public boolean okMessage(final Environmental myHost, final CMMsg msg)
	{
		if(!super.okMessage(myHost,msg))
			return false;

		if(!(affected instanceof MOB))
			return true;

		final MOB mob=(MOB)affected;
		if((msg.amITarget(mob))&&(msg.targetMinor()==CMMsg.TYP_DAMAGE)
		   &&(msg.sourceMinor()==CMMsg.TYP_FIRE))
		{
			final int recovery=(int)Math.round(CMath.mul((msg.value()),1.5));
			msg.setValue(msg.value()+recovery);
		}
		return true;
	}

	@Override
	public boolean tick(Tickable ticking, int tickID)
	{
		if(!super.tick(ticking,tickID)) return false;
		if(tickID!=Tickable.TICKID_MOB) return false;
		if((affecting()!=null)&&(affecting() instanceof MOB))
		{
			final MOB M=(MOB)affecting();
			final Room room=M.location();
			if(room!=null)
			{
				if((room.getArea().getClimateObj().weatherType(room)==Climate.WEATHER_HEAT_WAVE)
				&&(CMLib.dice().rollPercentage()>M.charStats().getSave(CharStats.STAT_SAVE_FIRE)))
				{
					final int damage=CMLib.dice().roll(1,8,0);
					CMLib.combat().postDamage(invoker,M,null,damage,CMMsg.MASK_MALICIOUS|CMMsg.MASK_ALWAYS|CMMsg.TYP_FIRE,Weapon.TYPE_BURNING,"The scorching heat <DAMAGE> <T-NAME>!");
				}
				else
				if((room.getArea().getClimateObj().weatherType(room)==Climate.WEATHER_DUSTSTORM)
				&&(CMLib.dice().rollPercentage()>M.charStats().getSave(CharStats.STAT_SAVE_FIRE)))
				{
					final int damage=CMLib.dice().roll(1,16,0);
					CMLib.combat().postDamage(invoker,M,null,damage,CMMsg.MASK_MALICIOUS|CMMsg.MASK_ALWAYS|CMMsg.TYP_FIRE,Weapon.TYPE_BURNING,"The burning hot dust <DAMAGE> <T-NAME>!");
				}
				else
				if((room.getArea().getClimateObj().weatherType(room)==Climate.WEATHER_DROUGHT)
				&&(CMLib.dice().rollPercentage()>M.charStats().getSave(CharStats.STAT_SAVE_FIRE)))
				{
					final int damage=CMLib.dice().roll(1,8,0);
					CMLib.combat().postDamage(invoker,M,null,damage,CMMsg.MASK_MALICIOUS|CMMsg.MASK_ALWAYS|CMMsg.TYP_FIRE,Weapon.TYPE_BURNING,"The burning dry heat <DAMAGE> <T-NAME>!");
				}
				else
					return true;
				if((!M.isInCombat())&&(M.isMonster())&&(M!=invoker)&&(invoker!=null)&&(M.location()==invoker.location())&&(M.location().isInhabitant(invoker))&&(CMLib.flags().canBeSeenBy(invoker,M)))
					CMLib.combat().postAttack(M,invoker,M.fetchWieldedItem());
			}
		}
		return true;
	}

	@Override
	public void unInvoke()
	{
		// undo the affects of this spell
		if(!(affected instanceof MOB))
			return;
		final MOB mob=(MOB)affected;
		if(canBeUninvoked())
			mob.tell(L("Your fire weakness is now gone."));

		super.unInvoke();

	}

	@Override
	public void affectCharStats(MOB affectedMOB, CharStats affectedStats)
	{
		super.affectCharStats(affectedMOB,affectedStats);
		affectedStats.setStat(CharStats.STAT_SAVE_FIRE,affectedStats.getStat(CharStats.STAT_SAVE_FIRE)-100);
	}
	@Override
	public boolean invoke(MOB mob, Vector commands, Physical givenTarget, boolean auto, int asLevel)
	{
		final MOB target=getTarget(mob,commands,givenTarget);
		if(target==null) return false;

		if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
			return false;

		boolean success=proficiencyCheck(mob,0,auto);
		if(success)
		{
			final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?L("A shimmering flammable field appears around <T-NAMESELF>."):L("^S<S-NAME> invoke(s) a flammable field around <T-NAMESELF>.^?"));
			if(mob.location().okMessage(mob,msg))
			{
				mob.location().send(mob,msg);
				if(msg.value()<=0)
					success=maliciousAffect(mob,target,asLevel,0,-1)!=null;
			}
		}
		else
			maliciousFizzle(mob,target,L("<S-NAME> attempt(s) to invoke weakness to fire, but fail(s)."));

		return success;
	}
}


text:
function Graph() {
	this._adjMap = {};
}

Graph.prototype.edge = function(from, to, cost) {
	if (!this._adjMap[from]) { this._adjMap[from] = {}; }
	if (!this._adjMap[to]) { this._adjMap[to] = {}; }
	this._adjMap[from][to] = cost;
	this._adjMap[to][from] = cost;
}

function bruteForceRouteDistance(from, route, distance, adjMap, initialDistance, comparator) {
	var toVisit = Object.keys(adjMap[from]).filter(function(city) {
		return route.indexOf(city) == -1;
	});

	if (toVisit.length === 0) {
		return distance;
	}

	return toVisit.reduce(function(acc, to) {
		return comparator(acc, bruteForceRouteDistance(to, route.concat([from]),
			distance + adjMap[from][to], adjMap, initialDistance, comparator));
	}, initialDistance);
}

function bruteForceRoute(adjMap, initialDistance, comparator) {
	return Object.keys(adjMap).reduce(function(acc, city) {
		return comparator(acc, bruteForceRouteDistance(city, [], 0, adjMap, initialDistance, comparator));
	}, initialDistance);
}

//
// brute force algorithm
// applicable to small number of nodes
// complexity: O(N!)
//
Graph.prototype.shortestRoute = function() {
	return bruteForceRoute(this._adjMap, Number.MAX_VALUE, function(a, b) {
		return a < b ? a : b;
	});
}

//
// brute force algorithm
// applicable to small number of nodes
// complexity: O(N!)
//
Graph.prototype.longestRoute = function() {
	return bruteForceRoute(this._adjMap, 0, function(a, b) {
		return a > b ? a : b;
	});
}

module.exports = Graph;


text:
package x509_cert

import (
	"bytes"
	"crypto/tls"
	"crypto/x509"
	"encoding/pem"
	"fmt"
	"io/ioutil"
	"net"
	"net/url"
	"strings"
	"time"

	"github.com/influxdata/telegraf"
	"github.com/influxdata/telegraf/internal"
	_tls "github.com/influxdata/telegraf/internal/tls"
	"github.com/influxdata/telegraf/plugins/inputs"
)

const sampleConfig = `
  ## List certificate sources
  sources = ["/etc/ssl/certs/ssl-cert-snakeoil.pem", "tcp://example.org:443"]

  ## Timeout for SSL connection
  # timeout = "5s"

  ## Optional TLS Config
  # tls_ca = "/etc/telegraf/ca.pem"
  # tls_cert = "/etc/telegraf/cert.pem"
  # tls_key = "/etc/telegraf/key.pem"
`
const description = "Reads metrics from a SSL certificate"

// X509Cert holds the configuration of the plugin.
type X509Cert struct {
	Sources []string          `toml:"sources"`
	Timeout internal.Duration `toml:"timeout"`
	tlsCfg  *tls.Config
	_tls.ClientConfig
}

// Description returns description of the plugin.
func (c *X509Cert) Description() string {
	return description
}

// SampleConfig returns configuration sample for the plugin.
func (c *X509Cert) SampleConfig() string {
	return sampleConfig
}

func (c *X509Cert) locationToURL(location string) (*url.URL, error) {
	if strings.HasPrefix(location, "/") {
		location = "file://" + location
	}

	u, err := url.Parse(location)
	if err != nil {
		return nil, fmt.Errorf("failed to parse cert location - %s", err.Error())
	}

	return u, nil
}

func (c *X509Cert) getCert(u *url.URL, timeout time.Duration) ([]*x509.Certificate, error) {
	switch u.Scheme {
	case "https":
		u.Scheme = "tcp"
		fallthrough
	case "udp", "udp4", "udp6":
		fallthrough
	case "tcp", "tcp4", "tcp6":
		ipConn, err := net.DialTimeout(u.Scheme, u.Host, timeout)
		if err != nil {
			return nil, err
		}
		defer ipConn.Close()

		c.tlsCfg.ServerName = u.Hostname()
		c.tlsCfg.InsecureSkipVerify = true
		conn := tls.Client(ipConn, c.tlsCfg)
		defer conn.Close()

		hsErr := conn.Handshake()
		if hsErr != nil {
			return nil, hsErr
		}

		certs := conn.ConnectionState().PeerCertificates

		return certs, nil
	case "file":
		content, err := ioutil.ReadFile(u.Path)
		if err != nil {
			return nil, err
		}
		var certs []*x509.Certificate
		for {
			block, rest := pem.Decode(bytes.TrimSpace(content))
			if block == nil {
				return nil, fmt.Errorf("failed to parse certificate PEM")
			}

			cert, err := x509.ParseCertificate(block.Bytes)
			if err != nil {
				return nil, err
			}
			certs = append(certs, cert)
			if rest == nil || len(rest) == 0 {
				break
			}
			content = rest
		}
		return certs, nil
	default:
		return nil, fmt.Errorf("unsuported scheme '%s' in location %s", u.Scheme, u.String())
	}
}

func getFields(cert *x509.Certificate, now time.Time) map[string]interface{} {
	age := int(now.Sub(cert.NotBefore).Seconds())
	expiry := int(cert.NotAfter.Sub(now).Seconds())
	startdate := cert.NotBefore.Unix()
	enddate := cert.NotAfter.Unix()

	fields := map[string]interface{}{
		"age":       age,
		"expiry":    expiry,
		"startdate": startdate,
		"enddate":   enddate,
	}

	return fields
}

func getTags(cert *x509.Certificate, location string) map[string]string {
	tags := map[string]string{
		"source":               location,
		"common_name":          cert.Subject.CommonName,
		"serial_number":        cert.SerialNumber.Text(16),
		"signature_algorithm":  cert.SignatureAlgorithm.String(),
		"public_key_algorithm": cert.PublicKeyAlgorithm.String(),
	}

	if len(cert.Subject.Organization) > 0 {
		tags["organization"] = cert.Subject.Organization[0]
	}
	if len(cert.Subject.OrganizationalUnit) > 0 {
		tags["organizational_unit"] = cert.Subject.OrganizationalUnit[0]
	}
	if len(cert.Subject.Country) > 0 {
		tags["country"] = cert.Subject.Country[0]
	}
	if len(cert.Subject.Province) > 0 {
		tags["province"] = cert.Subject.Province[0]
	}
	if len(cert.Subject.Locality) > 0 {
		tags["locality"] = cert.Subject.Locality[0]
	}

	tags["issuer_common_name"] = cert.Issuer.CommonName
	tags["issuer_serial_number"] = cert.Issuer.SerialNumber

	san := append(cert.DNSNames, cert.EmailAddresses...)
	for _, ip := range cert.IPAddresses {
		san = append(san, ip.String())
	}
	for _, uri := range cert.URIs {
		san = append(san, uri.String())
	}
	tags["san"] = strings.Join(san, ",")

	return tags
}

// Gather adds metrics into the accumulator.
func (c *X509Cert) Gather(acc telegraf.Accumulator) error {
	now := time.Now()

	for _, location := range c.Sources {
		u, err := c.locationToURL(location)
		if err != nil {
			acc.AddError(err)
			return nil
		}

		certs, err := c.getCert(u, c.Timeout.Duration*time.Second)
		if err != nil {
			acc.AddError(fmt.Errorf("cannot get SSL cert '%s': %s", location, err.Error()))
		}

		for i, cert := range certs {
			fields := getFields(cert, now)
			tags := getTags(cert, location)

			// The first certificate is the leaf/end-entity certificate which needs DNS
			// name validation against the URL hostname.
			opts := x509.VerifyOptions{
				Intermediates: x509.NewCertPool(),
			}
			if i == 0 {
				opts.DNSName = u.Hostname()
				for j, cert := range certs {
					if j != 0 {
						opts.Intermediates.AddCert(cert)
					}
				}
			}
			if c.tlsCfg.RootCAs != nil {
				opts.Roots = c.tlsCfg.RootCAs
			}

			_, err = cert.Verify(opts)
			if err == nil {
				tags["verification"] = "valid"
				fields["verification_code"] = 0
			} else {
				tags["verification"] = "invalid"
				fields["verification_code"] = 1
				fields["verification_error"] = err.Error()
			}

			acc.AddFields("x509_cert", fields, tags)
		}
	}

	return nil
}

func (c *X509Cert) Init() error {
	tlsCfg, err := c.ClientConfig.TLSConfig()
	if err != nil {
		return err
	}
	if tlsCfg == nil {
		tlsCfg = &tls.Config{}
	}

	c.tlsCfg = tlsCfg

	return nil
}

func init() {
	inputs.Add("x509_cert", func() telegraf.Input {
		return &X509Cert{
			Sources: []string{},
			Timeout: internal.Duration{Duration: 5},
		}
	})
}


text:
package com.strongblackcoffee.rngdoc2;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;

/**
 *
 * @author tsingle
 */
@RunWith(Suite.class)
@Suite.SuiteClasses({com.strongblackcoffee.rngdoc2.SimplifierTest.class,com.strongblackcoffee.rngdoc2.RngdocTest.class})
public class Rngdoc2Suite {

    @BeforeClass
    public static void setUpClass() throws Exception {
    }

    @AfterClass
    public static void tearDownClass() throws Exception {
    }

    @Before
    public void setUp() throws Exception {
    }

    @After
    public void tearDown() throws Exception {
    }

}