text:
using System;
using System.Linq;
using X.App.Com;
using X.Core.Utility;

namespace X.App.Views.wx
{
    public class auth : xview
    {
        protected override int needus
        {
            get
            {
                return 0;
            }
        }
        protected override void InitDict()
        {
            base.InitDict();

            var auth_code = GetReqParms("auth_code");
            if (string.IsNullOrEmpty(auth_code)) Context.Response.Redirect(Wx.Open.Get_AuthUrl(Context.Server.UrlDecode("http://" + cfg.domain + Context.Request.RawUrl)));

            var auth = Wx.Open.Get_AuthInfo(auth_code);

            var dbmp = DB.x_wxmp.SingleOrDefault(o => o.appid == auth.authorization_info.authorizer_appid);
            if (dbmp == null)
            {
                var mp = Wx.Open.Get_MpInfo(auth.authorization_info.authorizer_appid);
                dbmp = new Data.x_wxmp()
                {
                    access_refresh_token = auth.authorization_info.authorizer_refresh_token,
                    access_token = auth.authorization_info.authorizer_access_token,
                    appid = auth.authorization_info.authorizer_appid,
                    expires_in = auth.authorization_info.expires_in,
                    service_type_info = mp.authorizer_info.service_type_info.id,
                    verify_type_info = mp.authorizer_info.verify_type_info.id,
                    alias = mp.authorizer_info.alias,
                    head_img = mp.authorizer_info.head_img,
                    nick_name = mp.authorizer_info.nick_name,
                    user_name = mp.authorizer_info.user_name,
                    token_time = DateTime.Now,
                    open_card = mp.authorizer_info.business_info.open_card,
                    open_pay = mp.authorizer_info.business_info.open_pay,
                    open_scan = mp.authorizer_info.business_info.open_scan,
                    open_shake = mp.authorizer_info.business_info.open_shake,
                    open_store = mp.authorizer_info.business_info.open_store,
                    qrcode_url = mp.authorizer_info.qrcode_url,
                    user_id = cu.user_id,
                    ctime = DateTime.Now
                };
                if (mp.authorization_info.func_info != null)
                {
                    var func = ",";
                    foreach (var t in mp.authorization_info.func_info) func += t.id + ",";
                    dbmp.func_info = func;
                }
                DB.x_wxmp.InsertOnSubmit(dbmp);
            }
            else
            {
                dbmp.access_refresh_token = auth.authorization_info.authorizer_refresh_token;
                dbmp.access_token = auth.authorization_info.authorizer_access_token;
                dbmp.appid = auth.authorization_info.authorizer_appid;
                dbmp.expires_in = auth.authorization_info.expires_in;
            }
            SubmitDBChanges();
            Context.Response.Redirect("/app/mp/list.html");
        }
    }
}


text:
<?php

namespace core\datasources;

use core\datasources\DataSourceInterface;
use core\AbstractModel;
use Monolog\Logger;

/**
 * used for reading/writing info to a file datasource
 *
 * @author Dave Meikle
 */
class RemoteFileDataSource implements DataSourceInterface {

    private $keyname;
    private $logger = null;

    use \core\datasources\traits\CurlResourceTrait;

    public function __construct(Logger $logger) {
        $this->logger = $logger;
    }

    /**
     * query    - a few of the default parameters passed in will not be used for
     *            the basic simplicity of the File I/O
     *
     * @param string queryType  PUT/POST/GET/DELETE #ignored
     * @param AbstractModel entity  #ignored
     * @param string verb       save/delete/get/list #required
     * @param array params      parameters needed for file I/O
     */
    public function query($queryType, AbstractModel $entity, $verb, $params) {

        return $this->$verb($entity, $verb, $params);
    }

    /**
     *
     * @param string $keyName
     */
    public function setDatasourceKey($keyName) {
        $this->keyname = $keyName;
    }

    private function save($content, $filepath) {
        file_put_contents($filepath, $content);
    }

    private function delete($content, $filepath) {
        shell_exec('rm -fr ' . $filepath);
    }

    private function pdf(AbstractModel $entity, $verb, array $params) {

        $queryString = '';
        foreach ($params as $key => $value) {
            $queryString .= "&$key=" . urldecode($value);
        }

        return array('content' => $this->execute($entity->getTablename(), $verb, substr($queryString, 1)));
    }

}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CsvEnumerator
{
    public static class CsvUtil
    {
        public class CsvUnexpectedCharException : Exception
        {
            public string Content { get; private set; }

            public CsvUnexpectedCharException(string content, string message = null)
                : base(message ?? "Unexpected csv content")
            {
                Content = content;
            }
        }

        public static string EncodeCsvField(this string field, bool enforceQuote = false)
        {
            var sb = new StringBuilder();
            foreach (var c in field)
            {
                switch (c)
                {
                    case '"':
                        enforceQuote = true;
                        sb.Append("\"");
                        break;
                    case '\n':
                    case '\r':
                    case ',':
                        enforceQuote = true;
                        break;
                }
                sb.Append(c);
            }
            return enforceQuote ? String.Concat("\"", sb, "\"") : sb.ToString();
        }

        /// <summary>
        /// Decode a csv field from an inpu string
        /// </summary>
        /// <param name="inputStream"></param>
        /// <param name="allowUnmatchedQuote">whether to ignore unmatched quote</param>
        /// <param name="inFile">indicates if this parsing is against a whole file to determine whether to return a null to indicate the end </param>
        /// <returns></returns>
        public static string DecodeCsvField(this string field, bool allowUnmatchedQuote, bool inFile = true)
        {
            return new SeekableString(field).DecodeCsvField(allowUnmatchedQuote, inFile);
        }

        /// <summary>
        /// Decode a csv field from an inpu string
        /// </summary>
        /// <param name="inputStream"></param>
        /// <param name="allowUnmatchedQuote">whether to ignore unmatched quote</param>
        /// <param name="inFile">indicates if this parsing is against a whole file to determine whether to return a null to indicate the end </param>
        /// <returns></returns>
        public static string DecodeCsvField(this ISeekableString inputStream, bool allowUnmatchedQuote, bool inFile = true)
        {
            var count = 0;
            bool? quote = null;
            var sb = new StringBuilder();
            while (true)
            {
                var peek = inputStream.ReadChar();
                switch (peek)
                {
                    case -1:
                        return (inFile && count == 0) ? null : sb.ToString();
                    case '\n':
                    case '\r':
                        if (count == 0)
                        {
                            //line end
                            peek = inputStream.PeekChar();
                            while (peek == '\r' || peek == '\n')
                            {
                                inputStream.ReadChar();
                                peek = inputStream.PeekChar();
                            }
                            return null;
                        }
                        if (quote == true)
                        {
                            sb.Append((char)peek);
                            count++;
                        }
                        else
                        {
                            inputStream.Back();
                            return quote.HasValue ? sb.ToString() : sb.ToString().Trim();
                        }
                        break;
                    case ',':
                        if (quote == true)
                        {
                            sb.Append((char)peek);
                            count++;
                        }
                        else if (count == 0)
                        {
                            return String.Empty;
                        }
                        else
                        {
                            return quote.HasValue ? sb.ToString() : sb.ToString().Trim();
                        }
                        break;
                    case '"':
                        if (count == 0 && quote.HasValue != true)
                        {
                            quote = true;
                        }
                        else if (quote == true)
                        {
                            peek = inputStream.PeekChar();
                            if (peek == '"')
                            {
                                sb.Append((char)inputStream.ReadChar());
                                count++;
                            }
                            else
                            {
                                quote = false;
                            }
                        }
                        else if (count > 0)
                        {
                            if (allowUnmatchedQuote)
                            {
                                sb.Append((char)peek);
                                count++;
                            }
                            else
                            {
                                throw new CsvUnexpectedCharException("\"", "Quote must be encoded");
                            }
                        }
                        break;
                    case ' ':
                        if (count != 0 && quote != false)
                        {
                            sb.Append((char)peek);
                            count++;
                        }
                        break;
                    default:
                        sb.Append((char)peek);
                        count++;
                        break;
                }
            }
        }

        public static IList<IList<string>> ValidateCsv(this ISeekableString csvRefString, IList<string> errors, bool allowEmptyFields = true, bool alignColumnCounts = true)
        {
            var enumable = new CsvEnumerable(csvRefString);
            var dataSet = new List<IList<string>>();
            errors = errors ?? new List<string>() ;
            int? count = null;
            foreach (var record in enumable)
            {
                var recordFields = record.ToList();
                dataSet.Add(recordFields);
                if (alignColumnCounts && count.HasValue && recordFields.Count != count)
                {
                    errors.Add("Column count among rows are different");
                }
                else
                {
                    count = recordFields.Count;
                }
                if (!allowEmptyFields && recordFields.Any(String.IsNullOrEmpty))
                {
                    errors.Add("Empty record found ");
                }
            }
            return errors.Count == 0 ? dataSet : null;
        }
    }
}


