text:
from __future__ import print_function,division
import logging
import copy

try:
    import numpy as np
except ImportError:
    np = None

from ..hashutils import hasharray, hashcombine, hashdict

class Constraint(object):
    """
    Base class for all constraints to be applied to StarPopulations.
    """
    arrays = ('ok',)

    def __init__(self,mask,name='',**kwargs):
        self.name = name
        self.ok = np.array(mask)
        #self.frac = float(self.ok.sum())/np.size(mask)
        for kw in kwargs:
            setattr(self,kw,kwargs[kw])

    def __eq__(self,other):
        return hash(self) == hash(other)

    def __ne__(self,other):
        return not self.__eq__(other)

    def __hash__(self):
        return hashcombine(hash(self.name), hasharray(self.ok))

    def __str__(self):
        return self.name

    def __repr__(self):
        return '<%s: %s>' % (type(self),str(self))

    @property
    def N(self):
        return np.size(self.ok)

    @property
    def wok(self):
        return np.where(self.ok)[0]

    @property
    def frac(self):
        return float(self.ok.sum())/self.N

    def resample(self, inds):
        """Returns copy of constraint, with mask rearranged according to indices
        """
        new = copy.deepcopy(self)
        for arr in self.arrays:
            x = getattr(new, arr)
            setattr(new, arr, x[inds])
        return new

class ConstraintDict(dict):
    """
    A dictionary that is hashable.
    """
    def __hash__(self):
        return hashdict(self)

class JointConstraintAnd(Constraint):
    def __init__(self,c1,c2,name='',**kwargs):
        self.name = name
        mask = ~(~c1.ok & ~c2.ok)
        Constraint.__init__(self,mask,name=name,**kwargs)

class JointConstraintOr(Constraint):
    def __init__(self,c1,c2,name='',**kwargs):
        self.name = name
        mask = ~(~c1.ok | ~c2.ok)
        Constraint.__init__(self,mask,name=name,**kwargs)

class RangeConstraint(Constraint):
    arrays = Constraint.arrays + ('vals',)

    def __init__(self,vals,lo,hi,name='',**kwargs):
        self.lo = lo
        self.hi = hi
        Constraint.__init__(self,(vals > lo) & (vals < hi),
                            name=name,vals=vals,lo=lo,hi=hi,**kwargs)

    def __str__(self): #implement default string formatting better.....TODO
        return '{:.3g} < {} < {:.3g}'.format(self.lo,self.name,self.hi)

class UpperLimit(RangeConstraint):
    def __init__(self,vals,hi,name='',**kwargs):
        RangeConstraint.__init__(self,vals,name=name,lo=-np.inf,hi=hi,**kwargs)

    def __str__(self):
        return '{} < {:.3g}'.format(self.name,self.hi)

class LowerLimit(RangeConstraint):
    def __init__(self,vals,lo,name='',**kwargs):
        RangeConstraint.__init__(self,vals,name=name,lo=lo,hi=np.inf,**kwargs)

    def __str__(self):
        return '{} > {:.3g}'.format(self.name,self.lo)

class MeasurementConstraint(RangeConstraint):
    def __init__(self,vals,val,dval,thresh=3,name='',**kwargs):
        lo = val - thresh*dval
        hi = val + thresh*dval
        RangeConstraint.__init__(self,vals,lo,hi,name=name,val=val,
                                 dval=dval,thresh=thresh,**kwargs)

class FunctionLowerLimit(Constraint):
    arrays = Constraint.arrays + ('xs','ys')

    def __init__(self,xs,ys,fn,name='',**kwargs):
        Constraint.__init__(self,ys > fn(xs),name=name,xs=xs,ys=ys,fn=fn,**kwargs)

class FunctionUpperLimit(Constraint):
    arrays = Constraint.arrays + ('xs','ys')

    def __init__(self,xs,ys,fn,name='',**kwargs):
        Constraint.__init__(self,ys < fn(xs),name=name,
                            xs=xs,ys=ys,fn=fn,**kwargs)


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Moniliopsis fagi Konopacka

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
layout: post
image: /using-instructional-interactivity.png
tags: [elearning-cat, instructional-design-cat]
resource-url: http://learn.alleninteractions.com/instructional-interactivity
access: Requires Email
resource-type: Ebook
resource-author: Ethan Edwards
resource-org: Allen Interactions
title: "Using Instructional Interactivity to Improve e-Learning Designs!"
---
{% include JB/setup %}

In this e-book, Ethan Edwards covers the concept of instructional interactivity, and demonstrates how it can transform the learning experience for learners working independently through an e-learning program. Gain understanding of the four essential components of instructional interactivity, CCAF, which include: Context, Challenge, Activity, and Feedback.


text:
package org.guvnor.ala.services.api;

/**
 * Helper class for building a RuntimeQuery.
 * @see RuntimeQuery
 */
public class RuntimeQueryBuilder {

    private String providerId;

    private String pipelineId;

    private String pipelineExecutionId;

    private String runtimeId;

    private String runtimeName;

    private RuntimeQueryBuilder() {
    }

    public static RuntimeQueryBuilder newInstance() {
        return new RuntimeQueryBuilder();
    }

    public RuntimeQueryBuilder withProviderId(String providerId) {
        this.providerId = providerId;
        return this;
    }

    public RuntimeQueryBuilder withPipelineId(String pipelineId) {
        this.pipelineId = pipelineId;
        return this;
    }

    public RuntimeQueryBuilder withPipelineExecutionId(String pipelineExecutionId) {
        this.pipelineExecutionId = pipelineExecutionId;
        return this;
    }

    public RuntimeQueryBuilder withRuntimeId(String runtimeId) {
        this.runtimeId = runtimeId;
        return this;
    }

    public RuntimeQueryBuilder withRuntimeName(String runtimeName) {
        this.runtimeName = runtimeName;
        return this;
    }

    public RuntimeQuery build() {
        return new RuntimeQuery(providerId,
                                pipelineId,
                                pipelineExecutionId,
                                runtimeId,
                                runtimeName);
    }
}


text:
package metadslx.compiler;

import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CommonTokenStream;

import metadslx.compiler.MetaGeneratorParser.MainContext;

public class MetaGeneratorCompiler extends MetaCompiler {
	private MetaGeneratorLexer lexer;
	private MetaGeneratorParser parser;
	private MainContext parseTree;

	public MetaGeneratorCompiler(String source, String fileName) {
		super(source, fileName);
	}

	@Override
	protected void doCompile() {
		ANTLRInputStream inputStream = new ANTLRInputStream(this.getSource());
		this.lexer = new MetaGeneratorLexer(inputStream);
		this.lexer.addErrorListener(this);
		this.setCommonTokenStream(new CommonTokenStream(this.lexer));
		this.parser = new MetaGeneratorParser(this.getCommonTokenStream());
		this.parser.addErrorListener(this);
		this.parseTree = this.parser.main();
	}

	public MetaGeneratorLexer getLexer() {
		return lexer;
	}

	public MetaGeneratorParser getParser() {
		return parser;
	}

	public MainContext getParseTree() {
		return parseTree;
	}

}


text:
package template

const TemplateMainAutoScalingGroup = `
{{- define "auto_scaling_group" -}}
  NodePoolAutoScalingGroup:
    Type: AWS::AutoScaling::AutoScalingGroup
    Properties:
      VPCZoneIdentifier:
      {{- range $s := .AutoScalingGroup.Subnets }}
        - !Ref {{ $s }}
      {{- end }}
      AvailabilityZones:
      {{- range $az := .AutoScalingGroup.AvailabilityZones }}
        - {{ $az }}
      {{- end }}
      DesiredCapacity: {{ .AutoScalingGroup.DesiredCapacity }}
      MinSize: {{ .AutoScalingGroup.MinSize }}
      MaxSize: {{ .AutoScalingGroup.MaxSize }}
      MixedInstancesPolicy:
        LaunchTemplate:
          LaunchTemplateSpecification:
            LaunchTemplateId: !Ref NodePoolLaunchTemplate
            Version: !GetAtt NodePoolLaunchTemplate.LatestVersionNumber
          {{- if  .AutoScalingGroup.LaunchTemplateOverrides }}
          Overrides:
          {{- range $s := .AutoScalingGroup.LaunchTemplateOverrides }}
            - InstanceType: {{ $s.InstanceType }}
              WeightedCapacity: {{ $s.WeightedCapacity }}
          {{- end }}
          {{- end }}
        InstancesDistribution:
          OnDemandBaseCapacity: {{ .AutoScalingGroup.OnDemandBaseCapacity }}
          OnDemandPercentageAboveBaseCapacity: {{ .AutoScalingGroup.OnDemandPercentageAboveBaseCapacity }}
          SpotAllocationStrategy: {{ .AutoScalingGroup.SpotAllocationStrategy }}
          SpotInstancePools: {{ .AutoScalingGroup.SpotInstancePools }}
      # We define a lifecycle hook as part of the ASG in order to drain nodes
      # properly on Node Pool deletion. Earlier we defined a separate lifecycle
      # hook referencing the ASG name. In this setting when deleting a Node Pool
      # the lifecycle hook was never executed. We always want node draining for
      # reliably managing customer workloads.
      LifecycleHookSpecificationList:
        - DefaultResult: CONTINUE
          HeartbeatTimeout: 3600
          LifecycleHookName: {{ .AutoScalingGroup.LifeCycleHookName }}
          LifecycleTransition: autoscaling:EC2_INSTANCE_TERMINATING

      # 10 seconds after a new node comes into service, the ASG checks the new
      # instance's health.
      HealthCheckGracePeriod: 10

      MetricsCollection:
        - Granularity: "1Minute"
      Tags:
        - Key: Name
          Value: {{ .AutoScalingGroup.Cluster.ID }}-worker
          PropagateAtLaunch: true
        - Key: k8s.io/cluster-autoscaler/enabled
          Value: true
          PropagateAtLaunch: false
        - Key: k8s.io/cluster-autoscaler/{{ .AutoScalingGroup.Cluster.ID }}
          Value: true
          PropagateAtLaunch: false
        - Key: k8s.io/cluster-autoscaler/node-template/label/giantswarm.io/machine-deployment
          Value: {{ .AutoScalingGroup.NodePool.ID }}
          PropagateAtLaunch: false
    UpdatePolicy:
      AutoScalingRollingUpdate:

        # Minimum amount of nodes that must always be running during a rolling
        # update.
        MinInstancesInService: {{ .AutoScalingGroup.MinInstancesInService }}

        # Maximum amount of nodes being rolled at the same time.
        MaxBatchSize: {{ .AutoScalingGroup.MaxBatchSize }}

        # After creating a new instance, pause the rolling update on the ASG for
        # specified time.
        PauseTime: {{ .AutoScalingGroup.PauseTime }}
{{- end -}}
`


text:
//
// PaketUpdateSearchCommand.cs
//
// Author:
//       Matt Ward <ward.matt@gmail.com>
//
// Copyright (c) 2015 Matthew Ward
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

using MonoDevelop.Core;

namespace MonoDevelop.Paket.Commands
{
	public class PaketUpdateSearchCommand : PaketSearchCommand
	{
		public PaketUpdateSearchCommand ()
			: base ("update")
		{
		}

		public override void Run ()
		{
			var commandLine = PaketCommandLine.CreateCommandLine ("update");
			var message = ProgressMonitorStatusMessageFactory.CreateUpdateMessage ();
			PaketServices.CommandRunner.Run (commandLine, message, NotifyAllPaketAndProjectFilesChangedInSolution);
		}

		public override string GetDescriptionMarkup ()
		{
			return GettextCatalog.GetString ("Recomputes the dependencies and updates packages.");
		}
	}
}


text:
package org.teavm.dependency;

import org.teavm.model.CallLocation;

/**
 *
 * @author Alexey Andreev
 */
public abstract class AbstractDependencyListener implements DependencyListener {
    @Override
    public void started(DependencyAgent agent) {
    }

    @Override
    public void classReached(DependencyAgent agent, String className, CallLocation location) {
    }

    @Override
    public void methodReached(DependencyAgent agent, MethodDependency method, CallLocation location) {
    }

