text:
<tool id="EMBOSS: dreg27" name="dreg" version="@VERSION@">
  <description>Regular expression search of a nucleotide sequence</description>
  <macros>
    <import>macros.xml</import>
  </macros>
  <expand macro="requirements" />
  <command>dreg -sequence '$input1' -outfile '$out_file1' -pattern '$pattern' -raccshow3 "no" -rusashow3 "no" -rdesshow3 "no" -auto</command>
  <inputs>
    <param name="input1" type="data" format="data" label="Sequence 1" />
    <param name="pattern" type="text" value="(AUG)" label="Regular expression pattern" />
  </inputs>
  <outputs>
    <data name="out_file1" format="dreg" />
  </outputs>
  <!-- tests not possible since dreg timestamps output file -->
  <help>
    You can view the original documentation here_.

    .. _here: http://galaxy-iuc.github.io/emboss-5.0-docs/dreg.html
  </help>
  <expand macro="citations" />
</tool>

redpajama_set_name: RedPajamaGithub


text:
package ocrworker

const MOCK_ENGINE_RESPONSE = "mock engine decoder response"

type MockEngine struct {
}

func (m MockEngine) ProcessRequest(ocrRequest OcrRequest) (OcrResult, error) {
	return OcrResult{Text: MOCK_ENGINE_RESPONSE}, nil
}


text:
#include "ABI44_0_0ImageEventEmitter.h"

namespace ABI44_0_0facebook {
namespace ABI44_0_0React {

void ImageEventEmitter::onLoadStart() const {
  dispatchEvent("loadStart");
}

void ImageEventEmitter::onLoad() const {
  dispatchEvent("load");
}

void ImageEventEmitter::onLoadEnd() const {
  dispatchEvent("loadEnd");
}

void ImageEventEmitter::onProgress(double progress) const {
  dispatchEvent("progress", [=](jsi::Runtime &runtime) {
    auto payload = jsi::Object(runtime);
    payload.setProperty(runtime, "progress", progress);
    return payload;
  });
}

void ImageEventEmitter::onError() const {
  dispatchEvent("error");
}

void ImageEventEmitter::onPartialLoad() const {
  dispatchEvent("partialLoad");
}

} // namespace ABI44_0_0React
} // namespace ABI44_0_0facebook


text:
<<<<<<< HEAD
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
    int n, count = 0;;
    cin>>n;
    int start,endEntry;
    while(n--)
    {
        count = 0;
        cin>>start;
        cin>>endEntry;
        count = (floor(sqrt(endEntry)) - ceil(sqrt(start))) + 1;
        printf("%d\n",count);
    }
    return 0;
}

=======
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
    int n, count = 0;;
    cin>>n;
    int start,endEntry;
    while(n--)
    {
        count = 0;
        cin>>start;
        cin>>endEntry;
        count = (floor(sqrt(endEntry)) - ceil(sqrt(start))) + 1;
        printf("%d\n",count);
    }
    return 0;
}

>>>>>>> 25f321ca304be13c40132abb7f09bf7440d9753b


text:
package org.apache.shindig.social.opensocial.jpa;

import org.apache.shindig.social.opensocial.model.Organization;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;

/**
 * This object connects to a single Address, and to a single organization, defining the
 * organizations relationship with the address. The class extends AddressDb, which stores itself in
 * the address table. The specialization of this class is stored in organization_address and joined
 * on the objectId property (oid column). Records are discriminated using the address_usage column
 * in the address table and set to the value 'sharedaddress' (i.e. no discrimination) indicating
 * that the address is shared.
 */
// TODO, uncertain about the mapping of this, oid <-> oid means one to one, and this is only
// associated with a single
// Organization. IMHO, we should be mapping organizational_address.address_id to address.oid, but
// need to think about this.
@Entity
@Table(name = "organizational_address")
@DiscriminatorValue(value = "sharedaddress")
// this is the same as others since we want to share the data.
public class OrganizationAddressDb extends AddressDb {
  /**
   * Indicates this address is the primary address for the organization.
   */
  @Basic
  @Column(name = "primary_organization")
  private Boolean primary;

  /**
   * This address is associated with a single organization in this form.
   *
   */
  @OneToOne(targetEntity = OrganizationDb.class)
  @JoinColumn(name = "organization_id", referencedColumnName = "oid")
  private Organization organization;

  /**
   * the type of the address for the organization.
   *
   * @see org.apache.shindig.social.opensocial.model.Address
   */
  @Basic
  @Column(name = "type", length = 255)
  private String type;

  /**
   * Create an organizational address.
   */
  public OrganizationAddressDb() {
  }

  /**
   * {@inheritDoc}
   *
   * @see org.apache.shindig.social.opensocial.jpa.AddressDb#getType()
   */
  public String getType() {
    return type;
  }

  /**
   * {@inheritDoc}
   *
   * @see org.apache.shindig.social.opensocial.jpa.AddressDb#setType(java.lang.String)
   */
  public void setType(String type) {
    this.type = type;
  }

  /**
   * {@inheritDoc}
   *
   * @see org.apache.shindig.social.opensocial.jpa.AddressDb#getPrimary()
   */
  public Boolean getPrimary() {
    return primary;
  }

  /**
   * {@inheritDoc}
   *
   * @see org.apache.shindig.social.opensocial.jpa.AddressDb#setPrimary(java.lang.Boolean)
   */
  public void setPrimary(Boolean primary) {
    this.primary = primary;
  }

  /**
   * The organization this address address relates to.
   *
   * @return the organization
   */
  public Organization getOrganization() {
    return organization;
  }

  /**
   * Set the organization this address relates to.
   *
   * @param organization the organization to set
   */
  public void setOrganization(Organization organization) {
    this.organization = organization;
  }

}


text:
class ReadingListModel;

// Implementation of ReadingListManager.
// 1. Holds a in memory bookmark node tree. Contains a folder root and reading
// list nodes as children. Only has one level of children.
// 2. Talk to reading list model, and sync with the in memory bookmark tree.
// 3. Talk to observers to report model change events.
class ReadingListManagerImpl : public ReadingListManager,
                               public ReadingListModelObserver {
 public:
  explicit ReadingListManagerImpl(ReadingListModel* reading_list_model);
  ~ReadingListManagerImpl() override;

 private:
  // ReadingListModelObserver overrides.
  void ReadingListModelLoaded(const ReadingListModel* model) override;
  void ReadingListDidAddEntry(const ReadingListModel* model,
                              const GURL& url,
                              reading_list::EntrySource source) override;
  void ReadingListWillRemoveEntry(const ReadingListModel* model,
                                  const GURL& url) override;
  void ReadingListDidMoveEntry(const ReadingListModel* model,
                               const GURL& url) override;
  void ReadingListDidApplyChanges(ReadingListModel* model) override;
  void ReadingListModelBeganBatchUpdates(
      const ReadingListModel* model) override;
  void ReadingListModelCompletedBatchUpdates(
      const ReadingListModel* model) override;

  // ReadingListManager implementation.
  void AddObserver(Observer* observer) override;
  void RemoveObserver(Observer* observer) override;
  const bookmarks::BookmarkNode* Add(const GURL& url,
                                     const std::string& title) override;
  const bookmarks::BookmarkNode* Get(const GURL& url) const override;
  const bookmarks::BookmarkNode* GetNodeByID(int64_t id) const override;
  void GetMatchingNodes(
      const bookmarks::QueryFields& query,
      size_t max_count,
      std::vector<const bookmarks::BookmarkNode*>* results) override;
  bool IsReadingListBookmark(
      const bookmarks::BookmarkNode* node) const override;
  void Delete(const GURL& url) override;
  const bookmarks::BookmarkNode* GetRoot() const override;
  size_t size() const override;
  size_t unread_size() const override;
  void SetReadStatus(const GURL& url, bool read) override;
  bool GetReadStatus(const bookmarks::BookmarkNode* node) override;
  bool IsLoaded() const override;

  // Finds the child in the bookmark tree by URL. Returns nullptr if not found.
  // Not recursive since the reading list bookmark tree only has a folder root
  // node and one level of children.
  bookmarks::BookmarkNode* FindBookmarkByURL(const GURL& url) const;

  void RemoveBookmark(const GURL& url);
  const bookmarks::BookmarkNode* AddOrUpdateBookmark(
      const ReadingListEntry* entry);
  void NotifyReadingListChanged();

  // Contains reading list data, outlives this class.
  raw_ptr<ReadingListModel> reading_list_model_;

  // The bookmark root for reading list articles.
  std::unique_ptr<bookmarks::BookmarkNode> root_;

  // Auto increment bookmark id. Will not be persisted and only used in memory.
  int64_t maximum_id_;

  // Whether the |reading_list_model_| is loaded.
  bool loaded_;

  // Whether |reading_list_model_| is in batch update mode.
  bool performing_batch_update_;

  base::ObserverList<Observer> observers_;
};

#endif  // CHROME_BROWSER_READING_LIST_ANDROID_READING_LIST_MANAGER_IMPL_H_


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

import com.google.common.collect.ImmutableList;
import io.airlift.joni.Matcher;
import io.airlift.joni.Region;
import io.airlift.slice.DynamicSliceOutput;
import io.airlift.slice.Slice;
import io.airlift.slice.SliceOutput;
import io.trino.spi.PageBuilder;
import io.trino.spi.block.Block;
import io.trino.spi.block.BlockBuilder;
import io.trino.spi.function.Description;
import io.trino.spi.function.LiteralParameters;
import io.trino.spi.function.ScalarFunction;
import io.trino.spi.function.SqlNullable;
import io.trino.spi.function.SqlType;
import io.trino.sql.gen.lambda.UnaryFunctionInterface;
import io.trino.type.JoniRegexp;
import io.trino.type.JoniRegexpType;

import static io.airlift.slice.SliceUtf8.lengthOfCodePointFromStartByte;
import static io.trino.operator.scalar.JoniRegexpFunctions.getSearchingOffset;
import static io.trino.spi.type.VarcharType.VARCHAR;

@ScalarFunction("regexp_replace")
@Description("Replaces substrings matching a regular expression using a lambda function")
public final class JoniRegexpReplaceLambdaFunction
{
    private final PageBuilder pageBuilder = new PageBuilder(ImmutableList.of(VARCHAR));

