text:
namespace policy {

DeviceLocalAccountExtensionTracker::DeviceLocalAccountExtensionTracker(
    const DeviceLocalAccount& account,
    CloudPolicyStore* store,
    SchemaRegistry* schema_registry)
    : store_(store),
      schema_registry_(schema_registry) {
  if (account.type == DeviceLocalAccount::TYPE_KIOSK_APP) {
    // This is easy: Just add a component for the app id.
    PolicyNamespace ns(POLICY_DOMAIN_EXTENSIONS, account.kiosk_app_id);
    schema_registry_->RegisterComponent(ns, Schema());
  } else if (account.type == DeviceLocalAccount::TYPE_PUBLIC_SESSION) {
    // For public sessions, track the value of the ExtensionInstallForcelist
    // policy.
    store_->AddObserver(this);
    UpdateFromStore();
  } else {
    NOTREACHED();
  }

  schema_registry_->SetReady(POLICY_DOMAIN_EXTENSIONS);
}

DeviceLocalAccountExtensionTracker::~DeviceLocalAccountExtensionTracker() {
  store_->RemoveObserver(this);
}

void DeviceLocalAccountExtensionTracker::OnStoreLoaded(
    CloudPolicyStore* store) {
  UpdateFromStore();
}

void DeviceLocalAccountExtensionTracker::OnStoreError(CloudPolicyStore* store) {
  UpdateFromStore();
}

void DeviceLocalAccountExtensionTracker::UpdateFromStore() {
  const policy::PolicyMap& policy_map = store_->policy_map();

  // TODO(binjin): Use two policy handlers here after
  // ExtensionManagementPolicyHandler is introduced.
  extensions::ExtensionInstallForcelistPolicyHandler policy_handler;
  if (!policy_handler.CheckPolicySettings(policy_map, NULL))
    return;

  PrefValueMap pref_value_map;
  policy_handler.ApplyPolicySettings(policy_map, &pref_value_map);

  const base::Value* value = NULL;
  const base::DictionaryValue* dict = NULL;
  if (!pref_value_map.GetValue(extensions::pref_names::kInstallForceList,
                               &value) ||
      !value->GetAsDictionary(&dict)) {
    return;
  }

  for (base::DictionaryValue::Iterator it(*dict); !it.IsAtEnd(); it.Advance()) {
    PolicyNamespace ns(POLICY_DOMAIN_EXTENSIONS, it.key());
    schema_registry_->RegisterComponent(ns, Schema());
  }

  // Removing an extension from a public session at runtime can happen but is
  // a rare event. In that case we leave the extension ID in the SchemaRegistry,
  // and it will be purged on the next restart.
}

}  // namespace policy


text:
<?xml version="1.0"?>
<package>
  <name>husky_viz</name>
  <version>0.6.4</version>
  <description>Visualization configuration for Clearpath Husky</description>

  <author email="rgariepy@clearpathrobotics.com">Ryan Gariepy</author>
  <author email="mpurvis@clearpathrobotics.com">Mike Purvis</author>

  <maintainer email="tbaltovski@clearpathrobotics.com">Tony Baltovski</maintainer>

  <license>BSD</license>

  <url type="website">http://ros.org/wiki/husky_viz</url>
  <url type="bugtracker">https://github.com/husky/husky_desktop/issues</url>
  <url type="repository">https://github.com/husky/husky_desktop</url>

  <buildtool_depend>catkin</buildtool_depend>

  <build_depend>roslaunch</build_depend>

  <run_depend>husky_description</run_depend>
  <run_depend>joint_state_publisher</run_depend>
  <run_depend>robot_state_publisher</run_depend>
  <run_depend>joint_state_publisher_gui</run_depend>
  <run_depend>rviz</run_depend>
  <run_depend>rviz_imu_plugin</run_depend>
  <run_depend>rqt_gui</run_depend>
  <run_depend>rqt_console</run_depend>
  <run_depend>rqt_robot_monitor</run_depend>

  <export>
  </export>
</package>

redpajama_set_name: RedPajamaGithub


text:
package domain

import java.util.Date

case class Item(id: String,
                jobId: Long,
                status: String,
                createdAt: Date,
                updatedAt: Option[Date],
                attributes: Map[String, String])


text:
package org.apache.oltu.oauth2.as.request;

import javax.servlet.http.HttpServletRequest;

import org.apache.oltu.oauth2.as.validator.PasswordValidator;
import org.apache.oltu.oauth2.as.validator.UnauthenticatedAuthorizationCodeValidator;
import org.apache.oltu.oauth2.as.validator.UnauthenticatedPasswordValidator;
import org.apache.oltu.oauth2.as.validator.UnauthenticatedRefreshTokenValidator;
import org.apache.oltu.oauth2.common.OAuth;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.types.GrantType;
import org.apache.oltu.oauth2.common.utils.OAuthUtils;
import org.apache.oltu.oauth2.common.validators.OAuthValidator;

/**
 * The Unauthenticated OAuth Authorization Server class that validates whether a given HttpServletRequest is a valid
 * OAuth Token request.
 *

 * This class accepts requests that are NOT authenticated, that is requests that do not contain a client_secret.
 *

 * IMPORTANT: The ClientCredentials Grant Type is NOT supported by this class since client authentication is required
 * for this grant type. In order to support the client credentials grant type please use the {@link OAuthTokenRequest}
 * class.
 */
public class OAuthUnauthenticatedTokenRequest extends AbstractOAuthTokenRequest {

    public OAuthUnauthenticatedTokenRequest(HttpServletRequest request) throws OAuthSystemException,
            OAuthProblemException {
        super(request);
    }

    @Override
    protected OAuthValidator<HttpServletRequest> initValidator() throws OAuthProblemException, OAuthSystemException {
        validators.put(GrantType.PASSWORD.toString(), UnauthenticatedPasswordValidator.class);
        validators.put(GrantType.AUTHORIZATION_CODE.toString(), UnauthenticatedAuthorizationCodeValidator.class);
        validators.put(GrantType.REFRESH_TOKEN.toString(), UnauthenticatedRefreshTokenValidator.class);
        return super.initValidator();
    }
}


text:
    #define VT_SLASH L'\\'
    #define VT_SLASH_STR L"\\"
#else
    #define VT_SLASH L'/'
    #define VT_SLASH_STR L"/"
#endif

#ifdef COMPILER_MSVC
    #define VT_SLASH_UTF8 '\\'
    #define VT_SLASH_STR_UTF8 "\\"
#else
    #define VT_SLASH_UTF8 '/'
    #define VT_SLASH_STR_UTF8 "/"
#endif

namespace VT
{
    class Path
    {
    };

    // suitable only for reading small text files into a buffer
    bool read_file(const std::wstring& path, std::string& buffer);
    bool read_file(const std::wstring& path, std::vector<char>& buffer);
    bool read_file(const std::wstring& path, std::wstring& buffer);
    bool read_file(const std::wstring& path, std::vector<wchar_t>& buffer);

    std::wstring file_name(const std::wstring& full_path);
    std::wstring folder_name(const std::wstring& filename, bool trimTrailingSlash = false);

    std::wstring full_path(const std::wstring& filename);
    bool file_exists(const std::wstring& filename);
    bool ensure_path_exist(const std::wstring& path);
    bool delete_file_folder(std::wstring path);
    bool move_file(const std::wstring& filename, const std::wstring& newFile);

    size_t list_files(const std::wstring& directory, const std::wstring& mask, std::list<std::wstring>& result);
    size_t list_folders(const std::wstring& directory, const std::wstring& mask, std::list<std::wstring>& result);
    size_t list_files_folders(const std::wstring& directory, const std::wstring& mask, std::list<std::wstring>& result);

    // Generic file data operations
    class File
    {
    public:
        enum Flags
        {
            None = 0,
            ReadOnly,       // File will be opened in read only mode
            Sequential,     // Optimize for sequential access if possible
        };

    public:
        File();
        ~File();

        bool Open(const std::wstring& filename, Flags flags = None);
        bool Create(const std::wstring& filename, Flags flags = None);
        void Close();

        bool Read(void* data, uint32_t size, int64_t pos = -1);
        bool Write(const void* data, uint32_t size, int64_t pos = -1);

        int64_t ReadAll(std::unique_ptr<uint8_t[]>& data);

        int64_t size();

    private:
        File(const File&);
        File& operator=(const File&);

        struct Impl;
        Impl* _pImpl;
    };
}


text:
package service

import (
	"net"
	"os"
	"sync"

	"github.com/op/go-logging"
)

var log = logging.MustGetLogger("mortal_service")

// SetLogger allows setting a custom go-logging instance
func SetLogger(logger *logging.Logger) {
	log = logger
}

// MortalService can be killed at any time.
type MortalService struct {
	network            string
	address            string
	connectionCallback func(net.Conn) error

	conns     []net.Conn
	stopping  bool
	listener  net.Listener
	waitGroup *sync.WaitGroup
}