    @Override
    public void fieldReached(DependencyAgent agent, FieldDependency field, CallLocation location) {
    }

    @Override
    public void completing(DependencyAgent agent) {
    }
}


text:
using FluentAssertions;
using NUnit.Framework;
using NWamp.Messages;
using System;

namespace NWamp.Test.Messages
{
    [TestFixture]
    public class SubscribeMessageFixture
    {
        private SubscribeMessage message;
        private readonly string topicUri = "http://sample.org/major#minor";

        [SetUp]
        public void Init()
        {
            message = new SubscribeMessage(topicUri);
        }

        [Test]
        public void message_type_implements_IMessage_interface()
        {
            (message is IMessage).Should().BeTrue();
        }

        [Test]
        public void parametrized_constructor_should_assign_all_parameters()
        {
            message.TopicUri.Should().Be(topicUri);
        }

        [Test]
        public void array_serialization_serializes_all_properties_in_correct_order()
        {
            var array = message.ToArray();

            array.Length.Should().Be(2);
            array[0].Should().Be(MessageTypes.Subscribe);
            array[1].Should().Be(topicUri);
        }
    }
}


text:
package com.movilizer.connector.newTests.mappers.models;

import com.fasterxml.jackson.annotation.JsonFormat;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;

public class MapperTestObject {

    private String stringField;
    private int intField;
    private boolean booleanField;
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
    private GregorianCalendar dateField;
    private MapperTestSubObject objectField;
    private List<MapperTestSubObject> objectFieldList;
    private byte[] image;

    public MapperTestObject() {
    }

    public String getStringField() {
        return stringField;
    }

    public void setStringField(String stringField) {
        this.stringField = stringField;
    }

    public GregorianCalendar getDateField() {
        return dateField;
    }

    public void setDateField(GregorianCalendar dateField) {
        this.dateField = dateField;
    }

    public int getIntField() {
        return intField;
    }

    public void setIntField(int intField) {
        this.intField = intField;
    }

    public boolean isBooleanField() {
        return booleanField;
    }

    public void setBooleanField(boolean booleanField) {
        this.booleanField = booleanField;
    }

    public MapperTestSubObject getObjectField() {
        return objectField;
    }

    public void setObjectField(MapperTestSubObject objectField) {
        this.objectField = objectField;
    }

    public List<MapperTestSubObject> getObjectFieldList() {
        return objectFieldList;
    }

    public void setObjectFieldList(List<MapperTestSubObject> objectFieldList) {
        this.objectFieldList = objectFieldList;
    }

    public byte[] getImage() {
        return image;
    }

    public void setImage(byte[] image) {
        this.image = image;
    }

    public static MapperTestObject createTestObject() {
        MapperTestObject testObject = new MapperTestObject();
        testObject.setBooleanField(true);
        testObject.setIntField(100);
        GregorianCalendar calendar = new GregorianCalendar();
        calendar.set(2015, Calendar.JANUARY, 1);
        testObject.setDateField(calendar);

        MapperTestSubObject subObject1 = new MapperTestSubObject();
        subObject1.setStringField("test");
        testObject.setObjectField(subObject1);

        MapperTestSubObject subObject2 = new MapperTestSubObject();
        subObject2.setStringField("test");
        subObject2.setIntegerField(1);

        List<MapperTestSubObject> list = new ArrayList<>();
        list.add(subObject1);
        list.add(subObject2);
        testObject.setObjectFieldList(list);
        testObject.setStringField("test");

        testObject.setImage(new byte[]{'a', 'b'});

        return testObject;
    }

}


text:
package io.gatling.http.request.builder

import io.gatling.core.CoreComponents
import io.gatling.core.body.{ Body, RawFileBodies }
import io.gatling.core.session._
import io.gatling.http.action.sync.HttpRequestActionBuilder
import io.gatling.http.{ HeaderValues, HeaderNames }
import io.gatling.http.check.HttpCheck
import io.gatling.http.check.HttpCheckScope.Status
import io.gatling.http.protocol.HttpComponents
import io.gatling.http.request._
import io.gatling.http.response.Response

import com.softwaremill.quicklens._

case class HttpAttributes(
    checks:                List[HttpCheck]                             = Nil,
    ignoreDefaultChecks:   Boolean                                     = false,
    silent:                Option[Boolean]                             = None,
    followRedirect:        Boolean                                     = true,
    discardResponseChunks: Boolean                                     = true,
    responseTransformer:   Option[PartialFunction[Response, Response]] = None,
    explicitResources:     List[HttpRequestBuilder]                    = Nil,
    body:                  Option[Body]                                = None,
    bodyParts:             List[BodyPart]                              = Nil,
    formParams:            List[HttpParam]                             = Nil,
    form:                  Option[Expression[Map[String, Any]]]        = None,
    extraInfoExtractor:    Option[ExtraInfoExtractor]                  = None
)

object HttpRequestBuilder {

  implicit def toActionBuilder(requestBuilder: HttpRequestBuilder): HttpRequestActionBuilder =
    new HttpRequestActionBuilder(requestBuilder)

  val MultipartFormDataValueExpression = HeaderValues.MultipartFormData.expressionSuccess
  val ApplicationFormUrlEncodedValueExpression = HeaderValues.ApplicationFormUrlEncoded.expressionSuccess
}

/**
 * This class serves as model for all HttpRequestBuilders
 *
 * @param httpAttributes the base HTTP attributes
 */