text:
require 'nokogiri'

module Nokogiri
  module XML
    class Builder
      class NodeBuilder
        attr_reader :node
      end
    end
  end
end

module Epuber
  class Compiler
    class Generator
      # @return [Epuber::Compiler::CompilationContext]
      #
      attr_reader :compilation_context

      # @param [Epuber::Compiler::CompilationContext] compilation_context
      #
      def initialize(compilation_context)
        @compilation_context = compilation_context
        @book = compilation_context.book
        @target = compilation_context.target
        @file_resolver = compilation_context.file_resolver
      end

      protected

      def pretty_path_for_toc_item(toc_item, fragment: true)
        file = @file_resolver.file_from_request(toc_item.file_request)
        [file.destination_path, fragment ? toc_item.file_fragment : nil].compact.join('#')
      end

      # @param [Epuber::Compiler::FileTypes::AbstractFile] file
      #
      # @return [String]
      #
      def pretty_path(file)
        file.destination_path
      end

      # Helper function for generating XML
      #
      # @yields xml_builder
      # @yieldsparam [Nokogiri::XML::Builder] xml_builder
      #
      # @return [Nokogiri::XML::Document]
      #
      def generate_xml(&block)
        builder = Nokogiri::XML::Builder.new(encoding: 'utf-8') do |xml|
          @xml = xml

          block.call(xml) unless block.nil?

          @xml = nil
        end

        builder.doc
      end
    end
  end
end


text:
package org.pikater.core.agents.system.manager;

import jade.content.lang.Codec;
import jade.content.lang.Codec.CodecException;
import jade.content.onto.Ontology;
import jade.content.onto.OntologyException;
import jade.content.onto.basic.Action;
import jade.content.onto.basic.Result;
import jade.core.AID;
import jade.core.Agent;
import jade.domain.FIPAException;
import jade.domain.FIPANames;
import jade.domain.FIPAService;
import jade.domain.FIPAAgentManagement.FailureException;
import jade.lang.acl.ACLMessage;
import jade.wrapper.AgentController;
import jade.wrapper.ContainerController;
import jade.wrapper.ControllerException;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.sql.Timestamp;
import java.util.Calendar;

import org.pikater.core.CoreConfiguration;
import org.pikater.core.agents.system.Agent_ManagerAgent;
import org.pikater.core.configuration.Arguments;
import org.pikater.core.ontology.AgentManagementOntology;
import org.pikater.core.ontology.TerminationOntology;
import org.pikater.core.ontology.subtrees.agent.TerminateSelf;
import org.pikater.core.ontology.subtrees.management.ComputerInfo;
import org.pikater.core.ontology.subtrees.management.CreateAgent;
import org.pikater.core.ontology.subtrees.management.KillAgent;
import org.pikater.core.ontology.subtrees.management.LoadAgent;
import org.pikater.core.ontology.subtrees.management.SaveAgent;
import org.pikater.core.ontology.subtrees.ping.PingReply;
import org.pikater.core.ontology.subtrees.task.ExecuteTask;

/**
 * User: Kuba
 * Date: 7.11.13
 * Time: 15:51
 */
public class ManagerAgentRequestResponder {
	private Agent_ManagerAgent managerAgent;

	public ManagerAgentRequestResponder(Agent_ManagerAgent managerAgent) {
		this.managerAgent = managerAgent;
	}

	public Object toObject(byte[] bytes) throws IOException, ClassNotFoundException {
		Object object;

		object = new ObjectInputStream(new ByteArrayInputStream(bytes)).readObject();

		return object;
	}

	public ACLMessage respondToSaveAgent(ACLMessage request) throws OntologyException, Codec.CodecException, IOException, ClassNotFoundException {
		Action a = (Action) managerAgent.getContentManager().extractContent(request);
		SaveAgent sa = (SaveAgent) a.getAction();

		int userID = sa.getUserID();

		org.pikater.core.ontology.subtrees.management.Agent agent = sa.getAgent();

		String name = agent.getName(); // TODO - zajistit unikatni pro konkretniho uzivatele
		Timestamp currentTimestamp = new Timestamp(Calendar.getInstance().getTime().getTime());

		String filename = userID + "_" + name + "_" + currentTimestamp.toString().replace(":", "-").replace(" ", "_");

		// save serialized object to file
		byte[] object = sa.getAgent().getObject();
		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(CoreConfiguration.getSavedResultsPath() + filename + ".model"));

		oos.writeObject(toObject(object));
		oos.flush();
		oos.close();
		managerAgent.logInfo("Agent " + name + " saved to file" + filename + ".model");

		ACLMessage reply = request.createReply();
		reply.setContent(filename);
		reply.setPerformative(ACLMessage.INFORM);

