text:
package cmd

import (
	"fmt"

	"github.com/drud/ddev/pkg/appimport"
	"github.com/drud/ddev/pkg/ddevapp"
	"github.com/drud/ddev/pkg/dockerutil"
	"github.com/drud/ddev/pkg/output"
	"github.com/drud/ddev/pkg/util"
	"github.com/spf13/cobra"
)

var sourcePath string
var extPath string

// ImportFileCmd represents the `ddev import-db` command.
var ImportFileCmd = &cobra.Command{
	Use: "import-files",
	Example: `ddev import-files --src=/path/to/files.tar.gz
ddev import-files --src=/path/to/dir
ddev import-files --src=/path/to/files.tar.xz
ddev import-files --src=/path/to/files.tar.bz2`,
	Short: "Pull the uploaded files directory of an existing project to the default public upload directory of your project.",
	Long: `Pull the uploaded files directory of an existing project to the default
public upload directory of your project. The files can be provided as a
directory path or an archive in .tar, .tar.gz, .tar.xz, .tar.bz2, .tgz, or .zip format. For the
.zip and tar formats, the path to a directory within the archive can be
provided if it is not located at the top-level of the archive. If the
destination directory exists, it will be replaced with the assets being
imported.

The destination directory can be configured in your project's config.yaml
under the upload_dir key. If no custom upload directory is defined, the app
type's default upload directory will be used.`,
	PreRun: func(cmd *cobra.Command, args []string) {
		dockerutil.EnsureDdevNetwork()
	},
	Args: cobra.ExactArgs(0),
	Run: func(cmd *cobra.Command, args []string) {
		app, err := ddevapp.GetActiveApp("")
		if err != nil {
			util.Failed("Failed to import files: %v", err)
		}

		var showExtPathPrompt bool
		if sourcePath == "" {
			// Ensure we prompt for extraction path if an archive is provided, while still allowing
			// non-interactive use of --src flag without providing a --extract-path flag.
			if extPath == "" {
				showExtPathPrompt = true
			}

			promptForFileSource(&sourcePath)
		}

		importPath, isArchive, err := appimport.ValidateAsset(sourcePath, "files")
		if err != nil {
			util.Failed("Failed to import files for %s: %v", app.GetName(), err)
		}

		// Ensure we prompt for extraction path if an archive is provided, while still allowing
		// non-interactive use of --src flag without providing a --extract-path flag.
		if isArchive && showExtPathPrompt {
			promptForExtPath(&extPath)
		}

		if err = app.ImportFiles(importPath, extPath); err != nil {
			util.Failed("Failed to import files for %s: %v", app.GetName(), err)
		}

		util.Success("Successfully imported files for %v", app.GetName())
	},
}

const importPathPrompt = `Provide the path to the source directory or archive you wish to import.`

const importPathWarn = `Please note: if the destination directory exists, it will be replaced with the
import assets specified here.`

// promptForFileSource prompts the user for the path to the source file.
func promptForFileSource(val *string) {
	output.UserOut.Println(importPathPrompt)
	output.UserOut.Warnln(importPathWarn)

	// An empty string isn't acceptable here, keep
	// prompting until something is entered
	for {
		fmt.Print("Pull path: ")
		*val = util.GetInput("")
		if len(*val) > 0 {
			break
		}
	}
}

const extPathPrompt = `You provided an archive. Do you want to extract from a specific path in your
archive? You may leave this blank if you wish to use the full archive contents.`

// promptForExtPath prompts the user for the internal extraction path of an archive.
func promptForExtPath(val *string) {
	output.UserOut.Println(extPathPrompt)

	// An empty string is acceptable in this case, indicating
	// no particular extraction path
	fmt.Print("Archive extraction path: ")
	*val = util.GetInput("")
}

func init() {
	ImportFileCmd.Flags().StringVarP(&sourcePath, "src", "", "", "Provide the path to the source directory or tar/tar.gz/tgz/zip archive of files to import")
	ImportFileCmd.Flags().StringVarP(&extPath, "extract-path", "", "", "If provided asset is an archive, optionally provide the path to extract within the archive.")
	RootCmd.AddCommand(ImportFileCmd)
}


text:
'use strict';

const cleanText = require('./cleanText');

module.exports = function parseText(source, regexp = /^[0-9A-Z<]+$/) {
  if (!source.match(regexp)) {
    throw new Error(
      `invalid text: ${source}. Must match the following regular expression: ${regexp}`,
    );
  }
  return cleanText(source);
};

redpajama_set_name: RedPajamaGithub


text:
package lib

import (
	api "go.bytebuilders.dev/audit/api/v1"

	"kmodules.xyz/client-go/discovery"
	"sigs.k8s.io/controller-runtime/pkg/client"
)

type BillingEventCreator struct {
	Mapper discovery.ResourceMapper
}

func (p *BillingEventCreator) CreateEvent(obj client.Object) (*api.Event, error) {
	rid, err := p.Mapper.ResourceIDForGVK(obj.GetObjectKind().GroupVersionKind())
	if err != nil {
		return nil, err
	}

	return &api.Event{
		Resource:   obj,
		ResourceID: *rid,
	}, nil
}


text:
DROP TABLE IF EXISTS `user_details`;

CREATE TABLE `user_details` (
    `username` varchar(50) NOT NULL,
    `email` varchar (254),
    `about` varchar (500),
    `site` varchar (100),
    PRIMARY KEY (`username`),
    CONSTRAINT `fk_username` FOREIGN KEY (`username`) REFERENCES `users` (`username`) ON DELETE CASCADE
) DEFAULT charset=utf8;


text:
/*

 CEThemeManager.h

 CotEditor
 http://coteditor.com

 Created by 1024jp on 2014-04-12.

 ------------------------------------------------------------------------------

 © 2014-2015 1024jp

 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.

 */

@import AppKit;

// extension for theme file
extern NSString *const CEThemeExtension;

// keys for theme dict
extern NSString *const CEThemeTextKey;
extern NSString *const CEThemeBackgroundKey;
extern NSString *const CEThemeInvisiblesKey;
extern NSString *const CEThemeSelectionKey;
extern NSString *const CEThemeInsertionPointKey;
extern NSString *const CEThemeLineHighlightKey;

extern NSString *const CEThemeKeywordsKey;
extern NSString *const CEThemeCommandsKey;
extern NSString *const CEThemeTypesKey;
extern NSString *const CEThemeAttributesKey;
extern NSString *const CEThemeVariablesKey;
extern NSString *const CEThemeValuesKey;
extern NSString *const CEThemeNumbersKey;
extern NSString *const CEThemeStringsKey;
extern NSString *const CEThemeCharactersKey;
extern NSString *const CEThemeCommentsKey;

extern NSString *const CEThemeColorKey;
extern NSString *const CEThemeUsesSystemSettingKey;

// notifications
extern NSString *const CEThemeListDidUpdateNotification;
extern NSString *const CEThemeDidUpdateNotification;

@interface CEThemeManager : NSObject

@property (readonly, nonatomic, copy) NSArray *themeNames;

// singleton
+ (instancetype)sharedManager;

// public methods
/// Theme dict in which objects are property list ready.
- (NSMutableDictionary *)archivedTheme:(NSString *)themeName isBundled:(BOOL *)isBundled;

/// Return whether the theme that has the given name is bundled with the app.
- (BOOL)isBundledTheme:(NSString *)themeName cutomized:(BOOL *)isCustomized;

// manage themes
- (BOOL)saveTheme:(NSDictionary *)theme name:(NSString *)themeName completionHandler:(void (^)(NSError *error))completionHandler;
- (BOOL)renameTheme:(NSString *)themeName toName:(NSString *)newThemeName error:(NSError **)outError;
- (BOOL)removeTheme:(NSString *)themeName error:(NSError **)outError;
- (BOOL)restoreTheme:(NSString *)themeName completionHandler:(void (^)(NSError *error))completionHandler;
- (BOOL)duplicateTheme:(NSString *)themeName error:(NSError **)outError;
- (BOOL)exportTheme:(NSString *)themeName toURL:(NSURL *)URL error:(NSError **)outError;
- (BOOL)importTheme:(NSURL *)URL replace:(BOOL)doReplace error:(NSError **)outError;
- (BOOL)createUntitledThemeWithCompletionHandler:(void (^)(NSString *themeName, NSError *error))completionHandler;

@end

// Category for migration from CotEditor 1.x to 2.0. (2014-10)
// It can be removed when the most of users have been already migrated in the future.
@interface CEThemeManager (Migration)

- (BOOL)migrateTheme;

@end


text:
from django.conf.urls import *

urlpatterns = patterns('leonardo.module.media.views',
    url(r'^$', 'directory_list_nested', {'directory_slug': None}, name="directories"),
    url(r'^fullscreen/(?P<category_id>[\w\-]+)/$', 'directory_detail_standalone', name="directory_detail_standalone"),
    url(r'^(?P<directory_slug>.*)/$', 'directory_list_nested', name='directory_list_nested'),
    url(r'^(?P<parent_directory_slug>[\w\-]+)/(?P<directory_slug>[\w\-]+)/$', 'directory_list_nested', name="parent_directory_list_nested"),
    url(r'^(?P<grandparent_directory_slug>[\w\-]+)/(?P<parent_directory_slug>[\w\-]+)/(?P<directory_slug>[\w\-]+)/$', 'directory_list_nested'),
)


text:
//---------------------------------------------------------------------
// <copyright file="AtomObjectModelToPayloadElementConverter.cs" company="Microsoft">
//      Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------

namespace Microsoft.Test.Taupo.OData.Reader.Tests.Atom
{
    #region Namespaces
    using System;
    using System.Globalization;
    using System.Linq;
    using Microsoft.OData.Core;
    using Microsoft.OData.Core.Atom;
    using Microsoft.Test.Taupo.Astoria.Contracts.OData;
    using Microsoft.Test.Taupo.Common;
    using Microsoft.Test.Taupo.OData.Atom;
    using Microsoft.Test.Taupo.OData.Common;
    #endregion Namespaces

    /// <summary>
    /// Converts OData object model to ODataPayloadElement model with Atom specific behavior.
    /// </summary>
    public class AtomObjectModelToPayloadElementConverter : ObjectModelToPayloadElementConverter
    {
        /// <summary>
        /// Constructor.
        /// </summary>
        public AtomObjectModelToPayloadElementConverter()
        {
        }

        /// <summary>
        /// Virtual method to create the visitor to perform the conversion.
        /// </summary>
        /// <param name="response">true if payload represents a response payload, false if it's a request payload.</param>
        /// <param name="payloadContainsId">Whether or not the payload contains identity values for entries.</param>
        /// <param name="payloadContainsEtagForType">A function for determining whether the payload contains etag property values for a given type.</param>
        /// <returns>The newly created visitor.</returns>
        protected override ObjectModelToPayloadElementConverterVisitor CreateVisitor(bool response, bool payloadContainsId, Func<string, bool> payloadContainsEtagForType)
        {
            return new AtomObjectModelToPayloadElementConverterVisitor(response, this.RequestManager);
        }