case class HttpRequestBuilder(commonAttributes: CommonAttributes, httpAttributes: HttpAttributes) extends RequestBuilder[HttpRequestBuilder] {

  private[http] def newInstance(commonAttributes: CommonAttributes): HttpRequestBuilder = new HttpRequestBuilder(commonAttributes, httpAttributes)

  /**
   * Stops defining the request and adds checks on the response
   *
   * @param checks the checks that will be performed on the response
   */
  def check(checks: HttpCheck*): HttpRequestBuilder = this.modify(_.httpAttributes.checks).using(_ ::: checks.toList)

  /**
   * Ignore the default checks configured on HttpProtocol
   */
  def ignoreDefaultChecks: HttpRequestBuilder = this.modify(_.httpAttributes.ignoreDefaultChecks).setTo(true)

  def silent: HttpRequestBuilder = this.modify(_.httpAttributes.silent).setTo(Some(true))

  def notSilent: HttpRequestBuilder = this.modify(_.httpAttributes.silent).setTo(Some(false))

  def disableFollowRedirect: HttpRequestBuilder = this.modify(_.httpAttributes.followRedirect).setTo(false)

  def extraInfoExtractor(f: ExtraInfoExtractor): HttpRequestBuilder = this.modify(_.httpAttributes.extraInfoExtractor).setTo(Some(f))

  /**
   * @param responseTransformer transforms the response before it's handled to the checks pipeline
   */
  def transformResponse(responseTransformer: PartialFunction[Response, Response]): HttpRequestBuilder = this.modify(_.httpAttributes.responseTransformer).setTo(Some(responseTransformer))

  def body(bd: Body): HttpRequestBuilder = this.modify(_.httpAttributes.body).setTo(Some(bd))

  def processRequestBody(processor: Body => Body): HttpRequestBuilder = this.modify(_.httpAttributes.body).using(_.map(processor))

  def bodyPart(bodyPart: BodyPart): HttpRequestBuilder = this.modify(_.httpAttributes.bodyParts).using(_ ::: List(bodyPart))

  def resources(res: HttpRequestBuilder*): HttpRequestBuilder = this.modify(_.httpAttributes.explicitResources).setTo(res.toList)

  def disableResponseChunksDiscarding = this.modify(_.httpAttributes.discardResponseChunks).setTo(false)

  /**
   * Adds Content-Type header to the request set with "multipart/form-data" value
   */
  def asMultipartForm = header(HeaderNames.ContentType, HttpRequestBuilder.MultipartFormDataValueExpression)
  def asFormUrlEncoded = header(HeaderNames.ContentType, HttpRequestBuilder.ApplicationFormUrlEncodedValueExpression)

  def formParam(key: Expression[String], value: Expression[Any]): HttpRequestBuilder = formParam(SimpleParam(key, value))
  def multivaluedFormParam(key: Expression[String], values: Expression[Seq[Any]]) = formParam(MultivaluedParam(key, values))

  def formParamSeq(seq: Seq[(String, Any)]): HttpRequestBuilder = formParamSeq(seq2SeqExpression(seq))
  def formParamSeq(seq: Expression[Seq[(String, Any)]]): HttpRequestBuilder = formParam(ParamSeq(seq))

  def formParamMap(map: Map[String, Any]): HttpRequestBuilder = formParamSeq(map2SeqExpression(map))
  def formParamMap(map: Expression[Map[String, Any]]): HttpRequestBuilder = formParam(ParamMap(map))

  private def formParam(formParam: HttpParam): HttpRequestBuilder =
    this.modify(_.httpAttributes.formParams).using(_ ::: List(formParam))

  def form(form: Expression[Map[String, Any]]): HttpRequestBuilder =
    this.modify(_.httpAttributes.form).setTo(Some(form))

  def formUpload(name: Expression[String], filePath: Expression[String])(implicit rawFileBodies: RawFileBodies) =
    bodyPart(BodyPart.rawFileBodyPart(Some(name), filePath))

  /**
   * This method builds the request that will be sent
   *
   * @param coreComponents the CoreComponents
   * @param httpComponents the HttpComponents
   * @param throttled if throttling is enabled
   */
  def build(coreComponents: CoreComponents, httpComponents: HttpComponents, throttled: Boolean): HttpRequestDef = {

    val httpProtocol = httpComponents.httpProtocol

    val checks =
      if (httpAttributes.ignoreDefaultChecks)
        httpAttributes.checks
      else
        httpProtocol.responsePart.checks ::: httpAttributes.checks

    val resolvedChecks =
      if (checks.exists(_.scope == Status))
        checks
      else
        checks ::: List(RequestBuilder.DefaultHttpCheck)

    val resolvedFollowRedirect = httpProtocol.responsePart.followRedirect && httpAttributes.followRedirect

    val resolvedResponseTransformer = httpAttributes.responseTransformer.orElse(httpProtocol.responsePart.responseTransformer)

    val resolvedResources = httpAttributes.explicitResources.map(_.build(coreComponents, httpComponents, throttled))

    val resolvedExtraInfoExtractor = httpAttributes.extraInfoExtractor.orElse(httpProtocol.responsePart.extraInfoExtractor)

    val resolvedRequestExpression = new HttpRequestExpressionBuilder(commonAttributes, httpAttributes, coreComponents, httpComponents).build

    val resolvedDiscardResponseChunks = httpAttributes.discardResponseChunks && httpProtocol.responsePart.discardResponseChunks

    HttpRequestDef(
      commonAttributes.requestName,
      resolvedRequestExpression,
      HttpRequestConfig(
        checks = resolvedChecks,
        responseTransformer = resolvedResponseTransformer,
        extraInfoExtractor = resolvedExtraInfoExtractor,
        maxRedirects = httpProtocol.responsePart.maxRedirects,
        throttled = throttled,
        silent = httpAttributes.silent,
        followRedirect = resolvedFollowRedirect,
        discardResponseChunks = resolvedDiscardResponseChunks,
        coreComponents = coreComponents,
        httpComponents = httpComponents,
        explicitResources = resolvedResources
      )
    )
  }
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Collections.Generic;
using System.ComponentModel.Design;
using Xunit;

namespace System.ComponentModel.Tests
{
    public class EditorAttributeTests
    {
        [Fact]
        public void Ctor_Default()
        {
            var attribute = new EditorAttribute();
            Assert.Empty(attribute.EditorTypeName);
            Assert.Empty(attribute.EditorBaseTypeName);
        }

        [Theory]
        [InlineData("", null)]
        [InlineData("typeName", "")]
        [InlineData("typeName.dll", "baseTypeName")]
        public void Ctor_String_String(string typeName, string baseTypeName)
        {
            var attribute = new EditorAttribute(typeName, baseTypeName);
            Assert.Equal(typeName, attribute.EditorTypeName);
            Assert.Equal(baseTypeName, attribute.EditorBaseTypeName);
        }

        [Theory]
        [InlineData("", typeof(int))]
        [InlineData("typeName", typeof(EditorAttribute))]
        [InlineData("typeName.dll", typeof(EditorAttributeTests))]
        public void Ctor_String_Type(string typeName, Type baseType)
        {
            var attribute = new EditorAttribute(typeName, baseType);
            Assert.Equal(typeName, attribute.EditorTypeName);
            Assert.Equal(baseType.AssemblyQualifiedName, attribute.EditorBaseTypeName);
        }

        [Theory]
        [InlineData(typeof(EditorAttribute), typeof(int))]
        [InlineData(typeof(EditorAttributeTests), typeof(EditorAttribute))]
        [InlineData(typeof(int), typeof(EditorAttributeTests))]
        public void Ctor_Type_Type(Type type, Type baseType)
        {
            var attribute = new EditorAttribute(type, baseType);
            Assert.Equal(type.AssemblyQualifiedName, attribute.EditorTypeName);
            Assert.Equal(baseType.AssemblyQualifiedName, attribute.EditorBaseTypeName);
        }

        [Fact]
        public void Ctor_NullEditorTypeName_ThrowsArgumentNullException()
        {
            AssertExtensions.Throws<ArgumentNullException, NullReferenceException>(() => new EditorAttribute(null, "baseTypeName"));
            AssertExtensions.Throws<ArgumentNullException, NullReferenceException>(() => new EditorAttribute((string)null, typeof(int)));
        }

        [Fact]
        public void Ctor_NullType_ThrowsNullReferenceException()
        {
            Assert.Throws<NullReferenceException>(() => new EditorAttribute((Type)null, typeof(int)));
        }

        [Fact]
        public void Ctor_NullEditorBaseType_ThrowsNullReferenceException()
        {
            Assert.Throws<NullReferenceException>(() => new EditorAttribute("typeName", (Type)null));
            Assert.Throws<NullReferenceException>(() => new EditorAttribute(typeof(int), null));
        }

        [Theory]
        [InlineData("BaseTypeName", "System.ComponentModel.EditorAttributeBaseTypeName")]
        [InlineData("BaseTypeName,Other", "System.ComponentModel.EditorAttributeBaseTypeName")]
        public void TypeId_ValidEditorBaseTypeName_ReturnsExcepted(string baseTypeName, object expected)
        {
            var attribute = new EditorAttribute("Type", baseTypeName);
            Assert.Equal(expected, attribute.TypeId);
            Assert.Same(attribute.TypeId, attribute.TypeId);
        }

        [Fact]
        public void TypeId_NullBaseTypeName_ThrowsNullReferenceException()
        {
            var attribute = new EditorAttribute("Type", (string)null);
            Assert.Throws<NullReferenceException>(() => attribute.TypeId);
        }

        public static IEnumerable<object[]> Equals_TestData()
        {
            var attribute = new EditorAttribute("typeName", "baseTypeName");

            yield return new object[] { attribute, attribute, true };
            yield return new object[] { attribute, new EditorAttribute("typeName", "baseTypeName"), true };
            yield return new object[] { attribute, new EditorAttribute("typename", "baseTypeName"), false };
            yield return new object[] { attribute, new EditorAttribute("typeName", "basetypename"), false };
            yield return new object[] { attribute, new EditorAttribute("typeName", (string)null), false };

            yield return new object[] { new EditorAttribute("typeName", (string)null), new EditorAttribute("typeName", (string)null), true };
            yield return new object[] { new EditorAttribute("typeName", (string)null), new EditorAttribute("typename", (string)null), false };
            yield return new object[] { new EditorAttribute("typeName", (string)null), new EditorAttribute("typeName", "baseTypeName"), false };

            yield return new object[] { attribute, new object(), false };
            yield return new object[] { attribute, null, false };
        }

        [Theory]
        [MemberData(nameof(Equals_TestData))]
        public void Equals_Object_ReturnsExpected(EditorAttribute attribute, object other, bool expected)
        {
            Assert.Equal(expected, attribute.Equals(other));
        }

        [Fact]
        public void GetHashCode_Invoke_ReturnsConsistentValue()
        {
            var attribute = new EditorAttribute();
            Assert.Equal(attribute.GetHashCode(), attribute.GetHashCode());
        }
    }
}


text:
package io.moquette.broker.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Reader;
import java.text.ParseException;
import java.util.Properties;

/**
 * Configuration that loads config stream from a {@link IResourceLoader} instance.
 */
public class ResourceLoaderConfig extends IConfig {

    private static final Logger LOG = LoggerFactory.getLogger(ResourceLoaderConfig.class);

    private final Properties m_properties;
    private final IResourceLoader resourceLoader;

    public ResourceLoaderConfig(IResourceLoader resourceLoader) {
        this(resourceLoader, null);
    }

    public ResourceLoaderConfig(IResourceLoader resourceLoader, String configName) {
        LOG.info("Loading configuration. ResourceLoader = {}, configName = {}.", resourceLoader.getName(), configName);
        this.resourceLoader = resourceLoader;

        /*
         * If we use a conditional operator, the loadResource() and the loadDefaultResource()
         * methods will be always called. This makes the log traces confusing.
         */
        Reader configReader;
        if (configName != null) {
            configReader = resourceLoader.loadResource(configName);
        } else {
            configReader = resourceLoader.loadDefaultResource();
        }

        if (configReader == null) {
            LOG.error(
                    "The resource loader returned no configuration reader. ResourceLoader = {}, configName = {}.",
                    resourceLoader.getName(),
                    configName);
            throw new IllegalArgumentException("Can't locate " + resourceLoader.getName() + " \"" + configName + "\"");
        }

        LOG.info(
                "Parsing configuration properties. ResourceLoader = {}, configName = {}.",
                resourceLoader.getName(),
                configName);
        ConfigurationParser confParser = new ConfigurationParser();
        m_properties = confParser.getProperties();
        assignDefaults();
        try {
            confParser.parse(configReader);
        } catch (ParseException pex) {
            LOG.warn(
                    "Unable to parse configuration properties. Using default configuration. "
                    + "ResourceLoader = {}, configName = {}, cause = {}, errorMessage = {}.",
                    resourceLoader.getName(),
                    configName,
                    pex.getCause(),
                    pex.getMessage());
        }
    }

    @Override
    public void setProperty(String name, String value) {
        m_properties.setProperty(name, value);
    }

    @Override
    public String getProperty(String name) {
        return m_properties.getProperty(name);
    }

    @Override
    public String getProperty(String name, String defaultValue) {
        return m_properties.getProperty(name, defaultValue);
    }

    @Override
    public IResourceLoader getResourceLoader() {
        return resourceLoader;
    }

}


text:
/**
 *
 */
package com.ay.web.metrics.servlets;

import com.codahale.metrics.servlets.AdminServlet;

/**
 * AyAdminServlet is delegator to {@link AdminServlet} no need for a test
 * methods in the current implementation
 *
 * @author Youssef Arfaoui
 *
 *         Feb 16, 2015
 *
 */
public class AyAdminServletTest {

}


text:
class DockingSplitter;

#ifndef SPLITTER_CONTAINER_H
#include "SplitterContainer.h"
#endif //SPLITTER_CONTAINER_H

#define DSPC_CLASS_NAME TEXT("dockingManager")

using namespace std;

#define	CONT_MAP_MAX	50

class DockingManager : public Window
{
public :
	DockingManager();
	~DockingManager();

	void init(HINSTANCE hInst, HWND hWnd, Window ** ppWin);
	virtual void reSizeTo(RECT & rc);

	void setClientWnd(Window ** ppWin) {
		_ppWindow = ppWin;
		_ppMainWindow = ppWin;
	};

	void showContainer(HWND hCont, BOOL view = TRUE);

	void showContainer(UINT	uCont, BOOL view = TRUE) {
		_vContainer[uCont]->doDialog((view == TRUE));
		onSize();
	}

	void updateContainerInfo(HWND hClient);
	void createDockableDlg(tTbData data, int iCont = CONT_LEFT, bool isVisible = false);
	void setActiveTab(int iCont, int iItem);
	void showDockableDlg(HWND hDlg, BOOL view);
	void showDockableDlg(TCHAR* pszName, BOOL view);

	DockingCont* toggleActiveTb(DockingCont* pContSrc, UINT message, BOOL bNew = FALSE, LPRECT rcFloat = NULL);
	DockingCont* toggleVisTb(DockingCont* pContSrc, UINT message, LPRECT rcFloat = NULL);
	void		 toggleActiveTb(DockingCont* pContSrc, DockingCont* pContTgt);
	void		 toggleVisTb(DockingCont* pContSrc, DockingCont* pContTgt);

	// get number of container
	int  GetContainer(DockingCont* pCont);

	// get all container in vector
	vector<DockingCont*> & getContainerInfo() {
		return _vContainer;
	};
	// get dock data (sized areas)
	void getDockInfo(tDockMgr *pDockData) {
		*pDockData	= _dockData;
	};

	// setting styles of docking
	void setStyleCaption(BOOL captionOnTop) {
		_vContainer[CONT_TOP]->setCaptionTop(captionOnTop);
		_vContainer[CONT_BOTTOM]->setCaptionTop(captionOnTop);
	};

	void setTabStyle(BOOL orangeLine) {
		for (size_t i = 0; i < _vContainer.size(); ++i)
			_vContainer[i]->setTabStyle(orangeLine);
	};

	int getDockedContSize(int iCont);
	void setDockedContSize(int iCont, int iSize);
	virtual void destroy();

private :

	static LRESULT CALLBACK staticWinProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam);
	LRESULT runProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam);
	void onSize();

	void	toggleTb(DockingCont* pContSrc, DockingCont* pContTgt, tTbData TbData);

	// test if container exists
	BOOL ContExists(size_t iCont);
	int	 FindEmptyContainer();
	LRESULT SendNotify(HWND hWnd, UINT message);

private:
	Window						**_ppWindow;
	RECT						_rcWork;
	RECT						_rect;
	Window						**_ppMainWindow;
	vector<HWND>				_vImageList;
	HIMAGELIST					_hImageList;
	vector<DockingCont*>		_vContainer;
	tDockMgr					_dockData;
	static BOOL					_isRegistered;
	BOOL						_isInitialized;
	int							_iContMap[CONT_MAP_MAX];
	vector<DockingSplitter *>	_vSplitter;
};

#endif //DOCKINGMANAGER_H


text:
namespace mini_installer {

// A simple container of the mini_installer's configuration, as dictated by the
// command line used to invoke it.
class Configuration {
 public:
  enum Operation {
    INSTALL_PRODUCT,
    CLEANUP,
  };

  Configuration();
  ~Configuration();

  // Initializes this instance on the basis of the process's command line.
  bool Initialize(HMODULE module);

  // Returns the desired operation dictated by the command line options.
  Operation operation() const { return operation_; }

  // Returns the program portion of the command line, or NULL if it cannot be
  // determined (e.g., by misuse).
  const wchar_t* program() const;

  // Returns the number of arguments specified on the command line, including
  // the program itself.
  int argument_count() const { return argument_count_; }

  // Returns the original command line.
  const wchar_t* command_line() const { return command_line_; }

  // Returns the app guid to be used for Chrome. --chrome-sxs on the command
  // line makes this the canary's app guid (Google Chrome only).
  const wchar_t* chrome_app_guid() const { return chrome_app_guid_; }

  // Returns true if --system-level is on the command line or if
  // GoogleUpdateIsMachine=1 is set in the process's environment.
  bool is_system_level() const { return is_system_level_; }

  // Retuns true if --chrome-sxs is on the command line (Google Chrome only).
  bool is_side_by_side() const { return is_side_by_side_; }

  // Returns true if an existing multi-install Chrome is being updated (Google
  // Chrome only).
  bool is_updating_multi_chrome() const { return is_updating_multi_chrome_; }

  // Returns true if any invalid switch is found on the command line.
  bool has_invalid_switch() const { return has_invalid_switch_; }

  // Returns the previous version contained in the image's resource.
  const wchar_t* previous_version() const { return previous_version_; }

 protected:
  void Clear();
  bool ParseCommandLine(const wchar_t* command_line);
  void ReadResources(HMODULE module);