		return reply;
	}

	public ACLMessage respondToCreateAgent(ACLMessage request) throws OntologyException, CodecException {

		Action a = (Action) managerAgent.getContentManager().extractContent(request);
		CreateAgent createAgent = (CreateAgent) a.getAction();

		String agentName = createAgent.getName();
		String agentType = createAgent.getType();
		Arguments arguments = createAgent.getArguments();

		String agentNameCreated = managerAgent.createAgentInMyContainer(agentType, agentName, arguments);

		ACLMessage reply = request.createReply();
		reply.setPerformative(ACLMessage.INFORM);
		reply.setContent(agentNameCreated);
		managerAgent.logInfo("Agent " + agentNameCreated + " created.");

		return reply;
	}

	public ACLMessage respondToKillAgent(ACLMessage request) throws OntologyException, CodecException, FIPAException {
		Action a = (Action) managerAgent.getContentManager().extractContent(request);
		KillAgent killAgent = (KillAgent) a.getAction();

		String agentName = killAgent.getName();
		AID agentAID = new AID(agentName, false);

		managerAgent.logInfo("Request to kill " + agentName + " agent");
		Ontology ontology = TerminationOntology.getInstance();
		Codec codec = managerAgent.getCodec();

		ACLMessage msgToAgent = new ACLMessage(ACLMessage.REQUEST);
		msgToAgent.setLanguage(codec.getName());
		msgToAgent.setOntology(ontology.getName());
		msgToAgent.addReceiver(agentAID);

		Action actionToAgent = new Action(agentAID, new TerminateSelf());
		managerAgent.getContentManager().fillContent(msgToAgent, actionToAgent);

		ACLMessage replyFromAgent = FIPAService.doFipaRequestClient(managerAgent, msgToAgent, 10000);
		if (replyFromAgent == null) {
			throw new FailureException("Agent didn't terminate in within 10 sec: " + agentName);
		}
		managerAgent.logInfo("Terminated " + agentName);

		ACLMessage reply = request.createReply();
		reply.setPerformative(ACLMessage.INFORM);
		reply.setContent("OK");
		return reply;
	}

	public ACLMessage respondToLoadAgent(ACLMessage request) throws OntologyException, Codec.CodecException, IOException, ClassNotFoundException, ControllerException {

		Action a = (Action) managerAgent.getContentManager().extractContent(request);
		LoadAgent la = (LoadAgent) a.getAction();
		ExecuteTask fa = la.getFirstAction();

		Agent newAgent;

		if (la.getObject() != null) {
			newAgent = (Agent) toObject(la.getObject());
		} else {

			// read agent from file
			String filename = CoreConfiguration.getSavedResultsPath() + la.getFilename() + ".model";

			//Construct the ObjectInputStream object
			ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(filename));

			newAgent = (Agent) inputStream.readObject();

			inputStream.close();
		}

		managerAgent.logInfo("Resurrected agent : " + newAgent);
		// TODO kdyz se ozivuje 2x ten samej -> chyba

		String agentName = managerAgent.generateName(la.getFilename());

		if (newAgent != null) {
			// get a container controller for creating new agents

			ContainerController container = managerAgent.getContainerController();
			AgentController controller = container.acceptNewAgent(agentName, newAgent);
			controller.start();

		} else {
			throw new ControllerException("Agent not created.");
		}

		managerAgent.logInfo("Loaded agent:   " + agentName);

		ACLMessage reply;

		if (fa != null) {
			// send message with fa action to the loaded agent
			Action ac = new Action();
			ac.setAction(fa);
			ac.setActor(request.getSender());

			Ontology ontology = AgentManagementOntology.getInstance();

			ACLMessage first_message = new ACLMessage(ACLMessage.REQUEST);
			first_message.setLanguage(managerAgent.getCodec().getName());
			first_message.setOntology(ontology.getName());
			first_message.addReceiver(new AID(agentName, AID.ISLOCALNAME));
			first_message.clearAllReplyTo();
			first_message.addReplyTo(request.getSender());
			first_message.setProtocol(FIPANames.InteractionProtocol.FIPA_REQUEST);
			first_message.setConversationId(request.getConversationId());

			managerAgent.getContentManager().fillContent(first_message, ac);
			managerAgent.send(first_message);
		}
		reply = request.createReply();
		reply.setContent(newAgent.getLocalName());
		reply.setPerformative(ACLMessage.INFORM);

		return reply;
	}

	public ACLMessage respondToGetComputerInfo(ACLMessage request) throws OntologyException, CodecException {

		Action a = (Action) managerAgent.getContentManager().extractContent(request);

		managerAgent.logInfo("Request to get ComputerInfo");
		Ontology ontology = AgentManagementOntology.getInstance();
		Codec codec = managerAgent.getCodec();

		int cores = Runtime.getRuntime().availableProcessors();
		String osName = System.getProperty("os.name");

		ComputerInfo computerInfo = new ComputerInfo();
		computerInfo.setOperationSystem(osName);
		computerInfo.setNumberOfCores(cores);

		ACLMessage reply = request.createReply();
		reply.setPerformative(ACLMessage.INFORM);
		reply.setLanguage(codec.getName());
		reply.setOntology(ontology.getName());

		Result result = new Result(a.getAction(), computerInfo);

		try {
			managerAgent.getContentManager().fillContent(reply, result);
		} catch (CodecException e) {
			managerAgent.logException(e.getMessage(), e);
		} catch (OntologyException e) {
			managerAgent.logException(e.getMessage(), e);
		}

		return reply;
	}

	public ACLMessage respondToPing(ACLMessage request) throws OntologyException, CodecException {

		Action a = (Action) managerAgent.getContentManager().extractContent(request);

		managerAgent.logInfo("Request to get Ping");
		Ontology ontology = AgentManagementOntology.getInstance();
		Codec codec = managerAgent.getCodec();

		ACLMessage reply = request.createReply();
		reply.setPerformative(ACLMessage.INFORM);
		reply.setLanguage(codec.getName());
		reply.setOntology(ontology.getName());

		Result result = new Result(a.getAction(), new PingReply());

		try {
			managerAgent.getContentManager().fillContent(reply, result);
		} catch (CodecException e) {
			managerAgent.logException(e.getMessage(), e);
		} catch (OntologyException e) {
			managerAgent.logException(e.getMessage(), e);
		}

		return reply;

	}

}


text:
/*
 * Service class
 * Created on 17 déc. 2012 ( Time 15:40:00 )
 */

package org.demo.review.service;

import java.util.List;

import org.demo.review.bean.Review;
import org.demo.review.dao.JpaReviewDAO;
import org.telosys.starterkits.strutsjpa.EntityManagerHelper;
import org.telosys.starterkits.strutsjpa.IServices;
import javax.persistence.PersistenceException;

import com.opensymphony.xwork2.util.logging.Logger;
import com.opensymphony.xwork2.util.logging.LoggerFactory;

import org.demo.review.bean.ReviewKey;

public class ReviewServices implements IServices<Review, ReviewKey> {

	protected final Logger LOG = LoggerFactory.getLogger(ReviewServices.class);

	public Review load(final ReviewKey id) {
		if (LOG.isDebugEnabled()) LOG.debug("load");
		Review review;
		try {
			EntityManagerHelper.beginTransaction();
			JpaReviewDAO reviewDAO = new JpaReviewDAO();
			review = reviewDAO.findById(id);
			EntityManagerHelper.commitAndCloseEntityManager();
		} catch (PersistenceException ex) {
			LOG.error("Error", ex);
			throw ex;
		} finally {
			if (EntityManagerHelper.isCloseEntityManager() == false) EntityManagerHelper.rollback();
		}
		return review ;
	}

	public Review save(final Review entity) {
		if (LOG.isDebugEnabled()) LOG.debug("save");
		Review entityNew;
		try {
			EntityManagerHelper.beginTransaction();
			JpaReviewDAO reviewDAO = new JpaReviewDAO();
			entityNew = reviewDAO.update(entity);
			EntityManagerHelper.commitAndCloseEntityManager();
		} catch (PersistenceException ex) {
			LOG.error("Error", ex);
			throw ex;
		} finally {
			if (EntityManagerHelper.isCloseEntityManager() == false) EntityManagerHelper.rollback();
		}
		return entityNew;
	}

	public void delete(final ReviewKey id) {
		if (LOG.isDebugEnabled()) LOG.debug("delete");
		try {
			EntityManagerHelper.beginTransaction();
			JpaReviewDAO reviewDAO = new JpaReviewDAO();
			reviewDAO.delete(id);
			EntityManagerHelper.commitAndCloseEntityManager();
		} catch (PersistenceException ex) {
			LOG.error("Error", ex);
			throw ex;
		} finally {
			if (EntityManagerHelper.isCloseEntityManager() == false) EntityManagerHelper.rollback();
		}
	}

	public List<Review> search(final Review review) {
		if (LOG.isDebugEnabled()) LOG.debug("search");
		List<Review> liste;
		try {
			EntityManagerHelper.beginTransaction();
			JpaReviewDAO reviewDAO = new JpaReviewDAO();
			liste = reviewDAO.search(review);
			EntityManagerHelper.commitAndCloseEntityManager();
		} catch (PersistenceException ex) {
			LOG.error("Error", ex);
			throw ex;
		} finally {
			if (EntityManagerHelper.isCloseEntityManager() == false) EntityManagerHelper.rollback();
		}
		return liste;
	}

}


text:
import yargs from 'yargs';

export default {
  /**
   * Task name
   * @type {String}
   */
  name: 'sitecore:transforms',

  /**
   * Task description
   * @type {String}
   */
  description: 'Apply transforms and publish to project.',

  /**
   * Task default configuration
   * @type {Object}
   */
  config: {
    src: './src',
    options: {},
    deps: [],
  },

  /**
   * Task help options
   * @type {Object}
   */
  help: {
    'src, -s': 'Publish all `.transforms` files located within directory',
    'dest, -d': 'Destination directory for deployment',
  },

  /**
   * Task function
   * @param {object} config
   * @param {Function} end
   * @param {Function} error
   */
  fn(config, end, error) {
    if (!config) {
      error();
    }

    /* eslint no-unused-vars: 0 */
    const sample = yargs.argv.sample || config.sample;

    end();
  },
};


text:
package com.facebook.buck.features.rust;

import com.facebook.buck.core.model.FlavorDomain;
import com.facebook.buck.core.model.TargetConfiguration;
import com.facebook.buck.core.toolchain.ToolchainCreationContext;
import com.facebook.buck.core.toolchain.ToolchainFactory;
import com.facebook.buck.core.toolchain.ToolchainProvider;
import com.facebook.buck.cxx.toolchain.CxxPlatformsProvider;
import com.facebook.buck.cxx.toolchain.UnresolvedCxxPlatform;
import com.facebook.buck.util.stream.RichStream;
import java.util.Optional;