        /// <summary>
        /// The inner visitor which performs the conversion.
        /// </summary>
        protected class AtomObjectModelToPayloadElementConverterVisitor : ObjectModelToPayloadElementConverterVisitor
        {
            /// <summary>
            /// Constructor
            /// </summary>
            /// <param name="response">true if payload represents a response payload, false if it's a request payload.</param>
            /// <param name="requestManager">The request manager used to convert batch payloads.</param>
            public AtomObjectModelToPayloadElementConverterVisitor(bool response, IODataRequestManager requestManager)
                : base(response, requestManager)
            {
            }

            /// <summary>
            /// Visits an entity reference links item.
            /// </summary>
            /// <param name="entityReferenceLinks">The entity reference links item to visit.</param>
            /// <returns>An ODataPayloadElement representing the entity reference links.</returns>
            protected override ODataPayloadElement VisitEntityReferenceLinks(ODataEntityReferenceLinks entityReferenceLinks)
            {
                ExceptionUtilities.CheckArgumentNotNull(entityReferenceLinks, "entityReferenceLinks");

                LinkCollection linkCollection = (LinkCollection)base.VisitEntityReferenceLinks(entityReferenceLinks);

                AtomLinkMetadata atomMetadata = entityReferenceLinks.GetAnnotation<AtomLinkMetadata>();
                if (atomMetadata != null)
                {
                    ConvertAtomLinkMetadata(atomMetadata, linkCollection);
                }

                return linkCollection;
            }

            /// <summary>
            /// Visits an entry item.
            /// </summary>
            /// <param name="entry">The entry item to visit.</param>
            /// <returns>An ODataPayloadElement representing the entry.</returns>
            protected override ODataPayloadElement VisitEntry(ODataEntry entry)
            {
                ExceptionUtilities.CheckArgumentNotNull(entry, "entry");

                EntityInstance entity = (EntityInstance)base.VisitEntry(entry);

                var atomMetadata = entry.GetAnnotation<AtomEntryMetadata>();
                if (atomMetadata != null)
                {
                    ConvertAtomEntryMetadata(atomMetadata, entity);
                }

                return entity;
            }

            /// <summary>
            /// Visits a feed item.
            /// </summary>
            /// <param name="feed">The feed item to visit.</param>
            /// <returns>An ODataPayloadElement representing the feed.</returns>
            protected override ODataPayloadElement VisitFeed(ODataFeed feed)
            {
                ExceptionUtilities.CheckArgumentNotNull(feed, "feed");

                EntitySetInstance entitySet = (EntitySetInstance)base.VisitFeed(feed);

                var atomMetadata = feed.GetAnnotation<AtomFeedMetadata>();
                if (atomMetadata != null)
                {
                    ConvertAtomFeedMetadata(atomMetadata, entitySet);
                }

                return entitySet;
            }

            /// <summary>
            /// Visits a navigation link item.
            /// </summary>
            /// <param name="navigationLink">The navigation link to visit.</param>
            /// <returns>An ODataPayloadElement representing the navigation link.</returns>
            protected override ODataPayloadElement VisitNavigationLink(ODataNavigationLink navigationLink)
            {
                ExceptionUtilities.CheckArgumentNotNull(navigationLink, "navigationLink");

                NavigationPropertyInstance navigationProperty = (NavigationPropertyInstance)base.VisitNavigationLink(navigationLink);

                // In ATOM even deferred links may know if they point to collection or singleton.
                // So add the content type annotation to them (through it IsCollection) so that comparison is precise.
                DeferredLink deferredLink = navigationProperty.Value as DeferredLink;
                if (deferredLink != null && navigationLink.IsCollection.HasValue)
                {
                    deferredLink.IsCollection(navigationLink.IsCollection.Value);
                }

                AtomLinkMetadata atomMetadata = navigationLink.GetAnnotation<AtomLinkMetadata>();
                if (atomMetadata != null && deferredLink != null)
                {
                    ConvertAtomLinkChildrenMetadata(atomMetadata, navigationProperty.Value);
                }

                return navigationProperty;
            }

            /// <summary>
            /// Visits a stream reference value item.
            /// </summary>
            /// <param name="streamReferenceValue">The stream reference value item to visit.</param>
            /// <returns>An ODataPayloadElement representing the stream reference value.</returns>
            protected override ODataPayloadElement VisitStreamReferenceValue(ODataStreamReferenceValue streamReferenceValue)
            {
                ExceptionUtilities.CheckArgumentNotNull(streamReferenceValue, "streamReferenceValue");

                NamedStreamInstance namedStreamInstance = (NamedStreamInstance)base.VisitStreamReferenceValue(streamReferenceValue);

                AtomStreamReferenceMetadata streamMetadata = streamReferenceValue.GetAnnotation<AtomStreamReferenceMetadata>();
                if (streamMetadata != null)
                {
                    if (streamMetadata.EditLink != null)
                    {
                        AtomLinkMetadata editMetadata = streamMetadata.EditLink;
                        namedStreamInstance.AtomNamedStreamLink(editMetadata.Href == null ? null : editMetadata.Href.OriginalString, editMetadata.Relation, editMetadata.MediaType, editMetadata.HrefLang, editMetadata.Title, ToString(editMetadata.Length));
                    }

                    if (streamMetadata.SelfLink != null)
                    {
                        AtomLinkMetadata selfMetadata = streamMetadata.SelfLink;
                        namedStreamInstance.AtomNamedStreamLink(selfMetadata.Href == null ? null : selfMetadata.Href.OriginalString, selfMetadata.Relation, selfMetadata.MediaType, selfMetadata.HrefLang, selfMetadata.Title, ToString(selfMetadata.Length));
                    }
                }

                return namedStreamInstance;
            }

            /// <summary>
            /// Visits a serviceDocument item.
            /// </summary>
            /// <param name="serviceDocument">The serviceDocument item to visit.</param>
            /// <returns>An ODataPayloadElement representing a service document enclosing the serviceDocument.</returns>
            protected override ODataPayloadElement VisitWorkspace(ODataServiceDocument serviceDocument)
            {
                ExceptionUtilities.CheckArgumentNotNull(serviceDocument, "serviceDocument");

                ServiceDocumentInstance wrappingServiceDocumentInstance = (ServiceDocumentInstance)base.VisitWorkspace(serviceDocument);

                WorkspaceInstance workspaceInstance = wrappingServiceDocumentInstance.Workspaces.Single();
                AtomWorkspaceMetadata atomMetadata = serviceDocument.GetAnnotation<AtomWorkspaceMetadata>();
                if (atomMetadata != null)
                {
                    if (atomMetadata.Title != null)
                    {
                        workspaceInstance.Title = atomMetadata.Title.Text;
                        workspaceInstance.AtomTitle(atomMetadata.Title.Text, ToString(atomMetadata.Title.Kind));
                    }
                }

                return wrappingServiceDocumentInstance;
            }

            /// <summary>
            /// Visits a resource collection.
            /// </summary>
            /// <param name="entitySetInfo">The resource collection to visit.</param>
            protected override ODataPayloadElement VisitResourceCollection(ODataEntitySetInfo entitySetInfo)
            {
                ExceptionUtilities.CheckArgumentNotNull(entitySetInfo, "entitySetInfo");

                ResourceCollectionInstance collectionInstance = (ResourceCollectionInstance)base.VisitResourceCollection(entitySetInfo);

                AtomResourceCollectionMetadata atomMetadata = entitySetInfo.GetAnnotation<AtomResourceCollectionMetadata>();
                if (atomMetadata != null)
                {
                    if (atomMetadata.Title != null)
                    {
                        collectionInstance.Title = atomMetadata.Title.Text;
                        collectionInstance.AtomTitle(atomMetadata.Title.Text, ToString(atomMetadata.Title.Kind));
                    }

                    if (atomMetadata.Accept != null)
                    {
                        collectionInstance.AppAccept(atomMetadata.Accept);
                    }

                    if (atomMetadata.Categories != null)
                    {
                        if (atomMetadata.Categories.Href != null)
                        {
                            collectionInstance.AppOutOfLineCategories(atomMetadata.Categories.Href.OriginalString);
                        }
                        else
                        {
                            collectionInstance.AppInlineCategories(
                                atomMetadata.Categories.Fixed == null ? null : (atomMetadata.Categories.Fixed.Value ? TestAtomConstants.AtomPublishingFixedYesValue : TestAtomConstants.AtomPublishingFixedNoValue),
                                atomMetadata.Categories.Scheme,
                                atomMetadata.Categories.Categories == null ? new XmlTreeAnnotation[0] :
                                    atomMetadata.Categories.Categories.Select(category => AtomMetadataBuilder.AtomCategory(category.Term, category.Scheme, category.Label)).ToArray());
                        }
                    }
                }

                return collectionInstance;
            }

            /// <summary>
            /// Converts the Object Model representation of Atom metadata for entries into appropriate PayloadElement annotations
            /// </summary>
            /// <param name="entryMetadata">the Atom entry metadata, in Object Model representation, to convert</param>
            /// <param name="entry">the EntityInstance to annotate</param>
            private static void ConvertAtomEntryMetadata(AtomEntryMetadata entryMetadata, EntityInstance entry)
            {
                ExceptionUtilities.CheckArgumentNotNull(entryMetadata, "entryMetadata");
                ExceptionUtilities.CheckArgumentNotNull(entry, "entry");

                foreach (var author in entryMetadata.Authors)
                {
                    entry.AtomAuthor(author.Name, author.Uri == null ? null : author.Uri.OriginalString, author.Email);
                }

                foreach (var category in entryMetadata.Categories)
                {
                    entry.AtomCategory(category.Term, category.Scheme, category.Label);
                }

                foreach (var contributor in entryMetadata.Contributors)
                {
                    entry.AtomContributor(contributor.Name, contributor.Uri == null? null : contributor.Uri.OriginalString, contributor.Email);
                }

                if (entryMetadata.EditLink != null)
                {
                    AtomLinkMetadata editLink = entryMetadata.EditLink;
                    entry.AtomEditLink(editLink.Href == null ? null : editLink.Href.OriginalString, editLink.MediaType, editLink.HrefLang, editLink.Title, ToString(editLink.Length));
                }

                foreach (var link in entryMetadata.Links)
                {
                    entry.AtomLink(link.Href == null ? null : link.Href.OriginalString, link.Relation, link.MediaType, link.HrefLang, link.Title, ToString(link.Length));
                }

                if (entryMetadata.Published.HasValue)
                {
                    entry.AtomPublished(ToString(entryMetadata.Published));
                }

                if (entryMetadata.Rights != null)
                {
                    entry.AtomRights(entryMetadata.Rights.Text, ToString(entryMetadata.Rights.Kind));
                }

                if (entryMetadata.SelfLink != null)
                {
                    AtomLinkMetadata selfLink = entryMetadata.SelfLink;
                    entry.AtomSelfLink(selfLink.Href == null ? null : selfLink.Href.OriginalString, selfLink.MediaType, selfLink.HrefLang, selfLink.Title, ToString(selfLink.Length));
                }

                if (entryMetadata.CategoryWithTypeName != null)
                {
                    AtomCategoryMetadata categoryWithTypeName = entryMetadata.CategoryWithTypeName;
                    entry.AtomCategoryWithTypeName(categoryWithTypeName.Term, categoryWithTypeName.Label);
                }

                if (entryMetadata.Source != null)
                {
                    EntitySetInstance tempSourceFeed = new EntitySetInstance();
                    ConvertAtomFeedMetadata(entryMetadata.Source, tempSourceFeed);
                    entry.AtomSource(tempSourceFeed);
                }

                if (entryMetadata.Summary != null)
                {
                    entry.AtomSummary(entryMetadata.Summary.Text, ToString(entryMetadata.Summary.Kind));
                }

                if (entryMetadata.Title != null)
                {
                    entry.AtomTitle(entryMetadata.Title.Text, ToString(entryMetadata.Title.Kind));
                }

                if (entryMetadata.Updated.HasValue)
                {
                    entry.AtomUpdated(ToString(entryMetadata.Updated));
                }
            }