  wchar_t** args_;
  const wchar_t* chrome_app_guid_;
  const wchar_t* command_line_;
  int argument_count_;
  Operation operation_;
  bool is_system_level_;
  bool is_side_by_side_;
  bool is_updating_multi_chrome_;
  bool has_invalid_switch_;
  const wchar_t* previous_version_;

 private:
  Configuration(const Configuration&) = delete;
  Configuration& operator=(const Configuration&) = delete;

  // Returns true if multi-install Chrome is already present on the machine.
  bool IsUpdatingMultiChrome() const;
};

}  // namespace mini_installer

#endif  // CHROME_INSTALLER_MINI_INSTALLER_CONFIGURATION_H_


text:
using TwitterForUnity;

// Twitter for Unity の Setting からの分離
public static class TwitterKeysExtentions {
    public static Client CreateClient(this TwitterKeys keys)
    {
        var oauth = new Oauth(
            keys.ConsumerKey,
            keys.ConsumerSecret,
            keys.AccessToken,
            keys.AccessTokenSecret);
        return new Client(oauth);
    }
}


text:
typedef std::vector<DraggableElement*> ElementList;

class DragElemList : public QScrollArea
{
    Q_OBJECT
public:
    explicit DragElemList(QWidget *parent = 0);

    void changeActiveList(const ElementList* elemList);
protected:
    QWidget _elemListWidget;
    QVBoxLayout _layout;
};

#endif // DRAGELEMLIST_H


text:
(function() {

    var writeln = function(line) {
        $("#output").append(line).append("<br>");
    };

    var add = function addF(arg1, arg2) {
        var sum = arg1 + arg2;
        return sum;
    };

    var simpleCurryDemo = function simpleCurryDemoF() {

        var add1 = function add1F(arg2) {
            var result = add.call(null, 1, arg2);
            return result;
        };

        var add1To7 = add1(7);

        writeln(add1To7);
    };

    var converter = function(ratio, symbol, input) {
        return [
            (input * ratio).toFixed(1), symbol
        ].join(" ");
    };

    var curry = function curryF(func) {
        var curryArgs = Array.prototype.slice.call(arguments, 1);
        var curried = function curriedF() {
            var allArgs = curryArgs.concat(Array.prototype.slice.apply(arguments));
            var result = func.apply(null, allArgs);
            return result;
        };
        return curried;
    };

    var genericCurryDemo = function genericCurryDemoF() {
        var add1 = curry(add, 1);

        var add1To7 = add1(7);

        writeln(add1To7);

        var kilosToPounds = curry(converter, 2.2, "lbs");
        var milesToKilometers = curry(converter, 1.62, "km");

        var twoKilosEqualsNPounds = kilosToPounds(2);
        writeln("2 kilos = " + twoKilosEqualsNPounds);

        var twoMilesEqualsNKilometers = milesToKilometers(2);
        writeln("2 miles = " + twoMilesEqualsNKilometers);
    };

    $(document).ready(function() {
        simpleCurryDemo();
        genericCurryDemo();
    });

})();


text:
package com.adaptris.core.jms;

import com.adaptris.core.ProducerCase;

public abstract class JmsProducerExample extends ProducerCase {

  /**
   * Key in unit-test.properties that defines where example goes unless overriden {@link #setBaseDir(String)}.
   *
   */
  public static final String BASE_DIR_KEY = "JmsProducerExamples.baseDir";

  public JmsProducerExample(String name) {
    super(name);

    if (PROPERTIES.getProperty(BASE_DIR_KEY) != null) {
      setBaseDir(PROPERTIES.getProperty(BASE_DIR_KEY));
    }
  }
}


text:
package org.moskito.central.endpoints.rest;

import com.sun.jersey.test.framework.JerseyTest;

/**
 * Test class for MoSKito Central REST-endpoint.
 *
 * @author Vladyslav Bezuhlyi
 */
public class RESTEndpointTest extends JerseyTest {

    /*@Test
    public void testGetSnapshot() throws Exception {
        WebResource webResource = resource();
        String responseString = webResource.path("/central/getSnapshot").accept(MediaType.APPLICATION_JSON).get(String.class);
        System.out.println("*************************************\r\nresponseString=" + responseString);

        Snapshot responseSnapshot = webResource.path("/central/getSnapshot").accept(MediaType.APPLICATION_JSON).get(Snapshot.class);
        System.out.println("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\r\nresponseSnapshot=" + responseSnapshot);
        assertNotNull(responseSnapshot);
        assertNotNull(responseSnapshot.getStats());

        HashMap<String, HashMap<String, String>> stats = responseSnapshot.getStats();
        assertNotNull(stats);
        assertEquals(3, stats.size());
        assertNotNull(stats.get("test"));
        assertNotNull(stats.get("test2"));
        assertNotNull(stats.get("test3"));

        HashMap<String, String> test = stats.get("test");
        assertNotNull(test);
        assertEquals(2, test.size());
        assertNotNull(test.get("firstname"));
        assertNotNull(test.get("lastname"));
    }*/

}


text:
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeFamilies #-}
{-|
Module      : Marvin.API.Table.PrettyPrint
Description : Pretty printing tables and columns.
-}
module Marvin.API.Table.PrettyPrint where

import Control.Arrow

import Data.Text (Text)
import qualified Data.Text as Text
import Data.Vector (Vector, (!))
import qualified Data.Vector as Vec
import qualified Data.Vector.Unboxed as UVec
import Data.List (find, intersperse)
import Data.Maybe (isNothing)
import Data.Either (isRight)
import Data.ByteString (ByteString)
import Data.ByteString.Char8 (pack, unpack)

import Text.PrettyPrint.Boxes hiding (columns)
import qualified Text.PrettyPrint.Boxes as Boxes
import Text.Printf

import Marvin.API.Table.DataType
import Marvin.API.Fallible

import Marvin.API.Table.Internal
import Data.Typeable

import Control.Monad.Reader

-- * Pretty printable types

instance PrettyPrintable String where
  prettyPrint = return

instance PrettyPrintable Double where
  prettyPrint x = do
    numOfDecs <- asks numberOfDecimals
    return $ printf ("%." ++ show numOfDecs ++ "f") x

instance PrettyPrintable Bool where
  prettyPrint b = return $ show $ if b then 1 else 0

instance PrettyPrintable Text where
  prettyPrint = return . show

instance PrettyPrintable ByteString where
  prettyPrint = return . unpack

instance PrettyPrintable Int where
  prettyPrint = return . show

-- * Default configurations for showing

defaultPrettyPrintParams = PrettyPrintParams {
  numberOfDecimals = 3,
  maxNumberOfLinesToShow = 60,
  maxNumberOfColumnsInWindow = 5
}

withDefaultPrettyPrint :: Reader PrettyPrintParams a -> a
withDefaultPrettyPrint reader = runReader reader defaultPrettyPrintParams

defaultPrettyPrint :: PrettyPrintable a => a -> String
defaultPrettyPrint x = (runReader (prettyPrint x)) defaultPrettyPrintParams

defaultShowColumn :: (ColumnDataType a, PrettyPrintable (ColumnExposed a)) =>
  Column a -> String
defaultShowColumn col = runReader paramShown defaultPrettyPrintParams
  where
    paramShown = do
      bs <- prettyPrintColumnWithName col
      return $ "\n" ++ render (vcat Boxes.right (Vec.toList bs))

defaultShowTable :: (ColumnDataType a, PrettyPrintable (ColumnExposed a)) =>
  Table a -> String
defaultShowTable t = runReader (prettyPrintTable t) defaultPrettyPrintParams

defaultShowDataTable t = runReader (prettyPrintDataTable t) defaultPrettyPrintParams

-- * 'Show' instances for tables and columns --

-- ** Columns

instance Show DataColumn where
  show (DC c) = defaultShowColumn c

instance (ColumnDataType a, PrettyPrintable e,
  ColumnRepr a ~ r, ColumnExposed a ~ e) => Show (GenericColumn a r e) where
  show = defaultShowColumn

-- ** Tables

instance (ColumnDataType a, PrettyPrintable e,
  ColumnRepr a ~ r, ColumnExposed a ~ e) => Show (GenericTable a r e) where
  show = defaultShowTable

instance Show DataTable where
  show = defaultShowDataTable

instance Show RawTable where
  show t = runReader (ppTable prettyPrintColumnRaw t) defaultPrettyPrintParams

-- * Column pretty printing

prettyPrintColumnWithName :: (ColumnDataType a, PrettyPrintable (ColumnExposed a)) =>
  Column a -> Reader PrettyPrintParams (Vector Box)
prettyPrintColumnWithName col = do
  values <- prettyPrintColumn col
  let name = nameBox $ columnName col
  return $ Vec.cons name values

prettyPrintColumnRaw :: RawColumn -> Reader PrettyPrintParams (Vector Box)
prettyPrintColumnRaw col = do
  let colExposed = valuesRaw col
  prettyPrintVector colExposed

prettyPrintColumn :: (ColumnDataType a, PrettyPrintable (ColumnExposed a)) =>
  Column a -> Reader PrettyPrintParams (Vector Box)
prettyPrintColumn col = do
  let colExposed = Vec.map (exposure col) $ UVec.convert $ values col
  prettyPrintVector colExposed

ppDataColumn :: DataColumn -> Reader PrettyPrintParams (Vector Box)
ppDataColumn (DC col) = prettyPrintColumn col

-- | Pretty prints a vector by limiting the lines to show.
-- Shows the first n and last n values in a large column.
prettyPrintVector :: (PrettyPrintable a) =>
  Vector a -> Reader PrettyPrintParams (Vector Box)
prettyPrintVector vec = do
  maxLines <- asks maxNumberOfLinesToShow
  let dotBox = Vec.singleton $ text "..."

  let (startCol, endCol) = limitedLines maxLines vec
  start <- ppVec startCol
  end <- ppVec endCol
  let splitWithDots = start Vec.++ dotBox Vec.++ end

  if Vec.length vec <= maxLines + 1
    then ppVec vec
    else return $ splitWithDots

ppVec :: (PrettyPrintable a) => Vector a -> Reader PrettyPrintParams (Vector Box)
ppVec v = do
  vecStrings <- traverse prettyPrint v
  return $ Vec.map text vecStrings

-- | Splits a large column to a limited number of head elements and tail elements.
limitedLinesCol :: (ColumnDataType a) => Int -> Column a -> (Column a, Column a)
limitedLinesCol maxLines col = (col { values = UVec.convert v1 }, col { values = UVec.convert v2 })
  where
    (v1, v2) = limitedLines maxLines $ UVec.convert $ values col

-- | Splits a large 'Vector' to a limited number of head elements and tail elements.
limitedLines :: Int -> Vector a -> (Vector a, Vector a)
limitedLines maxLines xs = (Vec.take n xs, Vec.drop (Vec.length xs - m) xs)
  where
    m = maxLines `div` 2
    n = m + maxLines `mod` 2

-- | Creates a 'Box' from a name.
nameBox :: Fallible String -> Box
nameBox (Right name) = text name
nameBox (Left _) = emptyBox 1 1

-- * Table pretty printing

-- | Pretty prints a table with a given column pretty printer function.
ppTable :: (TableClass t) => (ColumnType t -> Reader PrettyPrintParams (Vector Box)) ->
  t -> Reader PrettyPrintParams String