/** Constructs {@link RustToolchain}s. */
public class RustToolchainFactory implements ToolchainFactory<RustToolchain> {

  @Override
  public Optional<RustToolchain> createToolchain(
      ToolchainProvider toolchainProvider,
      ToolchainCreationContext context,
      TargetConfiguration toolchainTargetConfiguration) {

    CxxPlatformsProvider cxxPlatformsProviderFactory =
        toolchainProvider.getByName(
            CxxPlatformsProvider.DEFAULT_NAME,
            toolchainTargetConfiguration,
            CxxPlatformsProvider.class);
    FlavorDomain<UnresolvedCxxPlatform> cxxPlatforms =
        cxxPlatformsProviderFactory.getUnresolvedCxxPlatforms();
    UnresolvedCxxPlatform defaultCxxPlatform =
        cxxPlatformsProviderFactory.getDefaultUnresolvedCxxPlatform();

    RustPlatformFactory platformFactory =
        ImmutableRustPlatformFactory.of(context.getBuckConfig(), context.getExecutableFinder());

    FlavorDomain<UnresolvedRustPlatform> rustPlatforms =
        FlavorDomain.from(
            "Rust Platforms",
            RichStream.from(cxxPlatforms.getValues())
                // TODO: Allow overlaying flavor-specific section configuration.
                .map(
                    cxxPlatform ->
                        platformFactory.getPlatform(
                            cxxPlatform.getFlavor().getName(),
                            cxxPlatform,
                            context.getProcessExecutor()))
                .toImmutableList());
    UnresolvedRustPlatform defaultRustPlatform =
        rustPlatforms.getValue(defaultCxxPlatform.getFlavor());

    return Optional.of(RustToolchain.of(defaultRustPlatform, rustPlatforms));
  }
}


text:
module xlib.reflection.variables {

  export interface IOptions {}

}


text:
"""
This module facilitates processing of Kaluza-generated flow
cytometry data. The user can choose multiple criteria to define
data points of interest. One or more Kaluza csv files can then
be imported, and the data points will be extracted and exported
to a new csv.
"""

import flowstats.gui

if __name__ == '__main__':
    flowstats.gui.main()


text:
package com.msopentech.odatajclient.engine.data.metadata.edm;

import com.fasterxml.jackson.annotation.JsonProperty;

public abstract class AbstractAnnotations extends AbstractEdm {

    private static final long serialVersionUID = 4926640428016042620L;

    @JsonProperty(value = "Target", required = true)
    private String target;

    @JsonProperty("Qualifier")
    private String qualifier;

    public String getTarget() {
        return target;
    }

    public void setTarget(final String target) {
        this.target = target;
    }

    public String getQualifier() {
        return qualifier;
    }

    public void setQualifier(final String qualifier) {
        this.qualifier = qualifier;
    }
}


text:
package org.apache.zookeeper.server.admin;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.PropertyNamingStrategy;
import org.codehaus.jackson.map.SerializationConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JsonOutputter implements CommandOutputter {
    static final Logger LOG = LoggerFactory.getLogger(JsonOutputter.class);

    public static final String ERROR_RESPONSE = "{\"error\": \"Exception writing command response to JSON\"}";

    private ObjectMapper mapper;

    public JsonOutputter() {
        mapper = new ObjectMapper();
        mapper.configure(SerializationConfig.Feature.WRITE_ENUMS_USING_TO_STRING, true);
        mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true);
        mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
    }

    @Override
    public String getContentType() {
        return "application/json";
    }

    @Override
    public void output(CommandResponse response, PrintWriter pw) {
        try {
            mapper.writeValue(pw, response.toMap());
        } catch (JsonGenerationException e) {
            LOG.warn("Exception writing command response to JSON:", e);
            pw.write(ERROR_RESPONSE);
        } catch (JsonMappingException e) {
            LOG.warn("Exception writing command response to JSON:", e);
            pw.write(ERROR_RESPONSE);
        } catch (IOException e) {
            LOG.warn("Exception writing command response to JSON:", e);
            pw.write(ERROR_RESPONSE);
        }
    }

}


text:
Encrypter::Encrypter()
{

}

void Encrypter::encrypt(int start, int end, string password, string file) {
    Salt* salt = new TimeSaltGeneration(512 - password.length());
    string generatedSalt = salt->saltedValue(password);

    string hash = password;
    SHADriver shaDriver;
    for(int i = 0; i < state.getN_hashing(); i++) {
        hash = shaDriver.sha256(hash);
    }
    FileReader fr(file);
    string fileContent = fr.read(start, end - start + 1);

    CrypticAlgorithm* c_algorithm = new AESAlgorithm;
    string* algorithmArgs = new string[2];
    algorithmArgs[0] = hash;
    algorithmArgs[1] = fileContent;
    int n_args = 2;

    string encryptedContent = c_algorithm->encrypt(algorithmArgs, n_args);

    FileWriter fw(file);
    string data_writable = generatedSalt + state.getOpeningDelimiter() + encryptedContent + state.getClosingDelimiter();
    fw.write(start, end, data_writable);
    delete algorithmArgs;
}


text:
<!DOCTYPE html>

  {%include head.html%}

    {%include banner.html%}

          {% include lssinglecat.html cat='gatherings' %}

{{page.title}}

            {{ content }}


text:
__author__ = 'stowellc17'

LEVEL_DEBUG = 0
LEVEL_INFO = 1
LEVEL_WARNING = 2
LEVEL_ERROR = 3

class NotifyCategory:
    def __init__(self, notify, name):
        self.notify = notify
        self.name = name

    def debug(self, message):
        if self.notify.can_output(LEVEL_DEBUG):
            print('|DEBUG| %s: %s' % (self.name, message))

    def info(self, message):
        if self.notify.can_output(LEVEL_INFO):
            print('|INFO| %s: %s' % (self.name, message))

    def warning(self, message):
        if self.notify.can_output(LEVEL_WARNING):
            print('|WARNING| %s: %s' % (self.name, message))

    def error(self, message):
        if self.notify.can_output(LEVEL_ERROR):
            print('|ERROR| %s: %s' % (self.name, message))
            app.exit()

class Notifier:
    def __init__(self):
        self.notify_level = LEVEL_DEBUG

    def can_output(self, notify_level):
        return notify_level >= self.notify_level

    def new_category(self, name):
        return NotifyCategory(self, name)

global_notify = Notifier()


text:
import React, { FC } from 'react';
import { styled, Theme } from '@storybook/theming';
import { transparentize } from 'polished';

import { withReset } from '../typography/shared';

const breakpoint = 600;

export interface DocsPageProps {
  title: string;
  subtitle?: string;
}

export const Title = styled.h1<{}>(withReset, ({ theme }: { theme: Theme }) => ({
  color: theme.color.defaultText,
  fontSize: theme.typography.size.m3,
  fontWeight: theme.typography.weight.black,
  lineHeight: '32px',

  [`@media (min-width: ${breakpoint}px)`]: {
    fontSize: theme.typography.size.l1,
    lineHeight: '36px',
    marginBottom: '.5rem', // 8px
  },
}));

export const Subtitle = styled.h2<{}>(withReset, ({ theme }: { theme: Theme }) => ({
  fontWeight: theme.typography.weight.regular,
  fontSize: theme.typography.size.s3,
  lineHeight: '20px',
  borderBottom: 'none',
  marginBottom: 15,

  [`@media (min-width: ${breakpoint}px)`]: {
    fontSize: theme.typography.size.m1,
    lineHeight: '28px',
    marginBottom: 24,
  },

  color: transparentize(0.25, theme.color.defaultText),
}));

export const DocsContent = styled.div({
  maxWidth: 1000,
  width: '100%',
});

export const DocsWrapper = styled.div<{}>(({ theme }) => ({
  background: theme.background.content,
  display: 'flex',
  justifyContent: 'center',
  padding: '4rem 20px',
  minHeight: '100vh',
  boxSizing: 'border-box',

  [`@media (min-width: ${breakpoint}px)`]: {},
}));

export const DocsPageWrapper: FC = ({ children }) => (
  <DocsWrapper>
    <DocsContent>{children}</DocsContent>
  </DocsWrapper>
);