            /// <summary>
            /// Converts the Object Model representation of Atom metadata for feeds into appropriate PayloadElement annotations
            /// </summary>
            /// <param name="feedMetadata">the Atom feed metadata, in Object Model representation, to convert</param>
            /// <param name="feed">the EntitySetInstance to annotate</param>
            private static void ConvertAtomFeedMetadata(AtomFeedMetadata feedMetadata, EntitySetInstance feed)
            {
                ExceptionUtilities.CheckArgumentNotNull(feedMetadata, "feedMetadata");
                ExceptionUtilities.CheckArgumentNotNull(feed, "feed");

                foreach (var author in feedMetadata.Authors)
                {
                    feed.AtomAuthor(author.Name, author.Uri == null ? null : author.Uri.OriginalString, author.Email);
                }

                foreach (var category in feedMetadata.Categories)
                {
                    feed.AtomCategory(category.Term, category.Scheme, category.Label);
                }

                foreach (var contributor in feedMetadata.Contributors)
                {
                    feed.AtomContributor(contributor.Name, contributor.Uri == null ? null : contributor.Uri.OriginalString, contributor.Email);
                }

                if (feedMetadata.Generator != null)
                {
                    feed.AtomGenerator(feedMetadata.Generator.Name, feedMetadata.Generator.Uri == null ? null : feedMetadata.Generator.Uri.OriginalString, feedMetadata.Generator.Version);
                }

                if (feedMetadata.Icon != null)
                {
                    feed.AtomIcon(feedMetadata.Icon.OriginalString);
                }

                foreach (var link in feedMetadata.Links)
                {
                    string linkLength = link.Length.HasValue ? link.Length.Value.ToString() : null;
                    feed.AtomLink(link.Href == null ? null : link.Href.OriginalString, link.Relation, link.MediaType, link.HrefLang, link.Title, linkLength);
                }

                if (feedMetadata.Logo != null)
                {
                    feed.AtomLogo(feedMetadata.Logo.OriginalString);
                }

                if (feedMetadata.Rights != null)
                {
                    feed.AtomRights(feedMetadata.Rights.Text, ToString(feedMetadata.Rights.Kind));
                }

                if (feedMetadata.SelfLink != null)
                {
                    AtomLinkMetadata selfLink = feedMetadata.SelfLink;
                    ExceptionUtilities.Assert(selfLink.Relation == TestAtomConstants.AtomSelfRelationAttributeValue, "The self link ATOM metadata must have the rel set to 'self'.");
                    string selfLinkLength = selfLink.Length.HasValue ? selfLink.Length.Value.ToString() : null;
                    feed.AtomSelfLink(selfLink.Href == null ? null : selfLink.Href.OriginalString, selfLink.MediaType, selfLink.HrefLang, selfLink.Title, selfLinkLength);
                }

                if (feedMetadata.NextPageLink != null)
                {
                    AtomLinkMetadata nextPageLink = feedMetadata.NextPageLink;
                    ExceptionUtilities.Assert(nextPageLink.Relation == TestAtomConstants.AtomNextRelationAttributeValue, "The next page link ATOM metadata must have the rel set to 'next'.");
                    string nextPageLinkLength = nextPageLink.Length.HasValue ? nextPageLink.Length.Value.ToString() : null;
                    feed.AtomNextPageLink(nextPageLink.Href == null ? null : nextPageLink.Href.OriginalString, nextPageLink.MediaType, nextPageLink.HrefLang, nextPageLink.Title, nextPageLinkLength);
                }

                if (feedMetadata.SourceId != null)
                {
                    // This should only occur when the metadata comes from the source element of an entry
                    // and we are annotating a temporary feed instance
                    feed.AtomId(UriUtils.UriToString(feedMetadata.SourceId));
                }

                if (feedMetadata.Subtitle != null)
                {
                    feed.AtomSubtitle(feedMetadata.Subtitle.Text, ToString(feedMetadata.Subtitle.Kind));
                }

                if (feedMetadata.Title != null)
                {
                    feed.AtomTitle(feedMetadata.Title.Text, ToString(feedMetadata.Title.Kind));
                }

                if (feedMetadata.Updated.HasValue)
                {
                    feed.AtomUpdated(ToString(feedMetadata.Updated));
                }
            }

            /// <summary>
            /// Converts the Object Model representation of Atom link metadata into appropriate annotations for a link ODataPayloadElement.
            /// </summary>
            /// <param name="linkMetadata">The Atom link metadata, in Object Model representation, to convert.</param>
            /// <param name="payloadElement">The payload element to annotate.</param>
            private static void ConvertAtomLinkMetadata(AtomLinkMetadata linkMetadata, ODataPayloadElement payloadElement)
            {
                ExceptionUtilities.CheckArgumentNotNull(linkMetadata, "linkMetadata");
                ExceptionUtilities.CheckArgumentNotNull(payloadElement, "link");

                string lengthValue = linkMetadata.Length.HasValue ? linkMetadata.Length.Value.ToString() : null;
                payloadElement.AtomLink(linkMetadata.Href == null ? null : linkMetadata.Href.OriginalString, linkMetadata.Relation, linkMetadata.MediaType, linkMetadata.HrefLang, linkMetadata.Title, lengthValue);
            }

            /// <summary>
            /// Converts the Object Model representation of Atom link metadata into appropriate annotations for a payload element representing a link.
            /// </summary>
            /// <param name="linkMetadata">The Atom link metadata, in Object Model representation, to convert.</param>
            /// <param name="linkPayloadElement">The link payload element to annotate.</param>
            /// <remarks>This method is only for use with payload elements that represent links, as it will skip over the root link annotation.</remarks>
            private static void ConvertAtomLinkChildrenMetadata(AtomLinkMetadata linkMetadata, ODataPayloadElement linkPayloadElement)
            {
                ExceptionUtilities.CheckArgumentNotNull(linkMetadata, "linkMetadata");
                ExceptionUtilities.CheckArgumentNotNull(linkPayloadElement, "linkPayloadElement");

                // Since the payload element already represents a link, we annotate a temporary element
                // and copy the "children" annotations onto the actual payload element.
                var tempPayloadElement = new EntityInstance();
                ExceptionUtilities.Assert(!tempPayloadElement.Annotations.OfType<XmlTreeAnnotation>().Any(), "Payload element should not have XmlTreeAnnotations after construction");
                ConvertAtomLinkMetadata(linkMetadata, tempPayloadElement);

                XmlTreeAnnotation linkAnnotation = tempPayloadElement.Annotations.OfType<XmlTreeAnnotation>().Single();
                foreach (XmlTreeAnnotation childAnnotation in linkAnnotation.Children)
                {
                    linkPayloadElement.AddAnnotation(childAnnotation);
                }
            }

            /// <summary>
            /// Converts a given <see cref="AtomTextConstructKind"/> to a string appropriate for Atom format.
            /// </summary>
            /// <param name="textConstructKind">The text construct kind to convert.</param>
            /// <returns>The string version of the text construct format in Atom format.</returns>
            private static string ToString(AtomTextConstructKind textConstructKind)
            {
                // This code copied from product's internal AtomValueUtils.ToString method
                ExceptionUtilities.CheckArgumentNotNull(textConstructKind, "textConstructorKind");

                switch (textConstructKind)
                {
                    case AtomTextConstructKind.Text:
                        return TestAtomConstants.AtomTextConstructTextKind;
                    case AtomTextConstructKind.Html:
                        return TestAtomConstants.AtomTextConstructHtmlKind;
                    case AtomTextConstructKind.Xhtml:
                        return TestAtomConstants.AtomTextConstructXHtmlKind;
                    default:
                        throw new TaupoArgumentException("Unknown AtomTextConstructKind " + textConstructKind.ToString());
                }
            }

            /// <summary>
            /// Converts a given nullable <see cref="DateTimeOffset"/> to a string.
            /// </summary>
            /// <param name="dateTimeOffset">The nullable DateTimeOffset instance to convert.</param>
            /// <returns>The string version of the DateTimeOffset, or null if the object is null.</returns>
            private static string ToString(DateTimeOffset? dateTimeOffset)
            {
                return dateTimeOffset.HasValue ? dateTimeOffset.Value.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture) : null;
            }

            /// <summary>
            /// Converts a given nullable integer to a string
            /// </summary>
            /// <param name="nullableInteger">The nullable integer to convert.</param>
            /// <returns>The string version of the integer, or null if the integer is null.</returns>
            private static string ToString(int? nullableInteger)
            {
                return nullableInteger.HasValue ? nullableInteger.ToString() : null;
            }
        }
    }
}


text:
package org.wso2.andes.amqp;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.andes.AMQException;
import org.wso2.andes.AMQInternalException;
import org.wso2.andes.exchange.ExchangeDefaults;
import org.wso2.andes.framing.AMQShortString;
import org.wso2.andes.framing.FieldTable;
import org.wso2.andes.kernel.*;
import org.wso2.andes.protocol.AMQConstant;
import org.wso2.andes.server.ClusterResourceHolder;
import org.wso2.andes.server.binding.Binding;
import org.wso2.andes.server.cassandra.AndesSubscriptionManager;
import org.wso2.andes.server.cassandra.QueueBrowserDeliveryWorker;
import org.wso2.andes.server.exchange.Exchange;
import org.wso2.andes.server.exchange.ExchangeRegistry;
import org.wso2.andes.server.message.AMQMessage;
import org.wso2.andes.server.queue.AMQQueue;
import org.wso2.andes.server.queue.IncomingMessage;
import org.wso2.andes.server.stats.PerformanceCounter;
import org.wso2.andes.server.store.StorableMessageMetaData;
import org.wso2.andes.server.subscription.Subscription;
import org.wso2.andes.server.subscription.SubscriptionImpl;
import org.wso2.andes.server.virtualhost.VirtualHost;
import org.wso2.andes.subscription.SubscriptionStore;

import java.nio.ByteBuffer;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

public class QpidAMQPBridge {

    private static Log log = LogFactory.getLog(QpidAMQPBridge.class);
    private static QpidAMQPBridge qpidAMQPBridge = null;
    /**
     * Following used by a performance counter
     */
    private static AtomicLong receivedMessageCounter = new AtomicLong();
    private static long last10kMessageReceivedTimestamp = System.currentTimeMillis();

    public static synchronized QpidAMQPBridge getInstance() {
        if(qpidAMQPBridge == null){
            qpidAMQPBridge = new QpidAMQPBridge();
        }
        return qpidAMQPBridge;
    }