// NewMortalService creates a new MortalService
func NewMortalService(network, address string, connectionCallback func(net.Conn) error) *MortalService {
	l := MortalService{
		network:            network,
		address:            address,
		connectionCallback: connectionCallback,

		conns:     make([]net.Conn, 0, 10),
		stopping:  false,
		waitGroup: &sync.WaitGroup{},
	}
	return &l
}

// Start the MortalService
func (l *MortalService) Start() error {
	var err error
	log.Debugf("starting listener service %s:%s", l.network, l.address)
	if l.network == "unix" {
		log.Debugf("removing unix socket file %s", l.address)
		os.Remove(l.address)
	}
	l.listener, err = net.Listen(l.network, l.address)
	if err != nil {
		return err
	}
	l.waitGroup.Add(1)
	go l.acceptLoop()
	return nil
}

// Stop will kill our listener and all it's connections
func (l *MortalService) Stop() {
	log.Debugf("stopping listener service %s:%s", l.network, l.address)
	l.stopping = true
	if l.listener != nil {
		l.listener.Close()
	}
	l.waitGroup.Wait()
	if l.network == "unix" {
		log.Debugf("removing unix socket file %s", l.address)
		os.Remove(l.address)
	}
}

func (l *MortalService) acceptLoop() {
	defer l.waitGroup.Done()
	defer func() {
		log.Debugf("acceptLoop stopping for listener service %s:%s", l.network, l.address)
		for i, conn := range l.conns {
			if conn != nil {
				log.Debugf("Closing connection #%d", i)
				conn.Close()
			}
		}
	}()
	defer l.listener.Close()

	for {
		conn, err := l.listener.Accept()
		if err != nil {
			log.Errorf("MortalService connection accept failure: %s\n", err)
			if l.stopping {
				return
			} else {
				continue
			}
		}

		l.conns = append(l.conns, conn)
		go l.handleConnection(conn, len(l.conns)-1)
	}
}

func (l *MortalService) handleConnection(conn net.Conn, id int) error {
	defer func() {
		log.Debugf("Closing connection #%d", id)
		conn.Close()
		l.conns[id] = nil
	}()

	log.Debugf("Starting connection #%d", id)
	if err := l.connectionCallback(conn); err != nil {
		log.Debugf(err.Error())
		return err
	}
	return nil
}


text:
using DTORepository.Common;
using DTORepository.Models;
using DTORepositoryTest.Samples.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DTORepositoryTest.Samples.Dtos
{
    class BlogWithPostsCreateDto : DtoBase<BloggingContext, Blog, BlogWithPostsCreateDto>
    {
        public int BlogId { get; set; }
        public string Name { get; set; }
        public string Url { get; set; }
        public List<PostDto> Posts { get; set; }
        public List<BlogTagDto> Tags { get; set; }
        protected override ActionFlags AllowedActions => ActionFlags.Create | ActionFlags.Update;
        protected override ISuccessOrErrors<Blog> UpdateDataFromDto(BloggingContext context, Blog entity, Blog oldEntity)
        {
            var dbContext = (BloggingContext) context;
            if (entity.Tags != null && entity.Tags != oldEntity.Tags)
            {
                var toUpdateTagIds = entity.Tags.Select(t => t.Id);
                var toBeDeletedTags = oldEntity.Tags.Where(x => !toUpdateTagIds.Contains(x.Id)).Select(x => dbContext.BlogTags.Find(x.Id));

                dbContext.BlogTags.RemoveRange(toBeDeletedTags);
            }
            return base.UpdateDataFromDto(context, entity, oldEntity);
        }
        protected override Blog SetupRestOfEntity(BloggingContext context, Blog blog)
        {
            blog.CreatedDate = DateTime.MaxValue;
            return blog;
        }
    }
}


text:
package it.unibz.krdb.sql.api;

import it.unibz.krdb.obda.parser.AggregationVisitor;
import it.unibz.krdb.obda.parser.AliasMapVisitor;
import it.unibz.krdb.obda.parser.ColumnsVisitor;
import it.unibz.krdb.obda.parser.JoinConditionVisitor;
import it.unibz.krdb.obda.parser.ProjectionVisitor;
import it.unibz.krdb.obda.parser.WhereClauseVisitor;
import it.unibz.krdb.obda.parser.SubSelectVisitor;
import it.unibz.krdb.obda.parser.TableNameVisitor;

import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.statement.select.Select;

/**
 * A structure to store the parsed SQL query string. It returns the information
 * about the query using the visitor classes
 */
public class ParsedSQLQuery implements Serializable {

	private static final long serialVersionUID = -4590590361733833782L;

	private String query;
	private Statement stm;
	boolean deepParsing = false; // used to remove all quotes from the query

	private Select selectQuery; // the parsed query

	public static Pattern pQuotes = Pattern.compile("[\"`\\[][^\\.]*[\"`\\]]");
	private List<RelationJSQL> tables;
	private List<SelectJSQL> subSelects;
	private Map<String, String> aliasMap;
	private List<Expression> joins;
	private SelectionJSQL whereClause;
	private ProjectionJSQL projection;
	private AggregationJSQL groupByClause;

	/**
	 * Parse a query given as a String
	 *
	 * @param queryString
	 *            the SQL query to parse
	 * @param deepParsing
	 *            if true removes quotes from columns and generate exceptions
	 *            for unsupported query in the mapping otherwise, keeps the
	 *            quotes from the columns, and support all the SQLs which can be
	 *            parsed by JSQLParser
	 * @throws JSQLParserException
	 */

	public ParsedSQLQuery(String queryString, boolean deepParsing)
			throws JSQLParserException {

		/**
		 * pattern used to remove quotes from the beginning and the end of
		 * columns
		 */

		query = queryString;

		this.deepParsing = deepParsing;

		stm = CCJSqlParserUtil.parse(query);

		if (stm instanceof Select) {
			selectQuery = (Select) stm;

			// getting the values we also eliminate or handle the quotes if
			// deepParsing is set to true
			if (deepParsing) {
				tables = getTables();
				whereClause = getWhereClause();
				projection = getProjection();
				joins = getJoinConditions();
				aliasMap = getAliasMap();
				groupByClause = getGroupByClause();
			}

		}
		// catch exception about wrong inserted columns
		else
			throw new JSQLParserException(
					"The inserted query is not a SELECT statement");

	}

	/**
	 * The query is not parsed again
	 *
	 * @param statement
	 *            we pass already a parsed statement
	 * @param deepParsing
	 *            if true removes quotes from columns and generate exceptions
	 *            for unsupported query in the mapping
	 * @throws JSQLParserException
	 */
	public ParsedSQLQuery(Statement statement, boolean deepParsing)
			throws JSQLParserException {

		pQuotes = Pattern.compile("[\"`\\[].*[\"`\\]]");

		query = statement.toString();

		stm = statement;

		this.deepParsing = deepParsing;

		if (stm instanceof Select) {
			selectQuery = (Select) stm;

			/**
			 * Getting the values we also eliminate or handle the quotes if
			 * deepParsing is set to true and we throw errors for unsupported values
			 */

			if (deepParsing) {
				tables = getTables();
				whereClause = getWhereClause();
				projection = getProjection();
				joins = getJoinConditions();
				aliasMap = getAliasMap();
				groupByClause = getGroupByClause();
			}

		}
		// catch exception about wrong inserted columns
		else
			throw new JSQLParserException(
					"The inserted query is not a SELECT statement");

	}

	/**
	 * Unquote the query and throw errors for unsupported values
	 *
	 * @throws JSQLParserException
	 */
	public void unquote() throws JSQLParserException {
		this.deepParsing = true;

		tables = getTables();
		whereClause = getWhereClause();
		projection = getProjection();
		joins = getJoinConditions();
		aliasMap = getAliasMap();
		groupByClause = getGroupByClause();

	}

	@Override
	public String toString() {
		return selectQuery.toString();
	}

	/**
	 * Returns all the tables in this query.
	 */
	public List<RelationJSQL> getTables() throws JSQLParserException {

		if (tables == null) {
			TableNameVisitor visitor = new TableNameVisitor();
			tables = visitor.getTables(selectQuery, deepParsing);
		}
		return tables;
	}

	/**
	 * Returns all the subSelect in this query .
	 */
	public List<SelectJSQL> getSubSelects() {

		if (subSelects == null) {
			SubSelectVisitor visitor = new SubSelectVisitor();
			subSelects = visitor.getSubSelects(selectQuery, deepParsing);
		}
		return subSelects;
	}

	/**
	 * Get the string construction of alias name.
	 */
	public Map<String, String> getAliasMap() {
		if (aliasMap == null) {
			AliasMapVisitor visitor = new AliasMapVisitor();
			aliasMap = visitor.getAliasMap(selectQuery, deepParsing);
		}
		return aliasMap;
	}