ppTable ppColumn t = if n == 0 then return ("Empty table " ++ rowsAndCols) else do
    colValuesVec <- traverse ppColumn cols
    let colValues = fmap Vec.toList colValuesVec
    -- data columns aligned right
    let cols = fmap (vcat Boxes.right) colValues
    -- attached horizontal indices, names, and columns
    let tableBox = zipWith3 (\idx name vals -> vcat Boxes.right [idx,name,vals]) hIdx colNames cols
    -- vertical indices
    vIdxVec <- indexes 0 (m-1)
    -- vertical indices aligned left
    let vIdx = vcat Boxes.left $ (nameAboveVIdx : Vec.toList vIdxVec)
    -- partitioning to blocks
    blockSize <- asks maxNumberOfColumnsInWindow
    let blocks = slicesOfSize blockSize $ tableBox
    -- insert empty space between columns
    let blockToBox block = hcat Boxes.bottom (vIdx : emptyBox 1 1 : intersperse (emptyBox 1 2) block)
    let box = vcat Boxes.left $ intersperse (emptyBox 1 1) $ fmap blockToBox blocks
    return $ "\n" ++ render box  ++ "\n" ++ rowsAndCols
    where
      -- number of columns
      n = numberOfColumns t
      -- horizontal indexes
      hIdx = (map (text . show) [0..(n-1)])
      -- indicating the size
      rowsAndCols = "["
        ++ show (numberOfRows t) ++ " rows x "
        ++ show (numberOfColumns t) ++ " columns]"
      cols = Vec.toList $ columnsVec t
      m = numberOfRows t
      -- check if there is no column name
      noColNames = isNothing $ find (isRight . columnName) $ cols
      colNames = if noColNames
        then (fmap (const nullBox) cols)
        else (fmap ppColName cols)
      nameAboveVIdx = if noColNames
        then nullBox
        else emptyBox 1 1

prettyPrintTable :: (ColumnDataType a, PrettyPrintable (ColumnExposed a)) =>
  Table a -> Reader PrettyPrintParams String
prettyPrintTable t = ppTable prettyPrintColumn t

prettyPrintDataTable :: DataTable -> Reader PrettyPrintParams String
prettyPrintDataTable = ppTable ppDataColumn

-- | Creates a 'Box' from a column name.
ppColName :: (ColumnClass c) => c -> Box
ppColName = columnName >>> nameBox

-- | Creates a 'Vector Box' from a given range of integers.
indexes :: Int -> Int -> Reader PrettyPrintParams (Vector Box)
indexes from to = prettyPrintVector $ Vec.fromList [from..to]

-- | Slices up a list to lists of a given size.
slicesOfSize :: Int -> [a] -> [[a]]
slicesOfSize k = iterate (drop k)
  >>> takeWhile (not . null)
  >>> map (take k)


text:
using System;
using UnityEngine;
using System.Collections;
using System.Collections.Specialized;
using System.Diagnostics;

using Amazon;
using Amazon.Runtime.Internal.Util;
using Amazon.Runtime.Internal;
using Amazon.Util;
using System.Threading;
using Amazon.Util.Internal;

namespace Amazon
{
    /// <summary>
    /// A singleton instance of which will initialize the Main thread dispatcher & logger.
    /// This class is linked to the AWSPrefab so that user can make any configuration
    /// changes and instance will be included in every scene via the prefab.
    /// </summary>
    public class UnityInitializer : MonoBehaviour
    {

        private static UnityInitializer _instance = null;
        private static object _lock = new object();

        #region constructor
        private UnityInitializer(){}
        #endregion

        #region public api
        /// <summary>
        /// Attaches the initializer to a game object
        /// </summary>
        /// <param name="gameObject">The game object to which you attach the initializer to</param>
        public static void AttachToGameObject(GameObject gameObject)
        {
            if (gameObject != null)
            {
                gameObject.AddComponent<UnityInitializer>();
                UnityEngine.Debug.Log(string.Format(@"Attached unity initializer to {0}", gameObject.name));
            }
            else
            {
                throw new ArgumentNullException("gameObject");
            }

        }

        /// <summary>
        /// Returns the Instance of UnityInitializer
        /// </summary>
        public static UnityInitializer Instance
        {
            get
            {
                return _instance;
            }
        }

        public void Awake()
        {
            lock (_lock)
            {
                if (_instance == null)
                {
                    // singleton instance
                    _instance = this;

                    if (_mainThread == null || !_mainThread.Equals(Thread.CurrentThread))
                        _mainThread = Thread.CurrentThread;

                    AmazonHookedPlatformInfo.Instance.Init();

                    // preventing the instance from getting destroyed between scenes
                    DontDestroyOnLoad(this);

                    //initialize the logger
                    TraceListener tracelistener = new UnityDebugTraceListener("UnityDebug");
                    AWSConfigs.AddTraceListener("Amazon", tracelistener);

                    // Associate the main thread dispatcher
                    _instance.gameObject.AddComponent<UnityMainThreadDispatcher>();

                }
                else
                {
                    if (this != _instance)
                    {
                        //destroy the new instance
                        DestroyObject(this);
                    }
                }

            }
        }
        #endregion

        private static Thread _mainThread;
        /// <summary>
        /// Checks if the thread is a game/main/unity thread
        /// </summary>
        /// <returns>true if the thread is the game/main/unity thread, else false</returns>
        public static bool IsMainThread()
        {
            if (null == _mainThread)
            {
                throw new Exception("Main thread has not been set, is the AWSPrefab on the scene?");
            }
            return Thread.CurrentThread.Equals(_mainThread);
        }

    }
}


text:
set -o errexit
set -o nounset
set -o pipefail

OS_ROOT=$(dirname "${BASH_SOURCE}")/..
source "${OS_ROOT}/hack/common.sh"

# Go to the top of the tree.
cd "${OS_ROOT}"

if [[ -z "${OS_TAG}" ]]; then
  echo "You must specify the OS_TAG variable as the name of the tag to create, e.g. 'v1.0.1'."
  exit 1
fi
tag="${OS_TAG}"

if [[ "$(git name-rev --name-only --tags HEAD)" != "${tag}^0" ]]; then
  if git rev-parse -q --short "${tag}" &>/dev/null; then
    echo "Tag ${tag} already exists"
    exit 1
  else
    git tag "${tag}" -a -m "${tag}" HEAD
  fi
fi

function removeimage() {
  for i in $@; do
    if docker inspect $i &>/dev/null; then
      docker rmi $i
    fi
    if docker inspect docker.io/$i &>/dev/null; then
      docker rmi docker.io/$i
    fi
  done
}

removeimage openshift/origin-base openshift/origin-release openshift/origin-haproxy-router-base
docker pull openshift/origin-base
docker pull openshift/origin-release
docker pull openshift/origin-haproxy-router-base

hack/build-release.sh
hack/build-images.sh
OS_PUSH_TAG="${tag}" OS_TAG="" OS_PUSH_LOCAL="1" hack/push-release.sh

echo
echo "Pushed ${tag} to DockerHub"
echo "1. Push tag to GitHub with: git push origin --tags # (ensure you have no extra tags in your environment)"
echo "2. Create a new release on the releases page and upload the built binaries in _output/local/releases"
echo "   Note: you should untar the Windows binary and recompress it as a zip"
echo "3. Send an email"


text:
import sys
import time
import errno
import socket
from email.utils import formatdate

class FileWrapper(object):

    def __init__(self, filelike, blksize=8192):
        self.filelike = filelike
        self.blksize = blksize
        if hasattr(filelike, 'close'):
            self.close = filelike.close

    def __getitem__(self, key):
        data = self.filelike.read(self.blksize)
        if data:
            return data
        raise IndexError

def import_app(module_app):
    splitter = module_app.split(':')
    if len(splitter) == 1:
        module_name, app_name = splitter[0], 'application'
    else:
        module_name, app_name = splitter[:2]

    try:
        __import__(module_name)
    except ImportError:
        raise

    module = sys.modules[module_name]
    app = getattr(module, app_name, None)
    if app is None:
        raise ImportError('Failed to find application object from: %r' % module)
    if not callable(app):
        raise ImportError('Application object must be callable')
    return app

def create_tcp_socket(addr):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
    sock.bind(addr)
    sock.setblocking(0)
    sock.listen(1024) # The maximum number of pending connections.
    return sock

def create_sockets(address_list, logger):
    socks = []
    for address in address_list:
        sock = None
        try:
            sock = create_tcp_socket(address)
        except socket.error as e:
            if e.args[0] == errno.EADDRINUSE:
                logger.error('Address in use: %s', address)
            elif e.args[0] == errno.EADDRNOTAVAIL:
                logger.error('Invalid address: %s', address)
                sys.exit(1)
        if sock is None:
            logger.error('Can not connect to %s', address)
            sys.exit(1)

        socks.append(sock)

    return socks

def format_addr_str(address):
    return '%s:%s' % address

def guess_scheme(environ):
    if environ.get('HTTP_X_FORWARDED_PROTOCOL', '').lower() == "ssl":
        return 'https'
    elif environ.get('HTTP_X_FORWARDED_SSL', '').lower() == "on":
        return 'https'
    else:
        return 'http'

def get_status_code(status):
    '''extract status code from status string
       200 OK -> 200
    '''
    code, text = status.strip().split()
    return int(code)

hop_headers = set('''
    connection keep-alive proxy-authenticate
    proxy-authorization te trailers
    transfer-encoding upgrade'''.split())

def is_hoppish(name):
    return name.lower().strip() in hop_headers

def http_date(timestamp=None):
    if timestamp is None:
        timestamp = time.time()
    return formatdate(timestamp, localtime=False, usegmt=True)


text:
function DynLayer(id,nestref,frame) {
	if (!is.ns5 && !DynLayer.set && !frame) DynLayerInit()
	this.frame = frame || self
	if (is.ns) {
		if (is.ns4) {
			if (!frame) {
				if (!nestref) var nestref = DynLayer.nestRefArray[id]
				if (!DynLayerTest(id,nestref)) return
				this.css = (nestref)? eval("document."+nestref+".document."+id) : document.layers[id]
			}
			else this.css = (nestref)? eval("frame.document."+nestref+".document."+id) : frame.document.layers[id]
			this.elm = this.event = this.css
			this.doc = this.css.document
		}
		else if (is.ns5) {
			this.elm = document.getElementById(id)
			this.css = this.elm.style
			this.doc = document
		}
		this.x = this.css.left
		this.y = this.css.top
		this.w = this.css.clip.width
		this.h = this.css.clip.height
	}
	else if (is.ie) {
		this.elm = this.event = this.frame.document.all[id]
		this.css = this.frame.document.all[id].style
		this.doc = document
		this.x = this.elm.offsetLeft
		this.y = this.elm.offsetTop
		this.w = (is.ie4)? this.css.pixelWidth : this.elm.offsetWidth
		this.h = (is.ie4)? this.css.pixelHeight : this.elm.offsetHeight
	}
	this.id = id
	this.nestref = nestref
	this.obj = id + "DynLayer"
	eval(this.obj + "=this")
}
function DynLayerMoveTo(x,y) {
	if (x!=null) {
		this.x = x
		if (is.ns) this.css.left = this.x
		else this.css.pixelLeft = this.x
	}
	if (y!=null) {
		this.y = y
		if (is.ns) this.css.top = this.y
		else this.css.pixelTop = this.y
	}
}
function DynLayerMoveBy(x,y) {
	this.moveTo(this.x+x,this.y+y)
}
function DynLayerShow() {
	this.css.visibility = (is.ns4)? "show" : "visible"
}
function DynLayerHide() {
	this.css.visibility = (is.ns4)? "hide" : "hidden"
}
DynLayer.prototype.moveTo = DynLayerMoveTo
DynLayer.prototype.moveBy = DynLayerMoveBy
DynLayer.prototype.show = DynLayerShow
DynLayer.prototype.hide = DynLayerHide
DynLayerTest = new Function('return true')

function DynLayerInit(nestref) {
	if (!DynLayer.set) DynLayer.set = true
	if (is.ns) {
		if (nestref) ref = eval('document.'+nestref+'.document')
		else {nestref = ''; ref = document;}
		for (var i=0; i<ref.layers.length; i++) {
			var divname = ref.layers[i].name
			DynLayer.nestRefArray[divname] = nestref
			var index = divname.indexOf("Div")
			if (index > 0) {
				eval(divname.substr(0,index)+' = new DynLayer("'+divname+'","'+nestref+'")')
			}
			if (ref.layers[i].document.layers.length > 0) {
				DynLayer.refArray[DynLayer.refArray.length] = (nestref=='')? ref.layers[i].name : nestref+'.document.'+ref.layers[i].name
			}
		}
		if (DynLayer.refArray.i < DynLayer.refArray.length) {
			DynLayerInit(DynLayer.refArray[DynLayer.refArray.i++])
		}
	}
	else if (is.ie) {
		for (var i=0; i<document.all.tags("DIV").length; i++) {
			var divname = document.all.tags("DIV")[i].id
			var index = divname.indexOf("Div")
			if (index > 0) {
				eval(divname.substr(0,index)+' = new DynLayer("'+divname+'")')
			}
		}
	}
	return true
}
DynLayer.nestRefArray = new Array()
DynLayer.refArray = new Array()
DynLayer.refArray.i = 0
DynLayer.set = false