    public void messageMetaDataReceived(IncomingMessage incomingMessage, int channelID) throws AMQException {
        try {
            //log.info("METADATA RECEIVED ID " + incomingMessage.getMessageNumber());
            AMQMessage message = new AMQMessage(incomingMessage.getStoredMessage());
            AndesMessageMetadata metadata = AMQPUtils.convertAMQMessageToAndesMetadata(message);
            String queue = message.getRoutingKey();

            if (queue == null) {
                log.error("Queue cannot be null, for " + incomingMessage.getMessageNumber());
            }

            MessagingEngine.getInstance().messageReceived(metadata, channelID);

            PerformanceCounter.recordMessageReceived(queue, incomingMessage.getReceivedChunkCount());
        } catch (AndesException e) {
            throw new AMQException(AMQConstant.INTERNAL_ERROR, "Error while storing incoming message metadata", e);
        }

        //Following code is only a performance counter
        Long localCount = receivedMessageCounter.incrementAndGet();
        if(localCount%10000 == 0){
            long timetook = System.currentTimeMillis() - last10kMessageReceivedTimestamp;
            log.info("Received " + localCount + ", throughput = " + (10000*1000/timetook) + " msg/sec, " + timetook);
            last10kMessageReceivedTimestamp = System.currentTimeMillis();
        }

    }

    public StorableMessageMetaData getMessageMetaData(long messageID) throws AMQException{
        StorableMessageMetaData metaData = null;
        try {
            metaData = AMQPUtils.convertAndesMetadataToAMQMetadata
                    (MessagingEngine.getInstance().getMessageMetaData(messageID));
        } catch (AndesException e) {
            log.error("Error in getting meta data for messageID", e);
            throw new AMQException(AMQConstant.INTERNAL_ERROR,"Error in getting meta data for messageID " + messageID, e);
        }
        return metaData;
    }

    public void messageContentChunkReceived(long messageID,  int offsetInMessage, ByteBuffer src) {

        log.debug("CONTENT PART RECEIVED ID " + messageID + " OFFSET " + offsetInMessage);
        AndesMessagePart part = new AndesMessagePart();
        src = src.slice();
        final byte[] chunkData = new byte[src.limit()];

        src.duplicate().get(chunkData);

        part.setData(chunkData);
        part.setMessageID(messageID);
        part.setOffSet(offsetInMessage);
        part.setDataLength(chunkData.length);

        MessagingEngine.getInstance().messageContentReceived(part);
    }

    public int getMessageContentChunk(long messageID, int offsetInMessage, ByteBuffer dst) throws AMQException{
        int contentLenWritten = 0;
        try {
            contentLenWritten = AMQPUtils.getMessageContentChunkConvertedCorrectly(messageID, offsetInMessage, dst);
        } catch (AndesException e) {
            log.error("Error in getting message content", e);
            throw new AMQException(AMQConstant.INTERNAL_ERROR,"Error in getting message content chunk messageID " + messageID + " offset=" + offsetInMessage, e);
        }
        return contentLenWritten;
    }

    public void createAMQPSubscription(Subscription subscription, AMQQueue queue) throws AMQException {
        try {
            log.info("===Andes Bridge: createAMQPSubscription subID " + subscription.getSubscriptionID() + " from queue " + queue.getName());
            addLocalSubscriptionsForAllBindingsOfQueue(queue, subscription);

            if (subscription instanceof SubscriptionImpl.BrowserSubscription) {
                boolean isInMemoryMode = ClusterResourceHolder.getInstance().getClusterConfiguration().isInMemoryMode();
                QueueBrowserDeliveryWorker deliveryWorker = new QueueBrowserDeliveryWorker(subscription, queue, ((SubscriptionImpl.BrowserSubscription) subscription).getProtocolSession(), isInMemoryMode);
                deliveryWorker.send();
            } else {
                log.info("Binding Subscription " + subscription.getSubscriptionID() + " to queue " + queue.getName());
            }
        } catch (AndesException e) {
            log.error("Error while adding the subscription", e);
            throw new AMQException(AMQConstant.INTERNAL_ERROR, "Error while registering subscription", e);
        }
    }

    public void closeAMQPSubscription(AMQQueue queue, Subscription subscription) throws AndesException{
        log.info("===Andes Bridge: closeAMQPSubscription subID " + subscription.getSubscriptionID() + " from queue " + queue.getName());
        closeLocalSubscriptionsForAllBindingsOfQueue(queue, subscription);
    }

    public void createExchange(Exchange exchange) throws AMQException{
        log.info("===Andes Bridge: createExchange" + exchange.getName());
/*        try {
            AndesSubscriptionManager subManager = ClusterResourceHolder.getInstance().getSubscriptionManager();
            LocalSubscription sub = AMQPUtils.createInactiveLocalSubscriberRepresentingExchange(exchange);
            subManager.addSubscription(sub);
        } catch (AndesException e) {
            log.error("error while creating exchange", e);
            throw new AMQException(AMQConstant.INTERNAL_ERROR,"error while creating exchange",e);
        }*/
    }

    public void deleteExchange(Exchange exchange) throws AMQException{
        log.info("===Andes Bridge: deleteExchange " + exchange.getName());
        try {
            AndesExchange andesExchange = new AndesExchange(exchange.getName(), exchange.getType().getName().toString(),
                    exchange.isAutoDelete() ? Short.parseShort("1") : Short.parseShort("0"));
            ClusterResourceHolder.getInstance().getSubscriptionManager().deleteSubscriptionsRepresentingExchange(andesExchange);
        } catch (AndesException e) {
            log.error("error while deleting exchange", e);
            throw new AMQException(AMQConstant.INTERNAL_ERROR,"error while deleting exchange",e);
        }
    }

    public void createQueue(AMQQueue queue) throws AMQException {
        log.info("===Andes Bridge create queue: " + queue.getName());
        try {
            AndesSubscriptionManager subManager = ClusterResourceHolder.getInstance().getSubscriptionManager();
            subManager.addSubscription(AMQPUtils.createInactiveLocalSubscriberRepresentingQueue(queue));
        } catch (AndesException e) {
            log.error("error while creating queue", e);
            throw new AMQException(AMQConstant.INTERNAL_ERROR,"error while creating queue",e);
        }
    }

    public void deleteQueue(AMQQueue queue) throws AMQException {
        log.info("Andes Bridge delete queue : " + queue.getName());
        try {
            ClusterResourceHolder.getInstance().getSubscriptionManager().removeSubscriptionsRepresentingQueue(queue.getName(),queue.isExclusive());

        } catch (AndesException e) {
            log.error("error while removing queue", e);
            throw new AMQException(AMQConstant.INTERNAL_ERROR,"error while removing queue",e);
        }
    }

    public void createBinding(Exchange exchange, AMQShortString routingKey,
                              AMQQueue queue, FieldTable args) throws AMQInternalException {
        log.info("===Andes Bridge createBinding exchange=" + exchange.getName() + " routingKey=" + routingKey + " queue=" + queue.getName());
        //todo:we create bindings for the whole queue's bindings at once. This is not needed
/*        try {
            LocalSubscription sub = AMQPUtils.createAMQPLocalSubscriptionRepresentingBinding(exchange, queue, routingKey);
            ClusterResourceHolder.getInstance().getSubscriptionManager().addSubscription(sub);
        } catch (AndesException e) {
            log.error("error while creating binding", e);
        }*/
    }

    public void removeBinding(Binding b, VirtualHost virtualHost) throws AndesException {
        log.info("===Andes Bridge removeBinding binding key: " + b.getBindingKey() + " queue: " + b.getQueue().getName());
        SubscriptionStore subscriptionStore = AndesContext.getInstance().getSubscriptionStore();
        //todo - hasitha - why queue bindings not removed??
        if(b.getExchange().getName().equalsIgnoreCase("amq.topic")) {

            //we remove bindings irrespective of temp or durable
            ClusterResourceHolder.getInstance().getSubscriptionManager().removeAllSubscriptionsRepresentingBinding
                    (b.getBindingKey(), b.getQueue().getName());

            //stop Topic Delivery Worker If Having No actual normal (not durable) topic subscriptions on this node
            if(ClusterResourceHolder.getInstance().getTopicDeliveryWorker() != null) {
                ExchangeRegistry exchangeRegistry = virtualHost.getExchangeRegistry();
                Exchange exchange = exchangeRegistry.getExchange(ExchangeDefaults.TOPIC_EXCHANGE_NAME);
                boolean havingNormalTopicSubscriptions = false;
                for(Binding binding: exchange.getBindings()){
                    if(!binding.isDurable()) {
                        havingNormalTopicSubscriptions = true;
                        break;
                    }
                }
                if(!havingNormalTopicSubscriptions) {
                    ClusterResourceHolder.getInstance().getTopicDeliveryWorker().stopWorking();
                }
            }
        }
        System.out.println("Removed Local Binding:  binding key: " + b.getBindingKey() + " queue:" + b.getQueue().getName());

    }

    /**
     * create local subscriptions and add for every binding of the queue
     * @param queue AMQ queue
     * @param subscription subscription
     * @throws AndesException
     */
    private void addLocalSubscriptionsForAllBindingsOfQueue(AMQQueue queue, Subscription subscription) throws AndesException {
        AndesSubscriptionManager subscriptionManager = ClusterResourceHolder.
                getInstance().getSubscriptionManager();

        List<Binding> bindingList = queue.getBindings();
        if (bindingList != null && !bindingList.isEmpty())

        /**
         * Iterate bindings of the queue and add subscription entries. We need to do this because of the flat
         * subscription model we have
         */
            for (Binding b : bindingList) {

                LocalSubscription localSubscription = AMQPUtils.createAMQPLocalSubscription(queue, subscription, b);
                subscriptionManager.addSubscription(localSubscription);

            }
    }

    private void closeLocalSubscriptionsForAllBindingsOfQueue(AMQQueue queue, Subscription subscription) throws AndesException {
        AndesSubscriptionManager subscriptionManager = ClusterResourceHolder.
                getInstance().getSubscriptionManager();
        List<Binding> bindingList = queue.getBindings();
        if (bindingList != null && !bindingList.isEmpty())

        /**
         * Iterate bindings of the queue and add subscription entries. We need to do this because of the flat
         * subscription model we have
         */
            for (Binding b : bindingList) {
                LocalSubscription localSubscription = AMQPUtils.createAMQPLocalSubscription(queue, subscription, b);
                subscriptionManager.closeSubscription(localSubscription);
            }
    }

}


text:
using System;

namespace Cake.Process
{
    /// <summary>
    ///     The event args that contains information about the line of text written to either
    ///     StandardOutputStream or StandardErrorStream on the created process.
    /// </summary>
    public class ProcessOutputReceivedEventArgs : EventArgs
    {
        /// <summary>
        ///     Initializes a new instance of the <see cref="ProcessOutputReceivedEventArgs" /> class.
        /// </summary>
        /// <param name="output">The Output.</param>
        public ProcessOutputReceivedEventArgs(string output)
        {
            Output = output;
        }

        /// <summary>
        ///     Gets the line of text written to StandardOutputStream / StandardErrorStream.
        /// </summary>
        /// <value>
        ///     The Output.
        /// </value>
        public string Output { get; private set; }
    }
}


text:
package com.feedilicious.integration.model;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "payload")
public class Payload {

    private Company company;
    private Order order;
    private String editionCode;
    private Account account;
    private Notice notice;

    public Company getCompany() {
        return company;
    }

    public void setCompany(Company company) {
        this.company = company;
    }

    public Order getOrder() {
        return order;
    }

    public void setOrder(Order order) {
        this.order = order;
    }

    public String getEditionCode() {
        return editionCode;
    }

    public void setEditionCode(String editionCode) {
        this.editionCode = editionCode;
    }