text:
package com.github.dockerjava.jaxrs;

import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
import com.github.dockerjava.api.DockerClientException;
import com.github.dockerjava.api.command.*;
import com.github.dockerjava.core.DockerClientConfig;
import com.github.dockerjava.jaxrs.util.JsonClientFilter;
import com.github.dockerjava.jaxrs.util.ResponseStatusExceptionFilter;
import com.github.dockerjava.jaxrs.util.SelectiveLoggingFilter;
import com.google.common.base.Preconditions;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.glassfish.jersey.CommonProperties;
import org.glassfish.jersey.SslConfigurator;
import org.glassfish.jersey.apache.connector.ApacheClientProperties;
import org.glassfish.jersey.apache.connector.ApacheConnectorProvider;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.client.ClientProperties;
import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;

import javax.net.ssl.SSLContext;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import java.io.IOException;
import java.net.URI;
import java.util.logging.Logger;

public class DockerCmdExecFactoryImpl implements DockerCmdExecFactory {

    private static final Logger LOGGER = Logger.getLogger(DockerCmdExecFactoryImpl.class.getName());
    private Client client;
    private WebTarget baseResource;

    @Override
    public void init(DockerClientConfig dockerClientConfig) {
        Preconditions.checkNotNull(dockerClientConfig, "config was not specified");

        ClientConfig clientConfig = new ClientConfig();
        clientConfig.connectorProvider(new ApacheConnectorProvider());
        clientConfig.property(CommonProperties.FEATURE_AUTO_DISCOVERY_DISABLE, true);

        clientConfig.register(ResponseStatusExceptionFilter.class);
        clientConfig.register(JsonClientFilter.class);
        clientConfig.register(JacksonJsonProvider.class);

        if (dockerClientConfig.isLoggingFilterEnabled()) {
            clientConfig.register(new SelectiveLoggingFilter(LOGGER, true));
        }

        if (dockerClientConfig.getReadTimeout() != null) {
            int readTimeout = dockerClientConfig.getReadTimeout();
            clientConfig.property(ClientProperties.READ_TIMEOUT, readTimeout);
        }

        URI originalUri = dockerClientConfig.getUri();

        SSLContext sslContext;
        try {
            sslContext = dockerClientConfig.getSslConfig().getSSLContext();
        } catch(Exception ex) {
            throw new DockerClientException("Error in SSL Configuration", ex);
        }
        if (sslContext == null) sslContext = SslConfigurator.getDefaultContext();

        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(getSchemeRegistry(originalUri, sslContext));
        connManager.setMaxTotal(dockerClientConfig.getMaxTotalConnections());
        connManager.setDefaultMaxPerRoute(dockerClientConfig.getMaxPerRoutConnections());
        clientConfig.property(ApacheClientProperties.CONNECTION_MANAGER, connManager);

        ClientBuilder clientBuilder = ClientBuilder.newBuilder().withConfig(clientConfig);

        clientBuilder.sslContext(sslContext);

        client = clientBuilder.build();

        if (originalUri.getScheme().equals("unix")) {
            dockerClientConfig.setUri(UnixConnectionSocketFactory.sanitizeUri(originalUri));
        }
        WebTarget webResource = client.target(dockerClientConfig.getUri());

        if (dockerClientConfig.getVersion() == null || dockerClientConfig.getVersion().isEmpty()) {
            baseResource = webResource;
        } else {
            baseResource = webResource.path("v" + dockerClientConfig.getVersion());
        }

        if (dockerClientConfig.getHttpUsername() != null && !dockerClientConfig.getHttpUsername().isEmpty() ) {
            HttpAuthenticationFeature basicAuth = HttpAuthenticationFeature.basic(
                    dockerClientConfig.getHttpUsername(),
                    dockerClientConfig.getHttpPassword()
            );
            baseResource.register(basicAuth);
        }

    }

    private org.apache.http.config.Registry<ConnectionSocketFactory> getSchemeRegistry(final URI originalUri, SSLContext sslContext) {
      RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.create();
      registryBuilder.register("http", PlainConnectionSocketFactory.getSocketFactory());
      if (sslContext != null) {
        registryBuilder.register("https", new SSLConnectionSocketFactory(sslContext));
      }
      registryBuilder.register("unix", new UnixConnectionSocketFactory(originalUri));
      return registryBuilder.build();
      }

    protected WebTarget getBaseResource() {
        Preconditions.checkNotNull(baseResource, "Factory not initialized. You probably forgot to call init()!");
        return baseResource;
    }

    @Override
    public AuthCmd.Exec createAuthCmdExec() {
        return new AuthCmdExec(getBaseResource());
    }

    @Override
    public InfoCmd.Exec createInfoCmdExec() {
        return new InfoCmdExec(getBaseResource());
    }

    @Override
    public PingCmd.Exec createPingCmdExec() {
        return new PingCmdExec(getBaseResource());
    }

    @Override
    public VersionCmd.Exec createVersionCmdExec() {
        return new VersionCmdExec(getBaseResource());
    }

    @Override
    public PullImageCmd.Exec createPullImageCmdExec() {
        return new PullImageCmdExec(getBaseResource());
    }

    @Override
    public PushImageCmd.Exec createPushImageCmdExec() {
        return new PushImageCmdExec(getBaseResource());
    }

    @Override
    public CreateImageCmd.Exec createCreateImageCmdExec() {
        return new CreateImageCmdExec(getBaseResource());
    }

    @Override
    public SearchImagesCmd.Exec createSearchImagesCmdExec() {
        return new SearchImagesCmdExec(getBaseResource());
    }

    @Override
    public RemoveImageCmd.Exec createRemoveImageCmdExec() {
        return new RemoveImageCmdExec(getBaseResource());
    }

    @Override
    public ListImagesCmd.Exec createListImagesCmdExec() {
        return new ListImagesCmdExec(getBaseResource());
    }

    @Override
    public InspectImageCmd.Exec createInspectImageCmdExec() {
        return new InspectImageCmdExec(getBaseResource());
    }

    @Override
    public ListContainersCmd.Exec createListContainersCmdExec() {
        return new ListContainersCmdExec(getBaseResource());
    }

    @Override
    public CreateContainerCmd.Exec createCreateContainerCmdExec() {
        return new CreateContainerCmdExec(getBaseResource());
    }

    @Override
    public StartContainerCmd.Exec createStartContainerCmdExec() {
        return new StartContainerCmdExec(getBaseResource());
    }

    @Override
    public InspectContainerCmd.Exec createInspectContainerCmdExec() {
        return new InspectContainerCmdExec(getBaseResource());
    }

    @Override
    public ExecCreateCmd.Exec createExecCmdExec() {
        return new ExecCreateCmdExec(getBaseResource());
    }

    @Override
    public RemoveContainerCmd.Exec createRemoveContainerCmdExec() {
        return new RemoveContainerCmdExec(getBaseResource());
    }

    @Override
    public WaitContainerCmd.Exec createWaitContainerCmdExec() {
        return new WaitContainerCmdExec(getBaseResource());
    }

    @Override
    public AttachContainerCmd.Exec createAttachContainerCmdExec() {
        return new AttachContainerCmdExec(getBaseResource());
    }

    @Override
    public ExecStartCmd.Exec createExecStartCmdExec() {
        return new ExecStartCmdExec(getBaseResource());
    }

    @Override
    public LogContainerCmd.Exec createLogContainerCmdExec() {
        return new LogContainerCmdExec(getBaseResource());
    }

    @Override
    public CopyFileFromContainerCmd.Exec createCopyFileFromContainerCmdExec() {
        return new CopyFileFromContainerCmdExec(getBaseResource());
    }

    @Override
    public StopContainerCmd.Exec createStopContainerCmdExec() {
        return new StopContainerCmdExec(getBaseResource());
    }

    @Override
    public ContainerDiffCmd.Exec createContainerDiffCmdExec() {
        return new ContainerDiffCmdExec(getBaseResource());
    }

    @Override
    public KillContainerCmd.Exec createKillContainerCmdExec() {
        return new KillContainerCmdExec(getBaseResource());
    }

    @Override
    public RestartContainerCmd.Exec createRestartContainerCmdExec() {
        return new RestartContainerCmdExec(getBaseResource());
    }