	/**
	 * Get the string construction of the join condition. The string has the
	 * format of "VAR1=VAR2".
	 */
	public List<Expression> getJoinConditions() throws JSQLParserException {
		if (joins == null) {
			JoinConditionVisitor visitor = new JoinConditionVisitor();
			joins = visitor.getJoinConditions(selectQuery, deepParsing);
		}
		return joins;
	}

	/**
	 * Get the object construction for the WHERE clause.
	 *
	 * @throws JSQLParserException
	 */
	public SelectionJSQL getWhereClause() throws JSQLParserException {
		if (whereClause == null) {
			WhereClauseVisitor visitor = new WhereClauseVisitor();
			whereClause = visitor.getWhereClause(selectQuery, deepParsing);
		}
		return whereClause;
	}

	/**
	 * Get the object construction for the SELECT clause.
	 *
	 * @throws JSQLParserException
	 */
	public ProjectionJSQL getProjection() throws JSQLParserException {
		if (projection == null) {
			ProjectionVisitor visitor = new ProjectionVisitor();
			projection = visitor.getProjection(selectQuery, deepParsing);
		}
		return projection;

	}

	/**
	 * Get the list of columns
	 *
	 * @return
	 */
	public List<String> getColumns() {
		ColumnsVisitor visitor = new ColumnsVisitor();

		return visitor.getColumns(selectQuery);
	}

	/**
	 * Set the object construction for the SELECT clause, modifying the current
	 * statement
	 *
	 * @param projection
	 */

	public void setProjection(ProjectionJSQL projection) {
		ProjectionVisitor visitor = new ProjectionVisitor();
		visitor.setProjection(selectQuery, projection);
		this.projection = projection;
	}

	/**
	 * Set the object construction for the WHERE clause, modifying the current
	 * statement
	 *
	 * @param whereClause
	 */

	public void setWhereClause(SelectionJSQL whereClause) {
		WhereClauseVisitor sel = new WhereClauseVisitor();
		sel.setWhereClause(selectQuery, whereClause);
		this.whereClause = whereClause;
	}

	/**
	 * Constructs the GROUP BY statement based on the Aggregation object.
	 */
	public AggregationJSQL getGroupByClause() {
		if (groupByClause == null) {
			AggregationVisitor agg = new AggregationVisitor();
			groupByClause = agg.getAggregation(selectQuery, deepParsing);
		}

		return groupByClause;
	}

	public Statement getStatement() {
		return selectQuery;
	}

}


text:
package com.pushtorefresh.storio3.contentresolver.impl;

import android.content.ContentResolver;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import com.pushtorefresh.storio3.Interceptor;
import com.pushtorefresh.storio3.TypeMappingFinder;
import com.pushtorefresh.storio3.contentresolver.BuildConfig;
import com.pushtorefresh.storio3.contentresolver.ContentResolverTypeMapping;
import com.pushtorefresh.storio3.contentresolver.StorIOContentResolver;
import com.pushtorefresh.storio3.contentresolver.operations.delete.DeleteResolver;
import com.pushtorefresh.storio3.contentresolver.operations.get.GetResolver;
import com.pushtorefresh.storio3.contentresolver.operations.put.PutResolver;
import com.pushtorefresh.storio3.contentresolver.queries.Query;
import com.pushtorefresh.storio3.internal.TypeMappingFinderImpl;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.util.ReflectionHelpers;

import java.lang.reflect.Field;
import java.util.Collections;

import io.reactivex.Scheduler;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

import static io.reactivex.BackpressureStrategy.LATEST;
import static org.assertj.core.api.Java6Assertions.assertThat;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

@RunWith(RobolectricTestRunner.class)
public class DefaultStorIOContentResolverTest {

    @Rule
    public ExpectedException expectedException = ExpectedException.none();

    @Test
    public void nullContentResolver() {
        DefaultStorIOContentResolver.Builder builder = DefaultStorIOContentResolver.builder();

        expectedException.expect(NullPointerException.class);
        expectedException.expectMessage("Please specify content resolver");
        expectedException.expectCause(nullValue(Throwable.class));

        //noinspection ConstantConditions
        builder.contentResolver(null);
    }

    @Test
    public void addTypeMappingNullType() {
        DefaultStorIOContentResolver.CompleteBuilder builder = DefaultStorIOContentResolver.builder()
                .contentResolver(mock(ContentResolver.class));

        expectedException.expect(NullPointerException.class);
        expectedException.expectMessage("Please specify type");
        expectedException.expectCause(nullValue(Throwable.class));

        //noinspection ConstantConditions,unchecked
        builder.addTypeMapping(null, ContentResolverTypeMapping.builder()
                        .putResolver(mock(PutResolver.class))
                        .getResolver(mock(GetResolver.class))
                        .deleteResolver(mock(DeleteResolver.class))
                        .build());
    }

    @Test
    public void addTypeMappingNullMapping() {
        DefaultStorIOContentResolver.CompleteBuilder builder = DefaultStorIOContentResolver.builder()
                .contentResolver(mock(ContentResolver.class));

        expectedException.expect(NullPointerException.class);
        expectedException.expectMessage("Please specify type mapping");
        expectedException.expectCause(nullValue(Throwable.class));

        //noinspection ConstantConditions
        builder.addTypeMapping(Object.class, null);
    }

    @Test
    public void nullTypeMappingFinder() {
        DefaultStorIOContentResolver.CompleteBuilder builder = DefaultStorIOContentResolver.builder()
                .contentResolver(mock(ContentResolver.class));

        expectedException.expect(NullPointerException.class);
        expectedException.expectMessage("Please specify typeMappingFinder");
        expectedException.expectCause(nullValue(Throwable.class));

        //noinspection ConstantConditions
        builder.typeMappingFinder(null);
    }

    @Test
    public void shouldUseSpecifiedTypeMappingFinder() throws NoSuchFieldException, IllegalAccessException {
        TypeMappingFinder typeMappingFinder = mock(TypeMappingFinder.class);
        DefaultStorIOContentResolver storIOContentResolver = DefaultStorIOContentResolver.builder()
                .contentResolver(mock(ContentResolver.class))
                .typeMappingFinder(typeMappingFinder)
                .build();

        assertThat(getTypeMappingFinder(storIOContentResolver)).isEqualTo(typeMappingFinder);
    }

    @Test
    public void typeMappingShouldWorkWithoutSpecifiedTypeMappingFinder() {
        //noinspection unchecked
        ContentResolverTypeMapping<ClassEntity> typeMapping = ContentResolverTypeMapping.builder()
                .putResolver(mock(PutResolver.class))
                .getResolver(mock(GetResolver.class))
                .deleteResolver(mock(DeleteResolver.class))
                .build();

        StorIOContentResolver storIOContentResolver = DefaultStorIOContentResolver.builder()
                .contentResolver(mock(ContentResolver.class))
                .addTypeMapping(ClassEntity.class, typeMapping)
                .build();

        assertThat(storIOContentResolver.lowLevel().typeMapping(ClassEntity.class)).isEqualTo(typeMapping);
    }

    @Test
    public void typeMappingShouldWorkWithSpecifiedTypeMappingFinder() {
        TypeMappingFinder typeMappingFinder = new TypeMappingFinderImpl();

        //noinspection unchecked
        ContentResolverTypeMapping<ClassEntity> typeMapping = ContentResolverTypeMapping.builder()
                .putResolver(mock(PutResolver.class))
                .getResolver(mock(GetResolver.class))
                .deleteResolver(mock(DeleteResolver.class))
                .build();

        StorIOContentResolver storIOContentResolver = DefaultStorIOContentResolver.builder()
                .contentResolver(mock(ContentResolver.class))
                .typeMappingFinder(typeMappingFinder)
                .addTypeMapping(ClassEntity.class, typeMapping)
                .build();

        assertThat(storIOContentResolver.lowLevel().typeMapping(ClassEntity.class)).isEqualTo(typeMapping);
    }

    @Test
    public void typeMappingShouldWorkForMultipleTypes() {
        class AnotherEntity {
        }

        TypeMappingFinder typeMappingFinder = new TypeMappingFinderImpl();

        //noinspection unchecked
        ContentResolverTypeMapping<ClassEntity> typeMapping = ContentResolverTypeMapping.builder()
                .putResolver(mock(PutResolver.class))
                .getResolver(mock(GetResolver.class))
                .deleteResolver(mock(DeleteResolver.class))
                .build();

        //noinspection unchecked
        ContentResolverTypeMapping<AnotherEntity> anotherMapping = ContentResolverTypeMapping.builder()
                .putResolver(mock(PutResolver.class))
                .getResolver(mock(GetResolver.class))
                .deleteResolver(mock(DeleteResolver.class))
                .build();

        StorIOContentResolver storIOContentResolver = DefaultStorIOContentResolver.builder()
                .contentResolver(mock(ContentResolver.class))
                .typeMappingFinder(typeMappingFinder)
                .addTypeMapping(ClassEntity.class, typeMapping)
                .addTypeMapping(AnotherEntity.class, anotherMapping)
                .build();

        assertThat(storIOContentResolver.lowLevel().typeMapping(ClassEntity.class)).isEqualTo(typeMapping);
        assertThat(storIOContentResolver.lowLevel().typeMapping(AnotherEntity.class)).isEqualTo(anotherMapping);
    }