function DynLayerSlideTo(endx,endy,inc,speed,fn) {
	if (endx==null) endx = this.x
	if (endy==null) endy = this.y
	var distx = endx-this.x
	var disty = endy-this.y
	this.slideStart(endx,endy,distx,disty,inc,speed,fn)
}
function DynLayerSlideBy(distx,disty,inc,speed,fn) {
	var endx = this.x + distx
	var endy = this.y + disty
	this.slideStart(endx,endy,distx,disty,inc,speed,fn)
}
function DynLayerSlideStart(endx,endy,distx,disty,inc,speed,fn) {
	if (this.slideActive) return
	if (!inc) inc = 10
	if (!speed) speed = 20
	var num = Math.sqrt(Math.pow(distx,2) + Math.pow(disty,2))/inc
	if (num==0) return
	var dx = distx/num
	var dy = disty/num
	if (!fn) fn = null
	this.slideActive = true
	this.slide(dx,dy,endx,endy,num,1,speed,fn)
}
function DynLayerSlide(dx,dy,endx,endy,num,i,speed,fn) {
	if (!this.slideActive) return
	if (i++ < num) {
		this.moveBy(dx,dy)
		this.onSlide()
		if (this.slideActive) setTimeout(this.obj+".slide("+dx+","+dy+","+endx+","+endy+","+num+","+i+","+speed+",\""+fn+"\")",speed)
		else this.onSlideEnd()
	}
	else {
		this.slideActive = false
		this.moveTo(endx,endy)
		this.onSlide()
		this.onSlideEnd()
		eval(fn)
	}
}
function DynLayerSlideInit() {}
DynLayer.prototype.slideInit = DynLayerSlideInit
DynLayer.prototype.slideTo = DynLayerSlideTo
DynLayer.prototype.slideBy = DynLayerSlideBy
DynLayer.prototype.slideStart = DynLayerSlideStart
DynLayer.prototype.slide = DynLayerSlide
DynLayer.prototype.onSlide = new Function()
DynLayer.prototype.onSlideEnd = new Function()

function DynLayerClipInit(clipTop,clipRight,clipBottom,clipLeft) {
	if (is.ie) {
		if (arguments.length==4) this.clipTo(clipTop,clipRight,clipBottom,clipLeft)
		else if (is.ie4) this.clipTo(0,this.css.pixelWidth,this.css.pixelHeight,0)
	}
}
function DynLayerClipTo(t,r,b,l) {
	if (t==null) t = this.clipValues('t')
	if (r==null) r = this.clipValues('r')
	if (b==null) b = this.clipValues('b')
	if (l==null) l = this.clipValues('l')
	if (is.ns) {
		this.css.clip.top = t
		this.css.clip.right = r
		this.css.clip.bottom = b
		this.css.clip.left = l
	}
	else if (is.ie) this.css.clip = "rect("+t+"px "+r+"px "+b+"px "+l+"px)"
}
function DynLayerClipBy(t,r,b,l) {
	this.clipTo(this.clipValues('t')+t,this.clipValues('r')+r,this.clipValues('b')+b,this.clipValues('l')+l)
}
function DynLayerClipValues(which) {
	if (is.ie) var clipv = this.css.clip.split("rect(")[1].split(")")[0].split("px")
	if (which=="t") return (is.ns)? this.css.clip.top : Number(clipv[0])
	if (which=="r") return (is.ns)? this.css.clip.right : Number(clipv[1])
	if (which=="b") return (is.ns)? this.css.clip.bottom : Number(clipv[2])
	if (which=="l") return (is.ns)? this.css.clip.left : Number(clipv[3])
}
DynLayer.prototype.clipInit = DynLayerClipInit
DynLayer.prototype.clipTo = DynLayerClipTo
DynLayer.prototype.clipBy = DynLayerClipBy
DynLayer.prototype.clipValues = DynLayerClipValues

function DynLayerWrite(html) {
	if (is.ns) {
		this.doc.open()
		this.doc.write(html)
		this.doc.close()
	}
	else if (is.ie) {
		this.event.innerHTML = html
	}
}
DynLayer.prototype.write = DynLayerWrite

function BrowserCheck() {
	var b = navigator.appName
	if (b=="Netscape") this.b = "ns"
	else if (b=="Microsoft Internet Explorer") this.b = "ie"
	else this.b = b
	this.version = navigator.appVersion
	this.v = parseInt(this.version)
	this.ns = (this.b=="ns" && this.v>=4)
	this.ns4 = (this.b=="ns" && this.v==4)
	this.ns5 = (this.b=="ns" && this.v==5)
	this.ie = (this.b=="ie" && this.v>=4)
	this.ie4 = (this.version.indexOf('MSIE 4')>0)
	this.ie5 = (this.version.indexOf('MSIE 5')>0)
	this.min = (this.ns||this.ie)
}
is = new BrowserCheck()

function css(id,left,top,width,height,color,vis,z,other) {
	if (id=="START") return '<STYLE TYPE="text/css">\n'
	else if (id=="END") return '</STYLE>'
	var str = (left!=null && top!=null)? '#'+id+' {position:absolute; left:'+left+'px; top:'+top+'px;' : '#'+id+' {position:relative;'
	if (arguments.length>=4 && width!=null) str += ' width:'+width+'px;'
	if (arguments.length>=5 && height!=null) {
		str += ' height:'+height+'px;'
		if (arguments.length<9 || other.indexOf('clip')==-1) str += ' clip:rect(0px '+width+'px '+height+'px 0px);'
	}
	if (arguments.length>=6 && color!=null) str += (is.ns)? ' layer-background-color:'+color+';' : ' background-color:'+color+';'
	if (arguments.length>=7 && vis!=null) str += ' visibility:'+vis+';'
	if (arguments.length>=8 && z!=null) str += ' z-index:'+z+';'
	if (arguments.length==9 && other!=null) str += ' '+other
	str += '}\n'
	return str
}
function writeCSS(str,showAlert) {
	str = css('START')+str+css('END')
	document.write(str)
	if (showAlert) alert(str)
}


text:
aws-silverstripe-cookbooks
==========================

Chef cookbooks for deploying Silverstripe on AWS using AWS Opworks.
This cookbook is setup for the following stack configuration:

- PHP App Server containing Silverstripe application files
- Seperate MySQl db server as DB layer in Opworks

The current stack setup uses the default Silverstripe cms & framework bundle supplied by the download .tar.gz file.
This cookbook will be updated to use composer to pull in the cms and framework repositories on the server,
with the installer set up as the base repository in the AWS Opworks stack

