text:
package com.zigapk.weather.exceptions;

/**
 * Created by zigapk on 22.6.2016.
 */
public class CityNotFoundException extends Exception{
    public CityNotFoundException(){}
    public CityNotFoundException(String message){
        super(message);
    }
}

redpajama_set_name: RedPajamaGithub


text:
class Admin::ManagedIssuePagesController < Admin::DashboardController

  authorize_resource :class => :admin_managed_issue_pages

  # GET /admin/issues/1/pages
  def all
    @managed_issue_pages = ManagedIssuePage.order('issue_id ASC, name ASC')
    render :index
  end

  # GET /admin/issues/1/pages
  def index
    @issue = ManagedIssue.find(params[:issue_id])
    @managed_issue_pages = ManagedIssuePage.where(issue_id: @issue.id).order('name ASC')
  end

  # GET /admin/issues/1/pages/1
  def show
    @issue = ManagedIssue.find(params[:issue_id])
    @managed_issue_page = ManagedIssuePage.find(params[:id])
  end

  # GET /admin/issues/1/pages/new
  def new
    @issue = ManagedIssue.find(params[:issue_id])
    @managed_issue_page = ManagedIssuePage.new(issue: @issue)
  end

  # GET /admin/issues/1/pages/1/edit
  def edit
    @issue = ManagedIssue.find(params[:issue_id])
    @managed_issue_page = ManagedIssuePage.find(params[:id])
  end

  # POST /admin/issues/1/pages
  def create
    @issue = ManagedIssue.find(params[:issue_id])
    @managed_issue_page = ManagedIssuePage.new(params[:managed_issue_page])
    @managed_issue_page.issue = @issue
    @managed_issue_page.author = current_person

    if @managed_issue_page.save
      redirect_to(admin_issue_page_path(@issue, @managed_issue_page), :notice => 'Content template was successfully created.')
    else
      render :new
    end
  end

  # PUT /admin/issues/1/pages/1
  def update
    @issue = ManagedIssue.find(params[:issue_id])
    @managed_issue_page = ManagedIssuePage.find(params[:id])
    @managed_issue_page.attributes = params[:managed_issue_page]
    @managed_issue_page.author = current_person

    if @managed_issue_page.save
      redirect_to(admin_issue_page_path(@issue, @managed_issue_page), :notice => 'Content template was successfully updated.')
    else
      render :edit
    end
  end

  # DELETE /admin/issues/1/pages/1
  def destroy
    @issue = ManagedIssue.find(params[:issue_id])
    @managed_issue_page = ManagedIssuePage.find(params[:id])
    @managed_issue_page.destroy
    redirect_to(admin_issue_pages_path(@issue))
  end
end


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

package com.google.j2objc.util.logging;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.LogRecord;

/*-[
// TODO(tball): update ASL use to iOS 10's os_log and remove clang pragmas.
#pragma clang diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"

#import <asl.h>

// Simple value holder, so aslclient is closed when thread dictionary is deallocated.
@interface ASLClientHolder : NSObject {
 @public
  aslclient _client;
}
@end

@implementation ASLClientHolder
- (instancetype)initWithClient:(aslclient)client {
  self = [super init];
  if (self) {
    _client = client;
  }
  return self;
}

- (void)dealloc {
  asl_close(_client);
#if !__has_feature(objc_arc)
  [super dealloc];
#endif
}
@end
#pragma clang diagnostic pop
]-*/

/**
 * Handler implementation that calls iOS asl_log().
 *
 * @author Tom Ball
 */
public class IOSLogHandler extends Handler {

  static class IOSLogFormatter extends Formatter {

    /**
     * Very simple formatter, since asl_log adds its own text.
     */
    @Override
    public String format(LogRecord record) {
      return formatMessage(record);
    }
  }

  // TODO(tball): Replace this with a system property that defines a java.util.logging.config.class.
  public static final String IOS_LOG_MANAGER_DEFAULTS =
      ".level=INFO\nhandlers=com.google.j2objc.util.logging.IOSLogHandler\n";

  private static final String ASLCLIENT = "IOSLogHandler-aslclient";

  public IOSLogHandler() {
    setFormatter(new IOSLogFormatter());
  }

  @Override
  public void close() {
    // No action needed
  }

  @Override
  public void flush() {
    // No action needed
  }

  @Override
  public void publish(LogRecord record) {
    if (!isLoggable(record)) {
      return;
    }
    StringBuilder sb = new StringBuilder(getFormatter().format(record));
    int aslLevel;
    switch (record.getLevel().intValue()) {
      case 1000:       // Level.SEVERE
        aslLevel = 3;  // ASL_LEVEL_ERR
        break;
      case 900:        // Level.WARNING
        aslLevel = 4;  // ASL_LEVEL_WARNING
        break;
      case 800:        // Level.INFO
      case 700:        // Level.CONFIG
        aslLevel = 5;  // ASL_LEVEL_NOTICE
        break;
      default:
        aslLevel = 6;  // ASL_LEVEL_INFO
    }

    if (record.getThrown() != null) {
      sb.append('\n');
      StringWriter stringWriter = new StringWriter();
      record.getThrown().printStackTrace(new PrintWriter(stringWriter));
      sb.append(stringWriter.toString());
    }
    log(sb.toString(), aslLevel);
  }

  private native void log(String logMessage, int aslLevel) /*-[
    // TODO(tball): update ASL use to iOS 10's os_log and remove clang pragmas.
    #pragma clang diagnostic push
    #pragma GCC diagnostic ignored "-Wdeprecated-declarations"

    // Add stderr as a log file, so that log messages are seen on the debug log,
    // and not just the device log.
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        asl_add_log_file(NULL, STDERR_FILENO);
    });

    NSThread *currentThread = [NSThread currentThread];
    NSMutableDictionary *threadData = [currentThread threadDictionary];
    ASLClientHolder *logClient =
        [threadData objectForKey:ComGoogleJ2objcUtilLoggingIOSLogHandler_ASLCLIENT];
    if (!logClient) {
      aslclient aslClient = asl_open([[currentThread name] UTF8String],
          [[[NSBundle mainBundle] bundleIdentifier] UTF8String], ASL_OPT_NO_DELAY | ASL_OPT_STDERR);
      logClient = AUTORELEASE([[ASLClientHolder alloc] initWithClient:aslClient]);
      [threadData setObject:logClient forKey:ComGoogleJ2objcUtilLoggingIOSLogHandler_ASLCLIENT];
    }
    asl_log(logClient->_client, NULL, aslLevel, "%s", [logMessage UTF8String]);
    #pragma clang diagnostic pop
  ]-*/;
}


text:
//  Copyright 2015-2017 Peter Dimov.
//
//  Distributed under the Boost Software License, Version 1.0.
//
//  See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt

namespace boost
{
namespace mp11
{

// mp_void<T...>
namespace detail
{

template<class... T> struct mp_void_impl
{
    using type = void;
};

} // namespace detail

template<class... T> using mp_void = typename detail::mp_void_impl<T...>::type;

} // namespace mp11
} // namespace boost

#endif // #ifndef BOOST_MP11_DETAIL_MP_VOID_HPP_INCLUDED


text:
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;

namespace Amazon.EC2.Model
{
    /// <summary>
    /// VPN Gateway
    /// </summary>
    [XmlRootAttribute(IsNullable = false)]
    public class VpnGateway
    {
        private string vpnGatewayIdField;
        private string vpnGatewayStateField;
        private string typeField;
        private string availabilityZoneField;
        private List<VpcAttachment> vpcAttachmentField;
        private List<Tag> tagField;

        /// <summary>
        /// The ID of the VPN gateway
        /// </summary>
        [XmlElementAttribute(ElementName = "VpnGatewayId")]
        public string VpnGatewayId
        {
            get { return this.vpnGatewayIdField; }
            set { this.vpnGatewayIdField = value; }
        }