    @Test
    public void shouldThrowExceptionIfContentResolverReturnsNull() {
        ContentResolver contentResolver = mock(ContentResolver.class);

        StorIOContentResolver storIOContentResolver = DefaultStorIOContentResolver.builder()
                .contentResolver(contentResolver)
                .build();

        Query query = Query.builder()
                .uri(mock(Uri.class))
                .build();

        when(contentResolver
                .query(any(Uri.class), any(String[].class), anyString(), any(String[].class), anyString()))
                .thenReturn(null); // Notice, we return null instead of Cursor

        try {
            storIOContentResolver
                    .lowLevel()
                    .query(query);
        } catch (IllegalStateException expected) {
            assertThat(expected).hasMessage("Cursor returned by content provider is null");
        }
    }

    @Test
    public void shouldReturnSameContentResolver() {
        ContentResolver contentResolver = mock(ContentResolver.class);

        StorIOContentResolver storIOContentResolver = DefaultStorIOContentResolver.builder()
                .contentResolver(contentResolver)
                .build();

        assertThat(storIOContentResolver.lowLevel().contentResolver()).isSameAs(contentResolver);
    }

    @Test
    public void deprecatedInternalImplShouldReturnSentToConstructorTypeMapping() throws NoSuchFieldException, IllegalAccessException {
        ContentResolver contentResolver = mock(ContentResolver.class);
        TypeMappingFinder typeMappingFinder = mock(TypeMappingFinder.class);

        TestDefaultStorIOContentResolver storIOContentResolver = new TestDefaultStorIOContentResolver(
                contentResolver,
                mock(Handler.class),
                typeMappingFinder
        );

        assertThat(storIOContentResolver.typeMappingFinder()).isSameAs(typeMappingFinder);
    }

    static class ClassEntity {
    }

    @Nullable
    private static TypeMappingFinder getTypeMappingFinder(@NonNull DefaultStorIOContentResolver storIOContentResolver)
            throws NoSuchFieldException, IllegalAccessException {

        Field field = DefaultStorIOContentResolver.LowLevelImpl.class.getDeclaredField("typeMappingFinder");
        field.setAccessible(true);
        return (TypeMappingFinder) field.get(storIOContentResolver.lowLevel());
    }

    class TestDefaultStorIOContentResolver extends DefaultStorIOContentResolver {

        private final LowLevel lowLevel;

        TestDefaultStorIOContentResolver(
                @NonNull ContentResolver contentResolver,
                @NonNull Handler contentObserverHandler,
                @NonNull TypeMappingFinder typeMappingFinder
        ) {
            super(contentResolver, contentObserverHandler, typeMappingFinder, null, Collections.<Interceptor>emptyList());
            lowLevel = new LowLevelImpl(typeMappingFinder);
        }

        @Nullable
        TypeMappingFinder typeMappingFinder() throws NoSuchFieldException, IllegalAccessException {
            Field field = DefaultStorIOContentResolver.LowLevelImpl.class.getDeclaredField("typeMappingFinder");
            field.setAccessible(true);
            return (TypeMappingFinder) field.get(lowLevel);
        }
    }

    @Test
    public void defaultSchedulerReturnsIOSchedulerIfNotSpecified() {
        StorIOContentResolver storIOContentResolver = DefaultStorIOContentResolver.builder()
                .contentResolver(mock(ContentResolver.class))
                .build();

        assertThat(storIOContentResolver.defaultRxScheduler()).isSameAs(Schedulers.io());
    }

    @Test
    public void defaultRxSchedulerReturnsSpecifiedScheduler() {
        Scheduler scheduler = mock(Scheduler.class);
        StorIOContentResolver storIOContentResolver = DefaultStorIOContentResolver.builder()
                .contentResolver(mock(ContentResolver.class))
                .defaultRxScheduler(scheduler)
                .build();

        assertThat(storIOContentResolver.defaultRxScheduler()).isSameAs(scheduler);
    }

    @Test
    public void defaultRxSchedulerReturnsNullIfSpecifiedSchedulerNull() {
        StorIOContentResolver storIOContentResolver = DefaultStorIOContentResolver.builder()
                .contentResolver(mock(ContentResolver.class))
                .defaultRxScheduler(null)
                .build();

        assertThat(storIOContentResolver.defaultRxScheduler()).isNull();
    }