    @LiteralParameters("x")
    @SqlType("varchar")
    @SqlNullable
    public Slice regexpReplace(
            @SqlType("varchar") Slice source,
            @SqlType(JoniRegexpType.NAME) JoniRegexp pattern,
            @SqlType("function(array(varchar), varchar(x))") UnaryFunctionInterface replaceFunction)
    {
        // If there is no match we can simply return the original source without doing copy.
        Matcher matcher = pattern.matcher(source.getBytes());
        if (getSearchingOffset(matcher, 0, source.length()) == -1) {
            return source;
        }

        SliceOutput output = new DynamicSliceOutput(source.length());

        // Prepare a BlockBuilder that will be used to create the target block
        // that will be passed to the lambda function.
        if (pageBuilder.isFull()) {
            pageBuilder.reset();
        }
        BlockBuilder blockBuilder = pageBuilder.getBlockBuilder(0);

        int groupCount = pattern.regex().numberOfCaptures();
        int appendPosition = 0;
        int nextStart;

        do {
            // nextStart is the same as the last appendPosition, unless the last match was zero-width.
            if (matcher.getEnd() == matcher.getBegin()) {
                if (matcher.getBegin() < source.length()) {
                    nextStart = matcher.getEnd() + lengthOfCodePointFromStartByte(source.getByte(matcher.getBegin()));
                }
                else {
                    // last match is empty and we matched end of source, move past the source length to terminate the loop
                    nextStart = matcher.getEnd() + 1;
                }
            }
            else {
                nextStart = matcher.getEnd();
            }

            // Append the un-matched part
            Slice unmatched = source.slice(appendPosition, matcher.getBegin() - appendPosition);
            appendPosition = matcher.getEnd();
            output.appendBytes(unmatched);

            // Append the capturing groups to the target block that will be passed to lambda
            Region matchedRegion = matcher.getEagerRegion();
            for (int i = 1; i <= groupCount; i++) {
                // Add to the block builder if the matched region is not null. In Joni null is represented as [-1, -1]
                if (matchedRegion.beg[i] >= 0 && matchedRegion.end[i] >= 0) {
                    VARCHAR.writeSlice(blockBuilder, source, matchedRegion.beg[i], matchedRegion.end[i] - matchedRegion.beg[i]);
                }
                else {
                    blockBuilder.appendNull();
                }
            }
            pageBuilder.declarePositions(groupCount);
            Block target = blockBuilder.getRegion(blockBuilder.getPositionCount() - groupCount, groupCount);

            // Call the lambda function to replace the block, and append the result to output
            Slice replaced = (Slice) replaceFunction.apply(target);
            if (replaced == null) {
                // replacing a substring with null (unknown) makes the entire string null
                return null;
            }
            output.appendBytes(replaced);
        }
        while (getSearchingOffset(matcher, nextStart, source.length()) != -1);
        // Append the last un-matched part
        output.writeBytes(source, appendPosition, source.length() - appendPosition);
        return output.slice();
    }
}


text:
#ifndef STAN_MATH_PRIM_FUN_DIAG_POST_MULTIPLY_HPP
#define STAN_MATH_PRIM_FUN_DIAG_POST_MULTIPLY_HPP

#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/Eigen.hpp>

namespace stan {
namespace math {

/**
 * Return the product of the matrix and the diagonal matrix
 * formed from the vector or row_vector.
 *
 * @tparam T1 type of the matrix
 * @tparam T2 type of the vector/row_vector
 * @param m1 input matrix
 * @param m2 input vector/row_vector
 *
 * @return product of the matrix and the diagonal matrix formed from the
 * vector or row_vector.
 */
template <typename T1, typename T2, require_eigen_t<T1>* = nullptr,
          require_eigen_vector_t<T2>* = nullptr,
          require_all_not_st_var<T1, T2>* = nullptr>
auto diag_post_multiply(const T1& m1, const T2& m2) {
  check_size_match("diag_post_multiply", "m2.size()", m2.size(), "m1.cols()",
                   m1.cols());
  return m1 * m2.asDiagonal();
}

}  // namespace math
}  // namespace stan
#endif


text:
from django.conf.urls import url
from django.views.generic.base import RedirectView

from views import MagicCardView, WelcomeView

urlpatterns = [
    url(r'^favicon\.ico$', RedirectView.as_view(url='/static/img/favicon.ico')),
    url(r'^$', WelcomeView.as_view(), name='welcome'),
    url(r'^magic-cards$', MagicCardView.as_view(), name='magic-cards'),
]


text: <script type="text/javascript" src="content/javascript/argos-AlexFMS.js"></script>


text:
<?php

namespace Simio\Zappi\Service;

interface SubscriberInterface
{
    /**
     * The purpose of this method is to set the subscriber identity
     *
     * @access public
     * @param  integer $identity A unique subscriber identifier
     * @return void
     */
    public function setIdentity($identity = null);

    /**
     * The purpose of this method is to get the subscriber identity
     *
     * @access public
     * @return integer
     */
    public function getIdentity();

    /**
     * The purpose of this method is to check if a subscriber has an identity
     *
     * @access public
     * @return boolean
     */
    public function hasIdentity();

    /**
     * The purpose of this method is to set the subscriber name
     *
     * @access public
     * @param  string $name A subscriber name
     * @return void
     */
    public function setName($name = "");

    /**
     * The purpose of this method is to get the subscriber name
     *
     * @access public
     * @return string
     */
    public function getName();
}


text:
//-------------------------------------------------------------------------------
// <copyright file="HierarchyBuilderTest.cs" company="Appccelerate">
//   Copyright (c) 2008-2019 Appccelerate
//
//   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.
// </copyright>
//-------------------------------------------------------------------------------

namespace Appccelerate.StateMachine.Facts.Machine
{
    using System;
    using System.Collections.Generic;
    using FakeItEasy;
    using FluentAssertions;
    using StateMachine.Machine;
    using StateMachine.Machine.States;
    using Xunit;

    public class HierarchyBuilderTest
    {
        private const string SuperState = "SuperState";
        private readonly HierarchyBuilder<string, int> testee;
        private readonly IImplicitAddIfNotAvailableStateDefinitionDictionary<string, int> states;
        private readonly StateDefinition<string, int> superState;
        private readonly IDictionary<string, string> initiallyLastActiveStates;

        public HierarchyBuilderTest()
        {
            this.superState = new StateDefinition<string, int>(SuperState);
            this.states = A.Fake<IImplicitAddIfNotAvailableStateDefinitionDictionary<string, int>>();
            A.CallTo(() => this.states[SuperState]).Returns(this.superState);
            this.initiallyLastActiveStates = A.Fake<IDictionary<string, string>>();

            this.testee = new HierarchyBuilder<string, int>(SuperState, this.states, this.initiallyLastActiveStates);
        }

        [Theory]
        [InlineData(HistoryType.Deep)]
        [InlineData(HistoryType.Shallow)]
        [InlineData(HistoryType.None)]
        public void SetsHistoryTypeOfSuperState(HistoryType historyType)
        {
            this.testee.WithHistoryType(historyType);

            this.superState.HistoryType
                .Should().Be(historyType);
        }

        [Fact]
        public void SetsInitialSubStateOfSuperState()
        {
            const string SubState = "SubState";
            var subState = new StateDefinition<string, int>(SubState)
            {
                SuperStateModifiable = null
            };
            A.CallTo(() => this.states[SubState]).Returns(subState);

            this.testee.WithInitialSubState(SubState);

            this.superState.InitialState
                .Should().BeSameAs(subState);
        }

        [Fact]
        public void SettingTheInitialSubStateAlsoAddsItToTheInitiallyLastActiveStates()
        {
            const string SubState = "SubState";
            var subState = new StateDefinition<string, int>(SubState)
            {
                SuperStateModifiable = null
            };
            A.CallTo(() => this.states[SubState]).Returns(subState);

            this.testee.WithInitialSubState(SubState);

            A.CallTo(() => this.initiallyLastActiveStates.Add(SuperState, subState.Id)).MustHaveHappenedOnceExactly();
        }

        [Fact]
        public void AddsSubStatesToSuperState()
        {
            const string AnotherSubState = "AnotherSubState";
            var anotherSubState = new StateDefinition<string, int>(AnotherSubState)
            {
                SuperStateModifiable = null
            };
            A.CallTo(() => this.states[AnotherSubState]).Returns(anotherSubState);

            this.testee
                .WithSubState(AnotherSubState);

            this.superState
                .SubStates
                .Should()
                .HaveCount(1)
                .And
                .Contain(anotherSubState);
        }

        [Fact]
        public void ThrowsExceptionIfSubStateAlreadyHasASuperState()
        {
            const string SubState = "SubState";
            var subState = new StateDefinition<string, int>(SubState)
            {
                SuperStateModifiable = new StateDefinition<string, int>("SomeOtherSuperState")
            };
            A.CallTo(() => this.states[SubState]).Returns(subState);

            this.testee.Invoking(t => t.WithInitialSubState(SubState))
                .Should().Throw<InvalidOperationException>()
                .WithMessage(ExceptionMessages.CannotSetStateAsASuperStateBecauseASuperStateIsAlreadySet(
                    SuperState,
                    subState));
        }
    }
}


text:
/*
This file is part of the GSM3 communications library for Arduino
-- Multi-transport communications platform
-- Fully asynchronous
-- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1
-- Voice calls
-- SMS
-- TCP/IP connections
-- HTTP basic clients

This library has been developed by Telefónica Digital - PDI -
- Physical Internet Lab, as part as its collaboration with
Arduino and the Open Hardware Community.

September-December 2012

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

The latest version of this library can always be found at
https://github.com/BlueVia/Official-Arduino
*/

#ifndef __GSM3_SHIELDV1MODEMCORE__
#define __GSM3_SHIELDV1MODEMCORE__

#include <GSM3SoftSerial.h>
#include <GSM3ShieldV1BaseProvider.h>
#include <GSM3MobileAccessProvider.h>
#include <Print.h>

#define UMPROVIDERS 3

class GSM3ShieldV1ModemCore : public GSM3SoftSerialMgr, public Print
{
	private:

		// Phone number, used when calling, sending SMS and reading calling numbers
		// Also PIN in modem configuration
		// Also APN
		// Also remote server
		char* phoneNumber;

		// Working port. Port used in the ongoing command, while opening a server
		// Also for IP address length
		int port;

		// 0 = ongoing
		// 1 = OK
		// 2 = Error. Incorrect state
		// 3 = Unexpected modem message
		// 4 = OK but not available data.
		uint8_t commandError;

		// Counts the steps by the command
		uint8_t commandCounter;

		// Presently ongoing command
		GSM3_commandType_e ongoingCommand;

		// Enable/disable debug
		bool _debug;
		byte _dataInBufferFrom;
		byte _dataInBufferTo;

		// This is the modem (known) status
		GSM3_NetworkStatus_t _status;

		GSM3ShieldV1BaseProvider* UMProvider[UMPROVIDERS];
		GSM3ShieldV1BaseProvider* activeProvider;

		// Private function for anage message
		void manageMsgNow(byte from, byte to);

		unsigned long milliseconds;

	public:

		/** Constructor */
		GSM3ShieldV1ModemCore();

		GSM3SoftSerial gss; // Direct access to modem

		/** Get phone number
			@return phone number
		 */
		char *getPhoneNumber(){return phoneNumber;};

		/** Establish a new phone number
			@param n			Phone number
		 */
		void setPhoneNumber(char *n){phoneNumber=n;};

		/** Get port used
			@return port
		 */
		int getPort(){return port;};

		/** Establish a new port for use
			@param p			Port
		 */
		void setPort(int p){port=p;};

		/** Get command error
			@return command error
		 */
		uint8_t getCommandError(){return commandError;};

		/** Establish a command error
			@param n			Command error
		 */
		void setCommandError(uint8_t n){commandError=n;};

		/** Get command counter
			@return command counter
		 */
		uint8_t getCommandCounter(){return commandCounter;};

		/** Set command counter
			@param c			Initial value
		 */
		void setCommandCounter(uint8_t c){commandCounter=c;};

		/** Get ongoing command
			@return command
		 */
		GSM3_commandType_e getOngoingCommand(){return ongoingCommand;};

		/** Set ongoing command
			@param c			 New ongoing command
		 */
		void setOngoingCommand(GSM3_commandType_e c){ongoingCommand=c;};

		/** Open command
			@param activeProvider	Active provider
			@param c				Command for open
		 */
		void openCommand(GSM3ShieldV1BaseProvider* activeProvider, GSM3_commandType_e c);

		/** Close command
			@param code			Close code
		 */
		void closeCommand(int code);

