text:
__author__ = 'Bohdan Mushkevych'

from datetime import datetime
from threading import RLock

from synergy.db.dao.unit_of_work_dao import UnitOfWorkDao
from synergy.db.dao.job_dao import JobDao
from synergy.db.model.job import Job
from synergy.db.model import job, unit_of_work
from synergy.conf import context
from synergy.conf import settings
from synergy.system import time_helper
from synergy.system.time_qualifier import *
from synergy.system.decorator import thread_safe
from synergy.scheduler.scheduler_constants import COLLECTION_JOB_HOURLY, COLLECTION_JOB_DAILY, \
    COLLECTION_JOB_MONTHLY, COLLECTION_JOB_YEARLY
from synergy.scheduler.tree import MultiLevelTree

class Timetable(object):
    """ Timetable holds all known process trees, where every node presents a timeperiod-driven job"""

    def __init__(self, logger):
        self.lock = RLock()
        self.logger = logger
        self.uow_dao = UnitOfWorkDao(self.logger)
        self.job_dao = JobDao(self.logger)
        self.reprocess = dict()

        # self.trees contain all of the trees and manages much of their life cycle
        # remember to enlist there all trees the system is working with
        self.trees = self._construct_trees_from_context()

        self._register_callbacks()
        self._register_dependencies()
        self.load_tree()
        self.build_trees()
        self.validate()

    def _construct_trees_from_context(self):
        trees = dict()
        for tree_name, context_entry in context.timetable_context.items():
            tree = MultiLevelTree(process_names=context_entry.enclosed_processes,
                                  tree_name=tree_name,
                                  mx_name=context_entry.mx_name,
                                  mx_page=context_entry.mx_page)
            trees[tree_name] = tree
        return trees

    def _register_dependencies(self):
        """ register dependencies between trees"""
        for tree_name, context_entry in context.timetable_context.items():
            tree = self.trees[tree_name]
            assert isinstance(tree, MultiLevelTree)
            for dependent_on in context_entry.dependent_on:
                dependent_on_tree = self.trees[dependent_on]
                assert isinstance(dependent_on_tree, MultiLevelTree)
                tree.register_dependent_on(dependent_on_tree)

    def _register_callbacks(self):
        """ register logic that reacts on reprocessing request
        and create embryo timetable record request"""

        # reprocessing request
        for tree_name, tree in self.trees.items():
            tree.register_reprocess_callback(self._callback_reprocess)

        # skip request
        for tree_name, tree in self.trees.items():
            tree.register_skip_callback(self._callback_skip)

        # callbacks register
        for tree_name, tree in self.trees.items():
            tree.register_create_callbacks(self._callback_create_job_record)

    # *** Call-back methods ***
    def _find_dependant_trees(self, tree_obj):
        """ returns list of trees that are dependent_on given tree_obj """
        dependant_trees = []
        for tree_name, tree in self.trees.items():
            if tree_obj in tree.dependent_on:
                dependant_trees.append(tree)
        return dependant_trees

    def _find_dependant_tree_nodes(self, node_a):
        dependant_nodes = set()
        for tree_b in self._find_dependant_trees(node_a.tree):
            node_b = node_a.find_counterpart_in(tree_b)
            if node_b is None:
                continue
            dependant_nodes.add(node_b)
        return dependant_nodes

    def _reprocess_single_tree_node(self, tree_node):
        """ is called from tree to answer reprocessing request.
        It is possible that timetable record will be transferred to STATE_IN_PROGRESS with no related unit_of_work"""
        uow_id = tree_node.job_record.related_unit_of_work
        if uow_id is not None:
            tree_node.job_record.state = job.STATE_IN_PROGRESS
            uow = self.uow_dao.get_one(uow_id)
            uow.state = unit_of_work.STATE_INVALID
            uow.number_of_retries = 0
            uow.created_at = datetime.utcnow()
            self.uow_dao.update(uow)
            msg = 'Transferred job record %s for %s in timeperiod %s to %s; Transferred unit_of_work to %s' \
                  % (tree_node.job_record.db_id,
                     tree_node.process_name,
                     tree_node.job_record.timeperiod,
                     tree_node.job_record.state,
                     uow.state)

            if tree_node.process_name not in self.reprocess:
                self.reprocess[tree_node.process_name] = dict()
            self.reprocess[tree_node.process_name][tree_node.timeperiod] = tree_node

        else:
            tree_node.job_record.state = job.STATE_EMBRYO
            msg = 'Transferred job record %s for %s in timeperiod %s to %s;' \
                  % (tree_node.job_record.db_id,
                     tree_node.process_name,
                     tree_node.job_record.timeperiod,
                     tree_node.job_record.state)

        tree_node.job_record.number_of_failures = 0
        self.job_dao.update(tree_node.job_record)
        self.logger.warn(msg)
        tree_node.add_log_entry([datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S'), msg])

    @thread_safe
    def _callback_reprocess(self, tree_node):
        """ is called from tree to answer reprocessing request.
        It is possible that job record will be transferred to STATE_IN_PROGRESS with no related unit_of_work"""
        if (tree_node.job_record.is_embryo and tree_node.job_record.number_of_failures == 0) \
            or (tree_node.process_name in self.reprocess
                and tree_node.timeperiod in self.reprocess[tree_node.process_name]):
            # the node has already been marked for re-processing or does not require one
            pass
        else:
            self._reprocess_single_tree_node(tree_node)

        reprocessing_nodes = self._find_dependant_tree_nodes(tree_node)
        for node in reprocessing_nodes:
            node.request_reprocess()

    @thread_safe
    def _callback_skip(self, tree_node):
        """ is called from tree to answer skip request"""
        tree_node.job_record.state = job.STATE_SKIPPED
        uow_id = tree_node.job_record.related_unit_of_work
        if uow_id is not None:
            uow = self.uow_dao.get_one(uow_id)
            uow.state = unit_of_work.STATE_CANCELED
            self.uow_dao.update(uow)
            msg = 'Transferred job record %s in timeperiod %s to %s; Transferred unit_of_work to %s' \
                  % (tree_node.job_record.db_id,
                     tree_node.job_record.timeperiod,
                     tree_node.job_record.state,
                     uow.state)
        else:
            msg = 'Transferred job record %s in timeperiod %s to %s;' \
                  % (tree_node.job_record.db_id,
                     tree_node.job_record.timeperiod,
                     tree_node.job_record.state)

        self.job_dao.update(tree_node.job_record)
        self.logger.warn(msg)
        tree_node.add_log_entry([datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S'), msg])

        if tree_node.process_name in self.reprocess \
                and tree_node.timeperiod in self.reprocess[tree_node.process_name]:
            del self.reprocess[tree_node.process_name][tree_node.timeperiod]

    @thread_safe
    def _callback_create_job_record(self, tree_node):
        """ is called from a tree to create job record in STATE_EMBRYO and bind it to the given tree node"""

        try:
            job_record = self.job_dao.get_one(tree_node.process_name, tree_node.timeperiod)
        except LookupError:
            job_record = Job()
            job_record.state = job.STATE_EMBRYO
            job_record.timeperiod = tree_node.timeperiod
            job_record.process_name = tree_node.process_name

            tr_id = self.job_dao.update(job_record)
            self.logger.info('Created job record %s, with timeperiod %s for process %s'
                             % (str(tr_id), tree_node.timeperiod, tree_node.process_name))
        tree_node.job_record = job_record

    # *** Tree-manipulation methods ***
    @thread_safe
    def get_tree(self, process_name):
        """ return tree that is managing time-periods for given process"""
        for tree_name, tree in self.trees.items():
            if process_name in tree:
                return tree

    @thread_safe
    def _build_tree_by_level(self, collection_name, since):
        """ method iterated thru all documents in all job collections and builds a tree of known system state"""
        try:
            unsupported_records = dict()
            job_records = self.job_dao.get_all(collection_name, since)
            for job_record in job_records:
                tree = self.get_tree(job_record.process_name)
                if tree is not None:
                    tree.update_node(job_record)
                else:
                    unsupported_records[job_record.process_name] = \
                        unsupported_records.get(job_record.process_name, 0) + 1

            for name, counter in unsupported_records.items():
                self.logger.warn('Skipping %r Job records for %s as no tree is handling it.' % (counter, name))

        except LookupError:
            self.logger.warn('No Job Records in %s.' % str(collection_name))

    @thread_safe
    def load_tree(self):
        """ method iterates thru all objects older than synergy_start_timeperiod parameter in job collections
        and loads them into this timetable"""
        timeperiod = settings.settings['synergy_start_timeperiod']
        yearly_timeperiod = time_helper.cast_to_time_qualifier(QUALIFIER_YEARLY, timeperiod)
        monthly_timeperiod = time_helper.cast_to_time_qualifier(QUALIFIER_MONTHLY, timeperiod)
        daily_timeperiod = time_helper.cast_to_time_qualifier(QUALIFIER_DAILY, timeperiod)
        hourly_timeperiod = time_helper.cast_to_time_qualifier(QUALIFIER_HOURLY, timeperiod)

        self._build_tree_by_level(COLLECTION_JOB_HOURLY, since=hourly_timeperiod)
        self._build_tree_by_level(COLLECTION_JOB_DAILY, since=daily_timeperiod)
        self._build_tree_by_level(COLLECTION_JOB_MONTHLY, since=monthly_timeperiod)
        self._build_tree_by_level(COLLECTION_JOB_YEARLY, since=yearly_timeperiod)

    @thread_safe
    def build_trees(self):
        """ method iterates thru all trees and ensures that all time-period nodes are created up till <utc_now>"""
        for tree_name, tree in self.trees.items():
            tree.build_tree()

    @thread_safe
    def validate(self):
        """validates that none of nodes in tree is improperly finalized and that every node has job_record"""
        for tree_name, tree in self.trees.items():
            tree.validate()

    @thread_safe
    def dependent_on_composite_state(self, job_record):
        """ :return instance of <NodesCompositeState> """
        assert isinstance(job_record, Job)
        tree = self.get_tree(job_record.process_name)
        node = tree.get_node(job_record.process_name, job_record.timeperiod)
        return node.dependent_on_composite_state()

    # *** Job manipulation methods ***
    @thread_safe
    def update_job_record(self, job_record, uow, new_state):
        """ method updates job record with a new unit_of_work and new state"""
        job_record.state = new_state
        job_record.related_unit_of_work = uow.db_id
        job_record.start_id = uow.start_id
        job_record.end_id = uow.end_id
        self.job_dao.update(job_record)

        tree = self.get_tree(job_record.process_name)
        tree.update_node(job_record)

        msg = 'Transferred job %s for %s in timeperiod %s to new state %s' \
              % (job_record.db_id, job_record.timeperiod, job_record.process_name, new_state)
        self.logger.info(msg)
        self.add_log_entry(job_record.process_name, job_record.timeperiod, msg)

    @thread_safe
    def failed_on_processing_job_record(self, process_name, timeperiod):
        """method increases node's inner counter of failed processing
        if _skip_node logic returns True - node is set to STATE_SKIP"""
        tree = self.get_tree(process_name)
        node = tree.get_node(process_name, timeperiod)
        node.job_record.number_of_failures += 1
        if tree._skip_the_node(node):
            node.request_skip()
        else:
            # job record is automatically updated in request_skip()
            # so if the node was not skipped - job record has to be updated explicitly
            self.job_dao.update(node.job_record)

    @thread_safe
    def get_next_job_record(self, process_name):
        """returns next job record to work on for given process"""
        if process_name in self.reprocess and len(self.reprocess[process_name]) > 0:
            timeperiod = sorted(self.reprocess[process_name].keys())[0]
            node = self.reprocess[process_name][timeperiod]
            del self.reprocess[process_name][timeperiod]
        else:
            tree = self.get_tree(process_name)
            node = tree.get_next_node(process_name)

        if node.job_record is None:
            node.request_embryo_job_record()
        return node.job_record

    @thread_safe
    def is_job_record_finalizable(self, job_record):
        """ :return True, if the node and all its children are either in STATE_PROCESSED or STATE_SKIPPED"""
        assert isinstance(job_record, Job)
        tree = self.get_tree(job_record.process_name)
        node = tree.get_node(job_record.process_name, job_record.timeperiod)
        return node.is_finalizable()

    @thread_safe
    def add_log_entry(self, process_name, timeperiod, msg):
        """ adds a log entry to the tree node. log entries has no persistence """
        tree = self.get_tree(process_name)
        node = tree.get_node(process_name, timeperiod)
        node.add_log_entry([datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S'), msg])


text:
<?php

namespace Cubiche\Core\Validator\Tests\Fixtures;

use Cubiche\Core\Validator\Assertion;
use Cubiche\Core\Validator\Mapping\ClassMetadata;

/**
 * Post class.
 *
 * @author Ivannis Suárez Jerez <ivannis.suarez@gmail.com>
 */
class Post
{
    /**
     * @var string
     */
    protected $title;

    /**
     * @var string
     */
    protected $content;

    /**
     * @var string[]
     */
    protected $comments;

    /**
     * Post constructor.
     *
     * @param string $title
     * @param string $content
     * @param array  $comments
     */
    public function __construct($title = null, $content = null, $comments = array(null, null))
    {
        $this->title = $title;
        $this->content = $content;
        $this->comments = $comments;
    }

    /**
     * @return string
     */
    public function title()
    {
        return $this->title;
    }

    /**
     * @return string
     */
    public function content()
    {
        return $this->content;
    }

    /**
     * @return string[]
     */
    public function comments()
    {
        return $this->comments;
    }

    /**
     * {@inheritdoc}
     */
    public function equals($other)
    {
        return parent::equals($other) &&
            $this->title() == $other->title() &&
            $this->content() == $other->content()
        ;
    }

    /**
     * {@inheritdoc}
     */
    public static function loadValidatorMetadata(ClassMetadata $classMetadata)
    {
        $classMetadata->addPropertyConstraint('title', Assertion::string()->notBlank());
        $classMetadata->addMethodConstraint('title', Assertion::string()->notBlank());
        $classMetadata->addPropertyConstraint('content', Assertion::string());

        $classMetadata->addPropertyConstraint('title', Assertion::integer()->notBlank(), 'foo');
        $classMetadata->addPropertyConstraint('content', Assertion::integer()->notBlank(), 'foo');
    }
}

redpajama_set_name: RedPajamaGithub


text:
/* global document */

// import React from 'react'
// import ReactDom from 'react-dom'

// import CycleNested from './CycleNested'
// import FunNested from './FunNested'
// import MixNested from './MixNested'

import {beginnerProgram} from '../index'
import App, * as AM from './App'

const rootEl = document.getElementById('app')

// ReactDom.render(<CycleNested />, rootEl)
// ReactDom.render(<MixNested />, rootEl)

beginnerProgram({
  model: AM.init(0, 0, 0),
  update: AM.update,
  view: App
}, rootEl)


text:
#ifndef _lucene_search_multisearcher
#define _lucene_search_multisearcher

//#include "SearchHeader.h"
#include "Searchable.h"
CL_CLASS_DEF(document,Document)
CL_CLASS_DEF(index,Term)

CL_NS_DEF(search)

 /** Implements search over a set of Searchables.
	*
	*
Applications usually need only call the inherited {@link #search(Query)}
	* or {@link #search(Query,Filter)} methods.
	*/
	class CLUCENE_EXPORT MultiSearcher: public Searcher {
  private:
    Searchable** searchables;
		int32_t searchablesLen;
    int32_t* starts;
    int32_t _maxDoc;
	protected:
		int32_t* getStarts();
		int32_t getLength();
  public:
      /** Creates a searcher which searches Searchables. */
      MultiSearcher(Searchable** searchables);

      ~MultiSearcher();

      /** Frees resources associated with this Searcher. */
      void close() ;

	  int32_t docFreq(const CL_NS(index)::Term* term) const ;

      /** For use by {@link HitCollector} implementations. */
	  bool doc(int32_t n, CL_NS(document)::Document* document);

      /** For use by {@link HitCollector} implementations to identify the
       * index of the sub-searcher that a particular hit came from. */
      int32_t searcherIndex(int32_t n) const;

	  int32_t subSearcher(int32_t n) const;

	  int32_t subDoc(int32_t n) const;

      int32_t maxDoc() const;

      TopDocs* _search(Query* query, Filter* filter, const int32_t nDocs) ;

      TopFieldDocs* _search (Query* query, Filter* filter, const int32_t n, const Sort* sort);

      /** Lower-level search API.
       *
       *
{@link HitCollector#collect(int32_t,float_t)} is called for every non-zero
       * scoring document.
       *
       *
Applications should only use this if they need all of the
       * matching documents.  The high-level search API ({@link
       * Searcher#search(Query)}) is usually more efficient, as it skips
       * non-high-scoring hits.
       *
       * @param query to match documents
       * @param filter if non-null, a bitset used to eliminate some documents
       * @param results to receive hits
       */
        void _search(Query* query, Filter* filter, HitCollector* results);

		Query* rewrite(Query* original);
		void explain(Query* query, int32_t doc, Explanation* ret);
    };

CL_NS_END
#endif


text:
-include ../tools.mk

all:
	# compile two different versions of crateA
	$(RUSTC) --crate-type=rlib crateA.rs -C metadata=-1 -C extra-filename=-1
	$(RUSTC) --crate-type=rlib crateA.rs -C metadata=-2 -C extra-filename=-2
	# make crateB depend on version 1 of crateA
	$(RUSTC) --crate-type=rlib crateB.rs --extern crateA=$(TMPDIR)/libcrateA-1.rlib
	# make crateC depend on version 2 of crateA
	$(RUSTC) crateC.rs --extern crateA=$(TMPDIR)/libcrateA-2.rlib 2>&1 | \
		tr -d '\r\n' | $(CGREP) -e \
	"mismatched types.*\
	crateB::try_foo\(foo2\);.*\
	expected struct \`crateA::foo::Foo\`, found struct \`crateA::Foo\`.*\
	different versions of crate \`crateA\`.*\
	mismatched types.*\
	crateB::try_bar\(bar2\);.*\
	expected trait \`crateA::bar::Bar\`, found trait \`crateA::Bar\`.*\
	different versions of crate \`crateA\`"


text:
require 'simplecov'

module SimpleCov::Configuration
  def clean_filters
    @filters = []
  end
end

SimpleCov.configure do
  clean_filters
  load_adapter 'test_frameworks'
end

ENV["COVERAGE"] && SimpleCov.start do
  add_filter "/.rvm/"
end
require 'rubygems'
require 'bundler'
begin
  Bundler.setup(:default, :development)
rescue Bundler::BundlerError => e
  $stderr.puts e.message
  $stderr.puts "Run `bundle install` to install missing gems"
  exit e.status_code
end
require 'test/unit'
require 'shoulda'

require "pry"

require "active_support/concern"
require "active_record"

ActiveRecord::Base.establish_connection(adapter: "sqlite3",
                                        database: ":memory:")

ActiveRecord::Schema.define do
  self.verbose = false

  create_table :test_classes, force: true do |t|
    t.string :store
  end
end

$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'typed-store'

class Test::Unit::TestCase
end


text:
package com.example.developer.whatsapp_tae;

import android.os.AsyncTask;
import android.util.Log;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

/**
 * Created by Erick Samaniego
 * Company Bordev Software Workshop && cometa.tech
 */
public class RestApiClient extends AsyncTask<String,String,String> {

    METHOD MethodType;
    String MethodName;
    String Url;
    Object Params;
    HttpURLConnection urlConnection;
    String TAG = getClass().getName();
    private final  RestInterface RestInterface;
    public enum METHOD {
        POST,PUT,GET,DELETE
    }

    /**
     * Especific every param to send for the rest api
     * @param Url Rest url http://api.dominio.com/
     * @param MethodName Rest Method name users
     * @param Params Rest params can be Variable, JsonObject or List
     * @param Method Rest Method type POST, GET, PUT, DELETE the predeterminate is GET
     * @param restInterface Interface of methods pre and post execute
     */
    public RestApiClient(String Url, String MethodName, Object Params, METHOD Method, RestInterface restInterface) {
        this.Url = Url;
        this.Params = Params;
        this.MethodName = MethodName;
        this.MethodType = Method;
        this.RestInterface = restInterface;
    }

    /**
     * IF you not need send params
     * @param Url Rest url http://api.dominio.com/
     * @param MethodName Rest Method name users
     * @param Method Rest Method type POST, GET, PUT, DELETE the predeterminate is GET
     * @param restInterface Interface of methods pre and post execute
     */
    public RestApiClient(String Url, String MethodName, METHOD Method, RestInterface restInterface) {
        this.Url = Url;
        this.MethodName = MethodName;
        this.MethodType = Method;
        this.RestInterface = restInterface;
    }

    /**
     *  the default method type is GET
     * @param Url Rest url http://api.dominio.com/
     * @param MethodName Rest Method name users
     * @param Params Rest params can be Variable, JsonObject or List
     * @param restInterface Interface of methods pre and post execute
     */
    public RestApiClient(String Url, String MethodName, Object Params, RestInterface restInterface) {
        this.Url = Url;
        this.Params = Params;
        this.MethodName = MethodName;
        this.RestInterface = restInterface;
        this.MethodType = METHOD.GET;
    }

    /**
     *  the default method type is GET and you not need send params
     * @param Url Rest url http://api.dominio.com/
     * @param MethodName Rest Method name users
     * @param restInterface Interface of methods pre and post execute
     */
    public RestApiClient(String Url, String MethodName,  RestInterface restInterface) {
        this.Url = Url;
        this.MethodName = MethodName;
        this.RestInterface = restInterface;
        this.MethodType = METHOD.GET;
    }

    public interface RestInterface{
        void onFinish(String Result);
        void onBefore();
    }

    private void setUrlConnection(String paramsURL){
        URL url;
        try {
            if(MethodType == METHOD.GET) {
                url = new URL(Url + MethodName  + "/" + paramsURL);
                Log.d(TAG,Url + MethodName  + "/" + paramsURL);
            }else{
                url = new URL(Url + MethodName);
            }
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod(MethodType.name());

            if(MethodType == METHOD.POST){
                urlConnection.setDoOutput(true);
                urlConnection.setRequestProperty("Content-Length", String.valueOf(paramsURL.length()));
            }else{
                urlConnection.setDoOutput(false);
            }
            urlConnection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            urlConnection.setRequestProperty("Accept", "application/json");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String paramsToUrlParams(){
        Log.d(TAG, "aqui ando dentro de la funcion nomas");

        if (Params instanceof String[]) {
            Log.d(TAG, "aqui ando");
            String[] Parameters = (String[]) Params;
            StringBuilder UrlParam = new StringBuilder();

            for(String param : Parameters)
            {
                UrlParam.append(param).append("/");
            }
            return UrlParam.toString();

        }else if(Params instanceof ArrayList) {
            return null;

        }else if(Params instanceof JSONObject) {
            return Params.toString();
        }else if(MethodType == METHOD.GET){
            return "";
        }else{
            return null;
        }
    }

    @Override
    protected String doInBackground(String... params) {
        try {
            String paramsURL = paramsToUrlParams();
            if(paramsURL == null){
                Log.i(TAG, "Param invalid please check the documentation");
                return "";
            }
            Log.d(TAG,paramsURL);
            setUrlConnection(paramsURL);
            OutputStream os;
            if(MethodType != METHOD.GET) {

                os = urlConnection.getOutputStream();
                os.write(paramsURL.getBytes("UTF-8"));
                os.flush();
            }

            int statusCode = urlConnection.getResponseCode();
            if (statusCode != HttpURLConnection.HTTP_CREATED && statusCode != HttpURLConnection.HTTP_OK && statusCode != HttpURLConnection.HTTP_ACCEPTED) {
                Log.d(TAG, "doInBackground(): connection failed: statusCode: " + statusCode);

                InputStream content = urlConnection.getErrorStream();
                BufferedReader in = new BufferedReader(new InputStreamReader(content));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = in.readLine()) != null) {
                    sb.append(line).append("\n");
                }

                Log.d(TAG, "doInBackground(): connection failed: response: " + sb.toString());
                urlConnection.disconnect();
                return null;
            }

            InputStream content = urlConnection.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(content));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = in.readLine()) != null) {
                sb.append(line).append("\n");
            }

            in.close();
//                os.close();
            urlConnection.disconnect();

            Log.d(TAG, "doInBackground() responseText: " + sb);
            return sb.toString();

        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        if(this.RestInterface != null){
            this.RestInterface.onBefore();
        }
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        if(this.RestInterface != null){
            this.RestInterface.onFinish(result);
        }

    }
}


text:
Junk is a simple wrapper around git that tracks all the files you're not supposed to commit. This might include your .rvmrc files, sqlite development databases, and any other local project settings files. It's good for keeping your local configs synced across your development machines.

Behind the scenes, junk moves your tracked files into a git repository stored in ~/.junkd and symlinks to them from their original location. If it finds a .gitignore file, junk will make sure git ignores the symlink. Many junk commands just run the analogous git command in ~/.junkd.

## Install

    $ gem install junk

## Requirements

Junk requires a version of git. It will probably work with most versions, but I developed it with 1.7.6.

## How it works

    $ cd myproject
    $ junk init
    Alright, /path/to/myproject now has a junk drawer.

    $ junk track .rvmrc
    Now tracking .rvmrc in your junk drawer

    # Edit .rvmrc

    $ junk status
    # runs git status in your junk drawer

    $ junk add .rvmrc
    $ junk commit -m "tracking my .rvmrc file in junk"

    $ junk remote add origin YOUR_GIT_REMOTE
    $ junk push -u origin master

    # on your other development machine
    $ cd myproject

    # for first time setup
    $ junk clone JUNK_REPO

    # or if you have already cloned the repo
    $ junk pull

    $ junk link
    Linking in myproject's junk drawer.

## Other commands

    $ junk --home
    ~/.junkd

    # to do any custom git stuff like changing your junk remote, just cd to the junk home and go from there.
    $ cd `junk --home`
    # run your git commands here!

    $ cd myproject
    $ junk --drawer
    ~/.junkd/myproject

## Hub support!

Junk supports [hub](https://github.com/defunkt/hub) out of the box. If you have hub installed in your path, junk will see it. This means you can do this:

    $ junk remote add -p origin YOUR_GITHUB_USERNAME/myjunk
    $ junk remote -v
    origin  git@github.com:YOUR_GITHUB_USERNAME/myjunk.git (fetch) # look, hub added expanded your private remote url!
    origin  git@github.com:YOUR_GITHUB_USERNAME/myjunk.git (push)

## License

Junk is licensed under the MIT License. See LICENSE.md for more information.

## Who are you?

I'm [Dave](http://dave.is/).

## That's it?

Well for now! I'm just getting started. Cut me some slack.


text:
#define LAST_TOOL_VAR 7   	// Tool changer Last tool position is saved globally in this Var
int *LastTool 		= &persist.UserData[LAST_TOOL_VAR];

main()
{
	 *LastTool=1;
}


text:
<?php

$view->extend('MauticCoreBundle:Default:content.html.php');
$view['slots']->set('mauticContent', 'page');
$view['slots']->set("headerTitle", $view['translator']->trans('mautic.page.pages'));

$view['slots']->set(
    'actions',
    $view->render(
        'MauticCoreBundle:Helper:page_actions.html.php',
        array(
            'templateButtons' => array(
                'new' => $permissions['page:pages:create']
            ),
            'routeBase'       => 'page'
        )
    )
);
?>

    <?php echo $view->render('MauticCoreBundle:Helper:list_toolbar.html.php', array(
        'searchValue' => $searchValue,
        'searchHelp'  => 'mautic.page.help.searchcommands',
        'action'      => $currentRoute,
        'routeBase'   => 'page',
        'templateButtons' => array(
            'delete' => $permissions['page:pages:deleteown'] || $permissions['page:pages:deleteother']
        )
    )); ?>

        <?php $view['slots']->output('_content'); ?>


text:
<?php
namespace CrudGenerator\Tests\General\Backbone\PreapreForGenerationBackboneFactory;

use CrudGenerator\Backbone\PreapreForGenerationBackboneFactory;
use CrudGenerator\Tests\TestCase;

class GetInstanceTest extends TestCase
{
    public function testInstance()
    {
        $contextStub = $this->createMock('CrudGenerator\Context\CliContext');

        $this->assertInstanceOf(
            'CrudGenerator\Backbone\PreapreForGenerationBackbone',
            PreapreForGenerationBackboneFactory::getInstance($contextStub)
        );
    }
}


text:
package com.intellij.xdebugger.impl.evaluate;

import com.intellij.openapi.Disposable;
import com.intellij.openapi.project.Project;
import com.intellij.ui.JBSplitter;
import com.intellij.xdebugger.XDebuggerBundle;
import com.intellij.xdebugger.XExpression;
import com.intellij.xdebugger.XSourcePosition;
import com.intellij.xdebugger.evaluation.XDebuggerEditorsProvider;
import com.intellij.xdebugger.impl.breakpoints.XExpressionImpl;
import com.intellij.xdebugger.impl.ui.XDebuggerEditorBase;
import com.intellij.xdebugger.impl.ui.XDebuggerExpressionEditor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.*;

/**
 * @author nik
 */
public class CodeFragmentInputComponent extends EvaluationInputComponent {
  private final XDebuggerExpressionEditor myMultilineEditor;
  private final ExpressionInputForm myMainForm = new ExpressionInputForm();
  private final String mySplitterProportionKey;

  public CodeFragmentInputComponent(final @NotNull Project project,
                                    @NotNull XDebuggerEditorsProvider editorsProvider,
                                    final @Nullable XSourcePosition sourcePosition,
                                    @Nullable XExpression statements,
                                    String splitterProportionKey,
                                    Disposable parentDisposable) {
    super(XDebuggerBundle.message("dialog.title.evaluate.code.fragment"));
    myMultilineEditor = new XDebuggerExpressionEditor(project, editorsProvider, "evaluateCodeFragment", sourcePosition,
                                                      statements != null ? statements : XExpressionImpl.EMPTY_CODE_FRAGMENT, true, true, false);

    myMainForm.setName(XDebuggerBundle.message("xdebugger.label.text.code.fragment"));
    myMainForm.addExpressionComponent(myMultilineEditor.getComponent());
    myMainForm.addLanguageComponent(myMultilineEditor.getLanguageChooser());

    mySplitterProportionKey = splitterProportionKey;
  }

  @Override
  @NotNull
  public XDebuggerEditorBase getInputEditor() {
    return myMultilineEditor;
  }

  @Override
  public JPanel getMainComponent() {
    return myMainForm.getMainPanel();
  }

  @Override
  public void addComponent(JPanel contentPanel, JPanel resultPanel) {
    final JBSplitter splitter = new JBSplitter(true, 0.3f, 0.2f, 0.7f);
    splitter.setSplitterProportionKey(mySplitterProportionKey);
    contentPanel.add(splitter, BorderLayout.CENTER);
    splitter.setFirstComponent(myMainForm.getMainPanel());
    splitter.setSecondComponent(resultPanel);
  }
}


text:
package videoPlatformURL

import (
	"net/url"
	"strings"
)

var (
	facebookVideoURL = "https://www.facebook.com/plugins/video.php?href="
)

//FindURL Create a well formated URL for different providers
func FindURL(str string, provider string) string {

	var url string
	switch provider {
	case "dailymotion":
		url = "http://www.dailymotion.com/video/" + string(str)
	case "youtube":
		url = "https://www.youtube.com/watch?v=" + string(str)
	case "proxy":
		url = analyzeDomain(str)
	case "digiteka":
		// if it's an URL
		if strings.Contains(str, "://") {
			url = string(str)
		} else {
			url = "https://www.ultimedia.com/deliver/generic/iframe/mdtk/01836272/src/" + string(str)
		}
	default:
		url = string(str)
	}

	return url
}

func analyzeDomain(str string) string {
	if len(str) > len(facebookVideoURL) && str[0:len(facebookVideoURL)] == facebookVideoURL {
		videoURL, err := url.QueryUnescape(str[len(facebookVideoURL):len(str)])
		if err != nil {
			return str[len(facebookVideoURL):len(str)]
		}
		return videoURL
	}
	return str
}


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.08.09 at 09:22:32 PM IST
//

package com.pacificmetrics.ims.apip.qti.item;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
 *                 The InterpolationTable complexType is the container for interpolation information. An interpolationTable transforms a source float (or integer) by finding the first interpolationTableEntry with a sourceValue that is less than or equal to (subject to includeBoundary) the source value. For example, an interpolation table can be used to map a raw numeric score onto an identifier representing a grade. It may also be used to implement numeric transformations such as those from a simple raw score to a value on a calibrated scale.
 *
 *
 *
Java class for InterpolationTable.Type complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="InterpolationTable.Type">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element ref="{http://www.imsglobal.org/xsd/apip/apipv1p0/qtiitem/imsqti_v2p2}interpolationTableEntry" maxOccurs="unbounded"/>
 *       </sequence>
 *       <attGroup ref="{http://www.imsglobal.org/xsd/apip/apipv1p0/qtiitem/imsqti_v2p2}defaultValue.InterpolationTable.Attr"/>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "InterpolationTable.Type", propOrder = {
    "interpolationTableEntries"
})
@XmlRootElement(name = "interpolationTable")
public class InterpolationTable {

    @XmlElement(name = "interpolationTableEntry", required = true)
    protected List<InterpolationTableEntry> interpolationTableEntries;
    @XmlAttribute(name = "defaultValue")
    protected String defaultValue;

    /**
     * Gets the value of the interpolationTableEntries property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the interpolationTableEntries property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getInterpolationTableEntries().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link InterpolationTableEntry }
     *
     *
     */
    public List<InterpolationTableEntry> getInterpolationTableEntries() {
        if (interpolationTableEntries == null) {
            interpolationTableEntries = new ArrayList<InterpolationTableEntry>();
        }
        return this.interpolationTableEntries;
    }

    /**
     * Gets the value of the defaultValue property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getDefaultValue() {
        return defaultValue;
    }

    /**
     * Sets the value of the defaultValue property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setDefaultValue(String value) {
        this.defaultValue = value;
    }

}


text:
//
// Copyright (c) 2000 by Tech Soft 3D, LLC.
// The information contained herein is confidential and proprietary to
// Tech Soft 3D, LLC., and considered a trade secret as defined under
// civil and criminal statutes.  Tech Soft 3D shall pursue its civil
// and criminal remedies in the event of unauthorized use or misappropriation
// of its trade secrets.  Use of this information by anyone other than
// authorized employees of Tech Soft 3D, LLC. is granted only under a
// written non-disclosure agreement, expressly prescribing the scope and
// manner of such use.
//

// Handles area selection

#ifndef _PMSELECTAREA_H
#define _PMSELECTAREA_H

#include "HTools.h"
#include "HOpConstructRectangle.h"

//! forward class declarations
class ImageWork;
class SimpleHQWidget;

//! Direved from the HOpSelectArea class
//! The PMSelectArea class computes a selection list for objects inside a rectangular area.
/*!
  PMSelectArea employs all of the drawing functionality of HOpConstructRectangle to define a temporary, overlayed rectangular selection
  area, then maps the rectangle information to the HOOPS routine HC_Compute_Selection_By_Area.  This provides the basic
  functionality for window selection.
  The operation consists of the following steps:

Left Button Down:				first point of rectangle

Left Button Down and Drag:	rubberband rectangle to desired dimensions

Left Button Up:				rectangled completed and flushed from scene, selection list computed, objects highlighted, operation ended

  More Detailed Description: see event methods
*/
class MVO_API PMSelectArea : public HOpConstructRectangle
{
public:
	/*! constructor */
    PMSelectArea(HBaseView* view, int DoRepeat=0, int DoCapture=1);
	~PMSelectArea();

	/*!
		Returns a pointer to a character string denoting the name of the operator  'PMSelectArea'
	*/
	virtual const char * GetName();

	/*!
		OnLButtonDown calls through to HOpConstructRectangle then sets a few
		attributes (color and visibility) that are specific to selection by area
		\param hevent An HEventInfo object containing information about the current event.
		\return A value indicating the result of the event handling.
	*/
	virtual int OnLButtonDown(HEventInfo &hevent);

	/*!
		OnLButtonUp maps rectangle information from HOpConstructRectangle into the HOOPS routine
		HC_Compute_Selection_By_Area.  This function also deselects any selected items that are not present in the current
		selection list.
		\param hevent An HEventInfo object containing information about the current event.
		\return A value indicating the result of the event handling.
	*/
    virtual int OnLButtonUp(HEventInfo &hevent);

	HBaseOperator * Clone(); /*! returns a pointer to a copy of the operator */
    int setWidget(SimpleHQWidget * temp_widget);
    int RemoveRectangle(void);

 private:
    SimpleHQWidget * simple_widget;
    //    HEventInfo l_button_up_event;

};

#endif


text:
'use strict';

var grunt = require('grunt');
var getDirRecursiveSync = require('./get-dir-recursive-sync');
var should = require('should');

var destination = [];

describe('Single Subtask', function(){
    before(function(){
        destination = getDirRecursiveSync('./test/tmp/');
    });

    describe('destination', function(){
        it('should contain no extra files', function(){
            destination.should.have.length(4);
        });

        it('should have files copied to exact locations', function(){
            destination.should.containEql('./test/tmp/multidest_1/test/fixtures/input1.txt');
            destination.should.containEql('./test/tmp/multidest_1/test/fixtures/input2.txt');
            destination.should.containEql('./test/tmp/multidest_2/test/fixtures/input1.txt');
            destination.should.containEql('./test/tmp/multidest_2/test/fixtures/input2.txt');
        });
    });

});


text:
require 'sinatra/base'

module Sinatra
  module Config
    def self.registered(app)
      app.configure do
        app.set :wsrep_state_dir, '/etc/mysql/wsrep'

        app.set(:hostname) { `hostname`.chomp }

        logger = ::Logger.new('log/check.log')
        logger.level = ::Logger::INFO
        app.set :check_logger, logger

        error_logger = ::File.new(::File.join('log', 'error.log'), 'a+')
        error_logger.sync = true
        app.set :error_logger, error_logger

        app.set :checkers, {}

        app.set :max_staleness, 10
        app.set :check_interval, 1

        app.set :statsd_host, '127.0.0.1'
        app.set :statsd_port, 8125

        app.set :services, [:xdb, :zk]
      end

      app.configure :test do
        app.set :connection_settings, {
          host: 'localhost',
          username: 'root',
          database: 'health_check',
          reconnect: true
        }
        app.set :zk_connection_settings, {
          host: 'localhost',
          port: 2181,
          timeout: 5
        }
        app.set :zk_outstanding_threshold, 60
        app.set :hostname, 'test.local'

        logger = Logger.new('/dev/null')
        logger.level = Logger::DEBUG
        app.set :check_logger, logger

        app.set :statsd_host, '0.0.0.0'
      end

      app.configure :development do
        app.set :wsrep_state_dir, 'spec/data/3_node_cluster_synced'
        app.set :connection_settings, {
          host: 'localhost',
          username: 'root',
          database: 'health_check',
          reconnect: true
        }

        app.set :zk_connection_settings, {
          host: 'localhost',
          port: 2181,
          timeout: 5
        }
        app.set :zk_outstanding_threshold, 60

        app.set :hostname, 'dev.local'

        logger = Logger.new(STDOUT)
        logger.level = Logger::DEBUG
        app.set :check_logger, logger
      end

      app.configure :production do
        config = YAML.load_file ENV['WHAZZUP_CONFIG']
        app.set :services, config['services'].map(&:to_sym)

        app.set :check_interval, config['check_interval'].to_i if config['check_interval']

        if config['connection_settings']
          app.set :connection_settings, {
            host: 'localhost',
            username: config['connection_settings']['username'],
            password: config['connection_settings']['password'],
            database: 'health_check',
            reconnect: true
          }
        end

        if config['zk']
          app.set :zk_connection_settings, {
            host: config['zk']['host'],
            port: config['zk']['port'],
            timeout: config['zk']['timeout']
          }
          app.set :zk_outstanding_threshold, config['zk']['outstanding_threshold']
        end
      end
    end
  end
end


text:
<?php
/* @var $this yii\web\View */
?>

Welcome, <?= Yii::$app->user->identity->username ?>

Informasi Akun Anda:

 Username: <?= Yii::$app->user->identity->username ?>

 Role: <?= Yii::$app->user->identity->role ?>

Lupa password? Hubungi Admin


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Metasphaeria bromigena R. Sprague

### Remarks
null


text:
package com.datatorrent.lib.appdata.schemas;

import org.junit.Assert;
import org.junit.Test;

import com.google.common.collect.Sets;

public class DataQuerySnapshotTest
{
  @Test
  public void simpleDataQuerySnapshotOneTime()
  {
    Fields fields = new Fields(Sets.newHashSet("a", "b"));

    DataQuerySnapshot query = new DataQuerySnapshot("1", fields);

    Assert.assertEquals("This query should be oneTime.", true, query.isOneTime());
  }

  @Test
  public void simpeDataQuerySnapshotCountdown()
  {
    Fields fields = new Fields(Sets.newHashSet("a", "b"));

    DataQuerySnapshot query = new DataQuerySnapshot("1", fields, 1L);

    Assert.assertEquals("This query should be oneTime.", false, query.isOneTime());
  }
}


text:
using System.IO;
using System.Collections;
using System.Runtime.Serialization;
using System.Diagnostics;

using Alachisoft.NCache.Caching.Queries;

namespace Alachisoft.NCache.Caching.Queries.Filters
{
    class ExpressionBuilder
    {
        public static readonly Predicate TRUE_PREDICATE = new AlwaysTruePredicate();
        public static readonly Predicate FALSE_PREDICATE = new AlwaysFalsePredicate();

        static public Predicate CreateSumFunctionPredicate(string attributeName)
        {
            AggregateFunctionPredicate predicate = new SumPredicate();
            predicate.AttributeName = attributeName;
            return predicate;
        }

        static public Predicate CreateCountFunctionPredicate()
        {
            AggregateFunctionPredicate predicate = new CountPredicate();
            return predicate;
        }

        static public Predicate CreateAverageFunctionPredicate(string attributeName)
        {
            AggregateFunctionPredicate predicate = new AveragePredicate();
            predicate.AttributeName = attributeName;
            return predicate;
        }

        static public Predicate CreateMinFunctionPredicate(string attributeName)
        {
            AggregateFunctionPredicate predicate = new MinPredicate();
            predicate.AttributeName = attributeName;
            return predicate;
        }

        static public Predicate CreateMaxFunctionPredicate(string attributeName)
        {
            AggregateFunctionPredicate predicate = new MaxPredicate();
            predicate.AttributeName = attributeName;
            return predicate;
        }

        static public Predicate CreateLogicalAndPredicate(Predicate lhsPred, Predicate rhsPred)
        {
            if (lhsPred.Equals(FALSE_PREDICATE) || rhsPred.Equals(FALSE_PREDICATE))
                return FALSE_PREDICATE;
            if (lhsPred.Equals(TRUE_PREDICATE))
                return rhsPred;
            if (rhsPred.Equals(TRUE_PREDICATE))
                return lhsPred;

            LogicalAndPredicate inc = null;
            if (lhsPred is LogicalAndPredicate)
                inc = lhsPred as LogicalAndPredicate;

            if (inc == null || inc.Inverse)
            {
                inc = new LogicalAndPredicate();
                inc.Children.Add(lhsPred);
            }
            inc.Children.Add(rhsPred);

            return inc;
        }

        static public Predicate CreateLogicalOrPredicate(Predicate lhsPred, Predicate rhsPred)
        {
            if (lhsPred.Equals(TRUE_PREDICATE) || rhsPred.Equals(TRUE_PREDICATE))
                return TRUE_PREDICATE;
            if (lhsPred.Equals(FALSE_PREDICATE))
                return rhsPred;
            if (rhsPred.Equals(FALSE_PREDICATE))
                return lhsPred;

            LogicalAndPredicate inc = null;
            if (lhsPred is LogicalAndPredicate)
            {
                inc = lhsPred as LogicalAndPredicate;
            }

            if (inc == null || !inc.Inverse)
            {
                inc = new LogicalAndPredicate();
                inc.Invert();
                inc.Children.Add(lhsPred);
            }
            inc.Children.Add(rhsPred);

            return inc;
        }

        static public Predicate CreateEqualsPredicate(object o, object v)
        {
            bool lhsIsGen = o is IGenerator;
            bool rhsIsGen = v is IGenerator;

            if (lhsIsGen || rhsIsGen)
            {
                if (lhsIsGen && rhsIsGen)
                {
                    object lhs = ((IGenerator)o).Evaluate();
                    object rhs = ((IGenerator)v).Evaluate();
                    return lhs.Equals(rhs) ? TRUE_PREDICATE : FALSE_PREDICATE;
                }

                IFunctor func = lhsIsGen ? (IFunctor)v : (IFunctor)o;
                IGenerator gen = lhsIsGen ? (IGenerator)o : (IGenerator)v;

                return new FunctorEqualsGeneratorPredicate(func, gen);
            }

            return new FunctorEqualsFunctorPredicate((IFunctor)o, (IFunctor)v);
        }

        static public Predicate CreateNotEqualsPredicate(object o, object v)
        {
            Predicate pred = CreateEqualsPredicate(o, v);
            if (pred.Equals(TRUE_PREDICATE))
                return FALSE_PREDICATE;
            if (pred.Equals(FALSE_PREDICATE))
                return TRUE_PREDICATE;

            pred.Invert();
            return pred;
        }

        static public Predicate CreateGreaterPredicate(object o, object v)
        {
            bool lhsIsGen = o is IGenerator;
            bool rhsIsGen = v is IGenerator;

            if (lhsIsGen || rhsIsGen)
            {
                if (lhsIsGen && rhsIsGen)
                {
                    object lhs = ((IGenerator)o).Evaluate();
                    object rhs = ((IGenerator)v).Evaluate();
                    return Comparer.Default.Compare(lhs, rhs) > 0
                        ? TRUE_PREDICATE : FALSE_PREDICATE;
                }

                IFunctor func = lhsIsGen ? (IFunctor)v : (IFunctor)o;
                IGenerator gen = lhsIsGen ? (IGenerator)o : (IGenerator)v;

                return new FunctorGreaterGeneratorPredicate(func, gen);
            }

            return new FunctorGreaterFunctorPredicate((IFunctor)o, (IFunctor)v);
        }

        static public Predicate CreateGreaterEqualsPredicate(object o, object v)
        {
            Predicate pred = CreateLesserPredicate(o, v);
            if (pred.Equals(TRUE_PREDICATE))
                return FALSE_PREDICATE;
            if (pred.Equals(FALSE_PREDICATE))
                return TRUE_PREDICATE;

            pred.Invert();
            return pred;
        }

        static public Predicate CreateLikePatternPredicate(object o, object pattern)
        {
            IFunctor functor = o as IFunctor;
            IGenerator generator = pattern as IGenerator;
            return new FunctorLikePatternPredicate(functor, generator);
        }

        static public Predicate CreateLesserPredicate(object o, object v)
        {
            bool lhsIsGen = o is IGenerator;
            bool rhsIsGen = v is IGenerator;

            if (lhsIsGen || rhsIsGen)
            {
                if (lhsIsGen && rhsIsGen)
                {
                    object lhs = ((IGenerator)o).Evaluate();
                    object rhs = ((IGenerator)v).Evaluate();
                    return Comparer.Default.Compare(lhs, rhs) < 0
                        ? TRUE_PREDICATE : FALSE_PREDICATE;
                }

                IFunctor func = lhsIsGen ? (IFunctor)v : (IFunctor)o;
                IGenerator gen = lhsIsGen ? (IGenerator)o : (IGenerator)v;

                return new FunctorLesserGeneratorPredicate(func, gen);
            }

            return new FunctorLesserFunctorPredicate((IFunctor)o, (IFunctor)v);
        }
        static public Predicate CreateLesserEqualsPredicate(object o, object v)
        {
            Predicate pred = CreateGreaterPredicate(o, v);
            if (pred.Equals(TRUE_PREDICATE))
                return FALSE_PREDICATE;
            if (pred.Equals(FALSE_PREDICATE))
                return TRUE_PREDICATE;

            pred.Invert();
            return pred;
        }
    }

    #region /		Generators		/

    #endregion

    #region /		Functors		/

    #endregion

    #region /		Unary Predicates		/

    #endregion

    #region /		Predicates		/

    #endregion

    #region /		Binary Predicates		/

    #endregion
}


text:
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var core_1 = require('@angular/core');
var http_1 = require('@angular/http');
var styles = require('./login.css');
var template = require('./login.html');
var Login = (function () {
    function Login(router, http) {
        this.router = router;
        this.http = http;
    }
    Login.prototype.login = function (event, username, password) {
        var _this = this;
        event.preventDefault();
        var navigationExtras = {
            queryParams: {
                "username": username
            }
        };
        var json = JSON.stringify({
            user: username,
            passw: password
        });
        var params = 'data=' + json;
        var header = new http_1.Headers();
        header.append('Content-type', 'application/x-www-form-urlencoded');
        var id_user;
        this.http.post("http://127.0.0.2:3001/get_one_user", params, { headers: header }) //'data='+JSON.stringify(jj)
            .toPromise()
            .then(function (response) {
            if (response.text().length != 0) {
                id_user = JSON.parse(response.text()).id;
                var user = {
                    id: id_user,
                    username: username,
                };
                localStorage.setItem('currentUser', JSON.stringify(user)); // docasne
                localStorage.setItem('id_token', "123456");
                if (!id_user.isEmpty) {
                    _this.router.navigate(['forumHome']);
                }
            }
        });
        // event.preventDefault();
        // let body = JSON.stringify({ username, password });
        // this.http.post('http://localhost:3001/sessions/create', body, { headers: contentHeaders })
        //   .subscribe(
        //     response => {
        //       localStorage.setItem('id_token', response.json().id_token);
        //       this.router.navigate(['home']);
        //     },
        //     error => {
        //       alert(error.text());
        //       console.log(error.text());
        //     }
        //   );
    };
    Login.prototype.signup = function (event) {
        event.preventDefault();
        this.router.navigate(['signup']);
    };
    Login = __decorate([
        core_1.Component({
            selector: 'login',
            template: template,
            styles: [styles]
        })
    ], Login);
    return Login;
}());
exports.Login = Login;


text:
title: The Year Ahead (2019)
layout: post
---

Last updated: 2019/01/01

Five years ago I would've argued that New Years resolutions were arbitrary and ultimately dishonest. I would have arrogantly told folks that [80% of New Years resolutions fail by February](https://www.businessinsider.com/new-years-resolutions-courses-2016-12) and if you were _really_ serious about accomplishing your goal you would've started before January 1st. But to be frank, five years ago I was a cynical jerk.

I now think there's immense value in taking a moment to pause and reflect on trajectories. And the new year is a natural checkpoint for reflection. Our accomplishments, failures, and future goals can be calibrated and we can see whether our choices have been helping us defeat our limbic system. If the choices have been counter-productive, we can try to adjust our approach.

## Reflection

### 1. Parenting

Being a Dad has been the most rewarding role I've ever undertaken! My kids have grown so much and I'm thankful for the moments during the day I can spend with them . Working remotely provides the flexibility to help put them down for naps, eat with them at lunch time, and see them whenever I exit my office.

**For 2019**: Keep it up, and also create more opportunities to have memorable experiences as a family. We didn't take any notable vacations in 2018 and I'd like to remedy that in 2019.

### 2. Career

After suffering from mild burnout at a previous company, I started work at [Etsy](https://www.etsy.com) in October. It has proven to be a great decision and the new position has rejuvenated my interest/passion for software engineering.

**For 2019**: Produce high quality work and become knowledgeable enough in the Etsy codebase to regularly assist my peers. As a stretch goal, I would like to have published at least one post on our [Code as Craft](https://codeascraft.com/) blog.

### 3. Engineering

I was able to read a couple of technical books this year, but don't really feel like 2018 was a year of engineering growth. I've refreshed my PHP knowledge since working at Etsy and have learned to appreciate it as a language. PHPUnit requires a different approach to testing than RSpec and I'm thankful to have the exposure.

**For 2019**: Read **at least** 2 more technical books, take a linear algebra course, and contribute to open source again. Launch at least 3 more products (I've built them, I just need to release them! Perhaps a story for a future blog post).

### 4. Fitness

2018 was an amazing year for physical improvement. I started cycling regularly and concluded the summer by riding my first metric century (a 62 mile race). I was one of the last people to cross the finish line, but it was a great thrill and I felt proud of the progress I made.

**For 2019**: Ride a full century! Also try to finish 2019 with 1500 total miles (I was just shy of 1000 miles this year).

### 5. Writing

I started this blog in 2018, but ultimately only wrote 1 post. Blogging has never been something I've taken seriously and I'm not going to be too hard on myself for the lack of activity. However, since quitting all social media it's my primary way of sharing my thoughts with the world at large. It's also a great way to get better at communicating which should have benefits in many other areas.

**For 2019**: Keep blogging! I'd like to see at least 10 new posts by the end of 2019. I have ideas for them, I just need to be persistent and make it a priority.

## Conclusion

2018 was one of my better years in terms of personal growth and development. I'm hoping to keep the momentum up going into 2019 and also take advantage of new growth opportunities as I see them. I hope to be more disciplined while also leaving room to enjoy life fully. I hope to approach every interaction by assuming good intentions and practicing empathy.

I'm sure 2019 will have it's share of failures, but these are the things I'll be working towards!


text:
#ifndef QFILEINFO_H
#define QFILEINFO_H

#include <QtCore/qfile.h>
#include <QtCore/qlist.h>
#include <QtCore/qshareddata.h>
#include <QtCore/qmetatype.h>

QT_BEGIN_NAMESPACE

class QDir;
class QDirIteratorPrivate;
class QDateTime;
class QFileInfoPrivate;

class Q_CORE_EXPORT QFileInfo
{
    friend class QDirIteratorPrivate;
public:
    explicit QFileInfo(QFileInfoPrivate *d);

    QFileInfo();
    QFileInfo(const QString &file);
    QFileInfo(const QFile &file);
    QFileInfo(const QDir &dir, const QString &file);
    QFileInfo(const QFileInfo &fileinfo);
    ~QFileInfo();

    QFileInfo &operator=(const QFileInfo &fileinfo);
#ifdef Q_COMPILER_RVALUE_REFS
    inline QFileInfo&operator=(QFileInfo &&other)
    { qSwap(d_ptr, other.d_ptr); return *this; }
#endif

    inline void swap(QFileInfo &other)
    { qSwap(d_ptr, other.d_ptr); }

    bool operator==(const QFileInfo &fileinfo) const;
    inline bool operator!=(const QFileInfo &fileinfo) const { return !(operator==(fileinfo)); }

    void setFile(const QString &file);
    void setFile(const QFile &file);
    void setFile(const QDir &dir, const QString &file);
    bool exists() const;
    static bool exists(const QString &file);
    void refresh();

    QString filePath() const;
    QString absoluteFilePath() const;
    QString canonicalFilePath() const;
    QString fileName() const;
    QString baseName() const;
    QString completeBaseName() const;
    QString suffix() const;
    QString bundleName() const;
    QString completeSuffix() const;

    QString path() const;
    QString absolutePath() const;
    QString canonicalPath() const;
    QDir dir() const;
    QDir absoluteDir() const;

    bool isReadable() const;
    bool isWritable() const;
    bool isExecutable() const;
    bool isHidden() const;
    bool isNativePath() const;

    bool isRelative() const;
    inline bool isAbsolute() const { return !isRelative(); }
    bool makeAbsolute();

    bool isFile() const;
    bool isDir() const;
    bool isSymLink() const;
    bool isRoot() const;
    bool isBundle() const;

    QString readLink() const;
    inline QString symLinkTarget() const { return readLink(); }

    QString owner() const;
    uint ownerId() const;
    QString group() const;
    uint groupId() const;

    bool permission(QFile::Permissions permissions) const;
    QFile::Permissions permissions() const;

    qint64 size() const;

    QDateTime created() const;
    QDateTime lastModified() const;
    QDateTime lastRead() const;

    bool caching() const;
    void setCaching(bool on);

protected:
    QSharedDataPointer<QFileInfoPrivate> d_ptr;

private:
    QFileInfoPrivate* d_func();
    inline const QFileInfoPrivate* d_func() const
    {
        return d_ptr.constData();
    }
};

Q_DECLARE_SHARED(QFileInfo)

typedef QList<QFileInfo> QFileInfoList;

QT_END_NAMESPACE

Q_DECLARE_METATYPE(QFileInfo)

#endif // QFILEINFO_H


text:
package gov.hhs.fha.nhinc.corex12.docsubmission.genericbatch.response.adapter;

import gov.hhs.fha.nhinc.adaptercoresecured.AdapterCOREGenericBatchTransactionSecuredPortType;
import gov.hhs.fha.nhinc.common.nhinccommonadapter.AdapterBatchSubmissionResponseSecuredType;
import gov.hhs.fha.nhinc.common.nhinccommonadapter.AdapterBatchSubmissionSecuredRequestType;
import javax.annotation.Resource;
import javax.xml.ws.BindingType;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.soap.Addressing;

/**
 *
 * @author svalluripalli
 */
@BindingType(value = javax.xml.ws.soap.SOAPBinding.SOAP12HTTP_BINDING)
@Addressing(enabled = true)
public class AdapterCORE_X12DSGenericBatchResponseSecured implements AdapterCOREGenericBatchTransactionSecuredPortType {

    @Resource
    private WebServiceContext context;

    /**
     *
     * @param body
     * @return AdapterBatchSubmissionResponseSecuredType
     */
    @Override
    public AdapterBatchSubmissionResponseSecuredType batchSubmitTransaction(AdapterBatchSubmissionSecuredRequestType body) {
        return new AdapterCORE_X12DSGenericBatchResponseImpl().batchSubmitTransaction(body, context);
    }
}


text:
package io.orber.site.markdown;

import com.petebevin.markdown.MarkdownProcessor;

/**
 * Renders Markdown to HTML.
 * <p>
 * If available uses native Sundown library to render Markdown into HTML. Fall
 * back to using com.petebevin.markdown.MarkdownProcessor if Sundown is
 * unavailable.
 *
 * @author Jeremy Raymond
 *
 * @see https://github.com/vmg/sundown
 * @see http://markdownj.org (https://github.com/myabc/markdownj)
 */
public class Renderer {

    /**
     * Render Markdown into HTML.
     *
     * @param markdown the Markdown
     * @return the rendered HTML
     */
    public String render(String markdown) {
        String html;

        if (Sundown.isAvailable()) {
            html = new Sundown().render(markdown);
        } else {
            MarkdownProcessor markdownProcessor = new MarkdownProcessor();
            html = markdownProcessor.markdown(markdown);
        }
        return html;
    }
}


text:
[![Build Status](https://travis-ci.org/floored1585/quagga-cookbook.svg?branch=master)](https://travis-ci.org/floored1585/quagga-cookbook)
[![Code Climate](https://codeclimate.com/github/floored1585/quagga-cookbook/badges/gpa.svg)](https://codeclimate.com/github/floored1585/quagga-cookbook)
[![GitHub version](https://badge.fury.io/gh/floored1585%2Fquagga-cookbook.svg)](https://badge.fury.io/gh/floored1585%2Fquagga-cookbook)

Description
===========

This is a fork of [https://github.com/ooyala/quagga-cookbook](https://github.com/ooyala/quagga-cookbook).  The functionality here is much different, and this cookbook is not backwards comptaible.

This cookbook provides an interface via attributes to serveral Quagga daemons. It's written with
the intention of deploying Quagga on [Cumulus](http://cumulusnetworks.com) switches, and managing
router configuration as code.

This cookbook currently supports the following daemons:

* BGP
* OSPF
* Zebra

Requirements
============

Tested on:
* Cumulus Linux 1.5.3
* Cumulus Linux 2.5.11
* Cumulus Linux 3.2.68
* Ubuntu 14.04

Attributes
==========

NOTE! Where you see "String or Array" for type, a String may be used _only_ for single values.  Use
an Array of Strings for multiple values.

### General

Attribute        | Description |Type | Default
-----------------|-------------|-----|--------
`node['quagga']['router_id']` | Router-id to use for all protocols. This is superseded by protocol-specific router-ids, if they are defined. | String | `nil`
`node['quagga']['enable_reload']` | Must be true in to enable reloading the quagga service (only applies to certain versions). | Boolean | `true`
`node['quagga']['max_instances']` | Sets /etc/defaults/quagga "MAX_INSTANCES" value. | Integer | `5`
`node['quagga']['integrated_vtysh_config']` | Must be set to true in order to reload quagga (vs restart) on config changes. Details [here](http://www.nongnu.org/quagga/docs/docs-multi/VTY-shell-integrated-configuration.html) and [here](http://docs.cumulusnetworks.com/display/DOCS/Configuring+Quagga). | Boolean | `false`
`node['quagga']['multiple_instance']` | Must be set to true in order to support multiple routing-instances or vrfs. Supported in Cumulus Linux 2.5.3SE and adopted in Cumulus Linux 3.0. | Boolean | `false`
`node['quagga']['interfaces'][$IF_NAME]` | The interface you wish to assign properties to (e.g. `eth0`). | Hash or Array (deprecated) | `nil`

### BGP General
General BGP settings, not specific to any neighbor or peer.

Attribute        | Description |Type | Default
-----------------|-------------|-----|--------
`node['quagga']['bgp']` | A hash containing the BGP processes and their configuration.  Keys are the local ASNs/processes (Integer), values are the data for that process (Hash). | Hash | `{}`
`node['quagga']['bgp'][$LOCAL_ASN]['router_id']` | Sets the router-id for this BGP process. | String | `nil`
`node['quagga']['bgp'][$LOCAL_ASN]['redistribute']` | Route types to redistribute into BGP (eg: `["connected","ospf"]`. | String or Array | `nil`
`node['quagga']['bgp'][$LOCAL_ASN]['hold_time']` | BGP hold time (must also set `keepalive_interval`). | Integer | `nil`
`node['quagga']['bgp'][$LOCAL_ASN]['keepalive_interval']` | BGP keepalive interval (must also set `hold_time`). | Integer | `nil`
`node['quagga']['bgp'][$LOCAL_ASN]['max_paths']` | Maximum number of ECMP paths. | Integer | `nil`
`node['quagga']['bgp'][$LOCAL_ASN]['multipath_relax']` | Allow for ECMP of different ASNs. | Boolean | `false`
`node['quagga']['bgp'][$LOCAL_ASN]['compare_routerid']` | Enable comparison of the router-id during best path selection. | Boolean | `false`
`node['quagga']['bgp'][$LOCAL_ASN]['neighbors']` | A hash containing neighbors and their configuration.  Keys are the neighbor IPs or group names (String), values are the data for that neighbor or group (Hash). | Hash | `nil`
`node['quagga']['bgp'][$LOCAL_ASN]['address_family']` | A hash containing address families and their configuration.  Keys are the family-type names (String), values are the data for that family (Hash). | Hash | `nil`
`node['quagga']['bgp'][$LOCAL_ASN]['address_family'][$FAMILY]['redistribute']` | Route types to redistribute into BGP (eg: `["connected","ripng","ospf6"]`. | String or Array | `nil`
`node['quagga']['bgp'][$LOCAL_ASN]['address_family'][$FAMILY]['max_paths']` | Maximum number of ECMP paths in the address family. | Integer | `nil`
`node['quagga']['bgp'][$LOCAL_ASN]['address_family'][$FAMILY]['aggregate_address']` | Hash of address ranges to aggregate, with optional values. (eg: `{ '100::/64': true, '200::/64': 'summary-only' }`) | Hash | `nil`

### BGP Neighbor

Note! As indicated below, some neighbor options are also valid under address-family (eg: for address-family 'ipv6').
Note #2! If you set attributes under the 'ipv4 unicast' address family, you must use override attributes.

Attribute        | Description |Type | Default
-----------------|-------------|-----|--------
`node['quagga']['bgp'][$LOCAL_ASN]['neighbors'][$NEIGHBOR]['description']` | String describing this neighbor or group. | String | `nil`
`node['quagga']['bgp'][$LOCAL_ASN]['neighbors'][$NEIGHBOR]['peer_group']` | Set to `true` if this is a peer-group. Set to string if peer-group member. | Boolean or String | `nil`
`node['quagga']['bgp'][$LOCAL_ASN]['neighbors'][$NEIGHBOR]['peer_type']` | The neighbor peer type to use with interface or peer-group. | String | `nil`
`node['quagga']['bgp'][$LOCAL_ASN]['neighbors'][$NEIGHBOR]['remote_as']` | The remote-as for this neighbor. | Integer or String | `nil`
`node['quagga']['bgp'][$LOCAL_ASN]['neighbors'][$NEIGHBOR]['local_as']` | The local-as for this neighbor. | Integer or String | `nil`
`node['quagga']['bgp'][$LOCAL_ASN]['neighbors'][$NEIGHBOR]['capability']` | `capability` flags for peer. | Array or String | `nil`
`node['quagga']['bgp'][$LOCAL_ASN]['neighbors'][$NEIGHBOR]['ebgp_multihop']` | Allow eBGP-multihop up to N hops | Integer | `nil`
`node['quagga']['bgp'][$LOCAL_ASN]['neighbors'][$NEIGHBOR]['connect_timer']` | Time in seconds between connection attempts. | Integer | `nil`
`node['quagga']['bgp'][$LOCAL_ASN]['neighbors'][$NEIGHBOR]['default_originate']` | Set to `true` to advertise a default route to this neighbor. | Boolean | `false`
`node['quagga']['bgp'][$LOCAL_ASN]['neighbors'][$NEIGHBOR]['default_originate_map']` | The name of the route-map to use with default-originate. | String | `nil`
`node['quagga']['bgp'][$LOCAL_ASN]['neighbors'][$NEIGHBOR]['next_hop_self']` | Set to `true` to advertise ourselfs as nexthop, Set to `"all"` for iBGP. | Boolean or string. | `false`
`node['quagga']['bgp'][$LOCAL_ASN]['neighbors'][$NEIGHBOR]['peer_group_range']` | The IP range(s) to permit for this group (BGP Dynamic Neighbors). | String or Array | `nil`
`node['quagga']['bgp'][$LOCAL_ASN]['neighbors'][$NEIGHBOR]['soft_reconfig_in']` | Enable soft-reconfiguration-inbound (to enable dispaly of received routes). | Boolean | `false`
`node['quagga']['bgp'][$LOCAL_ASN]['neighbors'][$NEIGHBOR]['prefix_list_in']` | Name of the prefix-list to use for filtering incoming routes. | String | `nil`
`node['quagga']['bgp'][$LOCAL_ASN]['neighbors'][$NEIGHBOR]['prefix_list_out']` | Name of the prefix-list to use for filtering outgoing routes. | String | `nil`
`node['quagga']['bgp'][$LOCAL_ASN]['neighbors'][$NEIGHBOR]['route_map_in']` | Name of the route-map to use for filtering incoming routes. | String | `nil`
`node['quagga']['bgp'][$LOCAL_ASN]['neighbors'][$NEIGHBOR]['route_map_out']` | Name of the route-map to use for filtering outgoing routes. | String | `nil`
`node['quagga']['bgp'][$LOCAL_ASN]['neighbors'][$NEIGHBOR]['route_map_export']` | Name of the route-map to use for filtering exported routes (route-server). | String | `nil`
`node['quagga']['bgp'][$LOCAL_ASN]['neighbors'][$NEIGHBOR]['route_map_import']` | Name of the route-map to use for filtering imported routes (route-server). | String | `nil`
`node['quagga']['bgp'][$LOCAL_ASN]['address_family'][$FAMILY]['neighbors'][$NEIGHBOR]` | Enable neighbor for this address-family (use an empty hash if no options are needed). | Hash | `nil`
`node['quagga']['bgp'][$LOCAL_ASN]['address_family'][$FAMILY]['neighbors'][$NEIGHBOR]['soft_reconfig_in']` | Enable soft-reconfiguration-inbound (to enable dispaly of received routes). | Boolean | `false`
`node['quagga']['bgp'][$LOCAL_ASN]['address_family'][$FAMILY]['neighbors'][$NEIGHBOR]['next_hop_self']` | Set to `true` to advertise ourselfs as nexthop, Set to `"all"` for iBGP. | Boolean or string. | `false`
`node['quagga']['bgp'][$LOCAL_ASN]['address_family'][$FAMILY]['neighbors'][$NEIGHBOR]['capability']` | `capability` flags for peer. | Array or String | `nil`
`node['quagga']['bgp'][$LOCAL_ASN]['address_family'][$FAMILY]['neighbors'][$NEIGHBOR]['default_originate']` | Set to `true` to advertise a default route to this neighbor. | Boolean | `false`
`node['quagga']['bgp'][$LOCAL_ASN]['address_family'][$FAMILY]['neighbors'][$NEIGHBOR]['default_originate_map']` | The name of the route-map to use with default-originate. | String | `nil`
`node['quagga']['bgp'][$LOCAL_ASN]['address_family'][$FAMILY]['neighbors'][$NEIGHBOR]['prefix_list_in']` | Name of the prefix-list to use for filtering incoming routes. | String | `nil`
`node['quagga']['bgp'][$LOCAL_ASN]['address_family'][$FAMILY]['neighbors'][$NEIGHBOR]['prefix_list_out']` | Name of the prefix-list to use for filtering outgoing routes. | String | `nil`
`node['quagga']['bgp'][$LOCAL_ASN]['address_family'][$FAMILY]['neighbors'][$NEIGHBOR]['route_map_in']` | Name of the route-map to use for filtering incoming routes. | String | `nil`
`node['quagga']['bgp'][$LOCAL_ASN]['address_family'][$FAMILY]['neighbors'][$NEIGHBOR]['route_map_out']` | Name of the route-map to use for filtering outgoing routes. | String | `nil`
`node['quagga']['bgp'][$LOCAL_ASN]['address_family'][$FAMILY]['neighbors'][$NEIGHBOR]['route_map_export']` | Name of the route-map to use for filtering exported routes (route-server). | String | `nil`
`node['quagga']['bgp'][$LOCAL_ASN]['address_family'][$FAMILY]['neighbors'][$NEIGHBOR]['route_map_import']` | Name of the route-map to use for filtering imported routes (route-server). | String | `nil`
> NOTE - when using `node['quagga']['bgp'][$LOCAL_ASN]['address_family'][$FAMILY]` with `ipv4 unicast` as $FAMILY you must to use node.normal or higher (node.default will be overwritten)

### OSPF

Attribute        | Description |Type | Default
-----------------|-------------|-----|--------
`node['quagga']['ospf']['router_id']` | Sets the router-id for OSPF. | String | `nil`
`node['quagga']['ospf']['reference_bandwidth']` | Sets the reference bandwidth for OSPF. | String | `nil`
`node['quagga']['ospf']['redistribute']` | Route types to redistribute into OSPF (eg: `["connected","bgp"]`. | String or Array | `[]`
`node['quagga']['ospf']['passive_default']` | Set passive-interface default (Active interfaces must be defined). ***needs tests*** | Boolean | `true`
`node['quagga']['ospf']['passive_ints']` | Names of passive interfaces. | String or Array | `nil`
`node['quagga']['ospf']['areas']` | A Hash containing areas and their configurations.  Keys are the area IDs (eg: 0.0.0.0), values are the data for that area. | Hash | `{}`
`node['quagga']['ospf']['areas'][$AREA]['networks']` | Networks to include in the area. | String or Array | `nil`
`node['quagga']['ospf']['areas'][$AREA]['stub_area']` | Make specific area a stub area | Boolean | `nil`
`node['quagga']['ospf']['networks']` | ***needs description & tests***. | String or Array | `[]`

### OSPF6

Attribute        | Description |Type | Default
-----------------|-------------|-----|--------
`node['quagga']['ospf6']['router_id']` | Sets the router-id for OSPF. | String | `nil`
`node['quagga']['ospf6']['reference_bandwidth']` | Sets the reference bandwidth for OSPF. | String | `nil`
`node['quagga']['ospf6']['redistribute']` | Route types to redistribute into OSPF (eg: `["connected","bgp"]`. | String or Array | `[]`
`node['quagga']['ospf6']['areas']` | A Hash containing areas and their configurations.  Keys are the area IDs (eg: 0.0.0.0), values are the data for that area. | Hash | `{}`
`node['quagga']['ospf6']['areas'][$AREA]['interfaces']` | Interfaces to include in the area. | String or Array | `nil`
`node['quagga']['ospf6']['areas'][$AREA]['stub_area']` | Make specific area a stub area | Boolean | `nil`
`node['quagga']['ospf6']['networks']` | ***needs description & tests***. | String or Array | `[]`

### Prefix Lists

Attribute        | Description |Type | Default
-----------------|-------------|-----|--------
`node['quagga']['prefix_lists']` | A hash containing all of the prefix-lists to configure in quagga.  Keys are the prefix-list names, values are hashes filled with the entries. | Hash | `{}`
`node['quagga']['prefix_lists'][$LIST]` | A hash containing all of the entries in a particular $LIST.  Keys are sequence numbers, values are hashes filled with the details of the entry. | Hash | `{}`
`node['quagga']['prefix_lists'][$LIST][$SEQ]['prefix']` | The prefix affected by this rule (must be `x.x.x.x/x` or `x::x/x` or `any_v6` for any ipv6 prefix). If left out, rule will match any ipv4 prefix | String | `any`
`node['quagga']['prefix_lists'][$LIST][$SEQ]['ge']` | The minimum prefix length to accept (eg: `24` or `128`) | Integer | `nil`
`node['quagga']['prefix_lists'][$LIST][$SEQ]['le']` | The maximum prefix length to accept (eg: `24` or `128`) | Integer | `nil`
`node['quagga']['prefix_lists'][$LIST][$SEQ]['action']` | The action to take (either 'permit' or 'deny'). | String | `nil`

### Route Maps

Attribute        | Description |Type | Default
-----------------|-------------|-----|--------
`node['quagga']['route_maps']` | A hash containing all of the route-maps to configure in quagga.  Keys are the route-map names, values are hashes filled with the entries. | Hash | `{}`
`node['quagga']['route_maps'][$MAP]` | A hash containing all of the entries in a particular $MAP.  Keys are sequence numbers, values are hashes filled with the details of the entry. | Hash | `{}`
`node['quagga']['route_maps'][$MAP][$SEQ]['action']` | The action to take (either 'permit' or 'deny'). | String | `nil`
`node['quagga']['route_maps'][$MAP][$SEQ]['set']` | A hash containing all the actions to set when mapping the route (must be a identified below). If left out the rule will not do anything  | Hash | `{}`
`node['quagga']['route_maps'][$MAP][$SEQ]['set']['aggregator']` | The aggregator AS as well as the aggregator IP address | Hash | `{}`
`node['quagga']['route_maps'][$MAP][$SEQ]['set']['aggregator']` | Hash containing the aggregator AS and IP address | Hash | `{}`
`node['quagga']['route_maps'][$MAP][$SEQ]['set']['aggregator']['as']` | The aggregator AS | Integer | `nil`
`node['quagga']['route_maps'][$MAP][$SEQ]['set']['aggregator']['ip']` | The aggregator IP address | String | `nil`
`node['quagga']['route_maps'][$MAP][$SEQ]['set']['local_preference']` | The local prefernce to set on the route | Integer | `nil`

### Static Routes

Attribute        | Description |Type | Default
-----------------|-------------|-----|--------
`node['quagga']['static_routes']` | A hash containing static routes to configure. This will work for ipv4 and ipv6 static routes.  Keys are the prefixes, values are the next-hop addresses.  | Hash | `nil`
`node['quagga']['static_routes'][$ROUTE]` | The next-hop address for given $ROUTE | String | `any`

### Multiple Routing Instances (VRFs)

Attribute        | Description |Type | Default
-----------------|-------------|-----|--------
`node['quagga']['multiple_instance']` | Must be set to true in order to support multiple routing-instances or vrfs. Supported in Cumulus Linux 2.5.3SE and adopted in Cumulus Linux 3.0. | Boolean | `false`
`node['quagga']['interfaces'][$IF_NAME]` | The interface you wish to assign to a routing table followed by a specific table (e.g. `swp1 table 100`). | Hash or Array | `nil`
`node['quagga']['bgp'][$LOCAL_ASN]['neighbors']` | A hash containing neighbors and their configuration. Local ASN need to have the table specified. Keys are the neighbor IPs or group names followed by (String) values for that neighbor or group (Hash). | Hash | `nil`
`node['quagga']['static_routes'][$ROUTE]` |  A hash, with a specified table, containing static routes to configure.  Keys are the prefixes, values are the next-hop addresses.  | Hash | `nil`

Usage
=====

Simply set the desired attributes (see Attributes section above) then call the proper recipe (quagga::bgpd, quagga::ospfd).  There is also a provider for zebra, but no recipe as of yet.

### BGP Example

The following example will create BGP process 64512 with dynamic neighbors.  Devices in the 10.0.0.0/8 range ('hosts' peer-group) will be able to peer with this process.  Two regular neighbor 192.168.52.1 & 192.168.99.1 are configured here also, one of which is in the peer-group.  Neighbors in the group and the normal neighbor will receive a default route when peered with this instance.

```ruby
node.set['quagga']['bgp']['64512']['log_neighbor_changes'] = true
node.set['quagga']['bgp']['64512']['neighbors']['hosts']['remote_as'] = 64512
node.set['quagga']['bgp']['64512']['neighbors']['hosts']['default_originate'] = true
node.set['quagga']['bgp']['64512']['neighbors']['hosts']['peer_group'] = true
node.set['quagga']['bgp']['64512']['neighbors']['hosts']['peer_group_range'] = '10.0.0.0/8'
node.set['quagga']['bgp']['64512']['neighbors']['192.168.52.1']['remote_as'] = 64512
node.set['quagga']['bgp']['64512']['neighbors']['192.168.52.1']['default_originate'] = true
node.set['quagga']['bgp']['64512']['neighbors']['192.168.99.1']['peer_group'] = 'hosts'

include_recipe 'quagga::bgpd'
```
### Unnumbered BGPv6 Example

The following example will create BGP process 64511 with unnumbered neighbors. We are also required to set the address family when working with these interfaces.

```ruby
node.set['quagga']['bgp']['64511']['neighbors']['swp1']['peer_type'] = 'interface'
node.set['quagga']['bgp']['64511']['neighbors']['swp1']['remote_as'] = 64512
node.set['quagga']['bgp']['64511']['neighbors']['swp1']['soft_reconfig_in'] = true
node.set['quagga']['bgp']['64511']['neighbors']['swp1']['ipv6'] = true
node.set['quagga']['bgp']['64511']['address_family']['ipv6'] = {}

include_recipe 'quagga::bgpd'
```

### OSPF Example

The following example will create an OSPF area 0, with quagga reload enabled and an OSPF-specific router-id.  All interfaces with addresses in 10.0.0.0/8 will actively participate in OSPF, except for the ones explicitly listed as `:passive_ints`.

```ruby
node.set['quagga']['integrated_vtysh_config'] = true
node.set['quagga']['ospf']['router'-id] = 10.0.0.1
node.set['quagga']['ospf']['passive_default'] = false
node.set['quagga']['ospf']['areas'][0.0.0.0]['networks'] = '10.0.0.0/8'
node.set['quagga']['ospf']['passive_ints'] = ['lo', 'br-access']

include_recipe 'quagga::ospfd'
```

### Static Route Example

The following example will create a static route to 10.0.0.0/24 using the next hop of 172.16.1.1

```ruby
node.set['quagga']['static_routes']['10.0.0.0/24'] = '172.16.1.1'

include_recipe 'quagga::zebra'
```
### Multiple Routing-Instaces (VRFs) Example

The following example will create a routing table with a static route, a bgp neighbor and a specific interface all on table 100.

```ruby
node.set['quagga']['multiple_instance'] = true
node.set['quagga']['interfaces']['swp1 table 100'] = {}
node.set['quagga']['bgp']['64512 table 100']['neighbors']['1.1.1.1']['remote_as'] = 64512
node.set['quagga']['static_routes']['10.0.0.0/24'] = '172.16.1.1 table 100'
```

Contributing
============

Any form of contribution is welcome!  Feature requests, bug reports, pull requests, whatever!
If you add features, make sure there are tests for them, and if you change any code, make sure
the existing tests all pass _before_ creating a pull request.

Tests are run on a [Cumulus VX](https://cumulusnetworks.com/cumulus-vx) VM using serverspec.

Testing requirements:
* Vagrant
* VirtualBox

To run the tests (after installing prerequisites):
* `bundle install`
* `rake rubocop`
* `bundle exec rake integration:vagrant`
* `foodcritic .`

Author and License
===================
### Maintainer, Authors and Contributors

| Role			| Individual
|:----------------------|:-----------------------------------------|
| **Author** (pre-0.2)  | [Ooyala Inc.](https://github.com/ooyala)
| **Maintainer** (0.2+) | [Ian Clark](https://github.com/floored1585)
| **Contributor**       | [James Farr Gomez](https://github.com/nertwork)

Copyright 2014, Ooyala Inc.
Copyright 2015-2017, Contributers

### License

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.