    @Test
    public void shouldUseCustomHandlerForContentObservers() {
        ContentResolver contentResolver = mock(ContentResolver.class);
        ArgumentCaptor<ContentObserver> observerArgumentCaptor = ArgumentCaptor.forClass(ContentObserver.class);
        doNothing().when(contentResolver)
                .registerContentObserver(any(Uri.class), anyBoolean(), observerArgumentCaptor.capture());
        Handler handler = mock(Handler.class);

        StorIOContentResolver storIOContentResolver = DefaultStorIOContentResolver.builder()
                .contentResolver(contentResolver)
                .contentObserverHandler(handler)
                .defaultRxScheduler(null)
                .build();

        Disposable disposable = storIOContentResolver.observeChangesOfUri(mock(Uri.class), LATEST).subscribe();

        assertThat(observerArgumentCaptor.getAllValues()).hasSize(1);
        ContentObserver contentObserver = observerArgumentCaptor.getValue();
        Object actualHandler = ReflectionHelpers.getField(contentObserver, "mHandler");
        assertThat(actualHandler).isEqualTo(handler);

        disposable.dispose();
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta name="generator"

content="HTML Tidy for Mac OS, see www.w3.org" />

<title>XHTML Functional -- INPUT - TYPE=checkbox</title>

The form below contains input elements with a type value of checkbox.

What are your favorite animals?

<form action="http://wetnap/cgi-bin/echo-form.cgi" method="post">

<input type="checkbox" name="pets" value="bird" /> bird

 <input type="checkbox" name="pets" value="cat"

checked="checked" /> cat

 <input type="checkbox" name="pets" value="dog"

checked="checked" /> dog

 <input type="reset" /> <input type="submit" /></form>


text:
class cItemDoorHandler :
	public cItemHandler
{
public:
	cItemDoorHandler(int a_ItemType) :
		cItemHandler(a_ItemType)
	{

	}

	virtual bool IsPlaceable(void) override
	{
		return true;
	}

	virtual bool GetPlacementBlockTypeMeta(
		cWorld * a_World, cPlayer * a_Player,
		int a_BlockX, int a_BlockY, int a_BlockZ, eBlockFace a_BlockFace,
		int a_CursorX, int a_CursorY, int a_CursorZ,
		BLOCKTYPE & a_BlockType, NIBBLETYPE & a_BlockMeta
	) override
	{
		a_BlockType = (m_ItemType == E_ITEM_WOODEN_DOOR) ? E_BLOCK_WOODEN_DOOR : E_BLOCK_IRON_DOOR;
		cChunkInterface ChunkInterface(a_World->GetChunkMap());
		bool Meta = BlockHandler(a_BlockType)->GetPlacementBlockTypeMeta(
			ChunkInterface, a_Player,
			a_BlockX, a_BlockY, a_BlockZ, a_BlockFace,
			a_CursorX, a_CursorY, a_CursorZ,
			a_BlockType, a_BlockMeta
		);
		return Meta;
	}
} ;


text:
namespace agg
{
class vcgen_dash
{
    enum max_dashes_e {
        max_dashes = 32
    };
    enum status_e {
        initial,
        ready,
        polyline,
        stop
    };
public:
    typedef vertex_sequence<vertex_dist, 6> vertex_storage;
    vcgen_dash();
    void remove_all_dashes();
    void add_dash(float dash_len, float gap_len);
    void dash_start(float ds);
    void shorten(float s)
    {
        m_shorten = s;
    }
    double shorten() const
    {
        return m_shorten;
    }
    void remove_all();
    void add_vertex(float x, float y, unsigned cmd);
    void     rewind(unsigned path_id);
    unsigned vertex(float* x, float* y);
private:
    vcgen_dash(const vcgen_dash&);
    const vcgen_dash& operator = (const vcgen_dash&);
    void calc_dash_start(float ds);
    float     m_dashes[max_dashes];
    float		m_total_dash_len;
    unsigned        m_num_dashes;
    float     m_dash_start;
    float     m_shorten;
    float     m_curr_dash_start;
    unsigned        m_curr_dash;
    float     m_curr_rest;
    const vertex_dist* m_v1;
    const vertex_dist* m_v2;
    vertex_storage m_src_vertices;
    unsigned       m_closed;
    status_e       m_status;
    unsigned       m_src_vertex;
};
}
#endif


text:
const QString OptionsDialog::SETTINGS_AUTOLOGIN = "autologin";
const QString OptionsDialog::SETTINGS_USERNAME = "username";
const QString OptionsDialog::SETTINGS_PASSWORD = "password";

OptionsDialog::OptionsDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::OptionsDialog),
    settingsPath(QDir(QStandardPaths::writableLocation(QStandardPaths::DataLocation)).filePath("settings.ini"))
{
    ui->setupUi(this);

    QSettings settings(settingsPath, QSettings::NativeFormat, this);

    autoLogin = settings.value(SETTINGS_AUTOLOGIN, false).toBool();
    username = settings.value(SETTINGS_USERNAME, QString("")).toString();
    password = settings.value(SETTINGS_PASSWORD, QString("")).toString();

    ui->autoLogin->setChecked(autoLogin);
    ui->formGroupBox->setEnabled(autoLogin);

    ui->username->setText(username);
    ui->password->setText(password);

}

OptionsDialog::~OptionsDialog()
{
    delete ui;
}

void OptionsDialog::saveSettings()
{
    autoLogin = ui->autoLogin->isChecked();
    username = ui->username->text();
    password = ui->password->text();

    QSettings settings(settingsPath, QSettings::NativeFormat, this);

    settings.setValue(SETTINGS_AUTOLOGIN, autoLogin);
    settings.setValue(SETTINGS_USERNAME, username);
    settings.setValue(SETTINGS_PASSWORD, password);
}

bool OptionsDialog::isAutoLogin() const
{
    return autoLogin;
}

const QString& OptionsDialog::getPassword() const
{
    return password;
}

const QString& OptionsDialog::getUsername() const
{
    return username;
}


text:
html { background: rgba(0, 0, 0, 0.8); }

.banner { overflow: hidden; display: block; position: relative; margin: 50px 0 0 200px; width: 160px; height: 600px; background: lightgrey; }
.banner .branding { position: absolute; top: auto; right: 0; bottom: 0; left: 0; z-index: 10; height: 54px; color: #333; font-size: 40px; background: white; }
.banner .branding .logo { position: absolute; bottom: 7px; right: 0; -webkit-transform: scale(0.9); transform: scale(0.9); }
.banner .image1, .banner .image2 { position: absolute; z-index: 3; width: 160px; }
.banner .image1 { bottom: 54px; }
.banner .image2 { bottom: 54px; z-index: 4; opacity: 0; }
.banner .overlay { position: absolute; top: 0; right: 0; bottom: auto; left: 0; z-index: 5; height: 300px; background: #e36d57; }
.banner .overlay > .text1, .banner .overlay > .text2, .banner .overlay > .text3 { position: absolute; top: 111px; left: 0; }
.banner .overlay > .text2 { top: 124px; left: 175px; }
.banner .overlay > .text3 { top: -67px; left: 0; }
.banner .button { position: absolute; top: 275px; right: -175px; z-index: 5; -webkit-transform: scale(0.6); transform: scale(0.6); }

/*# sourceMappingURL=banner.css.map */


text:
// -----------------------------------------------------------------------
// <copyright file="GetLinksByUserIdAsyncQuery.cs">
// Copyright (c) 2013-2015 Andrey Veselov. All rights reserved.
// License: Apache License 2.0
// Contacts: http://andrey.moveax.com andrey@moveax.com
// </copyright>
// -----------------------------------------------------------------------

namespace LoreKeeper.Tests.DataAccess.Queries.Links
{
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using LoreKeeper.Core;
    using LoreKeeper.Tests.Core.Models;
    using LoreKeeper.Tests.Core.Queries.Links;

    internal class GetLinksByUserIdAsyncQuery : IGetLinksByUserIdAsyncQuery
    {
        public async Task<IEnumerable<Link>> ExecuteAsync(int userId)
        {
            await Task.Delay(millisecondsDelay: 1);
            return Enumerable.Empty<Link>();
        }
    }
}


text:
require File.expand_path('../../test_helper', __FILE__)
require 'capybara/rails'

Capybara.default_driver = :selenium
Capybara.register_driver :selenium do |app|
  # Use the following driver definition to test locally using Chrome
  # (also requires chromedriver to be in PATH)
  # Capybara::Selenium::Driver.new(app, :browser => :chrome)
  # Add :switches => %w[--lang=en] to force default browser locale to English
  # Default for Selenium remote driver is to connect to local host on port 4444
  # This can be change using :url => 'http://localhost:9195' if necessary
  # PhantomJS 1.8 now directly supports Webdriver Wire API,
  # simply run it with `phantomjs --webdriver 4444`
  # Add :desired_capabilities => Selenium::WebDriver::Remote::Capabilities.internet_explorer)
  # to run on Selenium Grid Hub with IE
  Capybara::Selenium::Driver.new(app, :browser => :remote)
end

# default: 2
Capybara.default_wait_time = 2

module Redmine
  module UiTest
    # Base class for UI tests
    class Base < ActionDispatch::IntegrationTest
      include Capybara::DSL

      # Stop ActiveRecord from wrapping tests in transactions
      # Transactional fixtures do not work with Selenium tests, because Capybara
      # uses a separate server thread, which the transactions would be hidden
      self.use_transactional_fixtures = false

      # Should not depend on locale since Redmine displays login page
      # using default browser locale which depend on system locale for "real" browsers drivers
      def log_user(login, password)
        visit '/my/page'
        assert_equal '/login', current_path
        within('#login-form form') do
          fill_in 'username', :with => login
          fill_in 'password', :with => password
          find('input[name=login]').click
        end
        assert_equal '/my/page', current_path
      end

      teardown do
        Capybara.reset_sessions!    # Forget the (simulated) browser state
        Capybara.use_default_driver # Revert Capybara.current_driver to Capybara.default_driver
      end
    end
  end
end


text:
package org.assertj.core.api.offsetdatetime;

import static java.lang.String.format;
import static java.time.OffsetDateTime.of;
import static java.time.ZoneOffset.UTC;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.util.FailureMessages.actualIsNull;

import java.time.OffsetDateTime;

import org.junit.jupiter.api.Test;

/**
 * @author Paweł Stawicki
 * @author Joel Costigliola
 * @author Marcin Zajączkowski
 */
public class OffsetDateTimeAssert_isBefore_Test extends OffsetDateTimeAssertBaseTest {

  @Test
  public void test_isBefore_assertion() {
    // WHEN
    assertThat(BEFORE).isBefore(REFERENCE);
    assertThat(BEFORE).isBefore(REFERENCE.toString());
    // THEN
    verify_that_isBefore_assertion_fails_and_throws_AssertionError(REFERENCE, REFERENCE);
    verify_that_isBefore_assertion_fails_and_throws_AssertionError(AFTER, REFERENCE);
  }

  @Test
  public void test_isBefore_assertion_error_message() {
    assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(of(2000, 1, 5, 3, 0, 5, 0,
                                                                                UTC)).isBefore(of(1998, 1, 1, 3, 3,
                                                                                3, 0, UTC)))
                                                   .withMessage(format("%nExpecting:%n" +
                                                                       "  <2000-01-05T03:00:05Z>%n" +
                                                                       "to be strictly before:%n" +
                                                                       "  <1998-01-01T03:03:03Z>"));
  }

  @Test
  public void should_fail_if_actual_is_null() {
    assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> {
      OffsetDateTime actual = null;
      assertThat(actual).isBefore(OffsetDateTime.now());
    }).withMessage(actualIsNull());
  }

  @Test
  public void should_fail_if_dateTime_parameter_is_null() {
    assertThatIllegalArgumentException().isThrownBy(() -> assertThat(OffsetDateTime.now()).isBefore((OffsetDateTime) null))
                                        .withMessage("The OffsetDateTime to compare actual with should not be null");
  }

  @Test
  public void should_fail_if_dateTime_as_string_parameter_is_null() {
    assertThatIllegalArgumentException().isThrownBy(() -> assertThat(OffsetDateTime.now()).isBefore((String) null))
                                        .withMessage("The String representing the OffsetDateTime to compare actual with should not be null");
  }

  private static void verify_that_isBefore_assertion_fails_and_throws_AssertionError(OffsetDateTime dateToTest,
                                                                                OffsetDateTime reference) {
    assertThatThrownBy(() -> assertThat(dateToTest).isBefore(reference)).isInstanceOf(AssertionError.class);
    assertThatThrownBy(() -> assertThat(dateToTest).isBefore(reference.toString())).isInstanceOf(AssertionError.class);
  }

}


text:
// Template Source: BaseEntity.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All Rights Reserved.  Licensed under the MIT License.  See License in the project root for license information.
// ------------------------------------------------------------------------------

package com.microsoft.graph.models;
import com.microsoft.graph.serializer.ISerializer;
import com.microsoft.graph.serializer.IJsonBackedObject;
import com.microsoft.graph.serializer.AdditionalDataManager;
import java.util.EnumSet;
import com.microsoft.graph.models.Entity;

import com.google.gson.JsonObject;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;

// **NOTE** This file was generated by a tool and any changes will be overwritten.

/**
 * The class for the Search Hit.
 */
public class SearchHit implements IJsonBackedObject {