    @Override
    public CommitCmd.Exec createCommitCmdExec() {
        return new CommitCmdExec(getBaseResource());
    }

    @Override
    public BuildImageCmd.Exec createBuildImageCmdExec() {
        return new BuildImageCmdExec(getBaseResource());
    }

    @Override
    public TopContainerCmd.Exec createTopContainerCmdExec() {
        return new TopContainerCmdExec(getBaseResource());
    }

    @Override
    public TagImageCmd.Exec createTagImageCmdExec() {
        return new TagImageCmdExec(getBaseResource());
    }

    @Override
    public PauseContainerCmd.Exec createPauseContainerCmdExec() {
        return new PauseContainerCmdExec(getBaseResource());
    }

    @Override
    public UnpauseContainerCmd.Exec createUnpauseContainerCmdExec() {
        return new UnpauseContainerCmdExec(baseResource);
    }

    @Override
    public EventsCmd.Exec createEventsCmdExec() {
        return new EventsCmdExec(getBaseResource());
    }

    @Override
    public void close() throws IOException {
        Preconditions.checkNotNull(client, "Factory not initialized. You probably forgot to call init()!");
        client.close();
    }

}


text:
#bling-frame {
  height: 475px;
  width: 940px;
  background: url('../img/bling-frame.png') center top no-repeat;
  margin-bottom:-90px;
  background-position: center top;
}

#bling-screen {
  margin-left: auto;
  margin-right: auto;
  margin-top: 56px;
  height: 274px;
  width: 380px;
  background: url('../img/all-sprites.png');
}

ul {
list-style-type: none;
padding: 0px;
margin-left: -10px;
margin-right: 0px;
}

li {
background-image: url('../img/bullet_orange-square.png');
background-repeat: no-repeat;
background-position: 0px 5px;
padding-left: 14px;
margin-left: 14px;
}

#sidebar li {
  list-style-type: square;
  background-image: none;
  padding-left: 0px;
  margin-left: 28px;
}

#sidebar li.doc,
li.doc {
  background-image: url('../img/bullet_doc.png');
  list-style-type: none;
  padding-left: 20px;
  margin-left: 14px;
  line-height: 25px;
}
#sidebar li.web-doc,
li.web-doc {
  background-image: url('../img/bullet_web-doc.png');
  list-style-type: none;
  padding-left: 20px;
  margin-left: 14px;
  line-height: 25px;
}

#header li {
  background-image: none;
  padding: 0px;
  margin: 12px;
}

a img {
  border: none !important;
}

.clear {
  clear: both !important;
}

#header h2 {
  font-weight: normal;
  text-align: center;
  font-size: 2.4em;
}

#header .nav ul li {
  float: left;
  list-style-type: none;
  margin-top: 8px;
}

#header .nav {
  height: 34px;
  background: url('../img/main-nav_bg.png') repeat-x;
  text-transform: uppercase;
}

#header .nav ul {
  margin-left: 24px;
}

#header .nav a { color: white; }
#header .nav a:hover { color: #e3a534; }

/** Colors **/

body {
  background: url('../img/background-repeater.png') black repeat-x;
  color: white;
}

a:link, a:visited, a:active {
  color: #e3a534;
  text-decoration: none;
}

#logo {
  margin-top: 20px;
  margin-bottom: 24px;
}

#logo h1 {
  height: 124px;
  width: 155px;
}

h2#download {
  vertical-align: middle !important;
  margin-bottom: 12px !important;
}

#download a {
  background: url('../img/orange-button.png') no-repeat top left;
  width: 334px;
  padding-top: 10px;
  height: 44px;
  display: block;
  text-align: center;
  vertical-align: middle;
  color: white;
  text-shadow: 1px 1px #552200;
  text-transform: uppercase;
}

#sidebar h3 {
  font-size: 1.1em;
  margin-bottom: 0px;
}

#sidebar p {
  color: #ccc;
}

#sidebar h2 {
  color: #e3a534;
  font-weight: normal;
  margin-bottom: 0px;
}

#footer {
  width: 100%;
  clear: both;
  min-height: 269px;
  background: black url('http://duffy.fedorapeople.org/moksha/html/img/footer-bg.png') repeat-x;
}

#footer img {
  margin-right: 24px;
}

#content {
  margin-bottom: 100px;
}

#footer .container_16 div {
  margin-top: 36px;
}


text:
    Choose bot detection mechanism.

    <mat-card *ngFor="let botDetection of botDetections" fxFlex="30">
      <mat-card-header fxLayoutAlign="end end" fxLayout="row">
        <mat-radio-group [(ngModel)]="selectedBotDetectionTypeId" (ngModelChange)="selectBotDetectionType()">
          <mat-radio-button [value]="botDetection.id"></mat-radio-button>
        </mat-radio-group>
      </mat-card-header>
      <mat-card-content>
        {{displayName(botDetection)}}
      </mat-card-content>
    </mat-card>


text:
package com.facebook.buck.parser;

import com.facebook.buck.core.cell.Cell;
import com.facebook.buck.core.filesystems.ForwardRelPath;
import com.facebook.buck.core.model.targetgraph.impl.Package;
import com.facebook.buck.parser.api.PackageMetadata;
import com.facebook.buck.rules.param.CommonParamNames;
import com.facebook.buck.rules.visibility.VisibilityDefiningPath;
import com.facebook.buck.rules.visibility.VisibilityPattern;
import com.facebook.buck.rules.visibility.parser.VisibilityPatterns;
import com.google.common.collect.ImmutableSet;
import java.util.Optional;

/** Generic factory to create {@link Package} */
public class PackageFactory {

  /** Prevent initialization */
  private PackageFactory() {}

  /** Create a {@link Package} from the {@code rawPackage} */
  public static Package create(
      Cell cell,
      ForwardRelPath packageFile,
      PackageMetadata rawPackage,
      Optional<Package> parentPackage) {

    VisibilityDefiningPath definingPath = VisibilityDefiningPath.of(packageFile, false);

    String visibilityDefinerDescription =
        String.format("the package() at %s", definingPath.getPath());

    ImmutableSet.Builder<VisibilityPattern> visibilityBuilder = ImmutableSet.builder();
    ImmutableSet.Builder<VisibilityPattern> withinViewBuilder = ImmutableSet.builder();

    parentPackage.ifPresent(
        pkg -> {
          if (rawPackage.getInherit()) {
            visibilityBuilder.addAll(pkg.getVisibilityPatterns());
            withinViewBuilder.addAll(pkg.getWithinViewPatterns());
          }
        });

    visibilityBuilder.addAll(
        VisibilityPatterns.createFromStringList(
            cell.getCellPathResolver(),
            CommonParamNames.VISIBILITY.getSnakeCase(),
            rawPackage.getVisibility(),
            definingPath,
            () -> visibilityDefinerDescription));

    withinViewBuilder.addAll(
        VisibilityPatterns.createFromStringList(
            cell.getCellPathResolver(),
            CommonParamNames.WITHIN_VIEW.getSnakeCase(),
            rawPackage.getWithinView(),
            definingPath,
            () -> visibilityDefinerDescription));

    return Package.of(
        rawPackage.getInherit(), visibilityBuilder.build(), withinViewBuilder.build());
  }
}


text:
load("utils/req.jl")
req("utils/utils.jl")

abstract Expression

# == Node =====================================================================

type Node{T<:Expression}
    val::T
    args#::Vector{Node} # todo: add back once type inference bug is fixed

    name::Union(Symbol,Nothing)
    num_uses::Int

    # raw Node constructors
    function Node(val::T, args)
        if !isa(args, Vector{Node});   args = Node[args...];   end

        node = new(val, Node[args...], nothing, 0)
        check_args(node)
        node
    end
    function Node{S<:Expression}(val::S, args...)
        error("Node{$T}: No constructor for val = $val, args=$args")
    end

    # forwards typealias constructors to Node(T, args...)
    Node(targs...) = Node(T, targs...)
end

Node         {T<:Expression}(val::T, cargs...) = Node{T}(val, cargs...)
function Node{T<:Expression}(node::Node{T}, args) # copy node, but use new args
    newnode = Node(node.val, args)
    newnode.name = node.name
    newnode