    public Account getAccount() {
        return account;
    }

    public void setAccount(Account account) {
        this.account = account;
    }

    public Notice getNotice() {
        return notice;
    }

    public void setNotice(Notice notice) {
        this.notice = notice;
    }
}


text:
package io.rancher.service;

import io.rancher.base.Filters;
import io.rancher.base.TypeCollection;
import io.rancher.type.Setting;

import retrofit2.Call;
import retrofit2.Response;
import retrofit2.http.Body;
import retrofit2.http.DELETE;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.PUT;
import retrofit2.http.Path;
import retrofit2.http.QueryMap;

public interface SettingService {

  @GET("setting")
  Call<TypeCollection<Setting>> list();

  @GET("setting")
  Call<TypeCollection<Setting>> list(@QueryMap Filters filters);

  @GET("setting/{id}")
  Call<Setting> get(@Path("id") String id);

  @POST("setting")
  Call<Setting> create(@Body Setting setting);

  @PUT("setting/{id}")
  Call<Setting> update(@Path("id") String id, @Body Setting setting);

  @DELETE("setting/{id}")
  Call<Response> delete(@Path("id") String id);

}


text:
function usage {
  echo "Usage: bisect.sh [opts]" >&2
  echo "Options:" >&2
  echo "    -t testname    Name of regression test to run" >&2
  echo "    -p dirname     Path to regression test to run" >&2
  echo "    -s             Unstash/Stash when performing a run" >&2
  echo "    -n             No decisive output means bad revision" >&2
  echo "    -T num_secs    Test taking more than num_secs means failure" >&2
  echo "You must specify either -t or -p."
}

searchpath=-1
beatstash=0
nooutputisfail=0
dirpath=""
numsecs=0
while getopts "t:p:sT:" opt; do
  case $opt in
    t)
      testname=$OPTARG
      searchpath=1
      ;;
    p)
      searchpath=0
      dirpath=$OPTARG
      ;;
    s)
      beatstash=1
      ;;
    n)
      nooutputisfail=1
      ;;
    T)
      numsecs=$OPTARG
      ;;
    \?)
      echo "Invalid option -$OPTARG" >&2
      exit 1
      ;;
    :)
      echo "Option -$OPTARG requires argument" >&2
      exit 1
      ;;
  esac
done

if test $searchpath = -1; then
  echo "You must specify -t or -p" >&2
  exit -1
fi

# Assume we're run from project root
ESBMCDIR=`pwd`

if test $beatstash = 1; then
  git stash pop > /dev/null 2>&1
  if test $? != 0; then
    echo "Git stash pop failed" >&2
    exit -1
  fi
fi

function restash () {
  if test $beatstash = 1; then
    git stash > /dev/null 2>&1
    if test $? != 0; then
      echo "Git stash failed" >&2
      exit -1
    fi
  fi
}

# To build: make clean, make.
make clean > /dev/null 2>/dev/null
make > /dev/null 2>/dev/null
# Make twice to ensure z3 objects propagate; due to ancient dependancy faults.
make > /dev/null 2>/dev/null

# If the build failed, curses.
if test $? != 0; then
  echo "Failed to build this rev" >&2
  restash
  make clean > /dev/null 2>/dev/null
  exit 125 # untestable
fi

# Otherwise, find the test we'll be testing.
if test $searchpath = 1; then
  cd regression
  stat esbmc/$testname >/dev/null 2>&1
  if test $? = 0; then
    cd esbmc/$testname
  else
    stat esbmc-pt/$testname > /dev/null 2>&1
    if test $? = 0; then
      cd esbmc-pt/$testname
    else
      stat esbmc-cpp/$testname > /dev/null 2>&1
      if test $? != 0; then
        echo "Can't find $testname" >&2
        restash
        exit -1
      fi
      cd esbmc-cpp/$testname
    fi
  fi
else
  cd $dirpath
fi

counter=0
args=""
declare -a regexarr
data=`cat test.desc`
while read line
do
  if test $counter -lt 2; then
    args="$args $line"
  else
    regexarr[$(($counter-2))]="$line"
  fi
  counter=$(($counter+1))
done < test.desc

# Search the array of regexes we have for what we're looking for, success or
# failure.
success=0;
failure=0;
winregex='^VERIFICATION SUCCESSFUL$'
failregex='^VERIFICATION FAILED$'
for regexp in "${regexarr[@]}"
do
  if test "$regexp" = "$winregex"; then
    success=1;
    rightregex=$winregex
    wrongregex=$failregex
  fi
  if test "$regexp" = "$failregex"; then
    failure=1;
    rightregex=$failregex
    wrongregex=$winregex
  fi
done

if test $success = 1 -a $failure = 1; then
  echo "Test desc file matches both success and failure" >&2
  restash
  exit -1
fi

if test $success = 0 -a $failure = 0; then
  echo "Test desc file matches neither success nor failure in verification" >&2
  restash
  exit -1
fi

# Potentially run with a timeout
alarm() { perl -e 'sleep shift; exec @ARGV' "$@" &  }

alarmed_exit() {
  echo "Timed out" >&2
  kill -9 $esbmcpid
  exit 1
}

trap alarmed_exit SIGINT

if test $numsecs != 0; then
  alarm $numsecs kill -s SIGINT $$
  alarmprocpid=$!
fi

# Actually run esbmc
tmpfile=`mktemp`
$ESBMCDIR/esbmc/esbmc $args > $tmpfile 2>&1 &
esbmcpid=$!

wait $esbmcpid

if test $numsecs != 0; then
  kill -9 $alarmprocpid
fi

# Sadly due to binaries in the tree, git bisect can complain if we don't clean
# immediately.
make clean > /dev/null 2>&1

restash

# Look for success
grep "$rightregex" $tmpfile
if test $? = 0; then
  rm $tmpfilet
  echo "Correct output" >&2
  exit 0 # success
fi

# Was opposite true?
grep "$wrongregex" $tmpfile
if test $? = 0; then
  rm $tmpfile
  echo "Wrong output" >&2
  exit 1 # Failure; wrong outcome
fi

# Otherwise, something crashed or went wrong.
rm $tmpfile
if test $nooutputisfail = 0; then
  echo "Noncommital output" >&2
  exit 125
else
  echo "Crash or abnormal exit" >&2
  exit 1
fi


text:
using Clang.cindex
using Base.Test

top = cindex.parse_header(joinpath(dirname(@__FILE__), "cxx/cxxbasic.h");
                          cplusplus = true)

funcs = cindex.search(top, "func")
@test length(funcs) == 1
f = funcs[1]

#@test map(spelling, cindex.function_args(f)) == ["Int", "Int"]
@test map(spelling, cindex.function_args(f)) == ["x", "y"]
@test isa(return_type(f), IntType)

defs = cindex.function_arg_defaults(f)
@test defs == (nothing, -10)

funcs = cindex.search(top, "func2")
@test length(funcs) == 1
f = funcs[1]

@test all(map(x->x.text, function_return_modifiers(f)) .== ["const", ])


text:
package org.apache.hadoop.hbase.io;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Collection;
import java.util.Comparator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicReference;

import org.apache.hadoop.conf.Configurable;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.util.ReflectionUtils;

/**
 * A Writable Map.
 * Like {@link org.apache.hadoop.io.MapWritable} but dumb. It will fail
 * if passed a value type that it has not already been told about. Its  been
 * primed with hbase Writables and byte [].  Keys are always byte arrays.
 *
 * @param <K> <byte []> key  TODO: Parameter K is never used, could be removed.
 * @param <V> value Expects a Writable or byte [].
 */
public class HbaseMapWritable <K,V>
implements SortedMap<byte[],V>, Configurable, Writable, CodeToClassAndBack{
  private AtomicReference<Configuration> conf = null;
  protected SortedMap<byte [], V> instance = null;

  /**
   * The default contructor where a TreeMap is used
   **/
   public HbaseMapWritable(){
     this (new TreeMap<byte [], V>(Bytes.BYTES_COMPARATOR));
   }

  /**
   * Contructor where another SortedMap can be used
   *
   * @param map the SortedMap to be used
   */
  public HbaseMapWritable(SortedMap<byte[], V> map){
    conf = new AtomicReference<Configuration>();
    instance = map;
  }

  /** @return the conf */
  public Configuration getConf() {
    return conf.get();
  }

  /** @param conf the conf to set */
  public void setConf(Configuration conf) {
    this.conf.set(conf);
  }

  public void clear() {
    instance.clear();
  }

  public boolean containsKey(Object key) {
    return instance.containsKey(key);
  }

  public boolean containsValue(Object value) {
    return instance.containsValue(value);
  }

  public Set<Entry<byte [], V>> entrySet() {
    return instance.entrySet();
  }

  public V get(Object key) {
    return instance.get(key);
  }

  public boolean isEmpty() {
    return instance.isEmpty();
  }

  public Set<byte []> keySet() {
    return instance.keySet();
  }

  public int size() {
    return instance.size();
  }

  public Collection<V> values() {
    return instance.values();
  }

  public void putAll(Map<? extends byte [], ? extends V> m) {
    this.instance.putAll(m);
  }

  public V remove(Object key) {
    return this.instance.remove(key);
  }

  public V put(byte [] key, V value) {
    return this.instance.put(key, value);
  }

  public Comparator<? super byte[]> comparator() {
    return this.instance.comparator();
  }

  public byte[] firstKey() {
    return this.instance.firstKey();
  }

  public SortedMap<byte[], V> headMap(byte[] toKey) {
    return this.instance.headMap(toKey);
  }

  public byte[] lastKey() {
    return this.instance.lastKey();
  }

  public SortedMap<byte[], V> subMap(byte[] fromKey, byte[] toKey) {
    return this.instance.subMap(fromKey, toKey);
  }

  public SortedMap<byte[], V> tailMap(byte[] fromKey) {
    return this.instance.tailMap(fromKey);
  }

  // Writable

  /** @return the Class class for the specified id */
  @SuppressWarnings("boxing")
  protected Class<?> getClass(byte id) {
    return CODE_TO_CLASS.get(id);
  }

  /** @return the id for the specified Class */
  @SuppressWarnings("boxing")
  protected byte getId(Class<?> clazz) {
    Byte b = CLASS_TO_CODE.get(clazz);
    if (b == null) {
      throw new NullPointerException("Nothing for : " + clazz);
    }
    return b;
  }

  /**
   * @see java.lang.Object#toString()
   */
  @Override
  public String toString() {
    return this.instance.toString();
  }

  public void write(DataOutput out) throws IOException {
    // Write out the number of entries in the map
    out.writeInt(this.instance.size());
    // Then write out each key/value pair
    for (Map.Entry<byte [], V> e: instance.entrySet()) {
      Bytes.writeByteArray(out, e.getKey());
      Byte id = getId(e.getValue().getClass());
      out.writeByte(id);
      Object value = e.getValue();
      if (value instanceof byte []) {
        Bytes.writeByteArray(out, (byte [])value);
      } else {
        ((Writable)value).write(out);
      }
    }
  }

  @SuppressWarnings("unchecked")
  public void readFields(DataInput in) throws IOException {
    // First clear the map.  Otherwise we will just accumulate
    // entries every time this method is called.
    this.instance.clear();
    // Read the number of entries in the map
    int entries = in.readInt();
    // Then read each key/value pair
    for (int i = 0; i < entries; i++) {
      byte [] key = Bytes.readByteArray(in);
      byte id = in.readByte();
      Class clazz = getClass(id);
      V value = null;
      if (clazz.equals(byte [].class)) {
        byte [] bytes = Bytes.readByteArray(in);
        value = (V)bytes;
      } else {
        Writable w = (Writable)ReflectionUtils.
          newInstance(clazz, getConf());
        w.readFields(in);
        value = (V)w;
      }
      this.instance.put(key, value);
    }
  }
}