		// These functions allow writing to the SoftwareSerial
		// If debug is set, dump to the console

		/** Write a character in serial
			@param c			Character
			@return size
		 */
		size_t write(uint8_t c);

		/** Write PGM
			@param str			Buffer for write
			@param CR			Carriadge return adding automatically
			@return size
		 */
		virtual size_t writePGM(PGM_P str, bool CR=true);

		/** Establish debug mode
			@param db			Boolean that indicates debug on or off
		 */
		void setDebug(bool db){_debug=db;};

		/** Generic response parser
			@param rsp			Returns true if expected response exists
			@param string		Substring expected in response
			@param string2		Second substring expected in response
			@return true if parsed correctly
		 */
		bool genericParse_rsp(bool& rsp, char* string=0, char* string2=0);

		/** Generates a generic AT command request from PROGMEM buffer
			@param str			Buffer with AT command
			@param addCR		Carriadge return adding automatically
		 */
		void genericCommand_rq(PGM_P str, bool addCR=true);

		/** Generates a generic AT command request from a simple char buffer
			@param str			Buffer with AT command
			@param addCR		Carriadge return adding automatically
		 */
		void genericCommand_rqc(const char* str, bool addCR=true);

		/** Returns the circular buffer
			@return circular buffer
		 */
		inline GSM3CircularBuffer& theBuffer(){return gss.cb;};

		/** Establish a new network status
			@param status		Network status
		 */
		inline void setStatus(GSM3_NetworkStatus_t status) { _status = status; };

		/** Returns actual network status
			@return network status
		 */
		inline GSM3_NetworkStatus_t getStatus() { return _status; };

		/** Register provider as willing to receive unsolicited messages
			@param provider	Pointer to provider able to receive unsolicited messages
		*/
		void registerUMProvider(GSM3ShieldV1BaseProvider* provider);

		/** unegister provider as willing to receive unsolicited messages
			@param provider	Pointer to provider able to receive unsolicited messages
		*/
		void unRegisterUMProvider(GSM3ShieldV1BaseProvider* provider);

		/** Register a provider as "dialoguing" talking in facto with the modem
			@param provider	Pointer to provider receiving responses
		*/
		void registerActiveProvider(GSM3ShieldV1BaseProvider* provider){activeProvider=provider;};

		/** Needed to manage the SoftSerial. Receives the call when received data
			If _debugging, no code is called
		@param from Starting byte to read
		@param to Last byte to read
		*/
		void manageMsg(byte from, byte to);

		/** If _debugging, this call is assumed to be made out of interrupts
			Prints incoming info and calls manageMsgNow
		*/
		void manageReceivedData();

		/** Chronometer. Measure milliseconds from last call
			@return milliseconds from las time function was called
		*/
		unsigned long takeMilliseconds();

		/** Delay for interrupts
			@param milliseconds		Delay time in milliseconds
		 */
		void delayInsideInterrupt(unsigned long milliseconds);

};

extern GSM3ShieldV1ModemCore theGSM3ShieldV1ModemCore;

#endif


text:
'use strict';

var xtend = require('xtend');

var requestExecutor = require('./request-executor');

function oktaOauthRequest(config, oauthRequest, callback) {
  var req =  {
    url: config.org + 'oauth2/' + config.authorizationServerId + '/v1/token',
    method: 'POST',
    json: true,
    form: xtend({
      client_id: config.authorizationServerClientId,
      client_secret: config.authorizationServerClientSecret
    }, oauthRequest)
  };

  requestExecutor(req, callback);

}

module.exports = oktaOauthRequest;


text:
Slider API
===

``` javascript
requestUrl = '/api/admin/slider/delete'
method = 'POST'

request = {
  _id: Number
}

response = {
  errno: Number
}
```

``` javascript
requestUrl = '/api/admin/slider/post'
method = 'POST'

request = {
  img: String, // name
  title: String,
  url: String
}

response = {
  errno: Number,
  data: {
    _id: Number
  }
}
```


text:
The following environment variables have to be set in order for the application to run correctly.

### General
* `DEFAULT_ORG` Name for the default organization
* `DEFAULT_OAUTH_DOMAINS` Default Domain used for OAuth Authentication
* `TOLA_ACTIVITY_URL` URL for redirecting to TolaActivity
* `TOLA_TRACK_URL` URL for redirecting to TolaTrack
* `TOLA_TRACK_TOKEN` Token to access the TolaTrack API