    /** the OData type of the object as returned by the service */
    @SerializedName("@odata.type")
    @Expose
    @Nullable
    public String oDataType;

    private transient AdditionalDataManager additionalDataManager = new AdditionalDataManager(this);

    @Override
    @Nonnull
    public final AdditionalDataManager additionalDataManager() {
        return additionalDataManager;
    }

    /**
     * The Content Source.
     * The name of the content source that the externalItem is part of.
     */
    @SerializedName(value = "contentSource", alternate = {"ContentSource"})
    @Expose
	@Nullable
    public String contentSource;

    /**
     * The Hit Id.
     * The internal identifier for the item. The format of the identifier varies based on the entity type. For details, see hitId format.
     */
    @SerializedName(value = "hitId", alternate = {"HitId"})
    @Expose
	@Nullable
    public String hitId;

    /**
     * The Rank.
     * The rank or the order of the result.
     */
    @SerializedName(value = "rank", alternate = {"Rank"})
    @Expose
	@Nullable
    public Integer rank;

    /**
     * The Result Template Id.
     * ID of the result template used to render the search result. This ID must map to a display layout in the resultTemplates dictionary that is also included in the searchResponse.
     */
    @SerializedName(value = "resultTemplateId", alternate = {"ResultTemplateId"})
    @Expose
	@Nullable
    public String resultTemplateId;

    /**
     * The Summary.
     * A summary of the result, if a summary is available.
     */
    @SerializedName(value = "summary", alternate = {"Summary"})
    @Expose
	@Nullable
    public String summary;

    /**
     * The Resource.
     *
     */
    @SerializedName(value = "resource", alternate = {"Resource"})
    @Expose
	@Nullable
    public Entity resource;

    /**
     * Sets the raw JSON object
     *
     * @param serializer the serializer
     * @param json the JSON object to set this object to
     */
    public void setRawObject(@Nonnull final ISerializer serializer, @Nonnull final JsonObject json) {

    }
}


text:
<?php

use Tester\Assert;

require __DIR__ . '/../bootstrap.php';

webgenTest(
	__DIR__ . '/examples/external-libs',
	TEMP_DIR,
	__DIR__ . '/examples/external-libs/expected.output'
);


text:
class CreateUploads < ActiveRecord::Migration
  def change
    create_table :uploads do |t|
      t.string :uuid, :limit => 36, :null => false
      t.string :file_id, :limit => 100, :null => false
      t.string :file_filename, :limit => 255, :null => false
      t.integer :file_size, :limit => 4, :null => false
      t.string :file_content_type, :limit => 255, :null => false
      t.timestamps :null => false
      t.integer :creator_id
      t.integer :updater_id
    end

    add_index(:uploads, :uuid, :unique => true)
  end
end


text:
require 'tempfile'

module Backup
  module Syncer
    class RSync < Base

      ##
      # Server credentials
      attr_accessor :username, :password

      ##
      # Server IP Address and SSH port
      attr_accessor :ip

      ##
      # The SSH port to connect to
      attr_writer :port

      ##
      # Directories to sync
      attr_writer :directories

      ##
      # Path to store the synced files/directories to
      attr_accessor :path

      ##
      # Flag for mirroring the files/directories
      attr_writer :mirror

      ##
      # Flag for compressing (only compresses for the transfer)
      attr_writer :compress

      ##
      # Additional options for the rsync cli
      attr_accessor :additional_options

      ##
      # Instantiates a new RSync Syncer object and sets the default configuration
      # specified in the Backup::Configuration::Syncer::RSync. Then it sets the object
      # defaults if particular properties weren't set. Finally it'll evaluate the users
      # configuration file and overwrite anything that's been defined
      def initialize(&block)
        load_defaults!

        @directories          = Array.new
        @additional_options ||= Array.new
        @path               ||= 'backups'
        @port               ||= 22
        @mirror             ||= false
        @compress           ||= false

        instance_eval(&block) if block_given?
        write_password_file!