text:
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2017 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------

namespace think\session\driver;

use SessionHandler;
use think\Exception;

class Redis extends SessionHandler
{
    /** @var \Redis */
    protected $handler = null;
    protected $config = [
        'host' => '127.0.0.1', // redis主机
        'port' => 6379, // redis端口
        'password' => '', // 密码
        'select' => 0, // 操作库
        'expire' => 3600, // 有效期(秒)
        'timeout' => 0, // 超时时间(秒)
        'persistent' => true, // 是否长连接
        'session_name' => '', // sessionkey前缀
    ];

    public function __construct($config = [])
    {
        $this->config = array_merge($this->config, $config);
    }

    /**
     * 打开Session
     * @access public
     * @param string $savePath
     * @param mixed $sessName
     * @return bool
     * @throws Exception
     */
    public function open($savePath, $sessName)
    {
        // 检测php环境
        if (!extension_loaded('redis')) {
            throw new Exception('not support:redis');
        }
        $this->handler = new \Redis;

        // 建立连接
        $func = $this->config['persistent'] ? 'pconnect' : 'connect';
        $this->handler->$func($this->config['host'], $this->config['port'], $this->config['timeout']);

        if ('' != $this->config['password']) {
            $this->handler->auth($this->config['password']);
        }

        if (0 != $this->config['select']) {
            $this->handler->select($this->config['select']);
        }

        return true;
    }

    /**
     * 关闭Session
     * @access public
     */
    public function close()
    {
        $this->gc(ini_get('session.gc_maxlifetime'));
        $this->handler->close();
        $this->handler = null;
        return true;
    }

    /**
     * 读取Session
     * @access public
     * @param string $sessID
     * @return string
     */
    public function read($sessID)
    {
        return (string)$this->handler->get($this->config['session_name'] . $sessID);
    }

    /**
     * 写入Session
     * @access public
     * @param string $sessID
     * @param String $sessData
     * @return bool
     */
    public function write($sessID, $sessData)
    {
        if ($this->config['expire'] > 0) {
            return $this->handler->setex($this->config['session_name'] . $sessID, $this->config['expire'], $sessData);
        } else {
            return $this->handler->set($this->config['session_name'] . $sessID, $sessData);
        }
    }

    /**
     * 删除Session
     * @access public
     * @param string $sessID
     * @return bool
     */
    public function destroy($sessID)
    {
        return $this->handler->delete($this->config['session_name'] . $sessID) > 0;
    }

    /**
     * Session 垃圾回收
     * @access public
     * @param string $sessMaxLifeTime
     * @return bool
     */
    public function gc($sessMaxLifeTime)
    {
        return true;
    }
}


text:
set -e

if [ -d /usr/local/apache-tomcat-7.0.42/blog ];
then
    echo "deleting old bisen folder "

    rm -rf /usr/local/apache-tomcat-7.0.42/blog
else
    echo "no old bisen folder to delete "
fi
echo "getting trunk from bisenorg @ github "

svn export --force https://github.com/bisenorg/blog/trunk  /usr/local/apache-tomcat-7.0.42/blog

echo "creating war file "

cd /usr/local/apache-tomcat-7.0.42/blog

mvn package -DskipTests=true

echo " stopping tomcat "
/bin/bash /usr/local/apache-tomcat-7.0.42/bin/shutdown.sh

if [ -d /usr/local/apache-tomcat-7.0.42/webapps/ROOT ];
then
    echo " removing ROOT "
    rm -rf /usr/local/apache-tomcat-7.0.42/webapps/ROOT
else
    echo "no ROOT folder to delete "
fi

if [ -d /usr/local/apache-tomcat-7.0.42/blog/target/bisen-blog-1.0-SNAPSHOT ];
then
    echo " moving bisen-blog-1.0-SNAPSHOT to ROOT "
    mv /usr/local/apache-tomcat-7.0.42/blog/target/bisen-blog-1.0-SNAPSHOT /usr/local/apache-tomcat-7.0.42/webapps/ROOT

    echo " starting tomcat "
    /bin/bash /usr/local/apache-tomcat-7.0.42/bin/startup.sh

    echo " all done"
else
    echo "no bisen-blog-1.0-SNAPSHOT found to move to ROOT "
fi


text:
package org.apache.camel.component.wordpress.api.model;

public abstract class ClassifierSearchCriteria extends SearchCriteria {

    private static final long serialVersionUID = -4265001661257396589L;

    private boolean hideEmpty;
    private Integer postId;
    private String slug;
    private Context context;

    public ClassifierSearchCriteria() {

    }

    public boolean isHideEmpty() {
        return hideEmpty;
    }

    public void setHideEmpty(boolean hideEmpty) {
        this.hideEmpty = hideEmpty;
    }

    public Integer getPostId() {
        return postId;
    }

    public void setPostId(Integer postId) {
        this.postId = postId;
    }

    public String getSlug() {
        return slug;
    }

    public void setSlug(String slug) {
        this.slug = slug;
    }

    public Context getContext() {
        return context;
    }

    public void setContext(Context context) {
        this.context = context;
    }

}


text:
You can expose a Model's instance and static methods to clients. A remote method must accept a callback with the conventional `fn(err, result, ...)` signature.

### loopback.remoteMethod(fn, [options])

Expose a remote method.

```js
Product.stats = function(fn) {
  var statsResult = {
    totalPurchased: 123456
  };
  var err = null;

  // callback with an error and the result
  fn(err, statsResult);
}

loopback.remoteMethod(
  Product.stats,
  {
    returns: {arg: 'stats', type: 'object'},
    http: {path: '/info', verb: 'get'}
  }
);
```

**Options**

The options argument is a JSON object, described in the following table.

| Option  | Required? | Description |
| ----- | ----- |  ----- |
| accepts   | No | Describes the remote method's arguments; See Argument description. The `callback` argument is assumed; do not specify. |
| returns    | No | Describes the remote method's callback arguments; See Argument description. The `err` argument is assumed; do not specify. |
| http | No | HTTP routing information:

 **http.path**: path (relative to the model) at which the method is exposed. May be a path fragment (for example, `/:myArg`) that will be populated by an arg of the same name in the `accepts` description. For example, the `stats` method above will be at the whole path `/products/stats`.

 **http.verb**: HTTP method  (verb) from which the method is available (one of: get, post, put, del, or all).

**Argument description**