### Database
* `TOLA_DB_ENGINE` Configuration for Django Database engine. Valid options are defined
in the [Django Documentation](https://docs.djangoproject.com/en/2.0/ref/settings/#engine)
* `TOLA_DB_NAME` Database name
* `TOLA_DB_USER` Username for the database
* `TOLA_DB_PASS` Password for the database
* `TOLA_DB_HOST` Database Hostname or IP-Address
* `TOLA_DB_PORT` Database Port (default for postgresql is `5432`, for mysql `3306`)
* `TOLA_DEBUG` `True` or `False` value specifying if
[Django Debug mode](https://docs.djangoproject.com/en/2.0/ref/settings/#std:setting-DEBUG) should be enabled
* `TOLA_TEMPLATE_DIR` Specifies the template directory for Django templates
(should be set to `templates` for Django default)
* `TOLA_ERROR_LOG` Path to the logfile for errors
* `TOLA_HOSTNAME` Sets the `ALLOWED_HOSTS` settings in Django.
 See [Django Doc](https://docs.djangoproject.com/en/2.0/ref/settings/#allowed-hosts)
* `TOLA_USE_X_FORWARDED_HOST` `True` or `False` value specifying if `USE_X_FORWARDED_HOST` should be enabled
See [Django Doc](https://docs.djangoproject.com/en/2.0/ref/settings/#std:setting-USE_X_FORWARDED_HOST)
* `TOLA_USE_HTTPS` `True` or `False` value specifying if `SECURE_PROXY_SSL_HEADER` should be set to `https`
See [Django Doc](https://docs.djangoproject.com/en/2.0/ref/settings/#std:setting-SECURE_PROXY_SSL_HEADER)

### Social Auth Login/Signup
* `SOCIAL_AUTH_REDIRECT_IS_HTTPS` Value should be `True` or `False`, specifies if social auth will redirect to HTTPS
* `SOCIAL_AUTH_GOOGLE_OAUTH2_KEY` Only needed for Social Auth with Google, OAUTH2 Application Key obtained
from [Google](https://developers.google.com/identity/protocols/OAuth2)
* `SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET` The secret associated with the key defined above
* `SOCIAL_AUTH_GOOGLE_OAUTH2_WHITELISTED_DOMAINS` If using Google OAuth with company accounts, users with EMail addresses
 using the domains defined here can automatically sign up and create an account.
* `SOCIAL_AUTH_MICROSOFT_WHITELISTED_DOMAINS` If using Microsoft OAuth with company accounts, users with EMail addresses
 using the domains defined here can automatically sign up and create an account.
* `SOCIAL_AUTH_MICROSOFT_GRAPH_REDIRECT_URL` The redirect URL for this application.
Should point to `/complete/microsoft-graph` on the server the application is running on
* `SOCIAL_AUTH_MICROSOFT_GRAPH_KEY` Key for using Microsoft OAUTH2 APIs.
Generated in the [Microsoft Application Registration Portal](https://apps.dev.microsoft.com/)
* `SOCIAL_AUTH_MICROSOFT_GRAPH_SECRET` The secret obtained with the Key
* `SOCIAL_AUTH_LOGIN_REDIRECT_URL` The default URL the user should be redirected to after successful Social-Auth login

### Chargebee
Configuration necessary to work with Chargebee integration
* `CHARGEBEE_SITE_API_KEY` API Key obtained by Chargebee
* `CHARGEBEE_SITE` Sitename for Chargebee

### Search

The following environment variables are required to run with search enabled.

* `ELASTICSEARCH_ENABLED` decides whether objects saved to the database will also be indexed in elasticsearch. The search will work without it but only with existing data. This can be used if a lot of data is imported that should not be immediately indexed in ES.
* `ELASTICSEARCH_URL` sets the URL for connecting with the ES cluster.
* `ELASTICSEARCH_INDEX_PREFIX` sets a prefix for each index. There will be many indices for our instances and its important that we don't mix them up. Each index in the background will be created and named automatically, but we can set the prefix to separate between the servers.


text:
chef_version_for_provides '< 14.4' if respond_to?(:chef_version_for_provides)
resource_name :openssl_ec_private_key

include OpenSSLCookbook::Helpers

property :path,        String, name_property: true
property :key_curve,   equal_to: %w(secp384r1 secp521r1 prime256v1 secp224r1 secp256k1), default: 'prime256v1'
property :key_pass,    String
property :key_cipher,  String, default: 'des3', equal_to: ::OpenSSL::Cipher.ciphers
property :owner,       String
property :group,       String
property :mode,        [Integer, String], default: '0640'
property :force,       [true, false], default: false

action :create do
  unless new_resource.force || priv_key_file_valid?(new_resource.path, new_resource.key_pass)
    converge_by("Create an EC private key #{new_resource.path}") do
      log "Generating an #{new_resource.key_curve} "\
          "EC key file at #{new_resource.name}, this may take some time"

      if new_resource.key_pass
        unencrypted_ec_key = gen_ec_priv_key(new_resource.key_curve)
        ec_key_content = encrypt_ec_key(unencrypted_ec_key, new_resource.key_pass, new_resource.key_cipher)
      else
        ec_key_content = gen_ec_priv_key(new_resource.key_curve).to_pem
      end

      file new_resource.path do
        action :create
        owner new_resource.owner unless new_resource.owner.nil?
        group new_resource.group unless new_resource.group.nil?
        mode new_resource.mode
        sensitive true
        content ec_key_content
      end
    end
  end
end


text:
<?php

class PgsFrete
{
    private $_use     = 'curl';
    private $_debug   = false;
    private $_methods = array('curl');
    private $_result;

    public function PgsFrete()
    {
        if ($this->debug()) {
            echo "\nPgsFrete started!";
        }
    }

    public function debug($debug=null)
    {
        if (null===$debug) {
            return $this->_debug;
        }
        $this->_debug = (bool) $debug;
    }

    public function setUse($useMethod)
    {
        if ('string'!==gettype($useMethod)) {
            throw new Exception('Method for setUse not allowed.'.
              'Method passed: '.var_export($useMethod, true));
        }
        $useMethod = strtolower($useMethod);
        if (!in_array($useMethod, $this->_methods)) {
            throw new Exception('Method for setUse not allowed.'.
              'Method passed: '.var_export($useMethod, true));
        }
        $this->_use = $useMethod;
        if ($this->debug()) {
            echo "\nMethod changed to ".strtoupper($useMethod);
        }
    }

    public function getUse()
    {
        return $this->_use;
    }

    public function request($url, $post=null)
    {
        $method = $this->getUse();
        if (in_array($method, $this->_methods)) {
            $method_name = '_request'.ucWords($method);
            if (!method_exists($this, $method_name)) {
              throw new Exception("Method $method_name does not exists.");
            }
            if ($this->debug()) {
                echo "\nTrying to get '$url' using ".strtoupper($method);
            }
            return call_user_func(array($this, $method_name), $url, $post);
        } else {
            throw new Exception('Method not seted.');
        }
    }

    private function _requestCurl($url, $post=null)
    {
        $urlkey="URL:".md5("$url POST:$post");
        if(isset($_SESSION[$urlkey])){
          $this->_result = $_SESSION[$urlkey];
          return;
        }
        $parse = parse_url($url);
        $ch    = curl_init();
        if ('https'===$parse['scheme']) {
            // Nao verificar certificado
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        }
        curl_setopt($ch, CURLOPT_URL, $url); // Retornar o resultado
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Retornar o resultado
        if ($post) {
            curl_setopt($ch, CURLOPT_POST, true); // Ativa o modo POST
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post); // Insere os POSTs
        }
        $result = curl_exec($ch);
        curl_close($ch);
        $this->_result = $result;
        $_SESSION[$urlkey]=$result;
    }

    public function gerar($CepOrigem, $Peso, $Valor, $Destino)
    {
        $Peso=str_replace('.',',',$Peso);
        $url = "https://pagseguro.uol.com.br/desenvolvedor/simulador_de_frete_calcular.jhtml?postalCodeFrom={$CepOrigem}&weight={$Peso}&value={$Valor}&postalCodeTo={$Destino}";
        $this->request($url);
        $result = explode('|',$this->_result);
        $valores=array();
        if($result[0]=='ok'){
          $valores['Sedex']=$result[3];
          $valores['PAC']=$result[4];
        }else{
          die($result[1]);
        }
        return $valores;
    }
}


text:
package edu.ucdenver.ccp.datasource.fileparsers.hprd;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.junit.Test;

import edu.ucdenver.ccp.common.collections.CollectionsUtil;
import edu.ucdenver.ccp.common.file.CharacterEncoding;
import edu.ucdenver.ccp.common.file.FileUtil;
import edu.ucdenver.ccp.datasource.fileparsers.RecordReader;
import edu.ucdenver.ccp.datasource.fileparsers.test.RecordReaderTester;
import edu.ucdenver.ccp.datasource.identifiers.impl.bio.GenBankID;
import edu.ucdenver.ccp.datasource.identifiers.impl.bio.HprdID;
import edu.ucdenver.ccp.datasource.identifiers.impl.bio.NcbiGeneId;
import edu.ucdenver.ccp.datasource.identifiers.impl.bio.OmimID;
import edu.ucdenver.ccp.datasource.identifiers.impl.bio.RefSeqID;
import edu.ucdenver.ccp.datasource.identifiers.impl.bio.UniProtID;

/**
 *
 * @author Bill Baumgartner
 *
 */
public class HprdIdMappingsTxtFileParserTest extends RecordReaderTester {

	private static final String SAMPLE_HprdIdMappingsTxt_FILE_NAME = "HPRD_ID_MAPPINGS.txt";

	@Override
	protected String getSampleFileName() {
		return SAMPLE_HprdIdMappingsTxt_FILE_NAME;
	}

	@Override
	protected RecordReader<?> initSampleRecordReader() throws IOException {
		return new HprdIdMappingsTxtFileParser(sampleInputFile, CharacterEncoding.US_ASCII);
	}

	@Test
	public void testParser() {
		try {
			HprdIdMappingsTxtFileParser parser = new HprdIdMappingsTxtFileParser(sampleInputFile,
					CharacterEncoding.US_ASCII);

			if (parser.hasNext()) {
				/* 00001 ALDH1A1 NM_000689.3 NP_000680.2 216 0 P00352 Aldehyde dehydrogenase 1 */
				HprdIdMappingsTxtFileData record = parser.next();
				assertEquals(new HprdID("00001"), record.getHprdID());
				assertEquals("ALDH1A1", record.getGeneSymbol());
				assertEquals(new RefSeqID("NM_000689.3"), record.getNucleotideAccession());
				assertEquals(new RefSeqID("NP_000680.2"), record.getProteinAccession());
				assertEquals(new NcbiGeneId(216), record.getEntrezGeneID());
				assertNull(record.getOmimID());
				assertEquals(CollectionsUtil.createList(new UniProtID("P00352")), record.getSwissProtIDs());
				assertEquals("Aldehyde dehydrogenase 1", record.getMainName());
			} else {
				fail("Parser should have returned a record here.");
			}

			if (parser.hasNext()) {
				/*
				 * 19429 FXYD8 NM_001099278.1 NP_001092748.1 406875 - P58550 FXYD domain containing
				 * ion transport regulator 8
				 */
				HprdIdMappingsTxtFileData record = parser.next();
				assertEquals(new HprdID("19429"), record.getHprdID());
				assertEquals("FXYD8", record.getGeneSymbol());
				assertEquals(new RefSeqID("NM_001099278.1"), record.getNucleotideAccession());
				assertEquals(new RefSeqID("NP_001092748.1"), record.getProteinAccession());
				assertEquals(new NcbiGeneId(406875), record.getEntrezGeneID());
				assertNull(record.getOmimID());
				assertEquals(CollectionsUtil.createList(new UniProtID("P58550")), record.getSwissProtIDs());
				assertEquals("FXYD domain containing ion transport regulator 8", record.getMainName());
			} else {
				fail("Parser should have returned a record here.");
			}

			if (parser.hasNext()) {
				/* 19398 - NM_001039496.1 NP_001034585.1 25858 - - DKFZP566E164 protein */
				HprdIdMappingsTxtFileData record = parser.next();
				assertEquals(new HprdID("19398"), record.getHprdID());
				assertNull(record.getGeneSymbol());
				assertEquals(new RefSeqID("NM_001039496.1"), record.getNucleotideAccession());
				assertEquals(new RefSeqID("NP_001034585.1"), record.getProteinAccession());
				assertEquals(new NcbiGeneId(25858), record.getEntrezGeneID());
				assertNull(record.getOmimID());
				assertEquals(new ArrayList<UniProtID>(), record.getSwissProtIDs());
				assertEquals("DKFZP566E164 protein", record.getMainName());

			} else {
				fail("Parser should have returned a record here.");
			}

			if (parser.hasNext()) {
				/* 01828	TGFB2	M19154.1	AAA50404.1	7042	190220	P61812,Q59EG9	TGF beta 2 */
				HprdIdMappingsTxtFileData record = parser.next();
				assertEquals(new HprdID("01828"), record.getHprdID());
				assertEquals("TGFB2", record.getGeneSymbol());
				assertEquals(new GenBankID("M19154.1"), record.getNucleotideAccession());
				assertEquals(new GenBankID("AAA50404.1"), record.getProteinAccession());
				assertEquals(new NcbiGeneId(7042), record.getEntrezGeneID());
				assertEquals(new OmimID(190220), record.getOmimID());
				assertEquals(CollectionsUtil.createList(new UniProtID("P61812"), new UniProtID("Q59EG9")), record.getSwissProtIDs());
				assertEquals("TGF beta 2", record.getMainName());

			} else {
				fail("Parser should have returned a record here.");
			}

			assertFalse(parser.hasNext());

		} catch (IOException ioe) {
			ioe.printStackTrace();
			fail("Parser threw an IOException");
		}

	}

	protected Map<File, List<String>> getExpectedOutputFile2LinesMap() {
		final String NS = "<http://kabob.ucdenver.edu/ice/hprd/";
		List<String> lines = CollectionsUtil
				.createList(
						NS
								+ "HPRD_00001_ICE> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://kabob.ucdenver.edu/ice/hprd/HprdIce1> .",
						NS
								+ "HPRD_00001_ICE> <http://purl.obolibrary.org/obo/IAO_0000136> <http://www.hprd.org/HPRD_00001> .",
						NS
								+ "HPRD_00001_ICE> <http://www.hprd.org/isLinkedToRefSeqICE> <http://www.ncbi.nlm.nih.gov/refseq/NM_000689.3_ICE> .",
						NS
								+ "HPRD_00001_ICE> <http://www.hprd.org/isLinkedToRefSeqICE> <http://www.ncbi.nlm.nih.gov/refseq/NP_000680.2_ICE> .",
						NS
								+ "HPRD_00001_ICE> <http://www.hprd.org/isLinkedToEntrezGeneICE> <http://www.ncbi.nlm.nih.gov/gene/EG_216_ICE> .",
						NS
								+ "HPRD_00001_ICE> <http://www.hprd.org/isLinkedToUniProtICE> <http://purl.uniprot.org/uniprot/P00352_ICE> .",
						NS
								+ "HPRD_19429_ICE> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://kabob.ucdenver.edu/ice/hprd/HprdIce1> .",
						NS
								+ "HPRD_19429_ICE> <http://purl.obolibrary.org/obo/IAO_0000136> <http://www.hprd.org/HPRD_19429> .",
						NS
								+ "HPRD_19429_ICE> <http://www.hprd.org/isLinkedToRefSeqICE> <http://www.ncbi.nlm.nih.gov/refseq/NM_001099278.1_ICE> .",
						NS
								+ "HPRD_19429_ICE> <http://www.hprd.org/isLinkedToRefSeqICE> <http://www.ncbi.nlm.nih.gov/refseq/NP_001092748.1_ICE> .",
						NS
								+ "HPRD_19429_ICE> <http://www.hprd.org/isLinkedToEntrezGeneICE> <http://www.ncbi.nlm.nih.gov/gene/EG_406875_ICE> .",
						NS
								+ "HPRD_19429_ICE> <http://www.hprd.org/isLinkedToUniProtICE> <http://purl.uniprot.org/uniprot/P58550_ICE> .",
						NS
								+ "HPRD_19398_ICE> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://kabob.ucdenver.edu/ice/hprd/HprdIce1> .",
						NS
								+ "HPRD_19398_ICE> <http://purl.obolibrary.org/obo/IAO_0000136> <http://www.hprd.org/HPRD_19398> .",
						NS
								+ "HPRD_19398_ICE> <http://www.hprd.org/isLinkedToRefSeqICE> <http://www.ncbi.nlm.nih.gov/refseq/NM_001039496.1_ICE> .",
						NS
								+ "HPRD_19398_ICE> <http://www.hprd.org/isLinkedToRefSeqICE> <http://www.ncbi.nlm.nih.gov/refseq/NP_001034585.1_ICE> .",
						NS
								+ "HPRD_19398_ICE> <http://www.hprd.org/isLinkedToEntrezGeneICE> <http://www.ncbi.nlm.nih.gov/gene/EG_25858_ICE> .");
		Map<File, List<String>> file2LinesMap = new HashMap<File, List<String>>();
		file2LinesMap.put(FileUtil.appendPathElementsToDirectory(outputDirectory, "hprd-idmappings.nt"), lines);
		return file2LinesMap;
	}

	protected Map<String, Integer> getExpectedFileStatementCounts() {
		Map<String, Integer> counts = new HashMap<String, Integer>();
		counts.put("hprd-idmappings.nt", 17);
		counts.put("kabob-meta-hprd-idmappings.nt", 6);
		return counts;
	}
}


text:
<?php

namespace Swader\Diffbot;

use Swader\Diffbot\Exceptions\DiffbotException;

/**
 * Class Diffbot
 *
 * Основной класс работы с API
 *
 * @package Swader\Diffbot
 */
class Diffbot
{
    /** @var string Токен доступа к API */
    private static $token = null;

    /** @var string Токен экземпляра, устанавливается для каждой новой сущности */
    private $instanceToken;

    /**
     * @param string|null $token Токен доступа к API, полученный на
    diffbot.com/dev
     * @throws DiffbotException Если не передан токен
     */
    public function __construct($token = null)
    {
        if ($token === null) {
            if (self::$token === null) {
                $msg = 'Токен не передан и не установлен глобально. ';
                $msg .= 'Используйте Diffbot::setToken, или передайте его в конструктор.';
                throw new DiffbotException($msg);
            }
        } else {
            self::validateToken($token);
            $this->instanceToken = $token;
        }
    }

    /**
     * Устанавливает токен для всех новых сущностей
     * @param $token string Токен доступа к API, полученный на
    diffbot.com/dev
     * @return void
     */
    public static function setToken($token)
    {
        self::validateToken($token);
        self::$token = $token;
    }

    private static function validateToken($token)
    {
        if (!is_string($token)) {
            throw new \InvalidArgumentException('Переданный токен не является строкой.');
        }
        if (strlen($token) < 4) {
            throw new \InvalidArgumentException('Токен "' . $token . '" слишком короткий, и не является валидным.');
        }
        return true;
    }
}


text:
package restFul

import (
  log "github.com/helmutkemper/seelog"
  "github.com/helmutkemper/db"
  "github.com/helmutkemper/mgo/bson"
  "github.com/helmutkemper/mgo"
  "net/http"
  "time"
  "errors"
  "github.com/helmutkemper/customJwt"
  "strings"
  "fmt"
  "io/ioutil"
  "net"
)

type RouteStt struct {
  // English: MongoDB id
  //
  // Português: MongoDB id
  IdMongo                               bson.ObjectId                                                   `bson:"_id,omitempty"`

  // English: endpoint/link name
  //
  // Português: Nome do endpoint/link
  Name                                  string                                                          `bson:"name" json:"name"`

  // English: description of endpoint/link
  //
  // Português: descrição do endpoint/linc
  Description                           string                                                          `bson:"description" json:"description"`

  // English:
  //
  // Português: Nível de segurança. Cada endpoint/link recebe um número inteiro e cada usuário recebe um array com
  // números correspondentes. O nível 0 é aberto a todos os usuários, para os demais valores, o nível deve ter um valor
  // correspondente ao nível do usuário. Por exemplo, imagine que o nível escolhido foi 2, e o usuário tem nível
  // int[1 2 3], logo o mesmo tem acesso ao endpoint/link. Porém, se o endpoint/link tiver o nível 2 e o usuário tiver
  // o nível int[1, 3, 4], o usuário não tem acesso.
  // Por padrão do sistema, 1 será usado para o super usuário que pode estragar o sistema, 2 para o administrador
  Level                                 int                                                             `bson:"level" json:"level"`

  // English:
  //
  // Português: Método de acesso do endpoint/link segundo o padrão de API restful. Por exemplo, GET, POST, DELETE...
  Method                                string                                                          `bson:"method" json:"method"`

  // English:
  //
  // Português: Expressão regular responsável por identificar a URL do endpoint/link. Por exemplo: "/point/{id:[0-9]+}"
  Pattern                               string                                                          `bson:"pattern" json:"pattern"`

  // English:
  //
  // Português: Ponteiro da função a ser executado durante o acesso ao endpoint/link.
  HandlerFunc                           http.HandlerFunc                                                `bson:"-" json:"-"`

  // English:
  //
  // Português: [Opcional] Ponteiro da função de autorização para aceso ao endpoint/link.
  // A finalidade é que você possa usar a sua própria função de autorização, caso necessite.
  AuthorizationHandlerFunc              func(w http.ResponseWriter, r *http.Request, level int) bool    `bson:"-" json:"-"`

  // English:
  //
  // Português: Ponteiro da função de autorização negada.
  UnauthorizedHandlerFunc               http.HandlerFunc                                                `bson:"-" json:"-"`

  // English:
  //
  // Português: Nome da coleção de banco de dados, padrão do sistema.
  DbCollectionName                      string                                                          `bson:"dbCollectionName" json:"dbCollectionName"`

  Host                                  string                                                          `bson:"host" json:"host"`
  Next                                  http.HandlerFunc                                                `bson:"-" json:"-"`
  DockerUri                             string                                                          `bson:"dockerUri" json:"dockerUri"`
  Search                                string                                                          `bson:"search" json:"search"`
  Replace                               string                                                          `bson:"replace" json:"replace"`

  // Ponteiro da classe do MongoDB
  //mongodb class
  *db.DbStt                                                                                `bson:"-" json:"-"`
}

const (
  XForwardedPort     = "X-Forwarded-Port"
  XForwardedProto    = "X-Forwarded-Proto"
  XForwardedFor      = "X-Forwarded-For"
  XForwardedHost     = "X-Forwarded-Host"
  XForwardedServer   = "X-Forwarded-Server"
  Connection         = "Connection"
  KeepAlive          = "Keep-Alive"
  ProxyAuthenticate  = "Proxy-Authenticate"
  ProxyAuthorization = "Proxy-Authorization"
  Te                 = "Te" // canonicalized version of "TE"
  Trailers           = "Trailers"
  TransferEncoding   = "Transfer-Encoding"
  Upgrade            = "Upgrade"
  ContentLength      = "Content-Length"
  xForwardedURI      = "X-Forwarded-Uri"
)

// Hop-by-hop headers. These are removed when sent to the backend.
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html
// Copied from reverseproxy.go, too bad
var HopHeaders = []string{
  Connection,
  KeepAlive,
  ProxyAuthenticate,
  ProxyAuthorization,
  Te, // canonicalized version of "TE"
  Trailers,
  TransferEncoding,
  Upgrade,
}

// ClientTLS holds TLS specific configurations as client
// CA, Cert and Key can be either path or file contents
type clientTLS struct {
  CA                 string `description:"TLS CA"`
  CAOptional         bool   `description:"TLS CA.Optional"`
  Cert               string `description:"TLS cert"`
  Key                string `description:"TLS key"`
  InsecureSkipVerify bool   `description:"TLS insecure skip verify"`
}

// Forward authentication
type typeForward struct {
  Address            string     `description:"Authentication server address"`
  TLS                *clientTLS `description:"Enable TLS support" export:"true"`
  TrustForwardHeader bool       `description:"Trust X-Forwarded-* headers" export:"true"`
}

func( el *RouteStt ) Insert() error {
  var err error
  err = el.DbStt.TestConnection()
  if err != nil{
    log.Criticalf( "gOsmServer.restFul.typeRouter.error: %s", err )
    return err
  }

  if bson.IsObjectIdHex( el.IdMongo.String() ) == false {
    el.IdMongo, err = el.DbStt.GetMongoId()
    if err != nil{
      log.Criticalf( "gOsmServer.restFul.typeRouter.error: %s", err )
      return err
    }
  }

  if el.DbStt.HasIndex( el.DbCollectionName, "name" ) != true {
    el.DbStt.IndexKeyMake ( el.DbCollectionName, "name" )
  }

  err = el.DbStt.Insert( el.DbCollectionName, el )
  if err != nil {
    log.Criticalf( "gOsmServer.restFul.typeRouter.error: %s", err )
  }

  return err
}

func( el *RouteStt ) FindOne( queryAObj bson.M ) error {
  err := el.DbStt.TestConnection()
  if err != nil{
    log.Criticalf( "gOsmServer.restFul.typeRouter.error: %s", err )
    return err
  }

  err = el.DbStt.FindOne( el.DbCollectionName, el, queryAObj )
  if err != nil{
    log.Criticalf( "gOsmServer.restFul.typeRouter.error: %s", err )
  }

  return err
}

func( el *RouteStt ) Update( queryAObj ...interface{} ) error {
  err := el.DbStt.TestConnection()
  if err != nil {
    return err
  }

  if len( queryAObj ) == 1 {
    err = el.DbStt.Update(el.DbCollectionName, el, queryAObj[0])
    if err != nil{
      log.Criticalf( "gOsmServer.restFul.typeRouter.error: %s", err )
    }
    return err
  }

  err = el.DbStt.Update(el.DbCollectionName, queryAObj[1], queryAObj[0])
  if err != nil{
    log.Criticalf( "gOsmServer.restFul.typeRouter.error: %s", err )
  }
  return err
}

func( el *RouteStt ) RemoveAll( queryAObj bson.M ) ( *mgo.ChangeInfo, error ) {
  var change *mgo.ChangeInfo
  var err = el.DbStt.TestConnection()
  if err != nil{
    log.Criticalf( "gOsmServer.restFul.typeRouter.error: %s", err )
    return nil, err
  }

  change, err = el.DbStt.RemoveAll( el.DbCollectionName, queryAObj )
  if err != nil{
    log.Criticalf( "gOsmServer.restFul.typeRouter.error: %s", err )
    return change, err
  }

  return change, err
}

func( el *RouteStt ) WrapHandler(

      serverHandlerFunc func(w http.ResponseWriter, r *http.Request),
      level int,
      authorizationHandlerFunc func(w http.ResponseWriter, r *http.Request, level int) bool,
      unauthorizedHandlerFunc func(w http.ResponseWriter, r *http.Request),

    ) http.HandlerFunc {

  //unauthorizedHandler
  //fixme: falta fazer a função padrão

  h := func(w http.ResponseWriter, r *http.Request) {

    if unauthorizedHandlerFunc == nil {
      unauthorizedHandlerFunc = el.UnauthorizedAccess
    }

    if authorizationHandlerFunc != nil {
      if !authorizationHandlerFunc(w, r, level) {
        unauthorizedHandlerFunc(w, r)
        return
      }
    } else {
      if !el.UserIsAuthorized(r, level) {
        unauthorizedHandlerFunc(w, r)
        return
      }
    }

    serverHandlerFunc(w, r)
  }

  return h
}

func( el *RouteStt ) UserIsAuthorized(r *http.Request, level int) bool {
  if level == 0 {
    return true
  }

  data, err := customJwt.SessionTest(r)
  if err != nil {
    return false
  }

  for _, levelInJwt := range data["levels"].([]interface{}){
    if int(levelInJwt.(float64)) == level {
      log.Info( "autorizado" )
      return true
    }
  }

  log.Info( "nao autorizado" )
  return false

}

func( el *RouteStt ) UnauthorizedAccess(w http.ResponseWriter, r *http.Request) {
  output := JSonOutStt{}
  output.ToOutput( 0, errors.New("unauthorized access"), []int{}, w )
}

func( el *RouteStt ) Logger(route RouteStt) http.Handler {
  return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    start := time.Now()

    var newUri = route.DockerUri

    if route.Search != "" {
      newUri = route.DockerUri + strings.Replace( r.URL.Path, route.Search, route.Replace, 1 )
    }

    if route.HandlerFunc != nil {
      route.HandlerFunc( w, r )
    } else {
      el.Forward(w, r, route.Next, newUri)
    }

    log.Infof(
      "%s\t%s\t%s\t%s",
      r.Method,
      r.RequestURI,
      route.Name,
      time.Since(start),
    )
  })
}

// CopyHeaders copies http headers from source to destination, it
// does not overide, but adds multiple headers
func( el *RouteStt ) CopyHeaders(dst http.Header, src http.Header) {
  for k, vv := range src {
    dst[k] = append(dst[k], vv...)
  }
}

// Forward the authentication to a external server
func( el *RouteStt ) Forward(w http.ResponseWriter, r *http.Request, next http.HandlerFunc, url string) {

  config := typeForward{
    TrustForwardHeader: true,
  }

  // Ensure our request client does not follow redirects
  httpClient := http.Client{
    CheckRedirect: func(r *http.Request, via []*http.Request) error {
      return http.ErrUseLastResponse
    },
  }

  forwardReq, err := http.NewRequest(http.MethodGet, url, nil)
  if err != nil {
    fmt.Printf("erro no redirecionamento")
    w.WriteHeader(http.StatusInternalServerError)
    return
  }

  el.writeHeader(r, forwardReq, config.TrustForwardHeader)

  forwardResponse, forwardErr := httpClient.Do(forwardReq)
  if forwardErr != nil {
    fmt.Printf("Error calling %s. Cause: %s", config.Address, forwardErr)
    w.WriteHeader(http.StatusInternalServerError)
    return
  }

  body, readError := ioutil.ReadAll(forwardResponse.Body)
  if readError != nil {
    fmt.Printf("Error reading body %s. Cause: %s", config.Address, readError)
    w.WriteHeader(http.StatusInternalServerError)
    return
  }
  defer forwardResponse.Body.Close()

  // Pass the forward response's body and selected headers if it
  // didn't return a response within the range of [200, 300).
  if forwardResponse.StatusCode < http.StatusOK || forwardResponse.StatusCode >= http.StatusMultipleChoices {
    fmt.Printf("Remote error %s. StatusCode: %d", config.Address, forwardResponse.StatusCode)

    // Grab the location header, if any.
    redirectURL, err := forwardResponse.Location()

    if err != nil {
      if err != http.ErrNoLocation {
        fmt.Printf("Error reading response location header %s. Cause: %s", config.Address, err)
        w.WriteHeader(http.StatusInternalServerError)
        return
      }
    } else if redirectURL.String() != "" {
      // Set the location in our response if one was sent back.
      w.Header().Add("Location", redirectURL.String())
    }

    // Pass any Set-Cookie headers the forward auth server provides
    for _, cookie := range forwardResponse.Cookies() {
      w.Header().Add("Set-Cookie", cookie.String())
    }

    w.WriteHeader(forwardResponse.StatusCode)
    w.Write(body)
    return
  }

  r.RequestURI = r.URL.RequestURI()

  if next != nil {
    next(w, r)
  } else {
    w.Write( body )
  }
}

func( el *RouteStt ) writeHeader(req *http.Request, forwardReq *http.Request, trustForwardHeader bool) {
  el.CopyHeaders(forwardReq.Header, req.Header)

  if clientIP, _, err := net.SplitHostPort(req.RemoteAddr); err == nil {
    if trustForwardHeader {
      if prior, ok := req.Header[XForwardedFor]; ok {
        clientIP = strings.Join(prior, ", ") + ", " + clientIP
      }
    }
    forwardReq.Header.Set(XForwardedFor, clientIP)
  }

  if xfp := req.Header.Get(XForwardedProto); xfp != "" && trustForwardHeader {
    forwardReq.Header.Set(XForwardedProto, xfp)
  } else if req.TLS != nil {
    forwardReq.Header.Set(XForwardedProto, "https")
  } else {
    forwardReq.Header.Set(XForwardedProto, "http")
  }

  if xfp := req.Header.Get(XForwardedPort); xfp != "" && trustForwardHeader {
    forwardReq.Header.Set(XForwardedPort, xfp)
  }

  if xfh := req.Header.Get(XForwardedHost); xfh != "" && trustForwardHeader {
    forwardReq.Header.Set(XForwardedHost, xfh)
  } else if req.Host != "" {
    forwardReq.Header.Set(XForwardedHost, req.Host)
  } else {
    forwardReq.Header.Del(XForwardedHost)
  }

  if xfURI := req.Header.Get(xForwardedURI); xfURI != "" && trustForwardHeader {
    forwardReq.Header.Set(xForwardedURI, xfURI)
  } else if req.URL.RequestURI() != "" {
    forwardReq.Header.Set(xForwardedURI, req.URL.RequestURI())
  } else {
    forwardReq.Header.Del(xForwardedURI)
  }
}


text:
namespace hadesmem
{
// DANGER DANGER WILL ROBINSON
// This currently has some serious limitations. Notably:
//   Not even close to 'production' quality. Full of subtle bugs, gaps, etc.
//   Can only hook the 'current' thread.
//   Can only set one hook per thread.
//   No validation. e.g. Lets you orphan an existing hook by setting a new one.
//   Stomps over other things which may be using the debug registers.
//   Stomps over other types of VEH hooks (e.g. will stomp over an INT3 hook
//     on the same address).
//   Not handling TID reuse or invalidation.
//   Other bad things. Seriously, my head hurts from thinking of all the corner
//     cases.
template <typename TargetFuncT> class PatchDr : public PatchVeh<TargetFuncT>
{
public:
  template <typename TargetFuncT, typename DetourFuncT>
  explicit PatchDr(Process const& process,
                   TargetFuncT target,
                   DetourFuncT detour)
    : PatchVeh{process, target, detour}
  {
    HADESMEM_DETAIL_STATIC_ASSERT(detail::IsFunction<TargetFuncT>::value ||
                                  std::is_pointer<TargetFuncT>::value);
    HADESMEM_DETAIL_STATIC_ASSERT(detail::IsFunction<DetourFuncT>::value ||
                                  std::is_pointer<DetourFuncT>::value);
  }

  template <typename TargetFuncT, typename DetourFuncT>
  explicit PatchDr(Process&& process,
                   TargetFuncT target,
                   DetourFuncT detour) = delete;

  PatchDr(PatchDr const& other) = delete;

  PatchDr& operator=(PatchDr const& other) = delete;

  PatchDr(PatchDr&& other) : PatchVeh{std::move(other)}
  {
  }

  PatchDr& operator=(PatchDr&& other)
  {
    PatchVeh::operator=(std::move(other));
    return *this;
  }

protected:
  virtual std::size_t GetPatchSize() const override
  {
    // The patch size is actually zero, but we need to pretend that we've patch
    // something so we can generate the trampoline to jump over it.
    return 1;
  }

  virtual void WritePatch() override
  {
    hadesmem::detail::AcquireSRWLock const lock(
      &GetSrwLock(), hadesmem::detail::SRWLockType::Exclusive);

    auto& veh_hooks = GetVehHooks();

    HADESMEM_DETAIL_ASSERT(veh_hooks.find(target_) == std::end(veh_hooks));
    veh_hooks[target_] = this;

    auto const veh_cleanup_hook = [&]()
    {
      auto const veh_hooks_removed = veh_hooks.erase(target_);
      (void)veh_hooks_removed;
      HADESMEM_DETAIL_ASSERT(veh_hooks_removed);
    };
    auto scope_veh_cleanup_hook =
      hadesmem::detail::MakeScopeWarden(veh_cleanup_hook);

    HADESMEM_DETAIL_TRACE_A("Setting DR hook.");

    auto& dr_hooks = GetDrHooks();
    auto const thread_id = ::GetCurrentThreadId();
    HADESMEM_DETAIL_ASSERT(dr_hooks.find(thread_id) == std::end(dr_hooks));

    Thread const thread(thread_id);
    auto context = GetThreadContext(thread, CONTEXT_DEBUG_REGISTERS);

    std::uint32_t dr_index = static_cast<std::uint32_t>(-1);
    for (std::uint32_t i = 0; i < 4; ++i)
    {
      // Check whether the DR is available according to the control register
      bool const control_available = !(context.Dr7 & (1ULL << (i * 2)));
      // Check whether the DR is zero. Pobably not actually necessary, but
      // it's a nice additional sanity check. This may require a
      // user-controlable flag in future though if the code being hooked is
      // 'hostile'.
      bool const dr_available = !(&context.Dr0)[i];
      if (control_available && dr_available)
      {
        dr_index = i;
        break;
      }
    }

    if (dr_index == static_cast<std::uint32_t>(-1))
    {
      HADESMEM_DETAIL_THROW_EXCEPTION(
        Error{} << ErrorString{"No free debug registers."});
    }

    dr_hooks[ ::GetCurrentThreadId()] = dr_index;

    auto const dr_cleanup_hook = [&]()
    {
      auto const dr_hooks_removed = dr_hooks.erase(::GetCurrentThreadId());
      (void)dr_hooks_removed;
      HADESMEM_DETAIL_ASSERT(dr_hooks_removed);
    };
    auto scope_dr_cleanup_hook =
      hadesmem::detail::MakeScopeWarden(dr_cleanup_hook);

    (&context.Dr0)[dr_index] = reinterpret_cast<std::uintptr_t>(target_);
    // Set appropriate L0-L3 flag
    context.Dr7 |= static_cast<std::uintptr_t>(1ULL << (dr_index * 2));
    // Set appropriate RW0-RW3 field (Execution)
    std::uintptr_t break_type = 0;
    context.Dr7 |= (break_type << (16 + 4 * dr_index));
    // Set appropriate LEN0-LEN3 field (1 byte)
    std::uintptr_t break_len = 0;
    context.Dr7 |= (break_len << (18 + 4 * dr_index));
    // Set LE flag
    std::uintptr_t local_enable = 1 << 8;
    context.Dr7 |= local_enable;

    SetThreadContext(thread, context);

    scope_veh_cleanup_hook.Dismiss();
    scope_dr_cleanup_hook.Dismiss();
  }

  virtual void RemovePatch() override
  {
    hadesmem::detail::AcquireSRWLock const lock(
      &GetSrwLock(), hadesmem::detail::SRWLockType::Exclusive);

    HADESMEM_DETAIL_TRACE_A("Unsetting DR hook.");

    auto& dr_hooks = GetDrHooks();
    auto const thread_id = ::GetCurrentThreadId();
    auto const iter = dr_hooks.find(thread_id);
    HADESMEM_DETAIL_ASSERT(iter != std::end(dr_hooks));
    auto const dr_index = iter->second;

    Thread const thread(thread_id);
    auto context = GetThreadContext(thread, CONTEXT_DEBUG_REGISTERS);

    // Clear the appropriate DR
    *(&context.Dr0 + dr_index) = 0;
    // Clear appropriate L0-L3 flag
    context.Dr7 &= ~static_cast<std::uintptr_t>(1ULL << (dr_index * 2));

    SetThreadContext(thread, context);

    auto const dr_hooks_removed = dr_hooks.erase(thread_id);
    (void)dr_hooks_removed;
    HADESMEM_DETAIL_ASSERT(dr_hooks_removed);

    auto& veh_hooks = GetVehHooks();
    auto const veh_hooks_removed = veh_hooks.erase(target_);
    (void)veh_hooks_removed;
    HADESMEM_DETAIL_ASSERT(veh_hooks_removed);
  }

  virtual bool CanHookChainImpl() const noexcept override
  {
    return false;
  }
};
}


text:
"""Handles reports over scheduler data."""

from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import

import time
import datetime
import itertools
import logging
import fnmatch

import numpy as np
import pandas as pd

import six

_LOGGER = logging.getLogger(__name__)

def servers(cell):
    """Prepare DataFrame with server information."""

    # Hard-code order of columns
    columns = [
        'name', 'location', 'partition', 'traits',
        'state', 'valid_until',
        'mem', 'cpu', 'disk',
        'mem_free', 'cpu_free', 'disk_free'
    ]

    def _server_location(node):
        """Recursively yield the node's parents."""
        while node:
            yield node.name
            node = node.parent

    def _server_row(server):
        """Transform server into a DataFrame-ready dict."""
        partition = list(server.labels)[0]
        row = {
            'name': server.name,
            'location': '/'.join(reversed(list(
                _server_location(server.parent)
            ))),
            'partition': partition if partition else '-',
            'traits': server.traits.traits,
            'state': server.state.value,
            'valid_until': server.valid_until,
            'mem': server.init_capacity[0],
            'cpu': server.init_capacity[1],
            'disk': server.init_capacity[2],
            'mem_free': server.free_capacity[0],
            'cpu_free': server.free_capacity[1],
            'disk_free': server.free_capacity[2]
        }

        return row

    frame = pd.DataFrame.from_dict([
        _server_row(server)
        for server in cell.members().values()
    ]).astype({
        'mem': 'int',
        'cpu': 'int',
        'disk': 'int',
        'mem_free': 'int',
        'cpu_free': 'int',
        'disk_free': 'int'
    })

    if frame.empty:
        frame = pd.DataFrame(columns=columns)

    return frame[columns].set_index('name').sort_index()

def iterate_allocations(path, alloc):
    """Generate (path, alloc) tuples for the leaves of the allocation tree."""
    if not alloc.sub_allocations:
        return iter([('/'.join(path), alloc)])
    else:
        def _chain(acc, item):
            """Chains allocation iterators."""
            name, suballoc = item
            return itertools.chain(
                acc,
                iterate_allocations(path + [name], suballoc)
            )

        return six.moves.reduce(_chain, alloc.sub_allocations.iteritems(), [])

def allocations(cell):
    """Prepare DataFrame with allocation information."""

    # Hard-code order of columns
    columns = [
        'partition', 'name', 'mem', 'cpu', 'disk',
        'rank', 'rank_adj', 'traits', 'max_util'
    ]

    def _alloc_row(partition, name, alloc):
        """Transform allocation into a DataFrame-ready dict."""
        if not name:
            name = 'root'
        if not partition:
            partition = '-'

        return {
            'partition': partition,
            'name': name,
            'mem': alloc.reserved[0],
            'cpu': alloc.reserved[1],
            'disk': alloc.reserved[2],
            'rank': alloc.rank,
            'rank_adj': alloc.rank_adjustment,
            'traits': alloc.traits,
            'max_util': alloc.max_utilization,
        }

    frame = pd.DataFrame.from_dict([
        _alloc_row(label, name, alloc)
        for label, partition in cell.partitions.iteritems()
        for name, alloc in iterate_allocations([], partition.allocation)
    ])
    if frame.empty:
        frame = pd.DataFrame(columns=columns)

    return frame[columns].astype({
        'mem': 'int',
        'cpu': 'int',
        'disk': 'int'
    }).set_index(['partition', 'name']).sort_index()

def apps(cell):
    """Prepare DataFrame with app and queue information."""

    # Hard-code order of columns
    columns = [
        'instance', 'allocation', 'rank', 'affinity', 'partition',
        'identity_group', 'identity',
        'order', 'lease', 'expires', 'data_retention',
        'pending', 'server', 'util',
        'mem', 'cpu', 'disk'
    ]

    def _app_row(item):
        """Transform app into a DataFrame-ready dict."""
        rank, util, pending, order, app = item
        return {
            'instance': app.name,
            'affinity': app.affinity.name,
            'allocation': app.allocation.name,
            'rank': rank,
            'partition': app.allocation.label or '-',
            'util': util,
            'pending': pending,
            'order': order,
            'identity_group': app.identity_group,
            'identity': app.identity,
            'mem': app.demand[0],
            'cpu': app.demand[1],
            'disk': app.demand[2],
            'lease': app.lease,
            'expires': app.placement_expiry,
            'data_retention': app.data_retention_timeout,
            'server': app.server
        }

    queue = []
    for partition in cell.partitions.values():
        allocation = partition.allocation
        queue += allocation.utilization_queue(cell.size(allocation.label))

    frame = pd.DataFrame.from_dict([_app_row(item) for item in queue]).fillna({
        'expires': -1,
        'identity': -1,
        'data_retention': -1
    })
    if frame.empty:
        frame = pd.DataFrame(columns=columns)

    return frame[columns].astype({
        'mem': 'int',
        'cpu': 'int',
        'disk': 'int',
        'order': 'int',
        'expires': 'int',
        'data_retention': 'int',
        'identity': 'int'
    }).set_index('instance').sort_index()

def utilization(prev_utilization, apps_df):
    """Returns dataseries describing cell utilization.

    prev_utilization - utilization dataframe before current.
    apps - app queue dataframe.
    """
    # Passed by ref.
    row = apps_df.reset_index()
    if row.empty:
        return row

    row['count'] = 1
    row['name'] = row['instance'].apply(lambda x: x.split('#')[0])
    row = row.groupby('name').agg({'cpu': np.sum,
                                   'mem': np.sum,
                                   'disk': np.sum,
                                   'count': np.sum,
                                   'util': np.max})
    row = row.stack()
    dt_now = datetime.datetime.fromtimestamp(time.time())
    current = pd.DataFrame([row], index=pd.DatetimeIndex([dt_now]))

    if prev_utilization is None:
        return current
    else:
        return prev_utilization.append(current)

def reboots(cell):
    """Prepare dataframe with server reboot info."""

    # Hard-code order of columns
    columns = [
        'server', 'valid-until', 'days-left',
    ]

    def _reboot_row(server, now):
        valid_until = datetime.datetime.fromtimestamp(server.valid_until)
        return {
            'server': server.name,
            'valid-until': valid_until,
            'days-left': (valid_until - now).days,
        }

    now = datetime.datetime.now()

    frame = pd.DataFrame.from_dict([
        _reboot_row(server, now)
        for server in cell.members().values()
    ])

    return frame[columns].set_index('server').sort_index()

class ExplainVisitor(object):
    """Scheduler visitor"""

    def __init__(self):
        """Initialize result"""
        self.result = []

    def add(self, alloc, entry):
        """Add new row to result"""
        rank, util, _pending, _order, app = entry

        alloc_name = '/'.join(alloc.path)
        server = app.server if app.server else '-'

        self.result.append({
            'alloc': alloc_name,
            'rank': rank,
            'util': util if alloc_name else '',
            'name': app.name,
            'server': server if not alloc_name else '',
        })

    def finish(self):
        """Post-process result array"""
        def _sort_order(entry):
            return (entry['alloc'], entry['util'])

        result = sorted(self.result, key=_sort_order)

        # annotate with position in alloc queue
        pos = 1
        alloc = ''
        for row in result:
            if row['alloc'] != alloc:
                alloc = row['alloc']
                pos = 1
            row['pos'] = pos
            pos = pos + 1

        self.result = result

    def filter(self, pattern):
        """Filter result to rows with matching app instances"""
        self.result = [row for row in self.result
                       if fnmatch.fnmatch(row['name'], pattern)]

def explain_queue(cell, partition, pattern=None):
    """Compute dataframe for explaining app queue"""
    alloc = cell.partitions[partition].allocation
    size = cell.size(partition)
    visitor = ExplainVisitor()
    queue = alloc.utilization_queue(size, visitor.add)

    # we run the generator to completion, and this builds up the
    # visitor as a side-effect
    for _ in queue:
        pass

    visitor.finish()

    if pattern:
        visitor.filter(pattern)

    # set columns explicitly to control order
    columns = ['pos', 'alloc', 'name', 'rank', 'util', 'server']
    return pd.DataFrame(visitor.result, columns=columns)

def _preorder_walk(node, _app=None):
    """Walk the tree in preorder"""
    return itertools.chain(
        [node],
        *[_preorder_walk(child) for child in node.children]
    )

def _servers_walk(cell, _app):
    """Return servers only"""
    return cell.members().values()

def _limited_walk(node, app):
    """Walk the tree like preorder, but only expand nodes when they are
feasible for placement"""
    if node.check_app_constraints(app):
        return itertools.chain(
            [node],
            *[_limited_walk(child, app) for child in node.children]
        )
    else:
        return [node]

WALKS = {
    'servers': _servers_walk,
    'full': _preorder_walk,
    'default': _limited_walk,
}

def explain_placement(cell, app, mode):
    """Explain placement for app"""
    result = []
    for node in WALKS[mode](cell, app):
        capacity = node.free_capacity > app.demand
        result.append({
            'name': node.name,
            'affinity': node.check_app_affinity_limit(app),
            'traits': node.traits.has(app.traits),
            'partition': app.allocation.label in node.labels,
            'feasible': node.check_app_constraints(app),
            'memory': capacity[0],
            'cpu': capacity[1],
            'disk': capacity[2],
        })

    # Hard-code order of columns
    columns = [
        'partition', 'traits', 'affinity',
        'memory', 'cpu', 'disk', 'name'
    ]
    df = pd.DataFrame(result, columns=columns)
    df.replace(True, '.', inplace=True)
    df.replace(False, 'x', inplace=True)
    return df


text:
require 'bio-ucsc'
describe "Bio::Ucsc::Hg18::KnwonCanonical" do

  describe "#find_by_interval" do
    context "given range chr1:1-5,000" do
      it 'returns an results (r.chrom = "chr1")' do
        Bio::Ucsc::Hg18::DBConnection.default
        Bio::Ucsc::Hg18::DBConnection.connect
        i = Bio::GenomicInterval.parse("chr1:1-5,000")
        r = Bio::Ucsc::Hg18::KnownCanonical.find_by_interval(i)
        r.chrom.should == "chr1"
      end
    end
  end

end


text:
<?php

use Slim\LogWriter;
use SlimController\Slim;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Filesystem\Exception\IOExceptionInterface;
use rmatil\server\Middleware\SecurityMiddleware;

require 'vendor/autoload.php';

// enable this for log writing to file
$logWriter = new LogWriter(fopen(__DIR__.'/logs/server.log', 'a'));

// Prepare app
$app = new Slim(array(
    'debug'                      => true, // enable slim exception handler
    'log.level'                  => \Slim\Log::DEBUG,
    'log.enabled'                => true, // enable logging
    'controller.class_prefix'    => 'rmatil\server\Controller',
    'controller.class_suffix'    => 'Controller',
    'controller.method_suffix'   => 'Action',
    'controller.template_suffix' => 'php',
    'log.writer'                 => $logWriter, // enable this for log writing to file
    'templates.path'             => '../templates'
));

$app->add(new SecurityMiddleware());

$fs = new Filesystem();
$filePath = __DIR__ . "/html/addresses/addresses.json";

$app->filePath = $filePath;

$app->container->singleton('fs', function () use ($fs) {
    return $fs;
});

$app->addRoutes(array(
    '/'                     => array('get'     => 'App:listIpAddresses'),
    '/ip-addresses'         => array('get'     => 'App:listIpAddresses'),
    '/ip-addresses/new'     => array('post'    => 'App:insertIpAddress'),
    '/ip-addresses/remove'  => array('post'    => 'App:removeIpAddress'),
    '/keepalive'            => array('post'     => 'App:keepAlive'),
));

// Run app
$app->run();


text:
package com.tngtech.jgiven.junit.injection;

import com.tngtech.jgiven.Stage;
import com.tngtech.jgiven.annotation.ComposedScenarioStage;
import com.tngtech.jgiven.annotation.ExpectedScenarioState;
import com.tngtech.jgiven.annotation.ProvidedScenarioState;
import com.tngtech.jgiven.annotation.ScenarioStage;
import com.tngtech.jgiven.annotation.ScenarioState;
import com.tngtech.jgiven.junit.ScenarioTest;

import org.junit.Test;

import static org.assertj.core.api.Assertions.assertThat;

public class MultilevelComposedStepInjectionTest extends ScenarioTest {

    @ScenarioStage
    CustomerSteps customerSteps;

    @ScenarioStage
    ThenCustomer thenCustomer;

    @Test
    public void substeps_are_injected_into_test_case() {
        customerSteps.given().a_customer();
        thenCustomer.then().the_site_language_is( "de-DE" );
    }

    static class CustomerSteps extends Stage<CustomerSteps> {

        @ComposedScenarioStage
        LanguageSteps languageSteps;

        public CustomerSteps a_customer() {
            languageSteps.the_site_language_is_set_to( "de-DE" );
            return self();
        }

    }

    static class LanguageSteps extends Stage<LanguageSteps> {

        @ComposedScenarioStage
        OtherLanguageSteps otherLanguageSteps;

        public LanguageSteps the_site_language_is_set_to( String language ) {
            otherLanguageSteps.the_site_language_is_set_to( language );
            return this;
        }

    }

    static class ThenCustomer extends Stage<ThenCustomer> {

        @ExpectedScenarioState
        String language;

        @ComposedScenarioStage
        LanguageSteps languageSteps;

        @ComposedScenarioStage
        OtherLanguageSteps otherLanguageSteps;

        public ThenCustomer the_site_language_is( String expectedLanguage ) {
            assertThat( language ).isEqualTo( expectedLanguage );
            assertThat( languageSteps.otherLanguageSteps.language ).isEqualTo( expectedLanguage );
            assertThat( otherLanguageSteps.language ).isEqualTo( expectedLanguage );

            return self();
        }

    }

    static class OtherLanguageSteps extends Stage<OtherLanguageSteps> {

        @ExpectedScenarioState
        String language;

        public OtherLanguageSteps the_site_language_is_set_to(String language) {
            this.language = language;
            return this;
        }

    }

    static class Customer {
    }

}


text:
module Aws::Glacier
  class MultipartUpload

    extend Aws::Deprecations

    # @overload def initialize(account_id, vault_name, id, options = {})
    #   @param [String] account_id
    #   @param [String] vault_name
    #   @param [String] id
    #   @option options [Client] :client
    # @overload def initialize(options = {})
    #   @option options [required, String] :account_id
    #   @option options [required, String] :vault_name
    #   @option options [required, String] :id
    #   @option options [Client] :client
    def initialize(*args)
      options = Hash === args.last ? args.pop.dup : {}
      @account_id = extract_account_id(args, options)
      @vault_name = extract_vault_name(args, options)
      @id = extract_id(args, options)
      @data = options.delete(:data)
      @client = options.delete(:client) || Client.new(options)
    end

    # @!group Read-Only Attributes

    # @return [String]
    def account_id
      @account_id
    end

    # @return [String]
    def vault_name
      @vault_name
    end

    # @return [String]
    def id
      @id
    end
    alias :multipart_upload_id :id

    # The Amazon Resource Name (ARN) of the vault that contains the archive.
    # @return [String]
    def vault_arn
      data[:vault_arn]
    end

    # The description of the archive that was specified in the Initiate
    # Multipart Upload request.
    # @return [String]
    def archive_description
      data[:archive_description]
    end

    # The part size, in bytes, specified in the Initiate Multipart Upload
    # request. This is the size of all the parts in the upload except the
    # last part, which may be smaller than this size.
    # @return [Integer]
    def part_size_in_bytes
      data[:part_size_in_bytes]
    end

    # The UTC time at which the multipart upload was initiated.
    # @return [Time]
    def creation_date
      data[:creation_date]
    end

    # @!endgroup

    # @return [Client]
    def client
      @client
    end

    # @raise [NotImplementedError]
    # @api private
    def load
      msg = "#load is not implemented, data only available via enumeration"
      raise NotImplementedError, msg
    end
    alias :reload :load

    # @raise [NotImplementedError] Raises when {#data_loaded?} is `false`.
    # @return [Types::UploadListElement]
    #   Returns the data for this {MultipartUpload}.
    def data
      load unless @data
      @data
    end

    # @return [Boolean]
    #   Returns `true` if this resource is loaded.  Accessing attributes or
    #   {#data} on an unloaded resource will trigger a call to {#load}.
    def data_loaded?
      !!@data
    end

    # @deprecated Use [Aws::Glacier::Client] #wait_until instead
    #
    # Waiter polls an API operation until a resource enters a desired
    # state.
    #
    # @note The waiting operation is performed on a copy. The original resource remains unchanged
    #
    # ## Basic Usage
    #
    # Waiter will polls until it is successful, it fails by
    # entering a terminal state, or until a maximum number of attempts
    # are made.
    #
    #     # polls in a loop until condition is true
    #     resource.wait_until(options) {|resource| condition}
    #
    # ## Example
    #
    #     instance.wait_until(max_attempts:10, delay:5) {|instance| instance.state.name == 'running' }
    #
    # ## Configuration
    #
    # You can configure the maximum number of polling attempts, and the
    # delay (in seconds) between each polling attempt. The waiting condition is set
    # by passing a block to {#wait_until}:
    #
    #     # poll for ~25 seconds
    #     resource.wait_until(max_attempts:5,delay:5) {|resource|...}
    #
    # ## Callbacks
    #
    # You can be notified before each polling attempt and before each
    # delay. If you throw `:success` or `:failure` from these callbacks,
    # it will terminate the waiter.
    #
    #     started_at = Time.now
    #     # poll for 1 hour, instead of a number of attempts
    #     proc = Proc.new do |attempts, response|
    #       throw :failure if Time.now - started_at > 3600
    #     end
    #
    #       # disable max attempts
    #     instance.wait_until(before_wait:proc, max_attempts:nil) {...}
    #
    # ## Handling Errors
    #
    # When a waiter is successful, it returns the Resource. When a waiter
    # fails, it raises an error.
    #
    #     begin
    #       resource.wait_until(...)
    #     rescue Aws::Waiters::Errors::WaiterFailed
    #       # resource did not enter the desired state in time
    #     end
    #
    #
    # @yield param [Resource] resource to be used in the waiting condition
    #
    # @raise [Aws::Waiters::Errors::FailureStateError] Raised when the waiter terminates
    #   because the waiter has entered a state that it will not transition
    #   out of, preventing success.
    #
    #   yet successful.
    #
    # @raise [Aws::Waiters::Errors::UnexpectedError] Raised when an error is encountered
    #   while polling for a resource that is not expected.
    #
    # @raise [NotImplementedError] Raised when the resource does not
    #
    # @option options [Integer] :max_attempts (10) Maximum number of
    # attempts
    # @option options [Integer] :delay (10) Delay between each
    # attempt in seconds
    # @option options [Proc] :before_attempt (nil) Callback
    # invoked before each attempt
    # @option options [Proc] :before_wait (nil) Callback
    # invoked before each wait
    # @return [Resource] if the waiter was successful
    def wait_until(options = {}, &block)
      self_copy = self.dup
      attempts = 0
      options[:max_attempts] = 10 unless options.key?(:max_attempts)
      options[:delay] ||= 10
      options[:poller] = Proc.new do
        attempts += 1
        if block.call(self_copy)
          [:success, self_copy]
        else
          self_copy.reload unless attempts == options[:max_attempts]
          :retry
        end
      end
      Aws::Waiters::Waiter.new(options).wait({})
    end

    # @!group Actions

    # @example Request syntax with placeholder values
    #
    #   multipart_upload.abort()
    # @param [Hash] options ({})
    # @return [EmptyStructure]
    def abort(options = {})
      options = options.merge(
        account_id: @account_id,
        vault_name: @vault_name,
        upload_id: @id
      )
      resp = @client.abort_multipart_upload(options)
      resp.data
    end

    # @example Request syntax with placeholder values
    #
    #   multipart_upload.complete({
    #     archive_size: 1,
    #     checksum: "string",
    #   })
    # @param [Hash] options ({})
    # @option options [Integer] :archive_size
    #   The total size, in bytes, of the entire archive. This value should be
    #   the sum of all the sizes of the individual parts that you uploaded.
    # @option options [String] :checksum
    #   The SHA256 tree hash of the entire archive. It is the tree hash of
    #   SHA256 tree hash of the individual parts. If the value you specify in
    #   the request does not match the SHA256 tree hash of the final assembled
    #   archive as computed by Amazon Glacier, Amazon Glacier returns an error
    #   and the request fails.
    # @return [Types::ArchiveCreationOutput]
    def complete(options = {})
      options = options.merge(
        account_id: @account_id,
        vault_name: @vault_name,
        upload_id: @id
      )
      resp = @client.complete_multipart_upload(options)
      resp.data
    end

    # @example Request syntax with placeholder values
    #
    #   multipart_upload.parts({
    #     marker: "string",
    #     limit: 1,
    #   })
    # @param [Hash] options ({})
    # @option options [String] :marker
    #   An opaque string used for pagination. This value specifies the part at
    #   which the listing of parts should begin. Get the marker value from the
    #   response of a previous List Parts response. You need only include the
    #   marker if you are continuing the pagination of results started in a
    #   previous List Parts request.
    # @option options [Integer] :limit
    #   The maximum number of parts to be returned. The default limit is 50.
    #   The number of parts returned might be fewer than the specified limit,
    #   but the number of returned parts never exceeds the limit.
    # @return [Types::ListPartsOutput]
    def parts(options = {})
      options = options.merge(
        account_id: @account_id,
        vault_name: @vault_name,
        upload_id: @id
      )
      resp = @client.list_parts(options)
      resp.data
    end

    # @example Request syntax with placeholder values
    #
    #   multipart_upload.upload_part({
    #     checksum: "string",
    #     range: "string",
    #     body: "data",
    #   })
    # @param [Hash] options ({})
    # @option options [String] :checksum
    #   The SHA256 tree hash of the data being uploaded.
    # @option options [String] :range
    #   Identifies the range of bytes in the assembled archive that will be
    #   uploaded in this part. Amazon Glacier uses this information to
    #   assemble the archive in the proper sequence. The format of this header
    #   follows RFC 2616. An example header is Content-Range:bytes
    #   0-4194303/*.
    # @option options [String, IO] :body
    #   The data to upload.
    # @return [Types::UploadMultipartPartOutput]
    def upload_part(options = {})
      options = options.merge(
        account_id: @account_id,
        vault_name: @vault_name,
        upload_id: @id
      )
      resp = @client.upload_multipart_part(options)
      resp.data
    end

    # @!group Associations

    # @return [Vault]
    def vault
      Vault.new(
        account_id: @account_id,
        name: @vault_name,
        client: @client
      )
    end

    # @deprecated
    # @api private
    def identifiers
      {
        account_id: @account_id,
        vault_name: @vault_name,
        id: @id
      }
    end
    deprecated(:identifiers)

    private

    def extract_account_id(args, options)
      value = args[0] || options.delete(:account_id)
      case value
      when String then value
      when nil then raise ArgumentError, "missing required option :account_id"
      else
        msg = "expected :account_id to be a String, got #{value.class}"
        raise ArgumentError, msg
      end
    end

    def extract_vault_name(args, options)
      value = args[1] || options.delete(:vault_name)
      case value
      when String then value
      when nil then raise ArgumentError, "missing required option :vault_name"
      else
        msg = "expected :vault_name to be a String, got #{value.class}"
        raise ArgumentError, msg
      end
    end

    def extract_id(args, options)
      value = args[2] || options.delete(:id)
      case value
      when String then value
      when nil then raise ArgumentError, "missing required option :id"
      else
        msg = "expected :id to be a String, got #{value.class}"
        raise ArgumentError, msg
      end
    end

    class Collection < Aws::Resources::Collection; end
  end
end