*Note:* The cookbook is not currently functioning (see https://github.com/moveforward/aws-silverstripe-cookbooks/issues/1 )


text:
namespace MetX.Fimm.Setup;

public class LibraryActor : FimmActorBase
{
    public LibraryActor()
    {

    }

    public LibraryActor(ArgumentVerb verb, ArgumentNoun noun) : base(verb, noun)
    {
    }

    public override ProcessorResult Run(ArgumentSettings settings)
    {
        throw new System.NotImplementedException();
    }
}


text:
typedef struct __CFRunLoopObserver * CFRunLoopObserverRef;
typedef const struct __CFString * CFStringRef;

#include "wx/osx/core/cfref.h"

// ========================================================================
// wxApp
// ========================================================================
// Represents the application. Derive OnInit and declare
// a new App object to start application
class WXDLLIMPEXP_CORE wxApp: public wxAppBase
{
    DECLARE_DYNAMIC_CLASS(wxApp)
// ------------------------------------------------------------------------
// initialization
// ------------------------------------------------------------------------
public:
    wxApp();
    virtual ~wxApp();

// ------------------------------------------------------------------------
// Cocoa specifics
// ------------------------------------------------------------------------
public:
    inline WX_NSApplication GetNSApplication() { return m_cocoaApp; }
    virtual void CocoaDelegate_applicationWillBecomeActive();
    virtual void CocoaDelegate_applicationDidBecomeActive();
    virtual void CocoaDelegate_applicationWillResignActive();
    virtual void CocoaDelegate_applicationDidResignActive();
    virtual void CocoaDelegate_applicationWillUpdate();
    virtual void CF_ObserveMainRunLoopBeforeWaiting(CFRunLoopObserverRef observer, int activity);
protected:
    WX_NSApplication m_cocoaApp;
    struct objc_object *m_cocoaAppDelegate;
    WX_NSThread m_cocoaMainThread;
    wxCFRef<CFRunLoopObserverRef> m_cfRunLoopIdleObserver;
    wxCFRef<CFStringRef> m_cfObservedRunLoopMode;

// ------------------------------------------------------------------------
// Implementation
// ------------------------------------------------------------------------
public:
    // Implement wxAppBase pure virtuals
    virtual void Exit();

    virtual void WakeUpIdle();

    virtual bool Initialize(int& argc, wxChar **argv);
    virtual void CleanUp();
    virtual bool CallOnInit();

    virtual bool OnInit();
    virtual bool OnInitGui();

    // Set true _before_ initializing wx to force embedded mode (no app delegate, etc.)
    static bool sm_isEmbedded;
};

#endif // _WX_COCOA_APP_H_


text:
//
//  TRSStarsView.h
//  Pods
//
//  Created by Gero Herkenrath on 13/06/16.
//  (Class was formerly TRSRatingView)
//

#import <UIKit/UIKit.h>

/**
 A constant defining the number of stars in a `TRSStarsView`.
 */
FOUNDATION_EXPORT NSUInteger const kTRSStarsViewNumberOfStars;

/**
 The `TRSStarsView` class is a subclass of `UIView`.

 It simply draws five stars in a horizontal row that can be filled to an extent.
 For that it has a rating, a value between 1 and 5. If, for example, the rating is 4.5 then the first (left) four stars
 are filled with `activeStarColor`, and the last star's left half is also `activeStarColor`, while its right half
 is `inactiveStarColor`.

 Note that the view's frame rectangel always has an aspect ratio of 5 to 1 and that it has a minimum size of
 50.0 times 10.0 points on screen.
 */
@interface TRSStarsView : UIView

/** The rating given to the view. Lies between 1 and 5. */
@property (nonatomic, readonly) NSNumber *rating;

/** The color used to denote active (parts of) stars. Defaults to a shade of yellow (ananas). */
@property (nonatomic, strong) UIColor *activeStarColor;
/** The color used to denote inactive (parts of) stars. Defaults to a dark grey color.*/
@property (nonatomic, strong) UIColor *inactiveStarColor;

/**
 The designated initializer.

 If you specify `nil` for the rating value, the stars will be drawn completely filled with `activeStarColor`, i.e.
 the rating property defaults to 5.
 @param frame the view's frame.
 @param rating the view's rating.
 */
- (instancetype)initWithFrame:(CGRect)frame rating:(NSNumber *)rating NS_DESIGNATED_INITIALIZER;
/**
 Inits the view with a `CGRectZero` rect.

 Note that although the frame rectange is `CGRectZero` right after initialization, the view will always be drawn
 with its minimum size of 50.0 times 10.0.
 @param rating the view's rating.
 */
- (instancetype)initWithRating:(NSNumber *)rating;

/**
 A convenience initializer to instantiate a `TRSStarsView` with a given rating.

 This simply calls `initWithRating:` on a new allocated `TRSStarsView` object.
 @param rating the view's rating.
 */
+ (instancetype)starsWithRating:(NSNumber *)rating;

@end


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Intro: set.seed() and sample()</title>

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="robots" content="all,follow" >
  <meta name="googlebot" content="index,follow,snippet,archive" >
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

  <link rel="stylesheet" href="//fonts.googleapis.com/css?family=Roboto:400,300,700,400italic" >
  <link rel="stylesheet" href="https://ractuary.github.io/ractuary/css/font-awesome.min.css" />

  <meta name="google-site-verification" content="agjsDt8HXS4yYizS-kj6OnNXvJ-3J-ONvc2vVejs4ZQ" />
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.3.0/css/mdb.min.css" />
  <link href="https://ractuary.github.io/ractuary/css/style.css" rel="stylesheet" />

  <link rel="shortcut icon" href="https://ractuary.github.io/ractuary/img/ractuary-logo.png" />

  <link rel="stylesheet" href="https://ractuary.github.io/ractuary/css/tychobra-hljs.css">

  <link href="https://ractuary.github.io/ractuary/css/simplesidebar.css" rel="stylesheet" >

         Actuary

              About

              Projects

              Tutorials

              Gallery

              Blog

         < Back to Tutorials

Intro: set.seed() and sample()

Published: May 12, 2017

Last Updated: May 25, 2017

Simulation is very useful for creating sample data, coming up with quick confidence levels, and performing a wide range of other practical data analysis tasks. Additionally simulating data is a great way for beginners to quickly do something useful in R and get familiar with R's base data structures and functions.

Before generating random numbers, we set the seed so that our simulations will be reproducible.

set.seed(1234)

We set the seed by passing an integer to set.seed(). The seed contains the state for random number generation in R. By setting the seed before generating random numbers you will be able to reset the seed and rerun the simulation and get the exact same results. It is possible to reproduce "randomly" generated numbers because computers use pseudo random number generators which are not truely random, but are random enough (according to a bunch of tests of randomness). A remarkable amount of work has gone into making appropriate pseudo random number generators, and fortunately with R, we get to piggy back on all that hard work.

Now that we have our seed set we can do a very basic simulation using the sample() function.

sample(1:10, size = 2, replace = TRUE)

#> [1] 2 7

Above we drew two random observations from the numbers 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 with replacement. It may seem pretty boring, but the sample() function definitely comes in handy. Particularly for creating mock data sets.

If we rerun the simulation without setting the seed we will get a different result:

sample(1:10, size = 2, replace = TRUE)

#> [1] 7 7

Now we rerun our first simulation for a thrid time, but this time we will first set the seed using our original see value of 1234.

set.seed(1234)
sample(1:10, size = 2, replace = TRUE)

#> [1] 2 7

As you can see, this simulation produced the same results as our first simulation. The results are identical because we set R's random number generator to identical states in our first and third simulations.

As I am sure you have guessed by now, the sample function can draw from vectors other than numeric vectors. e.g. we could sample genders from a character vector:

sample(c("m", "f"), size = 5, replace = TRUE)

#> [1] "f" "f" "f" "f" "m"

Now that you know how to use set.seed() and sample() we can move on to more interesting simulations.

R comes with a variety of probability distributions that can generate random numbers. We will be using several of them in the upcoming tutorials. At the end of these tutorials we will put our simulation skills to the test by creating a Shiny application that simulates and plots random numbers.

  Please enable JavaScript to view the comments powered by
  Disqus.

            RActuary is a Tychobra Project | ©2017 Tychobra, LLC.


text:
Dummy graphic editor to make isometric illustrations. It's like pixel art, but with triangles.

Try it on [maxwellito.github.io/triangulart](https://maxwellito.github.io/triangulart)

This version is still on beta and not fully stable.

## File format

On the v2, we are making things simpler, one unique file format : the SVG. On the first version the editable format was in JSON, and I think it was a bad design choice. Having one format make it easier for the final user.

Here are the details

```xml
<svg version="1.1" preserveAspectRatio="xMinYMin slice" width="930" height="520" viewBox="0 0 930 520">
    <!--{"isLandscape":true,"mapWidth":"31","mapHeight":20,"palette":["#11aaff","#ff0002","#c5ceda","#000000"]}-->
    <path d="M345 0 L330 26 L360 26 Z" fill="#000000" rel="22"></path>
    <path d="M345 0 L360 26 L375 0 Z" fill="#000000" rel="23"></path>
    <path d="M375 0 L360 26 L390 26 Z" fill="#000000" rel="24"></path>
    <path d="M375 0 L390 26 L405 0 Z" fill="#000000" rel="25"></path>
    ...
</svg>
```

The SVG first child node is a comment containing the JSON of the basic details of the artwork. It contains the orientation, width, height, and the palette.
Then every path got the `rel` attribute to contain the triangle index.

## for v2.1 (aka neverland)

- Auto save (but better, with little signal)
- Responsive layout (the menu and nav is clunky)
- Better care of error cases
- MASSIVE PERF ISSUES ON BIG WORKSPACE : MOVE TO CANVAS (and light the weight of triangulart class)
- Zoom in/out
- Clipboard!


text:
/*
 * Base Yes/No confirmation box
 */

/* jshint browser: true */
/* exported confirmbox,alertbox */

var dlgboxPromise = (function() {
  'use strict';

  return {
    promise: function(title, message, params) {
      return new Promise(function(resolve, reject) {
        var dlg = document.getElementById('confirm_box');
        if (!dlg) {
          dlg = document.createElement('DIV');
          dlg.classList.add('UI-modal');
          dlg.id = 'confirm_box';
          var content = document.createElement('DIV');
          dlg.appendChild(content);
          content.classList.add('UI-modal-content');

          var h = document.createElement('H2');
          h.classList.add('UI-red');
          h.classList.add('UI-center');

          var s = document.createElement('SPAN');
          s.id = 'confirm_title';
          s.innerHTML = '';
          h.appendChild(s);
          content.appendChild(h);

          h = document.createElement('H3');
          h.classList.add('UI-center');
          s = document.createElement('SPAN');
          s.id = 'confirm_message';
          s.innerHTML = '';
          h.appendChild(s);
          content.appendChild(h);

          var form = document.createElement('DIV');
          form.classList.add('UI-center');
          content.appendChild(form);

          var b1 = document.createElement('BUTTON');
          b1.classList.add('UI-button');
          b1.classList.add('UI-center');
          b1.classList.add('UI-border');
          b1.classList.add('UI-margin');
          b1.classList.add('UI-padding');
          b1.innerHTML = 'Yes';
          b1.id = 'confirm_yes_button';
          form.appendChild(b1);

          var b2 = document.createElement('BUTTON');
          b2.classList.add('UI-button');
          b2.classList.add('UI-center');
          b2.classList.add('UI-border');
          b2.classList.add('UI-margin');
          b2.classList.add('UI-padding');
          b2.innerHTML = 'No';
          b2.id = 'confirm_no_button';
          form.appendChild(b2);

          document.body.appendChild(dlg);
        }

        var n = null;
        n = document.getElementById('confirm_title');
        n.innerHTML = title;
        n = document.getElementById('confirm_message');
        if (typeof message === 'undefined') {
          n.style.display = 'none';
        } else {
          n.innerHTML = message;
          n.style.display = 'inline';
        }

        document.getElementById('confirm_no_button').onclick = function() {
          reject(1);
          document.getElementById('confirm_box').style.display = 'none';
        };

        document.getElementById('confirm_yes_button').onclick = function() {
          resolve(1);
          document.getElementById('confirm_box').style.display = 'none';
        };

        if (params && 'yesMsg' in params) {
          n = document.getElementById('confirm_yes_button');
          n.innerHTML = params.yesMsg;
        } else {
          n = document.getElementById('confirm_yes_button');
          n.innerHTML = 'Yes';
        }
        if (params && 'noMsg' in params) {
          n = document.getElementById('confirm_no_button');
          n.innerHTML = params.noMsg;
        } else {
          n = document.getElementById('confirm_no_button');
          n.innerHTML = 'No';
        }
        if (params && 'alertBox' in params) {
          n = document.getElementById('confirm_no_button');
          n.style.display = 'none';
          if (!('yesMsg' in params)) {
            n = document.getElementById('confirm_yes_button');
            n.innerHTML = 'OK';
          }
        } else {
          n = document.getElementById('confirm_no_button');
          n.style.display = 'inline';
        }

        dlg.style.display = 'block';
      }
      );}
  };
}) ();

function confirmbox(title, message, params) {
  return dlgboxPromise.promise(title, message, params);
}

function alertbox(title, message, params) {
  var alertParams = params;
  if (!alertParams) {
    alertParams = Array();
  }
  alertParams.alertBox = true;
  return dlgboxPromise.promise(title, message, alertParams);
}


text:
<!DOCTYPE html>
<html lang="en">
<head>
  <style id="antiClickjack">
    body {
      display: none !important;
    }
  </style>
  <script type="text/javascript">
    if (self === top) {
      var antiClickjack = document.getElementById("antiClickjack");
      antiClickjack.parentNode.removeChild(antiClickjack);
    } else {
      top.location = self.location;
    }
  </script>

  <base href="<%= APP_BASE %>">
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>NIST Data Repository Page</title>
  <meta name="description" content="">
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"/>
    <meta name="apple-mobile-web-app-capable" content="yes" />
  <!-- inject:css -->
  <!-- endinject -->
</head>
<body>
  Landing Page Home

  <script>
  // Fixes undefined module function in SystemJS bundle
  function module() {}
  </script>

  <!-- shims:js -->
  <!-- endinject -->

  <% if (BUILD_TYPE === 'dev') { %>
  <script src="<%= APP_BASE %>pdr/system-config.js"></script>
  <% } %>

  <!-- libs:js -->
  <!-- endinject -->

  <!-- inject:js -->
  <!-- endinject -->

  <% if (BUILD_TYPE === 'dev') { %>
  <script>
  System.import('<%= BOOTSTRAP_MODULE %>')
    .catch(function (e) {
      console.error(e,
        'Report this error at https://github.com/mgechev/angular2-seed/issues');
    });
  </script>
  <% } %>

</body>
</html>


text:
import platform
from datetime import datetime
import psutil
from pyspectator.monitoring import AbcMonitor
from pyspectator.memory import NonvolatileMemory, VirtualMemory, SwapMemory
from pyspectator.processor import Cpu
from pyspectator.network import NetworkInterface

class Computer(AbcMonitor):

    def __init__(self):
        self.datetime_format = '%H:%M:%S %d/%m/%Y'
        self.__raw_boot_time = psutil.boot_time()
        self.__boot_time = datetime.fromtimestamp(self.raw_boot_time)
        self.__boot_time = self.__boot_time.strftime(self.datetime_format)
        self.__hostname = platform.node()
        self.__os = Computer.__get_os_name()
        self.__architecture = platform.machine()
        self.__python_version = '{} ver. {}'.format(
            platform.python_implementation(), platform.python_version()
        )
        self.__processor = Cpu(monitoring_latency=1)
        self.__nonvolatile_memory = NonvolatileMemory.instances_connected_devices(monitoring_latency=10)
        self.__nonvolatile_memory_devices = set(
            [dev_info.device for dev_info in self.__nonvolatile_memory]
        )
        self.__virtual_memory = VirtualMemory(monitoring_latency=1)
        self.__swap_memory = SwapMemory(monitoring_latency=1)
        self.__network_interface = NetworkInterface(monitoring_latency=3)
        super().__init__(monitoring_latency=3)

    @property
    def processor(self):
        return self.__processor

    @property
    def raw_boot_time(self):
        return self.__raw_boot_time

    @property
    def boot_time(self):
        return self.__boot_time

    @property
    def raw_uptime(self):
        return datetime.now() - datetime.fromtimestamp(self.raw_boot_time)

    @property
    def uptime(self):
        return str(self.raw_uptime).split('.')[0]

    @property
    def os(self):
        return self.__os

    @property
    def architecture(self):
        return self.__architecture

    @property
    def python_version(self):
        return self.__python_version

    @property
    def hostname(self):
        return self.__hostname

    @property
    def nonvolatile_memory(self):
        return self.__nonvolatile_memory

    @property
    def virtual_memory(self):
        return self.__virtual_memory

    @property
    def swap_memory(self):
        return self.__swap_memory

    @property
    def network_interface(self):
        return self.__network_interface

    @classmethod
    def __get_os_name(cls):
        system = '{} {}'.format(platform.system(), platform.release()).strip()
        if ('Linux' in system) and ('' not in platform.linux_distribution()):
            system = ' '.join(platform.linux_distribution())
        return system

    def _monitoring_action(self):
        # Look for connected & ejected nonvolatile memory devices
        for dev in self.nonvolatile_memory:
            if not dev.is_alive:
                dev.stop_monitoring()
                self.__nonvolatile_memory_devices.remove(dev.device)
                self.__nonvolatile_memory.remove(dev)
        connected_dev = set(NonvolatileMemory.names_connected_devices()) - \
            self.__nonvolatile_memory_devices
        for dev_name in connected_dev:
            dev = NonvolatileMemory(monitoring_latency=10, device=dev_name)
            self.__nonvolatile_memory.append(dev)
            self.__nonvolatile_memory_devices.add(dev_name)

    def start_monitoring(self, all_components=True):
        super().start_monitoring()
        if all_components:
            self.processor.start_monitoring()
            for mem in self.nonvolatile_memory:
                mem.start_monitoring()
            self.virtual_memory.start_monitoring()
            self.network_interface.start_monitoring()

    def stop_monitoring(self, all_components=True):
        if all_components:
            self.processor.stop_monitoring()
            for mem in self.nonvolatile_memory:
                mem.stop_monitoring()
            self.virtual_memory.stop_monitoring()
            self.network_interface.stop_monitoring()
        super().stop_monitoring()

    def __enter__(self):
        self.start_monitoring()

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.stop_monitoring()

__all__ = ['Computer']


text:
using jcFUS.PCL.Common;

using Microsoft.AspNet.SignalR.Client;

namespace jcFUS.PCL.Hubs {
    public class ChatHub {
        private HubConnection _connection;

        private IHubProxy _chat;

        public ChatHub() {
            _connection = new HubConnection(Constants.WEBAPI_BASE_ADDRESS);

            _chat = _connection.CreateHubProxy("Chat");
        }
    }
}


text:
import datetime
import logging
import os

import king_phisher.client.application as application
import king_phisher.client.dialogs.exception as exception
import king_phisher.client.gui_utilities as gui_utilities
import king_phisher.client.plugins as plugins

# logger name value
LOGGER_NAME = ''

# log file size, in MB
LOG_FILE_SIZE = 10

class Plugin(plugins.ClientPlugin):
	authors = ['Zach Janice', 'Spencer McIntyre']
	classifiers = ['Plugin :: Client :: Tool']
	title = 'File Logging'
	description = """
	Write the client's logs to a file in the users data directory. Additionally
	if an unhandled exception occurs, the details will be written to a dedicated
	directory.
	"""
	homepage = 'https://github.com/securestate/king-phisher-plugins'
	req_min_version = '1.6.0'
	version = '2.0'
	# this is the primary plugin entry point which is executed when the plugin is enabled
	def initialize(self):
		# ensure the directory for the logs exists
		log_dir = application.USER_DATA_PATH
		if not os.path.exists(log_dir):
			os.mkdir(log_dir)

		self.exception_dir = os.path.join(log_dir, 'exceptions')
		# ensure that the directory for exceptions exists
		if not os.path.exists(self.exception_dir):
			os.mkdir(self.exception_dir)

		# convert the specified log file size (MB) to bytes for use by the logger
		file_size = LOG_FILE_SIZE * 1024 * 1024

		# grab the logger in use by the client (root logger)
		logger = logging.getLogger(LOGGER_NAME)

		# set up the handler and formatter for the logger, and attach the components
		handler = logging.handlers.RotatingFileHandler(os.path.join(log_dir, 'king-phisher.log'), maxBytes=file_size, backupCount=2)
		formatter = logging.Formatter('%(asctime)s %(name)-50s %(levelname)-8s %(message)s')
		handler.setFormatter(formatter)
		logger.addHandler(handler)

		# keep reference of handler as an attribute
		self.handler = handler
		self.signal_connect('unhandled-exception', self.signal_kpc_unhandled_exception)
		return True

	# this is a cleanup method to allow the plugin to close any open resources
	def finalize(self):
		# remove the logging handler from the logger and close it
		logger = logging.getLogger(LOGGER_NAME)
		logger.removeHandler(self.handler)
		self.handler.flush()
		self.handler.close()

	def signal_kpc_unhandled_exception(self, _, exc_info, error_uid):
		exc_type, exc_value, exc_traceback = exc_info
		details = exception.format_exception_details(exc_type, exc_value, exc_traceback, error_uid=error_uid)
		filename = os.path.join(self.exception_dir, "{0:%Y-%m-%d_%H:%M}_{1}.txt".format(datetime.datetime.now(), error_uid))
		with open(filename, 'w') as file_h:
			file_h.write(details)


text:
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
                        unicode_literals, with_statement)

from pex.interpreter import PythonIdentity
from twitter.common.collections import maybe_list

from pants.backend.python.python_artifact import PythonArtifact
from pants.base.deprecated import deprecated_conditional
from pants.base.exceptions import TargetDefinitionException
from pants.base.payload import Payload
from pants.base.payload_field import PrimitiveField
from pants.build_graph.address import Address
from pants.build_graph.resources import Resources
from pants.build_graph.target import Target
from pants.util.memo import memoized_property

class PythonTarget(Target):
  """Base class for all Python targets.

  :API: public
  """

  def __init__(self,
               address=None,
               payload=None,
               sources=None,
               resources=None,  # Old-style resources (file list, Fileset).
               resource_targets=None,  # New-style resources (Resources target specs).
               provides=None,
               compatibility=None,
               **kwargs):
    """
    :param dependencies: The addresses of targets that this target depends on.
      These dependencies may
      be ``python_library``-like targets (``python_library``,
      ``python_thrift_library``, ``python_antlr_library`` and so forth) or
      ``python_requirement_library`` targets.
    :type dependencies: list of strings
    :param sources: Files to "include". Paths are relative to the
      BUILD file's directory.
    :type sources: ``Fileset`` or list of strings
    :param resources: non-Python resources, e.g. templates, keys, other data
      (it is
      recommended that your application uses the pkgutil package to access these
      resources in a .zip-module friendly way.) Paths are relative to the BUILD
      file's directory.
    :type sources: ``Fileset`` or list of strings
    :param resource_targets: The addresses of ``resources`` targets this target
      depends on.
    :type resource_targets: list of strings
    :param provides:
      The `setup_py <#setup_py>`_ to publish that represents this
      target outside the repo.
    :param compatibility: either a string or list of strings that represents
      interpreter compatibility for this target, using the Requirement-style
      format, e.g. ``'CPython>=3', or just ['>=2.7','<3']`` for requirements
      agnostic to interpreter class.
    """
    deprecated_conditional(lambda: resources is not None, '1.5.0.dev0',
                           'The `resources=` Python target argument', 'Depend on resources targets instead.')
    deprecated_conditional(lambda: resource_targets is not None, '1.5.0.dev0',
                           'The `resource_targets=` Python target argument', 'Use `dependencies=` instead.')
    self.address = address
    payload = payload or Payload()
    payload.add_fields({
      'sources': self.create_sources_field(sources, address.spec_path, key_arg='sources'),
      'resources': self.create_sources_field(resources, address.spec_path, key_arg='resources'),
      'provides': provides,
      'compatibility': PrimitiveField(maybe_list(compatibility or ())),
    })
    super(PythonTarget, self).__init__(address=address, payload=payload, **kwargs)
    self._resource_target_specs = resource_targets
    self.add_labels('python')

    if provides and not isinstance(provides, PythonArtifact):
      raise TargetDefinitionException(self,
        "Target must provide a valid pants setup_py object. Received a '{}' object instead.".format(
          provides.__class__.__name__))

    self._provides = provides

    # Check that the compatibility requirements are well-formed.
    for req in self.payload.compatibility:
      try:
        PythonIdentity.parse_requirement(req)
      except ValueError as e:
        raise TargetDefinitionException(self, str(e))

  @property
  def traversable_specs(self):
    for spec in super(PythonTarget, self).traversable_specs:
      yield spec
    if self._provides:
      for spec in self._provides._binaries.values():
        address = Address.parse(spec, relative_to=self.address.spec_path)
        yield address.spec

  @property
  def traversable_dependency_specs(self):
    for spec in super(PythonTarget, self).traversable_dependency_specs:
      yield spec
    if self._resource_target_specs:
      for spec in self._resource_target_specs:
        yield spec
    if self._synthetic_resources_target:
      yield self._synthetic_resources_target.address.spec

  @property
  def provides(self):
    return self.payload.provides

  @property
  def provided_binaries(self):
    def binary_iter():
      if self.payload.provides:
        for key, binary_spec in self.payload.provides.binaries.items():
          address = Address.parse(binary_spec, relative_to=self.address.spec_path)
          yield (key, self._build_graph.get_target(address))
    return dict(binary_iter())

  @property
  def compatibility(self):
    return self.payload.compatibility

  @property
  def resources(self):
    # Note: Will correctly find:
    #   - Regular dependencies on Resources targets.
    #   - Resources targets specified via resource_targets=.
    #   - The synthetic Resources target created from the resources= fileset.
    # Because these are all in the traversable_dependency_specs.
    return [dep for dep in self.dependencies if isinstance(dep, Resources)]

  def walk(self, work, predicate=None):
    super(PythonTarget, self).walk(work, predicate)
    for binary in self.provided_binaries.values():
      binary.walk(work, predicate)

  @memoized_property
  def _synthetic_resources_target(self):
    if not self.payload.resources.source_paths:
      return None

    # Create an address for the synthetic target.
    spec = self.address.spec + '_synthetic_resources'
    resource_address = Address.parse(spec=spec)
    # For safety, ensure an address that's not used already, even though that's highly unlikely.
    while self._build_graph.contains_address(resource_address):
      spec += '_'
      resource_address = Address.parse(spec=spec)

    self._build_graph.inject_synthetic_target(resource_address, Resources,
                                              sources=self.payload.resources.source_paths,
                                              derived_from=self)
    return self._build_graph.get_target(resource_address)


text:
function g = ngaussNoiseGradientParam(noise, mu, varsigma, y)

% NGAUSSNOISEGRADIENTPARAM Gradient of NGAUSS noise's parameters.
%
%	Description:
%
%	G = NGAUSSNOISEGRADIENTPARAM(NOISE, MU, VARSIGMA, Y) computes the
%	gradient of the log Z of the noiseless Gaussian noise model with
%	respect to the of functions with respect to the noiseless Gaussian
%	noise's parameters.
%	 Returns:
%	  G - gradients of the log Z with respect to the noise parameters.
%	   The ordering of the vector should match that provided by the
%	   function noiseExtractParam.
%	 Arguments:
%	  NOISE - the noise structure for which the gradients are being
%	   computed.
%	  MU - the input means for which the gradients are being computed.
%	  VARSIGMA - the input variances for which the gradients are being
%	   computed.
%	  Y - the target values for the noise model.
%
%
%
%	See also
%	% SEEALSO NGAUSSNOISEPARAMINIT, NGAUSSNOISEGRADVALS, NOISEGRADIENTPARAM

%	Copyright (c) 2004, 2005 Neil D. Lawrence

D = size(y, 2);
u = zeros(size(y));

for i = 1:D
  mu(:, i) = mu(:, i) + noise.bias(i);
end

u = y - mu;
nu = 1./(varsigma+noise.sigma2);
u = u.*nu;
gbias = sum(u, 1);
g = [gbias];


text:
<?php
require_once 'tests/HTTP/Exception/DownloadManagerException.php';

require_once 'PHPUnit/Framework/TestCase.php';

/**
 * DownloadManagerException test case.
 */
class DownloadManagerExceptionTest extends PHPUnit_Framework_TestCase
{

    /**
     *
     * @var DownloadManagerException
     */
    private $DownloadManagerException;

    /**
     * Prepares the environment before running a test.
     */
    protected function setUp()
    {
        parent::setUp();

        // TODO Auto-generated DownloadManagerExceptionTest::setUp()

        $this->DownloadManagerException = new DownloadManagerException(/* parameters */);
    }

    /**
     * Cleans up the environment after running a test.
     */
    protected function tearDown()
    {
        // TODO Auto-generated DownloadManagerExceptionTest::tearDown()
        $this->DownloadManagerException = null;

        parent::tearDown();
    }

    /**
     * Constructs the test case.
     */
    public function __construct()
    {
        // TODO Auto-generated constructor
    }
}