The arguments description defines either a single argument as an object or an ordered set of arguments as an array.  Each individual argument has keys for:

 * arg: argument name
 * type: argument datatype; must be a [loopback type](http://wiki.strongloop.com/display/DOC/LoopBack+types).
 * required: Boolean value indicating if argument is required.
 * root: For callback arguments: set this property to `true` if your function
   has a single callback argument to use as the root object
   returned to remote caller. Otherwise the root object returned is a map (argument-name to argument-value).
 * http: For input arguments: a function or an object describing mapping from HTTP request
   to the argument value, as explained below.

For example, a single argument, specified as an object:

```js
{arg: 'myArg', type: 'number'}
```

Multiple arguments, specified as an array:

```js
[
  {arg: 'arg1', type: 'number', required: true},
  {arg: 'arg2', type: 'array'}
]
```

**HTTP mapping of input arguments**

There are two ways to specify HTTP mapping for input parameters (what the method accepts):

 * Provide an object with a `source` property
 * Specify a custom mapping function

To use the first way to specify HTTP mapping for input parameters, provide an object with a `source` property
that has one of the values shown in the following table.

| Value of source property | Description |
|---|---|
| body | The whole request body is used as the value. |
| form | The value is looked up using `req.param`, which searches route arguments, the request body and the query string.|
| query | An alias for form (see above). |
| path | An alias for form (see above). |
| req | The whole HTTP reqest object is used as the value. |

For example, an argument getting the whole request body as the value:

```js
{ arg: 'data', type: 'object', http: { source: 'body' } }
```

The use the second way to specify HTTP mapping for input parameters, specify a custom mapping function
that looks like this:

```js
{
  arg: 'custom',
  type: 'number',
  http: function(ctx) {
    // ctx is LoopBack Context object

    // 1. Get the HTTP request object as provided by Express
    var req = ctx.req;

    // 2. Get 'a' and 'b' from query string or form data
    // and return their sum as the value
    return +req.param('a') + req.param('b');
  }
}
```

If you don't specify a mapping, LoopBack will determine the value
as follows (assuming `name` as the name of the input parameter to resolve):

 1. If there is a HTTP request parameter `args` with a JSON content,
    then the value of `args['name']` is used if it is defined.
 2. Otherwise `req.param('name')` is returned.

## Remote hooks

Run a function before or after a remote method is called by a client.

```js
// *.save === prototype.save
User.beforeRemote('*.save', function(ctx, user, next) {
  if(ctx.user) {
    next();
  } else {
    next(new Error('must be logged in to update'))
  }
});

User.afterRemote('*.save', function(ctx, user, next) {
  console.log('user has been saved', user);
  next();
});
```

Remote hooks also support wildcards. Run a function before any remote method is called.

```js
// ** will match both prototype.* and *.*
User.beforeRemote('**', function(ctx, user, next) {
  console.log(ctx.methodString, 'was invoked remotely'); // users.prototype.save was invoked remotely
  next();
});
```

Other wildcard examples

```js
// run before any static method eg. User.find
User.beforeRemote('*', ...);

// run before any instance method eg. User.prototype.save
User.beforeRemote('prototype.*', ...);

// prevent password hashes from being sent to clients
User.afterRemote('**', function (ctx, user, next) {
  if(ctx.result) {
    if(Array.isArray(ctx.result)) {
      ctx.result.forEach(function (result) {
        result.password = undefined;
      });
    } else {
      ctx.result.password = undefined;
    }
  }

  next();
});
```

### Context

Remote hooks are provided with a Context `ctx` object which contains transport specific data (eg. for http: `req` and `res`). The `ctx` object also has a set of consistent apis across transports.

#### ctx.user

A `Model` representing the user calling the method remotely. **Note:** this is undefined if the remote method is not invoked by a logged in user.

#### ctx.result

During `afterRemote` hooks, `ctx.result` will contain the data about to be sent to a client. Modify this object to transform data before it is sent.

#### Rest

When [loopback.rest](#loopbackrest) is used the following `ctx` properties are available.

##### ctx.req

The express ServerRequest object. [See full documentation](http://expressjs.com/api.html#req).

##### ctx.res

The express ServerResponse object. [See full documentation](http://expressjs.com/api.html#res).


text:
最终版本和里程碑版本部署在 Maven Central.(Artifacts for final releases and milestones are deployed to Maven Central.)

快照版本部署在 Sonatype 的[快照仓库](https://oss.sonatype.org/content/repositories/snapshots)的 [/org/junit](https://oss.sonatype.org/content/repositories/snapshots/org/junit/) 路径下.


text:
Default About Page

                Use this page to describe who you are and what your website does.


text:
using System;

namespace Orleans.Runtime
{
    [Serializable]
    internal class Response
    {
        public bool ExceptionFlag { get; private set; }
        public Exception Exception { get; private set; }
        public object Data { get; private set; }

        public Response(object data)
        {
            switch (data)
            {
                case Exception exception:
                    Exception = exception;
                    ExceptionFlag = true;
                    break;
                default:
                    Data = data;
                    ExceptionFlag = false;
                    break;
            }
        }

        private Response()
        {
        }

        static public Response ExceptionResponse(Exception exc)
        {
            return new Response
            {
                ExceptionFlag = true,
                Exception = exc
            };
        }

        public override string ToString()
        {
            if (ExceptionFlag)
            {
                return $"Response Exception={Exception}";
            }

            return $"Response Data={Data}";
        }
    }
}


text:
class PropertiesObject
  def initialize(props)
    props.each do |p|
      name = p[:@name]
      value = p[:@value]
      self.singleton_class.send(:attr_accessor, name.to_sym)
      self.send("#{name}=", value)
    end
  end
end

# In cases were there maybe one or more sub-elements of an element, this makes sure
# that it is consistent.
def ensure_array_of_objects(obj)
  obj.is_a?(Array) ? obj : [ obj ]
end

class ArtifactDependency
  attr_accessor :clean_destination_directory, :path_rules, :exclusion_rules, :revision_name, :revision_value, :build_type, :revision_branch

  def initialize(build_type, props)
    @build_type = build_type
    @clean_destination_directory = false
    @path_rules = {}
    @exclusion_rules = {}
    props.each do |p|
      name = p[:@name]
      value = p[:@value]
      case name
        when 'cleanDestinationDirectory'
          @clean_destination_directory = value.to_bool
        when 'pathRules'
          value.split("\n").each do |line|
            if line =~ /^[+\-]:/
              (op,pattern) = line.split(':')
              pattern = pattern.delete("\n").delete("\r")
              @exclusion_rules[pattern] = op
            else
              (src,dst) = line.split('=>')
              if dst.nil?
                @path_rules[src.strip] = ''
              else
                @path_rules[src.strip] = dst.strip
              end
            end
          end
        else
          self.send("#{name.snakecase}=", value)
      end
    end
  end

  def use_tagged_build(build_id)
    @revision_name = "tcbuildid"
    @revision_value = "#{build_id}.tcbuildid"
  end
end

class ArtifactDependencies
  attr_accessor :dependencies
  def initialize(xml)
    @dependencies = []
    parser = Nori.new(:convert_tags_to => lambda { |tag| tag.snakecase.to_sym })
    deps = ensure_array_of_objects( parser.parse(xml)[:artifact_dependencies][:artifact_dependency])
    deps.each do |d|
      props = d[:properties][:property]
      build_type = d[:source_build_type][:@id]
      disabled = d[:@disabled]
      unless disabled
        obj = ArtifactDependency.new(build_type, props)
        @dependencies.push(obj)
      end
    end
  end
end

class TeamCityProjects
  attr_reader :ids, :names
  def initialize(xml)
    @ids = {}
    @names = {}
    parser = Nori.new(:convert_tags_to => lambda { |tag| tag.snakecase.to_sym })
    projects = parser.parse(xml)[:projects][:project]
    projects.each do |p|
      name = p[:@name]
      id = p[:@id]
      @ids[name] = id
      @names[id] = name
    end
  end
end

class TeamCityBuilds
  attr_reader :ids, :names
  def initialize(xml)
    @ids = {}
    @names = {}
    parser = Nori.new(:convert_tags_to => lambda { |tag| tag.snakecase.to_sym })
    builds = ensure_array_of_objects(parser.parse(xml)[:build_types][:build_type])
    builds.each do |p|
      name = p[:@name]
      id = p[:@id]
      @ids[name] = id
      @names[id] = name
    end
  end
end

class BuildType
  attr_reader :project_name, :build_name, :url, :vcs_root_id, :parameters, :settings
  def initialize(xml)
    parser = Nori.new(:convert_tags_to => lambda { |tag| tag.snakecase.to_sym })
    build = parser.parse(xml)[:build_type]
    @build_name = build[:@name]
    @url = build[:@web_url]
    @project_name = build[:project][:@name]
    @parameters = get_properties(build[:parameters])
    @settings = get_properties(build[:settings])

    def artifacts
      result = []
      rules = @settings['artifactRules']
      unless rules.nil?
        results = rules.split("\n")
      end
    end
    begin
      @vcs_root_id = build[:vcs_root_entries][:vcs_root_entry][:@id]
    rescue
      verbose("Note: No VCS Root defined for project=#{@project_name}, build_name=#{@build_name}")
    end
  end
  def get_properties(container)
    properties = {}
    begin
      props = container[:property]
      props.each do |p|
        name = p[:@name]
        value = p[:@value]
        properties[name] = value
      end
    rescue
      # No properties
    end
    properties
  end
  def resolve(str)
    if str =~ /%[^%]+%/
      key = str.gsub(/%/,'')
      str = @parameters[key]
    end
    str
  end
end

class VCSRoot
  attr_reader :repository_path, :branch_name
  def initialize(xml)
    parser = Nori.new(:convert_tags_to => lambda { |tag| tag.snakecase.to_sym })
    props = parser.parse(xml)[:vcs_root][:properties][:property]
    props.each do |p|
      name = p[:@name]
      value = p[:@value]
      case name
        when 'url'
          @repository_path = value
        when 'branch'
          @branch_name = value
        when 'repositoryPath'
          @repository_path = value
        when 'branchName'
          @branch_name = value
        else
          # ignore these
      end
    end
  end

end

class IvyArtifacts
  attr_reader :artifacts
  def initialize(xml)
    @artifacts = []
    parser = Nori.new(:convert_tags_to => lambda { |tag| tag.snakecase.to_sym })
    artifacts = ensure_array_of_objects(parser.parse(xml)[:ivy_module][:publications][:artifact])
    artifacts.each do |a|
      @artifacts.push("#{a[:@name]}.#{a[:@ext]}")
    end
  end
end

class Builds
  attr_reader :build_ids
  def initialize(xml)
    @build_ids = []
    parser = Nori.new(:convert_tags_to => lambda { |tag| tag.snakecase.to_sym})
    builds =  ensure_array_of_objects(parser.parse(xml)[:builds][:build])
    builds.each do |b|
      @build_ids.push(b[:@id])
    end
  end
end

class BuildDependency
  attr_reader :build_id, :build_type
  def initialize(build_id, build_type)
    @build_id = build_id
    @build_type = build_type
  end
end

class Build
  attr_reader :build_id, :dependencies
  def initialize(xml)
    @dependencies = []
    parser = Nori.new(:convert_tags_to => lambda { |tag| tag.snakecase.to_sym})
    build = parser.parse(xml)[:build]
    @build_id = build[:@id]
    dependencies = build[:artifact_dependencies][:build]
    dependencies.each do |d|
      @dependencies.push(BuildDependency.new(d[:@id], d[:@build_type_id]))
    end
  end
end


text:
from biohub.core.routes import register_api, url

from .models import AnotherModel

from rest_framework.response import Response
from rest_framework.decorators import api_view

register_api(r'^another_plugin/', [
    url(r'^$', api_view(['GET'])(
        lambda r: Response(list(AnotherModel.objects.all()))), name='index')
], namespace='another')


text:
html, body
{
    height: 100%;
}
.navbar-brand{
	padding: 0px;
}

#main{
	min-height: 100%;
	//background: green;
}

#navbar{
	padding:0px;
}
#navbarLogin{
	margin-top: 6px;
}

.activeTestOptions {
	background: #ccc;
	color:red !important;
}

.allow-drow {
	text-align: center;
	button {
		margin: 0 auto;
		height: 30px;
		padding: 0px 20px;
	}
}

.modal-lg {
	margin: 0 5%;
	width: 90%;
}

#body{
	padding-top: 100px;
}

#id{
	  text-align: center;
	color: red;
	margin:0 auto;
}

#login, th{
	text-align: center;
	color: blue;
	margin:0 auto;
}
#loginpanel{border-color: green;}
.help-block{
	color: red;
}

/*User*/
#selectedUserList{
	max-height: 220px;
	border-color: green;
	overflow-y:scroll;
}
::-webkit-scrollbar {
    //display: none;
}

#userTD{
	width: 50% !important;
}
#userlistUsernameInput{
	padding-top: 4px;
	background: #ccc;
	width: 95%;
	height: 30px;
}
#userlistUsernameInputDelete{
	padding-top: 4px;
	height: 30px;
}

/* User account */
#navbaruserinside{height: 40px;}
#userActivityWall{min-height:450px;border-color: green;}
#userwall{padding: 8px 25px;}
#usernavbar{
	margin-top: -40px;
	margin-bottom: -30px;
	background: rgb(83,154,169);  /* Magic color */
}
#usercollapsbutton{
	background: rgb(83,183,235);
	margin-top: 15px;
	margin-right: 28px;

}

#usercollapsa > .open > a, #usercollapsa > .open > a:hover, #usercollapsa > .open > a:focus {
	color: #555555;
	background-color: rgb(63,134,149);
}
#usercollapsa > li > a{color: white;}
#usercollapsa > li > a:hover{color: black;}
#googleMap{width:100%;height:350px;border:1px dotted green;}
#mapDefaultPlace > div{height:350px;border:1px dotted green;}

.full-screen {margin: 0px !important;}
.full-screen > div > button {background: #fff !important; border: 1px dotted green; padding: 5px 10px !important; height: 28px !important; border-radius: 5px;}
.full-screen > div > button:hover {color: red !important;}

//#mapModalPlace > #map-canvas{width: 90%; height: 500px;}

/* Creating new Account */
#createAccount{
	//background: white;
	//padding-left: 20px;
	max-width: 300px;
}
#createAccauntpanel{border-color: green;}

/* Users Events    */
.selectedMyOwnEvents{background: rgb(83,154,169);}
#userOwnEventsList{height: 200px;border-color: green;overflow:scroll;}
#map-canvas-showTrip{height:250px;border:1px dotted green;}

footer {
	background: #333;
	color: #eee;
	font-size: 11px;
	padding: 20px;
}

.b-tree {
	position: relative;
}
.b-tree .dropdown-menu {
}

.b-tree-data {

}

.tree-row {
	padding: 10px;
	margin: 10px;
	text-align: center;
}

.tree-row .tree-node {
	border: 1px solid green;
	padding: 5px;
	margin: 5px;
}
.tree-row .tree-node span {
	border: 1px solid #CFCFCF;
	border-radius: 2px;
	padding: 2px 5px;
}

.tree-row .row-index {
	float: left;
}


text:
package com.amazonaws.services.inspector2.model.transform;