end

typealias Nodes Vector{Node}

has_name(node::Node) = !is(node.name, nothing)
get_name(node::Node) = node.name

# == Expressions ==============================================================

## terminals ##
abstract Terminal      <: Expression
type       NoEx        <: Terminal; end
type       LiteralEx   <: Terminal; value; end
type       SymbolEx    <: Terminal;
    name::Symbol
    kind::Symbol
    SymbolEx(name::Symbol, kind::Symbol) = new(name, kind)
end

## nonterminals ##
abstract Nonterminal  <: Expression
abstract   Operation  <: Nonterminal # Nonterminal with storable value
abstract     FuncOp   <: Operation     # Operation without side effects
type           KnotEx   <: FuncOp; end   # To encode additional order relations
type           TupleEx  <: FuncOp; end
type           CallEx   <: FuncOp; end
type           RefEx    <: FuncOp; end
abstract     Action   <: Operation     # Operation with side effects
type           AssignEx <: Action; end
type       EllipsisEx   <: Nonterminal; end

## expression comparison ##
# (expression types without fields compare by identity already
isequal(n1::SymbolEx,  n2::SymbolEx) = (n1.name, n1.kind)==(n2.name, n2.kind)
isequal(n1::LiteralEx, n2::LiteralEx) = n1.value==n2.value

# -- Node types ---------------------------------------------------------------

## Node type aliases ##

typealias TerminalNode{T<:Terminal}    Node{T}
typealias NontermNode {T<:Nonterminal} Node{T}
typealias OpNode      {T<:Operation}   Node{T}
typealias FuncOpNode  {T<:FuncOp}      Node{T}
typealias ActionNode  {T<:Action}      Node{T}

typealias NoNode       Node{NoEx}
typealias LiteralNode  Node{LiteralEx}
typealias SymNode      Node{SymbolEx}

typealias CallNode     Node{CallEx}
typealias RefNode      Node{RefEx}
typealias TupleNode    Node{TupleEx}
typealias KnotNode     Node{KnotEx}

typealias EllipsisNode Node{EllipsisEx}
typealias AssignNode   Node{AssignEx}

## Node type dependent methods: constructors, checker, getters ##

Node      {T<:Terminal}(::Type{T}, targs...) = Node{T}(T(targs...), ())
check_args{T<:Terminal}(node::Node{T}) = (@expect length(node.args) == 0)

Node      {T<:Nonterminal}(::Type{T}, args...) = Node{T}(T(), args)
get_args  {T<:Nonterminal}(node::Node{T}) = node.args
check_args{T<:Nonterminal}(::Node{T}) = nothing

get_op       (node::CallNode) = node.args[1]
get_callargs (node::CallNode) = node.args[2:end]
check_args   (node::CallNode) = (@expect length(node.args) >= 1)

get_A        (node::RefNode) = node.args[1]
get_inds     (node::RefNode) = node.args[2:end]
check_args   (node::RefNode)  = (@expect length(node.args) >= 1)

check_args(node::KnotNode) = (@expect length(node.args) >= 1)

get_lhs      (node::AssignNode) = node.args[1]
get_rhs      (node::AssignNode) = node.args[2]
get_preevents(node::AssignNode) = node.args[3:end]
function check_args(node::AssignNode)
    get_lhs(node)::RefNode
    @expect length(node.args) >= 2
    @expect allp(arg->isa(arg, ActionNode), get_preevents(node))
end


text:
package spawn

import (
	"os"
	"path/filepath"
	"strings"
)

/*
GetThrustDirectory returns the Directory where the unzipped thrust contents are.
Differs between builds based on OS
*/
func GetThrustDirectory() string {
	return filepath.Join(base, "vendor", "linux", "x64", thrustVersion)
}

/*
GetDownloadDirectory gets the download or extract directory for Thrust
*/
func GetDownloadPath() string {
	return strings.Replace(filepath.Join(base, "$V"), "$V", thrustVersion, 1)
}

/*
GetExecutablePath returns the path to the Thrust Executable
Differs between builds based on OS
*/
func GetExecutablePath() string {
	return GetThrustDirectory() + "/thrust_shell"
}

/*
GetDownloadURL returns the interpolatable version of the Thrust download url
Differs between builds based on OS
*/
func GetDownloadURL() string {
	return "https://github.com/breach/thrust/releases/download/v$V/thrust-v$V-linux-x64.zip"
}

/*
Bootstrap executes the default bootstrapping plan for this system and returns an error if failed
*/
func Bootstrap() error {
	if executableNotExist() == true {
		return prepareExecutable()
	}
	return nil
}

func executableNotExist() bool {
	_, err := os.Stat(GetExecutablePath())
	return os.IsNotExist(err)
}

func prepareExecutable() error {
	path, err := downloadFromUrl(GetDownloadURL(), base+"/$V", thrustVersion)
	if err != nil {
		return err
	}

	return UnzipExecutable(path)
}

func UnzipExecutable(path string) error {
	return unzip(path, GetThrustDirectory())
}

func PathNotExist(path string) bool {
	_, err := os.Stat(path)
	return os.IsNotExist(err)
}


text:
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.test.pagecontroller.controllers.ntp;

import org.chromium.chrome.R;
import org.chromium.chrome.test.pagecontroller.controllers.PageController;
import org.chromium.chrome.test.pagecontroller.controllers.tabswitcher.TabSwitcherController;
import org.chromium.chrome.test.pagecontroller.controllers.urlpage.UrlPage;
import org.chromium.chrome.test.pagecontroller.utils.IUi2Locator;
import org.chromium.chrome.test.pagecontroller.utils.Ui2Locators;

/**
 * New Tab Page Page Controller, handles either Feed or Zine implementations.
 */
public class NewTabPageController extends PageController {
    private static final float SCROLL_SWIPE_FRACTION = 0.6f;
    // The test will timeout for Small and Medium sizes before 50 swipes is
    // reached.  This number is set so that it should not be hit if everything
    // is working fine.  Please bump it up if test cases exceeding 50 swipes
    // becomes common.
    private static final int MAX_SCROLL_SWIPES = 50;

    private static final String TEXT_HEADER_STATUS_HIDE = "Hide";
    private static final String TEXT_HEADER_STATUS_SHOW = "Show";
    private static final String REGEX_TEXT_HEADER_STATUS = "^Hide|Show$";

    private static final IUi2Locator LOCATOR_SEARCH_BOX_TEXT =
            Ui2Locators.withAnyResEntry(R.id.search_box_text);
    private static final IUi2Locator LOCATOR_URL_BAR = Ui2Locators.withAnyResEntry(R.id.url_bar);
    private static final IUi2Locator LOCATOR_SEARCH_PROVIDER_LOGO =
            Ui2Locators.withAnyResEntry(R.id.search_provider_logo);
    private static final IUi2Locator LOCATOR_MORE_BUTTON =
            Ui2Locators.withAnyResEntry(R.id.action_button);
    private static final IUi2Locator LOCATOR_MENU_BUTTON =
            Ui2Locators.withAnyResEntry(R.id.menu_button);
    private static final IUi2Locator LOCATOR_FEED_STREAM_RECYCLER_VIEW =
            Ui2Locators.withAnyResEntry(org.chromium.chrome.feed.R.id.feed_stream_recycler_view);
    private static final IUi2Locator LOCATOR_HEADER_STATUS =
            Ui2Locators.withPath(Ui2Locators.withAnyResEntry(R.id.header_status),
                    Ui2Locators.withTextRegex(REGEX_TEXT_HEADER_STATUS));

    private static final IUi2Locator LOCATOR_TAB_SWITCHER =
            Ui2Locators.withAnyResEntry(R.id.tab_switcher_button);

    private static final IUi2Locator LOCATOR_NEW_TAB_PAGE = Ui2Locators.withAnyResEntry(
            R.id.ntp_content, org.chromium.chrome.feed.R.id.feed_stream_recycler_view,
            org.chromium.chrome.feed.R.id.feed_content_card);

    private static final NewTabPageController sInstance = new NewTabPageController();
    private NewTabPageController() {}
    public static NewTabPageController getInstance() {
        return sInstance;
    }