        /// <summary>
        /// Sets the ID of the VPN gateway
        /// </summary>
        /// <param name="vpnGatewayId">The ID of the VPN gateway</param>
        /// <returns>this instance</returns>
        [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
        public VpnGateway WithVpnGatewayId(string vpnGatewayId)
        {
            this.vpnGatewayIdField = vpnGatewayId;
            return this;
        }

        /// <summary>
        /// Checks if VpnGatewayId property is set
        /// </summary>
        /// <returns>true if VpnGatewayId property is set</returns>
        public bool IsSetVpnGatewayId()
        {
            return this.vpnGatewayIdField != null;
        }

        /// <summary>
        /// The current state of the VPN gateway.
        /// Valid values: pending, available, deleting, deleted
        /// </summary>
        [XmlElementAttribute(ElementName = "VpnGatewayState")]
        public string VpnGatewayState
        {
            get { return this.vpnGatewayStateField; }
            set { this.vpnGatewayStateField = value; }
        }

        /// <summary>
        /// Sets the current state of the VPN gateway.
        /// </summary>
        /// <param name="vpnGatewayState">The current state of the VPN gateway (pending,
        /// available, deleting, deleted)</param>
        /// <returns>this instance</returns>
        [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
        public VpnGateway WithVpnGatewayState(string vpnGatewayState)
        {
            this.vpnGatewayStateField = vpnGatewayState;
            return this;
        }

        /// <summary>
        /// Checks if VpnGatewayState property is set
        /// </summary>
        /// <returns>true if VpnGatewayState property is set</returns>
        public bool IsSetVpnGatewayState()
        {
            return this.vpnGatewayStateField != null;
        }

        /// <summary>
        /// The type of VPN connection the VPN gateway supports (ipsec.1)
        /// </summary>
        [XmlElementAttribute(ElementName = "Type")]
        public string Type
        {
            get { return this.typeField; }
            set { this.typeField = value; }
        }

        /// <summary>
        /// Sets the type of VPN connection the VPN gateway supports
        /// </summary>
        /// <param name="type">The type of VPN connection the VPN gateway supports (ipsec.1)</param>
        /// <returns>this instance</returns>
        [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
        public VpnGateway WithType(string type)
        {
            this.typeField = type;
            return this;
        }

        /// <summary>
        /// Checks if Type property is set
        /// </summary>
        /// <returns>true if Type property is set</returns>
        public bool IsSetType()
        {
            return this.typeField != null;
        }

        /// <summary>
        /// The Availability Zone where the VPN gateway was created
        /// </summary>
        [XmlElementAttribute(ElementName = "AvailabilityZone")]
        public string AvailabilityZone
        {
            get { return this.availabilityZoneField; }
            set { this.availabilityZoneField = value; }
        }

        /// <summary>
        /// Sets the Availability Zone where the VPN gateway was created
        /// </summary>
        /// <param name="availabilityZone">The Availability Zone where the VPN gateway was created</param>
        /// <returns>this instance</returns>
        [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
        public VpnGateway WithAvailabilityZone(string availabilityZone)
        {
            this.availabilityZoneField = availabilityZone;
            return this;
        }

        /// <summary>
        /// Checks if AvailabilityZone property is set
        /// </summary>
        /// <returns>true if AvailabilityZone property is set</returns>
        public bool IsSetAvailabilityZone()
        {
            return this.availabilityZoneField != null;
        }

        /// <summary>
        /// List of VPC attachments.
        /// </summary>
        [XmlElementAttribute(ElementName = "VpcAttachment")]
        public List<VpcAttachment> VpcAttachment
        {
            get
            {
                if (this.vpcAttachmentField == null)
                {
                    this.vpcAttachmentField = new List<VpcAttachment>();
                }
                return this.vpcAttachmentField;
            }
            set { this.vpcAttachmentField = value; }
        }

        /// <summary>
        /// Sets the list of VPC attachments.
        /// </summary>
        /// <param name="list">list of VPC attachments</param>
        /// <returns>this instance</returns>
        [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
        public VpnGateway WithVpcAttachment(params VpcAttachment[] list)
        {
            foreach (VpcAttachment item in list)
            {
                VpcAttachment.Add(item);
            }
            return this;
        }

        /// <summary>
        /// Checks if VpcAttachment property is set
        /// </summary>
        /// <returns>true if VpcAttachment property is set</returns>
        public bool IsSetVpcAttachment()
        {
            return (VpcAttachment.Count > 0);
        }

        /// <summary>
        /// A list of tags for the VpnGateway.
        /// </summary>
        [XmlElementAttribute(ElementName = "Tag")]
        public List<Tag> Tag
        {
            get
            {
                if (this.tagField == null)
                {
                    this.tagField = new List<Tag>();
                }
                return this.tagField;
            }
            set { this.tagField = value; }
        }

        /// <summary>
        /// Sets a list of tags for the VpnGateway.
        /// </summary>
        /// <param name="list">A list of tags for the VpnGateway.</param>
        /// <returns>this instance</returns>
        [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
        public VpnGateway WithTag(params Tag[] list)
        {
            foreach (Tag item in list)
            {
                Tag.Add(item);
            }
            return this;
        }

        /// <summary>
        /// Checks if Tag property is set
        /// </summary>
        /// <returns>true if Tag property is set</returns>
        public bool IsSetTag()
        {
            return (Tag.Count > 0);
        }

    }
}


text:
import re

from streamlink.plugin import Plugin
from streamlink.plugin.api import validate
from streamlink.stream import HLSStream

class TVRBy(Plugin):
    url_re = re.compile(r"""https?://(?:www\.)?tvr.by/televidenie/belarus""")
    file_re = re.compile(r"""(?P<url>https://stream\.hoster\.by[^"',]+\.m3u8[^"',]*)""")
    player_re = re.compile(r"""["'](?P<url>[^"']+tvr\.by/plugines/online-tv-main\.php[^"']+)["']""")

    stream_schema = validate.Schema(
        validate.all(
            validate.transform(file_re.finditer),
            validate.transform(list),
            [validate.get("url")],
            # remove duplicates
            validate.transform(set),
            validate.transform(list),
        ),
    )

    def __init__(self, url):
        # ensure the URL ends with a /
        if not url.endswith("/"):
            url += "/"
        super(TVRBy, self).__init__(url)

    @classmethod
    def can_handle_url(cls, url):
        return cls.url_re.match(url) is not None

    def _get_streams(self):
        res = self.session.http.get(self.url)
        m = self.player_re.search(res.text)
        if not m:
            return

        player_url = m.group("url")
        res = self.session.http.get(player_url)
        stream_urls = self.stream_schema.validate(res.text)
        self.logger.debug("Found {0} stream URL{1}", len(stream_urls),
                          "" if len(stream_urls) == 1 else "s")

        for stream_url in stream_urls:
            for s in HLSStream.parse_variant_playlist(self.session, stream_url).items():
                yield s

__plugin__ = TVRBy


text:
package nz.govt.natlib.meta.ui;

import java.awt.Dimension;
import java.awt.Point;

import nz.govt.natlib.meta.HarvestEvent;
import nz.govt.natlib.meta.HarvestStatus;
import nz.govt.natlib.meta.Harvester;
import nz.govt.natlib.meta.MetaUtil;
import nz.govt.natlib.meta.ProgressListener;
import nz.govt.natlib.meta.ProgressStopListener;
import nz.govt.natlib.meta.PropertySource;
import nz.govt.natlib.meta.config.Configuration;
import nz.govt.natlib.meta.log.LogManager;
import nz.govt.natlib.meta.log.LogMessage;
import nz.govt.natlib.meta.ui.tree.BaseNode;
import nz.govt.natlib.meta.ui.tree.FileModel;
import nz.govt.natlib.meta.ui.tree.FileTree;
import nz.govt.natlib.meta.ui.tree.ObjectFolderNode;
import nz.govt.natlib.meta.ui.tree.Property;
import nz.govt.natlib.meta.ui.tree.RootNode;

/**
 * This runnable class manages the harvesting of metadata. It constructs an
 * appropriate 'harvester' for every type of object/config combination and sets
 * the job going.
 *
 * @author unascribed
 * @version 1.0
 */

public class HarvestProcess implements Runnable, ProgressStopListener,
		ProgressListener {

	private FileModel fileList;

	private FileTree fileTree;

	private boolean stopping = false;

	private int totalFiles;

	private long totalBytes;

	private long processedBytes;

	private int processedFileCount;

	private Progress prog;

	private Harvester harvester = null;

	private Main mainFrame;

	private Configuration config;

	private long startTime = 0;

	private long lastEstimate = Long.MAX_VALUE;

	private boolean error = false;

	public HarvestProcess(Main mainFrame, FileTree fileTree,
			Configuration config) {
		this.fileList = (FileModel) fileTree.getModel();
		this.fileTree = fileTree;
		this.mainFrame = mainFrame;
		this.config = config;
	}

	public void progressEvent(Object subject) {
		if (stopping)
			return;

		// mark off some sort of progress...
		HarvestEvent event = (HarvestEvent) subject;
		processedFileCount++;

		if (event.isSucessful()) {
			event.getSource().setStatus(HarvestStatus.OK, null);
		} else {
			// find the error and 'mark' it
			Object source = event.getError();
			String comment = "";
			if (source instanceof Throwable) {
				comment = ((Throwable) source).getMessage();
			}
			LogMessage msg = new LogMessage(LogMessage.ERROR, source,
					"Error harvesting file :"
							+ event.getSource().getFile().getName(), comment);
			LogManager.getInstance().logMessage(msg);
			event.getSource().setStatus(HarvestStatus.ERROR,
					comment + " <b>(log id=" + msg.getId() + ")</b>");
			error = true;
		}

		String name = event.getSource().getFile().getName();
		processedBytes += event.getSource().getFile().length();
		// fancy bit... Work out how long it's taken so far - how long it will
		// be yet!
		long msEstimate = -1;
		if (processedFileCount > 50) {
			long ms = System.currentTimeMillis() - startTime;
			double msPerFile = ms / (double) processedFileCount;
			long workingEstimate = (long) (msPerFile * (totalFiles - processedFileCount));
			// the estimate is only allowed to go down - unless there is a 20sec
			// upwards re-estimate
			if ((workingEstimate < lastEstimate)
					|| (workingEstimate > lastEstimate + 20000)) {
				lastEstimate = msEstimate = workingEstimate;
			} else {
				msEstimate = lastEstimate;
			}
		}

		// show progress.
		prog
				.setProgress(
						"Processing: "
								+ name
										.substring(0, Math.min(name.length(),
												40)),
						"Files: " + processedFileCount + " of " + totalFiles,
						msEstimate > -1 ? "Estimated time remaining: "
								+ MetaUtil.formatMs(msEstimate) : " ",
						(int) (((double) processedFileCount / (double) totalFiles) * 100));
	}

	/**
	 * count the tree model...
	 */
	private void fileCount(BaseNode node) {
		if (stopping)
			return;

		if (node.isLeaf()) {
			totalFiles++;
			totalBytes += node.getFile().length();
			// Updating this takes more time tan adding the files - so only do
			// it occasionally
			boolean update = (totalFiles % 34) == 7; // air of randomness!
			if (update) {
				prog.setProgress("Preparing to Process", "Files: " + 0 + " of "
						+ totalFiles, " ", 0);
			}
		} else {
			for (int i = 0; i < node.getChildCount() && !stopping; i++) {
				fileCount((BaseNode) node.getChildAt(i));
			}
		}
	}

	public void run() {
		// show the progress window
		// set the cursor to be an hourglass...
		mainFrame.setBusy(true);

		prog = new Progress(mainFrame, true);
		prog.setProgressStopListener(this);

		prog.setSize((int) prog.getPreferredSize().getWidth() + 150, (int) prog
				.getPreferredSize().getHeight() + 20);
		prog.setResizable(false);

		// set the location.
		Point p1 = mainFrame.getLocation();
		Dimension d1 = mainFrame.getSize();
		Dimension d2 = prog.getSize();
		prog.setLocation((p1.x + (d1.width / 2)) - (d2.width / 2),
				(p1.y + (d1.height / 2)) - (d2.height / 2));
		prog.setProgress("Preparing to Process", " ", " ", 0);
		prog.setVisible(true);

		// temporarily stop all events on the tree...
		fileList.suspendEvents(true);

		// how many files are to be processed?
		fileCount((BaseNode) fileList.getRoot());

		startTime = System.currentTimeMillis();
		RootNode root = (RootNode) fileList.getRoot();
		for (int i = 0; i < root.getChildCount() && !stopping; i++) {
			ObjectFolderNode object = (ObjectFolderNode) root.getChildAt(i);
			// work out what kind of harvester to use for each object...

			if (!FileModel.hasAFile(object)) {
				LogMessage msg = new LogMessage(LogMessage.DEBUG, object
						.getName(), "Object contains no files - skipping",
						"Add files to this object");
				LogManager.getInstance().logMessage(msg);
				continue;
			}

			String harvesterClass = config.getClassName();
			if (harvesterClass != null) {
				try {
					harvester = (Harvester) Class.forName(harvesterClass)
							.newInstance();
					// go to it...
					System.out.println("Harvesting " + object);
					harvester.harvest(config, object, new PropsManager(object,
							mainFrame), this);
				} catch (Throwable ex) {
					System.out.println("Exception Harvesting " + object);
					LogMessage msg = new LogMessage(LogMessage.ERROR, ex, ex
							.getMessage(), "");
					LogManager.getInstance().logMessage(msg);
					object.setStatus(HarvestStatus.ERROR, ex.getMessage()
							+ " (logid=" + msg.getId() + ")");
					error = true;
				}
				System.gc();
			} else {
				LogMessage msg = new LogMessage(
						LogMessage.ERROR,
						null,
						"No harvester class specified for " + config.getName(),
						"check the config file, there should be a\n<harvester class='<classname>'/> tag");
				LogManager.getInstance().logMessage(msg);
			}
		}

		fileList.suspendEvents(false);
		fileList.nodeStructureChanged(root); // now that events are enabled,
												// fire one for all changes
		fileTree.repaint();
		prog.setVisible(false);
		prog.dispose();

		mainFrame.setStatus(error == true ? HarvestStatus.ERROR
				: HarvestStatus.OK);
		mainFrame.setBusy(false);
		LogManager.getInstance()
				.logMessage(LogMessage.INFO, "Harvest Complete");
	}

	public void stop() {
		if (harvester != null) {
			harvester.stop();
		}

		prog.setProgress("Stopping processing, cleaning up", " ", " ", 100);

		stopping = true;
	}

	private class PropsManager implements PropertySource {

		private ObjectFolderNode rootContext;

		private PropertySource appContext;

		private PropsManager(ObjectFolderNode rootContext,
				PropertySource appContext) {
			this.rootContext = rootContext;
			this.appContext = appContext;
		}

		public Object getProperty(String property, String condition) {
			Object result = null;

			// there are some values that are not stored as properties.
			if (property.equalsIgnoreCase("type")) {
				result = rootContext.getType() == ObjectFolderNode.COMPLEX ? "complex"
						: "simple";
			}

			// check the parent
			Property[] props = rootContext.getProperties();
			Property prop = null;
			for (int i = 0; i < props.length; i++) {
				if (props[i].getName().toLowerCase().equals(
						property.toLowerCase())) {
					prop = props[i];
					break;
				}
			}
			if (prop != null) {
				result = rootContext.getPropertyValue(prop);
			}

			// check app context...
			/**
			 *
			 */
			if (result == null) {
				result = appContext.getProperty(property, condition);
			}

			return result;
		}

	}
}


text:
import {createStore, applyMiddleware} from 'redux';
import rootReducer from './reducers/rootReducer';

export default function configureStore(initialState) {
  //todo delete extra
  return createStore(
      rootReducer,
      window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
      // applyMiddleware(reduxInvariant())
  );
}


text:
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using ApiTemplate.Api.Application.Common.Paging;
using ApiTemplate.Api.Application.Features.MasterFiles;
using ApiTemplate.Api.Contracts;
using ApiTemplate.Api.Domain.Model.MasterFiles;
using FluentAssertions;
using Specs.Library.Data;
using Specs.Library.Drivers.Api;
using TestStack.Dossier;
using TestStack.Dossier.Lists;

namespace Specs.Acceptance._CurrentSprint.MasterFiles.DisposalReasons.GetAll
{
    public class GetAllDisposalReasonsPaging : ScenarioFor<AsyncApiDriver, DisposalReasonStory>
    {
        private ApiResponse<PagedList<DisposalReasonDto>> _result;
        private IList<DisposalReason> _entityList;

        public void Given_7_DisposalReasons_where_5_contain_the_search_term()
        {
            _entityList = Builder<DisposalReason>.CreateListOfSize(7)
                .All().Set(x => x.Id, 0)
                .TheLast(5).Set(x => x.DisposalReasonDescription, "Avocado")
                .ListBuilder
                .Persist();
        }

        public void AndGiven_I_want_to_see_the_second_page_and_3_records_at_a_time() { }

        public async Task When_I_search_for_that_term()
        {
            _result = await SUT.GetAllPagedAsync<DisposalReasonDto>(
                ApiRoutes.Master.GetAllFor<DisposalReason>(pageSize: 3, page: 2,
                    filterField: "DisposalReasonDescription", filterText: "Avo"));
        }

        public void Then_I_should_see_the_last_2_of_the_matching_5_records()
        {
            _result.StatusCode.Should().Be(HttpStatusCode.OK);
            _result.Model.Results.Count.Should().Be(2);
            _result.Model.CurrentPage.Should().Be(2);
            _result.Model.PageSize.Should().Be(3);
            _result.Model.RowCount.Should().Be(5);

            _result.Model.Results[0].Id.Should().Be(_entityList[5].Id);
            _result.Model.Results[1].Id.Should().Be(_entityList[6].Id);
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace spectra.camera.Views
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class ProjectGallery : Page
    {
        public ProjectGallery()
        {
            this.InitializeComponent();
        }
    }
}


text:
package com.robotzero.sandbox.algorithms.models.quickunion;

public class QuickUnion {

    private int[] container;

    public QuickUnion() {
        this.container = new int[10];
        for (int i = 0; i < 10; i++) {
            this.container[i] = i;
        }
    }

    public boolean connected(int p, int q) {
        return root(p) == root(q);
    }

    public void union(int p, int q) {
        int i = root(p);
        int j = root(q);
        container[i] = j;
    }

    /* chase parent pointers until reach root */
    private int root(int i) {
        while (i != container[i]) {
            i = container[i];
        }
        return i;
    }
}


text:
import Ember from 'ember';
import FilterableMixin from 'hive/mixins/filterable';
import constants from 'hive/utils/constants';

export default Ember.ArrayController.extend(FilterableMixin, {
  needs: [ constants.namingConventions.routes.history,
           constants.namingConventions.openQueries ],

  history: Ember.computed.alias('controllers.' + constants.namingConventions.routes.history),
  openQueries: Ember.computed.alias('controllers.' + constants.namingConventions.openQueries),

  sortAscending: true,
  sortProperties: [],

  init: function () {
    this._super();

    this.set('columns', Ember.ArrayProxy.create({ content: Ember.A([
       Ember.Object.create({
        caption: "columns.shortQuery",
        property: 'shortQuery',
        link: constants.namingConventions.subroutes.savedQuery
      }),
      Ember.Object.create({
        caption: "columns.title",
        property: 'title',
        link: constants.namingConventions.subroutes.savedQuery
      }),
      Ember.Object.create({
        caption: "columns.database",
        property: 'dataBase',
        link: constants.namingConventions.subroutes.savedQuery
      }),
      Ember.Object.create({
        caption: "columns.owner",
        property: 'owner',
        link: constants.namingConventions.subroutes.savedQuery
      })
    ])}));
  },

  //row buttons
  links: [
    "buttons.history",
    "buttons.delete",
    "buttons.downloadQuery"
  ],

  model: function () {
    return this.filter(this.get('queries'));
  }.property('queries', 'filters.@each'),

  actions: {
    executeAction: function (action, savedQuery) {
      var self = this;

      switch (action) {
        case "buttons.history":
          this.get('history').filterBy('queryId', savedQuery.get('id'), true);
          this.transitionToRoute(constants.namingConventions.routes.history);
          break;
        case "buttons.delete":
          var defer = Ember.RSVP.defer();
          this.send('openModal',
                    'modal-delete',
                     {
                        heading: "modals.delete.heading",
                        text: "modals.delete.message",
                        defer: defer
                     });

          defer.promise.then(function () {
            savedQuery.destroyRecord();
            self.get('openQueries').updatedDeletedQueryTab(savedQuery);
          });

          break;
        case "buttons.downloadQuery":
          var self = this,
          defer = Ember.RSVP.defer();
          this.send('openModal',
                    'modal-save',
                    {
                       heading: "modals.downloadQuery.heading",
                       text: savedQuery.get('title')+".hql",
                       defer: defer
                    });
          defer.promise.then(function (text) {
            var adapter = self.container.lookup('adapter:application').buildURL();
            var a = document.createElement('a');
            a.href = adapter + '/savedQueries/' + savedQuery.get('id') + '?op=download';
            a.download = text;
            document.body.appendChild(a);
            a.click();
          });
          break;
      }
    },

    sort: function (property) {
      //if same column has been selected, toggle flag, else default it to true
      if (this.get('sortProperties').objectAt(0) === property) {
        this.set('sortAscending', !this.get('sortAscending'));
      } else {
        this.set('sortAscending', true);
        this.set('sortProperties', [ property ]);
      }
    },

    clearFilters: function () {
      var columns = this.get('columns');

      if (columns) {
        columns.forEach(function (column) {
          var filterValue = column.get('filterValue');

          if (filterValue && typeof filterValue === 'string') {
            column.set('filterValue');
          }
        });
      }

      //call clear filters from Filterable mixin
      this.clearFilters();
    }
  }
});


text:
<?php

namespace Symfony\Component\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;

/**
 * Resolves named arguments to their corresponding numeric index.
 *
 * @author Kévin Dunglas <dunglas@gmail.com>
 */
class ResolveNamedArgumentsPass extends AbstractRecursivePass
{
    /**
     * {@inheritdoc}
     */
    protected function processValue($value, $isRoot = false)
    {
        if (!$value instanceof Definition) {
            return parent::processValue($value, $isRoot);
        }

        $parameterBag = $this->container->getParameterBag();

        if ($class = $value->getClass()) {
            $class = $parameterBag->resolveValue($class);
        }

        $calls = $value->getMethodCalls();
        $calls[] = array('__construct', $value->getArguments());

        foreach ($calls as $i => $call) {
            list($method, $arguments) = $call;
            $method = $parameterBag->resolveValue($method);
            $parameters = null;
            $resolvedArguments = array();

            foreach ($arguments as $key => $argument) {
                if (is_int($key)) {
                    $resolvedArguments[] = $argument;
                    continue;
                }
                if ('' === $key || '$' !== $key[0]) {
                    throw new InvalidArgumentException(sprintf('Invalid key "%s" found in arguments of method "%s" for service "%s": only integer or $named arguments are allowed.', $key, $method, $this->currentId));
                }

                $parameters = null !== $parameters ? $parameters : $this->getParameters($class, $method);

                foreach ($parameters as $j => $p) {
                    if ($key === '$'.$p->name) {
                        $resolvedArguments[$j] = $argument;

                        continue 2;
                    }
                }

                throw new InvalidArgumentException(sprintf('Unable to resolve service "%s": method "%s::%s" has no argument named "%s". Check your service definition.', $this->currentId, $class, $method, $key));
            }

            if ($resolvedArguments !== $call[1]) {
                ksort($resolvedArguments);
                $calls[$i][1] = $resolvedArguments;
            }
        }

        list(, $arguments) = array_pop($calls);

        if ($arguments !== $value->getArguments()) {
            $value->setArguments($arguments);
        }
        if ($calls !== $value->getMethodCalls()) {
            $value->setMethodCalls($calls);
        }

        return parent::processValue($value, $isRoot);
    }

    /**
     * @param string|null $class
     * @param string      $method
     *
     * @throws InvalidArgumentException
     *
     * @return array
     */
    private function getParameters($class, $method)
    {
        if (!$class) {
            throw new InvalidArgumentException(sprintf('Unable to resolve service "%s": the class is not set.', $this->currentId));
        }

        if (!$r = $this->container->getReflectionClass($class)) {
            throw new InvalidArgumentException(sprintf('Unable to resolve service "%s": class "%s" does not exist.', $this->currentId, $class));
        }

        if (!$r->hasMethod($method)) {
            throw new InvalidArgumentException(sprintf('Unable to resolve service "%s": method "%s::%s" does not exist.', $this->currentId, $class, $method));
        }

        $method = $r->getMethod($method);
        if (!$method->isPublic()) {
            throw new InvalidArgumentException(sprintf('Unable to resolve service "%s": method "%s::%s" must be public.', $this->currentId, $class, $method->name));
        }

        return $method->getParameters();
    }
}


text:
<template name="donationModal">

Thank you for your donation!

              Donation Amount
              <input type="text" data-content="donationAmount" value=""/>

              <button type="button" class="btn btn-info" data-action="confirm">Confirm</button>
              <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

</template>


text:
package org.demidenko05.android.chromatography.sqlite;

import java.util.Map;
import org.demidenko05.android.chromatography.model.AbstractEntityWithName;
import org.demidenko05.android.chromatography.model.DbColumnType;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class OrmServiceEntityWithName  <T extends AbstractEntityWithName> extends OrmService<T> {

	public OrmServiceEntityWithName(String tableName, Class<T> entityClass, SQLiteDatabase db) {
		super(tableName, entityClass, db);
	}

	@Override
	public Map<String, ColumnDescriptor> getColumsDescriptor() {
		Map<String, ColumnDescriptor> columnsDescriptor = super.getColumsDescriptor();
		columnsDescriptor.put(COLUMN_NAME, new ColumnDescriptor("Text Not Null", DbColumnType.FIELD));
		return columnsDescriptor;
	}

	@Override
	protected void fillEntity(T entity, Cursor cursor) {
		entity.setId(cursor.getLong(0));
		entity.setName(cursor.getString(1));
	}

	@Override
	protected String[] getAllColumns() {
		String[] allColumns = {COLUMN_ID, COLUMN_NAME};
		return allColumns;
	}

	@Override
	protected ContentValues getValuesMap(T entity) {
		ContentValues valuesMap = new ContentValues();
		valuesMap.put(COLUMN_NAME, entity.getName());
		return valuesMap;
	}

}


text:
<?php

class Google_Service_CloudSearch_FacetOptions extends Google_Model
{
  public $numFacetBuckets;
  public $objectType;
  public $operatorName;
  public $sourceName;

  public function setNumFacetBuckets($numFacetBuckets)
  {
    $this->numFacetBuckets = $numFacetBuckets;
  }
  public function getNumFacetBuckets()
  {
    return $this->numFacetBuckets;
  }
  public function setObjectType($objectType)
  {
    $this->objectType = $objectType;
  }
  public function getObjectType()
  {
    return $this->objectType;
  }
  public function setOperatorName($operatorName)
  {
    $this->operatorName = $operatorName;
  }
  public function getOperatorName()
  {
    return $this->operatorName;
  }
  public function setSourceName($sourceName)
  {
    $this->sourceName = $sourceName;
  }
  public function getSourceName()
  {
    return $this->sourceName;
  }
}


text:
import { Entity, PrimaryColumn, OneToMany } from "typeorm";
import Setting from "./setting";

@Entity("guild")
export default class Guild {
  @PrimaryColumn()
  id!: string;
  @OneToMany(() => Setting, (setting) => setting.guild)
  settings!: Setting[];
}


text:
package org.ethereum.net.peerdiscovery;

import org.ethereum.net.client.PeerData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * www.ethereumJ.com
 * @author: Roman Mandeleil
 * Created on: 22/05/2014 09:26
 */
public class WorkerThread implements Runnable {

    private final static Logger logger = LoggerFactory.getLogger("peerdiscovery");

    ThreadPoolExecutor poolExecutor;
    private PeerData peerData;
    private PeerTaster peerTaster;

    public WorkerThread(PeerData peerData, ThreadPoolExecutor poolExecutor) {
        this.poolExecutor = poolExecutor;
        this.peerData = peerData;
    }

    @Override
    public void run() {
        logger.info(Thread.currentThread().getName()+" Start. Command = "+ peerData.toString());
        processCommand();
        logger.info(Thread.currentThread().getName()+" End.");

        try {Thread.sleep(10000); } catch (InterruptedException e) {logger.error("sleep interrupted");}
        poolExecutor.execute(this);
    }

    private void processCommand() {

        try {

            peerTaster = new PeerTaster();
            peerTaster.connect(peerData.getInetAddress().getHostAddress(), peerData.getPort());

            peerData.setOnline(true);
            peerData.setHandshake(peerTaster.getHandshake());
            logger.info("Peer: " + peerData.toString() + " isOnline: true");
        }
        catch (Throwable e) {
            if (peerData.isOnline() == true)
                logger.info("Peer: [ {} ] got offline, due: [ {} ]",
                        peerData.getInetAddress().getHostAddress(),
                        e);
            logger.info("Peer: " + peerData.toString() + " isOnline: false");
            peerData.setOnline(false);
        } finally {
            peerData.setLastCheckTime(System.currentTimeMillis());
        }
    }

    @Override
    public String toString() {
        return " Worker for: " + this.peerData.toString();
    }
}


text:
class GraphQL::Schema::EachItemValidator
  def initialize(errors)
    @errors = errors
  end

  def validate(items, as:, must_be:)
    invalid_items = items.select {|k| !yield(k) }
    if invalid_items.any?
      @errors << "#{as} must be #{must_be}, but some aren't: #{invalid_items.map(&:to_s).join(", ")}"
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>

<recipeml version="0.5">
  <recipe>
    <head>
      <title>Bacon Omelet</title>
      <categories>
        <cat>Egg</cat></categories>
      <yield>1</yield></head>
    <ingredients>
      <ing>
        <amt>
          <qty>1</qty>
          <unit>tablespoon</unit></amt>
        <item>Butter</item></ing>
      <ing>
        <amt>
          <qty>4</qty>
          <unit/></amt>
        <item>Eggs</item></ing>
      <ing>
        <amt>
          <qty>4</qty>
          <unit>tablespoons</unit></amt>
        <item>Milk</item></ing>
      <ing>
        <amt>
          <qty>3</qty>
          <unit/></amt>
        <item>Slices of bacon Cooked and</item></ing>
      <ing>
        <amt>
          <qty/>
          <unit/></amt>
        <item>Crumbled</item></ing></ingredients>
    <directions>
      <step>  Put butter in 9 inch pie plate.  Microwave on high 30 seconds until melted.
  Beat eggs and milk and pour into pie plate. Sprinkle bacon on top and cover
  with waxed paper. Microwave on high 4 minutes stirring once during cooking.
  Cover and let stand 1 to 2 minutes. Fold in half

  From Gemini's MASSIVE MealMaster collection at www.synapse.com/~gemini

</step></directions></recipe></recipeml>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WorldSimulation.Entities;
using WorldSimulation.Flags;

namespace WorldSimulation.People.LifeEvents.Relations
{
    public class StartDatingLifeEvent : ILifeEvent
    {
        /// <summary>
        /// Simple gate-keeping check to determine if it is even physically possible for this event
        /// to be triggered.
        /// An example would be lighting a car on fire without a car. Without the car,
        /// you couldn't light the fire on said car.
        /// </summary>
        /// <param name="person">The person.</param>
        /// <returns>
        /// Whether or not this encounter can be encountered.
        /// </returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public bool CanEncounter(Person person)
        {
            // For purposes of this simulation, we assume if you're already in a relationship,
            // you won't be dating anyone else.
            //
            // We also assume that boys and girls are gross until about 14.
            //
            // (And that there's someone to date.)
            return person.Partner == null
                   && !person.HasFlag(RomanticFlags.DatingFlag)
                   && !person.HasFlag(RomanticFlags.EngagedFlag)
                   && !person.HasFlag(RomanticFlags.MarriedFlag)
                   && person.Age >= 14
                   && person.Location.GetPeopleWhere(p => ValidPartner(person, p)).Any();
        }

        public float ScoreEncounter(Person enactor)
        {
            return FacetInfluenceEnum.Minor.ToScore();
        }

        public IList<Tuple<FacetTypeEnum, int>> ScorePersonalityEncounter()
        {
            return new Tuple<FacetTypeEnum, int>[0];
        }

        public bool Encounter(Person person)
        {
            var potentialPartner =
                person.Location.GetPeopleWhere(p => ValidPartner(person, p))
                    .OrderBy(_ => Guid.NewGuid())
                    .FirstOrDefault();
            if (potentialPartner == null)
            {
                return false;
            }

            person.Log("I've started dating {0}!", potentialPartner.Name);
            potentialPartner.Log("I've started dating {0}!", person.Name);
            person.AddFlag(RomanticFlags.DatingFlag);
            potentialPartner.AddFlag(RomanticFlags.DatingFlag);

            person.Partner = potentialPartner;
            person.PopulationModule.SaveChanges(potentialPartner);

            return true;
        }

        private static bool ValidPartner(Person seeker, Person potentialPartner)
        {
            return !potentialPartner.HasFlag(RomanticFlags.DatingFlag) || !potentialPartner.HasFlag(RomanticFlags.MarriedFlag) ||
                   !potentialPartner.HasFlag(RomanticFlags.EngagedFlag) && potentialPartner.Age >= 14 &&
                   potentialPartner.Id != seeker.Id;
        }
    }
}


text:
package tproxy

import (
	"bytes"
	"encoding/binary"
	"fmt"
	"net"
	"os"
	"strconv"
	"syscall"
	"unsafe"
)

// ListenUDP will construct a new UDP listener
// socket with the Linux IP_TRANSPARENT option
// set on the underlying socket
func ListenUDP(network string, laddr *net.UDPAddr) (*net.UDPConn, error) {
	listener, err := net.ListenUDP(network, laddr)
	if err != nil {
		return nil, err
	}

	fileDescriptorSource, err := listener.File()
	if err != nil {
		return nil, &net.OpError{Op: "listen", Net: network, Source: nil, Addr: laddr, Err: fmt.Errorf("get file descriptor: %s", err)}
	}
	defer fileDescriptorSource.Close()

	fileDescriptor := int(fileDescriptorSource.Fd())
	if err = syscall.SetsockoptInt(fileDescriptor, syscall.SOL_IP, syscall.IP_TRANSPARENT, 1); err != nil {
		return nil, &net.OpError{Op: "listen", Net: network, Source: nil, Addr: laddr, Err: fmt.Errorf("set socket option: IP_TRANSPARENT: %s", err)}
	}

	if err = syscall.SetsockoptInt(fileDescriptor, syscall.SOL_IP, syscall.IP_RECVORIGDSTADDR, 1); err != nil {
		return nil, &net.OpError{Op: "listen", Net: network, Source: nil, Addr: laddr, Err: fmt.Errorf("set socket option: IP_RECVORIGDSTADDR: %s", err)}
	}

	return listener, nil
}

// ReadFromUDP reads a UDP packet from c, copying the payload into b.
// It returns the number of bytes copied into b and the return address
// that was on the packet.
//
// Out-of-band data is also read in so that the original destination
// address can be identified and parsed.
func ReadFromUDP(conn *net.UDPConn, b []byte) (int, *net.UDPAddr, *net.UDPAddr, error) {
	oob := make([]byte, 1024)
	n, oobn, _, addr, err := conn.ReadMsgUDP(b, oob)
	if err != nil {
		return 0, nil, nil, err
	}

	msgs, err := syscall.ParseSocketControlMessage(oob[:oobn])
	if err != nil {
		return 0, nil, nil, fmt.Errorf("parsing socket control message: %s", err)
	}

	var originalDst *net.UDPAddr
	for _, msg := range msgs {
		if msg.Header.Level == syscall.SOL_IP && msg.Header.Type == syscall.IP_RECVORIGDSTADDR {
			originalDstRaw := &syscall.RawSockaddrInet4{}
			if err = binary.Read(bytes.NewReader(msg.Data), binary.LittleEndian, originalDstRaw); err != nil {
				return 0, nil, nil, fmt.Errorf("reading original destination address: %s", err)
			}

			switch originalDstRaw.Family {
			case syscall.AF_INET:
				pp := (*syscall.RawSockaddrInet4)(unsafe.Pointer(originalDstRaw))
				p := (*[2]byte)(unsafe.Pointer(&pp.Port))
				originalDst = &net.UDPAddr{
					IP:   net.IPv4(pp.Addr[0], pp.Addr[1], pp.Addr[2], pp.Addr[3]),
					Port: int(p[0])<<8 + int(p[1]),
				}

			case syscall.AF_INET6:
				pp := (*syscall.RawSockaddrInet6)(unsafe.Pointer(originalDstRaw))
				p := (*[2]byte)(unsafe.Pointer(&pp.Port))
				originalDst = &net.UDPAddr{
					IP:   net.IP(pp.Addr[:]),
					Port: int(p[0])<<8 + int(p[1]),
					Zone: strconv.Itoa(int(pp.Scope_id)),
				}

			default:
				return 0, nil, nil, fmt.Errorf("original destination is an unsupported network family")
			}
		}
	}

	if originalDst == nil {
		return 0, nil, nil, fmt.Errorf("unable to obtain original destination: %s", err)
	}

	return n, addr, originalDst, nil
}

// DialUDP connects to the remote address raddr on the network net,
// which must be "udp", "udp4", or "udp6".  If laddr is not nil, it is
// used as the local address for the connection.
func DialUDP(network string, laddr *net.UDPAddr, raddr *net.UDPAddr) (*net.UDPConn, error) {
	remoteSocketAddress, err := udpAddrToSocketAddr(raddr)
	if err != nil {
		return nil, &net.OpError{Op: "dial", Err: fmt.Errorf("build destination socket address: %s", err)}
	}

	localSocketAddress, err := udpAddrToSocketAddr(laddr)
	if err != nil {
		return nil, &net.OpError{Op: "dial", Err: fmt.Errorf("build local socket address: %s", err)}
	}

	fileDescriptor, err := syscall.Socket(udpAddrFamily(network, laddr, raddr), syscall.SOCK_DGRAM, 0)
	if err != nil {
		return nil, &net.OpError{Op: "dial", Err: fmt.Errorf("socket open: %s", err)}
	}

	if err = syscall.SetsockoptInt(fileDescriptor, syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1); err != nil {
		syscall.Close(fileDescriptor)
		return nil, &net.OpError{Op: "dial", Err: fmt.Errorf("set socket option: SO_REUSEADDR: %s", err)}
	}

	if err = syscall.SetsockoptInt(fileDescriptor, syscall.SOL_IP, syscall.IP_TRANSPARENT, 1); err != nil {
		syscall.Close(fileDescriptor)
		return nil, &net.OpError{Op: "dial", Err: fmt.Errorf("set socket option: IP_TRANSPARENT: %s", err)}
	}

	if err = syscall.Bind(fileDescriptor, localSocketAddress); err != nil {
		syscall.Close(fileDescriptor)
		return nil, &net.OpError{Op: "dial", Err: fmt.Errorf("socket bind: %s", err)}
	}

	if err = syscall.Connect(fileDescriptor, remoteSocketAddress); err != nil {
		syscall.Close(fileDescriptor)
		return nil, &net.OpError{Op: "dial", Err: fmt.Errorf("socket connect: %s", err)}
	}

	fdFile := os.NewFile(uintptr(fileDescriptor), fmt.Sprintf("net-udp-dial-%s", raddr.String()))
	defer fdFile.Close()

	remoteConn, err := net.FileConn(fdFile)
	if err != nil {
		syscall.Close(fileDescriptor)
		return nil, &net.OpError{Op: "dial", Err: fmt.Errorf("convert file descriptor to connection: %s", err)}
	}

	return remoteConn.(*net.UDPConn), nil
}

// udpAddToSockerAddr will convert a UDPAddr
// into a Sockaddr that may be used when
// connecting and binding sockets
func udpAddrToSocketAddr(addr *net.UDPAddr) (syscall.Sockaddr, error) {
	switch {
	case addr.IP.To4() != nil:
		ip := [4]byte{}
		copy(ip[:], addr.IP.To4())

		return &syscall.SockaddrInet4{Addr: ip, Port: addr.Port}, nil

	default:
		ip := [16]byte{}
		copy(ip[:], addr.IP.To16())

		zoneID, err := strconv.ParseUint(addr.Zone, 10, 32)
		if err != nil {
			return nil, err
		}

		return &syscall.SockaddrInet6{Addr: ip, Port: addr.Port, ZoneId: uint32(zoneID)}, nil
	}
}

// udpAddrFamily will attempt to work
// out the address family based on the
// network and UDP addresses
func udpAddrFamily(net string, laddr, raddr *net.UDPAddr) int {
	switch net[len(net)-1] {
	case '4':
		return syscall.AF_INET
	case '6':
		return syscall.AF_INET6
	}

	if (laddr == nil || laddr.IP.To4() != nil) &&
		(raddr == nil || laddr.IP.To4() != nil) {
		return syscall.AF_INET
	}
	return syscall.AF_INET6
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
atg.multisite (ATG Java API)
</TITLE>

<META NAME="date" CONTENT="2013-04-01">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../stylesheet.css" TITLE="Style">

atg.multisite

Interfaces

InactiveSiteHandler

Site

SiteContext

SiteContextRuleFilter

SiteGroup

SiteRequestProcessor

SiteSessionEndProcessor

SiteSessionStartProcessor

SiteStateProcessor

URLPatternMatchingRuleFilter.URLPatternMatchingRuleFilterRegistrar

Classes

DefaultSiteContextRuleFilter

NucleusComponentShareableType

ProfileRealmManager

PushedSiteParamFilter

ShareableType

SiteContextManager

SiteContextPipelineServlet

SiteGroupManager

SiteManager

SiteSession

SiteSessionManager

SiteURLManager

URLPatternMatchingRuleFilter

Exceptions

SiteContextException

SiteGroupException


text:
"""
Script to print potentially missing source dependencies based on the actual
.h and .cc files in the source tree and which files are included in the gyp
and gn files. The latter inclusion is overapproximated.

TODO(machenbach): Gyp files in src will point to source files in src without a
src/ prefix. For simplicity, all paths relative to src are stripped. But this
tool won't be accurate for other sources in other directories (e.g. cctest).
"""

import itertools
import re
import os

V8_BASE = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
V8_SRC_BASE = os.path.join(V8_BASE, 'src')
V8_INCLUDE_BASE = os.path.join(V8_BASE, 'include')

GYP_FILES = [
  os.path.join(V8_BASE, 'src', 'd8.gyp'),
  os.path.join(V8_BASE, 'src', 'v8.gyp'),
  os.path.join(V8_BASE, 'src', 'third_party', 'vtune', 'v8vtune.gyp'),
  os.path.join(V8_BASE, 'test', 'cctest', 'cctest.gyp'),
  os.path.join(V8_BASE, 'test', 'unittests', 'unittests.gyp'),
  os.path.join(V8_BASE, 'tools', 'parser-shell.gyp'),
]

def path_no_prefix(path):
  if path.startswith('../'):
    return path_no_prefix(path[3:])
  elif path.startswith('src/'):
    return path_no_prefix(path[4:])
  else:
    return path

def isources(directory):
  for root, dirs, files in os.walk(directory):
    for f in files:
      if not (f.endswith('.h') or f.endswith('.cc')):
        continue
      yield path_no_prefix(os.path.relpath(os.path.join(root, f), V8_BASE))

def iflatten(obj):
  if isinstance(obj, dict):
    for value in obj.values():
      for i in iflatten(value):
        yield i
  elif isinstance(obj, list):
    for value in obj:
      for i in iflatten(value):
        yield i
  elif isinstance(obj, basestring):
    yield path_no_prefix(obj)

def iflatten_gyp_file(gyp_file):
  """Overaproximates all values in the gyp file.

  Iterates over all string values recursively. Removes '../' path prefixes.
  """
  with open(gyp_file) as f:
    return iflatten(eval(f.read()))

def iflatten_gn_file(gn_file):
  """Overaproximates all values in the gn file.

  Iterates over all double quoted strings.
  """
  with open(gn_file) as f:
    for line in f.read().splitlines():
      match = re.match(r'.*"([^"]*)".*', line)
      if match:
        yield path_no_prefix(match.group(1))

def icheck_values(values, *source_dirs):
  for source_file in itertools.chain(
      *[isources(source_dir) for source_dir in source_dirs]
    ):
    if source_file not in values:
      yield source_file

gyp_values = set(itertools.chain(
  *[iflatten_gyp_file(gyp_file) for gyp_file in GYP_FILES]
  ))

print "----------- Files not in gyp: ------------"
for i in sorted(icheck_values(gyp_values, V8_SRC_BASE, V8_INCLUDE_BASE)):
  print i

gn_values = set(iflatten_gn_file(os.path.join(V8_BASE, 'BUILD.gn')))

print "\n----------- Files not in gn: -------------"
for i in sorted(icheck_values(gn_values, V8_SRC_BASE, V8_INCLUDE_BASE)):
  print i


text:
package nz.ac.lconz.irr.dspace.app.xmlui.aspect.opengraph;

import org.apache.cocoon.caching.CacheableProcessingComponent;
import org.apache.cocoon.util.HashUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.excalibur.source.SourceValidity;
import org.apache.log4j.Logger;
import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer;
import org.dspace.app.xmlui.utils.DSpaceValidity;
import org.dspace.app.xmlui.utils.HandleUtil;
import org.dspace.app.xmlui.utils.UIException;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.AuthorizeManager;
import org.dspace.content.*;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants;
import org.dspace.eperson.Group;
import org.dspace.handle.HandleManager;
import org.xml.sax.SAXException;

import java.io.IOException;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: schweer
 * Date: 30/08/12
 * Time: 4:44 PM
 * To change this template use File | Settings | File Templates.
 */
public class OpenGraphTransformer extends AbstractDSpaceTransformer implements CacheableProcessingComponent {
	private DSpaceValidity validity = null;
	private Logger log = Logger.getLogger(OpenGraphTransformer.class);

	/**
	 * Generates the unique caching key - this references the item.
	 * @return The unique caching key or 0 in case of errors
	 */
	public Serializable getKey() {
		try {
			DSpaceObject dso = HandleUtil.obtainHandle(objectModel);

			if (dso == null)
			{
				return "0"; // no item, something is wrong.
			}

			return HashUtil.hash(dso.getHandle());
		}
		catch (SQLException sqle)
		{
			// Ignore all errors and just return that the component is not cachable.
			return "0";
		}
	}

	/**
	 * Generates the cache validity object - linked to the item being viewed.
	 * @return The cache validity object or null in case of errors
	 */
	public SourceValidity getValidity() {
		DSpaceObject dso = null;

		if (this.validity == null)
		{
			try {
				dso = HandleUtil.obtainHandle(objectModel);

				DSpaceValidity validity = new DSpaceValidity();
				validity.add(dso);
				this.validity =  validity.complete();
			}
			catch (Exception e)
			{
				// Ignore all errors and just invalidate the cache.
			}

		}
		return this.validity;
	}

	@Override
	public void recycle() {
		validity = null;
		super.recycle();
	}

	@Override
	public void addPageMeta(PageMeta pageMeta) throws SAXException, WingException, UIException, SQLException, IOException, AuthorizeException {
		DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
		if (!(dso instanceof Item))
		{
			return;
		}

		Item item = (Item) dso;

		StringBuilder meta = new StringBuilder();
		// item type - always article
		meta.append(makePropertyStatement("og:type", "article"));

		// link to the item
		String handle = item.getHandle();
		meta.append(makePropertyStatement("og:url", HandleManager.resolveToURL(context, handle)));

		// name of the site
		String siteName = ConfigurationManager.getProperty("dspace.name");
		meta.append(makePropertyStatement("og:site_name", siteName));

		// images - take image files from content bundle, or thumbnails if there aren't any images, but in either case only public ones
		List<String> imageUrls = new ArrayList<String>();
		Bundle[] contentBundles = item.getBundles(Constants.CONTENT_BUNDLE_NAME);
		for (Bundle bundle : contentBundles) {
			if (anonymousCanRead(bundle)) {
				for (Bitstream bitstream : bundle.getBitstreams()) {
					if (anonymousCanRead(bitstream) && isImageFile(bitstream)) {
						imageUrls.add(buildBitstreamUrl(item, bitstream));
					}
				}
			}
		}
		if (imageUrls.isEmpty()) {
			Bundle[] thumbnailBundles = item.getBundles("THUMBNAIL");
			for (Bundle bundle : thumbnailBundles) {
				if (anonymousCanRead(bundle)) {
					for (Bitstream bitstream : bundle.getBitstreams()) {
						if (anonymousCanRead(bitstream) && isImageFile(bitstream)) {
							imageUrls.add(buildBitstreamUrl(item, bitstream));
						}
					}
				}
			}
		}
		for (String url : imageUrls) {
			meta.append(makePropertyStatement("og:image", url));
		}

		// title
		String itemName = item.getName();
		meta.append(makePropertyStatement("og:title", itemName));

		// description
		String descriptionText = " ";
		Metadatum[] descriptions = item.getMetadata("dc", "description", "abstract", Item.ANY);
		if (descriptions.length > 0) {
			try {
				descriptionText = StringUtils.abbreviate(descriptions[0].value, 500);
			} catch (IllegalArgumentException e) {
				// string is too short - just leave as is
			}
		}
		meta.append(makePropertyStatement("og:description", descriptionText));

		// published time
		Metadatum[] availableDates = item.getMetadata("dc", "date", "available", Item.ANY);
		if (availableDates.length > 0 && availableDates[0] != null && availableDates[0].value != null) {
			DCDate available = new DCDate(availableDates[0].value);
			String displayDate = available.toString();
			meta.append(makePropertyStatement("article:published_time", displayDate));
		}

		// modified time
		DCDate lastModified = new DCDate(item.getLastModified());
		meta.append(makePropertyStatement("article:modified_time", lastModified.toString()));

		// section - use name of top-level community in which this item lives
		Community parent = (Community) item.getOwningCollection().getParentObject();
		while (parent.getParentCommunity() != null) {
			parent = parent.getParentCommunity();
		}
		String parentName = parent.getName();
		meta.append(makePropertyStatement("article:section", parentName));

		// tags
		Metadatum[] keywords = item.getMetadata("dc", "subject", null, Item.ANY);
		for (Metadatum keyword : keywords) {
			meta.append(makePropertyStatement("article:tag", keyword.value));
		}

		pageMeta.addMetadata("xhtml_head_item", "opengraph").addContent(meta.toString());

		// add prefix declarations - the theme should add these to the <head> element like so:
		// <head prefix="og: http://ogp.me/ns# article: http://ogp.me/ns/article#">
		pageMeta.addMetadata("xhtml_head_prefix", "og").addContent("http://ogp.me/ns#");
		pageMeta.addMetadata("xhtml_head_prefix", "article").addContent("http://ogp.me/ns/article#");
	}

	private String buildBitstreamUrl(Item item, Bitstream bitstream) throws UIException {
		StringBuilder bitstreamUrl = new StringBuilder(ConfigurationManager.getProperty("dspace.url"));
		bitstreamUrl.append("/bitstream/handle/");
		bitstreamUrl.append(item.getHandle());
		bitstreamUrl.append("/");
		bitstreamUrl.append(encodeForURL(bitstream.getName()));
		bitstreamUrl.append("?sequence=");
		bitstreamUrl.append(bitstream.getSequenceID());
		return bitstreamUrl.toString();
	}

	private boolean isImageFile(Bitstream bitstream) {
		return !bitstream.getFormat().isInternal() && bitstream.getFormat().getMIMEType().startsWith("image/");
	}

	private boolean anonymousCanRead(DSpaceObject dso) {
		try {
			Group[] readGroups = AuthorizeManager.getAuthorizedGroups(context, dso, Constants.READ);
			for (Group group : readGroups) {
				if (group.getID() == 0) {
					return true;
				}
			}
			return false;
		} catch (SQLException e) {
			log.warn("Cannot determine whether object type " + dso.getType() + ", id=" + dso.getID() + "is publicly readable, assuming it isn't");
			return false;
		}
	}

	private StringBuilder makePropertyStatement(Object propertyName, String value) {
		StringBuilder result = new StringBuilder();
		if (value != null && !"".equals(value)) {
			result.append("<meta property=\"");
			result.append(propertyName);
			result.append("\" content=\"");
			result.append(value);
			result.append("\"/>\n");
		}
		return result;
	}
}


text:
//
// gaiatypes.h
//
// Types used in storage server and in the client library to access
// storage server.
//

#ifndef _GAIATYPES_H
#define _GAIATYPES_H

#include <assert.h>
#include "inttypes.h"
#include "os.h"

typedef u64 Cid; // container id type
typedef u64 Oid; // object id type

// container and object id
struct COid {
  Cid cid;
  Oid oid;
  static unsigned hash(const COid &c) {
    return (unsigned) ((u32)c.cid ^ (u32)(c.cid>>32) ^
                       (u32)c.oid ^ (u32)(c.oid>>32));
  }
  static int cmp(const COid &l, const COid &r) {
    if (l.cid < r.cid) return -1;
    if (l.cid > r.cid) return +1;
    // l.cid == r.cid
    if (l.oid < r.oid) return -1;
    if (l.oid > r.oid) return +1;
    return 0;
  }
  void setInvalid(){ cid=oid=0xffffffffffffffffULL; }
  bool isInvalid(){ return cid+1==0 && oid+1==0; }
};

struct Interval {
  int off;
  int len;
};

// returns a unique identifier for the current process
// consists of IP concatenated with PID
class UniqueId
{
private:
  static Tlocal u64 myid;
public:
  static void init(u32 myip=0);
  static u64 getUniqueId(void){
    if (!myid) init();
    return myid;
  }
};

// 128-bit Tid
class Tid {
private:
  static u32 count;
public:
  u64 d1, d2;
  void setNew(void);

  static int cmp(const Tid &l, const Tid &r){
    if (l.d1 < r.d1) return -1;
    if (l.d1 > r.d1) return +1;
    // l.d1 == r.d1
    if (l.d2 < r.d2) return -1;
    if (l.d2 > r.d2) return +1;
    return 0;
  }

  static unsigned hash(const Tid &l){
    return (unsigned)((u32)l.d1 ^ (u32)(l.d1>>32) ^
                      (u32)l.d2 ^ (u32)(l.d2>>32));
  }
};

// 128-bit timestamp
// Format for timestamps:
// [magic] [localclock] [count] [uniqueid]
// 16 bits   48 bits    16 bits  48 bits
class Timestamp {
private:
  static Tlocal u32 count;
  static Tlocal i64 advance;
  static Tlocal u64 lastus;
  static Tlocal u32 countoverflow; // for debugging purposes. Number of times
                                   // count has overflown
  u64 d[2];
public:
  u64 getd1(void){ return d[0]; }
  u64 getd2(void){ return d[1]; }
  static u64 getadvance(){ return advance; } // for debugging purposes
  static u32 getcountoverflow(){ return countoverflow; } // for debugging
                                                         // purposes

  // set timestamp to a new fresh timestamp
  void setNew();

  // sets a timestamp in the past by ms milliseconds, if ms >= 0.
  // If ms < 0 then sets a timestamp in the future
  void setOld(i64 ms);

  // returns how old is the timestamp in ms. A negative value
  // means that the timestamp is in the future.
  int age(void);
  int ageus(void); // same as age() but in us

  // set timestamp to one of the lowest possible timestamp
  // (not necessarily "the" lowest, because we want to keep timestamps unique)
  // The illegal timestamp is actually the lowest timestamp
  void setLowest(void);
  void setHighest(void);

  // sets timestamp as an illegal timestamp. It is also the real lowest
  // timestamp.
  void setIllegal(void){ d[0] = d[1] = 0; }
  bool isIllegal(void){ return (d[0]==0 && d[1]==0); }
  static int cmp(const Timestamp &l, const Timestamp &r){
    if (l.d[0] < r.d[0]) return -1;
    if (l.d[0] > r.d[0]) return +1;
    // l.d[0] == r.d[0]
    if (l.d[1] < r.d[1]) return -1;
    if (l.d[1] > r.d[1]) return +1;
    return 0;
  }

  // adds time to the timstamp. The time is given in ms, and it can be negative
  void addMs(i64 ms){ d[0] = d[0] + 1000*ms; }

  // gets a timestamp a little bit bigger while maintaining the same unique
  // id part
  void addEpsilon();

  // check if ts is bigger than time now, and if so set advance appropriately
  static void catchup(Timestamp &ts);
};

#endif


text:
<!DOCTYPE html>

    <title>Ag Floating Label Demo</title>
    <link rel="stylesheet" type="text/css" href="../dist/floating-label.css">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" type="text/css" href="./bootstrap/bootstrap.css"/>
    <link rel="stylesheet" type="text/css" href="./examples.css"/>

    <link href="https://fonts.googleapis.com/icon?family=Material+Icons"
          rel="stylesheet">

            ag-floating-label

                    View on GitHub

                        (view on github)

Floating Label Inputs for AngularJS

Brought to you via <nobr><ag-floating-label></nobr>

Demos, please!

                        Standard Inputs

                    <ag-floating-label>

                            Name

                        <input type="text" ng-model="name" name="name"/>
                    </ag-floating-label>
                    <ag-floating-label>

                            City

                        <input type="text" ng-model="name" name="name"/>
                    </ag-floating-label>
                    <ag-floating-label>

                            State

                        <select ng-model="selected" name="select">
                            <option value="DC">DC</option>
                            <option value="DC">MD</option>
                            <option value="DC">VA</option>
                            <option value="DC">None of the above</option>
                        </select>
                    </ag-floating-label>

                        Inputs with Hints

                    <ag-floating-label>

                            Name

                        <input type="text" ng-model="name" name="name"/>
                        <ag-hints>
                            <ag-hint>Enter your name</ag-hint>
                        </ag-hints>
                    </ag-floating-label>
                    <ag-floating-label>

                            City

                        <input type="text" ng-model="name" name="name"/>
                        <ag-hints>
                            <ag-hint>Enter your city, any city at all!</ag-hint>
                        </ag-hints>
                    </ag-floating-label>
                    <ag-floating-label>

                            State

                        <select ng-model="selected" name="select">
                            <option value="DC">DC</option>
                            <option value="DC">MD</option>
                            <option value="DC">VA</option>
                            <option value="DC">None of the above</option>
                        </select>
                    </ag-floating-label>

                        Inputs with Hints, and Errors

                    <form name="errorsForm">
                        <ag-floating-label>

                                Name (with hint and error)

                            <input type="text" ng-model="errorsFormName" name="name" ng-minlength="5"/>
                            <ag-hints>
                                <ag-hint>
                                    To show the error, enter a name less than 5 characters
                                </ag-hint>
                            </ag-hints>

Please enter at least 5 characters

                        </ag-floating-label>
                        <ag-floating-label>

                                City (with error only) *

                            <input type="text"
                                   ng-model="errorsFormCity"
                                   name="city"
                                   maxlength="30"
                                   minlength="5"
                                   required
                            />

Please enter at least 5 characters

Required

                        </ag-floating-label>
                        <ag-floating-label>

                                State *

                            <select ng-model="errorsFormState" name="state" required>
                                <option value="DC">DC</option>
                                <option value="DC">MD</option>
                                <option value="DC">VA</option>
                                <option value="DC">None of the above</option>
                            </select>

This field is required

                        </ag-floating-label>
                    </form>

                        A multi-column form using Bootstrap row and col classes

                    <form name="bootstrapForm">

                                <ag-floating-label>
                                    Name
                                    <input type="text" ng-model="bootstrapFormName" name="name"/>
                                </ag-floating-label>

                                <ag-floating-label>
                                    Age
                                    <input type="number" ng-model="bootstrapFormAge" name="age" min="18"/>
                                    <ag-hints>
                                        <ag-hint>
                                            18+
                                        </ag-hint>
                                    </ag-hints>

You must be 18 to continue

                                </ag-floating-label>

                                <ag-floating-label>
                                    Gender *
                                    <select ng-model="bootstrapFormGender" name="gender" required>
                                        <option value="DC">Male</option>
                                        <option value="DC">Female</option>
                                        <option value="DC">Neither</option>
                                        <option value="DC">Both</option>
                                    </select>

Please select your gender

                                </ag-floating-label>

                                <ag-floating-label>
                                    Comments
                                    <textarea rows="4" ag-no-autogrow></textarea>
                                    <ag-hints>
                                        <ag-hint>
                                            A great big textarea, which will maintain it's current size when multiple lines are added.
                                        </ag-hint>
                                    </ag-hints>
                                </ag-floating-label>

                    </form>

                        Icon support using bootstrap's input groups style.  <ag-input-group>

                    <form name="iconForm">

                                <ag-floating-label>
                                    Name

                                            person

                                        <input type="text" required ng-model="iconFormName" name="name"/>

                                    <ag-hints>
                                        <ag-hint>
                                            What should we call you?
                                        </ag-hint>
                                    </ag-hints>

Please select a name

                                </ag-floating-label>

                                <ag-floating-label>
                                    Phone

                                            phone

                                        <input type="phone" ng-model="iconFormPhone" name="phone"/>

                                    <ag-hints>
                                        <ag-hint>
                                            How can we reach you?
                                        </ag-hint>
                                    </ag-hints>
                                </ag-floating-label>

                                <ag-floating-label>
                                    Email

                                            email

                                        <input type="email" ng-model="iconsFormEmail" name="email"/>

                                    <ag-hints>
                                        <ag-hint>
                                            Where should we direct the spam? :-)
                                        </ag-hint>
                                    </ag-hints>

Please enter a valid email

                                </ag-floating-label>

                    </form>

                        Icon support using <ag-icon>

                    <form name="iconForm">

                                <ag-floating-label>
                                    Name
                                    <ag-icon>
                                        person
                                    </ag-icon>
                                    <input type="text" required ng-model="iconFormName" name="name"/>
                                    <ag-hints>
                                        <ag-hint>
                                            What should we call you?
                                        </ag-hint>
                                    </ag-hints>

Please select a name

                                </ag-floating-label>

                                <ag-floating-label>
                                    Phone
                                    <ag-icon>
                                        phone
                                    </ag-icon>
                                    <input type="phone" ng-model="iconFormPhone" name="phone"/>
                                    <ag-hints>
                                        <ag-hint>
                                            How can we reach you?
                                        </ag-hint>
                                    </ag-hints>
                                </ag-floating-label>

                                <ag-floating-label>
                                    Email
                                    <ag-icon>
                                        email
                                    </ag-icon>
                                    <input type="email" ng-model="iconsFormEmail" name="email"/>
                                    <ag-hints>
                                        <ag-hint>
                                            Where should we direct the spam? :-)
                                        </ag-hint>
                                    </ag-hints>

Please enter a valid email

                                </ag-floating-label>

                    </form>

            See the
            examples folder for the raw code.

            Go to GitHub

            Created with ♥ by

                Stephen Gardner


text:
<meta charset="UTF-8">
<title>WIMSDataFragment.<init> - </title>
<link rel="stylesheet" href="../../style.css">

com.epimorphics.android.myrivers.fragments / WIMSDataFragment / <init>

<init>

WIMSDataFragment()

A fragment occupying top part of the screen showcasing basic WIMSPoint Measurements.
It is initiated by clicking a WIMSPoint marker in DataViewActivity

See Also

DataViewActivity


text:
#ifndef CAF_SCHEDULER_ABSTRACT_COORDINATOR_HPP
#define CAF_SCHEDULER_ABSTRACT_COORDINATOR_HPP

#include <chrono>
#include <atomic>
#include <cstddef>

#include "caf/fwd.hpp"
#include "caf/atom.hpp"
#include "caf/actor.hpp"
#include "caf/channel.hpp"
#include "caf/message.hpp"
#include "caf/duration.hpp"
#include "caf/actor_addr.hpp"

namespace caf {
namespace scheduler {

/// A coordinator creates the workers, manages delayed sends and
/// the central printer instance for {@link aout}. It also forwards
/// sends from detached workers or non-actor threads to randomly
/// chosen workers.
class abstract_coordinator {
public:
  friend class detail::singletons;

  explicit abstract_coordinator(size_t num_worker_threads);

  virtual ~abstract_coordinator();

  /// Returns a handle to the central printing actor.
  inline actor printer() const {
    return printer_;
  }

  /// Puts `what` into the queue of a randomly chosen worker.
  virtual void enqueue(resumable* what) = 0;

  template <class Duration, class... Data>
  void delayed_send(Duration rel_time, actor_addr from, channel to,
                    message_id mid, message data) {
    timer_->enqueue(invalid_actor_addr, invalid_message_id,
                     make_message(duration{rel_time}, std::move(from),
                                  std::move(to), mid, std::move(data)),
                     nullptr);
  }

  inline size_t num_workers() const {
    return num_workers_;
  }

protected:
  abstract_coordinator();

  virtual void initialize();

  virtual void stop() = 0;

  void stop_actors();

  // Creates a default instance.
  static abstract_coordinator* create_singleton();

  inline void dispose() {
    delete this;
  }

  actor timer_;
  actor printer_;

  // ID of the worker receiving the next enqueue
  std::atomic<size_t> next_worker_;

  size_t num_workers_;
};

} // namespace scheduler
} // namespace caf

#endif // CAF_SCHEDULER_ABSTRACT_COORDINATOR_HPP


text:
""" Testing

"""
from __future__ import division, print_function, absolute_import

import sys

from io import BytesIO
cStringIO = BytesIO

import numpy as np

from nose.tools import assert_true, assert_false, \
     assert_equal, assert_raises

from numpy.testing import assert_array_equal, assert_array_almost_equal, \
     run_module_suite

from scipy._lib.six import u

import scipy.io.matlab.byteordercodes as boc
import scipy.io.matlab.streams as streams
import scipy.io.matlab.mio5_params as mio5p
import scipy.io.matlab.mio5_utils as m5u

def test_byteswap():
    for val in (
        1,
        0x100,
        0x10000):
        a = np.array(val, dtype=np.uint32)
        b = a.byteswap()
        c = m5u.byteswap_u4(a)
        yield assert_equal, b.item(), c
        d = m5u.byteswap_u4(c)
        yield assert_equal, a.item(), d

def _make_tag(base_dt, val, mdtype, sde=False):
    ''' Makes a simple matlab tag, full or sde '''
    base_dt = np.dtype(base_dt)
    bo = boc.to_numpy_code(base_dt.byteorder)
    byte_count = base_dt.itemsize
    if not sde:
        udt = bo + 'u4'
        padding = 8 - (byte_count % 8)
        all_dt = [('mdtype', udt),
                  ('byte_count', udt),
                  ('val', base_dt)]
        if padding:
            all_dt.append(('padding', 'u1', padding))
    else:  # is sde
        udt = bo + 'u2'
        padding = 4-byte_count
        if bo == '<':  # little endian
            all_dt = [('mdtype', udt),
                      ('byte_count', udt),
                      ('val', base_dt)]
        else:  # big endian
            all_dt = [('byte_count', udt),
                      ('mdtype', udt),
                      ('val', base_dt)]
        if padding:
            all_dt.append(('padding', 'u1', padding))
    tag = np.zeros((1,), dtype=all_dt)
    tag['mdtype'] = mdtype
    tag['byte_count'] = byte_count
    tag['val'] = val
    return tag

def _write_stream(stream, *strings):
    stream.truncate(0)
    stream.seek(0)
    for s in strings:
        stream.write(s)
    stream.seek(0)

def _make_readerlike(stream, byte_order=boc.native_code):
    class R(object):
        pass
    r = R()
    r.mat_stream = stream
    r.byte_order = byte_order
    r.struct_as_record = True
    r.uint16_codec = sys.getdefaultencoding()
    r.chars_as_strings = False
    r.mat_dtype = False
    r.squeeze_me = False
    return r

def test_read_tag():
    # mainly to test errors
    # make reader-like thing
    str_io = BytesIO()
    r = _make_readerlike(str_io)
    c_reader = m5u.VarReader5(r)
    # This works for StringIO but _not_ cStringIO
    yield assert_raises, IOError, c_reader.read_tag
    # bad SDE
    tag = _make_tag('i4', 1, mio5p.miINT32, sde=True)
    tag['byte_count'] = 5
    _write_stream(str_io, tag.tostring())
    yield assert_raises, ValueError, c_reader.read_tag

def test_read_stream():
    tag = _make_tag('i4', 1, mio5p.miINT32, sde=True)
    tag_str = tag.tostring()
    str_io = cStringIO(tag_str)
    st = streams.make_stream(str_io)
    s = streams._read_into(st, tag.itemsize)
    yield assert_equal, s, tag.tostring()

def test_read_numeric():
    # make reader-like thing
    str_io = cStringIO()
    r = _make_readerlike(str_io)
    # check simplest of tags
    for base_dt, val, mdtype in (('u2', 30, mio5p.miUINT16),
                                 ('i4', 1, mio5p.miINT32),
                                 ('i2', -1, mio5p.miINT16)):
        for byte_code in ('<', '>'):
            r.byte_order = byte_code
            c_reader = m5u.VarReader5(r)
            yield assert_equal, c_reader.little_endian, byte_code == '<'
            yield assert_equal, c_reader.is_swapped, byte_code != boc.native_code
            for sde_f in (False, True):
                dt = np.dtype(base_dt).newbyteorder(byte_code)
                a = _make_tag(dt, val, mdtype, sde_f)
                a_str = a.tostring()
                _write_stream(str_io, a_str)
                el = c_reader.read_numeric()
                yield assert_equal, el, val
                # two sequential reads
                _write_stream(str_io, a_str, a_str)
                el = c_reader.read_numeric()
                yield assert_equal, el, val
                el = c_reader.read_numeric()
                yield assert_equal, el, val

def test_read_numeric_writeable():
    # make reader-like thing
    str_io = cStringIO()
    r = _make_readerlike(str_io, '<')
    c_reader = m5u.VarReader5(r)
    dt = np.dtype('<u2')
    a = _make_tag(dt, 30, mio5p.miUINT16, 0)
    a_str = a.tostring()
    _write_stream(str_io, a_str)
    el = c_reader.read_numeric()
    yield assert_true, el.flags.writeable

def test_zero_byte_string():
    # Tests hack to allow chars of non-zero length, but 0 bytes
    # make reader-like thing
    str_io = cStringIO()
    r = _make_readerlike(str_io, boc.native_code)
    c_reader = m5u.VarReader5(r)
    tag_dt = np.dtype([('mdtype', 'u4'), ('byte_count', 'u4')])
    tag = np.zeros((1,), dtype=tag_dt)
    tag['mdtype'] = mio5p.miINT8
    tag['byte_count'] = 1
    hdr = m5u.VarHeader5()
    # Try when string is 1 length
    hdr.set_dims([1,])
    _write_stream(str_io, tag.tostring() + b'        ')
    str_io.seek(0)
    val = c_reader.read_char(hdr)
    assert_equal(val, u(' '))
    # Now when string has 0 bytes 1 length
    tag['byte_count'] = 0
    _write_stream(str_io, tag.tostring())
    str_io.seek(0)
    val = c_reader.read_char(hdr)
    assert_equal(val, u(' '))
    # Now when string has 0 bytes 4 length
    str_io.seek(0)
    hdr.set_dims([4,])
    val = c_reader.read_char(hdr)
    assert_array_equal(val, [u(' ')] * 4)

if __name__ == "__main__":
    run_module_suite()


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Aecidium heliotropii-europaei J. Schröt.

### Remarks
null


text:
package com.microsoft.spring.data.gremlin.repository.config;

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

public class GremlinRepositoryRegistrarUnitTest {

    private GremlinRepositoryRegistrar registrar;

    @Before
    public void setup() {
        this.registrar = new GremlinRepositoryRegistrar();
    }

    @Test
    public void testGremlinRepositoryRegistrarGetters() {
        Assert.assertSame(this.registrar.getAnnotation(), EnableGremlinRepositories.class);
        Assert.assertTrue(this.registrar.getExtension() instanceof GremlinRepositoryConfigurationExtension);
    }
}


text:
package org.opencompare.api.java.impl.io

import org.opencompare.api.java.extractor.CellContentInterpreter
import org.opencompare.api.java.impl.PCMFactoryImpl
import org.opencompare.api.java.io._

/**
 * Created by smangin on 01/06/15.
 */
class HtmlPCMCircularTestImpl extends HtmlPCMCircularTest (new PCMFactoryImpl, new CellContentInterpreter(new PCMFactoryImpl))


text:
<?php

namespace tests\unit;

use common\forms\ResetPassword;
use Faker\Factory;
use OTPHP\TOTP;
use Base32\Base32;
use Yii;

use yrc\models\redis\Code;

class ResetPasswordTest extends \tests\codeception\Unit
{
    use \Codeception\Specify;

    public function testInit()
    {
        $user = $this->register();
        $this->specify(
            'test init scenario', function () use ($user) {
                $form = new ResetPassword(['scenario' => ResetPassword::SCENARIO_INIT]);
                $form->email = $this->getUser()->email;

                expect('form validates', $form->validate())->true();
                expect('form does init', $form->reset())->true();
            }
        );
    }

    public function testReset()
    {
        $user = $this->register();
        $this->specify(
            'test reset scenario (with token)', function () use ($user) {
                // Generate a mock activation token
                $token = Base32::encode(\random_bytes(64));
                $code = new Code();
                $code->hash = hash('sha256', $token . '_reset_token');
                $code->user_id = $this->getUser()->id;

                expect('code saves', $code->save())->true();

                $faker = Factory::create();
                $form = new ResetPassword(['scenario' => ResetPassword::SCENARIO_RESET]);
                $form->password = $faker->password(24);
                $form->password_verify = $form->password;
                $form->reset_token = $token;

                expect('form validates', $form->validate())->true();
                expect('form resets', $form->reset())->true();
            }
        );

        $this->specify(
            'test reset scenario (with user)', function () use ($user) {
                $faker = Factory::create();
                $form = new ResetPassword(['scenario' => ResetPassword::SCENARIO_RESET]);
                $form->setUser($user);
                $token = Base32::encode(\random_bytes(64));
                $code = new Code();
                $code->hash = hash('sha256', $token . '_reset_token');
                $code->user_id = $this->getUser()->id;

                expect('code saves', $code->save())->true();
                $form->reset_token = $token;
                $form->password = $faker->password(24);
                $form->password_verify = $form->password;

                expect('form validates', $form->validate())->true();
                expect('form resets', $form->reset())->true();
            }
        );
    }

    public function testResetWithOTP()
    {
        $user = $this->register();
        $this->specify(
            'test that password cannot be reset if OTP is enabled', function () use ($user) {
                // Enable OTP on the account
                $this->getUser()->provisionOTP();
                $this->getUser()->enableOTP();

                expect('OTP is enabled', $this->getUser()->isOTPEnabled())->true();

                $faker = Factory::create();
                $form = new ResetPassword(['scenario' => ResetPassword::SCENARIO_RESET]);
                $form->setUser($user);
                $token = Base32::encode(\random_bytes(64));
                $code = new Code();
                $code->hash = hash('sha256', $token . '_reset_token');
                $code->user_id = $this->getUser()->id;

                expect('code saves', $code->save())->true();

                $form->reset_token = $token;
                $form->password = $faker->password(24);
                $form->password_verify = $form->password;

                expect('form validates', $form->validate())->false();
                expect('form has OTP error', $form->getErrors())->hasKey('otp');
            }
        );

        $this->specify(
            'tests password reset with valid OTP code', function () use ($user) {
                // Enable OTP on the account
                $this->getUser()->provisionOTP();
                $this->getUser()->enableOTP();

                expect('OTP is enabled', $this->getUser()->isOTPEnabled())->true();

                $totp = TOTP::create(
                    $this->getUser()->otp_secret,
                    30,
                    'sha256',
                    6
                );

                $totp->setLabel($this->getUser()->username);

                $faker = Factory::create();
                $form = new ResetPassword(['scenario' => ResetPassword::SCENARIO_RESET]);
                $form->setUser($user);
                $token = Base32::encode(\random_bytes(64));
                $code = new Code();
                $code->hash = hash('sha256', $token . '_reset_token');
                $code->user_id = $this->getUser()->id;

                expect('code saves', $code->save())->true();

                $form->reset_token = $token;
                $form->password = $faker->password(24);
                $form->password_verify = $form->password;
                $form->otp = $totp->now();

                expect('form validates', $form->validate())->true();
                expect('form resets', $form->reset())->true();
            }
        );
    }

    public function testAuthenticatedResetScenario()
    {
        $user = $this->register();
        $this->specify(
            'test authenticated password reset', function () use ($user) {
                $faker = Factory::create();
                $form = new ResetPassword(['scenario' => ResetPassword::SCENARIO_RESET_AUTHENTICATED]);
                $form->setUser($user);
                $form->user_id = $user;

                $form->password = $faker->password(24);
                $form->password_verify = $form->password;
                $form->old_password = $this->getPassword();

                expect('form validates', $form->validate())->true();
                expect('form resets', $form->reset())->true();
            }
        );

        $user = $this->register();
        $this->specify(
            'test authenticated password reset with OTP', function () use ($user) {
                $faker = Factory::create();
                $form = new ResetPassword(['scenario' => ResetPassword::SCENARIO_RESET_AUTHENTICATED]);

                // Enable OTP on the account
                $this->getUser()->provisionOTP();
                $this->getUser()->enableOTP();

                expect('OTP is enabled', $this->getUser()->isOTPEnabled())->true();

                $totp = TOTP::create(
                    $this->getUser()->otp_secret,
                    30,
                    'sha256',
                    6
                );

                $totp->setLabel($this->getUser()->username);

                $form->setUser($user);
                $form->user_id = $user;

                $form->password = $faker->password(24);
                $form->password_verify = $form->password;
                $form->old_password = $this->getPassword();
                $form->otp = $totp->now();

                expect('form validates', $form->validate())->true();
                expect('form resets', $form->reset())->true();
            }
        );
    }
}


text:
date: 2016-09-13T09:00:00+00:00
title: Artifacts
menu:
  main:
    identifier: "artifacts-v094"
    parent: "Using Vamp"
    weight: 10
---

{{< note title="The information on this page is written for Vamp v0.9.4" >}}

* Switch to the [latest version of this page](/documentation/using-vamp/artifacts).
* Read the [release notes](/documentation/release-notes/latest) for the latest Vamp release.
{{< /note >}}

Vamp has a few basic entities or artifacts you can work with, these can be classed as static resource descriptions and dynamic runtime entities. Note that API actions on static resource descriptions are mostly synchronous, while API actions on dynamic runtime entities are largely asychronous.

### Dynamic runtime entities

-   **Deployments** are running blueprints. You can have many deployments from one blueprint and perform actions on each at runtime. Plus, you can turn any running deployment into a blueprint.  [Read more...](/documentation/using-vamp/v0.9.4/deployments/)
-   **Gateways** are the "stable" routing endpoint - defined by a port (incoming) and routes (outgoing).  [Read more...](/documentation/using-vamp/v0.9.4/gateways/)
-   **Workflows** are apps (services) deployed on cluster, used for dynamically changing the runtime configuration (e.g. SLA, scaling, condition weight update).  [Read more...](/documentation/using-vamp/v0.9.4/workflows/)

### Static resource descriptions

-   **Blueprints** are, well, blueprints! They describe how breeds work in runtime and what properties they should have.  [Read more...](/documentation/using-vamp/v0.9.4/blueprints/)
-   **Breeds** describe single services and their dependencies.  [Read more...](/documentation/using-vamp/v0.9.4/breeds/)
-   **Scales** define the size of a deployed service [Read more...](/documentation/using-vamp/v0.9.4/blueprints/#scale)
-   **Conditions** define filters for incoming traffic [Read more...](/documentation/using-vamp/v0.9.4/conditions)

## Working across multiple teams

In larger companies with multiple teams working together on a large project, all required information is often not available at the same time. To facilitate this style of working, Vamp allows you to set placeholders. Placeholders let you communicate with other teams using simple references and gradually build up a complicated deployment. Vamp will only check references at deployment time, this means:

- Breeds can be referenced in blueprints before they exist
- You do not need to know the contents of an SLA when you reference it.
- You can reference a variable that someone else should fill in.

Read more about [referencing artifacts](/documentation/using-vamp/v0.9.4/references/) and [environment variables](/documentation/using-vamp/v0.9.4/environment-variables/).

{{< note title="What next?" >}}
* Read about [Vamp deployments](/documentation/using-vamp/v0.9.4/deployments/)
* Check the [API documentation](/documentation/api/v0.9.4/api-reference)
* [Try Vamp](/documentation/installation/hello-world)
{{< /note >}}