import java.util.List;
import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.inspector2.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * AwsEcrContainerImageDetailsMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class AwsEcrContainerImageDetailsMarshaller {

    private static final MarshallingInfo<String> ARCHITECTURE_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("architecture").build();
    private static final MarshallingInfo<String> AUTHOR_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("author").build();
    private static final MarshallingInfo<String> IMAGEHASH_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("imageHash").build();
    private static final MarshallingInfo<List> IMAGETAGS_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("imageTags").build();
    private static final MarshallingInfo<String> PLATFORM_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("platform").build();
    private static final MarshallingInfo<java.util.Date> PUSHEDAT_BINDING = MarshallingInfo.builder(MarshallingType.DATE)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("pushedAt").timestampFormat("unixTimestamp").build();
    private static final MarshallingInfo<String> REGISTRY_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("registry").build();
    private static final MarshallingInfo<String> REPOSITORYNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("repositoryName").build();

    private static final AwsEcrContainerImageDetailsMarshaller instance = new AwsEcrContainerImageDetailsMarshaller();

    public static AwsEcrContainerImageDetailsMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(AwsEcrContainerImageDetails awsEcrContainerImageDetails, ProtocolMarshaller protocolMarshaller) {

        if (awsEcrContainerImageDetails == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(awsEcrContainerImageDetails.getArchitecture(), ARCHITECTURE_BINDING);
            protocolMarshaller.marshall(awsEcrContainerImageDetails.getAuthor(), AUTHOR_BINDING);
            protocolMarshaller.marshall(awsEcrContainerImageDetails.getImageHash(), IMAGEHASH_BINDING);
            protocolMarshaller.marshall(awsEcrContainerImageDetails.getImageTags(), IMAGETAGS_BINDING);
            protocolMarshaller.marshall(awsEcrContainerImageDetails.getPlatform(), PLATFORM_BINDING);
            protocolMarshaller.marshall(awsEcrContainerImageDetails.getPushedAt(), PUSHEDAT_BINDING);
            protocolMarshaller.marshall(awsEcrContainerImageDetails.getRegistry(), REGISTRY_BINDING);
            protocolMarshaller.marshall(awsEcrContainerImageDetails.getRepositoryName(), REPOSITORYNAME_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
var File = require('vinyl');
var fs = require('fs');

module.exports = new File({
  cwd: process.cwd(),
  base: 'test/fixtures',
  path: 'test/fixtures/example.md',
  contents: fs.readFileSync('test/fixtures/example.md')
});


text:
<?php

class Dashboard extends Eloquent {

	protected $connection = 'mysql2';
	protected $table = 'cch_info';

    private function getProperty($property)
    {
        $v = DB::connection('mysql2')->table('cch_info')
                    ->where('property', $property)
                    ->pluck('value');
        return $v;
    }

    public function lastRefreshDate()
    {
        return $this->getProperty('last_refresh_date');
    }

    public function projectLength($percentage=false)
    {
        $today = date('Y-m-d');
        $prsd = $this->getProperty('project_start_date');
        $prlm = $this->getProperty('project_length_in_months');

        return ($percentage)
             ? round($this->DateDiff($prsd, $today, 'months') / $prlm,2) * 100
             : $this->DateDiff($prsd, $today, 'months');
    }

    public function numDistricts($percentage=false)
    {
        $l = new Facility;
        $c = $l->districtCount();

        return ($percentage)
            ? round($c / $this->getProperty('num_ghana_districts'),2) * 100
            : $c;
    }

    public function numFacilities($percentage=false)
    {
        $l = new Facility;
        $c = $l->facilityCount();

        return ($percentage)
            ? round($c / $this->getProperty('num_ghana_facilities'),2) * 100
            : $c;
    }

    public function numNurses($percentage=false)
    {
        $s = new User;
        $c = $s->nurseCount();

        return ($percentage)
            ? round($c / $this->getProperty('num_ghana_nurses'),2) * 100
            : $c;
    }

    public function moduleUsage($params=null)
    {
        $data = array();

        $where = Dashboard::buildWhere($params);

        $d =  DB::connection('mysql2')->table('moduleusage')
                        ->select(DB::raw('module, CEILING(sum(mins_spent)) as timespent'))
                        ->whereRaw($where)
                        ->whereRaw('module in ("Achievement Center","Event Planner","Learning Center","Point of Care","Staying Well")')
                        ->groupBy('module')
                        ->orderBy('module')
                        ->get();

        foreach($d as $p) { $data[$p->module] = round($p->timespent / 3600,2); }

        return $data;
    }

    public function moduleUsageBySection($params=null)
    {
        $data = array('Achievement Center'=>array(),
                      'Event Planner'=>array(),
                      'Learning Center'=>array(),
                      'Point of Care'=>array(),
                      'Staying Well'=>array());

        $where = Dashboard::buildWhere($params);

        $d =  DB::connection('mysql2')->table('moduleusage')
                        ->select(DB::raw('module, "Main Page" as section, CEILING(sum(mins_spent)) as timespent'))
                        ->whereRaw($where)
                        ->whereRaw('module in ("Achievement Center","Event Planner")')
                        ->groupBy('module')
                        ->groupBy('section')
                        ->orderBy('section')
                        ->get();
        foreach($d as $p) { array_push($data[$p->module], array($p->section, round($p->timespent/3600,2))); }

        $d =  DB::connection('mysql2')->table('pointofcare')
                        ->select(DB::raw('"Point of Care" as module, section, CEILING(sum(mins_spent)) as timespent'))
                        ->whereRaw($where)
                        ->groupBy('module')
                        ->groupBy('section')
                        ->orderBy('section')
                        ->get();
        foreach($d as $p) { array_push($data[$p->module], array($p->section, round($p->timespent/3600,2))); }

        $d =  DB::connection('mysql2')->table('learningcenter_access')
                        ->select(DB::raw('"Learning Center" as module, section, CEILING(sum(mins_spent)) as timespent'))
                        ->whereRaw($where)
                        ->groupBy('module')
                        ->groupBy('section')
                        ->orderBy('section')
                        ->get();
        foreach($d as $p) { array_push($data[$p->module], array($p->section, round($p->timespent/3600,2))); }

        $d =  DB::connection('mysql2')->table('stayingwell')
                        ->select(DB::raw('"Staying Well" as module, section, CEILING(sum(mins_spent)) as timespent'))
                        ->whereRaw($where)
                        ->groupBy('module')
                        ->groupBy('section')
                        ->orderBy('section')
                        ->get();
        foreach($d as $p) { array_push($data[$p->module], array($p->section, round($p->timespent/3600,2))); }

        return $data;
    }

    /*** Staying Well **/
    public function swPlans($params=null)
    {
        $data = array();

        $where = Dashboard::buildWhere($params);

        $d =  DB::connection('mysql2')->table('stayingwell_plans')
                        ->select(DB::raw('plan, COUNT(nurseid) as c'))
                        ->whereRaw($where)
                        ->groupBy('plan')
                        ->orderBy('plan')
                        ->get();

        foreach($d as $p) { $data[ucfirst($p->plan)] = $p->c; }

        return $data;
    }

    public function swPlansByProfile($params=null)
    {
        $data = array('Appearance'=>array(),
                      'Strength'=>array(),
                      'Michael'=>array());

        $where = Dashboard::buildWhere($params);

        $d =  DB::connection('mysql2')->table('stayingwell_plans')
                        ->select(DB::raw('plan, profile, COUNT(nurseid) as c'))
                        ->whereRaw($where)
                        ->groupBy('plan')
                        ->groupBy('profile')
                        ->orderBy('profile')
                        ->get();

        foreach($d as $p) {
            if (in_array(ucfirst($p->plan), array_keys($data))) {
                array_push($data[ucfirst($p->plan)], array(ucfirst($p->profile), $p->c));
            }

        }

        return $data;
    }

    /*** End Staying well **/

    protected function makePercentage($data)
    {
        $total = 0;
        foreach($data as $c) { $total += $c; }
        foreach($data as $k => $c) { $data[$k] = round($c/$total,2) * 100; }
        return $data;
    }

    /** HTML utility methods **/
    public function locationsForSelect()
    {
        $l = new Facility;
        return array('all'=>'All','Regions'=>$l->regions(),
                     'Districts'=>$l->districts(),
                     'Facilities'=>$l->facilities());
    }

    /** Utility functions **/

    private function DateDiff($date1, $date2, $format='long')
    {
        $info = $this->dateDifference($date1, $date2);

        switch($format)
        {
          case 'years': $diff = $info[0]; break;
          case 'months': $diff = ($info[0]*12)+($info[1] + round($info[2] / 31,0)); break;
          case 'days': $diff = ($info[0]*365) + ($info[1]*30) + $info[2]; break;

          default:
            $diff = $info[0].' years, '.$info[1].' months, '.$info[2].' days';
        }
        return $diff;
    }

    private function dateDifference($startDate, $endDate)
    {
            $startDate = strtotime($startDate);
            $endDate = strtotime($endDate);

            if ($startDate === false || $startDate < 0 ||
                $endDate === false || $endDate < 0 || $startDate > $endDate)
                return false;

            $years = date('Y', $endDate) - date('Y', $startDate);

            $endMonth = date('m', $endDate);
            $startMonth = date('m', $startDate);

            // Calculate months
            $months = $endMonth - $startMonth;
            if ($months <= 0)  {
                $months += 12;
                $years--;
            }
            if ($years < 0)
                return false;

            // Calculate the days
            $offsets = array();
            if ($years > 0)
                $offsets[] = $years . (($years == 1) ? ' year' : ' years');
            if ($months > 0)
                $offsets[] = $months . (($months==1) ? ' month' : ' months');

            $offsets = count($offsets) > 0 ? '+'.implode(' ',$offsets):'now';

            $days = $endDate - strtotime($offsets, $startDate);
            $days = date('z', $days);

            return array($years, $months, $days);
   }

    protected static function buildWhere($params)
    {
        if (is_null($params)) { return "1=1"; }

        $params = Dashboard::processInput($params);

        // process dates
        $where = "`year` BETWEEN  YEAR('".$params['startdate']."') AND YEAR('".$params['enddate']."')";
        $where .= " AND MONTH(str_to_date(`month`,'%M')) BETWEEN  MONTH('".$params['startdate']."') AND MONTH('".$params['enddate']."')";

        // process location option
        if (! is_null($params['location']))
        {
            if (!in_array('all',$params['location']))
            {
                $facs = array();
                $l = new Facility;

                foreach($params['location'] as $f)
                {
                    if (preg_match("/Region/",$f)) {
                        $ids = $l->facilities($f,null);
                        foreach($ids as $id =>$v) { array_push($facs, $id); }

                    } else if (preg_match("/District/",$f)) {
                        $ids = $l->facilities(null,$f);
                        foreach($ids as $id =>$v) { array_push($facs, $id); }

                    } else {
                        array_push($facs, $f);
                    }
                }

                if (! empty($facs)) {
                    $where .= " AND motech_facility_id in (".implode(',',$facs).")";
                }
            }
        }

        return $where;
    }

    public static function processInput($data)
    {
        $params = array('enddate','location','percentage', 'startdate');

        // set unlisted or empty param values to null
        foreach($params as $param) {
            if (!in_array($param, array_keys($data)) || $data[$param]=='') { $data[$param] = null; }
        }

        // fix or set defaults for params
        foreach($data as $key => $val) {
            if (in_array($key,array('startdate','enddate'))) {
                if (preg_match('/\d{2}\/\d{2}\/\d{4}/',$val)) {
                    list($m,$d,$y) = preg_split('/\//',$val);
                    $data[$key] =  "$y-$m-$d";
                } else {
                    $data[$key] = ($key=='startdate') ? '2014-06-01' : date('Y-m-d');
                }
            }

            if ($key=='percentage') { $data[$key] = ($val==1) ? true : false; }
        }

        return $data;
    }
}