    /**
     * Hide articles if shown, and vice-versa.  This will cause page to scroll to where the
     * show/hide articles button is visible.
     */
    public void toggleHideArticles() {
        scrollToTop();
        mUtils.swipeUpVerticallyUntilFound(LOCATOR_HEADER_STATUS, LOCATOR_MORE_BUTTON);
        mUtils.click(LOCATOR_HEADER_STATUS);
    }

    /**
     * This will cause page to scroll to where the show/hide articles button is visible.
     * @return True if articles are currently hidden as indicated by the presence of the
     *         show/hide articles button, else false.
     */
    public boolean areArticlesHidden() {
        scrollToTop();

        String status_text = mLocatorHelper.getOneText(LOCATOR_HEADER_STATUS);

        // The ariticles are hidden if "Show" is displayed, appears to be reversed but makes UI
        // sense since the user can click on "Show" to unhide them.
        if (status_text.equals(TEXT_HEADER_STATUS_HIDE)) {
            return false;
        } else if (status_text.equals(TEXT_HEADER_STATUS_SHOW)) {
            return true;
        } else {
            throw new IllegalStateException("Bad status text: " + status_text);
        }
    }

    public void scrollTowardsTop(float screenHeightPercentage) {
        mUtils.swipeDownVertically(screenHeightPercentage);
    }

    public void scrollTowardsBottom(float screenHeightPercentage) {
        mUtils.swipeUpVertically(screenHeightPercentage);
    }

    public boolean hasScrolledToBottom() {
        // If TEXT_HEADER_STATUS_SHOW is displayed, it means articles are hidden.
        IUi2Locator locator = Ui2Locators.withPath(
                LOCATOR_HEADER_STATUS, Ui2Locators.withTextRegex(TEXT_HEADER_STATUS_SHOW));
        if (mLocatorHelper.isOnScreen(locator)) {
            return true;
        } else {
            return mLocatorHelper.isOnScreen(LOCATOR_MORE_BUTTON);
        }
    }

    public boolean hasScrolledToTop() {
        return mLocatorHelper.isOnScreen(LOCATOR_SEARCH_PROVIDER_LOGO);
    }

    public void scrollToBottom() {
        scrollToBottom(MAX_SCROLL_SWIPES);
    }

    public void scrollToBottom(int maxSwipes) {
        int swipes = 0;
        while (swipes++ < maxSwipes && !hasScrolledToBottom()) {
            scrollTowardsBottom(SCROLL_SWIPE_FRACTION);
        }
    }

    public void scrollToTop() {
        scrollToTop(MAX_SCROLL_SWIPES);
    }

    public void scrollToTop(int maxSwipes) {
        for (int swipes = 0; swipes < maxSwipes && !hasScrolledToTop(); swipes++) {
            scrollTowardsTop(SCROLL_SWIPE_FRACTION);
        }
    }

    /**
     * Open the tab switcher at the top.  This will cause the page to scroll to the top.
     * @return The TabSwitcher Page Controller.
     */
    public TabSwitcherController openTabSwitcher() {
        scrollToTop();
        mUtils.click(LOCATOR_TAB_SWITCHER);
        return TabSwitcherController.getInstance().verifyActive();
    }

    /**
     * Open the 3-dot menu at the top.  This will cause the page to scroll to the top.
     * @return The ChromeMenu Page Controller.
     */
    public ChromeMenu openChromeMenu() {
        scrollToTop();
        mUtils.click(LOCATOR_MENU_BUTTON);
        return ChromeMenu.getInstance().verifyActive();
    }

    public UrlPage omniboxSearch(String url) {
        mUtils.click(LOCATOR_SEARCH_BOX_TEXT);
        mUtils.setTextAndEnter(LOCATOR_URL_BAR, url);
        return UrlPage.getInstance().verifyActive();
    }

    @Override
    public NewTabPageController verifyActive() {
        mLocatorHelper.verifyOnScreen(LOCATOR_NEW_TAB_PAGE);
        return this;
    }
}


text:
  A repository of
  high-quality, third-party library type definitions
  for use with Flow.

Check out the [quick start](https://flow-typed.github.io/flow-typed/#/quickstart) page
in the docs to get started. It will walk you through installing typedefs, using them,
as well as writing and including your own.

## Huh?

When you start a project with Flow, **you likely want to use some third-party
libraries that were *not* written with Flow**. By default, Flow will just ignore
these libraries **leaving them untyped**. As a result, Flow can't give errors if
you accidentally mis-use the library (nor will it be able to auto-complete the
library).

To address this, **Flow supports
[library definitions](https://flow.org/en/docs/libdefs)** which allow
you to describe the interface of a module or library separate from the
implementation of that module/library.

**The `flow-typed` repo is a collection of high-quality library definitions**,
tests to ensure that definitions remain high quality, and tooling to make it
as easy as possible to import them into your project.

All you have to do when you add one or more new dependencies to your project
is run `flow-typed install`. This will search the libdef repo and download all
the libdefs that are relevant for your project and install them for you. After
that, **simply check them in** and be on your way!

## The CLI

The `flow-typed` npm package provides a CLI that includes several commands for
working with this repository. The full list of commands is available
[in the docs](https://flow-typed.github.io/flow-typed/#/install) .

## FAQs

Before opening an issue, take a look at the [FAQs](https://flow-typed.github.io/flow-typed/#/faq).
Chances are your question has already been answered! If not, don't hesitate to
[open an issue](https://github.com/flow-typed/flow-typed/issues/new).

## How Do I Contribute Library Definitions?

Just send a pull request! The documentation highlighted in [CONTRIBUTING.md](https://github.com/flow-typed/flow-typed/blob/master/CONTRIBUTING.md) should give a detailed overview of how to raise a pull request following our best practices.

### Contributing to the CLI

Bugfixes and improvements to the core CLI are welcome. If you'd like to contribute
a new feature, consider opening an issue first to discuss it.

## Active Maintenance Team

[![Andrew Smith](https://github.com/andrewsouthpaw.png?size=100)](https://github.com/andrewsouthpaw) | [![Brian Chen](https://github.com/Brianzchen.png?size=100)](https://github.com/Brianzchen)  | [![Georges-Antoine Assi](https://github.com/gantoine.png?size=100)](https://github.com/gantoine) | [![Pascal Duez](https://github.com/pascalduez.png?size=100)](https://github.com/pascalduez) | [![Ville Saukkonen](https://github.com/villesau.png?size=100)](https://github.com/villesau)
:---:|:---:|:---:|:---:|:---:
[@AndrewSouthpaw](https://github.com/andrewsouthpaw) | [@Brianzchen](https://github.com/Brianzchen) | [@GAntoine](https://github.com/gantoine) | [@pascalduez](https://github.com/pascalduez) | [@villesau](https://github.com/villesau)


text:
package org.apache.camel.component.mybatis;

import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.Test;

public class MyBatisInsertWithOutputHeaderTest extends MyBatisTestSupport {

    private static final String TEST_CASE_HEADER_NAME = "testCaseHeader";
    private static final int TEST_ACCOUNT_ID = 444;

    @Test
    public void testInsert() throws Exception {
        MockEndpoint mock = getMockEndpoint("mock:result");
        mock.expectedMessageCount(1);
        mock.message(0).body().isInstanceOf(Account.class);
        mock.message(0).header(TEST_CASE_HEADER_NAME).isEqualTo(1);
        mock.message(0).header(MyBatisConstants.MYBATIS_RESULT).isNull();

        Account account = new Account();
        account.setId(TEST_ACCOUNT_ID);
        account.setFirstName("Willem");
        account.setLastName("Jiang");
        account.setEmailAddress("Faraway@gmail.com");

        template.sendBody("direct:start", account);

        assertMockEndpointsSatisfied();

        // there should be 3 rows now
        Integer rows = template.requestBody("mybatis:count?statementType=SelectOne", null, Integer.class);
        assertEquals("There should be 3 rows", 3, rows.intValue());
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:start")
                    .to("mybatis:insertAccount?statementType=Insert&outputHeader=" + TEST_CASE_HEADER_NAME)
                    .to("mock:result");
            }
        };
    }

}