        @path = path.sub(/^\~\//, '')
      end

      ##
      # Performs the RSync operation
      # debug options: -vhP
      def perform!
        Logger.message("#{ self.class } started syncing #{ directories }.")
        Logger.silent(
          run("#{ utility(:rsync) } -vhP #{ options } #{ directories } '#{ username }@#{ ip }:#{ path }'")
        )

        remove_password_file!
      end

      ##
      # Returns all the specified Rsync options, concatenated, ready for the CLI
      def options
        ([archive, mirror, compress, port, password] + additional_options).compact.join("\s")
      end

      ##
      # Returns Rsync syntax for enabling mirroring
      def mirror
        '--delete' if @mirror
      end

      ##
      # Returns Rsync syntax for compressing the file transfers
      def compress
        '--compress' if @compress
      end

      ##
      # Returns Rsync syntax for invoking "archive" mode
      def archive
        '--archive'
      end

      ##
      # Returns Rsync syntax for defining a port to connect to
      def port
        "--port='#{@port}'"
      end

      ##
      # Returns Rsync syntax for setting a password (via a file)
      def password
        "--password-file='#{@password_file.path}'" unless @password.nil?
      end

      ##
      # If no block has been provided, it'll return the array of @directories.
      # If a block has been provided, it'll evaluate it and add the defined paths to the @directories
      def directories(&block)
        unless block_given?
          return @directories.map do |directory|
            "'#{directory}'"
          end.join("\s")
        end
        instance_eval(&block)
      end

      ##
      # Adds a path to the @directories array
      def add(path)
        @directories << path
      end

      private

      ##
      # Writes the provided password to a temporary file so that
      # the rsync utility can read the password from this file
      def write_password_file!
        unless @password.nil?
          @password_file = Tempfile.new('backup-rsync-password')
          @password_file.write(@password)
          @password_file.close
        end
      end

      ##
      # Removes the previously created @password_file
      # (temporary file containing the password)
      def remove_password_file!
        @password_file.unlink unless @password.nil?
      end

    end
  end
end


text:
$(document).ready(function () {
    fixForms();
    //bind 'myForm' and provide a simple callback function
    $('#profile-form').ajaxForm();
    $('#id_avatar').change(enableSubmit);
        var s = 4.0/7.0*100 + "%";
        $(".bar").width(s);

    $("#back").button().click(function () {
        $(this).button("option", "disabled", true);
        $.get("{% url setup_referral %}?from=profile", function (data) {
            $("#ui-dialog-title-setup-dialog").html(data.title);
            $("#setup-dialog").html(data.contents);
        });
    });

    $("#profile-submit").button().click(function () {
        $(this).button("option", "disabled", true);
        $('#profile-form').ajaxSubmit({
            //beforeSubmit: showRequest,
            dataType:"json",
            success:showResponse,
            //error:handleError
        });
        $(this).button("option", "disabled", false);
    });

    function enableSubmit() {
        if($('#id_avatar').val() != ''){
           $('#profile-submit').removeAttr('disabled');
        }
    }

    // Useful for debugging.
    function showRequest(formData, jqForm, options) {
        // formData is an array; here we use $.param to convert it to a string to display it
        // but the form plugin does this for you automatically when it submits the data
        var queryString = $.param(formData);

        // jqForm is a jQuery object encapsulating the form element.  To access the
        // DOM element for the form do this:
        // var formElement = jqForm[0];

        alert('About to submit: \n\n' + queryString);

        // here we could return false to prevent the form from being submitted;
        // returning anything other than false will allow the form submit to continue
        return true;
    }

    function handleError(xhr, text, error) {
        alert("Error" + text);
        alert(xhr.status);
        alert(error);
    }

    function showResponse(data) {
        $("#ui-dialog-title-setup-dialog").html(data.title);
        $("#setup-dialog").html(data.contents);
    }
});


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

public interface JiraConstants {

    String JIRA = "jira";
    String ACCESS_TOKEN = "accessToken";
    String VERIFICATION_CODE = "verificationCode";
    String JIRA_URL = "jiraUrl";
    String PRIVATE_KEY = "privateKey";
    String CONSUMER_KEY = "consumerKey";
    String ISSUE_ASSIGNEE = "IssueAssignee";
    String ISSUE_COMPONENTS = "IssueComponents";
    String ISSUE_COMMENT = "IssueComment";
    String ISSUE_KEY = "IssueKey";
    String ISSUE_PRIORITY_ID = "IssuePriorityId";
    String ISSUE_PRIORITY_NAME = "IssuePriorityName";
    String ISSUE_PROJECT_KEY = "ProjectKey";
    String ISSUE_SUMMARY = "IssueSummary";
    String ISSUE_TRANSITION_ID = "IssueTransitionId";
    String ISSUE_TYPE_ID = "IssueTypeId";
    String ISSUE_TYPE_NAME = "IssueTypeName";
    String ISSUE_WATCHERS_ADD = "IssueWatchersAdd";
    String ISSUE_WATCHERS_REMOVE = "IssueWatchersRemove";
    String JIRA_REST_CLIENT_FACTORY = "JiraRestClientFactory";
    String PARENT_ISSUE_KEY = "ParentIssueKey";
    String CHILD_ISSUE_KEY = "ChildIssueKey";
    String LINK_TYPE = "linkType";
    String MINUTES_SPENT = "minutesSpent";
}


text:
module Faker
  module AddressUK
    include Faker::Address
    extend ModuleUtils
    extend self

    def county
      UK_COUNTY.rand
    end

    def country
      UK_COUNTRY.rand
    end

    def postcode
      Faker.bothify(UK_POSTCODE.rand).upcase
    end

    UK_COUNTY = k ['Avon', 'Bedfordshire', 'Berkshire', 'Borders',
      'Buckinghamshire', 'Cambridgeshire', 'Central', 'Cheshire', 'Cleveland',
      'Clwyd', 'Cornwall', 'County Antrim', 'County Armagh', 'County Down',
      'County Fermanagh', 'County Londonderry', 'County Tyrone', 'Cumbria',
      'Derbyshire', 'Devon', 'Dorset', 'Dumfries and Galloway', 'Durham',
      'Dyfed', 'East Sussex', 'Essex', 'Fife', 'Gloucestershire', 'Grampian',
      'Greater Manchester', 'Gwent', 'Gwynedd County', 'Hampshire',
      'Herefordshire', 'Hertfordshire', 'Highlands and Islands', 'Humberside',
      'Isle of Wight', 'Kent', 'Lancashire', 'Leicestershire', 'Lincolnshire',
      'Lothian', 'Merseyside', 'Mid Glamorgan', 'Norfolk', 'North Yorkshire',
      'Northamptonshire', 'Northumberland', 'Nottinghamshire', 'Oxfordshire',
      'Powys', 'Rutland', 'Shropshire', 'Somerset', 'South Glamorgan',
      'South Yorkshire', 'Staffordshire', 'Strathclyde', 'Suffolk', 'Surrey',
      'Tayside', 'Tyne and Wear', 'Warwickshire', 'West Glamorgan', 'West Midlands',
      'West Sussex', 'West Yorkshire', 'Wiltshire', 'Worcestershire']

    UK_COUNTRY = k ['England', 'Scotland', 'Wales', 'Northern Ireland']

    UK_POSTCODE = k ['??# #??', '??## #??']
  end
end


text:
namespace media {

class MEDIA_EXPORT AudioManagerOpenBSD : public AudioManagerBase {
 public:
  AudioManagerOpenBSD();

  // Implementation of AudioManager.
  virtual bool HasAudioOutputDevices() OVERRIDE;
  virtual bool HasAudioInputDevices() OVERRIDE;

  // Implementation of AudioManagerBase.
  virtual AudioOutputStream* MakeLinearOutputStream(
      const AudioParameters& params) OVERRIDE;
  virtual AudioOutputStream* MakeLowLatencyOutputStream(
      const AudioParameters& params) OVERRIDE;
  virtual AudioInputStream* MakeLinearInputStream(
      const AudioParameters& params, const std::string& device_id) OVERRIDE;
  virtual AudioInputStream* MakeLowLatencyInputStream(
      const AudioParameters& params, const std::string& device_id) OVERRIDE;

 protected:
  virtual ~AudioManagerOpenBSD();

 private:
  // Called by MakeLinearOutputStream and MakeLowLatencyOutputStream.
  AudioOutputStream* MakeOutputStream(const AudioParameters& params);

  DISALLOW_COPY_AND_ASSIGN(AudioManagerOpenBSD);
};

}  // namespace media

#endif  // MEDIA_AUDIO_OPENBSD_AUDIO_MANAGER_OPENBSD_H_


text:
package com.socrata.ssync;

import com.socrata.ssync.exceptions.input.ChecksumMismatch;
import com.socrata.ssync.exceptions.input.InputException;
import com.socrata.ssync.exceptions.signature.*;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.DigestException;
import java.io.InputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;

public class SignatureTable {
    static final int MaxSignatureBlockSize = 0xffff;

    static int signatureBlockSizeForBlockSize(int blockSize) {
        // each block of signatures should represent ~1M of data in order to
        // make streaming signature files practical.
        return Math.min(1 + (1024*1024) / blockSize, SignatureTable.MaxSignatureBlockSize);
    }

    private static class Entry {
        final int blockNum;
        final int weakHash;
        final byte[] strongHash;
        int firstOffset; // offset of the first entry with this weak hash
        int endOffset; // one past the offset of the last entry with this weak hash

        Entry(int blockNum, int weakHash, byte[] strongHash) {
            this.blockNum = blockNum;
            this.weakHash = weakHash;
            this.strongHash = strongHash;
        }
    }

    public final String checksumAlgorithmName;
    private final Entry[] allEntries;
    private final int[] entries = new int[1 << 17]; // entries is a list of (start, end) slices of allEntries
    public final int blockSize;
    private final MessageDigest strongHasher;
    private final byte[] strongHash;
    private final Stats stats = new Stats();

    private static int hash16(int weakHash) {
            return (weakHash >> 16 ^ weakHash) & 0xffff;
    }

    public static class Stats implements Cloneable {
        private long totalProbes;
        private long weak16Hits;
        private long weakHits;
        private long strongProbes;
        private long strongHits;

        public long getTotalProbes() {
            return totalProbes;
        }

        public long getWeak16Hits() {
            return weak16Hits;
        }

        public long getWeakHits() {
            return weakHits;
        }

        public long getStrongProbes() {
            return strongProbes;
        }

        public long strongHits() {
            return strongHits;
        }

        private void reset() {
            totalProbes = weak16Hits = weakHits = strongProbes = strongHits = 0L;
        }

        public String toString() {
            return String.format("Total probes: %d; weak16 hits: %d; weak hits: %d; strong probes: %d; strong hits: %d",
                    totalProbes, weak16Hits, weakHits, strongProbes, strongHits);
        }

        public Stats clone() {
            try {
                return (Stats) super.clone();
            } catch (CloneNotSupportedException e) {
                throw new RuntimeException("SignatureTable.Stats implements cloneable but threw CloneNotSupportedException?");
            }
        }
    }

    public SignatureTable(InputStream inStream) throws IOException, InputException, SignatureException {
        InputStreamReadHelper.MessageDigestAndOriginalName checksumInfo = InputStreamReadHelper.readChecksumAlgorithm(inStream);
        checksumAlgorithmName = checksumInfo.originalName;
        InputStreamReadHelper in = new InputStreamReadHelper(inStream, checksumInfo.messageDigest);

        blockSize = in.readInt();
        if(blockSize <= 0 || blockSize > Patch.MaxBlockSize) {
            throw new InvalidBlockSize(blockSize);
        }

        String strongHashAlgorithmName = in.readShortUTF8();
        try {
            strongHasher = MessageDigest.getInstance(strongHashAlgorithmName);
        } catch(NoSuchAlgorithmException e) {
            throw new UnknownStrongHashAlgorithm(strongHashAlgorithmName);
        }
        int signatureBlockSize = in.readInt();
        if(signatureBlockSize <= 0 || signatureBlockSize > MaxSignatureBlockSize) {
            throw new InvalidSignatureBlockSize(signatureBlockSize);
        }
        int strongHashSize = strongHasher.getDigestLength();
        strongHash = new byte[strongHashSize];

        ArrayList<Entry> entryBuilder = new ArrayList<>();
        while(true) {
            int count = in.readInt();
            if(count < 0 || count > signatureBlockSize) throw new InvalidSignatureCount(count);
            for(int i = 0; i != count; ++i) {
                int weakHash = in.readInt4();
                byte[] strongHash = new byte[strongHashSize];
                in.readBytes(strongHash, strongHashSize);
                entryBuilder.add(new Entry(entryBuilder.size(), weakHash, strongHash));
            }
            if(count != signatureBlockSize) break;
        }

        byte[] checksum = in.checksum();
        byte[] correctChecksum = new byte[checksum.length];
        in.readFullyWithoutUpdatingChecksum(correctChecksum);
        if(!java.util.Arrays.equals(checksum, correctChecksum)) {
            throw new ChecksumMismatch();
        }

        allEntries = entryBuilder.toArray(new Entry[entryBuilder.size()]);
        entryBuilder = null; // Do not want this anymore.  Let the GC free it.

        java.util.Arrays.sort(allEntries, new Comparator<Entry>() {
                public int compare(Entry a, Entry b) {
                    int major = Integer.compare(hash16(a.weakHash), hash16(b.weakHash));
                    if(major == 0) {
                        int minor = Integer.compare(a.weakHash, b.weakHash);
                        if(minor == 0) return byteArrayCompare(a.strongHash, b.strongHash);
                        else return minor;
                    }
                    else return major;
                }
            });

        // ok, now we have a sorted list of entries.  Let's break them
        // up by hash16...
        int end = allEntries.length;
        int pos = 0;
        while(pos != end) {
            int start = pos;
            int hash16 = hash16(allEntries[start].weakHash);
            int firstHash = start;
            do {
                if(allEntries[pos].weakHash != allEntries[firstHash].weakHash) {
                    for(int i = firstHash; i != pos; ++i) {
                        allEntries[i].endOffset = pos;
                    }
                    firstHash = pos;
                }
                allEntries[pos].firstOffset = firstHash;
                pos += 1;
            } while(pos != end && hash16(allEntries[pos].weakHash) == hash16);
            for(int i = firstHash; i != pos; ++i) {
                allEntries[i].endOffset = pos;
            }
            entries[hash16 << 1] = start;
            entries[(hash16 << 1) + 1] = pos;
        }
    }

    public Stats getStats() {
        return stats.clone();
    }

    public Stats getStatsView() {
        return stats;
    }

    public void resetStats() {
        stats.reset();
    }

    public int findBlock(int weakHash, byte[] block, int offset, int len) {
        stats.totalProbes += 1;

        int potentialsListIdx = hash16(weakHash) << 1;
        int start = entries[potentialsListIdx];
        int end = entries[potentialsListIdx + 1];
        if(start == end) return -1; // nothing even with this 16-bit hash
        stats.weak16Hits += 1;

        int p = findFirstWeakEntry(start, end, weakHash);
        if(p == -1) return -1; // nothing with this weak hash
        stats.weakHits += 1;

        try {
            strongHasher.update(block, offset, Math.min(blockSize, len));
            strongHasher.digest(strongHash, 0, strongHash.length);
        } catch(DigestException e) {
            throw new RuntimeException("Shouldn't happen");
        }

        stats.strongProbes += 1;
        p = findStrongEntry(allEntries[p].firstOffset, allEntries[p].endOffset, strongHash);
        if(p != -1) p = allEntries[p].blockNum;
        return p;
    }

    private int findStrongEntry(int start, int end, byte[] strongHash) {
        while(true) {
            if(end - start < LinearProbeThreshold) return linearProbeStrong(start, end, strongHash);
            int m = ((end - start) >>> 1) + start;

            int ord = byteArrayCompare(strongHash, allEntries[m].strongHash);
            if(ord < 0) end = m;
            else if(ord > 0) start = m+1;
            else return m;
        }
    }

    private static int byteArrayCompare(byte[] a, byte[] b) {
        int end = Math.min(a.length, b.length);
        for(int i = 0; i < end; ++i) {
            int c = Byte.compare(a[i], b[i]);
            if(c != 0) return c;
        }
        return Integer.compare(a.length, b.length);
    }

    static final int LinearProbeThreshold = 8;
    private int findFirstWeakEntry(int start, int end, int weakHash) {
        while(true) {
            if(end - start < LinearProbeThreshold) return linearProbe(start, end, weakHash);
            int m = ((end - start) >>> 1) + start;

            int c = Integer.compare(weakHash, allEntries[m].weakHash);
            if(c < 0) end = m;
            else if(c > 0) start = m+1;
            else return allEntries[m].firstOffset;
        }
    }

    private int linearProbe(int start, int end, int weakHash) {
        for(int i = start; i != end; ++i) {
            if(allEntries[i].weakHash == weakHash) return i;
        }
        return -1;
    }

    private int linearProbeStrong(int start, int end, byte[] strongHash) {
        for(int i = start; i != end; ++i) {
            if(java.util.Arrays.equals(allEntries[i].strongHash, strongHash)) return i;
        }
        return -1;
    }
}


text:
#include <saffire/general/path_handling.h>
#include <saffire/general/definitions.h>
#include <saffire/memory/smm.h>
#include <string.h>
#include <stdio.h>
#include <sys/stat.h>

/**
 * Replaces or adds an extension on a path. Returns path with new extension.
 */
char *replace_extension(const char *path, const char *source_ext, const char *dest_ext) {
    char *dest_path, *ptr;
    int len;

    // Allocate enough room for path + complete extension
    dest_path = smm_malloc(strlen(path) + sizeof(dest_ext));
    bzero(dest_path, strlen(path) + sizeof(dest_ext));

    // Seek last .
    ptr = strrchr(path, '.');

    // Check if the last part is the actual source extension
    if (ptr != NULL && ! strcmp(ptr, source_ext)) {
        // Only copy until the extension
        len = ptr - path;
    } else {
        // Copy whole source
        len = strlen(path);
    }

    // Copy required part of path and add extension
    strncpy(dest_path, path, len);
    strcat(dest_path, dest_ext);

    return dest_path;
}

/**
 * Checks if target is a regular file
 */
int is_file(const char *target) {
    struct stat s;

    if(stat(target,&s) == 0) {
        if(s.st_mode & S_IFREG) {
            return 1;
        }
    }
    return 0;
}

/**
 * Checks if target is a directory
 */
int is_directory(const char *target) {
    struct stat s;

    if(stat(target,&s) == 0) {
        if(s.st_mode & S_IFDIR) {
            return 1;
        }
    }
    return 0;
}

/**
 * Checks if filename is a saffire file (ends with .sf)
 */
int is_saffire_file(const char *filename) {
    char *extension = strrchr(filename, '.');

    if (extension && strcmp(filename, extension) != 0 && strcmp(extension, SAFFIRE_EXTENSION) == 0) {
        return 1;
    }
    return 0;
}


text:
from utils import CanadianScraper, CanadianPerson as Person

COUNCIL_PAGE = 'http://www.markham.ca/wps/portal/Markham/MunicipalGovernment/MayorAndCouncil/RegionalAndWardCouncillors/!ut/p/a1/04_Sj9CPykssy0xPLMnMz0vMAfGjzOJN_N2dnX3CLAKNgkwMDDw9XcJM_VwCDUMDDfULsh0VAfz7Fis!/'

class MarkhamPersonScraper(CanadianScraper):
    def scrape(self):
        regional_councillor_seat_number = 1

        page = self.lxmlize(COUNCIL_PAGE)

        mayor_url = page.xpath('//a[contains(text(), "Office of the Mayor")]/@href')[0]
        yield self.scrape_mayor(mayor_url)

        councillors = page.xpath('//div[@class="interiorContentWrapper"]//td[./a]')
        assert len(councillors), 'No councillors found'
        for councillor in councillors:
            name_elem = ' '.join(councillor.xpath('.//strong/text()'))
            if 'Mayor' in name_elem:
                name = name_elem.split('Mayor')[1]
            elif 'Councillor' in name_elem:
                name = name_elem.split('Councillor')[1]
            else:
                name = name_elem

            district = councillor.xpath('.//a//text()[normalize-space()]')[0]
            if 'Ward' in district:
                district = district.replace('Councillor', '')
                role = 'Councillor'
            elif 'Regional' in district:
                role = 'Regional Councillor'
                district = 'Markham (seat {})'.format(regional_councillor_seat_number)
                regional_councillor_seat_number += 1
            else:
                role = district
                district = 'Markham'

            image = councillor.xpath('.//img/@src')[0]
            url = councillor.xpath('.//a/@href')[0]

            address, phone, email, links = self.get_contact(url)

            p = Person(primary_org='legislature', name=name, district=district, role=role)
            p.add_source(COUNCIL_PAGE)
            p.add_source(url)

            p.image = image
            p.add_contact('address', address, 'legislature')
            p.add_contact('voice', phone, 'legislature')
            p.add_contact('email', email)

            for link in links:
                p.add_link(link)

            yield p

    def get_contact(self, url):
        page = self.lxmlize(url)

        node = page.xpath('//div[@class="microSiteLinksWrapper"]')
        links = []

        if node:
            contact_node = node[1]

            if contact_node.xpath('.//p/text()'):
                contact = contact_node.xpath('.//p/text()')
                links = get_links(contact_node.xpath('.//p')[0])
            else:
                contact = contact_node.xpath('./div/text()')
                links = get_links(contact_node.xpath('./div')[0])

            address = ' '.join(contact[:2])
            phone = contact[2].split(':')[1].strip()
        else:
            contact_node = page.xpath('//div[@class="interiorContentWrapper"]')[0]
            address = ' '.join(contact_node.xpath('./p[1]/text()'))
            phone = contact_node.xpath('./p[2]/text()')[0].split(':')[1].strip()

        email = self.get_email(contact_node)

        return address, phone, email, links

    def scrape_mayor(self, url):
        page = self.lxmlize(url)
        name = page.xpath('//img/@alt[contains(., "Mayor")]')[0].split(' ', 1)[1]

        p = Person(primary_org='legislature', name=name, district='Markham', role='Mayor')
        p.add_source(url)

        yield p

def get_links(elem):
    links_r = []
    links = elem.xpath('.//a')
    for link in links:
        link = link.attrib['href']
        if 'mailto:' not in link and 'http://www.markham.ca' not in link:
            links_r.append(link)
    return links_r


text:
Welcome to LocalData

Enter your email to reset your password

      <form id="reset-password">
        <input type="text" name="email" placeholder="Your email" class="large">

        <button class="ok">Save</button>

Thanks! We've emailed you a link to reset your password.

      </form>